Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/d3d8/d3d8_private.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/d3d8/d3d8_private.h	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/d3d8/d3d8_private.h	(revision 22496)
@@ -107,4 +107,6 @@
     _pD3D8Caps->MaxPixelShaderValue               = _pWineCaps->PixelShader1xMaxValue;
 
+void fixup_caps(WINED3DCAPS *pWineCaps);
+
 /* Direct3D8 Interfaces: */
 typedef struct IDirect3DBaseTexture8Impl IDirect3DBaseTexture8Impl;
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/d3d8/device.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/d3d8/device.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/d3d8/device.c	(revision 22496)
@@ -404,15 +404,7 @@
     hrc = IWineD3DDevice_GetDeviceCaps(This->WineD3DDevice, pWineCaps);
     LeaveCriticalSection(&d3d8_cs);
+    fixup_caps(pWineCaps);
     WINECAPSTOD3D8CAPS(pCaps, pWineCaps)
     HeapFree(GetProcessHeap(), 0, pWineCaps);
-
-    /* D3D8 doesn't support SM 2.0 or higher, so clamp to 1.x */
-    if(pCaps->PixelShaderVersion > D3DPS_VERSION(1,4)){
-        pCaps->PixelShaderVersion = D3DPS_VERSION(1,4);
-    }
-    if(pCaps->VertexShaderVersion > D3DVS_VERSION(1,1)){
-        pCaps->VertexShaderVersion = D3DVS_VERSION(1,1);
-    }
-    pCaps->MaxVertexShaderConst = min(D3D8_MAX_VERTEX_SHADER_CONSTANTF, pCaps->MaxVertexShaderConst);
 
     TRACE("Returning %p %p\n", This, pCaps);
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/d3d8/directx.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/d3d8/directx.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/d3d8/directx.c	(revision 22496)
@@ -205,4 +205,12 @@
     TRACE("(%p)->(%d, %d, %d, %08x, %d, %d)\n", This, Adapter, DeviceType, AdapterFormat, Usage, RType, CheckFormat);
 
+    if(CheckFormat == D3DFMT_R8G8B8)
+    {
+        /* See comment in dlls/d3d9/directx.c, IDirect3D9Impl_CheckDeviceFormat for details */
+        WARN("D3DFMT_R8G8B8 is not available on windows, returning D3DERR_NOTAVAILABLE\n");
+        return D3DERR_NOTAVAILABLE;
+    }
+
+
     switch(RType) {
         case D3DRTYPE_VERTEXBUFFER:
@@ -252,4 +260,18 @@
 }
 
+void fixup_caps(WINED3DCAPS *caps)
+{
+    /* D3D8 doesn't support SM 2.0 or higher, so clamp to 1.x */
+    if (caps->PixelShaderVersion > D3DPS_VERSION(1,4)) {
+        caps->PixelShaderVersion = D3DPS_VERSION(1,4);
+    }
+    if (caps->VertexShaderVersion > D3DVS_VERSION(1,1)) {
+        caps->VertexShaderVersion = D3DVS_VERSION(1,1);
+    }
+    caps->MaxVertexShaderConst = min(D3D8_MAX_VERTEX_SHADER_CONSTANTF, caps->MaxVertexShaderConst);
+
+    caps->StencilCaps &= ~WINED3DSTENCILCAPS_TWOSIDED;
+}
+
 static HRESULT  WINAPI  IDirect3D8Impl_GetDeviceCaps(LPDIRECT3D8 iface, UINT Adapter, D3DDEVTYPE DeviceType, D3DCAPS8* pCaps) {
     IDirect3D8Impl *This = (IDirect3D8Impl *)iface;
@@ -269,15 +291,7 @@
     hrc = IWineD3D_GetDeviceCaps(This->WineD3D, Adapter, DeviceType, pWineCaps);
     LeaveCriticalSection(&d3d8_cs);
+    fixup_caps(pWineCaps);
     WINECAPSTOD3D8CAPS(pCaps, pWineCaps)
     HeapFree(GetProcessHeap(), 0, pWineCaps);
-
-    /* D3D8 doesn't support SM 2.0 or higher, so clamp to 1.x */
-    if(pCaps->PixelShaderVersion > D3DPS_VERSION(1,4)){
-        pCaps->PixelShaderVersion = D3DPS_VERSION(1,4);
-    }
-    if(pCaps->VertexShaderVersion > D3DVS_VERSION(1,1)){
-        pCaps->VertexShaderVersion = D3DVS_VERSION(1,1);
-    }
-    pCaps->MaxVertexShaderConst = min(D3D8_MAX_VERTEX_SHADER_CONSTANTF, pCaps->MaxVertexShaderConst);
 
     TRACE("(%p) returning %p\n", This, pCaps);
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/d3d8/version.rc
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/d3d8/version.rc	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/d3d8/version.rc	(revision 22496)
@@ -35,4 +35,13 @@
  */
 
+/*
+ * Sun LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
+ * other than GPL or LGPL is available it will apply instead, Sun elects to use only
+ * the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
+ * a choice of LGPL license versions is made available with the language indicating
+ * that LGPLv2 or any later version may be used, or where a choice of which version
+ * of the LGPL is applied is otherwise unspecified.
+ */
+
 #define WINE_FILEDESCRIPTION_STR "Wine Direct3D"
 #define WINE_FILENAME_STR "d3d8.dll"
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/d3d9/device.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/d3d9/device.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/d3d9/device.c	(revision 22496)
@@ -882,10 +882,21 @@
     IDirect3DDevice9Impl *This = (IDirect3DDevice9Impl *)iface;
     IDirect3DSurface9Impl *pSurface;
-    HRESULT hr;
-    TRACE("(%p) Relay\n" , This);
+    IDirect3DSurface9 *pOldSurface;
+    HRESULT hr;
+    TRACE("(%p) Relay\n" , This);
+
+
+    EnterCriticalSection(&d3d9_cs);
+    hr = IDirect3DDevice9_GetDepthStencilSurface(iface, &pOldSurface);
+    if (D3D_OK==hr) {
+        IDirect3DSurface9_Release(pOldSurface);
+        IDirect3DSurface9_Release(pOldSurface);
+    }
 
     pSurface = (IDirect3DSurface9Impl*)pZStencilSurface;
-    EnterCriticalSection(&d3d9_cs);
     hr = IWineD3DDevice_SetDepthStencilSurface(This->WineD3DDevice, NULL==pSurface ? NULL : pSurface->wineD3DSurface);
+    if (pZStencilSurface) {
+        IDirect3DSurface9_AddRef(pZStencilSurface);
+    }
     LeaveCriticalSection(&d3d9_cs);
     return hr;
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/d3d9/directx.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/d3d9/directx.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/d3d9/directx.c	(revision 22496)
@@ -208,4 +208,16 @@
     WINED3DRESOURCETYPE WineD3DRType;
     TRACE("%p\n", This);
+
+    /* This format is nothing special and it is supported perfectly.
+     * However, ati and nvidia driver on windows do not mark this format as
+     * supported (tested with the dxCapsViewer) and pretending to
+     * support this format uncovers a bug in Battlefield 1942 (fonts are missing)
+     * So do the same as Windows drivers and pretend not to support it on dx8 and 9
+     */
+    if(CheckFormat == D3DFMT_R8G8B8)
+    {
+        WARN("D3DFMT_R8G8B8 is not available on windows, returning D3DERR_NOTAVAILABLE\n");
+        return D3DERR_NOTAVAILABLE;
+    }
 
     switch(RType) {
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/d3d9/version.rc
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/d3d9/version.rc	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/d3d9/version.rc	(revision 22496)
@@ -35,4 +35,13 @@
  */
 
+/*
+ * Sun LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
+ * other than GPL or LGPL is available it will apply instead, Sun elects to use only
+ * the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
+ * a choice of LGPL license versions is made available with the language indicating
+ * that LGPLv2 or any later version may be used, or where a choice of which version
+ * of the LGPL is applied is otherwise unspecified.
+ */
+
 #define WINE_FILEDESCRIPTION_STR "Wine Direct3D"
 #define WINE_FILENAME_STR "d3d9.dll"
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/commctrl.rh
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/commctrl.rh	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/commctrl.rh	(revision 22496)
@@ -15,4 +15,13 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
+ */
+
+/*
+ * Sun LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
+ * other than GPL or LGPL is available it will apply instead, Sun elects to use only
+ * the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
+ * a choice of LGPL license versions is made available with the language indicating
+ * that LGPLv2 or any later version may be used, or where a choice of which version
+ * of the LGPL is applied is otherwise unspecified.
  */
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/config.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/config.h	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/config.h	(revision 22496)
@@ -510,5 +510,5 @@
 
 /* Define to 1 if the system has the type `off_t'. */
-//#define HAVE_OFF_T 1
+#define HAVE_OFF_T 1
 
 /* Define if OpenGL is present on the system */
@@ -1151,9 +1151,26 @@
 #define X_DISPLAY_MISSING 1
 
+/* Define to a macro to output a .cfi assembly pseudo-op */
+#define __ASM_CFI(str) str
+
+/* Define to a macro to define an assembly function */
+#define __ASM_DEFINE_FUNC(name,suffix,code) asm(".text\n\t.align 4\n\t.globl _" #name suffix "\n\t.def _" #name suffix "; .scl 2; .type 32; .endef\n_" #name suffix ":\n\t.cfi_startproc\n\t" code "\n\t.cfi_endproc");
+
 /* Define to a macro to generate an assembly function directive */
 #define __ASM_FUNC(name) ".def " __ASM_NAME(name) "; .scl 2; .type 32; .endef"
 
+/* Define to a macro to generate an assembly function with C calling
+   convention */
+#define __ASM_GLOBAL_FUNC(name,code) __ASM_DEFINE_FUNC(name,"",code)
+
 /* Define to a macro to generate an assembly name from a C symbol */
 #define __ASM_NAME(name) "_" name
+
+/* Define to a macro to generate an stdcall suffix */
+#define __ASM_STDCALL(args) "@" #args
+
+/* Define to a macro to generate an assembly function with stdcall calling
+   convention */
+#define __ASM_STDCALL_FUNC(name,args,code) __ASM_DEFINE_FUNC(name,__ASM_STDCALL(args),code)
 
 /* Define to empty if `const' does not conform to ANSI C. */
@@ -1163,4 +1180,4 @@
    calls it, or to nothing if 'inline' is not supported under any name.  */
 #ifndef __cplusplus
- #undef inline 
+/* #undef inline */
 #endif
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/d3dcaps.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/d3dcaps.h	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/d3dcaps.h	(revision 22496)
@@ -321,5 +321,4 @@
 #define D3DSTENCILCAPS_INCR     0x00000040
 #define D3DSTENCILCAPS_DECR     0x00000080
-#define D3DSTENCILCAPS_TWOSIDED 0x00000100
 
 #define D3DTEXOPCAPS_DISABLE                    0x00000001
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/d3dx8.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/d3dx8.h	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/d3dx8.h	(revision 22496)
@@ -62,4 +62,13 @@
  */
 
+/*
+ * Sun LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
+ * other than GPL or LGPL is available it will apply instead, Sun elects to use only
+ * the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
+ * a choice of LGPL license versions is made available with the language indicating
+ * that LGPLv2 or any later version may be used, or where a choice of which version
+ * of the LGPL is applied is otherwise unspecified.
+ */
+
 #ifndef __D3DX8_H__
 #define __D3DX8_H__
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/d3dx8core.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/d3dx8core.h	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/d3dx8core.h	(revision 22496)
@@ -15,4 +15,13 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
+ */
+
+/*
+ * Sun LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
+ * other than GPL or LGPL is available it will apply instead, Sun elects to use only
+ * the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
+ * a choice of LGPL license versions is made available with the language indicating
+ * that LGPLv2 or any later version may be used, or where a choice of which version
+ * of the LGPL is applied is otherwise unspecified.
  */
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/d3dx8math.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/d3dx8math.h	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/d3dx8math.h	(revision 22496)
@@ -16,4 +16,13 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
+ */
+
+/*
+ * Sun LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
+ * other than GPL or LGPL is available it will apply instead, Sun elects to use only
+ * the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
+ * a choice of LGPL license versions is made available with the language indicating
+ * that LGPLv2 or any later version may be used, or where a choice of which version
+ * of the LGPL is applied is otherwise unspecified.
  */
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/d3dx8math.inl
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/d3dx8math.inl	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/d3dx8math.inl	(revision 22496)
@@ -63,4 +63,13 @@
  */
 
+/*
+ * Sun LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
+ * other than GPL or LGPL is available it will apply instead, Sun elects to use only
+ * the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
+ * a choice of LGPL license versions is made available with the language indicating
+ * that LGPLv2 or any later version may be used, or where a choice of which version
+ * of the LGPL is applied is otherwise unspecified.
+ */
+
 #ifndef __D3DX8MATH_INL__
 #define __D3DX8MATH_INL__
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/d3dx8mesh.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/d3dx8mesh.h	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/d3dx8mesh.h	(revision 22496)
@@ -15,4 +15,13 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
+ */
+
+/*
+ * Sun LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
+ * other than GPL or LGPL is available it will apply instead, Sun elects to use only
+ * the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
+ * a choice of LGPL license versions is made available with the language indicating
+ * that LGPLv2 or any later version may be used, or where a choice of which version
+ * of the LGPL is applied is otherwise unspecified.
  */
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/dbprop.idl
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/dbprop.idl	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/dbprop.idl	(revision 22496)
@@ -40,5 +40,5 @@
     [call_as(GetProperties)] HRESULT RemoteGetProperties(
              [in] ULONG cPropertyIDSets,
-             [in, size_is(cPropertyIDSets)] const DBPROPIDSET rgPropertyIDSets[],
+             [in, unique, size_is(cPropertyIDSets)] const DBPROPIDSET *rgPropertyIDSets,
              [in, out] ULONG *pcPropertySets,
              [out, size_is(,*pcPropertySets)] DBPROPSET **prgPropertySets,
@@ -49,9 +49,10 @@
              [in, size_is(cPropertyIDSets)] const DBPROPIDSET rgPropertyIDSets[],
              [in, out] ULONG *pcPropertyInfoSets,
-             [out, size_is(,*pcPropertyInfoSets)] DBPROPINFOSET **prgPropertyInfoSets);
+             [out, size_is(,*pcPropertyInfoSets)] DBPROPINFOSET **prgPropertyInfoSets,
+             [out, /*annotation("__deref_out_z_opt")*/] OLECHAR **ppDescBuffer);
 
     [call_as(GetPropertyInfo)] HRESULT RemoteGetPropertyInfo(
              [in] ULONG cPropertyIDSets,
-             [in,size_is(cPropertyIDSets)] const DBPROPIDSET *rgPropertyIDSets,
+             [in, unique, size_is(cPropertyIDSets)] const DBPROPIDSET *rgPropertyIDSets,
              [in, out] ULONG *pcPropertyInfoSets,
              [out, size_is(,*pcPropertyInfoSets)] DBPROPINFOSET **prgPropertyInfoSets,
@@ -59,5 +60,5 @@
              [out, size_is(,*pcOffsets)] DBBYTEOFFSET **prgDescOffsets,
              [in, out] ULONG *pcbDescBuffer,
-             [out, size_is(,*pcbDescBuffer)] OLECHAR **ppDescBuffer,
+             [in, out, unique, size_is(,*pcbDescBuffer)] OLECHAR **ppDescBuffer,
              [out] IErrorInfo **ppErrorInfoRem);
 
@@ -68,5 +69,5 @@
     [call_as(SetProperties)] HRESULT RemoteSetProperties(
              [in] ULONG cPropertySets,
-             [in, out, size_is(cPropertySets)] DBPROPSET *rgPropertySets,
+             [in, unique, size_is(cPropertySets)] DBPROPSET *rgPropertySets,
              [in] ULONG cTotalProps,
              [out, size_is(cTotalProps)] DBPROPSTATUS *rgPropStatus,
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/dbs.idl
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/dbs.idl	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/dbs.idl	(revision 22496)
@@ -109,2 +109,12 @@
     GUID guidPropertySet;
 } DBPROPINFOSET;
+
+typedef DWORD DBBINDURLFLAG;
+typedef DWORD DBBINDURLSTATUS;
+
+typedef struct tagDBIMPLICITSESSION
+{
+    IUnknown *pUnkOuter;
+    IID *piid;
+    IUnknown *pSession;
+} DBIMPLICITSESSION;
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/gdiplusflat.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/gdiplusflat.h	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/gdiplusflat.h	(revision 22496)
@@ -356,4 +356,5 @@
 GpStatus WINGDIPAPI GdipGetImageHorizontalResolution(GpImage*,REAL*);
 GpStatus WINGDIPAPI GdipGetImageItemData(GpImage*,ImageItemData*);
+GpStatus WINGDIPAPI GdipGetImagePalette(GpImage*,ColorPalette*,INT);
 GpStatus WINGDIPAPI GdipGetImagePixelFormat(GpImage*,PixelFormat*);
 GpStatus WINGDIPAPI GdipGetImageRawFormat(GpImage*,GUID*);
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/msctf.idl
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/msctf.idl	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/msctf.idl	(revision 22496)
@@ -43,7 +43,14 @@
 cpp_quote("HRESULT WINAPI TF_CreateInputProcessorProfiles(ITfInputProcessorProfiles **ppipr);")
 
+cpp_quote("EXTERN_C const GUID GUID_PROP_TEXTOWNER;")
+cpp_quote("DEFINE_GUID(GUID_PROP_ATTRIBUTE,0x34b45670,0x7526,0x11d2,0xa1,0x47,0x00,0x10,0x5a,0x27,0x99,0xb5);")
+cpp_quote("EXTERN_C const GUID GUID_PROP_LANGID;")
+cpp_quote("EXTERN_C const GUID GUID_PROP_READING;")
+cpp_quote("EXTERN_C const GUID GUID_PROP_COMPOSING;")
+
 cpp_quote("EXTERN_C const CLSID CLSID_TF_ThreadMgr;")
 cpp_quote("EXTERN_C const CLSID CLSID_TF_InputProcessorProfiles;")
 cpp_quote("EXTERN_C const CLSID CLSID_TF_CategoryMgr;")
+cpp_quote("DEFINE_GUID(CLSID_TF_DisplayAttributeMgr,0x3ce74de4,0x53d3,0x4d74,0x8b,0x83,0x43,0x1b,0x38,0x28,0xba,0x53);")
 
 /* GUIDs for Compartments */
@@ -160,4 +167,15 @@
 };
 
+[
+    object,
+    uuid(d7540241-f9a1-4364-befc-dbcd2c4395b7),
+    pointer_default(unique)
+]
+interface ITfCompositionView : IUnknown
+{
+    HRESULT GetOwnerClsid([out] CLSID *pclsid);
+
+    HRESULT GetRange([out] ITfRange **ppRange);
+}
 
 [
@@ -411,4 +429,107 @@
 };
 
+typedef [uuid(c4cc07f1-80cc-4a7b-bc54-98512782cbe3)]
+enum {
+    TF_LS_NONE      = 0,
+    TF_LS_SOLID     = 1,
+    TF_LS_DOT       = 2,
+    TF_LS_DASH      = 3,
+    TF_LS_SQUIGGLE  = 4
+} TF_DA_LINESTYLE;
+
+typedef [uuid(d9b92e21-084a-401b-9c64-1e6dad91a1ab)]
+enum {
+    TF_CT_NONE      = 0,
+    TF_CT_SYSCOLOR  = 1,
+    TF_CT_COLORREF  = 2
+} TF_DA_COLORTYPE;
+
+typedef [uuid(90d0cb5e-6520-4a0f-b47c-c39bd955f0d6)]
+struct TF_DA_COLOR {
+    TF_DA_COLORTYPE type;
+    [switch_type(TF_DA_COLORTYPE), switch_is(type)]
+    union {
+        [case(TF_CT_SYSCOLOR)] int nIndex;
+        [case(TF_CT_COLORREF)] COLORREF cr;
+    };
+} TF_DA_COLOR;
+
+typedef [uuid(33d2fe4b-6c24-4f67-8d75-3bc1819e4126)]
+enum {
+    TF_ATTR_INPUT                = 0,
+    TF_ATTR_TARGET_CONVERTED     = 1,
+    TF_ATTR_CONVERTED            = 2,
+    TF_ATTR_TARGET_NOTCONVERTED  = 3,
+    TF_ATTR_INPUT_ERROR          = 4,
+    TF_ATTR_FIXEDCONVERTED       = 5,
+    TF_ATTR_OTHER                = -1
+} TF_DA_ATTR_INFO;
+
+typedef [uuid(1bf1c305-419b-4182-a4d2-9bfadc3f021f)]
+struct TF_DISPLAYATTRIBUTE {
+    TF_DA_COLOR      crText;
+    TF_DA_COLOR      crBk;
+    TF_DA_LINESTYLE  lsStyle;
+    BOOL             fBoldLine;
+    TF_DA_COLOR      crLine;
+    TF_DA_ATTR_INFO  bAttr;
+} TF_DISPLAYATTRIBUTE;
+
+[
+    object,
+    uuid(70528852-2f26-4aea-8c96-215150578932),
+    pointer_default(unique)
+]
+interface ITfDisplayAttributeInfo : IUnknown
+{
+    HRESULT GetGUID([out] GUID *pguid);
+
+    HRESULT GetDescription([out] BSTR *pbstrDesc);
+
+    HRESULT GetAttributeInfo([out] TF_DISPLAYATTRIBUTE *pda);
+
+    HRESULT SetAttributeInfo([in] const TF_DISPLAYATTRIBUTE *pda);
+
+    HRESULT Reset();
+}
+
+[
+    object,
+    uuid(7cef04d7-cb75-4e80-a7ab-5f5bc7d332de),
+    pointer_default(unique)
+]
+interface IEnumTfDisplayAttributeInfo : IUnknown
+{
+    HRESULT Clone([out] IEnumTfDisplayAttributeInfo **ppEnum);
+
+    HRESULT Next(
+            [in] ULONG ulCount,
+            [out, size_is(ulCount), length_is(*pcFetched)] ITfDisplayAttributeInfo **rgInfo,
+            [out] ULONG *pcFetched);
+
+    HRESULT Reset();
+
+    HRESULT Skip([in] ULONG ulCount);
+}
+
+[
+    object,
+    local,
+    uuid(8ded7393-5db1-475c-9e71-a39111b0ff67),
+    pointer_default(unique)
+]
+interface ITfDisplayAttributeMgr : IUnknown
+{
+    HRESULT OnUpdateInfo();
+
+    HRESULT EnumDisplayAttributeInfo([out] IEnumTfDisplayAttributeInfo **ppEnum);
+
+    HRESULT GetDisplayAttributeInfo(
+            [in] REFGUID guid,
+            [out] ITfDisplayAttributeInfo **ppInfo,
+            [out] CLSID *pclsidOwner);
+
+}
+
 [
   object,
@@ -896,4 +1017,18 @@
 [
     object,
+    uuid(057a6296-029b-4154-b79a-0d461d4ea94c),
+    pointer_default(unique)
+]
+interface ITfRangeACP : ITfRange
+{
+    HRESULT GetExtent([out] LONG *pacpAnchor,
+                      [out] LONG *pcch);
+
+    HRESULT SetExtent([in] LONG acpAnchor,
+                      [in] LONG cch);
+}
+
+[
+    object,
     uuid(55ce16ba-3014-41c1-9ceb-fade1446ac6c),
     pointer_default(unique)
@@ -920,4 +1055,201 @@
 
 [
+    object,
+    uuid(6834b120-88cb-11d2-bf45-00105a2799b5),
+    pointer_default(unique)
+]
+interface ITfPropertyStore : IUnknown
+{
+    const DWORD TF_TU_CORRECTION = 0x1;
+
+    HRESULT GetType([out] GUID *pguid);
+
+    HRESULT GetDataType([out] DWORD *pdwReserved);
+
+    HRESULT GetData([out] VARIANT *pvarValue);
+
+    HRESULT OnTextUpdated(
+            [in] DWORD dwFlags,
+            [in] ITfRange *pRangeNew,
+            [out] BOOL *pfAccept);
+
+    HRESULT Shrink(
+            [in] ITfRange *pRangeNew,
+            [out] BOOL *pfFree);
+
+    HRESULT Divide(
+            [in] ITfRange *pRangeThis,
+            [in] ITfRange *pRangeNew,
+            [out] ITfPropertyStore **ppPropStore);
+
+    HRESULT Clone(
+            [out] ITfPropertyStore **pPropStore);
+
+    HRESULT GetPropertyRangeCreator(
+            [out] CLSID *pclsid);
+
+    HRESULT Serialize(
+            [in] IStream *pStream,
+            [out] ULONG *pcb);
+}
+
+[
+    object,
+    uuid(f99d3f40-8e32-11d2-bf46-00105a2799b5),
+    pointer_default(unique)
+]
+interface IEnumTfRanges : IUnknown
+{
+    HRESULT Clone([out] IEnumTfRanges **ppEnum);
+
+    HRESULT Next(
+            [in] ULONG ulCount,
+            [out, size_is(ulCount), length_is(*pcFetched)] ITfRange **ppRange,
+            [out] ULONG *pcFetched);
+
+    HRESULT Reset();
+
+    HRESULT Skip(ULONG ulCount);
+}
+
+[
+    object,
+    uuid(5efd22Ba-7838-46cb-88e2-cadb14124f8f),
+    pointer_default(unique)
+]
+interface IEnumITfCompositionView : IUnknown
+{
+    HRESULT Clone([out] IEnumITfCompositionView **ppEnum);
+
+    HRESULT Next(
+            [in] ULONG ulCount,
+            [out, size_is(ulCount), length_is(*pcFetched)] ITfCompositionView **rgCompositionView,
+            [out] ULONG *pcFetched);
+
+    HRESULT Reset();
+
+    HRESULT Skip([in] ULONG ulCount);
+}
+
+[
+    object,
+    uuid(20168d64-5a8f-4a5a-b7bd-cfa29f4D0fd9),
+    pointer_default(unique)
+]
+interface ITfComposition : IUnknown
+{
+    HRESULT GetRange([out] ITfRange **ppRange);
+
+    HRESULT ShiftStart(
+            [in] TfEditCookie ecWrite,
+            [in] ITfRange *pNewStart);
+
+    HRESULT ShiftEnd(
+            [in] TfEditCookie ecWrite,
+            [in] ITfRange *pNewEnd);
+
+    HRESULT EndComposition([in] TfEditCookie ecWrite);
+}
+
+[
+    object,
+    uuid(a781718c-579a-4b15-a280-32b8577acc5e),
+    pointer_default(unique)
+]
+interface ITfCompositionSink : IUnknown
+{
+    HRESULT OnCompositionTerminated(
+            [in] TfEditCookie ecWrite,
+            [in] ITfComposition *pComposition);
+}
+
+[
+    object,
+    uuid(d40C8aae-aC92-4fc7-9a11-0ee0e23aa39b),
+    pointer_default(unique)
+]
+interface ITfContextComposition : IUnknown
+{
+    HRESULT StartComposition(
+            [in] TfEditCookie ecWrite,
+            [in] ITfRange *pCompositionRange,
+            [in] ITfCompositionSink *pSink,
+            [out] ITfComposition **ppComposition);
+
+    HRESULT EnumCompositions([out] IEnumITfCompositionView **ppEnum);
+
+    HRESULT FindComposition(
+            [in] TfEditCookie ecRead,
+            [in] ITfRange *pTestRange,
+            [out] IEnumITfCompositionView **ppEnum);
+
+    HRESULT TakeOwnership(
+            [in] TfEditCookie ecWrite,
+            [in] ITfCompositionView *pComposition,
+            [in] ITfCompositionSink *pSink,
+            [out] ITfComposition **ppComposition);
+}
+
+[
+    object,
+    uuid(86462810-593b-4916-9764-19c08e9ce110),
+    pointer_default(unique)
+]
+interface ITfContextOwnerCompositionServices : ITfContextComposition
+{
+    HRESULT TerminateComposition([in] ITfCompositionView *pComposition);
+}
+
+[
+    object,
+    uuid(17d49a3d-f8b8-4b2f-b254-52319dd64c53),
+    pointer_default(unique)
+]
+interface ITfReadOnlyProperty : IUnknown
+{
+    HRESULT GetType([out] GUID *pguid);
+
+    HRESULT EnumRanges(
+            [in] TfEditCookie ec,
+            [out] IEnumTfRanges **ppEnum,
+            [in] ITfRange *pTargetRange);
+
+    HRESULT GetValue(
+            [in] TfEditCookie ec,
+            [in] ITfRange *pRange,
+            [out] VARIANT *pvarValue);
+
+    HRESULT GetContext([out] ITfContext **ppContext);
+}
+
+[
+    object,
+    uuid(e2449660-9542-11d2-bf46-00105a2799b5),
+    pointer_default(unique)
+]
+interface ITfProperty : ITfReadOnlyProperty
+{
+    HRESULT FindRange(
+            [in] TfEditCookie ec,
+            [in] ITfRange *pRange,
+            [out] ITfRange **ppRange,
+            [in] TfAnchor aPos);
+
+    HRESULT SetValueStore(
+            [in] TfEditCookie ec,
+            [in] ITfRange *pRange,
+            [in] ITfPropertyStore *pPropStore);
+
+    HRESULT SetValue(
+            [in] TfEditCookie ec,
+            [in] ITfRange *pRange,
+            [in] const VARIANT *pvarValue);
+
+    HRESULT Clear(
+            [in] TfEditCookie ec,
+            [in] ITfRange *pRange);
+}
+
+[
   object,
   uuid(bb08f7a9-607a-4384-8623-056892b64371),
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/mshtml.idl
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/mshtml.idl	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/mshtml.idl	(revision 22496)
@@ -102,4 +102,24 @@
 } SELECTION_TYPE;
 
+[
+    odl,
+    oleautomation,
+    dual,
+    uuid(3051049b-98b5-11cf-bb82-00aa00bdce0b)
+]
+interface IHTMLDOMConstructor : IDispatch
+{
+    [propget, id(DISPID_IHTMLDOMCONSTRUCTOR_CONSTRUCTOR), hidden]
+    HRESULT constructor([retval, out] IDispatch* * p);
+
+    HRESULT LookupGetter([in] BSTR propname, [retval, out] VARIANT* ppDispHandler);
+
+    HRESULT LookupSetter([in] BSTR propname, [retval, out] VARIANT* ppDispHandler);
+
+    HRESULT DefineGetter([in] BSTR propname, [in] VARIANT* pdispHandler);
+
+    HRESULT DefineSetter([in] BSTR propname, [in] VARIANT* pdispHandler);
+}
+
 interface IHTMLDocument2;
 interface IHTMLStyleSheetsCollection;
@@ -5387,4 +5407,39 @@
 }
 
+[
+    hidden,
+    uuid(3050f50e-98b5-11cf-bb82-00aa00bdce0b)
+]
+dispinterface DispHTMLStyleSheetRule
+{
+properties:
+methods:
+    [propput, id(DISPID_IHTMLSTYLESHEETRULE_SELECTORTEXT)]
+    void selectorText(BSTR v);
+
+    [propget, id(DISPID_IHTMLSTYLESHEETRULE_SELECTORTEXT)]
+    BSTR selectorText();
+
+    [propget, id(DISPID_IHTMLSTYLESHEETRULE_STYLE), nonbrowsable]
+    IHTMLRuleStyle* style();
+
+    [propget, id(DISPID_IHTMLSTYLESHEETRULE_READONLY)]
+    VARIANT_BOOL readOnly();
+
+    [propget, id(DISPID_IHTMLDOMCONSTRUCTOR_CONSTRUCTOR), hidden]
+    IDispatch* constructor();
+}
+
+[
+    noncreatable,
+    uuid(3050f3ce-98b5-11cf-bb82-00aa00bdce0b)
+]
+coclass HTMLStyleSheetRule
+{
+    [default]           dispinterface DispHTMLStyleSheetRule;
+                        interface IHTMLStyleSheetRule;
+                        interface IHTMLDOMConstructor;
+}
+
 /*****************************************************************************
  *    IHTMLStyleSheetRulesCollection interface
@@ -5408,4 +5463,33 @@
 
 [
+    hidden,
+    uuid(3050f52f-98b5-11cf-bb82-00aa00bdce0b)
+]
+dispinterface DispHTMLStyleSheetRulesCollection
+{
+properties:
+methods:
+    [propget, id(DISPID_IHTMLSTYLESHEETRULESCOLLECTION_LENGTH)]
+    long length();
+
+    [id(DISPID_IHTMLSTYLESHEETRULESCOLLECTION_ITEM)]
+    IHTMLStyleSheetRule* item([in] long index);
+
+    [propget, id(DISPID_IHTMLDOMCONSTRUCTOR_CONSTRUCTOR), hidden]
+    IDispatch* constructor();
+}
+
+[
+    noncreatable,
+    uuid(3050f3cd-98b5-11cf-bb82-00aa00bdce0b)
+]
+coclass HTMLStyleSheetRulesCollection
+{
+    [default]           dispinterface DispHTMLStyleSheetRulesCollection;
+                        interface IHTMLStyleSheetRulesCollection;
+                        interface IHTMLDOMConstructor;
+}
+
+[
     odl,
     oleautomation,
@@ -5421,4 +5505,32 @@
     HRESULT pseudoClass([retval, out] BSTR *p);
 }
+
+[
+    hidden,
+    uuid(3050f540-98b5-11cf-bb82-00aa00bdce0b)
+]
+dispinterface DispHTMLStyleSheetPage
+{
+properties:
+methods:
+    [propget, id(DISPID_IHTMLSTYLESHEETPAGE_SELECTOR)]
+    BSTR selector();
+
+    [propget, id(DISPID_IHTMLSTYLESHEETPAGE_PSEUDOCLASS)]
+    BSTR pseudoClass();
+
+    [propget, id(DISPID_IHTMLDOMCONSTRUCTOR_CONSTRUCTOR), hidden]
+    IDispatch* constructor();
+}
+[
+    noncreatable,
+    uuid(3050f7ef-98b5-11cf-bb82-00aa00bdce0b)
+]
+coclass HTMLStyleSheetPage
+{
+    [default]           dispinterface DispHTMLStyleSheetPage;
+                        interface IHTMLStyleSheetPage;
+                        interface IHTMLDOMConstructor;
+};
 
 [
@@ -5437,4 +5549,33 @@
         [in] LONG index,
         [retval, out] IHTMLStyleSheetPage **ppHTMLStyleSheetPage);
+}
+
+[
+    hidden,
+    uuid(3050f543-98b5-11cf-bb82-00aa00bdce0b)
+]
+dispinterface DispHTMLStyleSheetPagesCollection
+{
+properties:
+methods:
+    [propget, id(DISPID_IHTMLSTYLESHEETPAGESCOLLECTION_LENGTH)]
+    long length();
+
+    [id(DISPID_IHTMLSTYLESHEETPAGESCOLLECTION_ITEM)]
+    IHTMLStyleSheetPage* item([in] long index);
+
+    [propget, id(DISPID_IHTMLDOMCONSTRUCTOR_CONSTRUCTOR), hidden]
+    IDispatch* constructor();
+}
+
+[
+    noncreatable,
+    uuid(3050f7f1-98b5-11cf-bb82-00aa00bdce0b)
+]
+coclass HTMLStyleSheetPagesCollection
+{
+    [default]           dispinterface DispHTMLStyleSheetPagesCollection;
+                        interface IHTMLStyleSheetPagesCollection;
+                        interface IHTMLDOMConstructor;
 }
 
@@ -9626,4 +9767,19 @@
 }
 
+[
+    odl,
+    oleautomation,
+    dual,
+    uuid(3050f820-98b5-11cf-bb82-00aa00bdce0b)
+]
+interface IHTMLOptionElement3 : IDispatch
+{
+    [propput, id(DISPID_IHTMLOPTIONELEMENT3_LABEL), displaybind, bindable]
+    HRESULT label([in] BSTR v);
+
+    [propget, id(DISPID_IHTMLOPTIONELEMENT3_LABEL), displaybind, bindable]
+    HRESULT label([retval, out] BSTR * p);
+}
+
 /*****************************************************************************
  *    IHTMLOptionElementFactory interface
@@ -10535,4 +10691,25 @@
     [propget, id(DISPID_IHTMLOPTIONELEMENT3_LABEL), displaybind, bindable]
     BSTR label();
+}
+
+[
+    noncreatable,
+    uuid(3050f24d-98b5-11cf-bb82-00aa00bdce0b)
+]
+coclass HTMLOptionElement
+{
+    [default]           dispinterface DispHTMLOptionElement;
+    [source, default]   dispinterface HTMLElementEvents;
+    [source]            dispinterface HTMLElementEvents2;
+                        interface IHTMLElement;
+                        interface IHTMLElement2;
+                        interface IHTMLElement3;
+                        interface IHTMLElement4;
+                        interface IHTMLUniqueName;
+                        interface IHTMLDOMNode;
+                        interface IHTMLDOMNode2;
+                        interface IHTMLDatabinding;
+                        interface IHTMLOptionElement;
+                        interface IHTMLOptionElement3;
 }
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/msxml.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/msxml.h	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/msxml.h	(revision 22496)
@@ -1,3 +1,3 @@
-/*** Autogenerated by WIDL 1.1.26 from ../../include/msxml.idl - Do not edit ***/
+/*** Autogenerated by WIDL 1.1.27 from ../../include/msxml.idl - Do not edit ***/
 
 #include <rpc.h>
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/oaidl.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/oaidl.h	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/oaidl.h	(revision 22496)
@@ -1,3 +1,3 @@
-/*** Autogenerated by WIDL 1.1.26 from ../../include/oaidl.idl - Do not edit ***/
+/*** Autogenerated by WIDL 1.1.27 from ../../include/oaidl.idl - Do not edit ***/
 
 #include <rpc.h>
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/objidl.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/objidl.h	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/objidl.h	(revision 22496)
@@ -1,3 +1,3 @@
-/*** Autogenerated by WIDL 1.1.26 from ../../include/objidl.idl - Do not edit ***/
+/*** Autogenerated by WIDL 1.1.27 from ../../include/objidl.idl - Do not edit ***/
 
 #include <rpc.h>
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/oledb.idl
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/oledb.idl	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/oledb.idl	(revision 22496)
@@ -16,5 +16,5 @@
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
  */
-
+cpp_quote("#ifdef _WIN64")
 /*
  * Sun LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
@@ -26,12 +26,31 @@
  */
 
+cpp_quote("#include <pshpack8.h>")
+cpp_quote("#else")
+cpp_quote("#include <pshpack2.h>")
+cpp_quote("#endif")
+cpp_quote("")
+
 import "wtypes.idl";
 import "oaidl.idl";
 import "ocidl.idl";
 import "propidl.idl";
+import "urlmon.idl";
 
 typedef ULONG DBBYTEOFFSET;
+typedef ULONG DBCOUNTITEM;
 
+#include "dbs.idl"
+
+#include "dbccmd.idl"
+#include "dbcses.idl"
+#include "dbprop.idl"
 #include "dbinit.idl"
-#include "dbs.idl"
-#include "dbprop.idl"
+#include "dbdsad.idl"
+#include "sesprp.idl"
+#include "opnrst.idl"
+#include "binres.idl"
+#include "crtrow.idl"
+
+cpp_quote("#include <poppack.h>")
+cpp_quote("")
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/oleidl.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/oleidl.h	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/oleidl.h	(revision 22496)
@@ -1,3 +1,3 @@
-/*** Autogenerated by WIDL 1.1.26 from ../../include/oleidl.idl - Do not edit ***/
+/*** Autogenerated by WIDL 1.1.27 from ../../include/oleidl.idl - Do not edit ***/
 
 #include <rpc.h>
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/propidl.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/propidl.h	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/propidl.h	(revision 22496)
@@ -1,3 +1,3 @@
-/*** Autogenerated by WIDL 1.1.26 from ../../include/propidl.idl - Do not edit ***/
+/*** Autogenerated by WIDL 1.1.27 from ../../include/propidl.idl - Do not edit ***/
 
 #include <rpc.h>
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/servprov.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/servprov.h	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/servprov.h	(revision 22496)
@@ -1,3 +1,3 @@
-/*** Autogenerated by WIDL 1.1.26 from ../../include/servprov.idl - Do not edit ***/
+/*** Autogenerated by WIDL 1.1.27 from ../../include/servprov.idl - Do not edit ***/
 
 #include <rpc.h>
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/textstor.idl
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/textstor.idl	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/textstor.idl	(revision 22496)
@@ -30,6 +30,17 @@
 #endif
 
+cpp_quote("#define TS_E_INVALIDPOS      MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0200)")
+cpp_quote("#define TS_E_NOLOCK          MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0201)")
+cpp_quote("#define TS_E_NOOBJECT        MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0202)")
+cpp_quote("#define TS_E_NOSERVICE       MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0203)")
+cpp_quote("#define TS_E_NOINTERFACE     MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0204)")
+cpp_quote("#define TS_E_NOSELECTION     MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0205)")
+cpp_quote("#define TS_E_NOLAYOUT        MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0206)")
+cpp_quote("#define TS_E_INVALIDPOINT    MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0207)")
+cpp_quote("#define TS_E_SYNCHRONOUS     MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0208)")
 cpp_quote("#define TS_E_READONLY        MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0209)")
-cpp_quote("#define TS_E_NOLOCK          MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0201)")
+cpp_quote("#define TS_E_FORMAT          MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x020a)")
+
+cpp_quote("#define TS_S_ASYNC           MAKE_HRESULT(SEVERITY_SUCCESS, FACILITY_ITF, 0x0300)")
 
 
@@ -59,4 +70,7 @@
 const WCHAR TS_CHAR_REGION       = 0x0000;
 const WCHAR TS_CHAR_REPLACEMENT  = 0xfffd;
+
+const DWORD TS_IAS_NOQUERY    = 0x1;
+const DWORD TS_IAS_QUERYONLY  = 0x2;
 
 typedef [uuid(05fcf85b-5e9c-4c3e-ab71-29471d4f38e7)]  enum { TS_AE_NONE, TS_AE_START, TS_AE_END } TsActiveSelEnd;
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/unknwn.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/unknwn.h	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/unknwn.h	(revision 22496)
@@ -1,3 +1,3 @@
-/*** Autogenerated by WIDL 1.1.26 from ../../include/unknwn.idl - Do not edit ***/
+/*** Autogenerated by WIDL 1.1.27 from ../../include/unknwn.idl - Do not edit ***/
 
 #include <rpc.h>
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/urlmon.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/urlmon.h	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/urlmon.h	(revision 22496)
@@ -1,3 +1,3 @@
-/*** Autogenerated by WIDL 1.1.26 from ../../include/urlmon.idl - Do not edit ***/
+/*** Autogenerated by WIDL 1.1.27 from ../../include/urlmon.idl - Do not edit ***/
 
 /*
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/winbase.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/winbase.h	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/winbase.h	(revision 22496)
@@ -1434,4 +1434,5 @@
 WINBASEAPI BOOL        WINAPI DebugBreakProcess(HANDLE);
 WINBASEAPI BOOL        WINAPI DebugSetProcessKillOnExit(BOOL);
+WINBASEAPI PVOID       WINAPI DecodePointer(PVOID);
 WINADVAPI  BOOL        WINAPI DecryptFileA(LPCSTR,DWORD);
 WINADVAPI  BOOL        WINAPI DecryptFileW(LPCWSTR,DWORD);
@@ -1466,4 +1467,5 @@
 WINADVAPI  BOOL        WINAPI DuplicateTokenEx(HANDLE,DWORD,LPSECURITY_ATTRIBUTES,SECURITY_IMPERSONATION_LEVEL,TOKEN_TYPE,PHANDLE);
 WINBASEAPI BOOL        WINAPI EscapeCommFunction(HANDLE,UINT);
+WINBASEAPI PVOID       WINAPI EncodePointer(PVOID);
 WINADVAPI  BOOL        WINAPI EncryptFileA(LPCSTR);
 WINADVAPI  BOOL        WINAPI EncryptFileW(LPCWSTR);
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wincodec.idl
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wincodec.idl	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wincodec.idl	(revision 22496)
@@ -79,4 +79,29 @@
 } WICBitmapPaletteType;
 
+typedef enum WICComponentType {
+    WICDecoder = 0x00000001,
+    WICEncoder = 0x00000002,
+    WICPixelFormatConverter = 0x00000004,
+    WICMetadataReader = 0x00000008,
+    WICMetadataWriter = 0x00000010,
+    WICPixelFormat = 0x00000020,
+    WICCOMPONENTTYPE_FORCE_DWORD = CODEC_FORCE_DWORD
+} WICComponentType;
+
+typedef enum WICComponentSigning {
+    WICComponentSigned = 0x00000001,
+    WICComponentUnsigned = 0x00000002,
+    WICComponentSafe = 0x00000004,
+    WICComponentDisabled = 0x80000000
+} WICComponentSigning;
+
+typedef enum WICComponentEnumerateOptions {
+    WICComponentEnumerateDefault = 0x00000000,
+    WICComponentEnumerateRefresh = 0x00000001,
+    WICComponentEnumerateBuiltInOnly = 0x20000000,
+    WICComponentEnumerateUnsigned = 0x40000000,
+    WICComponentEnumerateDisabled = 0x80000000
+} WICComponentEnumerateOptions;
+
 typedef GUID WICPixelFormatGUID;
 typedef REFGUID REFWICPixelFormatGUID;
@@ -101,4 +126,12 @@
 } WICRect;
 
+typedef struct WICBitmapPattern {
+    ULARGE_INTEGER Position;
+    ULONG Length;
+    BYTE *Pattern;
+    BYTE *Mask;
+    BOOL EndOfStream;
+} WICBitmapPattern;
+
 typedef UINT32 WICColor;
 
@@ -106,8 +139,9 @@
 cpp_quote("#define WINCODEC_ERR_CODECNOTHUMBNAIL 0x88982f44")
 cpp_quote("#define WINCODEC_ERR_PALETTEUNAVAILABLE 0x88982f45")
+cpp_quote("#define WINCODEC_ERR_COMPONENTNOTFOUND 0x88982f50")
 cpp_quote("#define WINCODEC_ERR_UNSUPPORTEDOPERATION 0x88982f81")
+cpp_quote("#define WINCODEC_ERR_INSUFFICIENTBUFFER 0x88982f8c")
 
 interface IWICBitmap;
-interface IWICComponentInfo;
 interface IWICBitmapEncoder;
 interface IWICPalette;
@@ -122,5 +156,4 @@
 interface IWICMetadataQueryReader;
 interface IWICMetadataQueryWriter;
-interface IWICBitmapDecoderInfo;
 
 [
@@ -196,4 +229,43 @@
 [
     object,
+    uuid(23bc3f0a-698b-4357-886b-f24d50671334)
+]
+interface IWICComponentInfo : IUnknown
+{
+    HRESULT GetComponentType(
+        [out] WICComponentType *pType);
+
+    HRESULT GetCLSID(
+        [out] CLSID *pclsid);
+
+    HRESULT GetSigningStatus(
+        [out] DWORD *pStatus);
+
+    HRESULT GetAuthor(
+        [in] UINT cchAuthor,
+        [in, out, unique, size_is(cchAuthor)] WCHAR *wzAuthor,
+        [out] UINT *pcchActual);
+
+    HRESULT GetVendorGUID(
+        [out] GUID *pguidVendor);
+
+    HRESULT GetVersion(
+        [in] UINT cchVersion,
+        [in, out, unique, size_is(cchVersion)] WCHAR *wzVersion,
+        [out] UINT *pcchActual);
+
+    HRESULT GetSpecVersion(
+        [in] UINT cchSpecVersion,
+        [in, out, unique, size_is(cchSpecVersion)] WCHAR *wzSpecVersion,
+        [out] UINT *pcchActual);
+
+    HRESULT GetFriendlyName(
+        [in] UINT cchFriendlyName,
+        [in, out, unique, size_is(cchFriendlyName)] WCHAR *wzFriendlyName,
+        [out] UINT *pcchActual);
+}
+
+[
+    object,
     uuid(3b16811b-6a43-4ec9-a813-3d930c13b940)
 ]
@@ -210,4 +282,83 @@
     HRESULT GetThumbnail(
         [out] IWICBitmapSource **ppIThumbnail);
+}
+
+[
+    object,
+    uuid(e87a44c4-b76e-4c47-8b09-298eb12a2714)
+]
+interface IWICBitmapCodecInfo : IWICComponentInfo
+{
+    HRESULT GetContainerFormat(
+        [out] GUID *pguidContainerFormat);
+
+    HRESULT GetPixelFormats(
+        [in] UINT cFormats,
+        [in, out, unique, size_is(cFormats)] GUID *pguidPixelFormats,
+        [out] UINT *pcActual);
+
+    HRESULT GetColorManagementVersion(
+        [in] UINT cchColorManagementVersion,
+        [in, out, unique, size_is(cchColorManagementVersion)] WCHAR *wzColorManagementVersion,
+        [out] UINT *pcchActual);
+
+    HRESULT GetDeviceManufacturer(
+        [in] UINT cchDeviceManufacturer,
+        [in, out, unique, size_is(cchDeviceManufacturer)] WCHAR *wzDeviceManufacturer,
+        [out] UINT *pcchActual);
+
+    HRESULT GetDeviceModels(
+        [in] UINT cchDeviceModels,
+        [in, out, unique, size_is(cchDeviceModels)] WCHAR *wzDeviceModels,
+        [out] UINT *pcchActual);
+
+    HRESULT GetMimeTypes(
+        [in] UINT cchMimeTypes,
+        [in, out, unique, size_is(cchMimeTypes)] WCHAR *wzMimeTypes,
+        [out] UINT *pcchActual);
+
+    HRESULT GetFileExtensions(
+        [in] UINT cchFileExtensions,
+        [in, out, unique, size_is(cchFileExtensions)] WCHAR *wzFileExtensions,
+        [out] UINT *pcchActual);
+
+    HRESULT DoesSupportAnimation(
+        [out] BOOL *pfSupportAnimation);
+
+    HRESULT DoesSupportChromaKey(
+        [out] BOOL *pfSupportChromaKey);
+
+    HRESULT DoesSupportLossless(
+        [out] BOOL *pfSupportLossless);
+
+    HRESULT DoesSupportMultiframe(
+        [out] BOOL *pfSupportMultiframe);
+
+    HRESULT MatchesMimeType(
+        [in] LPCWSTR wzMimeType,
+        [out] BOOL *pfMatches);
+}
+
+interface IWICBitmapDecoder;
+
+[
+    object,
+    uuid(d8cd007f-d08f-4191-9bfc-236ea7f0e4b5)
+]
+interface IWICBitmapDecoderInfo : IWICBitmapCodecInfo
+{
+    [local]
+    HRESULT GetPatterns(
+        [in] UINT cbSizePatterns,
+        [in, out, unique] WICBitmapPattern *pPatterns,
+        [in, out, unique] UINT *pcPatterns,
+        [in, out, unique] UINT *pcbPatternsActual);
+
+    HRESULT MatchesPattern(
+        [in] IStream *pIStream,
+        [out] BOOL *pfMatches);
+
+    HRESULT CreateInstance(
+        [out] IWICBitmapDecoder **ppIBitmapDecoder);
 }
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/dcetypes.idl
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/dcetypes.idl	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/dcetypes.idl	(revision 22496)
@@ -17,4 +17,13 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
+ */
+
+/*
+ * Sun LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
+ * other than GPL or LGPL is available it will apply instead, Sun elects to use only
+ * the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
+ * a choice of LGPL license versions is made available with the language indicating
+ * that LGPLv2 or any later version may be used, or where a choice of which version
+ * of the LGPL is applied is otherwise unspecified.
  */
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/epm.idl
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/epm.idl	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/epm.idl	(revision 22496)
@@ -17,4 +17,13 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
+ */
+
+/*
+ * Sun LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
+ * other than GPL or LGPL is available it will apply instead, Sun elects to use only
+ * the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
+ * a choice of LGPL license versions is made available with the language indicating
+ * that LGPLv2 or any later version may be used, or where a choice of which version
+ * of the LGPL is applied is otherwise unspecified.
  */
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/irot.idl
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/irot.idl	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/irot.idl	(revision 22496)
@@ -15,4 +15,13 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
+ */
+
+/*
+ * Sun LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
+ * other than GPL or LGPL is available it will apply instead, Sun elects to use only
+ * the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
+ * a choice of LGPL license versions is made available with the language indicating
+ * that LGPLv2 or any later version may be used, or where a choice of which version
+ * of the LGPL is applied is otherwise unspecified.
  */
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/itss.idl
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/itss.idl	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/itss.idl	(revision 22496)
@@ -15,4 +15,13 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
+ */
+
+/*
+ * Sun LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
+ * other than GPL or LGPL is available it will apply instead, Sun elects to use only
+ * the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
+ * a choice of LGPL license versions is made available with the language indicating
+ * that LGPLv2 or any later version may be used, or where a choice of which version
+ * of the LGPL is applied is otherwise unspecified.
  */
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/pthread.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/pthread.h	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/pthread.h	(revision 22496)
@@ -17,4 +17,13 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
+ */
+
+/*
+ * Sun LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
+ * other than GPL or LGPL is available it will apply instead, Sun elects to use only
+ * the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
+ * a choice of LGPL license versions is made available with the language indicating
+ * that LGPLv2 or any later version may be used, or where a choice of which version
+ * of the LGPL is applied is otherwise unspecified.
  */
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/svcctl.idl
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/svcctl.idl	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/svcctl.idl	(revision 22496)
@@ -29,4 +29,13 @@
  */
 
+/*
+ * Sun LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
+ * other than GPL or LGPL is available it will apply instead, Sun elects to use only
+ * the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
+ * a choice of LGPL license versions is made available with the language indicating
+ * that LGPLv2 or any later version may be used, or where a choice of which version
+ * of the LGPL is applied is otherwise unspecified.
+ */
+
 import "wtypes.idl";
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/wine_common_ver.rc
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/wine_common_ver.rc	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/wine_common_ver.rc	(revision 22496)
@@ -16,4 +16,13 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
+ */
+
+/*
+ * Sun LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
+ * other than GPL or LGPL is available it will apply instead, Sun elects to use only
+ * the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
+ * a choice of LGPL license versions is made available with the language indicating
+ * that LGPLv2 or any later version may be used, or where a choice of which version
+ * of the LGPL is applied is otherwise unspecified.
  */
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/wined3d.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/wined3d.h	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/wined3d.h	(revision 22496)
@@ -1,3 +1,3 @@
-/*** Autogenerated by WIDL 1.1.26 from ../../include/wine/wined3d.idl - Do not edit ***/
+/*** Autogenerated by WIDL 1.1.27 from ../../include/wine/wined3d.idl - Do not edit ***/
 
 #include <rpc.h>
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/wined3d.idl
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/wined3d.idl	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/wined3d.idl	(revision 22496)
@@ -22,4 +22,13 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
+ */
+
+/*
+ * Sun LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
+ * other than GPL or LGPL is available it will apply instead, Sun elects to use only
+ * the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
+ * a choice of LGPL license versions is made available with the language indicating
+ * that LGPLv2 or any later version may be used, or where a choice of which version
+ * of the LGPL is applied is otherwise unspecified.
  */
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/winedxgi.idl
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/winedxgi.idl	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wine/winedxgi.idl	(revision 22496)
@@ -15,4 +15,13 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
+ */
+
+/*
+ * Sun LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
+ * other than GPL or LGPL is available it will apply instead, Sun elects to use only
+ * the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
+ * a choice of LGPL license versions is made available with the language indicating
+ * that LGPLv2 or any later version may be used, or where a choice of which version
+ * of the LGPL is applied is otherwise unspecified.
  */
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wingdi.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wingdi.h	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wingdi.h	(revision 22496)
@@ -1785,5 +1785,5 @@
   /* Device-independent bitmaps */
 
-typedef struct {
+typedef struct tagRGBQUAD {
   BYTE rgbBlue;
   BYTE rgbGreen;
@@ -1792,5 +1792,5 @@
 } RGBQUAD, *LPRGBQUAD;
 
-typedef struct {
+typedef struct tagRGBTRIPLE {
   BYTE rgbtBlue;
   BYTE rgbtGreen;
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/winuser.rh
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/winuser.rh	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/winuser.rh	(revision 22496)
@@ -15,4 +15,13 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
+ */
+
+/*
+ * Sun LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
+ * other than GPL or LGPL is available it will apply instead, Sun elects to use only
+ * the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
+ * a choice of LGPL license versions is made available with the language indicating
+ * that LGPLv2 or any later version may be used, or where a choice of which version
+ * of the LGPL is applied is otherwise unspecified.
  */
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wtypes.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wtypes.h	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/include/wtypes.h	(revision 22496)
@@ -1,3 +1,3 @@
-/*** Autogenerated by WIDL 1.1.26 from ../../include/wtypes.idl - Do not edit ***/
+/*** Autogenerated by WIDL 1.1.27 from ../../include/wtypes.idl - Do not edit ***/
 
 #include <rpc.h>
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/libWine/cptable.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/libWine/cptable.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/libWine/cptable.c	(revision 22496)
@@ -27,4 +27,7 @@
  * of the LGPL is applied is otherwise unspecified.
  */
+
+#include "config.h"
+#include "wine/port.h"
 
 #include <stdlib.h>
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/libWine/defaults
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/libWine/defaults	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/libWine/defaults	(revision 22496)
@@ -34,4 +34,13 @@
 # are handled automatically and do not have to be defined here. They can
 # still be defined if necessary to override the unicode decomposition.
+#
+
+#
+# Sun LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
+# other than GPL or LGPL is available it will apply instead, Sun elects to use only
+# the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
+# a choice of LGPL license versions is made available with the language indicating
+# that LGPLv2 or any later version may be used, or where a choice of which version
+# of the LGPL is applied is otherwise unspecified.
 #
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/libWine/loader.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/libWine/loader.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/libWine/loader.c	(revision 22496)
@@ -59,5 +59,7 @@
 #define environ (*_NSGetEnviron())
 #else
+# ifndef _MSC_VER
 extern char **environ;
+# endif
 #endif
 
@@ -458,5 +460,9 @@
 char **__wine_get_main_environment(void)
 {
+#ifndef _MSC_VER
     return environ;
+#else
+    return _environ;
+#endif
 }
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/libWine/mbtowc.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/libWine/mbtowc.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/libWine/mbtowc.c	(revision 22496)
@@ -28,4 +28,7 @@
  */
 
+#include "config.h"
+#include "wine/port.h"
+
 #include <string.h>
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/libWine/string.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/libWine/string.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/libWine/string.c	(revision 22496)
@@ -27,4 +27,7 @@
  * of the LGPL is applied is otherwise unspecified.
  */
+
+#include "config.h"
+#include "wine/port.h"
 
 #include <assert.h>
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/libWine/utf8.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/libWine/utf8.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/libWine/utf8.c	(revision 22496)
@@ -28,4 +28,7 @@
  */
 
+#include "config.h"
+#include "wine/port.h"
+
 #include <string.h>
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/libWine/version.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/libWine/version.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/libWine/version.c	(revision 22496)
@@ -1,1 +1,1 @@
-const char wine_build[] = "wine-1.1.26";
+const char wine_build[] = "wine-1.1.27";
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/libWine/wctomb.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/libWine/wctomb.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/libWine/wctomb.c	(revision 22496)
@@ -28,4 +28,7 @@
  */
 
+#include "config.h"
+#include "wine/port.h"
+
 #include <string.h>
 
@@ -79,7 +82,7 @@
                                          WCHAR wch, unsigned char ch )
 {
-    if (flags & WC_NO_BEST_FIT_CHARS) return (table->cp2uni[ch] == wch);
-    if (ch != (unsigned char)table->info.def_char) return 1;
-    return (wch == table->info.def_unicode_char);
+    if ((flags & WC_NO_BEST_FIT_CHARS) || ch == (unsigned char)table->info.def_char)
+        return (table->cp2uni[ch] == wch);
+    return 1;
 }
 
@@ -272,6 +275,5 @@
                                          WCHAR wch, unsigned short ch )
 {
-    if (ch == table->info.def_char && wch != table->info.def_unicode_char) return 0;
-    if (flags & WC_NO_BEST_FIT_CHARS)
+    if ((flags & WC_NO_BEST_FIT_CHARS) || ch == table->info.def_char)
     {
         /* check if char maps back to the same Unicode value */
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/arb_program_shader.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/arb_program_shader.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/arb_program_shader.c	(revision 22496)
@@ -59,9 +59,16 @@
 }
 
+/* Returns TRUE if result.clip from GL_NV_vertex_program2 should be used and FALSE otherwise */
+static inline BOOL use_nv_clip(const struct wined3d_gl_info *gl_info)
+{
+    return GL_SUPPORT(NV_VERTEX_PROGRAM2_OPTION);
+}
+
 static BOOL need_helper_const(const struct wined3d_gl_info *gl_info)
 {
     if (!GL_SUPPORT(NV_VERTEX_PROGRAM) /* Need to init colors. */
-            || gl_info->quirks & WINED3D_QUIRK_ARB_VS_OFFSET_LIMIT /* Load the immval offset. */
-            || gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W) /* Have to init texcoords. */
+        || gl_info->quirks & WINED3D_QUIRK_ARB_VS_OFFSET_LIMIT /* Load the immval offset. */
+        || gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W /* Have to init texcoords. */
+        || (!use_nv_clip(gl_info)) /* Init the clip texcoord */)
     {
         return TRUE;
@@ -84,10 +91,4 @@
 {
     return stateblock->lowest_disabled_stage < 7;
-}
-
-/* Returns TRUE if result.clip from GL_NV_vertex_program2 should be used and FALSE otherwise */
-static inline BOOL use_nv_clip(const struct wined3d_gl_info *gl_info)
-{
-    return GL_SUPPORT(NV_VERTEX_PROGRAM2_OPTION);
 }
 
@@ -293,5 +294,5 @@
 {
     local_constant* lconst;
-    DWORD i, j;
+    DWORD i = 0, j;
     unsigned int ret;
 
@@ -308,5 +309,8 @@
     {
         float lcl_const[4];
-        for(i = 0; i < max_constants; i++) {
+        /* ps 1.x supports only 8 constants, clamp only those. When switching between 1.x and higher
+         * shaders, the first 8 constants are marked dirty for reload
+         */
+        for(; i < min(8, max_constants); i++) {
             if(!dirty_consts[i]) continue;
             dirty_consts[i] = 0;
@@ -331,29 +335,37 @@
             GL_EXTCALL(glProgramEnvParameter4fvARB(target_type, i, lcl_const));
         }
+
+        /* If further constants are dirty, reload them without clamping.
+         *
+         * The alternative is not to touch them, but then we cannot reset the dirty constant count
+         * to zero. That's bad for apps that only use PS 1.x shaders, because in that case the code
+         * above would always re-check the first 8 constants since max_constant remains at the init
+         * value
+         */
+    }
+
+    if(GL_SUPPORT(EXT_GPU_PROGRAM_PARAMETERS)) {
+        /* TODO: Benchmark if we're better of with finding the dirty constants ourselves,
+         * or just reloading *all* constants at once
+         *
+        GL_EXTCALL(glProgramEnvParameters4fvEXT(target_type, i, max_constants, constants + (i * 4)));
+         */
+        for(; i < max_constants; i++) {
+            if(!dirty_consts[i]) continue;
+
+            /* Find the next block of dirty constants */
+            dirty_consts[i] = 0;
+            j = i;
+            for(i++; (i < max_constants) && dirty_consts[i]; i++) {
+                dirty_consts[i] = 0;
+            }
+
+            GL_EXTCALL(glProgramEnvParameters4fvEXT(target_type, j, i - j, constants + (j * 4)));
+        }
     } else {
-        if(GL_SUPPORT(EXT_GPU_PROGRAM_PARAMETERS)) {
-            /* TODO: Benchmark if we're better of with finding the dirty constants ourselves,
-             * or just reloading *all* constants at once
-             *
-            GL_EXTCALL(glProgramEnvParameters4fvEXT(target_type, 0, max_constants, constants));
-             */
-            for(i = 0; i < max_constants; i++) {
-                if(!dirty_consts[i]) continue;
-
-                /* Find the next block of dirty constants */
+        for(; i < max_constants; i++) {
+            if(dirty_consts[i]) {
                 dirty_consts[i] = 0;
-                j = i;
-                for(i++; (i < max_constants) && dirty_consts[i]; i++) {
-                    dirty_consts[i] = 0;
-                }
-
-                GL_EXTCALL(glProgramEnvParameters4fvEXT(target_type, j, i - j, constants + (j * 4)));
-            }
-        } else {
-            for(i = 0; i < max_constants; i++) {
-                if(dirty_consts[i]) {
-                    dirty_consts[i] = 0;
-                    GL_EXTCALL(glProgramEnvParameter4fvARB(target_type, i, constants + (i * 4)));
-                }
+                GL_EXTCALL(glProgramEnvParameter4fvARB(target_type, i, constants + (i * 4)));
             }
         }
@@ -437,6 +449,7 @@
 static inline void shader_arb_ps_local_constants(IWineD3DDeviceImpl* deviceImpl)
 {
+    const struct wined3d_context *context = context_get_current();
     IWineD3DStateBlockImpl* stateBlock = deviceImpl->stateBlock;
-    const struct wined3d_gl_info *gl_info = &deviceImpl->adapter->gl_info;
+    const struct wined3d_gl_info *gl_info = context->gl_info;
     unsigned char i;
     struct shader_arb_priv *priv = deviceImpl->shader_priv;
@@ -472,6 +485,7 @@
         */
         float val[4];
-        val[0] = deviceImpl->render_offscreen ? 0.0f : ((IWineD3DSurfaceImpl *) deviceImpl->render_targets[0])->currentDesc.Height;
-        val[1] = deviceImpl->render_offscreen ? 1.0f : -1.0f;
+        val[0] = context->render_offscreen ? 0.0f
+                : ((IWineD3DSurfaceImpl *) deviceImpl->render_targets[0])->currentDesc.Height;
+        val[1] = context->render_offscreen ? 1.0f : -1.0f;
         val[2] = 1.0f;
         val[3] = 0.0f;
@@ -537,12 +551,9 @@
  */
 /* GL locking is done by the caller (state handler) */
-static void shader_arb_load_constants(
-    IWineD3DDevice* device,
-    char usePixelShader,
-    char useVertexShader) {
-   
-    IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) device; 
-    IWineD3DStateBlockImpl* stateBlock = deviceImpl->stateBlock;
-    const struct wined3d_gl_info *gl_info = &deviceImpl->adapter->gl_info;
+static void shader_arb_load_constants(const struct wined3d_context *context, char usePixelShader, char useVertexShader)
+{
+    IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice;
+    IWineD3DStateBlockImpl* stateBlock = device->stateBlock;
+    const struct wined3d_gl_info *gl_info = context->gl_info;
 
     if (useVertexShader) {
@@ -550,11 +561,7 @@
 
         /* Load DirectX 9 float constants for vertex shader */
-        deviceImpl->highest_dirty_vs_const = shader_arb_load_constantsF(
-                vshader, gl_info, GL_VERTEX_PROGRAM_ARB,
-                deviceImpl->highest_dirty_vs_const,
-                stateBlock->vertexShaderConstantF,
-                deviceImpl->activeContext->vshader_const_dirty);
-
-        shader_arb_vs_local_constants(deviceImpl);
+        device->highest_dirty_vs_const = shader_arb_load_constantsF(vshader, gl_info, GL_VERTEX_PROGRAM_ARB,
+                device->highest_dirty_vs_const, stateBlock->vertexShaderConstantF, context->vshader_const_dirty);
+        shader_arb_vs_local_constants(device);
     }
 
@@ -563,10 +570,7 @@
 
         /* Load DirectX 9 float constants for pixel shader */
-        deviceImpl->highest_dirty_ps_const = shader_arb_load_constantsF(
-                pshader, gl_info, GL_FRAGMENT_PROGRAM_ARB,
-                deviceImpl->highest_dirty_ps_const,
-                stateBlock->pixelShaderConstantF,
-                deviceImpl->activeContext->pshader_const_dirty);
-        shader_arb_ps_local_constants(deviceImpl);
+        device->highest_dirty_ps_const = shader_arb_load_constantsF(pshader, gl_info, GL_FRAGMENT_PROGRAM_ARB,
+                device->highest_dirty_ps_const, stateBlock->pixelShaderConstantF, context->pshader_const_dirty);
+        shader_arb_ps_local_constants(device);
     }
 }
@@ -575,9 +579,11 @@
 {
     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
+    struct wined3d_context *context = context_get_current();
 
     /* We don't want shader constant dirtification to be an O(contexts), so just dirtify the active
      * context. On a context switch the old context will be fully dirtified */
-    memset(This->activeContext->vshader_const_dirty + start, 1,
-            sizeof(*This->activeContext->vshader_const_dirty) * count);
+    if (!context || ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice != This) return;
+
+    memset(context->vshader_const_dirty + start, 1, sizeof(*context->vshader_const_dirty) * count);
     This->highest_dirty_vs_const = max(This->highest_dirty_vs_const, start + count);
 }
@@ -586,9 +592,11 @@
 {
     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
+    struct wined3d_context *context = context_get_current();
 
     /* We don't want shader constant dirtification to be an O(contexts), so just dirtify the active
      * context. On a context switch the old context will be fully dirtified */
-    memset(This->activeContext->pshader_const_dirty + start, 1,
-            sizeof(*This->activeContext->pshader_const_dirty) * count);
+    if (!context || ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice != This) return;
+
+    memset(context->pshader_const_dirty + start, 1, sizeof(*context->pshader_const_dirty) * count);
     This->highest_dirty_ps_const = max(This->highest_dirty_ps_const, start + count);
 }
@@ -4223,8 +4231,9 @@
 
 /* GL locking is done by the caller */
-static void shader_arb_select(IWineD3DDevice *iface, BOOL usePS, BOOL useVS) {
-    IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
+static void shader_arb_select(const struct wined3d_context *context, BOOL usePS, BOOL useVS)
+{
+    IWineD3DDeviceImpl *This = ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice;
     struct shader_arb_priv *priv = This->shader_priv;
-    const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
+    const struct wined3d_gl_info *gl_info = context->gl_info;
     int i;
 
@@ -4261,8 +4270,8 @@
             for(i = 0; i < 8; i++)
             {
-                This->activeContext->pshader_const_dirty[i] = 1;
+                context->pshader_const_dirty[i] = 1;
             }
             /* Also takes care of loading local constants */
-            shader_arb_load_constants(iface, TRUE, FALSE);
+            shader_arb_load_constants(context, TRUE, FALSE);
         }
         else
@@ -4272,5 +4281,6 @@
 
         /* Force constant reloading for the NP2 fixup (see comment in shader_glsl_select for more info) */
-        if (compiled->np2fixup_info.super.active) This->shader_backend->shader_load_np2fixup_constants(iface, usePS, useVS);
+        if (compiled->np2fixup_info.super.active)
+            shader_arb_load_np2fixup_constants((IWineD3DDevice *)This, usePS, useVS);
     } else if(GL_SUPPORT(ARB_FRAGMENT_PROGRAM) && !priv->use_arbfp_fixed_func) {
         /* Disable only if we're not using arbfp fixed function fragment processing. If this is used,
@@ -4369,6 +4379,4 @@
     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
 
-    ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
-
     if (shader_is_pshader_version(baseShader->baseShader.reg_maps.shader_version.type))
     {
@@ -4379,4 +4387,7 @@
         if(!shader_data) return; /* This can happen if a shader was never compiled */
         ENTER_GL();
+
+        if(shader_data->num_gl_shaders) ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
+
         for(i = 0; i < shader_data->num_gl_shaders; i++) {
             GL_EXTCALL(glDeleteProgramsARB(1, &shader_data->gl_shaders[i].prgId));
@@ -4394,4 +4405,7 @@
         if(!shader_data) return; /* This can happen if a shader was never compiled */
         ENTER_GL();
+
+        if(shader_data->num_gl_shaders) ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
+
         for(i = 0; i < shader_data->num_gl_shaders; i++) {
             GL_EXTCALL(glDeleteProgramsARB(1, &shader_data->gl_shaders[i].prgId));
@@ -5167,5 +5181,6 @@
 
 #define GLINFO_LOCATION stateblock->wineD3DDevice->adapter->gl_info
-static void state_texfactor_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_texfactor_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     float col[4];
     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
@@ -5178,5 +5193,5 @@
 
         device = stateblock->wineD3DDevice;
-        device->activeContext->pshader_const_dirty[ARB_FFP_CONST_TFACTOR] = 1;
+        context->pshader_const_dirty[ARB_FFP_CONST_TFACTOR] = 1;
         device->highest_dirty_ps_const = max(device->highest_dirty_ps_const, ARB_FFP_CONST_TFACTOR + 1);
     }
@@ -5188,5 +5203,6 @@
 }
 
-static void state_arb_specularenable(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_arb_specularenable(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     float col[4];
     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
@@ -5199,5 +5215,5 @@
 
         device = stateblock->wineD3DDevice;
-        device->activeContext->pshader_const_dirty[ARB_FFP_CONST_SPECULAR_ENABLE] = 1;
+        context->pshader_const_dirty[ARB_FFP_CONST_SPECULAR_ENABLE] = 1;
         device->highest_dirty_ps_const = max(device->highest_dirty_ps_const, ARB_FFP_CONST_SPECULAR_ENABLE + 1);
     }
@@ -5215,5 +5231,6 @@
 }
 
-static void set_bumpmat_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void set_bumpmat_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     DWORD stage = (state - STATE_TEXTURESTAGE(0, 0)) / (WINED3D_HIGHEST_TEXTURE_STATE + 1);
     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
@@ -5237,5 +5254,5 @@
         }
     } else if(device->shader_backend == &arb_program_shader_backend) {
-        device->activeContext->pshader_const_dirty[ARB_FFP_CONST_BUMPMAT(stage)] = 1;
+        context->pshader_const_dirty[ARB_FFP_CONST_BUMPMAT(stage)] = 1;
         device->highest_dirty_ps_const = max(device->highest_dirty_ps_const, ARB_FFP_CONST_BUMPMAT(stage) + 1);
     }
@@ -5250,5 +5267,6 @@
 }
 
-static void tex_bumpenvlum_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void tex_bumpenvlum_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     DWORD stage = (state - STATE_TEXTURESTAGE(0, 0)) / (WINED3D_HIGHEST_TEXTURE_STATE + 1);
     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
@@ -5272,5 +5290,5 @@
         }
     } else if(device->shader_backend == &arb_program_shader_backend) {
-        device->activeContext->pshader_const_dirty[ARB_FFP_CONST_LUMINANCE(stage)] = 1;
+        context->pshader_const_dirty[ARB_FFP_CONST_LUMINANCE(stage)] = 1;
         device->highest_dirty_ps_const = max(device->highest_dirty_ps_const, ARB_FFP_CONST_LUMINANCE(stage) + 1);
     }
@@ -5757,5 +5775,6 @@
 }
 
-static void fragment_prog_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void fragment_prog_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
     struct shader_arb_priv *priv = device->fragment_priv;
@@ -5777,5 +5796,5 @@
             state_arb_specularenable(STATE_RENDER(WINED3DRS_SPECULARENABLE), stateblock, context);
         } else if(use_pshader && !isStateDirty(context, device->StateTable[STATE_VSHADER].representative)) {
-            device->shader_backend->shader_select((IWineD3DDevice *)stateblock->wineD3DDevice, use_pshader, use_vshader);
+            device->shader_backend->shader_select(context, use_pshader, use_vshader);
         }
         return;
@@ -5793,5 +5812,4 @@
                 return;
             }
-
             new_desc->num_textures_used = 0;
             for(i = 0; i < GL_LIMITS(texture_stages); i++) {
@@ -5838,5 +5856,5 @@
      */
     if(!isStateDirty(context, device->StateTable[STATE_VSHADER].representative)) {
-        device->shader_backend->shader_select((IWineD3DDevice *)stateblock->wineD3DDevice, use_pshader, use_vshader);
+        device->shader_backend->shader_select(context, use_pshader, use_vshader);
 
         if (!isStateDirty(context, STATE_VERTEXSHADERCONSTANT) && (use_vshader || use_pshader)) {
@@ -5855,5 +5873,6 @@
  * fragment_prog_arbfp function being called because FOGENABLE is dirty, which calls this function here
  */
-static void state_arbfp_fog(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_arbfp_fog(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     enum fogsource new_source;
 
@@ -5885,5 +5904,6 @@
 }
 
-static void textransform(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void textransform(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(!isStateDirty(context, STATE_PIXELSHADER)) {
         fragment_prog_arbfp(state, stateblock, context);
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/ati_fragment_shader.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/ati_fragment_shader.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/ati_fragment_shader.c	(revision 22496)
@@ -806,5 +806,6 @@
 
 #define GLINFO_LOCATION stateblock->wineD3DDevice->adapter->gl_info
-static void set_tex_op_atifs(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void set_tex_op_atifs(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     IWineD3DDeviceImpl          *This = stateblock->wineD3DDevice;
     const struct atifs_ffp_desc *desc;
@@ -852,5 +853,6 @@
 }
 
-static void state_texfactor_atifs(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_texfactor_atifs(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     float col[4];
     D3DCOLORTOGLFLOAT4(stateblock->renderState[WINED3DRS_TEXTUREFACTOR], col);
@@ -860,5 +862,6 @@
 }
 
-static void set_bumpmat(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void set_bumpmat(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     DWORD stage = (state - STATE_TEXTURESTAGE(0, 0)) / (WINED3D_HIGHEST_TEXTURE_STATE + 1);
     float mat[2][2];
@@ -883,5 +886,6 @@
 }
 
-static void textransform(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void textransform(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(!isStateDirty(context, STATE_PIXELSHADER)) {
         set_tex_op_atifs(state, stateblock, context);
@@ -889,5 +893,6 @@
 }
 
-static void atifs_apply_pixelshader(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void atifs_apply_pixelshader(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
     BOOL use_vshader = use_vs(stateblock);
@@ -906,5 +911,5 @@
      */
     if(!isStateDirty(context, device->StateTable[STATE_VSHADER].representative)) {
-        device->shader_backend->shader_select((IWineD3DDevice *)stateblock->wineD3DDevice, FALSE, use_vshader);
+        device->shader_backend->shader_select(context, FALSE, use_vshader);
 
         if (!isStateDirty(context, STATE_VERTEXSHADERCONSTANT) && use_vshader) {
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/baseshader.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/baseshader.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/baseshader.c	(revision 22496)
@@ -1377,10 +1377,10 @@
 
 static void shader_none_handle_instruction(const struct wined3d_shader_instruction *ins) {}
-static void shader_none_select(IWineD3DDevice *iface, BOOL usePS, BOOL useVS) {}
+static void shader_none_select(const struct wined3d_context *context, BOOL usePS, BOOL useVS) {}
 static void shader_none_select_depth_blt(IWineD3DDevice *iface, enum tex_types tex_type) {}
 static void shader_none_deselect_depth_blt(IWineD3DDevice *iface) {}
 static void shader_none_update_float_vertex_constants(IWineD3DDevice *iface, UINT start, UINT count) {}
 static void shader_none_update_float_pixel_constants(IWineD3DDevice *iface, UINT start, UINT count) {}
-static void shader_none_load_constants(IWineD3DDevice *iface, char usePS, char useVS) {}
+static void shader_none_load_constants(const struct wined3d_context *context, char usePS, char useVS) {}
 static void shader_none_load_np2fixup_constants(IWineD3DDevice *iface, char usePS, char useVS) {}
 static void shader_none_destroy(IWineD3DBaseShader *iface) {}
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/basetexture.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/basetexture.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/basetexture.c	(revision 22496)
@@ -58,4 +58,15 @@
     texture->baseTexture.pow2Matrix_identity = TRUE;
 
+    if (texture->resource.format_desc->Flags & WINED3DFMT_FLAG_FILTERING)
+    {
+        texture->baseTexture.minMipLookup = minMipLookup;
+        texture->baseTexture.magLookup = magLookup;
+    }
+    else
+    {
+        texture->baseTexture.minMipLookup = minMipLookup_noFilter;
+        texture->baseTexture.magLookup = magLookup_noFilter;
+    }
+
     return WINED3D_OK;
 }
@@ -73,5 +84,5 @@
 
     if(This->baseTexture.textureName) {
-        ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+        ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
         ENTER_GL();
         glDeleteTextures(1, &This->baseTexture.textureName);
@@ -81,5 +92,5 @@
 
     if(This->baseTexture.srgbTextureName) {
-        ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+        ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
         ENTER_GL();
         glDeleteTextures(1, &This->baseTexture.srgbTextureName);
@@ -145,5 +156,5 @@
        * immediately.
        */
-      ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+      ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
       ENTER_GL();
       glBindTexture(textureDimensions, This->baseTexture.textureName);
@@ -175,10 +186,9 @@
 WINED3DTEXTUREFILTERTYPE basetexture_get_autogen_filter_type(IWineD3DBaseTexture *iface)
 {
-  IWineD3DBaseTextureImpl *This = (IWineD3DBaseTextureImpl *)iface;
-  FIXME("(%p) : stub\n", This);
-  if (!(This->resource.usage & WINED3DUSAGE_AUTOGENMIPMAP)) {
-     return WINED3DTEXF_NONE;
-  }
-  return This->baseTexture.filterType;
+    IWineD3DBaseTextureImpl *This = (IWineD3DBaseTextureImpl *)iface;
+
+    FIXME("(%p) : stub\n", This);
+
+    return This->baseTexture.filterType;
 }
 
@@ -252,5 +262,5 @@
         states[WINED3DTEXSTA_MIPFILTER]     = WINED3DTEXF_LINEAR; /* GL_NEAREST_MIPMAP_LINEAR */
         states[WINED3DTEXSTA_MAXMIPLEVEL]   = 0;
-        states[WINED3DTEXSTA_MAXANISOTROPY] = 0;
+        states[WINED3DTEXSTA_MAXANISOTROPY] = 1;
         states[WINED3DTEXSTA_SRGBTEXTURE]   = 0;
         states[WINED3DTEXSTA_ELEMENTINDEX]  = 0;
@@ -341,4 +351,5 @@
     GLint textureDimensions = IWineD3DBaseTexture_GetTextureDimensions(iface);
     BOOL cond_np2 = IWineD3DBaseTexture_IsCondNP2(iface);
+    DWORD aniso;
 
     TRACE("iface %p, textureStates %p, samplerStates %p\n", iface, textureStates, samplerStates);
@@ -386,15 +397,12 @@
         if (state > WINED3DTEXF_ANISOTROPIC) {
             FIXME("Unrecognized or unsupported MAGFILTER* value %d\n", state);
-        } else {
-            glValue = This->baseTexture.magLookup[state - WINED3DTEXF_NONE];
-            TRACE("ValueMAG=%d setting MAGFILTER to %x\n", state, glValue);
-            glTexParameteri(textureDimensions, GL_TEXTURE_MAG_FILTER, glValue);
-            /* We need to reset the Anisotropic filtering state when we change the mag filter to WINED3DTEXF_ANISOTROPIC (this seems a bit weird, check the documentation to see how it should be switched off. */
-            if (GL_SUPPORT(EXT_TEXTURE_FILTER_ANISOTROPIC) && WINED3DTEXF_ANISOTROPIC == state &&
-                !cond_np2) {
-                glTexParameteri(textureDimensions, GL_TEXTURE_MAX_ANISOTROPY_EXT, samplerStates[WINED3DSAMP_MAXANISOTROPY]);
-            }
-            states[WINED3DTEXSTA_MAGFILTER] = state;
-        }
+        }
+
+        glValue = wined3d_gl_mag_filter(This->baseTexture.magLookup,
+                min(max(state, WINED3DTEXF_POINT), WINED3DTEXF_LINEAR));
+        TRACE("ValueMAG=%d setting MAGFILTER to %x\n", state, glValue);
+        glTexParameteri(textureDimensions, GL_TEXTURE_MAG_FILTER, glValue);
+
+        states[WINED3DTEXSTA_MAGFILTER] = state;
     }
 
@@ -408,6 +416,6 @@
         states[WINED3DTEXSTA_MAXMIPLEVEL] = samplerStates[WINED3DSAMP_MAXMIPLEVEL];
 
-        if (states[WINED3DTEXSTA_MINFILTER] > WINED3DTEXF_ANISOTROPIC ||
-            states[WINED3DTEXSTA_MIPFILTER] > WINED3DTEXF_LINEAR)
+        if (states[WINED3DTEXSTA_MINFILTER] > WINED3DTEXF_ANISOTROPIC
+                || states[WINED3DTEXSTA_MIPFILTER] > WINED3DTEXF_ANISOTROPIC)
         {
 
@@ -416,7 +424,7 @@
                   states[WINED3DTEXSTA_MIPFILTER]);
         }
-        glValue = This->baseTexture.minMipLookup
-                [min(max(samplerStates[WINED3DSAMP_MINFILTER],WINED3DTEXF_NONE), WINED3DTEXF_ANISOTROPIC)]
-                .mip[min(max(samplerStates[WINED3DSAMP_MIPFILTER],WINED3DTEXF_NONE), WINED3DTEXF_LINEAR)];
+        glValue = wined3d_gl_min_mip_filter(This->baseTexture.minMipLookup,
+                min(max(samplerStates[WINED3DSAMP_MINFILTER], WINED3DTEXF_POINT), WINED3DTEXF_LINEAR),
+                min(max(samplerStates[WINED3DSAMP_MIPFILTER], WINED3DTEXF_NONE), WINED3DTEXF_LINEAR));
 
         TRACE("ValueMIN=%d, ValueMIP=%d, setting MINFILTER to %x\n",
@@ -438,12 +446,28 @@
     }
 
-    if(samplerStates[WINED3DSAMP_MAXANISOTROPY] != states[WINED3DTEXSTA_MAXANISOTROPY]) {
-        if (GL_SUPPORT(EXT_TEXTURE_FILTER_ANISOTROPIC) && !cond_np2) {
-            glTexParameteri(textureDimensions, GL_TEXTURE_MAX_ANISOTROPY_EXT, samplerStates[WINED3DSAMP_MAXANISOTROPY]);
-            checkGLcall("glTexParameteri GL_TEXTURE_MAX_ANISOTROPY_EXT ...");
-        } else {
-            WARN("Unsupported in local OpenGL implementation: glTexParameteri GL_TEXTURE_MAX_ANISOTROPY_EXT\n");
-        }
-        states[WINED3DTEXSTA_MAXANISOTROPY] = samplerStates[WINED3DSAMP_MAXANISOTROPY];
-    }
-}
+    if ((states[WINED3DSAMP_MAGFILTER] != WINED3DTEXF_ANISOTROPIC
+            && states[WINED3DSAMP_MINFILTER] != WINED3DTEXF_ANISOTROPIC
+            && states[WINED3DSAMP_MIPFILTER] != WINED3DTEXF_ANISOTROPIC)
+            || cond_np2)
+    {
+        aniso = 1;
+    }
+    else
+    {
+        aniso = samplerStates[WINED3DSAMP_MAXANISOTROPY];
+    }
+
+    if (states[WINED3DTEXSTA_MAXANISOTROPY] != aniso)
+    {
+        if (GL_SUPPORT(EXT_TEXTURE_FILTER_ANISOTROPIC))
+        {
+            glTexParameteri(textureDimensions, GL_TEXTURE_MAX_ANISOTROPY_EXT, aniso);
+            checkGLcall("glTexParameteri(GL_TEXTURE_MAX_ANISOTROPY_EXT, aniso)");
+        }
+        else
+        {
+            WARN("Anisotropic filtering not supported.\n");
+        }
+        states[WINED3DTEXSTA_MAXANISOTROPY] = aniso;
+    }
+}
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/buffer.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/buffer.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/buffer.c	(revision 22496)
@@ -613,5 +613,5 @@
         IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
 
-        ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+        ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
 
         /* Download the buffer, but don't permanently enable double buffering */
@@ -700,5 +700,5 @@
     TRACE("iface %p\n", iface);
 
-    ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+    ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
 
     if (!This->buffer_object)
@@ -810,5 +810,5 @@
         if (!device->isInDraw)
         {
-            ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+            ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
         }
         ENTER_GL();
@@ -960,5 +960,5 @@
             }
 
-            ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+            ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
             ENTER_GL();
             GL_EXTCALL(glBindBufferARB(This->buffer_type_hint, This->buffer_object));
@@ -1012,5 +1012,5 @@
         }
 
-        ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+        ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
         ENTER_GL();
         GL_EXTCALL(glBindBufferARB(This->buffer_type_hint, This->buffer_object));
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/context.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/context.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/context.c	(revision 22496)
@@ -3,4 +3,5 @@
  *
  * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
+ * Copyright 2009 Henri Verbeet for CodeWeavers
  *
  * This library is free software; you can redistribute it and/or
@@ -18,5 +19,4 @@
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
  */
-
 /*
  * Sun LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
@@ -28,4 +28,5 @@
  */
 
+
 #include "config.h"
 #include <stdio.h>
@@ -39,20 +40,10 @@
 #define GLINFO_LOCATION (*gl_info)
 
-/* The last used device.
- *
- * If the application creates multiple devices and switches between them, ActivateContext has to
- * change the opengl context. This flag allows to keep track which device is active
- */
-static IWineD3DDeviceImpl *last_device;
-
-void context_set_last_device(IWineD3DDeviceImpl *device)
-{
-    last_device = device;
-}
+static DWORD wined3d_context_tls_idx;
 
 /* FBO helper functions */
 
 /* GL locking is done by the caller */
-void context_bind_fbo(struct WineD3DContext *context, GLenum target, GLuint *fbo)
+void context_bind_fbo(struct wined3d_context *context, GLenum target, GLuint *fbo)
 {
     const struct wined3d_gl_info *gl_info = context->gl_info;
@@ -120,5 +111,5 @@
 
 /* GL locking is done by the caller */
-static void context_destroy_fbo(struct WineD3DContext *context, GLuint *fbo)
+static void context_destroy_fbo(struct wined3d_context *context, GLuint *fbo)
 {
     const struct wined3d_gl_info *gl_info = context->gl_info;
@@ -197,5 +188,5 @@
 
 /* GL locking is done by the caller */
-void context_attach_depth_stencil_fbo(struct WineD3DContext *context,
+void context_attach_depth_stencil_fbo(struct wined3d_context *context,
         GLenum fbo_target, IWineD3DSurface *depth_stencil, BOOL use_render_buffer)
 {
@@ -269,5 +260,5 @@
 
 /* GL locking is done by the caller */
-void context_attach_surface_fbo(const struct WineD3DContext *context,
+void context_attach_surface_fbo(const struct wined3d_context *context,
         GLenum fbo_target, DWORD idx, IWineD3DSurface *surface)
 {
@@ -291,5 +282,5 @@
 
 /* GL locking is done by the caller */
-static void context_check_fbo_status(struct WineD3DContext *context)
+static void context_check_fbo_status(struct wined3d_context *context)
 {
     const struct wined3d_gl_info *gl_info = context->gl_info;
@@ -304,4 +295,5 @@
         unsigned int i;
         FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
+
 
         if (context->current_fbo)
@@ -316,4 +308,5 @@
                             i, attachment, debug_d3dformat(attachment->resource.format_desc->format),
                             attachment->pow2Width, attachment->pow2Height);
+        
                 }
             }
@@ -329,5 +322,5 @@
 }
 
-static struct fbo_entry *context_create_fbo_entry(struct WineD3DContext *context)
+static struct fbo_entry *context_create_fbo_entry(struct wined3d_context *context)
 {
     IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice;
@@ -346,5 +339,5 @@
 
 /* GL locking is done by the caller */
-static void context_reuse_fbo_entry(struct WineD3DContext *context, struct fbo_entry *entry)
+static void context_reuse_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
 {
     IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice;
@@ -360,5 +353,5 @@
 
 /* GL locking is done by the caller */
-static void context_destroy_fbo_entry(struct WineD3DContext *context, struct fbo_entry *entry)
+static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
 {
     if (entry->id)
@@ -375,5 +368,5 @@
 
 /* GL locking is done by the caller */
-static struct fbo_entry *context_find_fbo_entry(struct WineD3DContext *context)
+static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context)
 {
     IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice;
@@ -410,5 +403,5 @@
 
 /* GL locking is done by the caller */
-static void context_apply_fbo_entry(struct WineD3DContext *context, struct fbo_entry *entry)
+static void context_apply_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
 {
     IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice;
@@ -458,9 +451,7 @@
 
 /* GL locking is done by the caller */
-static void context_apply_fbo_state(struct WineD3DContext *context)
-{
-    IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice;
-
-    if (device->render_offscreen)
+static void context_apply_fbo_state(struct wined3d_context *context)
+{
+    if (context->render_offscreen)
     {
         context->current_fbo = context_find_fbo_entry(context);
@@ -474,4 +465,127 @@
 }
 
+/* Context activation is done by the caller. */
+void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
+{
+    const struct wined3d_gl_info *gl_info = context->gl_info;
+
+    if (context->free_occlusion_query_count)
+    {
+        query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
+    }
+    else
+    {
+        if (GL_SUPPORT(ARB_OCCLUSION_QUERY))
+        {
+            ENTER_GL();
+            GL_EXTCALL(glGenQueriesARB(1, &query->id));
+            checkGLcall("glGenQueriesARB");
+            LEAVE_GL();
+
+            TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
+        }
+        else
+        {
+            WARN("Occlusion queries not supported, not allocating query id.\n");
+            query->id = 0;
+        }
+    }
+
+    query->context = context;
+    list_add_head(&context->occlusion_queries, &query->entry);
+}
+
+void context_free_occlusion_query(struct wined3d_occlusion_query *query)
+{
+    struct wined3d_context *context = query->context;
+
+    list_remove(&query->entry);
+    query->context = NULL;
+
+    if (context->free_occlusion_query_count >= context->free_occlusion_query_size - 1)
+    {
+        UINT new_size = context->free_occlusion_query_size << 1;
+        GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_occlusion_queries,
+                new_size * sizeof(*context->free_occlusion_queries));
+
+        if (!new_data)
+        {
+            ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
+            return;
+        }
+
+        context->free_occlusion_query_size = new_size;
+        context->free_occlusion_queries = new_data;
+    }
+
+    context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
+}
+
+/* Context activation is done by the caller. */
+void context_alloc_event_query(struct wined3d_context *context, struct wined3d_event_query *query)
+{
+    const struct wined3d_gl_info *gl_info = context->gl_info;
+
+    if (context->free_event_query_count)
+    {
+        query->id = context->free_event_queries[--context->free_event_query_count];
+    }
+    else
+    {
+        if (GL_SUPPORT(APPLE_FENCE))
+        {
+            ENTER_GL();
+            GL_EXTCALL(glGenFencesAPPLE(1, &query->id));
+            checkGLcall("glGenFencesAPPLE");
+            LEAVE_GL();
+
+            TRACE("Allocated event query %u in context %p.\n", query->id, context);
+        }
+        else if(GL_SUPPORT(NV_FENCE))
+        {
+            ENTER_GL();
+            GL_EXTCALL(glGenFencesNV(1, &query->id));
+            checkGLcall("glGenFencesNV");
+            LEAVE_GL();
+
+            TRACE("Allocated event query %u in context %p.\n", query->id, context);
+        }
+        else
+        {
+            WARN("Event queries not supported, not allocating query id.\n");
+            query->id = 0;
+        }
+    }
+
+    query->context = context;
+    list_add_head(&context->event_queries, &query->entry);
+}
+
+void context_free_event_query(struct wined3d_event_query *query)
+{
+    struct wined3d_context *context = query->context;
+
+    list_remove(&query->entry);
+    query->context = NULL;
+
+    if (context->free_event_query_count >= context->free_event_query_size - 1)
+    {
+        UINT new_size = context->free_event_query_size << 1;
+        GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_event_queries,
+                new_size * sizeof(*context->free_event_queries));
+
+        if (!new_data)
+        {
+            ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
+            return;
+        }
+
+        context->free_event_query_size = new_size;
+        context->free_event_queries = new_data;
+    }
+
+    context->free_event_queries[context->free_event_query_count++] = query->id;
+}
+
 void context_resource_released(IWineD3DDevice *iface, IWineD3DResource *resource, WINED3DRESOURCETYPE type)
 {
@@ -479,64 +593,19 @@
     UINT i;
 
+    if (!This->d3d_initialized) return;
+
     switch(type)
     {
         case WINED3DRTYPE_SURFACE:
         {
-            if ((IWineD3DSurface *)resource == This->lastActiveRenderTarget)
-            {
-                IWineD3DSwapChainImpl *swapchain;
-
-                TRACE("Last active render target destroyed.\n");
-
-                /* Find a replacement surface for the currently active back
-                 * buffer. The context manager does not do NULL checks, so
-                 * switch to a valid target as long as the currently set
-                 * surface is still valid. Use the surface of the implicit
-                 * swpchain. If that is the same as the destroyed surface the
-                 * device is destroyed and the lastActiveRenderTarget member
-                 * shouldn't matter. */
-                swapchain = This->swapchains ? (IWineD3DSwapChainImpl *)This->swapchains[0] : NULL;
-                if (swapchain)
-                {
-                    if (swapchain->backBuffer && swapchain->backBuffer[0] != (IWineD3DSurface *)resource)
-                    {
-                        TRACE("Activating primary back buffer.\n");
-                        ActivateContext(This, swapchain->backBuffer[0], CTXUSAGE_RESOURCELOAD);
-                    }
-                    else if (!swapchain->backBuffer && swapchain->frontBuffer != (IWineD3DSurface *)resource)
-                    {
-                        /* Single buffering environment */
-                        TRACE("Activating primary front buffer.\n");
-
-                        ActivateContext(This, swapchain->frontBuffer, CTXUSAGE_RESOURCELOAD);
-                    }
-                    else
-                    {
-                        /* Implicit render target destroyed, that means the
-                         * device is being destroyed whatever we set here, it
-                         * shouldn't matter. */
-                        TRACE("Device is being destroyed, setting lastActiveRenderTarget to 0xdeadbabe.\n");
-
-                        This->lastActiveRenderTarget = (IWineD3DSurface *) 0xdeadbabe;
-                    }
-                }
-                else
-                {
-                    WARN("Render target set, but swapchain does not exist!\n");
-
-                    /* May happen during ddraw uninitialization. */
-                    This->lastActiveRenderTarget = (IWineD3DSurface *)0xdeadcafe;
-                }
-            }
-            else if (This->d3d_initialized)
-            {
-                ActivateContext(This, This->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
-            }
+            ActivateContext(This, NULL, CTXUSAGE_RESOURCELOAD);
 
             for (i = 0; i < This->numContexts; ++i)
             {
-                WineD3DContext *context = This->contexts[i];
+                struct wined3d_context *context = This->contexts[i];
                 const struct wined3d_gl_info *gl_info = context->gl_info;
                 struct fbo_entry *entry, *entry2;
+
+                if (context->current_rt == (IWineD3DSurface *)resource) context->current_rt = NULL;
 
                 ENTER_GL();
@@ -571,4 +640,153 @@
 }
 
+static void context_destroy_gl_resources(struct wined3d_context *context)
+{
+    const struct wined3d_gl_info *gl_info = context->gl_info;
+    struct wined3d_occlusion_query *occlusion_query;
+    struct wined3d_event_query *event_query;
+    struct fbo_entry *entry, *entry2;
+    BOOL has_glctx;
+
+    has_glctx = pwglMakeCurrent(context->hdc, context->glCtx);
+    if (!has_glctx) WARN("Failed to activate context. Window already destroyed?\n");
+
+    ENTER_GL();
+
+    LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
+    {
+        if (has_glctx && GL_SUPPORT(ARB_OCCLUSION_QUERY)) GL_EXTCALL(glDeleteQueriesARB(1, &occlusion_query->id));
+        occlusion_query->context = NULL;
+    }
+
+    LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
+    {
+        if (has_glctx)
+        {
+            if (GL_SUPPORT(APPLE_FENCE)) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->id));
+            else if (GL_SUPPORT(NV_FENCE)) GL_EXTCALL(glDeleteFencesNV(1, &event_query->id));
+        }
+        event_query->context = NULL;
+    }
+
+    LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry) {
+        if (!has_glctx) entry->id = 0;
+        context_destroy_fbo_entry(context, entry);
+    }
+    if (has_glctx)
+    {
+        if (context->src_fbo)
+        {
+            TRACE("Destroy src FBO %d\n", context->src_fbo);
+            context_destroy_fbo(context, &context->src_fbo);
+        }
+        if (context->dst_fbo)
+        {
+            TRACE("Destroy dst FBO %d\n", context->dst_fbo);
+            context_destroy_fbo(context, &context->dst_fbo);
+        }
+        if (context->dummy_arbfp_prog)
+        {
+            GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
+        }
+
+        GL_EXTCALL(glDeleteQueriesARB(context->free_occlusion_query_count, context->free_occlusion_queries));
+
+        if (GL_SUPPORT(APPLE_FENCE))
+            GL_EXTCALL(glDeleteFencesAPPLE(context->free_event_query_count, context->free_event_queries));
+        else if (GL_SUPPORT(NV_FENCE))
+            GL_EXTCALL(glDeleteFencesNV(context->free_event_query_count, context->free_event_queries));
+
+        checkGLcall("context cleanup");
+    }
+
+    LEAVE_GL();
+
+    HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
+    HeapFree(GetProcessHeap(), 0, context->free_event_queries);
+
+    if (!pwglMakeCurrent(NULL, NULL))
+    {
+        ERR("Failed to disable GL context.\n");
+    }
+
+    if (context->isPBuffer)
+    {
+        GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
+        GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
+    }
+    else
+    {
+        ReleaseDC(context->win_handle, context->hdc);
+    }
+
+    if (!pwglDeleteContext(context->glCtx))
+    {
+        DWORD err = GetLastError();
+        ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
+    }
+}
+
+DWORD context_get_tls_idx(void)
+{
+    return wined3d_context_tls_idx;
+}
+
+void context_set_tls_idx(DWORD idx)
+{
+    wined3d_context_tls_idx = idx;
+}
+
+struct wined3d_context *context_get_current(void)
+{
+    return TlsGetValue(wined3d_context_tls_idx);
+}
+
+BOOL context_set_current(struct wined3d_context *ctx)
+{
+    struct wined3d_context *old = context_get_current();
+
+    if (old == ctx)
+    {
+        TRACE("Already using D3D context %p.\n", ctx);
+        return TRUE;
+    }
+
+    if (old)
+    {
+        if (old->destroyed)
+        {
+            TRACE("Switching away from destroyed context %p.\n", old);
+            context_destroy_gl_resources(old);
+            HeapFree(GetProcessHeap(), 0, old);
+        }
+        else
+        {
+            old->current = 0;
+        }
+    }
+
+    if (ctx)
+    {
+        TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
+        if (!pwglMakeCurrent(ctx->hdc, ctx->glCtx))
+        {
+            ERR("Failed to make GL context %p current on device context %p.\n", ctx->glCtx, ctx->hdc);
+            return FALSE;
+        }
+        ctx->current = 1;
+    }
+    else
+    {
+        TRACE("Clearing current D3D context.\n");
+        if (!pwglMakeCurrent(NULL, NULL))
+        {
+            ERR("Failed to clear current GL context.\n");
+            return FALSE;
+        }
+    }
+
+    return TlsSetValue(wined3d_context_tls_idx, ctx);
+}
+
 /*****************************************************************************
  * Context_MarkStateDirty
@@ -584,5 +802,6 @@
  *
  *****************************************************************************/
-static void Context_MarkStateDirty(WineD3DContext *context, DWORD state, const struct StateEntry *StateTable) {
+static void Context_MarkStateDirty(struct wined3d_context *context, DWORD state, const struct StateEntry *StateTable)
+{
     DWORD rep = StateTable[state].representative;
     DWORD idx;
@@ -613,6 +832,8 @@
  *
  *****************************************************************************/
-static WineD3DContext *AddContextToArray(IWineD3DDeviceImpl *This, HWND win_handle, HDC hdc, HGLRC glCtx, HPBUFFERARB pbuffer) {
-    WineD3DContext **oldArray = This->contexts;
+static struct wined3d_context *AddContextToArray(IWineD3DDeviceImpl *This,
+        HWND win_handle, HDC hdc, HGLRC glCtx, HPBUFFERARB pbuffer)
+{
+    struct wined3d_context **oldArray = This->contexts;
     DWORD state;
 
@@ -627,5 +848,5 @@
     }
 
-    This->contexts[This->numContexts] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WineD3DContext));
+    This->contexts[This->numContexts] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(**This->contexts));
     if(This->contexts[This->numContexts] == NULL) {
         ERR("Unable to allocate a new context\n");
@@ -843,8 +1064,10 @@
  *
  *****************************************************************************/
-WineD3DContext *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, HWND win_handle, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms) {
+struct wined3d_context *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target,
+        HWND win_handle, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms)
+{
     const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
+    struct wined3d_context *ret = NULL;
     HPBUFFERARB pbuffer = NULL;
-    WineD3DContext *ret = NULL;
     unsigned int s;
     HGLRC ctx;
@@ -965,5 +1188,5 @@
         if(!iPixelFormat) {
             ERR("Can't find a suitable iPixelFormat\n");
-            return FALSE;
+            return NULL;
         }
 
@@ -984,5 +1207,5 @@
                 if(!res) {
                     ERR("wglSetPixelFormatWINE failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
-                    return FALSE;
+                    return NULL;
                 }
             } else if(oldPixelFormat) {
@@ -992,5 +1215,5 @@
             } else {
                 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
-                return FALSE;
+                return NULL;
             }
         }
@@ -1032,4 +1255,5 @@
     ret->gl_info = &This->adapter->gl_info;
     ret->surface = (IWineD3DSurface *) target;
+    ret->current_rt = (IWineD3DSurface *)target;
     ret->isPBuffer = create_pbuffer;
     ret->tid = GetCurrentThreadId();
@@ -1046,4 +1270,18 @@
     }
 
+    ret->free_occlusion_query_size = 4;
+    ret->free_occlusion_queries = HeapAlloc(GetProcessHeap(), 0,
+            ret->free_occlusion_query_size * sizeof(*ret->free_occlusion_queries));
+    if (!ret->free_occlusion_queries) goto out;
+
+    list_init(&ret->occlusion_queries);
+
+    ret->free_event_query_size = 4;
+    ret->free_event_queries = HeapAlloc(GetProcessHeap(), 0,
+            ret->free_event_query_size * sizeof(*ret->free_event_queries));
+    if (!ret->free_event_queries) goto out;
+
+    list_init(&ret->event_queries);
+
     TRACE("Successfully created new context %p\n", ret);
 
@@ -1051,5 +1289,6 @@
 
     /* Set up the context defaults */
-    if(pwglMakeCurrent(hdc, ctx) == FALSE) {
+    if (!context_set_current(ret))
+    {
         ERR("Cannot activate context to set up defaults\n");
         goto out;
@@ -1135,5 +1374,4 @@
     LEAVE_GL();
 
-    context_set_last_device(This);
     This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
 
@@ -1141,4 +1379,12 @@
 
 out:
+    if (ret)
+    {
+        HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
+        HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
+        HeapFree(GetProcessHeap(), 0, ret->pshader_const_dirty);
+        HeapFree(GetProcessHeap(), 0, ret->vshader_const_dirty);
+        HeapFree(GetProcessHeap(), 0, ret);
+    }
     return NULL;
 }
@@ -1158,6 +1404,7 @@
  *
  *****************************************************************************/
-static void RemoveContextFromArray(IWineD3DDeviceImpl *This, WineD3DContext *context) {
-    WineD3DContext **new_array;
+static void RemoveContextFromArray(IWineD3DDeviceImpl *This, struct wined3d_context *context)
+{
+    struct wined3d_context **new_array;
     BOOL found = FALSE;
     UINT i;
@@ -1169,5 +1416,4 @@
         if (This->contexts[i] == context)
         {
-            HeapFree(GetProcessHeap(), 0, context);
             found = TRUE;
             break;
@@ -1215,64 +1461,30 @@
  *
  *****************************************************************************/
-void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context) {
-    const struct wined3d_gl_info *gl_info = context->gl_info;
-    struct fbo_entry *entry, *entry2;
-    BOOL has_glctx;
+void DestroyContext(IWineD3DDeviceImpl *This, struct wined3d_context *context)
+{
+    BOOL destroy;
 
     TRACE("Destroying ctx %p\n", context);
 
-    /* The correct GL context needs to be active to cleanup the GL resources below */
-    has_glctx = pwglMakeCurrent(context->hdc, context->glCtx);
-    context_set_last_device(NULL);
-
-    if (!has_glctx) WARN("Failed to activate context. Window already destroyed?\n");
-
-    ENTER_GL();
-
-    LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry) {
-        if (!has_glctx) entry->id = 0;
-        context_destroy_fbo_entry(context, entry);
-    }
-    if (has_glctx)
-    {
-        if (context->src_fbo)
-        {
-            TRACE("Destroy src FBO %d\n", context->src_fbo);
-            context_destroy_fbo(context, &context->src_fbo);
-        }
-        if (context->dst_fbo)
-        {
-            TRACE("Destroy dst FBO %d\n", context->dst_fbo);
-            context_destroy_fbo(context, &context->dst_fbo);
-        }
-        if (context->dummy_arbfp_prog)
-        {
-            GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
-        }
-    }
-
-    LEAVE_GL();
-
-    if (This->activeContext == context)
-    {
-        This->activeContext = NULL;
-        TRACE("Destroying the active context.\n");
-    }
-
-    /* Cleanup the GL context */
-    if (!pwglMakeCurrent(NULL, NULL))
-    {
-        ERR("Failed to disable GL context.\n");
-    }
-
-    if(context->isPBuffer) {
-        GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
-        GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
-    } else ReleaseDC(context->win_handle, context->hdc);
-    pwglDeleteContext(context->glCtx);
+    if (context->tid == GetCurrentThreadId() || !context->current)
+    {
+        context_destroy_gl_resources(context);
+        destroy = TRUE;
+
+        if (!context_set_current(NULL))
+        {
+            ERR("Failed to clear current D3D context.\n");
+        }
+    }
+    else
+    {
+        context->destroyed = 1;
+        destroy = FALSE;
+    }
 
     HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
     HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
     RemoveContextFromArray(This, context);
+    if (destroy) HeapFree(GetProcessHeap(), 0, context);
 }
 
@@ -1308,5 +1520,6 @@
  *****************************************************************************/
 /* Context activation is done by the caller. */
-static inline void SetupForBlit(IWineD3DDeviceImpl *This, WineD3DContext *context, UINT width, UINT height) {
+static inline void SetupForBlit(IWineD3DDeviceImpl *This, struct wined3d_context *context, UINT width, UINT height)
+{
     int i, sampler;
     const struct StateEntry *StateTable = This->StateTable;
@@ -1334,5 +1547,5 @@
     /* Disable shaders */
     ENTER_GL();
-    This->shader_backend->shader_select((IWineD3DDevice *)This, FALSE, FALSE);
+    This->shader_backend->shader_select(context, FALSE, FALSE);
     LEAVE_GL();
 
@@ -1453,5 +1666,5 @@
     glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
     checkGLcall("glColorMask");
-    Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
+    Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE), StateTable);
     if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
         glDisable(GL_COLOR_SUM_EXT);
@@ -1497,5 +1710,6 @@
  *
  *****************************************************************************/
-static WineD3DContext *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid) {
+static struct wined3d_context *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid)
+{
     unsigned int i;
 
@@ -1523,24 +1737,33 @@
  *
  *****************************************************************************/
-static inline WineD3DContext *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid) {
+static inline struct wined3d_context *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid)
+{
     IWineD3DSwapChain *swapchain = NULL;
-    BOOL readTexture = wined3d_settings.offscreen_rendering_mode != ORM_FBO && This->render_offscreen;
-    WineD3DContext *context = This->activeContext;
-    BOOL oldRenderOffscreen = This->render_offscreen;
-    const struct GlPixelFormatDesc *old = ((IWineD3DSurfaceImpl *)This->lastActiveRenderTarget)->resource.format_desc;
-    const struct GlPixelFormatDesc *new = ((IWineD3DSurfaceImpl *)target)->resource.format_desc;
+    struct wined3d_context *current_context = context_get_current();
     const struct StateEntry *StateTable = This->StateTable;
-
-    /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
-     * the alpha blend state changes with different render target formats
-     */
-    if (old->format != new->format)
-    {
-        /* Disable blending when the alpha mask has changed and when a format doesn't support blending */
-        if ((old->alpha_mask && !new->alpha_mask) || (!old->alpha_mask && new->alpha_mask)
-                || !(new->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
-        {
-            Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
-        }
+    struct wined3d_context *context;
+    BOOL old_render_offscreen;
+
+    if (current_context && current_context->destroyed) current_context = NULL;
+
+    if (!target)
+    {
+        if (current_context
+                && current_context->current_rt
+                && ((IWineD3DSurfaceImpl *)current_context->surface)->resource.wineD3DDevice == This)
+        {
+            target = current_context->current_rt;
+        }
+        else
+        {
+            IWineD3DSwapChainImpl *swapchain = (IWineD3DSwapChainImpl *)This->swapchains[0];
+            if (swapchain->backBuffer) target = swapchain->backBuffer[0];
+            else target = swapchain->frontBuffer;
+        }
+    }
+
+    if (current_context && current_context->current_rt == target)
+    {
+        return current_context;
     }
 
@@ -1550,5 +1773,6 @@
         context = findThreadContextForSwapChain(swapchain, tid);
 
-        This->render_offscreen = FALSE;
+        old_render_offscreen = context->render_offscreen;
+        context->render_offscreen = FALSE;
         /* The context != This->activeContext will catch a NOP context change. This can occur
          * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
@@ -1562,143 +1786,141 @@
         }
         IWineD3DSwapChain_Release(swapchain);
-
-        if(oldRenderOffscreen) {
-            Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
-            Context_MarkStateDirty(context, STATE_VDECL, StateTable);
-            Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
-            Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
-            Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
-        }
-
-    } else {
+    }
+    else
+    {
         TRACE("Rendering offscreen\n");
-        This->render_offscreen = TRUE;
-
-        switch(wined3d_settings.offscreen_rendering_mode) {
-            case ORM_FBO:
-                /* FBOs do not need a different context. Stay with whatever context is active at the moment */
-                if(This->activeContext && tid == This->lastThread) {
-                    context = This->activeContext;
-                } else {
-                    /* This may happen if the app jumps straight into offscreen rendering
-                     * Start using the context of the primary swapchain. tid == 0 is no problem
-                     * for findThreadContextForSwapChain.
-                     *
-                     * Can also happen on thread switches - in that case findThreadContextForSwapChain
-                     * is perfect to call.
-                     */
-                    context = findThreadContextForSwapChain(This->swapchains[0], tid);
+
+retry:
+        if (wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER)
+        {
+            IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *)target;
+            if (!This->pbufferContext
+                    || This->pbufferWidth < targetimpl->currentDesc.Width
+                    || This->pbufferHeight < targetimpl->currentDesc.Height)
+            {
+                if (This->pbufferContext) DestroyContext(This, This->pbufferContext);
+
+                /* The display is irrelevant here, the window is 0. But
+                 * CreateContext needs a valid X connection. Create the context
+                 * on the same server as the primary swapchain. The primary
+                 * swapchain is exists at this point. */
+                This->pbufferContext = CreateContext(This, targetimpl,
+                        ((IWineD3DSwapChainImpl *)This->swapchains[0])->context[0]->win_handle,
+                        TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
+                This->pbufferWidth = targetimpl->currentDesc.Width;
+                This->pbufferHeight = targetimpl->currentDesc.Height;
+            }
+
+            if (This->pbufferContext)
+            {
+                if (This->pbufferContext->tid && This->pbufferContext->tid != tid)
+                {
+                    FIXME("The PBuffer context is only supported for one thread for now!\n");
                 }
-                break;
-
-            case ORM_PBUFFER:
+                This->pbufferContext->tid = tid;
+                context = This->pbufferContext;
+            }
+            else
             {
-                IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *) target;
-                if(This->pbufferContext == NULL ||
-                   This->pbufferWidth < targetimpl->currentDesc.Width ||
-                   This->pbufferHeight < targetimpl->currentDesc.Height) {
-                    if(This->pbufferContext) {
-                        DestroyContext(This, This->pbufferContext);
-                    }
-
-                    /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
-                     * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
-                     */
-                    This->pbufferContext = CreateContext(This, targetimpl,
-                            ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0]->win_handle,
-                            TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
-                    This->pbufferWidth = targetimpl->currentDesc.Width;
-                    This->pbufferHeight = targetimpl->currentDesc.Height;
-                   }
-
-                   if(This->pbufferContext) {
-                       if(This->pbufferContext->tid != 0 && This->pbufferContext->tid != tid) {
-                           FIXME("The PBuffr context is only supported for one thread for now!\n");
-                       }
-                       This->pbufferContext->tid = tid;
-                       context = This->pbufferContext;
-                       break;
-                   } else {
-                       ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
-                       wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
-                   }
-            }
-
-            case ORM_BACKBUFFER:
-                /* Stay with the currently active context for back buffer rendering */
-                if(This->activeContext && tid == This->lastThread) {
-                    context = This->activeContext;
-                } else {
-                    /* This may happen if the app jumps straight into offscreen rendering
-                     * Start using the context of the primary swapchain. tid == 0 is no problem
-                     * for findThreadContextForSwapChain.
-                     *
-                     * Can also happen on thread switches - in that case findThreadContextForSwapChain
-                     * is perfect to call.
-                     */
-                    context = findThreadContextForSwapChain(This->swapchains[0], tid);
-                }
-                break;
-        }
-
-        if(!oldRenderOffscreen) {
-            Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
-            Context_MarkStateDirty(context, STATE_VDECL, StateTable);
-            Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
-            Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
-            Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
-        }
-    }
-
-    /* When switching away from an offscreen render target, and we're not using FBOs,
-     * we have to read the drawable into the texture. This is done via PreLoad(and
-     * SFLAG_INDRAWABLE set on the surface). There are some things that need care though.
-     * PreLoad needs a GL context, and FindContext is called before the context is activated.
-     * It also has to be called with the old rendertarget active, otherwise a wrong drawable
-     * is read. This leads to these possible situations:
-     *
-     * 0) lastActiveRenderTarget == target && oldTid == newTid:
-     *    Nothing to do, we don't even reach this code in this case...
-     *
-     * 1) lastActiveRenderTarget != target && oldTid == newTid:
-     *    The currently active context is OK for readback. Call PreLoad, and it
-     *    performs the read
-     *
-     * 2) lastActiveRenderTarget == target && oldTid != newTid:
-     *    Nothing to do - the drawable is unchanged
-     *
-     * 3) lastActiveRenderTarget != target && oldTid != newTid:
-     *    This is tricky. We have to get a context with the old drawable from somewhere
-     *    before we can switch to the new context. In this case, PreLoad calls
-     *    ActivateContext(lastActiveRenderTarget) from the new(current) thread. This
-     *    is case (2) then. The old drawable is activated for the new thread, and the
-     *    readback can be done. The recursed ActivateContext does *not* call PreLoad again.
-     *    After that, the outer ActivateContext(which calls PreLoad) can activate the new
-     *    target for the new thread
-     */
-    if (readTexture && This->lastActiveRenderTarget != target) {
-        BOOL oldInDraw = This->isInDraw;
-
-        /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
-         * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
-         * when using offscreen rendering with multithreading
-         */
-        This->isInDraw = TRUE;
-
-        /* Do that before switching the context:
-         * Read the back buffer of the old drawable into the destination texture
-         */
-        if (((IWineD3DSurfaceImpl *)This->lastActiveRenderTarget)->texture_name_srgb)
-        {
-            surface_internal_preload(This->lastActiveRenderTarget, SRGB_BOTH);
-        } else {
-            surface_internal_preload(This->lastActiveRenderTarget, SRGB_RGB);
-        }
-
-        /* Assume that the drawable will be modified by some other things now */
-        IWineD3DSurface_ModifyLocation(This->lastActiveRenderTarget, SFLAG_INDRAWABLE, FALSE);
-
-        This->isInDraw = oldInDraw;
-    }
+                ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering.\n");
+                wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
+                goto retry;
+            }
+        }
+        else
+        {
+            /* Stay with the currently active context. */
+            if (current_context
+                    && ((IWineD3DSurfaceImpl *)current_context->surface)->resource.wineD3DDevice == This)
+            {
+                context = current_context;
+            }
+            else
+            {
+                /* This may happen if the app jumps straight into offscreen rendering
+                 * Start using the context of the primary swapchain. tid == 0 is no problem
+                 * for findThreadContextForSwapChain.
+                 *
+                 * Can also happen on thread switches - in that case findThreadContextForSwapChain
+                 * is perfect to call. */
+                context = findThreadContextForSwapChain(This->swapchains[0], tid);
+            }
+        }
+
+        old_render_offscreen = context->render_offscreen;
+        context->render_offscreen = TRUE;
+    }
+
+    if (context->render_offscreen != old_render_offscreen)
+    {
+        Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
+        Context_MarkStateDirty(context, STATE_VDECL, StateTable);
+        Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
+        Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
+        Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
+    }
+
+    /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
+     * the alpha blend state changes with different render target formats. */
+    if (!context->current_rt)
+    {
+        Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
+    }
+    else
+    {
+        const struct GlPixelFormatDesc *old = ((IWineD3DSurfaceImpl *)context->current_rt)->resource.format_desc;
+        const struct GlPixelFormatDesc *new = ((IWineD3DSurfaceImpl *)target)->resource.format_desc;
+
+        if (old->format != new->format)
+        {
+            /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
+            if ((old->alpha_mask && !new->alpha_mask) || (!old->alpha_mask && new->alpha_mask)
+                    || !(new->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
+            {
+                Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
+            }
+        }
+
+        /* When switching away from an offscreen render target, and we're not
+         * using FBOs, we have to read the drawable into the texture. This is
+         * done via PreLoad (and SFLAG_INDRAWABLE set on the surface). There
+         * are some things that need care though. PreLoad needs a GL context,
+         * and FindContext is called before the context is activated. It also
+         * has to be called with the old rendertarget active, otherwise a
+         * wrong drawable is read. */
+        if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
+                && old_render_offscreen && context->current_rt != target)
+        {
+            BOOL oldInDraw = This->isInDraw;
+
+            /* surface_internal_preload() requires a context to load the
+             * texture, so it will call ActivateContext. Set isInDraw to true
+             * to signal surface_internal_preload() that it has a context. */
+
+            /* FIXME: This is just broken. There's no guarantee whatsoever
+             * that the currently active context, if any, is appropriate for
+             * reading back the render target. We should probably call
+             * context_set_current(context) here and then rely on
+             * ActivateContext() doing the right thing. */
+            This->isInDraw = TRUE;
+
+            /* Read the back buffer of the old drawable into the destination texture. */
+            if (((IWineD3DSurfaceImpl *)context->current_rt)->texture_name_srgb)
+            {
+                surface_internal_preload(context->current_rt, SRGB_BOTH);
+            }
+            else
+            {
+                surface_internal_preload(context->current_rt, SRGB_RGB);
+            }
+
+            IWineD3DSurface_ModifyLocation(context->current_rt, SFLAG_INDRAWABLE, FALSE);
+
+            This->isInDraw = oldInDraw;
+        }
+    }
+
+    context->draw_buffer_dirty = TRUE;
+    context->current_rt = target;
 
     return context;
@@ -1706,14 +1928,17 @@
 
 /* Context activation is done by the caller. */
-static void apply_draw_buffer(IWineD3DDeviceImpl *This, IWineD3DSurface *target, BOOL blit)
-{
-    const struct wined3d_gl_info *gl_info = This->activeContext->gl_info;
+static void context_apply_draw_buffer(struct wined3d_context *context, BOOL blit)
+{
+    const struct wined3d_gl_info *gl_info = context->gl_info;
+    IWineD3DSurface *rt = context->current_rt;
     IWineD3DSwapChain *swapchain;
-
-    if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain)))
+    IWineD3DDeviceImpl *device;
+
+    device = ((IWineD3DSurfaceImpl *)rt)->resource.wineD3DDevice;
+    if (SUCCEEDED(IWineD3DSurface_GetContainer(rt, &IID_IWineD3DSwapChain, (void **)&swapchain)))
     {
         IWineD3DSwapChain_Release((IUnknown *)swapchain);
         ENTER_GL();
-        glDrawBuffer(surface_get_gl_buffer(target, swapchain));
+        glDrawBuffer(surface_get_gl_buffer(rt, swapchain));
         checkGLcall("glDrawBuffers()");
         LEAVE_GL();
@@ -1728,10 +1953,10 @@
                 if (GL_SUPPORT(ARB_DRAW_BUFFERS))
                 {
-                    GL_EXTCALL(glDrawBuffersARB(GL_LIMITS(buffers), This->draw_buffers));
+                    GL_EXTCALL(glDrawBuffersARB(GL_LIMITS(buffers), device->draw_buffers));
                     checkGLcall("glDrawBuffers()");
                 }
                 else
                 {
-                    glDrawBuffer(This->draw_buffers[0]);
+                    glDrawBuffer(device->draw_buffers[0]);
                     checkGLcall("glDrawBuffer()");
                 }
@@ -1743,5 +1968,5 @@
         else
         {
-            glDrawBuffer(This->offscreenBuffer);
+            glDrawBuffer(device->offscreenBuffer);
             checkGLcall("glDrawBuffer()");
         }
@@ -1763,55 +1988,38 @@
  *
  *****************************************************************************/
-void ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, ContextUsage usage) {
+struct wined3d_context *ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, enum ContextUsage usage)
+{
+    struct wined3d_context *current_context = context_get_current();
     DWORD                         tid = GetCurrentThreadId();
     DWORD                         i, dirtyState, idx;
     BYTE                          shift;
-    WineD3DContext                *context;
     const struct StateEntry       *StateTable = This->StateTable;
     const struct wined3d_gl_info *gl_info;
+    struct wined3d_context *context;
 
     TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
-    if(This->lastActiveRenderTarget != target || tid != This->lastThread) {
-        context = FindContext(This, target, tid);
-        context->draw_buffer_dirty = TRUE;
-        This->lastActiveRenderTarget = target;
-        This->lastThread = tid;
-    } else {
-        /* Stick to the old context */
-        context = This->activeContext;
-    }
+
+    context = FindContext(This, target, tid);
 
     gl_info = context->gl_info;
 
     /* Activate the opengl context */
-    if(last_device != This || context != This->activeContext) {
-        BOOL ret;
-
-        /* Prevent an unneeded context switch as those are expensive */
-        if(context->glCtx && (context->glCtx == pwglGetCurrentContext())) {
-            TRACE("Already using gl context %p\n", context->glCtx);
-        }
-        else {
-            TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context, context->hdc, context->glCtx);
-
-            ret = pwglMakeCurrent(context->hdc, context->glCtx);
-            if(ret == FALSE) {
-                ERR("Failed to activate the new context\n");
-            } else if(!context->last_was_blit) {
-                This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
-            } else {
-                This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
-            }
-        }
-        if(This->activeContext->vshader_const_dirty) {
-            memset(This->activeContext->vshader_const_dirty, 1,
-                   sizeof(*This->activeContext->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
-        }
-        if(This->activeContext->pshader_const_dirty) {
-            memset(This->activeContext->pshader_const_dirty, 1,
-                   sizeof(*This->activeContext->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
-        }
-        This->activeContext = context;
-        context_set_last_device(This);
+    if (context != current_context)
+    {
+        if (!context_set_current(context)) ERR("Failed to activate the new context.\n");
+        else This->frag_pipe->enable_extension((IWineD3DDevice *)This, !context->last_was_blit);
+
+        if (context->vshader_const_dirty)
+        {
+            memset(context->vshader_const_dirty, 1,
+                    sizeof(*context->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
+            This->highest_dirty_vs_const = GL_LIMITS(vshader_constantsF);
+        }
+        if (context->pshader_const_dirty)
+        {
+            memset(context->pshader_const_dirty, 1,
+                   sizeof(*context->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
+            This->highest_dirty_ps_const = GL_LIMITS(pshader_constantsF);
+        }
     }
 
@@ -1825,5 +2033,5 @@
             }
             if (context->draw_buffer_dirty) {
-                apply_draw_buffer(This, target, FALSE);
+                context_apply_draw_buffer(context, FALSE);
                 context->draw_buffer_dirty = FALSE;
             }
@@ -1832,5 +2040,6 @@
         case CTXUSAGE_BLIT:
             if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
-                if (This->render_offscreen) {
+                if (context->render_offscreen)
+                {
                     FIXME("Activating for CTXUSAGE_BLIT for an offscreen target with ORM_FBO. This should be avoided.\n");
                     ENTER_GL();
@@ -1847,5 +2056,5 @@
             }
             if (context->draw_buffer_dirty) {
-                apply_draw_buffer(This, target, TRUE);
+                context_apply_draw_buffer(context, TRUE);
                 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
                     context->draw_buffer_dirty = FALSE;
@@ -1915,7 +2124,5 @@
             FIXME("Unexpected context usage requested\n");
     }
-}
-
-WineD3DContext *getActiveContext(void) {
-    return last_device->activeContext;
-}
+
+    return context;
+}
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/cubetexture.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/cubetexture.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/cubetexture.c	(revision 22496)
@@ -76,5 +76,5 @@
         /* No danger of recursive calls, ActivateContext sets isInDraw to true
          * when loading offscreen render targets into their texture. */
-        ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+        ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
     }
 
@@ -200,15 +200,4 @@
         WARN("Failed to initialize basetexture, returning %#x\n", hr);
         return hr;
-    }
-
-    if (texture->resource.format_desc->Flags & WINED3DFMT_FLAG_FILTERING)
-    {
-        texture->baseTexture.minMipLookup = minMipLookup;
-        texture->baseTexture.magLookup = magLookup;
-    }
-    else
-    {
-        texture->baseTexture.minMipLookup = minMipLookup_noFilter;
-        texture->baseTexture.magLookup = magLookup_noFilter;
     }
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/device.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/device.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/device.c	(revision 22496)
@@ -1201,30 +1201,11 @@
     switch(Type){
     case WINED3DQUERYTYPE_OCCLUSION:
-        object->extendedData = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WineQueryOcclusionData));
-        ((WineQueryOcclusionData *)(object->extendedData))->ctx = This->activeContext;
-
-        if(GL_SUPPORT(ARB_OCCLUSION_QUERY)) {
-            TRACE("(%p) Allocating data for an occlusion query\n", This);
-
-            ActivateContext(This, This->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
-            ENTER_GL();
-            GL_EXTCALL(glGenQueriesARB(1, &((WineQueryOcclusionData *)(object->extendedData))->queryId));
-            LEAVE_GL();
-            break;
-        }
+        object->extendedData = HeapAlloc(GetProcessHeap(), 0, sizeof(struct wined3d_occlusion_query));
+        ((struct wined3d_occlusion_query *)object->extendedData)->context = NULL;
+        break;
+
     case WINED3DQUERYTYPE_EVENT:
-        object->extendedData = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WineQueryEventData));
-        ((WineQueryEventData *)(object->extendedData))->ctx = This->activeContext;
-
-        ActivateContext(This, This->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
-        ENTER_GL();
-        if(GL_SUPPORT(APPLE_FENCE)) {
-            GL_EXTCALL(glGenFencesAPPLE(1, &((WineQueryEventData *)(object->extendedData))->fenceId));
-            checkGLcall("glGenFencesAPPLE");
-        } else if(GL_SUPPORT(NV_FENCE)) {
-            GL_EXTCALL(glGenFencesNV(1, &((WineQueryEventData *)(object->extendedData))->fenceId));
-            checkGLcall("glGenFencesNV");
-        }
-        LEAVE_GL();
+        object->extendedData = HeapAlloc(GetProcessHeap(), 0, sizeof(struct wined3d_event_query));
+        ((struct wined3d_event_query *)object->extendedData)->context = NULL;
         break;
 
@@ -2168,14 +2149,10 @@
         TRACE("Setting rendertarget to %p\n", swapchain->backBuffer);
         This->render_targets[0] = swapchain->backBuffer[0];
-        This->lastActiveRenderTarget = swapchain->backBuffer[0];
     }
     else {
         TRACE("Setting rendertarget to %p\n", swapchain->frontBuffer);
         This->render_targets[0] = swapchain->frontBuffer;
-        This->lastActiveRenderTarget = swapchain->frontBuffer;
     }
     IWineD3DSurface_AddRef(This->render_targets[0]);
-    This->activeContext = swapchain->context[0];
-    This->lastThread = GetCurrentThreadId();
 
     /* Depth Stencil support */
@@ -2223,5 +2200,6 @@
         case ORM_BACKBUFFER:
         {
-            if(This->activeContext->aux_buffers > 0) {
+            if (context_get_current()->aux_buffers > 0)
+            {
                 TRACE("Using auxilliary buffer for offscreen rendering\n");
                 This->offscreenBuffer = GL_AUX0;
@@ -2328,5 +2306,5 @@
      * it was created. Thus make sure a context is active for the glDelete* calls
      */
-    ActivateContext(This, This->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+    ActivateContext(This, NULL, CTXUSAGE_RESOURCELOAD);
 
     if(This->logo_surface) IWineD3DSurface_Release(This->logo_surface);
@@ -4410,5 +4388,5 @@
 
     /* Need any context to write to the vbo. */
-    ActivateContext(This, This->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+    ActivateContext(This, NULL, CTXUSAGE_RESOURCELOAD);
 
     /* ProcessVertices reads from vertex buffers, which have to be assigned. DrawPrimitive and DrawPrimitiveUP
@@ -4876,5 +4854,5 @@
     }
 
-    ActivateContext(This, This->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+    ActivateContext(This, NULL, CTXUSAGE_RESOURCELOAD);
     /* We only have to do this if we need to read the, swapbuffers performs a flush for us */
     glFlush();
@@ -4920,4 +4898,5 @@
     IWineD3DSurfaceImpl *depth_stencil = (IWineD3DSurfaceImpl *) This->stencilBufferTarget;
     IWineD3DSwapChainImpl *swapchain = NULL;
+    struct wined3d_context *context;
 
     /* When we're clearing parts of the drawable, make sure that the target surface is well up to date in the
@@ -4955,7 +4934,8 @@
     }
 
-    target->get_drawable_size(target, &drawable_width, &drawable_height);
-
-    ActivateContext(This, (IWineD3DSurface *) target, CTXUSAGE_CLEAR);
+    context = ActivateContext(This, (IWineD3DSurface *)target, CTXUSAGE_CLEAR);
+
+    target->get_drawable_size(context, &drawable_width, &drawable_height);
+
     ENTER_GL();
 
@@ -4969,5 +4949,5 @@
 
     if (Flags & WINED3DCLEAR_ZBUFFER) {
-        DWORD location = This->render_offscreen ? SFLAG_DS_OFFSCREEN : SFLAG_DS_ONSCREEN;
+        DWORD location = context->render_offscreen ? SFLAG_DS_OFFSCREEN : SFLAG_DS_ONSCREEN;
         glDepthMask(GL_TRUE);
         glClearDepth(Z);
@@ -4978,5 +4958,5 @@
         if (vp->X != 0 || vp->Y != 0 ||
                 vp->Width < depth_stencil->currentDesc.Width || vp->Height < depth_stencil->currentDesc.Height) {
-            surface_load_ds_location(This->stencilBufferTarget, location);
+            surface_load_ds_location(This->stencilBufferTarget, context, location);
         }
         else if (This->stateBlock->renderState[WINED3DRS_SCISSORTESTENABLE] && (
@@ -4984,5 +4964,5 @@
                 This->stateBlock->scissorRect.right < depth_stencil->currentDesc.Width ||
                 This->stateBlock->scissorRect.bottom < depth_stencil->currentDesc.Height)) {
-            surface_load_ds_location(This->stencilBufferTarget, location);
+            surface_load_ds_location(This->stencilBufferTarget, context, location);
         }
         else if (Count > 0 && pRects && (
@@ -4990,5 +4970,5 @@
                 pRects[0].x2 < depth_stencil->currentDesc.Width ||
                 pRects[0].y2 < depth_stencil->currentDesc.Height)) {
-            surface_load_ds_location(This->stencilBufferTarget, location);
+            surface_load_ds_location(This->stencilBufferTarget, context, location);
         }
     }
@@ -5015,5 +4995,6 @@
             IntersectRect(&vp_rect, &vp_rect, &This->stateBlock->scissorRect);
         }
-        if(This->render_offscreen) {
+        if (context->render_offscreen)
+        {
             glScissor(vp_rect.left, vp_rect.top,
                         vp_rect.right - vp_rect.left, vp_rect.bottom - vp_rect.top);
@@ -5047,5 +5028,6 @@
             }
 
-            if(This->render_offscreen) {
+            if (context->render_offscreen)
+            {
                 glScissor(curRect.x1, curRect.y1,
                           curRect.x2 - curRect.x1, curRect.y2 - curRect.y1);
@@ -5075,9 +5057,9 @@
          * it is most likely more efficient to perform a clear on the sysmem copy too instead of downloading it
          */
-        IWineD3DSurface_ModifyLocation(This->lastActiveRenderTarget, SFLAG_INDRAWABLE, TRUE);
+        IWineD3DSurface_ModifyLocation((IWineD3DSurface *)target, SFLAG_INDRAWABLE, TRUE);
     }
     if (Flags & WINED3DCLEAR_ZBUFFER) {
         /* Note that WINED3DCLEAR_ZBUFFER implies a depth stencil exists on the device */
-        DWORD location = This->render_offscreen ? SFLAG_DS_OFFSCREEN : SFLAG_DS_ONSCREEN;
+        DWORD location = context->render_offscreen ? SFLAG_DS_OFFSCREEN : SFLAG_DS_ONSCREEN;
         surface_modify_ds_location(This->stencilBufferTarget, location);
     }
@@ -5805,5 +5787,5 @@
     }
 
-    ActivateContext(This, This->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+    ActivateContext(This, NULL, CTXUSAGE_RESOURCELOAD);
 
     ENTER_GL();
@@ -6041,4 +6023,5 @@
 {
     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
+    struct wined3d_context *context;
     IWineD3DSwapChain *swapchain;
 
@@ -6049,7 +6032,7 @@
         TRACE("Surface %p is onscreen\n", surface);
 
-        ActivateContext(This, surface, CTXUSAGE_RESOURCELOAD);
+        context = ActivateContext(This, surface, CTXUSAGE_RESOURCELOAD);
         ENTER_GL();
-        context_bind_fbo(This->activeContext, GL_FRAMEBUFFER_EXT, NULL);
+        context_bind_fbo(context, GL_FRAMEBUFFER_EXT, NULL);
         buffer = surface_get_gl_buffer(surface, swapchain);
         glDrawBuffer(buffer);
@@ -6058,9 +6041,9 @@
         TRACE("Surface %p is offscreen\n", surface);
 
-        ActivateContext(This, This->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+        context = ActivateContext(This, NULL, CTXUSAGE_RESOURCELOAD);
         ENTER_GL();
-        context_bind_fbo(This->activeContext, GL_FRAMEBUFFER_EXT, &This->activeContext->dst_fbo);
-        context_attach_surface_fbo(This->activeContext, GL_FRAMEBUFFER_EXT, 0, surface);
-        context_attach_depth_stencil_fbo(This->activeContext, GL_FRAMEBUFFER_EXT, NULL, FALSE);
+        context_bind_fbo(context, GL_FRAMEBUFFER_EXT, &context->dst_fbo);
+        context_attach_surface_fbo(context, GL_FRAMEBUFFER_EXT, 0, surface);
+        context_attach_depth_stencil_fbo(context, GL_FRAMEBUFFER_EXT, NULL, FALSE);
     }
 
@@ -6089,10 +6072,4 @@
     glClear(GL_COLOR_BUFFER_BIT);
     checkGLcall("glClear");
-
-    if (This->activeContext->current_fbo) {
-        context_bind_fbo(This->activeContext, GL_FRAMEBUFFER_EXT, &This->activeContext->current_fbo->id);
-    } else {
-        context_bind_fbo(This->activeContext, GL_FRAMEBUFFER_EXT, NULL);
-    }
 
     if (swapchain && surface == ((IWineD3DSwapChainImpl *)swapchain)->frontBuffer
@@ -6233,5 +6210,5 @@
         BltFx.u5.dwFillColor = argb_to_fmt(color, surface->resource.format_desc->format);
         return IWineD3DSurface_Blt(pSurface, (const RECT *)pRect, NULL, NULL,
-                WINEDDBLT_COLORFILL, &BltFx, WINED3DTEXF_NONE);
+                WINEDDBLT_COLORFILL, &BltFx, WINED3DTEXF_POINT);
     }
 }
@@ -6280,5 +6257,5 @@
         BltFx.dwSize = sizeof(BltFx);
         BltFx.u5.dwFillColor = argb_to_fmt(c, ((IWineD3DSurfaceImpl *)surface)->resource.format_desc->format);
-        hr = IWineD3DSurface_Blt(surface, NULL, NULL, NULL, WINEDDBLT_COLORFILL, &BltFx, WINED3DTEXF_NONE);
+        hr = IWineD3DSurface_Blt(surface, NULL, NULL, NULL, WINEDDBLT_COLORFILL, &BltFx, WINED3DTEXF_POINT);
         if (FAILED(hr))
         {
@@ -6425,4 +6402,5 @@
     GLbitfield mask = GL_COLOR_BUFFER_BIT; /* TODO: Support blitting depth/stencil surfaces */
     IWineD3DSwapChain *src_swapchain, *dst_swapchain;
+    struct wined3d_context *context;
     GLenum gl_filter;
     POINT offset = {0, 0};
@@ -6450,7 +6428,7 @@
     dst_swapchain = get_swapchain(dst_surface);
 
-    if (src_swapchain) ActivateContext(This, src_surface, CTXUSAGE_RESOURCELOAD);
-    else if (dst_swapchain) ActivateContext(This, dst_surface, CTXUSAGE_RESOURCELOAD);
-    else ActivateContext(This, This->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+    if (src_swapchain) context = ActivateContext(This, src_surface, CTXUSAGE_RESOURCELOAD);
+    else if (dst_swapchain) context = ActivateContext(This, dst_surface, CTXUSAGE_RESOURCELOAD);
+    else context = ActivateContext(This, NULL, CTXUSAGE_RESOURCELOAD);
 
     if (src_swapchain) {
@@ -6477,5 +6455,5 @@
 
         ENTER_GL();
-        context_bind_fbo(This->activeContext, GL_READ_FRAMEBUFFER_EXT, NULL);
+        context_bind_fbo(context, GL_READ_FRAMEBUFFER_EXT, NULL);
         glReadBuffer(buffer);
         checkGLcall("glReadBuffer()");
@@ -6483,9 +6461,9 @@
         TRACE("Source surface %p is offscreen\n", src_surface);
         ENTER_GL();
-        context_bind_fbo(This->activeContext, GL_READ_FRAMEBUFFER_EXT, &This->activeContext->src_fbo);
-        context_attach_surface_fbo(This->activeContext, GL_READ_FRAMEBUFFER_EXT, 0, src_surface);
+        context_bind_fbo(context, GL_READ_FRAMEBUFFER_EXT, &context->src_fbo);
+        context_attach_surface_fbo(context, GL_READ_FRAMEBUFFER_EXT, 0, src_surface);
         glReadBuffer(GL_COLOR_ATTACHMENT0_EXT);
         checkGLcall("glReadBuffer()");
-        context_attach_depth_stencil_fbo(This->activeContext, GL_READ_FRAMEBUFFER_EXT, NULL, FALSE);
+        context_attach_depth_stencil_fbo(context, GL_READ_FRAMEBUFFER_EXT, NULL, FALSE);
     }
     LEAVE_GL();
@@ -6516,5 +6494,5 @@
 
         ENTER_GL();
-        context_bind_fbo(This->activeContext, GL_DRAW_FRAMEBUFFER_EXT, NULL);
+        context_bind_fbo(context, GL_DRAW_FRAMEBUFFER_EXT, NULL);
         glDrawBuffer(buffer);
         checkGLcall("glDrawBuffer()");
@@ -6523,9 +6501,9 @@
 
         ENTER_GL();
-        context_bind_fbo(This->activeContext, GL_DRAW_FRAMEBUFFER_EXT, &This->activeContext->dst_fbo);
-        context_attach_surface_fbo(This->activeContext, GL_DRAW_FRAMEBUFFER_EXT, 0, dst_surface);
+        context_bind_fbo(context, GL_DRAW_FRAMEBUFFER_EXT, &context->dst_fbo);
+        context_attach_surface_fbo(context, GL_DRAW_FRAMEBUFFER_EXT, 0, dst_surface);
         glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
         checkGLcall("glDrawBuffer()");
-        context_attach_depth_stencil_fbo(This->activeContext, GL_DRAW_FRAMEBUFFER_EXT, NULL, FALSE);
+        context_attach_depth_stencil_fbo(context, GL_DRAW_FRAMEBUFFER_EXT, NULL, FALSE);
     }
     glDisable(GL_SCISSOR_TEST);
@@ -6543,10 +6521,4 @@
 
     IWineD3DSurface_ModifyLocation(dst_surface, SFLAG_INDRAWABLE, TRUE);
-
-    if (This->activeContext->current_fbo) {
-        context_bind_fbo(This->activeContext, GL_FRAMEBUFFER_EXT, &This->activeContext->current_fbo->id);
-    } else {
-        context_bind_fbo(This->activeContext, GL_FRAMEBUFFER_EXT, NULL);
-    }
 
     /* If we switched from GL_BACK to GL_FRONT above, we need to switch back here */
@@ -6633,6 +6605,6 @@
                 surface_modify_ds_location(This->stencilBufferTarget, SFLAG_DS_DISCARDED);
             } else {
-                ActivateContext(This, This->render_targets[0], CTXUSAGE_RESOURCELOAD);
-                surface_load_ds_location(This->stencilBufferTarget, SFLAG_DS_OFFSCREEN);
+                struct wined3d_context *context = ActivateContext(This, This->render_targets[0], CTXUSAGE_RESOURCELOAD);
+                surface_load_ds_location(This->stencilBufferTarget, context, SFLAG_DS_OFFSCREEN);
                 surface_modify_ds_location(This->stencilBufferTarget, SFLAG_DS_OFFSCREEN);
             }
@@ -6642,16 +6614,6 @@
         This->stencilBufferTarget = pNewZStencil;
         /* should we be calling the parent or the wined3d surface? */
-        if (NULL != This->stencilBufferTarget) {
-            IUnknown *pParent;
-            IWineD3DSurface_AddRef(This->stencilBufferTarget);
-            IWineD3DSurface_GetParent(This->stencilBufferTarget, &pParent);
-        }
-        if (NULL != tmp) {
-            IUnknown *pParent;
-            IWineD3DSurface_GetParent(This->stencilBufferTarget, &pParent);
-            IUnknown_Release(pParent);
-            IUnknown_Release(pParent);
-            IWineD3DSurface_Release(tmp);
-        }
+        if (NULL != This->stencilBufferTarget) IWineD3DSurface_AddRef(This->stencilBufferTarget);
+        if (NULL != tmp) IWineD3DSurface_Release(tmp);
         hr = WINED3D_OK;
 
@@ -6678,5 +6640,5 @@
     /* some basic validation checks */
     if(This->cursorTexture) {
-        ActivateContext(This, This->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+        ActivateContext(This, NULL, CTXUSAGE_RESOURCELOAD);
         ENTER_GL();
         glDeleteTextures(1, &This->cursorTexture);
@@ -6737,5 +6699,5 @@
                 IWineD3DSurface_UnlockRect(pCursorBitmap);
 
-                ActivateContext(This, This->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+                ActivateContext(This, NULL, CTXUSAGE_RESOURCELOAD);
 
                 ENTER_GL();
@@ -6938,5 +6900,5 @@
     if (surface->texture_name)
     {
-        ActivateContext(This, This->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+        ActivateContext(This, NULL, CTXUSAGE_RESOURCELOAD);
         ENTER_GL();
         glDeleteTextures(1, &surface->texture_name);
@@ -7003,5 +6965,5 @@
     IWineD3DBaseShaderImpl *shader;
 
-    ActivateContext(This, This->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+    ActivateContext(This, NULL, CTXUSAGE_RESOURCELOAD);
 
     IWineD3DDevice_EnumResources(iface, reset_unload_resources, NULL);
@@ -7039,5 +7001,4 @@
         DestroyContext(This, This->contexts[0]);
     }
-    This->activeContext = NULL;
     HeapFree(GetProcessHeap(), 0, swapchain->context);
     swapchain->context = NULL;
@@ -7061,5 +7022,4 @@
                                           &swapchain->presentParms);
     swapchain->num_contexts = 1;
-    This->activeContext = swapchain->context[0];
 
     create_dummy_textures(This);
@@ -7731,8 +7691,8 @@
 void IWineD3DDeviceImpl_MarkStateDirty(IWineD3DDeviceImpl *This, DWORD state) {
     DWORD rep = This->StateTable[state].representative;
+    struct wined3d_context *context;
     DWORD idx;
     BYTE shift;
     UINT i;
-    WineD3DContext *context;
 
     if(!rep) return;
@@ -7748,27 +7708,28 @@
 }
 
-void get_drawable_size_pbuffer(IWineD3DSurfaceImpl *This, UINT *width, UINT *height) {
-    IWineD3DDeviceImpl *dev = This->resource.wineD3DDevice;
-    /* The drawable size of a pbuffer render target is the current pbuffer size
-     */
-    *width = dev->pbufferWidth;
-    *height = dev->pbufferHeight;
-}
-
-void get_drawable_size_fbo(IWineD3DSurfaceImpl *This, UINT *width, UINT *height) {
-    /* The drawable size of a fbo target is the opengl texture size, which is the power of two size
-     */
-    *width = This->pow2Width;
-    *height = This->pow2Height;
-}
-
-void get_drawable_size_backbuffer(IWineD3DSurfaceImpl *This, UINT *width, UINT *height) {
-    IWineD3DDeviceImpl *dev = This->resource.wineD3DDevice;
+void get_drawable_size_pbuffer(struct wined3d_context *context, UINT *width, UINT *height)
+{
+    IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->current_rt)->resource.wineD3DDevice;
+    /* The drawable size of a pbuffer render target is the current pbuffer size. */
+    *width = device->pbufferWidth;
+    *height = device->pbufferHeight;
+}
+
+void get_drawable_size_fbo(struct wined3d_context *context, UINT *width, UINT *height)
+{
+    IWineD3DSurfaceImpl *surface = (IWineD3DSurfaceImpl *)context->current_rt;
+    /* The drawable size of a fbo target is the opengl texture size, which is the power of two size. */
+    *width = surface->pow2Width;
+    *height = surface->pow2Height;
+}
+
+void get_drawable_size_backbuffer(struct wined3d_context *context, UINT *width, UINT *height)
+{
+    IWineD3DSurfaceImpl *surface = (IWineD3DSurfaceImpl *)context->surface;
     /* The drawable size of a backbuffer / aux buffer offscreen target is the size of the
      * current context's drawable, which is the size of the back buffer of the swapchain
      * the active context belongs to. The back buffer of the swapchain is stored as the
-     * surface the context belongs to.
-     */
-    *width = ((IWineD3DSurfaceImpl *) dev->activeContext->surface)->currentDesc.Width;
-    *height = ((IWineD3DSurfaceImpl *) dev->activeContext->surface)->currentDesc.Height;
-}
+     * surface the context belongs to. */
+    *width = surface->currentDesc.Width;
+    *height = surface->currentDesc.Height;
+}
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/directx.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/directx.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/directx.c	(revision 22496)
@@ -178,17 +178,30 @@
 DWORD *stateLookup[MAX_LOOKUPS];
 
-struct min_lookup minMipLookup[WINED3DTEXF_ANISOTROPIC + 1];
-const struct min_lookup minMipLookup_noFilter[WINED3DTEXF_ANISOTROPIC + 1] =
-{
-    {{GL_NEAREST, GL_NEAREST, GL_NEAREST}},
-    {{GL_NEAREST, GL_NEAREST, GL_NEAREST}},
-    {{GL_NEAREST, GL_NEAREST, GL_NEAREST}},
-    {{GL_NEAREST, GL_NEAREST, GL_NEAREST}},
+const struct min_lookup minMipLookup[] =
+{
+    /* NONE         POINT                       LINEAR */
+    {{GL_NEAREST,   GL_NEAREST,                 GL_NEAREST}},               /* NONE */
+    {{GL_NEAREST,   GL_NEAREST_MIPMAP_NEAREST,  GL_NEAREST_MIPMAP_LINEAR}}, /* POINT*/
+    {{GL_LINEAR,    GL_LINEAR_MIPMAP_NEAREST,   GL_LINEAR_MIPMAP_LINEAR}},  /* LINEAR */
 };
 
-GLenum magLookup[WINED3DTEXF_ANISOTROPIC + 1];
-const GLenum magLookup_noFilter[WINED3DTEXF_ANISOTROPIC + 1] =
-{
-    GL_NEAREST, GL_NEAREST, GL_NEAREST, GL_NEAREST
+const struct min_lookup minMipLookup_noFilter[] =
+{
+    /* NONE         POINT                       LINEAR */
+    {{GL_NEAREST,   GL_NEAREST,                 GL_NEAREST}},               /* NONE */
+    {{GL_NEAREST,   GL_NEAREST,                 GL_NEAREST}},               /* POINT */
+    {{GL_NEAREST,   GL_NEAREST,                 GL_NEAREST}},               /* LINEAR */
+};
+
+const GLenum magLookup[] =
+{
+    /* NONE     POINT       LINEAR */
+    GL_NEAREST, GL_NEAREST, GL_LINEAR,
+};
+
+const GLenum magLookup_noFilter[] =
+{
+    /* NONE     POINT       LINEAR */
+    GL_NEAREST, GL_NEAREST, GL_NEAREST,
 };
 
@@ -284,4 +297,9 @@
 
     /* Make it the current GL context. */
+    if (!context_set_current(NULL))
+    {
+        ERR_(d3d_caps)("Failed to clear current D3D context.\n");
+    }
+
     if (!pwglMakeCurrent(ctx->dc, ctx->gl_ctx))
     {
@@ -289,5 +307,4 @@
         goto fail;
     }
-    context_set_last_device(NULL);
 
     return TRUE;
@@ -706,7 +723,10 @@
      * has this extension promoted to core. The extension loading code sets this extension supported
      * due to that, so this code works on fglrx as well. */
-    TRACE("GL_ARB_texture_non_power_of_two advertised on R500 or earlier card, removing.\n");
-    gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO] = FALSE;
-    gl_info->supported[WINE_NORMALIZED_TEXRECT] = TRUE;
+    if(gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO])
+    {
+        TRACE("GL_ARB_texture_non_power_of_two advertised on R500 or earlier card, removing.\n");
+        gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO] = FALSE;
+        gl_info->supported[WINE_NORMALIZED_TEXRECT] = TRUE;
+    }
 
     /* fglrx has the same structural issues as the one described in quirk_apple_glsl_constants, although
@@ -1997,29 +2017,4 @@
              gl_info->supported[ATI_TEXTURE_MIRROR_ONCE] ? GL_MIRROR_CLAMP_TO_EDGE_ATI : GL_REPEAT;
 
-    magLookup[WINED3DTEXF_NONE        - WINED3DTEXF_NONE]  = GL_NEAREST;
-    magLookup[WINED3DTEXF_POINT       - WINED3DTEXF_NONE] = GL_NEAREST;
-    magLookup[WINED3DTEXF_LINEAR      - WINED3DTEXF_NONE] = GL_LINEAR;
-    magLookup[WINED3DTEXF_ANISOTROPIC - WINED3DTEXF_NONE] =
-             gl_info->supported[EXT_TEXTURE_FILTER_ANISOTROPIC] ? GL_LINEAR : GL_NEAREST;
-
-
-    minMipLookup[WINED3DTEXF_NONE].mip[WINED3DTEXF_NONE]     = GL_LINEAR;
-    minMipLookup[WINED3DTEXF_NONE].mip[WINED3DTEXF_POINT]    = GL_LINEAR;
-    minMipLookup[WINED3DTEXF_NONE].mip[WINED3DTEXF_LINEAR]   = GL_LINEAR;
-    minMipLookup[WINED3DTEXF_POINT].mip[WINED3DTEXF_NONE]    = GL_NEAREST;
-    minMipLookup[WINED3DTEXF_POINT].mip[WINED3DTEXF_POINT]   = GL_NEAREST_MIPMAP_NEAREST;
-    minMipLookup[WINED3DTEXF_POINT].mip[WINED3DTEXF_LINEAR]  = GL_NEAREST_MIPMAP_LINEAR;
-    minMipLookup[WINED3DTEXF_LINEAR].mip[WINED3DTEXF_NONE]   = GL_LINEAR;
-    minMipLookup[WINED3DTEXF_LINEAR].mip[WINED3DTEXF_POINT]  = GL_LINEAR_MIPMAP_NEAREST;
-    minMipLookup[WINED3DTEXF_LINEAR].mip[WINED3DTEXF_LINEAR] = GL_LINEAR_MIPMAP_LINEAR;
-    minMipLookup[WINED3DTEXF_ANISOTROPIC].mip[WINED3DTEXF_NONE]
-            = gl_info->supported[EXT_TEXTURE_FILTER_ANISOTROPIC] ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR;
-    minMipLookup[WINED3DTEXF_ANISOTROPIC].mip[WINED3DTEXF_POINT]
-            = gl_info->supported[EXT_TEXTURE_FILTER_ANISOTROPIC] ? GL_LINEAR_MIPMAP_NEAREST : GL_LINEAR;
-    minMipLookup[WINED3DTEXF_ANISOTROPIC].mip[WINED3DTEXF_LINEAR]
-            = gl_info->supported[EXT_TEXTURE_FILTER_ANISOTROPIC] ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR;
-
-/* TODO: config lookups */
-
     /* Make sure there's an active HDC else the WGL extensions will fail */
     hdc = pwglGetCurrentDC();
@@ -2704,5 +2699,5 @@
 
     /* Only allow depth/stencil formats */
-    if (!(ds_format_desc->Flags & (WINED3DFMT_FLAG_DEPTH | WINED3DFMT_FLAG_STENCIL))) return FALSE;
+    if (!(ds_format_desc->depth_size || ds_format_desc->stencil_size)) return FALSE;
 
     /* Walk through all WGL pixel formats to find a match */
@@ -2894,4 +2889,5 @@
         case WINED3DFMT_R10G10B10A2_UNORM:
         case WINED3DFMT_R16G16_UNORM:
+        case WINED3DFMT_R16G16B16A16_UNORM:
             TRACE_(d3d_caps)("[OK]\n");
             return TRUE;
@@ -3006,5 +3002,4 @@
 
             /* Not supported */
-        case WINED3DFMT_R16G16B16A16_UNORM:
         case WINED3DFMT_A8R3G3B2:
             TRACE_(d3d_caps)("[FAILED]\n"); /* Enable when implemented */
@@ -3659,16 +3654,4 @@
     }
 
-    /* This format is nothing special and it is supported perfectly.
-     * However, ati and nvidia driver on windows do not mark this format as
-     * supported (tested with the dxCapsViewer) and pretending to
-     * support this format uncovers a bug in Battlefield 1942 (fonts are missing)
-     * So do the same as Windows drivers and pretend not to support it on dx8 and 9
-     * Enable it on dx7. It will need additional checking on dx10 when we support it.
-     */
-    if(This->dxVersion > 7 && CheckFormat == WINED3DFMT_R8G8B8) {
-        TRACE_(d3d_caps)("[FAILED]\n");
-        return WINED3DERR_NOTAVAILABLE;
-    }
-
     /* When the UsageCaps exactly matches Usage return WINED3D_OK except for the situation in which
      * WINED3DUSAGE_AUTOGENMIPMAP isn't around, then WINED3DOK_NOAUTOGEN is returned if all the other
@@ -4077,7 +4060,5 @@
                               WINED3DSTENCILCAPS_INCR;
     }
-    if ( This->dxVersion > 8 &&
-        ( GL_SUPPORT(EXT_STENCIL_TWO_SIDE) ||
-            GL_SUPPORT(ATI_SEPARATE_STENCIL) ) ) {
+    if (GL_SUPPORT(EXT_STENCIL_TWO_SIDE) || GL_SUPPORT(ATI_SEPARATE_STENCIL)) {
         pCaps->StencilCaps |= WINED3DSTENCILCAPS_TWOSIDED;
     }
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/drawprim.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/drawprim.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/drawprim.c	(revision 22496)
@@ -82,6 +82,7 @@
 
 /* GL locking is done by the caller */
-static void drawStridedSlow(IWineD3DDevice *iface, const struct wined3d_stream_info *si, UINT NumVertexes,
-        GLenum glPrimType, const void *idxData, UINT idxSize, UINT minIndex, UINT startIdx)
+static void drawStridedSlow(IWineD3DDevice *iface, const struct wined3d_context *context,
+        const struct wined3d_stream_info *si, UINT NumVertexes, GLenum glPrimType,
+        const void *idxData, UINT idxSize, UINT minIndex, UINT startIdx)
 {
     unsigned int               textureNo    = 0;
@@ -134,5 +135,5 @@
     if (element->data) diffuse = element->data + streamOffset[element->stream_idx];
     else glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
-    num_untracked_materials = This->activeContext->num_untracked_materials;
+    num_untracked_materials = context->num_untracked_materials;
     if (num_untracked_materials && element->format_desc->format != WINED3DFMT_A8R8G8B8)
         FIXME("Implement diffuse color tracking from %s\n", debug_d3dformat(element->format_desc->format));
@@ -273,5 +274,5 @@
                 for (i = 0; i < num_untracked_materials; ++i)
                 {
-                    glMaterialfv(GL_FRONT_AND_BACK, This->activeContext->untracked_materials[i], color);
+                    glMaterialfv(GL_FRONT_AND_BACK, context->untracked_materials[i], color);
                 }
             }
@@ -570,4 +571,5 @@
     IWineD3DDeviceImpl           *This = (IWineD3DDeviceImpl *)iface;
     IWineD3DSurfaceImpl          *target;
+    struct wined3d_context *context;
     unsigned int i;
 
@@ -591,5 +593,5 @@
     This->isInDraw = TRUE;
 
-    ActivateContext(This, This->render_targets[0], CTXUSAGE_DRAWPRIM);
+    context = ActivateContext(This, This->render_targets[0], CTXUSAGE_DRAWPRIM);
 
     if (This->stencilBufferTarget) {
@@ -599,8 +601,8 @@
          * depthstencil for D3DCMP_NEVER and D3DCMP_ALWAYS as well. Also note
          * that we never copy the stencil data.*/
-        DWORD location = This->render_offscreen ? SFLAG_DS_OFFSCREEN : SFLAG_DS_ONSCREEN;
+        DWORD location = context->render_offscreen ? SFLAG_DS_OFFSCREEN : SFLAG_DS_ONSCREEN;
         if (This->stateBlock->renderState[WINED3DRS_ZWRITEENABLE]
                 || This->stateBlock->renderState[WINED3DRS_ZENABLE])
-            surface_load_ds_location(This->stencilBufferTarget, location);
+            surface_load_ds_location(This->stencilBufferTarget, context, location);
         if (This->stateBlock->renderState[WINED3DRS_ZWRITEENABLE])
             surface_modify_ds_location(This->stencilBufferTarget, location);
@@ -619,5 +621,5 @@
         if (!use_vs(This->stateBlock))
         {
-            if (!This->strided_streams.position_transformed && This->activeContext->num_untracked_materials
+            if (!This->strided_streams.position_transformed && context->num_untracked_materials
                     && This->stateBlock->renderState[WINED3DRS_LIGHTING])
             {
@@ -631,5 +633,6 @@
                 emulation = TRUE;
             }
-            else if(This->activeContext->fog_coord && This->stateBlock->renderState[WINED3DRS_FOGENABLE]) {
+            else if (context->fog_coord && This->stateBlock->renderState[WINED3DRS_FOGENABLE])
+            {
                 /* Either write a pipeline replacement shader or convert the specular alpha from unsigned byte
                  * to a float in the vertex buffer
@@ -665,5 +668,6 @@
                 drawStridedSlowVs(iface, stream_info, index_count, glPrimType, idxData, idxSize, minIndex, StartIdx);
             } else {
-                drawStridedSlow(iface, stream_info, index_count, glPrimType, idxData, idxSize, minIndex, StartIdx);
+                drawStridedSlow(iface, context, stream_info, index_count,
+                        glPrimType, idxData, idxSize, minIndex, StartIdx);
             }
         } else if(This->instancedDraw) {
@@ -771,5 +775,5 @@
      * takes care of dirtifying. Dirtifying is preferred over pushing / popping, since drawing the
      * patch (as opposed to normal draws) will most likely need different changes anyway. */
-    ActivateContext(This, This->lastActiveRenderTarget, CTXUSAGE_BLIT);
+    ActivateContext(This, NULL, CTXUSAGE_BLIT);
 
     /* First, locate the position data. This is provided in a vertex buffer in the stateblock.
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/gl_compat.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/gl_compat.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/gl_compat.c	(revision 22496)
@@ -157,5 +157,5 @@
 static void WINE_GLAPI wine_glEnable(GLenum cap) {
     if(cap == GL_FOG) {
-        WineD3DContext *ctx = getActiveContext();
+        struct wined3d_context *ctx = context_get_current();
         ctx->fog_enabled = 1;
         if(ctx->gl_fog_source != GL_FRAGMENT_DEPTH_EXT) return;
@@ -167,5 +167,5 @@
 static void WINE_GLAPI wine_glDisable(GLenum cap) {
     if(cap == GL_FOG) {
-        WineD3DContext *ctx = getActiveContext();
+        struct wined3d_context *ctx = context_get_current();
         ctx->fog_enabled = 0;
         if(ctx->gl_fog_source != GL_FRAGMENT_DEPTH_EXT) return;
@@ -176,6 +176,7 @@
 static void (WINE_GLAPI *old_fogcoord_glFogi) (GLenum pname, GLint param) = NULL;
 static void WINE_GLAPI wine_glFogi(GLenum pname, GLint param) {
+    struct wined3d_context *ctx = context_get_current();
+
     if(pname == GL_FOG_COORDINATE_SOURCE_EXT) {
-        WineD3DContext *ctx = getActiveContext();
         ctx->gl_fog_source = param;
         if(param == GL_FRAGMENT_DEPTH_EXT) {
@@ -187,7 +188,7 @@
     } else {
         if(pname == GL_FOG_START) {
-            getActiveContext()->fogstart = param;
+            ctx->fogstart = param;
         } else if(pname == GL_FOG_END) {
-            getActiveContext()->fogend = param;
+            ctx->fogend = param;
         }
         old_fogcoord_glFogi(pname, param);
@@ -197,6 +198,6 @@
 static void (WINE_GLAPI *old_fogcoord_glFogiv) (GLenum pname, const GLint *param) = NULL;
 static void WINE_GLAPI wine_glFogiv(GLenum pname, const GLint *param) {
+    struct wined3d_context *ctx = context_get_current();
     if(pname == GL_FOG_COORDINATE_SOURCE_EXT) {
-        WineD3DContext *ctx = getActiveContext();
         ctx->gl_fog_source = *param;
         if(*param == GL_FRAGMENT_DEPTH_EXT) {
@@ -208,7 +209,7 @@
     } else {
         if(pname == GL_FOG_START) {
-            getActiveContext()->fogstart = *param;
+            ctx->fogstart = *param;
         } else if(pname == GL_FOG_END) {
-            getActiveContext()->fogend = *param;
+            ctx->fogend = *param;
         }
         old_fogcoord_glFogiv(pname, param);
@@ -218,6 +219,6 @@
 static void (WINE_GLAPI *old_fogcoord_glFogf) (GLenum pname, GLfloat param) = NULL;
 static void WINE_GLAPI wine_glFogf(GLenum pname, GLfloat param) {
+    struct wined3d_context *ctx = context_get_current();
     if(pname == GL_FOG_COORDINATE_SOURCE_EXT) {
-        WineD3DContext *ctx = getActiveContext();
         ctx->gl_fog_source = (GLint) param;
         if(param == GL_FRAGMENT_DEPTH_EXT) {
@@ -229,7 +230,7 @@
     } else {
         if(pname == GL_FOG_START) {
-            getActiveContext()->fogstart = param;
+            ctx->fogstart = param;
         } else if(pname == GL_FOG_END) {
-            getActiveContext()->fogend = param;
+            ctx->fogend = param;
         }
         old_fogcoord_glFogf(pname, param);
@@ -239,6 +240,6 @@
 static void (WINE_GLAPI *old_fogcoord_glFogfv) (GLenum pname, const GLfloat *param) = NULL;
 static void WINE_GLAPI wine_glFogfv(GLenum pname, const GLfloat *param) {
+    struct wined3d_context *ctx = context_get_current();
     if(pname == GL_FOG_COORDINATE_SOURCE_EXT) {
-        WineD3DContext *ctx = getActiveContext();
         ctx->gl_fog_source = (GLint) *param;
         if(*param == GL_FRAGMENT_DEPTH_EXT) {
@@ -250,5 +251,4 @@
     } else {
         if(pname == GL_FOG_COLOR) {
-            WineD3DContext *ctx = getActiveContext();
             ctx->fogcolor[0] = param[0];
             ctx->fogcolor[1] = param[1];
@@ -256,7 +256,7 @@
             ctx->fogcolor[3] = param[3];
         } else if(pname == GL_FOG_START) {
-            getActiveContext()->fogstart = *param;
+            ctx->fogstart = *param;
         } else if(pname == GL_FOG_END) {
-            getActiveContext()->fogend = *param;
+            ctx->fogend = *param;
         }
         old_fogcoord_glFogfv(pname, param);
@@ -279,5 +279,5 @@
 
 static void WINE_GLAPI wine_glVertex4f(GLfloat x, GLfloat y, GLfloat z, GLfloat w) {
-    WineD3DContext *ctx = getActiveContext();
+    struct wined3d_context *ctx = context_get_current();
     if(ctx->gl_fog_source == GL_FOG_COORDINATE_EXT && ctx->fog_enabled) {
         GLfloat c[4] = {ctx->color[0], ctx->color[1], ctx->color[2], ctx->color[3]};
@@ -309,5 +309,5 @@
 
 static void WINE_GLAPI wine_glColor4f(GLfloat r, GLfloat g, GLfloat b, GLfloat a) {
-    WineD3DContext *ctx = getActiveContext();
+    struct wined3d_context *ctx = context_get_current();
     ctx->color[0] = r;
     ctx->color[1] = g;
@@ -337,5 +337,5 @@
  */
 static void WINE_GLAPI wine_glFogCoordfEXT(GLfloat f) {
-    WineD3DContext *ctx = getActiveContext();
+    struct wined3d_context *ctx = context_get_current();
     ctx->fog_coord_value = f;
 }
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/glsl_shader.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/glsl_shader.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/glsl_shader.c	(revision 22496)
@@ -638,13 +638,11 @@
  */
 /* GL locking is done by the caller (state handler) */
-static void shader_glsl_load_constants(
-    IWineD3DDevice* device,
-    char usePixelShader,
-    char useVertexShader) {
-   
-    IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) device;
-    struct shader_glsl_priv *priv = deviceImpl->shader_priv;
-    IWineD3DStateBlockImpl* stateBlock = deviceImpl->stateBlock;
-    const struct wined3d_gl_info *gl_info = &deviceImpl->adapter->gl_info;
+static void shader_glsl_load_constants(const struct wined3d_context *context,
+        char usePixelShader, char useVertexShader)
+{
+    IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice;
+    const struct wined3d_gl_info *gl_info = context->gl_info;
+    IWineD3DStateBlockImpl* stateBlock = device->stateBlock;
+    struct shader_glsl_priv *priv = device->shader_priv;
 
     GLhandleARB programId;
@@ -676,5 +674,5 @@
 
         /* Upload the position fixup params */
-        GL_EXTCALL(glUniform4fvARB(prog->posFixup_location, 1, &deviceImpl->posFixup[0]));
+        GL_EXTCALL(glUniform4fvARB(prog->posFixup_location, 1, &device->posFixup[0]));
         checkGLcall("glUniform4fvARB");
     }
@@ -724,10 +722,12 @@
         if(((IWineD3DPixelShaderImpl *) pshader)->vpos_uniform) {
             float correction_params[4];
-            if(deviceImpl->render_offscreen) {
+
+            if (context->render_offscreen)
+            {
                 correction_params[0] = 0.0f;
                 correction_params[1] = 1.0f;
             } else {
                 /* position is window relative, not viewport relative */
-                correction_params[0] = ((IWineD3DSurfaceImpl *) deviceImpl->render_targets[0])->currentDesc.Height;
+                correction_params[0] = ((IWineD3DSurfaceImpl *)context->current_rt)->currentDesc.Height;
                 correction_params[1] = -1.0f;
             }
@@ -815,11 +815,12 @@
 
 /** Generate the variable & register declarations for the GLSL output target */
-static void shader_generate_glsl_declarations(IWineD3DBaseShader *iface, const shader_reg_maps *reg_maps,
-        struct wined3d_shader_buffer *buffer, const struct wined3d_gl_info *gl_info,
-        struct shader_glsl_ctx_priv *ctx_priv)
+static void shader_generate_glsl_declarations(const struct wined3d_context *context,
+        struct wined3d_shader_buffer *buffer, IWineD3DBaseShader *iface,
+        const shader_reg_maps *reg_maps, struct shader_glsl_ctx_priv *ctx_priv)
 {
     IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
     const struct ps_compile_args *ps_args = ctx_priv->cur_ps_args;
+    const struct wined3d_gl_info *gl_info = context->gl_info;
     unsigned int i, extra_constants_needed = 0;
     const local_constant *lconst;
@@ -942,6 +943,6 @@
                 FIXME("Cannot find a free uniform for vpos correction params\n");
                 shader_addline(buffer, "const vec4 ycorrection = vec4(%f, %f, 0.0, 0.0);\n",
-                        device->render_offscreen ? 0.0f : ((IWineD3DSurfaceImpl *)device->render_targets[0])->currentDesc.Height,
-                        device->render_offscreen ? 1.0f : -1.0f);
+                        context->render_offscreen ? 0.0f : ((IWineD3DSurfaceImpl *)device->render_targets[0])->currentDesc.Height,
+                        context->render_offscreen ? 1.0f : -1.0f);
             }
             shader_addline(buffer, "vec4 vpos;\n");
@@ -3705,10 +3706,11 @@
 
 /* GL locking is done by the caller */
-static GLuint shader_glsl_generate_pshader(IWineD3DPixelShaderImpl *This, struct wined3d_shader_buffer *buffer,
+static GLuint shader_glsl_generate_pshader(const struct wined3d_context *context,
+        struct wined3d_shader_buffer *buffer, IWineD3DPixelShaderImpl *This,
         const struct ps_compile_args *args, struct ps_np2fixup_info *np2fixup_info)
 {
     const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
+    const struct wined3d_gl_info *gl_info = context->gl_info;
     CONST DWORD *function = This->baseShader.function;
-    const struct wined3d_gl_info *gl_info = &((IWineD3DDeviceImpl *)This->baseShader.device)->adapter->gl_info;
     struct shader_glsl_ctx_priv priv_ctx;
 
@@ -3733,5 +3735,5 @@
 
     /* Base Declarations */
-    shader_generate_glsl_declarations( (IWineD3DBaseShader*) This, reg_maps, buffer, &GLINFO_LOCATION, &priv_ctx);
+    shader_generate_glsl_declarations(context, buffer, (IWineD3DBaseShader *)This, reg_maps, &priv_ctx);
 
     /* Pack 3.0 inputs */
@@ -3803,10 +3805,11 @@
 
 /* GL locking is done by the caller */
-static GLuint shader_glsl_generate_vshader(IWineD3DVertexShaderImpl *This,
-        struct wined3d_shader_buffer *buffer, const struct vs_compile_args *args)
+static GLuint shader_glsl_generate_vshader(const struct wined3d_context *context,
+        struct wined3d_shader_buffer *buffer, IWineD3DVertexShaderImpl *This,
+        const struct vs_compile_args *args)
 {
     const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
+    const struct wined3d_gl_info *gl_info = context->gl_info;
     CONST DWORD *function = This->baseShader.function;
-    const struct wined3d_gl_info *gl_info = &((IWineD3DDeviceImpl *)This->baseShader.device)->adapter->gl_info;
     struct shader_glsl_ctx_priv priv_ctx;
 
@@ -3820,5 +3823,5 @@
 
     /* Base Declarations */
-    shader_generate_glsl_declarations( (IWineD3DBaseShader*) This, reg_maps, buffer, &GLINFO_LOCATION, &priv_ctx);
+    shader_generate_glsl_declarations(context, buffer, (IWineD3DBaseShader *)This, reg_maps, &priv_ctx);
 
     /* Base Shader Body */
@@ -3869,5 +3872,6 @@
 }
 
-static GLhandleARB find_glsl_pshader(struct wined3d_shader_buffer *buffer, IWineD3DPixelShaderImpl *shader,
+static GLhandleARB find_glsl_pshader(const struct wined3d_context *context,
+        struct wined3d_shader_buffer *buffer, IWineD3DPixelShaderImpl *shader,
         const struct ps_compile_args *args, const struct ps_np2fixup_info **np2fixup_info)
 {
@@ -3924,5 +3928,5 @@
 
     shader_buffer_clear(buffer);
-    ret = shader_glsl_generate_pshader(shader, buffer, args, np2fixup);
+    ret = shader_glsl_generate_pshader(context, buffer, shader, args, np2fixup);
     shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
     *np2fixup_info = np2fixup;
@@ -3937,5 +3941,6 @@
 }
 
-static GLhandleARB find_glsl_vshader(struct wined3d_shader_buffer *buffer, IWineD3DVertexShaderImpl *shader,
+static GLhandleARB find_glsl_vshader(const struct wined3d_context *context,
+        struct wined3d_shader_buffer *buffer, IWineD3DVertexShaderImpl *shader,
         const struct vs_compile_args *args)
 {
@@ -3986,5 +3991,5 @@
 
     shader_buffer_clear(buffer);
-    ret = shader_glsl_generate_vshader(shader, buffer, args);
+    ret = shader_glsl_generate_vshader(context, buffer, shader, args);
     shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
 
@@ -4002,10 +4007,11 @@
 
 /* GL locking is done by the caller */
-static void set_glsl_shader_program(IWineD3DDevice *iface, BOOL use_ps, BOOL use_vs) {
-    IWineD3DDeviceImpl *This               = (IWineD3DDeviceImpl *)iface;
-    struct shader_glsl_priv *priv          = This->shader_priv;
-    const struct wined3d_gl_info *gl_info  = &This->adapter->gl_info;
-    IWineD3DPixelShader  *pshader          = use_ps ? This->stateBlock->pixelShader : NULL;
-    IWineD3DVertexShader *vshader          = use_vs ? This->stateBlock->vertexShader : NULL;
+static void set_glsl_shader_program(const struct wined3d_context *context,
+        IWineD3DDeviceImpl *device, BOOL use_ps, BOOL use_vs)
+{
+    IWineD3DVertexShader *vshader = use_vs ? device->stateBlock->vertexShader : NULL;
+    IWineD3DPixelShader *pshader = use_ps ? device->stateBlock->pixelShader : NULL;
+    const struct wined3d_gl_info *gl_info = context->gl_info;
+    struct shader_glsl_priv *priv = device->shader_priv;
     struct glsl_shader_prog_link *entry    = NULL;
     GLhandleARB programId                  = 0;
@@ -4016,6 +4022,6 @@
     struct vs_compile_args vs_compile_args;
 
-    if (vshader) find_vs_compile_args((IWineD3DVertexShaderImpl *)vshader, This->stateBlock, &vs_compile_args);
-    if (pshader) find_ps_compile_args((IWineD3DPixelShaderImpl *)pshader, This->stateBlock, &ps_compile_args);
+    if (vshader) find_vs_compile_args((IWineD3DVertexShaderImpl *)vshader, device->stateBlock, &vs_compile_args);
+    if (pshader) find_ps_compile_args((IWineD3DPixelShaderImpl *)pshader, device->stateBlock, &ps_compile_args);
 
     entry = get_glsl_program_entry(priv, vshader, pshader, &vs_compile_args, &ps_compile_args);
@@ -4047,6 +4053,6 @@
     if (vshader)
     {
-        GLhandleARB vshader_id = find_glsl_vshader(&priv->shader_buffer, (IWineD3DVertexShaderImpl *)vshader,
-                &vs_compile_args);
+        GLhandleARB vshader_id = find_glsl_vshader(context, &priv->shader_buffer,
+                (IWineD3DVertexShaderImpl *)vshader, &vs_compile_args);
         WORD map = ((IWineD3DBaseShaderImpl *)vshader)->baseShader.reg_maps.input_registers;
         char tmp_name[10];
@@ -4089,6 +4095,6 @@
     if (pshader)
     {
-        GLhandleARB pshader_id = find_glsl_pshader(&priv->shader_buffer, (IWineD3DPixelShaderImpl *)pshader,
-                &ps_compile_args, &entry->np2Fixup_info);
+        GLhandleARB pshader_id = find_glsl_pshader(context, &priv->shader_buffer,
+                (IWineD3DPixelShaderImpl *)pshader, &ps_compile_args, &entry->np2Fixup_info);
         TRACE("Attaching GLSL shader object %u to program %u\n", pshader_id, programId);
         GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
@@ -4169,6 +4175,6 @@
      * won't change.
      */
-    if (vshader) shader_glsl_load_vsamplers(gl_info, This->texUnitMap, programId);
-    if (pshader) shader_glsl_load_psamplers(gl_info, This->texUnitMap, programId);
+    if (vshader) shader_glsl_load_vsamplers(gl_info, device->texUnitMap, programId);
+    if (pshader) shader_glsl_load_psamplers(gl_info, device->texUnitMap, programId);
 
     /* If the local constants do not have to be loaded with the environment constants,
@@ -4260,8 +4266,9 @@
 
 /* GL locking is done by the caller */
-static void shader_glsl_select(IWineD3DDevice *iface, BOOL usePS, BOOL useVS) {
-    IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
-    struct shader_glsl_priv *priv = This->shader_priv;
-    const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
+static void shader_glsl_select(const struct wined3d_context *context, BOOL usePS, BOOL useVS)
+{
+    IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice;
+    const struct wined3d_gl_info *gl_info = context->gl_info;
+    struct shader_glsl_priv *priv = device->shader_priv;
     GLhandleARB program_id = 0;
     GLenum old_vertex_color_clamp, current_vertex_color_clamp;
@@ -4269,5 +4276,5 @@
     old_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
 
-    if (useVS || usePS) set_glsl_shader_program(iface, usePS, useVS);
+    if (useVS || usePS) set_glsl_shader_program(context, device, usePS, useVS);
     else priv->glsl_program = NULL;
 
@@ -4291,6 +4298,7 @@
      * constants. This has to be done because it can't be guaranteed that sampler() (from state.c) is
      * called between selecting the shader and using it, which results in wrong fixup for some frames. */
-    if (priv->glsl_program && priv->glsl_program->np2Fixup_info) {
-        This->shader_backend->shader_load_np2fixup_constants(iface, usePS, useVS);
+    if (priv->glsl_program && priv->glsl_program->np2Fixup_info)
+    {
+        shader_glsl_load_np2fixup_constants((IWineD3DDevice *)device, usePS, useVS);
     }
 }
@@ -4333,5 +4341,6 @@
     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)This->baseShader.device;
     struct shader_glsl_priv *priv = device->shader_priv;
-    const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
+    const struct wined3d_context *context;
+    const struct wined3d_gl_info *gl_info;
     IWineD3DPixelShaderImpl *ps = NULL;
     IWineD3DVertexShaderImpl *vs = NULL;
@@ -4341,6 +4350,4 @@
      */
     char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
-
-    ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
 
     if(pshader) {
@@ -4355,8 +4362,11 @@
         }
 
+        context = ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
+        gl_info = context->gl_info;
+
         if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->pshader == iface)
         {
             ENTER_GL();
-            shader_glsl_select(This->baseShader.device, FALSE, FALSE);
+            shader_glsl_select(context, FALSE, FALSE);
             LEAVE_GL();
         }
@@ -4372,8 +4382,11 @@
         }
 
+        context = ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
+        gl_info = context->gl_info;
+
         if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->vshader == iface)
         {
             ENTER_GL();
-            shader_glsl_select(This->baseShader.device, FALSE, FALSE);
+            shader_glsl_select(context, FALSE, FALSE);
             LEAVE_GL();
         }
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/nvidia_texture_shader.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/nvidia_texture_shader.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/nvidia_texture_shader.c	(revision 22496)
@@ -43,5 +43,6 @@
 /* GL locking for state handlers is done by the caller. */
 
-static void nvts_activate_dimensions(DWORD stage, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void nvts_activate_dimensions(DWORD stage, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     BOOL bumpmap = FALSE;
 
@@ -463,5 +464,6 @@
 
 
-static void nvrc_colorop(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void nvrc_colorop(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     DWORD stage = (state - STATE_TEXTURESTAGE(0, 0)) / (WINED3D_HIGHEST_TEXTURE_STATE + 1);
     DWORD mapped_stage = stateblock->wineD3DDevice->texUnitMap[stage];
@@ -555,5 +557,6 @@
 }
 
-static void nvts_texdim(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void nvts_texdim(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     DWORD sampler = state - STATE_SAMPLER(0);
     DWORD mapped_stage = stateblock->wineD3DDevice->texUnitMap[sampler];
@@ -570,5 +573,6 @@
 }
 
-static void nvts_bumpenvmat(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void nvts_bumpenvmat(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     DWORD stage = (state - STATE_TEXTURESTAGE(0, 0)) / (WINED3D_HIGHEST_TEXTURE_STATE + 1);
     DWORD mapped_stage = stateblock->wineD3DDevice->texUnitMap[stage + 1];
@@ -597,5 +601,6 @@
 }
 
-static void nvrc_texfactor(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void nvrc_texfactor(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     float col[4];
     D3DCOLORTOGLFLOAT4(stateblock->renderState[WINED3DRS_TEXTUREFACTOR], col);
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/pixelshader.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/pixelshader.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/pixelshader.c	(revision 22496)
@@ -372,5 +372,5 @@
     IWineD3DBaseTextureImpl *tex;
 
-    memset(args, 0, sizeof(*args));
+    memset(args, 0, sizeof(*args)); /* FIXME: Make sure all bits are set */
     args->srgb_correction = stateblock->renderState[WINED3DRS_SRGBWRITEENABLE] ? 1 : 0;
     args->np2_fixup = 0;
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/query.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/query.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/query.c	(revision 22496)
@@ -77,49 +77,13 @@
         if (This->type == WINED3DQUERYTYPE_EVENT)
         {
-            WineQueryEventData *query_data = (WineQueryEventData *)This->extendedData;
-
-            if (query_data->ctx->tid != GetCurrentThreadId())
-            {
-                FIXME("Query was created in a different thread, skipping deletion.\n");
-            }
-            else
-            {
-                ActivateContext(This->wineD3DDevice, query_data->ctx->surface, CTXUSAGE_RESOURCELOAD);
-
-                ENTER_GL();
-
-                if (GL_SUPPORT(APPLE_FENCE))
-                {
-                    GL_EXTCALL(glDeleteFencesAPPLE(1, &query_data->fenceId));
-                    checkGLcall("glDeleteFencesAPPLE");
-                }
-                else if (GL_SUPPORT(NV_FENCE))
-                {
-                    GL_EXTCALL(glDeleteFencesNV(1, &query_data->fenceId));
-                    checkGLcall("glDeleteFencesNV");
-                }
-
-                LEAVE_GL();
-            }
-        }
-        else if (This->type == WINED3DQUERYTYPE_OCCLUSION && GL_SUPPORT(ARB_OCCLUSION_QUERY))
-        {
-            WineQueryOcclusionData *query_data = (WineQueryOcclusionData *)This->extendedData;
-
-            if (query_data->ctx->tid != GetCurrentThreadId())
-            {
-                FIXME("Query was created in a different thread, skipping deletion.\n");
-            }
-            else
-            {
-                ActivateContext(This->wineD3DDevice, query_data->ctx->surface, CTXUSAGE_RESOURCELOAD);
-
-                ENTER_GL();
-
-                GL_EXTCALL(glDeleteQueriesARB(1, &query_data->queryId));
-                checkGLcall("glDeleteQueriesARB");
-
-                LEAVE_GL();
-            }
+            struct wined3d_event_query *query = This->extendedData;
+
+            if (query->context) context_free_event_query(query);
+        }
+        else if (This->type == WINED3DQUERYTYPE_OCCLUSION)
+        {
+            struct wined3d_occlusion_query *query = This->extendedData;
+
+            if (query->context) context_free_occlusion_query(query);
         }
 
@@ -315,5 +279,5 @@
 static HRESULT  WINAPI IWineD3DOcclusionQueryImpl_GetData(IWineD3DQuery* iface, void* pData, DWORD dwSize, DWORD dwGetDataFlags) {
     IWineD3DQueryImpl *This = (IWineD3DQueryImpl *) iface;
-    WineQueryOcclusionData *query_data = (WineQueryOcclusionData *)This->extendedData;
+    struct wined3d_occlusion_query *query = This->extendedData;
     DWORD* data = pData;
     GLuint available;
@@ -323,4 +287,6 @@
     TRACE("(%p) : type D3DQUERY_OCCLUSION, pData %p, dwSize %#x, dwGetDataFlags %#x\n", This, pData, dwSize, dwGetDataFlags);
 
+    if (!query->context) This->state = QUERY_CREATED;
+
     if (This->state == QUERY_CREATED)
     {
@@ -345,5 +311,5 @@
     }
 
-    if (query_data->ctx->tid != GetCurrentThreadId())
+    if (query->context->tid != GetCurrentThreadId())
     {
         FIXME("%p Wrong thread, returning 1.\n", This);
@@ -352,9 +318,9 @@
     }
 
-    ActivateContext(This->wineD3DDevice, query_data->ctx->surface, CTXUSAGE_RESOURCELOAD);
+    ActivateContext(This->wineD3DDevice, query->context->current_rt, CTXUSAGE_RESOURCELOAD);
 
     ENTER_GL();
 
-    GL_EXTCALL(glGetQueryObjectuivARB(query_data->queryId, GL_QUERY_RESULT_AVAILABLE_ARB, &available));
+    GL_EXTCALL(glGetQueryObjectuivARB(query->id, GL_QUERY_RESULT_AVAILABLE_ARB, &available));
     checkGLcall("glGetQueryObjectuivARB(GL_QUERY_RESULT_AVAILABLE)");
     TRACE("(%p) : available %d.\n", This, available);
@@ -364,5 +330,5 @@
         if (data)
         {
-            GL_EXTCALL(glGetQueryObjectuivARB(query_data->queryId, GL_QUERY_RESULT_ARB, &samples));
+            GL_EXTCALL(glGetQueryObjectuivARB(query->id, GL_QUERY_RESULT_ARB, &samples));
             checkGLcall("glGetQueryObjectuivARB(GL_QUERY_RESULT)");
             TRACE("(%p) : Returning %d samples.\n", This, samples);
@@ -383,6 +349,6 @@
 static HRESULT  WINAPI IWineD3DEventQueryImpl_GetData(IWineD3DQuery* iface, void* pData, DWORD dwSize, DWORD dwGetDataFlags) {
     IWineD3DQueryImpl *This = (IWineD3DQueryImpl *) iface;
+    struct wined3d_event_query *query = This->extendedData;
     BOOL* data = pData;
-    WineQueryEventData *query_data = (WineQueryEventData *)This->extendedData;
 
     TRACE("(%p) : type D3DQUERY_EVENT, pData %p, dwSize %#x, dwGetDataFlags %#x\n", This, pData, dwSize, dwGetDataFlags);
@@ -390,5 +356,5 @@
     if (!pData || !dwSize) return S_OK;
 
-    if (query_data->ctx->tid != GetCurrentThreadId())
+    if (query->context->tid != GetCurrentThreadId())
     {
         /* See comment in IWineD3DQuery::Issue, event query codeblock */
@@ -399,5 +365,5 @@
     }
 
-    ActivateContext(This->wineD3DDevice, query_data->ctx->surface, CTXUSAGE_RESOURCELOAD);
+    ActivateContext(This->wineD3DDevice, query->context->current_rt, CTXUSAGE_RESOURCELOAD);
 
     ENTER_GL();
@@ -405,10 +371,10 @@
     if (GL_SUPPORT(APPLE_FENCE))
     {
-        *data = GL_EXTCALL(glTestFenceAPPLE(query_data->fenceId));
+        *data = GL_EXTCALL(glTestFenceAPPLE(query->id));
         checkGLcall("glTestFenceAPPLE");
     }
     else if (GL_SUPPORT(NV_FENCE))
     {
-        *data = GL_EXTCALL(glTestFenceNV(query_data->fenceId));
+        *data = GL_EXTCALL(glTestFenceNV(query->id));
         checkGLcall("glTestFenceNV");
     }
@@ -499,37 +465,43 @@
     if (dwIssueFlags & WINED3DISSUE_END)
     {
-        WineQueryEventData *query_data = (WineQueryEventData *)This->extendedData;
-
-        if (query_data->ctx->tid != GetCurrentThreadId())
-        {
-            /* GL fences can be used only from the context that created them,
-             * so if a different context is active, don't bother setting the query. The penalty
-             * of a context switch is most likely higher than the gain of a correct query result
-             *
-             * If the query is used from a different thread, don't bother creating a multithread
-             * context - there's no point in doing that as the query would be unusable anyway
-             */
-            WARN("Query context not active\n");
+        struct wined3d_event_query *query = This->extendedData;
+        struct wined3d_context *context;
+
+        if (query->context)
+        {
+            if (query->context->tid != GetCurrentThreadId())
+            {
+                context_free_event_query(query);
+                context = ActivateContext(This->wineD3DDevice, NULL, CTXUSAGE_RESOURCELOAD);
+                context_alloc_event_query(context, query);
+            }
+            else
+            {
+                ActivateContext(This->wineD3DDevice, query->context->current_rt, CTXUSAGE_RESOURCELOAD);
+            }
         }
         else
         {
-            ActivateContext(This->wineD3DDevice, query_data->ctx->surface, CTXUSAGE_RESOURCELOAD);
-
-            ENTER_GL();
-
-            if (GL_SUPPORT(APPLE_FENCE))
-            {
-                GL_EXTCALL(glSetFenceAPPLE(query_data->fenceId));
-                checkGLcall("glSetFenceAPPLE");
-            }
-            else if (GL_SUPPORT(NV_FENCE))
-            {
-                GL_EXTCALL(glSetFenceNV(query_data->fenceId, GL_ALL_COMPLETED_NV));
-                checkGLcall("glSetFenceNV");
-            }
-
-            LEAVE_GL();
-        }
-    } else if(dwIssueFlags & WINED3DISSUE_BEGIN) {
+            context = ActivateContext(This->wineD3DDevice, NULL, CTXUSAGE_RESOURCELOAD);
+            context_alloc_event_query(context, query);
+        }
+
+        ENTER_GL();
+
+        if (GL_SUPPORT(APPLE_FENCE))
+        {
+            GL_EXTCALL(glSetFenceAPPLE(query->id));
+            checkGLcall("glSetFenceAPPLE");
+        }
+        else if (GL_SUPPORT(NV_FENCE))
+        {
+            GL_EXTCALL(glSetFenceNV(query->id, GL_ALL_COMPLETED_NV));
+            checkGLcall("glSetFenceNV");
+        }
+
+        LEAVE_GL();
+    }
+    else if(dwIssueFlags & WINED3DISSUE_BEGIN)
+    {
         /* Started implicitly at device creation */
         ERR("Event query issued with START flag - what to do?\n");
@@ -550,36 +522,63 @@
     if (GL_SUPPORT(ARB_OCCLUSION_QUERY))
     {
-        WineQueryOcclusionData *query_data = (WineQueryOcclusionData *)This->extendedData;
-
-        if (query_data->ctx->tid != GetCurrentThreadId())
-        {
-            FIXME("Not the owning context, can't start query.\n");
-        }
-        else
-        {
-            ActivateContext(This->wineD3DDevice, query_data->ctx->surface, CTXUSAGE_RESOURCELOAD);
-
-            ENTER_GL();
-            /* This is allowed according to msdn and our tests. Reset the query and restart */
-            if (dwIssueFlags & WINED3DISSUE_BEGIN) {
-                if(This->state == QUERY_BUILDING) {
+        struct wined3d_occlusion_query *query = This->extendedData;
+        struct wined3d_context *context;
+
+        /* This is allowed according to msdn and our tests. Reset the query and restart */
+        if (dwIssueFlags & WINED3DISSUE_BEGIN)
+        {
+            if (This->state == QUERY_BUILDING)
+            {
+                if (query->context->tid != GetCurrentThreadId())
+                {
+                    FIXME("Wrong thread, can't restart query.\n");
+
+                    context_free_occlusion_query(query);
+                    context = ActivateContext(This->wineD3DDevice, NULL, CTXUSAGE_RESOURCELOAD);
+                    context_alloc_occlusion_query(context, query);
+                }
+                else
+                {
+                    ActivateContext(This->wineD3DDevice, query->context->current_rt, CTXUSAGE_RESOURCELOAD);
+
+                    ENTER_GL();
                     GL_EXTCALL(glEndQueryARB(GL_SAMPLES_PASSED_ARB));
                     checkGLcall("glEndQuery()");
+                    LEAVE_GL();
                 }
-
-                GL_EXTCALL(glBeginQueryARB(GL_SAMPLES_PASSED_ARB, query_data->queryId));
-                checkGLcall("glBeginQuery()");
             }
-            if (dwIssueFlags & WINED3DISSUE_END) {
-                /* Msdn says _END on a non-building occlusion query returns an error, but
-                 * our tests show that it returns OK. But OpenGL doesn't like it, so avoid
-                 * generating an error
-                 */
-                if(This->state == QUERY_BUILDING) {
+            else
+            {
+                if (query->context) context_free_occlusion_query(query);
+                context = ActivateContext(This->wineD3DDevice, NULL, CTXUSAGE_RESOURCELOAD);
+                context_alloc_occlusion_query(context, query);
+            }
+
+            ENTER_GL();
+            GL_EXTCALL(glBeginQueryARB(GL_SAMPLES_PASSED_ARB, query->id));
+            checkGLcall("glBeginQuery()");
+            LEAVE_GL();
+        }
+        if (dwIssueFlags & WINED3DISSUE_END) {
+            /* Msdn says _END on a non-building occlusion query returns an error, but
+             * our tests show that it returns OK. But OpenGL doesn't like it, so avoid
+             * generating an error
+             */
+            if (This->state == QUERY_BUILDING)
+            {
+                if (query->context->tid != GetCurrentThreadId())
+                {
+                    FIXME("Wrong thread, can't end query.\n");
+                }
+                else
+                {
+                    ActivateContext(This->wineD3DDevice, query->context->current_rt, CTXUSAGE_RESOURCELOAD);
+
+                    ENTER_GL();
                     GL_EXTCALL(glEndQueryARB(GL_SAMPLES_PASSED_ARB));
                     checkGLcall("glEndQuery()");
+                    LEAVE_GL();
                 }
             }
-            LEAVE_GL();
         }
     } else {
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/shader_sm4.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/shader_sm4.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/shader_sm4.c	(revision 22496)
@@ -62,4 +62,5 @@
     WINED3D_SM4_OP_DP4      = 0x11,
     WINED3D_SM4_OP_EXP      = 0x19,
+    WINED3D_SM4_OP_LOG      = 0x2f,
     WINED3D_SM4_OP_MOV      = 0x36,
     WINED3D_SM4_OP_MUL      = 0x38,
@@ -112,4 +113,5 @@
     {WINED3D_SM4_OP_DP4,    WINED3DSIH_DP4,         1,  2},
     {WINED3D_SM4_OP_EXP,    WINED3DSIH_EXP,         1,  1},
+    {WINED3D_SM4_OP_LOG,    WINED3DSIH_LOG,         1,  1},
     {WINED3D_SM4_OP_MOV,    WINED3DSIH_MOV,         1,  1},
     {WINED3D_SM4_OP_MUL,    WINED3DSIH_MUL,         1,  2},
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/state.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/state.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/state.c	(revision 22496)
@@ -48,7 +48,8 @@
 /* GL locking for state handlers is done by the caller. */
 
-static void state_blendop(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context);
-
-static void state_nogl(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_blendop(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context);
+
+static void state_nogl(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     /* Used for states which are not mapped to a gl state as-is, but used somehow different,
      * e.g as a parameter for drawing, or which are unimplemented in windows d3d
@@ -63,5 +64,6 @@
 }
 
-static void state_undefined(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_undefined(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     /* Print a WARN, this allows the stateblock code to loop over all states to generate a display
      * list without causing confusing terminal output. Deliberately no special debug name here
@@ -71,5 +73,6 @@
 }
 
-static void state_fillmode(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_fillmode(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     WINED3DFILLMODE Value = stateblock->renderState[WINED3DRS_FILLMODE];
 
@@ -92,5 +95,6 @@
 }
 
-static void state_lighting(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_lighting(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     /* Lighting is not enabled if transformed vertices are drawn
      * but lighting does not affect the stream sources, so it is not grouped for performance reasons.
@@ -114,5 +118,6 @@
 }
 
-static void state_zenable(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_zenable(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     /* No z test without depth stencil buffers */
     if(stateblock->wineD3DDevice->stencilBufferTarget == NULL) {
@@ -142,5 +147,6 @@
 }
 
-static void state_cullmode(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_cullmode(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     /* glFrontFace() is set in context.c at context init and on an offscreen / onscreen rendering
      * switch
@@ -168,5 +174,6 @@
 }
 
-static void state_shademode(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_shademode(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     switch ((WINED3DSHADEMODE) stateblock->renderState[WINED3DRS_SHADEMODE]) {
         case WINED3DSHADE_FLAT:
@@ -186,5 +193,6 @@
 }
 
-static void state_ditherenable(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_ditherenable(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if (stateblock->renderState[WINED3DRS_DITHERENABLE]) {
         glEnable(GL_DITHER);
@@ -196,5 +204,6 @@
 }
 
-static void state_zwritenable(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_zwritenable(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     /* TODO: Test if in d3d z writing is enabled even if ZENABLE is off. If yes,
      * this has to be merged with ZENABLE and ZFUNC
@@ -209,5 +218,6 @@
 }
 
-static void state_zfunc(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_zfunc(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     int glParm = CompareFunc(stateblock->renderState[WINED3DRS_ZFUNC]);
 
@@ -232,5 +242,6 @@
 }
 
-static void state_ambient(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_ambient(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     float col[4];
     D3DCOLORTOGLFLOAT4(stateblock->renderState[WINED3DRS_AMBIENT], col);
@@ -241,5 +252,6 @@
 }
 
-static void state_blend(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_blend(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     int srcBlend = GL_ZERO;
     int dstBlend = GL_ZERO;
@@ -453,9 +465,11 @@
 }
 
-static void state_blendfactor_w(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_blendfactor_w(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     WARN("Unsupported in local OpenGL implementation: glBlendColorEXT\n");
 }
 
-static void state_blendfactor(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_blendfactor(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     float col[4];
 
@@ -466,5 +480,6 @@
 }
 
-static void state_alpha(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_alpha(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     int glParm = 0;
     float ref;
@@ -531,5 +546,6 @@
 }
 
-static void state_clipping(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_clipping(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     DWORD enable  = 0xFFFFFFFF;
     DWORD disable = 0x00000000;
@@ -599,9 +615,11 @@
 }
 
-static void state_blendop_w(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_blendop_w(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     WARN("Unsupported in local OpenGL implementation: glBlendEquation\n");
 }
 
-static void state_blendop(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_blendop(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     int blendEquation = GL_FUNC_ADD;
     int blendEquationAlpha = GL_FUNC_ADD;
@@ -644,6 +662,6 @@
 }
 
-static void
-state_specularenable(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_specularenable(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     /* Originally this used glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL,GL_SEPARATE_SPECULAR_COLOR)
      * and (GL_LIGHT_MODEL_COLOR_CONTROL,GL_SINGLE_COLOR) to swap between enabled/disabled
@@ -744,5 +762,6 @@
 }
 
-static void state_texfactor(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_texfactor(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     unsigned int i;
 
@@ -778,6 +797,6 @@
 }
 
-static void
-state_stencil(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_stencil(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     DWORD onesided_enable = FALSE;
     DWORD twosided_enable = FALSE;
@@ -868,5 +887,6 @@
 }
 
-static void state_stencilwrite2s(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_stencilwrite2s(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     DWORD mask;
 
@@ -886,5 +906,6 @@
 }
 
-static void state_stencilwrite(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_stencilwrite(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     DWORD mask;
 
@@ -899,5 +920,6 @@
 }
 
-static void state_fog_vertexpart(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_fog_vertexpart(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
 
     TRACE("state %#x, stateblock %p, context %p\n", state, stateblock, context);
@@ -936,5 +958,6 @@
 }
 
-void state_fogstartend(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+void state_fogstartend(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     float fogstart, fogend;
     union {
@@ -985,5 +1008,6 @@
 }
 
-void state_fog_fragpart(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+void state_fog_fragpart(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     enum fogsource new_source;
 
@@ -1126,5 +1150,6 @@
 }
 
-static void state_rangefog_w(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_rangefog_w(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(stateblock->renderState[WINED3DRS_RANGEFOGENABLE]) {
         WARN("Range fog enabled, but not supported by this opengl implementation\n");
@@ -1132,5 +1157,6 @@
 }
 
-static void state_rangefog(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_rangefog(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(stateblock->renderState[WINED3DRS_RANGEFOGENABLE]) {
         glFogi(GL_FOG_DISTANCE_MODE_NV, GL_EYE_RADIAL_NV);
@@ -1142,5 +1168,6 @@
 }
 
-void state_fogcolor(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+void state_fogcolor(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     float col[4];
     D3DCOLORTOGLFLOAT4(stateblock->renderState[WINED3DRS_FOGCOLOR], col);
@@ -1149,5 +1176,6 @@
 }
 
-void state_fogdensity(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+void state_fogdensity(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     union {
         DWORD d;
@@ -1159,5 +1187,6 @@
 }
 
-static void state_colormat(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_colormat(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
     GLenum Parm = 0;
@@ -1271,5 +1300,6 @@
 }
 
-static void state_linepattern(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_linepattern(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     union {
         DWORD                 d;
@@ -1291,5 +1321,6 @@
 }
 
-static void state_zbias(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_zbias(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     union {
         DWORD d;
@@ -1319,5 +1350,6 @@
 
 
-static void state_normalize(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_normalize(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(isStateDirty(context, STATE_VDECL)) {
         return;
@@ -1339,5 +1371,6 @@
 }
 
-static void state_psizemin_w(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_psizemin_w(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     union {
         DWORD d;
@@ -1358,5 +1391,6 @@
 }
 
-static void state_psizemin_ext(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_psizemin_ext(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     union {
         DWORD d;
@@ -1378,5 +1412,6 @@
 }
 
-static void state_psizemin_arb(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_psizemin_arb(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     union {
         DWORD d;
@@ -1398,5 +1433,6 @@
 }
 
-static void state_pscale(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_pscale(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     /* TODO: Group this with the viewport */
     /*
@@ -1468,5 +1504,6 @@
 }
 
-static void state_colorwrite(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_colorwrite(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     DWORD Value = stateblock->renderState[WINED3DRS_COLORWRITEENABLE];
 
@@ -1493,5 +1530,6 @@
 }
 
-static void state_localviewer(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_localviewer(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(stateblock->renderState[WINED3DRS_LOCALVIEWER]) {
         glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1);
@@ -1503,5 +1541,6 @@
 }
 
-static void state_lastpixel(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_lastpixel(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(stateblock->renderState[WINED3DRS_LASTPIXEL]) {
         TRACE("Last Pixel Drawing Enabled\n");
@@ -1517,5 +1556,6 @@
 }
 
-static void state_pointsprite_w(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_pointsprite_w(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     BOOL warned = FALSE;
     /* TODO: NV_POINT_SPRITE */
@@ -1527,5 +1567,6 @@
 }
 
-static void state_pointsprite(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_pointsprite(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if (stateblock->renderState[WINED3DRS_POINTSPRITEENABLE]) {
         BOOL warned = FALSE;
@@ -1545,5 +1586,6 @@
 }
 
-static void state_wrap(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_wrap(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     /**
      http://www.cosc.brocku.ca/Offerings/3P98/course/lectures/texture/
@@ -1575,5 +1617,6 @@
 }
 
-static void state_msaa_w(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_msaa_w(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(stateblock->renderState[WINED3DRS_MULTISAMPLEANTIALIAS]) {
         WARN("Multisample antialiasing not supported by gl\n");
@@ -1581,5 +1624,6 @@
 }
 
-static void state_msaa(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_msaa(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(stateblock->renderState[WINED3DRS_MULTISAMPLEANTIALIAS]) {
         glEnable(GL_MULTISAMPLE_ARB);
@@ -1591,5 +1635,6 @@
 }
 
-static void state_scissor(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_scissor(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(stateblock->renderState[WINED3DRS_SCISSORTESTENABLE]) {
         glEnable(GL_SCISSOR_TEST);
@@ -1601,5 +1646,6 @@
 }
 
-static void state_depthbias(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_depthbias(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     union {
         DWORD d;
@@ -1620,5 +1666,6 @@
 }
 
-static void state_perspective(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_perspective(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if (stateblock->renderState[WINED3DRS_TEXTUREPERSPECTIVE]) {
         glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
@@ -1630,5 +1677,6 @@
 }
 
-static void state_stippledalpha(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_stippledalpha(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     TRACE("Stub\n");
     if (stateblock->renderState[WINED3DRS_STIPPLEDALPHA])
@@ -1636,5 +1684,6 @@
 }
 
-static void state_antialias(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_antialias(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     TRACE("Stub\n");
     if (stateblock->renderState[WINED3DRS_ANTIALIAS])
@@ -1642,5 +1691,6 @@
 }
 
-static void state_multisampmask(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_multisampmask(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     TRACE("Stub\n");
     if (stateblock->renderState[WINED3DRS_MULTISAMPLEMASK] != 0xFFFFFFFF)
@@ -1648,5 +1698,6 @@
 }
 
-static void state_patchedgestyle(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_patchedgestyle(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     TRACE("Stub\n");
     if (stateblock->renderState[WINED3DRS_PATCHEDGESTYLE] != WINED3DPATCHEDGE_DISCRETE)
@@ -1654,5 +1705,6 @@
 }
 
-static void state_patchsegments(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_patchsegments(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     union {
         DWORD d;
@@ -1674,5 +1726,6 @@
 }
 
-static void state_positiondegree(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_positiondegree(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     TRACE("Stub\n");
     if (stateblock->renderState[WINED3DRS_POSITIONDEGREE] != WINED3DDEGREE_CUBIC)
@@ -1680,5 +1733,6 @@
 }
 
-static void state_normaldegree(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_normaldegree(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     TRACE("Stub\n");
     if (stateblock->renderState[WINED3DRS_NORMALDEGREE] != WINED3DDEGREE_LINEAR)
@@ -1686,5 +1740,6 @@
 }
 
-static void state_tessellation(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_tessellation(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     TRACE("Stub\n");
     if(stateblock->renderState[WINED3DRS_ENABLEADAPTIVETESSELLATION])
@@ -1692,5 +1747,6 @@
 }
 
-static void state_wrapu(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_wrapu(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(stateblock->renderState[WINED3DRS_WRAPU]) {
         FIXME("Render state WINED3DRS_WRAPU not implemented yet\n");
@@ -1698,5 +1754,6 @@
 }
 
-static void state_wrapv(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_wrapv(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(stateblock->renderState[WINED3DRS_WRAPV]) {
         FIXME("Render state WINED3DRS_WRAPV not implemented yet\n");
@@ -1704,5 +1761,6 @@
 }
 
-static void state_monoenable(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_monoenable(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(stateblock->renderState[WINED3DRS_MONOENABLE]) {
         FIXME("Render state WINED3DRS_MONOENABLE not implemented yet\n");
@@ -1710,5 +1768,6 @@
 }
 
-static void state_rop2(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_rop2(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(stateblock->renderState[WINED3DRS_ROP2]) {
         FIXME("Render state WINED3DRS_ROP2 not implemented yet\n");
@@ -1716,5 +1775,6 @@
 }
 
-static void state_planemask(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_planemask(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(stateblock->renderState[WINED3DRS_PLANEMASK]) {
         FIXME("Render state WINED3DRS_PLANEMASK not implemented yet\n");
@@ -1722,5 +1782,6 @@
 }
 
-static void state_subpixel(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_subpixel(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(stateblock->renderState[WINED3DRS_SUBPIXEL]) {
         FIXME("Render state WINED3DRS_SUBPIXEL not implemented yet\n");
@@ -1728,5 +1789,6 @@
 }
 
-static void state_subpixelx(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_subpixelx(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(stateblock->renderState[WINED3DRS_SUBPIXELX]) {
         FIXME("Render state WINED3DRS_SUBPIXELX not implemented yet\n");
@@ -1734,5 +1796,6 @@
 }
 
-static void state_stippleenable(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_stippleenable(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(stateblock->renderState[WINED3DRS_STIPPLEENABLE]) {
         FIXME("Render state WINED3DRS_STIPPLEENABLE not implemented yet\n");
@@ -1740,5 +1803,6 @@
 }
 
-static void state_bordercolor(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_bordercolor(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(stateblock->renderState[WINED3DRS_BORDERCOLOR]) {
         FIXME("Render state WINED3DRS_BORDERCOLOR not implemented yet\n");
@@ -1746,5 +1810,6 @@
 }
 
-static void state_mipmaplodbias(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_mipmaplodbias(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(stateblock->renderState[WINED3DRS_MIPMAPLODBIAS]) {
         FIXME("Render state WINED3DRS_MIPMAPLODBIAS not implemented yet\n");
@@ -1752,5 +1817,6 @@
 }
 
-static void state_anisotropy(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_anisotropy(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(stateblock->renderState[WINED3DRS_ANISOTROPY]) {
         FIXME("Render state WINED3DRS_ANISOTROPY not implemented yet\n");
@@ -1758,5 +1824,6 @@
 }
 
-static void state_flushbatch(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_flushbatch(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(stateblock->renderState[WINED3DRS_FLUSHBATCH]) {
         FIXME("Render state WINED3DRS_FLUSHBATCH not implemented yet\n");
@@ -1764,5 +1831,6 @@
 }
 
-static void state_translucentsi(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_translucentsi(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(stateblock->renderState[WINED3DRS_TRANSLUCENTSORTINDEPENDENT]) {
         FIXME("Render state WINED3DRS_TRANSLUCENTSORTINDEPENDENT not implemented yet\n");
@@ -1770,5 +1838,6 @@
 }
 
-static void state_extents(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_extents(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(stateblock->renderState[WINED3DRS_EXTENTS]) {
         FIXME("Render state WINED3DRS_EXTENTS not implemented yet\n");
@@ -1776,5 +1845,6 @@
 }
 
-static void state_ckeyblend(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_ckeyblend(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(stateblock->renderState[WINED3DRS_COLORKEYBLENDENABLE]) {
         FIXME("Render state WINED3DRS_COLORKEYBLENDENABLE not implemented yet\n");
@@ -2855,5 +2925,6 @@
 
 
-static void tex_colorop(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void tex_colorop(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     DWORD stage = (state - STATE_TEXTURESTAGE(0, 0)) / (WINED3D_HIGHEST_TEXTURE_STATE + 1);
     DWORD mapped_stage = stateblock->wineD3DDevice->texUnitMap[stage];
@@ -2913,5 +2984,6 @@
 }
 
-void tex_alphaop(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+void tex_alphaop(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     DWORD stage = (state - STATE_TEXTURESTAGE(0, 0)) / (WINED3D_HIGHEST_TEXTURE_STATE + 1);
     DWORD mapped_stage = stateblock->wineD3DDevice->texUnitMap[stage];
@@ -3012,5 +3084,6 @@
 }
 
-static void transform_texture(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void transform_texture(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     DWORD texUnit = (state - STATE_TEXTURESTAGE(0, 0)) / (WINED3D_HIGHEST_TEXTURE_STATE + 1);
     DWORD mapped_stage = stateblock->wineD3DDevice->texUnitMap[texUnit];
@@ -3113,5 +3186,6 @@
 }
 
-static void tex_coordindex(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void tex_coordindex(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     DWORD stage = (state - STATE_TEXTURESTAGE(0, 0)) / (WINED3D_HIGHEST_TEXTURE_STATE + 1);
     DWORD mapped_stage = stateblock->wineD3DDevice->texUnitMap[stage];
@@ -3286,5 +3360,6 @@
 }
 
-static void shaderconstant(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void shaderconstant(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
 
@@ -3297,8 +3372,9 @@
     }
 
-    device->shader_backend->shader_load_constants((IWineD3DDevice *)device, use_ps(stateblock), use_vs(stateblock));
-}
-
-static void tex_bumpenvlscale(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+    device->shader_backend->shader_load_constants(context, use_ps(stateblock), use_vs(stateblock));
+}
+
+static void tex_bumpenvlscale(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     DWORD stage = (state - STATE_TEXTURESTAGE(0, 0)) / (WINED3D_HIGHEST_TEXTURE_STATE + 1);
 
@@ -3315,5 +3391,6 @@
 }
 
-static void sampler_texmatrix(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void sampler_texmatrix(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     const DWORD sampler = state - STATE_SAMPLER(0);
     IWineD3DBaseTexture *texture = stateblock->textures[sampler];
@@ -3341,5 +3418,6 @@
 }
 
-static void sampler(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void sampler(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     DWORD sampler = state - STATE_SAMPLER(0);
     DWORD mapped_stage = stateblock->wineD3DDevice->texUnitMap[sampler];
@@ -3413,5 +3491,6 @@
 }
 
-void apply_pixelshader(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+void apply_pixelshader(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
     BOOL use_pshader = use_ps(stateblock);
@@ -3450,5 +3529,5 @@
 
     if(!isStateDirty(context, device->StateTable[STATE_VSHADER].representative)) {
-        device->shader_backend->shader_select((IWineD3DDevice *)stateblock->wineD3DDevice, use_pshader, use_vshader);
+        device->shader_backend->shader_select(context, use_pshader, use_vshader);
 
         if (!isStateDirty(context, STATE_VERTEXSHADERCONSTANT) && (use_vshader || use_pshader)) {
@@ -3458,5 +3537,6 @@
 }
 
-static void shader_bumpenvmat(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void shader_bumpenvmat(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     DWORD stage = (state - STATE_TEXTURESTAGE(0, 0)) / (WINED3D_HIGHEST_TEXTURE_STATE + 1);
     if(stateblock->pixelShader && stage != 0 &&
@@ -3472,5 +3552,6 @@
 }
 
-static void transform_world(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void transform_world(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     /* This function is called by transform_view below if the view matrix was changed too
      *
@@ -3500,5 +3581,6 @@
 }
 
-static void clipplane(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void clipplane(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     UINT index = state - STATE_CLIPPLANE(0);
 
@@ -3520,7 +3602,5 @@
         glPushMatrix();
         glLoadIdentity();
-        if(stateblock->wineD3DDevice->render_offscreen) {
-            glScalef(1.0f, -1.0f, 1.0f);
-        }
+        if (context->render_offscreen) glScalef(1.0f, -1.0f, 1.0f);
     }
 
@@ -3536,5 +3616,6 @@
 }
 
-static void transform_worldex(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void transform_worldex(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     UINT matrix = state - STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0));
     GLenum glMat;
@@ -3575,5 +3656,6 @@
 }
 
-static void state_vertexblend_w(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_vertexblend_w(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     static BOOL once = FALSE;
 
@@ -3594,5 +3676,6 @@
 }
 
-static void state_vertexblend(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void state_vertexblend(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     WINED3DVERTEXBLENDFLAGS val = stateblock->renderState[WINED3DRS_VERTEXBLEND];
 
@@ -3636,5 +3719,6 @@
 }
 
-static void transform_view(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void transform_view(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     unsigned int k;
 
@@ -3693,5 +3777,6 @@
 }
 
-static void transform_projection(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void transform_projection(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     glMatrixMode(GL_PROJECTION);
     checkGLcall("glMatrixMode(GL_PROJECTION)");
@@ -3732,5 +3817,6 @@
              */
             TRACE("Calling glOrtho with %f, %f, %f, %f\n", width, height, -minZ, -maxZ);
-            if(stateblock->wineD3DDevice->render_offscreen) {
+            if (context->render_offscreen)
+            {
                 glOrtho(X, X + width, -Y, -Y - height, -minZ, -maxZ);
             } else {
@@ -3746,5 +3832,6 @@
              */
             TRACE("Calling glOrtho with %f, %f, %f, %f\n", width, height, 1.0, -1.0);
-            if(stateblock->wineD3DDevice->render_offscreen) {
+            if (context->render_offscreen)
+            {
                 glOrtho(X, X + width, -Y, -Y - height, 0.0, -1.0);
             } else {
@@ -3759,5 +3846,6 @@
         /* D3D texture coordinates are flipped compared to OpenGL ones, so
          * render everything upside down when rendering offscreen. */
-        if (stateblock->wineD3DDevice->render_offscreen) {
+        if (context->render_offscreen)
+        {
             glScalef(1.0f, -1.0f, 1.0f);
             checkGLcall("glScalef");
@@ -3801,5 +3889,6 @@
          */
 
-        if (stateblock->wineD3DDevice->render_offscreen) {
+        if (context->render_offscreen)
+        {
             /* D3D texture coordinates are flipped compared to OpenGL ones, so
              * render everything upside down when rendering offscreen. */
@@ -3836,5 +3925,5 @@
 }
 
-static inline void unload_numbered_array(IWineD3DStateBlockImpl *stateblock, WineD3DContext *context, int i)
+static inline void unload_numbered_array(IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context, int i)
 {
     GL_EXTCALL(glDisableVertexAttribArrayARB(i));
@@ -3847,5 +3936,5 @@
  * TODO: Only load / unload arrays if we have to.
  */
-static inline void unloadNumberedArrays(IWineD3DStateBlockImpl *stateblock, WineD3DContext *context)
+static inline void unloadNumberedArrays(IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
 {
     /* disable any attribs (this is the same for both GLSL and ARB modes) */
@@ -3864,5 +3953,5 @@
 
 static inline void loadNumberedArrays(IWineD3DStateBlockImpl *stateblock,
-        const struct wined3d_stream_info *stream_info, WineD3DContext *context)
+        const struct wined3d_stream_info *stream_info, struct wined3d_context *context)
 {
     GLuint curVBO = GL_SUPPORT(ARB_VERTEX_BUFFER_OBJECT) ? ~0U : 0;
@@ -4295,5 +4384,6 @@
 }
 
-static void streamsrc(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void streamsrc(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
     BOOL fixup = FALSE;
@@ -4374,5 +4464,6 @@
 }
 
-static void vertexdeclaration(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void vertexdeclaration(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     BOOL updateFog = FALSE;
     BOOL useVertexShaderFunction = use_vs(stateblock);
@@ -4411,5 +4502,5 @@
          */
         if (useVertexShaderFunction) {
-            device->posFixup[1] = device->render_offscreen ? -1.0f : 1.0f;
+            device->posFixup[1] = context->render_offscreen ? -1.0f : 1.0f;
             device->posFixup[3] = -device->posFixup[1] / stateblock->viewport.Height;
         }
@@ -4507,5 +4598,5 @@
      */
     if (!isStateDirty(context, STATE_PIXELSHADER)) {
-        device->shader_backend->shader_select((IWineD3DDevice *)device, usePixelShaderFunction, useVertexShaderFunction);
+        device->shader_backend->shader_select(context, usePixelShaderFunction, useVertexShaderFunction);
 
         if (!isStateDirty(context, STATE_VERTEXSHADERCONSTANT) && (useVertexShaderFunction || usePixelShaderFunction)) {
@@ -4529,5 +4620,6 @@
 }
 
-static void viewport_miscpart(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void viewport_miscpart(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     UINT width, height;
     IWineD3DSurfaceImpl *target;
@@ -4537,5 +4629,6 @@
     /* Note: GL requires lower left, DirectX supplies upper left. This is reversed when using offscreen rendering
      */
-    if(stateblock->wineD3DDevice->render_offscreen) {
+    if (context->render_offscreen)
+    {
         glViewport(stateblock->viewport.X,
                    stateblock->viewport.Y,
@@ -4543,5 +4636,5 @@
     } else {
         target = (IWineD3DSurfaceImpl *) stateblock->wineD3DDevice->render_targets[0];
-        target->get_drawable_size(target, &width, &height);
+        target->get_drawable_size(context, &width, &height);
 
         glViewport(stateblock->viewport.X,
@@ -4553,5 +4646,6 @@
 }
 
-static void viewport_vertexpart(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void viewport_vertexpart(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     stateblock->wineD3DDevice->posFixup[2] = 1.0f / stateblock->viewport.Width;
     stateblock->wineD3DDevice->posFixup[3] = -stateblock->wineD3DDevice->posFixup[1] / stateblock->viewport.Height;
@@ -4564,5 +4658,6 @@
 }
 
-static void light(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void light(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     UINT Index = state - STATE_ACTIVELIGHT(0);
     const PLIGHTINFOEL *lightInfo = stateblock->activeLights[Index];
@@ -4679,5 +4774,6 @@
 }
 
-static void scissorrect(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void scissorrect(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     RECT *pRect = &stateblock->scissorRect;
     UINT height;
@@ -4685,5 +4781,5 @@
     IWineD3DSurfaceImpl *target = (IWineD3DSurfaceImpl *) stateblock->wineD3DDevice->render_targets[0];
 
-    target->get_drawable_size(target, &width, &height);
+    target->get_drawable_size(context, &width, &height);
     /* Warning: glScissor uses window coordinates, not viewport coordinates, so our viewport correction does not apply
      * Warning2: Even in windowed mode the coords are relative to the window, not the screen
@@ -4692,5 +4788,6 @@
           pRect->right - pRect->left, pRect->bottom - pRect->top);
 
-    if (stateblock->wineD3DDevice->render_offscreen) {
+    if (context->render_offscreen)
+    {
         glScissor(pRect->left, pRect->top, pRect->right - pRect->left, pRect->bottom - pRect->top);
     } else {
@@ -4700,5 +4797,6 @@
 }
 
-static void indexbuffer(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void indexbuffer(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(stateblock->streamIsUP || stateblock->pIndexData == NULL ) {
         GL_EXTCALL(glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0));
@@ -4709,6 +4807,8 @@
 }
 
-static void frontface(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
-    if(stateblock->wineD3DDevice->render_offscreen) {
+static void frontface(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
+    if (context->render_offscreen)
+    {
         glFrontFace(GL_CCW);
         checkGLcall("glFrontFace(GL_CCW)");
@@ -5479,10 +5579,12 @@
 }
 
-static void multistate_apply_2(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void multistate_apply_2(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     stateblock->wineD3DDevice->multistate_funcs[state][0](state, stateblock, context);
     stateblock->wineD3DDevice->multistate_funcs[state][1](state, stateblock, context);
 }
 
-static void multistate_apply_3(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+static void multistate_apply_3(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     stateblock->wineD3DDevice->multistate_funcs[state][0](state, stateblock, context);
     stateblock->wineD3DDevice->multistate_funcs[state][1](state, stateblock, context);
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/stateblock.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/stateblock.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/stateblock.c	(revision 22496)
@@ -367,5 +367,5 @@
             BOOL updated = FALSE;
             PLIGHTINFOEL *src = LIST_ENTRY(e, PLIGHTINFOEL, entry), *realLight;
-            if(!src->changed || !src->enabledChanged) continue;
+            if (!src->changed && !src->enabledChanged) continue;
 
             /* Look up the light in the destination */
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/surface.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/surface.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/surface.c	(revision 22496)
@@ -59,5 +59,5 @@
     if (device->render_targets && device->render_targets[0])
     {
-        ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+        ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
     }
 
@@ -510,64 +510,46 @@
     const struct GlPixelFormatDesc *format_desc = This->resource.format_desc;
 
+    TRACE("This %p, internal %#x, width %d, height %d, format %#x, type %#x, data %p.\n",
+            This, internal, width, height, format, type, data);
+    TRACE("target %#x, level %u, resource size %u.\n",
+            This->texture_target, This->texture_level, This->resource.size);
+
     if (format_desc->heightscale != 1.0f && format_desc->heightscale != 0.0f) height *= format_desc->heightscale;
 
+    ENTER_GL();
+
+    if (This->Flags & SFLAG_PBO)
+    {
+        GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
+        checkGLcall("glBindBufferARB");
+
+        TRACE("(%p) pbo: %#x, data: %p.\n", This, This->pbo, data);
+        data = NULL;
+    }
+
     if (format_desc->Flags & WINED3DFMT_FLAG_COMPRESSED)
     {
-        /* glCompressedTexSubImage2D() for uploading and glTexImage2D() for
-         * allocating does not work well on some drivers (r200 dri, MacOS ATI
-         * driver). glCompressedTexImage2D() does not accept NULL pointers. So
-         * for compressed textures surface_allocate_surface() does nothing,
-         * and this function uses glCompressedTexImage2D() instead of
-         * glCompressedTexSubImage2D(). */
-        TRACE("(%p) : Calling glCompressedTexImage2DARB w %u, h %u, data %p.\n", This, width, height, data);
-
-        ENTER_GL();
-
-        if (This->Flags & SFLAG_PBO)
-        {
-            GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
-            checkGLcall("glBindBufferARB");
-
-            TRACE("(%p) pbo: %#x, data: %p.\n", This, This->pbo, data);
-
-            GL_EXTCALL(glCompressedTexImage2DARB(This->texture_target, This->texture_level,
-                    internal, width, height, 0 /* border */, This->resource.size, NULL));
-            checkGLcall("glCompressedTexImage2DARB");
-
-            GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
-            checkGLcall("glBindBufferARB");
-        }
-        else
-        {
-            GL_EXTCALL(glCompressedTexImage2DARB(This->texture_target, This->texture_level,
-                    internal, width, height, 0 /* border */, This->resource.size, data));
-            checkGLcall("glCompressedTexSubImage2D");
-        }
-
-        LEAVE_GL();
+        TRACE("Calling glCompressedTexSubImage2DARB.\n");
+
+        GL_EXTCALL(glCompressedTexSubImage2DARB(This->texture_target, This->texture_level,
+                0, 0, width, height, internal, This->resource.size, data));
+        checkGLcall("glCompressedTexSubImage2DARB");
     }
     else
     {
-        TRACE("(%p) : Calling glTexSubImage2D w %d,  h %d, data, %p\n", This, width, height, data);
-        ENTER_GL();
-
-        if(This->Flags & SFLAG_PBO) {
-            GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
-            checkGLcall("glBindBufferARB");
-            TRACE("(%p) pbo: %#x, data: %p\n", This, This->pbo, data);
-
-            glTexSubImage2D(This->texture_target, This->texture_level, 0, 0, width, height, format, type, NULL);
-            checkGLcall("glTexSubImage2D");
-
-            GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
-            checkGLcall("glBindBufferARB");
-        }
-        else {
-            glTexSubImage2D(This->texture_target, This->texture_level, 0, 0, width, height, format, type, data);
-            checkGLcall("glTexSubImage2D");
-        }
-
-        LEAVE_GL();
-    }
+        TRACE("Calling glTexSubImage2D.\n");
+
+        glTexSubImage2D(This->texture_target, This->texture_level,
+                0, 0, width, height, format, type, data);
+        checkGLcall("glTexSubImage2D");
+    }
+
+    if (This->Flags & SFLAG_PBO)
+    {
+        GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
+        checkGLcall("glBindBufferARB");
+    }
+
+    LEAVE_GL();
 }
 
@@ -585,25 +567,4 @@
             This, This->texture_target, This->texture_level, debug_d3dformat(format_desc->format),
             internal, width, height, format, type);
-
-    if (format_desc->Flags & WINED3DFMT_FLAG_COMPRESSED)
-    {
-        /* glCompressedTexImage2D does not accept NULL pointers, so we cannot allocate a compressed texture without uploading data */
-        TRACE("Not allocating compressed surfaces, surface_upload_data will specify them\n");
-
-        /* We have to point GL to the client storage memory here, because upload_data might use a PBO. This means a double upload
-         * once, unfortunately
-         */
-        if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
-            /* Neither NONPOW2, DIBSECTION nor OVERSIZE flags can be set on compressed textures */
-            This->Flags |= SFLAG_CLIENT;
-            mem = (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
-            ENTER_GL();
-            GL_EXTCALL(glCompressedTexImage2DARB(This->texture_target, This->texture_level, internal,
-                    width, height, 0 /* border */, This->resource.size, mem));
-            LEAVE_GL();
-        }
-
-        return;
-    }
 
     ENTER_GL();
@@ -631,6 +592,16 @@
         }
     }
-    glTexImage2D(This->texture_target, This->texture_level, internal, width, height, 0, format, type, mem);
-    checkGLcall("glTexImage2D");
+
+    if (format_desc->Flags & WINED3DFMT_FLAG_COMPRESSED && mem)
+    {
+        GL_EXTCALL(glCompressedTexImage2DARB(This->texture_target, This->texture_level,
+                internal, width, height, 0, This->resource.size, mem));
+    }
+    else
+    {
+        glTexImage2D(This->texture_target, This->texture_level,
+                internal, width, height, 0, format, type, mem);
+        checkGLcall("glTexImage2D");
+    }
 
     if(enable_client_storage) {
@@ -788,5 +759,5 @@
         IWineD3DBaseTextureImpl *tex_impl = (IWineD3DBaseTextureImpl *) baseTexture;
         TRACE("Passing to container\n");
-        tex_impl->baseTexture.internal_preload(baseTexture, SRGB_RGB);
+        tex_impl->baseTexture.internal_preload(baseTexture, srgb);
         IWineD3DBaseTexture_Release(baseTexture);
     } else {
@@ -794,5 +765,5 @@
 
         if(!device->isInDraw) {
-            ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+            ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
         }
 
@@ -880,5 +851,5 @@
     This->Flags &= ~(SFLAG_ALLOCATED | SFLAG_SRGBALLOCATED);
 
-    ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+    ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
 
     /* Destroy PBOs, but load them into real sysmem before */
@@ -1257,5 +1228,5 @@
         IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
 
-        ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+        ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
         ENTER_GL();
 
@@ -1353,5 +1324,5 @@
 lock_end:
     if(This->Flags & SFLAG_PBO) {
-        ActivateContext(myDevice, myDevice->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+        ActivateContext(myDevice, NULL, CTXUSAGE_RESOURCELOAD);
         ENTER_GL();
         GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
@@ -1513,5 +1484,5 @@
     if (This->Flags & SFLAG_PBO) {
         TRACE("Freeing PBO memory\n");
-        ActivateContext(myDevice, myDevice->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+        ActivateContext(myDevice, NULL, CTXUSAGE_RESOURCELOAD);
         ENTER_GL();
         GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
@@ -2655,5 +2626,5 @@
         name = srgb ? &This->texture_name_srgb : &This->texture_name;
         if(!device->isInDraw) {
-            ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+            ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
         }
 
@@ -3150,4 +3121,5 @@
     UINT fbwidth = Src->currentDesc.Width;
     UINT fbheight = Src->currentDesc.Height;
+    struct wined3d_context *context;
     GLenum drawBuffer = GL_BACK;
     GLenum texture_target;
@@ -3156,5 +3128,5 @@
     TRACE("Using hwstretch blit\n");
     /* Activate the Proper context for reading from the source surface, set it up for blitting */
-    ActivateContext(myDevice, SrcSurface, CTXUSAGE_BLIT);
+    context = ActivateContext(myDevice, SrcSurface, CTXUSAGE_BLIT);
     surface_internal_preload((IWineD3DSurface *) This, SRGB_RGB);
 
@@ -3170,8 +3142,11 @@
      * This way we don't have to wait for the 2nd readback to finish to leave this function.
      */
-    if(myDevice->activeContext->aux_buffers >= 2) {
+    if (context->aux_buffers >= 2)
+    {
         /* Got more than one aux buffer? Use the 2nd aux buffer */
         drawBuffer = GL_AUX1;
-    } else if((swapchain || myDevice->offscreenBuffer == GL_BACK) && myDevice->activeContext->aux_buffers >= 1) {
+    }
+    else if ((swapchain || myDevice->offscreenBuffer == GL_BACK) && context->aux_buffers >= 1)
+    {
         /* Only one aux buffer, but it isn't used (Onscreen rendering, or non-aux orm)? Use it! */
         drawBuffer = GL_AUX0;
@@ -3217,8 +3192,8 @@
     /* No issue with overriding these - the sampler is dirty due to blit usage */
     glTexParameteri(texture_target, GL_TEXTURE_MAG_FILTER,
-                    magLookup[Filter - WINED3DTEXF_NONE]);
+            wined3d_gl_mag_filter(magLookup, Filter));
     checkGLcall("glTexParameteri");
     glTexParameteri(texture_target, GL_TEXTURE_MIN_FILTER,
-                    minMipLookup[Filter].mip[WINED3DTEXF_NONE]);
+            wined3d_gl_min_mip_filter(minMipLookup, Filter, WINED3DTEXF_NONE));
     checkGLcall("glTexParameteri");
 
@@ -3779,7 +3754,9 @@
 
         /* Filtering for StretchRect */
-        glTexParameteri(Src->texture_target, GL_TEXTURE_MAG_FILTER, magLookup[Filter - WINED3DTEXF_NONE]);
+        glTexParameteri(Src->texture_target, GL_TEXTURE_MAG_FILTER,
+                wined3d_gl_mag_filter(magLookup, Filter));
         checkGLcall("glTexParameteri");
-        glTexParameteri(Src->texture_target, GL_TEXTURE_MIN_FILTER, minMipLookup[Filter].mip[WINED3DTEXF_NONE]);
+        glTexParameteri(Src->texture_target, GL_TEXTURE_MIN_FILTER,
+                wined3d_gl_min_mip_filter(minMipLookup, Filter, WINED3DTEXF_NONE));
         checkGLcall("glTexParameteri");
         glTexParameteri(Src->texture_target, GL_TEXTURE_WRAP_S, GL_CLAMP);
@@ -4107,5 +4084,5 @@
 
             /* Re-upload the palette */
-            ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+            ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
             d3dfmt_p8_upload_palette(iface, convert);
         } else {
@@ -4380,5 +4357,6 @@
 
 /* Context activation is done by the caller. */
-void surface_load_ds_location(IWineD3DSurface *iface, DWORD location) {
+void surface_load_ds_location(IWineD3DSurface *iface, struct wined3d_context *context, DWORD location)
+{
     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
     IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
@@ -4414,5 +4392,5 @@
             /* Note that we use depth_blt here as well, rather than glCopyTexImage2D
              * directly on the FBO texture. That's because we need to flip. */
-            context_bind_fbo(device->activeContext, GL_FRAMEBUFFER_EXT, NULL);
+            context_bind_fbo(context, GL_FRAMEBUFFER_EXT, NULL);
             if (This->texture_target == GL_TEXTURE_RECTANGLE_ARB)
             {
@@ -4449,8 +4427,8 @@
             }
 
-            context_bind_fbo(device->activeContext, GL_FRAMEBUFFER_EXT, &device->activeContext->dst_fbo);
+            context_bind_fbo(context, GL_FRAMEBUFFER_EXT, &context->dst_fbo);
             GL_EXTCALL(glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, device->depth_blt_rb));
             checkGLcall("glFramebufferRenderbufferEXT");
-            context_attach_depth_stencil_fbo(device->activeContext, GL_FRAMEBUFFER_EXT, iface, FALSE);
+            context_attach_depth_stencil_fbo(context, GL_FRAMEBUFFER_EXT, iface, FALSE);
 
             /* Do the actual blit */
@@ -4458,9 +4436,6 @@
             checkGLcall("depth_blt");
 
-            if (device->activeContext->current_fbo) {
-                context_bind_fbo(device->activeContext, GL_FRAMEBUFFER_EXT, &device->activeContext->current_fbo->id);
-            } else {
-                context_bind_fbo(device->activeContext, GL_FRAMEBUFFER_EXT, NULL);
-            }
+            if (context->current_fbo) context_bind_fbo(context, GL_FRAMEBUFFER_EXT, &context->current_fbo->id);
+            else context_bind_fbo(context, GL_FRAMEBUFFER_EXT, NULL);
 
             LEAVE_GL();
@@ -4474,12 +4449,10 @@
             ENTER_GL();
 
-            context_bind_fbo(device->activeContext, GL_FRAMEBUFFER_EXT, NULL);
+            context_bind_fbo(context, GL_FRAMEBUFFER_EXT, NULL);
             surface_depth_blt(This, This->texture_name, This->currentDesc.Width,
                     This->currentDesc.Height, This->texture_target);
             checkGLcall("depth_blt");
 
-            if (device->activeContext->current_fbo) {
-                context_bind_fbo(device->activeContext, GL_FRAMEBUFFER_EXT, &device->activeContext->current_fbo->id);
-            }
+            if (context->current_fbo) context_bind_fbo(context, GL_FRAMEBUFFER_EXT, &context->current_fbo->id);
 
             LEAVE_GL();
@@ -4566,5 +4539,7 @@
 }
 
-static inline void surface_blt_to_drawable(IWineD3DSurfaceImpl *This, const RECT *rect_in) {
+static inline void surface_blt_to_drawable(IWineD3DSurfaceImpl *This, const RECT *rect_in)
+{
+    const struct wined3d_context *context;
     struct coords coords[4];
     RECT rect;
@@ -4673,5 +4648,6 @@
     }
 
-    ActivateContext(device, (IWineD3DSurface*)This, CTXUSAGE_BLIT);
+    context = ActivateContext(device, (IWineD3DSurface*)This, CTXUSAGE_BLIT);
+
     ENTER_GL();
 
@@ -4685,5 +4661,5 @@
     checkGLcall("glTexParameteri");
 
-    if (device->render_offscreen)
+    if (context->render_offscreen)
     {
         LONG tmp = rect.top;
@@ -4798,5 +4774,5 @@
         /* Download the surface to system memory */
         if(This->Flags & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX)) {
-            if(!device->isInDraw) ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+            if (!device->isInDraw) ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
             surface_bind_and_dirtify(This, !(This->Flags & SFLAG_INTEXTURE));
 
@@ -4830,5 +4806,5 @@
             if((convert != NO_CONVERSION) && (This->Flags & SFLAG_PBO)) {
                 TRACE("Removing the pbo attached to surface %p\n", This);
-                if (!device->isInDraw) ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+                if (!device->isInDraw) ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
                 surface_remove_pbo(This);
             }
@@ -4882,5 +4858,5 @@
             }
 
-            if(!device->isInDraw) ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+            if (!device->isInDraw) ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
             surface_bind_and_dirtify(This, srgb);
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/swapchain.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/swapchain.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/swapchain.c	(revision 22496)
@@ -76,20 +76,4 @@
     for (i = 0; i < This->num_contexts; ++i)
     {
-        if (This->context[i] == This->wineD3DDevice->activeContext)
-        {
-            IWineD3DSwapChainImpl *swapchain = (IWineD3DSwapChainImpl *)This->wineD3DDevice->swapchains[0];
-
-            /* Avoid destroying the currently active context for non-implicit swapchains. */
-            if (This != swapchain)
-            {
-                TRACE("Would destroy currently active context %p on a non-implicit swapchain.\n", This->context[i]);
-
-                if (swapchain->backBuffer)
-                    ActivateContext(This->wineD3DDevice, swapchain->backBuffer[0], CTXUSAGE_RESOURCELOAD);
-                else
-                    ActivateContext(This->wineD3DDevice, swapchain->frontBuffer, CTXUSAGE_RESOURCELOAD);
-            }
-        }
-
         DestroyContext(This->wineD3DDevice, This->context[i]);
     }
@@ -158,5 +142,6 @@
             MapWindowPoints(NULL, This->win_handle, (LPPOINT)&destRect, 2);
         }
-        IWineD3DSurface_Blt(This->backBuffer[0], &destRect, (IWineD3DSurface *) &cursor, NULL, WINEDDBLT_KEYSRC, NULL, WINED3DTEXF_NONE);
+        IWineD3DSurface_Blt(This->backBuffer[0], &destRect, (IWineD3DSurface *)&cursor,
+                NULL, WINEDDBLT_KEYSRC, NULL, WINED3DTEXF_POINT);
     }
     if(This->wineD3DDevice->logo_surface) {
@@ -398,8 +383,9 @@
 };
 
-WineD3DContext *IWineD3DSwapChainImpl_CreateContextForThread(IWineD3DSwapChain *iface) {
-    WineD3DContext *ctx;
+struct wined3d_context *IWineD3DSwapChainImpl_CreateContextForThread(IWineD3DSwapChain *iface)
+{
     IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *) iface;
-    WineD3DContext **newArray;
+    struct wined3d_context **newArray;
+    struct wined3d_context *ctx;
 
     TRACE("Creating a new context for swapchain %p, thread %d\n", This, GetCurrentThreadId());
@@ -428,9 +414,10 @@
 }
 
-void get_drawable_size_swapchain(IWineD3DSurfaceImpl *This, UINT *width, UINT *height) {
+void get_drawable_size_swapchain(struct wined3d_context *context, UINT *width, UINT *height)
+{
+    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 = This->currentDesc.Width;
-    *height = This->currentDesc.Height;
-}
+     * (Actually: The window size, but the surface is created in window size) */
+    *width = surface->currentDesc.Width;
+    *height = surface->currentDesc.Height;
+}
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/texture.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/texture.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/texture.c	(revision 22496)
@@ -73,5 +73,5 @@
         /* ActivateContext sets isInDraw to TRUE when loading a pbuffer into a texture,
          * thus no danger of recursive calls. */
-        ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+        ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
     }
 
@@ -205,15 +205,4 @@
         WARN("Failed to initialize basetexture, returning %#x.\n", hr);
         return hr;
-    }
-
-    if (texture->resource.format_desc->Flags & WINED3DFMT_FLAG_FILTERING)
-    {
-        texture->baseTexture.minMipLookup = minMipLookup;
-        texture->baseTexture.magLookup = magLookup;
-    }
-    else
-    {
-        texture->baseTexture.minMipLookup = minMipLookup_noFilter;
-        texture->baseTexture.magLookup = magLookup_noFilter;
     }
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/utils.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/utils.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/utils.c	(revision 22496)
@@ -283,21 +283,21 @@
     {WINED3DFMT_R16_FLOAT,          GL_RGB16F_ARB,                    GL_RGB16F_ARB,                          0,
             GL_RED,                 GL_HALF_FLOAT_ARB,
-            WINED3DFMT_FLAG_FILTERING | WINED3DFMT_FLAG_RENDERTARGET,
+            WINED3DFMT_FLAG_RENDERTARGET,
             ARB_TEXTURE_FLOAT},
     {WINED3DFMT_R16_FLOAT,          GL_R16F,                          GL_R16F,                                0,
             GL_RED,                 GL_HALF_FLOAT_ARB,
-            WINED3DFMT_FLAG_FILTERING | WINED3DFMT_FLAG_RENDERTARGET,
+            WINED3DFMT_FLAG_RENDERTARGET,
             ARB_TEXTURE_RG},
     {WINED3DFMT_R16G16_FLOAT,       GL_RGB16F_ARB,                    GL_RGB16F_ARB,                          0,
             GL_RGB,                 GL_HALF_FLOAT_ARB,
-            WINED3DFMT_FLAG_FILTERING | WINED3DFMT_FLAG_RENDERTARGET,
+            WINED3DFMT_FLAG_RENDERTARGET,
             ARB_TEXTURE_FLOAT},
     {WINED3DFMT_R16G16_FLOAT,       GL_RG16F,                         GL_RG16F,                               0,
             GL_RG,                  GL_HALF_FLOAT_ARB,
-            WINED3DFMT_FLAG_FILTERING | WINED3DFMT_FLAG_RENDERTARGET,
+            WINED3DFMT_FLAG_RENDERTARGET,
             ARB_TEXTURE_RG},
     {WINED3DFMT_R16G16B16A16_FLOAT, GL_RGBA16F_ARB,                   GL_RGBA16F_ARB,                         0,
             GL_RGBA,                GL_HALF_FLOAT_ARB,
-            WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING | WINED3DFMT_FLAG_FILTERING | WINED3DFMT_FLAG_RENDERTARGET,
+            WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING | WINED3DFMT_FLAG_RENDERTARGET,
             ARB_TEXTURE_FLOAT},
     /* Palettized formats */
@@ -780,4 +780,174 @@
 }
 
+static BOOL color_match(DWORD c1, DWORD c2, BYTE max_diff)
+{
+    if (abs((c1 & 0xff) - (c2 & 0xff)) > max_diff) return FALSE;
+    c1 >>= 8; c2 >>= 8;
+    if (abs((c1 & 0xff) - (c2 & 0xff)) > max_diff) return FALSE;
+    c1 >>= 8; c2 >>= 8;
+    if (abs((c1 & 0xff) - (c2 & 0xff)) > max_diff) return FALSE;
+    c1 >>= 8; c2 >>= 8;
+    if (abs((c1 & 0xff) - (c2 & 0xff)) > max_diff) return FALSE;
+    return TRUE;
+}
+
+/* A context is provided by the caller */
+static BOOL check_filter(const struct wined3d_gl_info *gl_info, GLenum internal)
+{
+    GLuint tex, fbo, buffer;
+    const DWORD data[] = {0x00000000, 0xffffffff};
+    DWORD readback[16 * 1];
+    BOOL ret = FALSE;
+
+    /* Render a filtered texture and see what happens. This is intended to detect the lack of
+     * float16 filtering on ATI X1000 class cards. The drivers disable filtering instead of
+     * falling back to software. If this changes in the future this code will get fooled and
+     * apps might hit the software path due to incorrectly advertised caps.
+     *
+     * Its unlikely that this changes however. GL Games like Mass Effect depend on the filter
+     * disable fallback, if Apple or ATI ever change the driver behavior they will break more
+     * than Wine. The Linux binary <= r500 driver is not maintained any more anyway
+     */
+
+    ENTER_GL();
+    while(glGetError());
+
+    glGenTextures(1, &buffer);
+    glBindTexture(GL_TEXTURE_2D, buffer);
+    memset(readback, 0x7e, sizeof(readback));
+    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 16, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, readback);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
+
+    glGenTextures(1, &tex);
+    glBindTexture(GL_TEXTURE_2D, tex);
+    glTexImage2D(GL_TEXTURE_2D, 0, internal, 2, 1, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, data);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
+    glEnable(GL_TEXTURE_2D);
+
+    GL_EXTCALL(glGenFramebuffersEXT(1, &fbo));
+    GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo));
+    GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, buffer, 0));
+    glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
+
+    glViewport(0, 0, 16, 1);
+    glDisable(GL_LIGHTING);
+    glMatrixMode(GL_MODELVIEW);
+    glLoadIdentity();
+    glMatrixMode(GL_PROJECTION);
+    glLoadIdentity();
+
+    glClearColor(0, 1, 0, 0);
+    glClear(GL_COLOR_BUFFER_BIT);
+
+    glBegin(GL_TRIANGLE_STRIP);
+    glTexCoord2f(0.0, 0.0);
+    glVertex2f(-1.0f, -1.0f);
+    glTexCoord2f(1.0, 0.0);
+    glVertex2f(1.0f, -1.0f);
+    glTexCoord2f(0.0, 1.0);
+    glVertex2f(-1.0f, 1.0f);
+    glTexCoord2f(1.0, 1.0);
+    glVertex2f(1.0f, 1.0f);
+    glEnd();
+
+    glBindTexture(GL_TEXTURE_2D, buffer);
+    memset(readback, 0x7f, sizeof(readback));
+    glGetTexImage(GL_TEXTURE_2D, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, readback);
+    if(color_match(readback[6], 0xffffffff, 5) || color_match(readback[6], 0x00000000, 5) ||
+       color_match(readback[9], 0xffffffff, 5) || color_match(readback[9], 0x00000000, 5))
+    {
+        TRACE("Read back colors 0x%08x and 0x%08x close to unfiltered color, asuming no filtering\n",
+              readback[6], readback[9]);
+        ret = FALSE;
+    }
+    else
+    {
+        TRACE("Read back colors are 0x%08x and 0x%08x, assuming texture is filtered\n",
+              readback[6], readback[9]);
+        ret = TRUE;
+    }
+
+    GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
+    GL_EXTCALL(glDeleteFramebuffersEXT(1, &fbo));
+    glDeleteTextures(1, &tex);
+    glDeleteTextures(1, &buffer);
+
+    if(glGetError())
+    {
+        FIXME("Error during filtering test for format %x, returning no filtering\n", internal);
+        ret = FALSE;
+    }
+    LEAVE_GL();
+    return ret;
+}
+
+static void init_format_filter_info(struct wined3d_gl_info *gl_info)
+{
+    unsigned int fmt_idx, i;
+    WINED3DFORMAT fmts16[] = {
+        WINED3DFMT_R16_FLOAT,
+        WINED3DFMT_R16G16_FLOAT,
+        WINED3DFMT_R16G16B16A16_FLOAT,
+    };
+    BOOL filtered;
+    struct GlPixelFormatDesc *desc;
+
+    if(wined3d_settings.offscreen_rendering_mode != ORM_FBO)
+    {
+        WARN("No FBO support, or no FBO ORM, guessing filter info from GL caps\n");
+        if(gl_info->gl_vendor == VENDOR_NVIDIA && GL_SUPPORT(ARB_TEXTURE_FLOAT))
+        {
+            TRACE("Nvidia card with texture_float support: Assuming float16 blending\n");
+            filtered = TRUE;
+        }
+        else if(GL_LIMITS(glsl_varyings > 44))
+        {
+            TRACE("More than 44 GLSL varyings - assuming d3d10 card with float16 blending\n");
+            filtered = TRUE;
+        }
+        else
+        {
+            TRACE("Assuming no float16 blending\n");
+            filtered = FALSE;
+        }
+
+        if(filtered)
+        {
+            for(i = 0; i < (sizeof(fmts16) / sizeof(*fmts16)); i++)
+            {
+                fmt_idx = getFmtIdx(fmts16[i]);
+                gl_info->gl_formats[fmt_idx].Flags |= WINED3DFMT_FLAG_FILTERING;
+            }
+        }
+        return;
+    }
+
+    for(i = 0; i < (sizeof(fmts16) / sizeof(*fmts16)); i++)
+    {
+        fmt_idx = getFmtIdx(fmts16[i]);
+        desc = &gl_info->gl_formats[fmt_idx];
+        if(!desc->glInternal) continue; /* Not supported by GL */
+
+        filtered = check_filter(gl_info, gl_info->gl_formats[fmt_idx].glInternal);
+        if(filtered)
+        {
+            TRACE("Format %s supports filtering\n", debug_d3dformat(fmts16[i]));
+            desc->Flags |= WINED3DFMT_FLAG_FILTERING;
+        }
+        else
+        {
+            TRACE("Format %s does not support filtering\n", debug_d3dformat(fmts16[i]));
+        }
+    }
+}
+
 static void apply_format_fixups(struct wined3d_gl_info *gl_info)
 {
@@ -952,4 +1122,5 @@
     apply_format_fixups(gl_info);
     init_format_fbo_compat_info(gl_info);
+    init_format_filter_info(gl_info);
 
     return TRUE;
@@ -2406,5 +2577,6 @@
 #define GLINFO_LOCATION stateblock->wineD3DDevice->adapter->gl_info
 /* GL locking is done by the caller (state handler) */
-void texture_activate_dimensions(DWORD stage, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+void texture_activate_dimensions(DWORD stage, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     if(stateblock->textures[stage]) {
         switch (IWineD3DBaseTexture_GetTextureDimensions(stateblock->textures[stage])) {
@@ -2480,5 +2652,6 @@
 
 /* GL locking is done by the caller (state handler) */
-void sampler_texdim(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
+void sampler_texdim(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
+{
     DWORD sampler = state - STATE_SAMPLER(0);
     DWORD mapped_stage = stateblock->wineD3DDevice->texUnitMap[sampler];
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/volumetexture.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/volumetexture.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/volumetexture.c	(revision 22496)
@@ -51,5 +51,5 @@
     if (!device->isInDraw)
     {
-        ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
+        ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
     }
     else if (GL_SUPPORT(EXT_TEXTURE_SRGB) && This->baseTexture.bindCount > 0)
@@ -158,15 +158,4 @@
         WARN("Failed to initialize basetexture, returning %#x.\n", hr);
         return hr;
-    }
-
-    if (texture->resource.format_desc->Flags & WINED3DFMT_FLAG_FILTERING)
-    {
-        texture->baseTexture.minMipLookup = minMipLookup;
-        texture->baseTexture.magLookup = magLookup;
-    }
-    else
-    {
-        texture->baseTexture.minMipLookup = minMipLookup_noFilter;
-        texture->baseTexture.magLookup = magLookup_noFilter;
     }
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/wined3d_main.c
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/wined3d_main.c	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/wined3d_main.c	(revision 22496)
@@ -51,5 +51,5 @@
     VBO_HW,         /* Hardware by default */
     TRUE,           /* Use of GLSL enabled by default */
-    ORM_FBO,        /* Use the fbo to do offscreen rendering */
+    ORM_FBO,        /* Use FBOs to do offscreen rendering */
     RTL_AUTO,       /* Automatically determine best locking method */
     PCI_VENDOR_NONE,/* PCI Vendor ID */
@@ -107,4 +107,5 @@
 static BOOL wined3d_init(HINSTANCE hInstDLL)
 {
+    DWORD wined3d_context_tls_idx;
     HMODULE mod;
     char buffer[MAX_PATH+10];
@@ -114,4 +115,13 @@
     DWORD len, tmpvalue;
     WNDCLASSA wc;
+
+    wined3d_context_tls_idx = TlsAlloc();
+    if (wined3d_context_tls_idx == TLS_OUT_OF_INDEXES)
+    {
+        DWORD err = GetLastError();
+        ERR("Failed to allocate context TLS index, err %#x.\n", err);
+        return FALSE;
+    }
+    context_set_tls_idx(wined3d_context_tls_idx);
 
     /* We need our own window class for a fake window which we use to retrieve GL capabilities */
@@ -132,4 +142,9 @@
     {
         ERR("Failed to register window class 'WineD3D_OpenGL'!\n");
+        if (!TlsFree(wined3d_context_tls_idx))
+        {
+            DWORD err = GetLastError();
+            ERR("Failed to free context TLS index, err %#x.\n", err);
+        }
         return FALSE;
     }
@@ -332,4 +347,12 @@
 static BOOL wined3d_destroy(HINSTANCE hInstDLL)
 {
+    DWORD wined3d_context_tls_idx = context_get_tls_idx();
+
+    if (!TlsFree(wined3d_context_tls_idx))
+    {
+        DWORD err = GetLastError();
+        ERR("Failed to free context TLS index, err %#x.\n", err);
+    }
+
     HeapFree(GetProcessHeap(), 0, wined3d_settings.logo);
     UnregisterClassA(WINED3D_OPENGL_WINDOW_CLASS_NAME, hInstDLL);
@@ -351,4 +374,13 @@
             return wined3d_destroy(hInstDLL);
 
+        case DLL_THREAD_DETACH:
+        {
+            if (!context_set_current(NULL))
+            {
+                ERR("Failed to clear current context.\n");
+            }
+            return TRUE;
+        }
+
         default:
             return TRUE;
Index: trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/wined3d_private.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/wined3d_private.h	(revision 22495)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/wined3d_private.h	(revision 22496)
@@ -186,11 +186,19 @@
 };
 
-struct min_lookup minMipLookup[WINED3DTEXF_ANISOTROPIC + 1];
-const struct min_lookup minMipLookup_noFilter[WINED3DTEXF_ANISOTROPIC + 1];
-GLenum magLookup[WINED3DTEXF_ANISOTROPIC + 1];
-const GLenum magLookup_noFilter[WINED3DTEXF_ANISOTROPIC + 1];
-
-extern const struct filter_lookup filter_lookup_nofilter;
-extern struct filter_lookup filter_lookup;
+const struct min_lookup minMipLookup[WINED3DTEXF_LINEAR + 1];
+const struct min_lookup minMipLookup_noFilter[WINED3DTEXF_LINEAR + 1];
+const GLenum magLookup[WINED3DTEXF_LINEAR + 1];
+const GLenum magLookup_noFilter[WINED3DTEXF_LINEAR + 1];
+
+static inline GLenum wined3d_gl_mag_filter(const GLenum mag_lookup[], WINED3DTEXTUREFILTERTYPE mag_filter)
+{
+    return mag_lookup[mag_filter];
+}
+
+static inline GLenum wined3d_gl_min_mip_filter(const struct min_lookup min_mip_lookup[],
+        WINED3DTEXTUREFILTERTYPE min_filter, WINED3DTEXTUREFILTERTYPE mip_filter)
+{
+    return min_mip_lookup[min_filter].mip[mip_filter];
+}
 
 /* float_16_to_32() and float_32_to_16() (see implementation in
@@ -205,11 +213,12 @@
  */
 static inline float float_16_to_32(const unsigned short *in) {
+    unsigned long fNaN = 0x7fc00000;
+    unsigned long fNegInf = 0xff800000;
+    unsigned long fInf = 0x7f800000;
+
     const unsigned short s = ((*in) & 0x8000);
     const unsigned short e = ((*in) & 0x7C00) >> 10;
     const unsigned short m = (*in) & 0x3FF;
     const float sgn = (s ? -1.0f : 1.0f);
-    unsigned long fNaN = 0x7fc00000;
-    unsigned long fNegInf = 0xff800000;
-    unsigned long fInf = 0x7f800000;
 
     if(e == 0) {
@@ -825,12 +834,14 @@
 };
 
+struct wined3d_context;
+
 typedef struct {
     void (*shader_handle_instruction)(const struct wined3d_shader_instruction *);
-    void (*shader_select)(IWineD3DDevice *iface, BOOL usePS, BOOL useVS);
+    void (*shader_select)(const struct wined3d_context *context, BOOL usePS, BOOL useVS);
     void (*shader_select_depth_blt)(IWineD3DDevice *iface, enum tex_types tex_type);
     void (*shader_deselect_depth_blt)(IWineD3DDevice *iface);
     void (*shader_update_float_vertex_constants)(IWineD3DDevice *iface, UINT start, UINT count);
     void (*shader_update_float_pixel_constants)(IWineD3DDevice *iface, UINT start, UINT count);
-    void (*shader_load_constants)(IWineD3DDevice *iface, char usePS, char useVS);
+    void (*shader_load_constants)(const struct wined3d_context *context, char usePS, char useVS);
     void (*shader_load_np2fixup_constants)(IWineD3DDevice *iface, char usePS, char useVS);
     void (*shader_destroy)(IWineD3DBaseShader *iface);
@@ -1086,6 +1097,4 @@
 
 /* Routines and structures related to state management */
-typedef struct WineD3DContext WineD3DContext;
-typedef void (*APPLYSTATEFUNC)(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *ctx);
 
 #define STATE_RENDER(a) (a)
@@ -1139,61 +1148,4 @@
 #define STATE_HIGHEST (STATE_FRONTFACE)
 
-struct StateEntry
-{
-    DWORD               representative;
-    APPLYSTATEFUNC      apply;
-};
-
-struct StateEntryTemplate
-{
-    DWORD               state;
-    struct StateEntry   content;
-    GL_SupportedExt     extension;
-};
-
-struct fragment_caps {
-    DWORD               PrimitiveMiscCaps;
-
-    DWORD               TextureOpCaps;
-    DWORD               MaxTextureBlendStages;
-    DWORD               MaxSimultaneousTextures;
-};
-
-struct fragment_pipeline {
-    void (*enable_extension)(IWineD3DDevice *iface, BOOL enable);
-    void (*get_caps)(WINED3DDEVTYPE devtype, const struct wined3d_gl_info *gl_info, struct fragment_caps *caps);
-    HRESULT (*alloc_private)(IWineD3DDevice *iface);
-    void (*free_private)(IWineD3DDevice *iface);
-    BOOL (*color_fixup_supported)(struct color_fixup_desc fixup);
-    const struct StateEntryTemplate *states;
-    BOOL ffp_proj_control;
-};
-
-extern const struct StateEntryTemplate misc_state_template[];
-extern const struct StateEntryTemplate ffp_vertexstate_template[];
-extern const struct fragment_pipeline ffp_fragment_pipeline;
-extern const struct fragment_pipeline atifs_fragment_pipeline;
-extern const struct fragment_pipeline arbfp_fragment_pipeline;
-extern const struct fragment_pipeline nvts_fragment_pipeline;
-extern const struct fragment_pipeline nvrc_fragment_pipeline;
-
-/* "Base" state table */
-HRESULT compile_state_table(struct StateEntry *StateTable, APPLYSTATEFUNC **dev_multistate_funcs,
-        const struct wined3d_gl_info *gl_info, const struct StateEntryTemplate *vertex,
-        const struct fragment_pipeline *fragment, const struct StateEntryTemplate *misc);
-
-/* Shaders for color conversions in blits */
-struct blit_shader {
-    HRESULT (*alloc_private)(IWineD3DDevice *iface);
-    void (*free_private)(IWineD3DDevice *iface);
-    HRESULT (*set_shader)(IWineD3DDevice *iface, const struct GlPixelFormatDesc *format_desc,
-            GLenum textype, UINT width, UINT height);
-    void (*unset_shader)(IWineD3DDevice *iface);
-    BOOL (*color_fixup_supported)(struct color_fixup_desc fixup);
-};
-
-extern const struct blit_shader ffp_blit;
-extern const struct blit_shader arbfp_blit;
-
 enum fogsource {
     FOGSOURCE_FFP,
@@ -1204,6 +1156,19 @@
 #define WINED3D_MAX_FBO_ENTRIES 64
 
-/* The new context manager that should deal with onscreen and offscreen rendering */
-struct WineD3DContext
+struct wined3d_occlusion_query
+{
+    struct list entry;
+    GLuint id;
+    struct wined3d_context *context;
+};
+
+struct wined3d_event_query
+{
+    struct list entry;
+    GLuint id;
+    struct wined3d_context *context;
+};
+
+struct wined3d_context
 {
     const struct wined3d_gl_info *gl_info;
@@ -1219,7 +1184,9 @@
 
     IWineD3DSurface         *surface;
+    IWineD3DSurface *current_rt;
     DWORD                   tid;    /* Thread ID which owns this context at the moment */
 
     /* Stores some information about the context state for optimization */
+    WORD render_offscreen : 1;
     WORD draw_buffer_dirty : 1;
     WORD last_was_rhw : 1;              /* true iff last draw_primitive was in xyzrhw mode */
@@ -1234,5 +1201,6 @@
     WORD fog_enabled : 1;
     WORD num_untracked_materials : 2;   /* Max value 2 */
-    WORD padding : 3;
+    WORD current : 1;
+    WORD destroyed : 1;
     BYTE texShaderBumpMap;              /* MAX_TEXTURES, 8 */
     BYTE lastWasPow2Texture;            /* MAX_TEXTURES, 8 */
@@ -1261,4 +1229,15 @@
     GLuint                  fbo_draw_binding;
 
+    /* Queries */
+    GLuint *free_occlusion_queries;
+    UINT free_occlusion_query_size;
+    UINT free_occlusion_query_count;
+    struct list occlusion_queries;
+
+    GLuint *free_event_queries;
+    UINT free_event_query_size;
+    UINT free_event_query_count;
+    struct list event_queries;
+
     /* Extension emulation */
     GLint                   gl_fog_source;
@@ -1267,4 +1246,65 @@
     GLuint                  dummy_arbfp_prog;
 };
+
+typedef void (*APPLYSTATEFUNC)(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *ctx);
+
+struct StateEntry
+{
+    DWORD representative;
+    APPLYSTATEFUNC apply;
+};
+
+struct StateEntryTemplate
+{
+    DWORD state;
+    struct StateEntry content;
+    GL_SupportedExt extension;
+};
+
+struct fragment_caps
+{
+    DWORD PrimitiveMiscCaps;
+    DWORD TextureOpCaps;
+    DWORD MaxTextureBlendStages;
+    DWORD MaxSimultaneousTextures;
+};
+
+struct fragment_pipeline
+{
+    void (*enable_extension)(IWineD3DDevice *iface, BOOL enable);
+    void (*get_caps)(WINED3DDEVTYPE devtype, const struct wined3d_gl_info *gl_info, struct fragment_caps *caps);
+    HRESULT (*alloc_private)(IWineD3DDevice *iface);
+    void (*free_private)(IWineD3DDevice *iface);
+    BOOL (*color_fixup_supported)(struct color_fixup_desc fixup);
+    const struct StateEntryTemplate *states;
+    BOOL ffp_proj_control;
+};
+
+extern const struct StateEntryTemplate misc_state_template[];
+extern const struct StateEntryTemplate ffp_vertexstate_template[];
+extern const struct fragment_pipeline ffp_fragment_pipeline;
+extern const struct fragment_pipeline atifs_fragment_pipeline;
+extern const struct fragment_pipeline arbfp_fragment_pipeline;
+extern const struct fragment_pipeline nvts_fragment_pipeline;
+extern const struct fragment_pipeline nvrc_fragment_pipeline;
+
+/* "Base" state table */
+HRESULT compile_state_table(struct StateEntry *StateTable, APPLYSTATEFUNC **dev_multistate_funcs,
+        const struct wined3d_gl_info *gl_info, const struct StateEntryTemplate *vertex,
+        const struct fragment_pipeline *fragment, const struct StateEntryTemplate *misc);
+
+/* Shaders for color conversions in blits */
+struct blit_shader
+{
+    HRESULT (*alloc_private)(IWineD3DDevice *iface);
+    void (*free_private)(IWineD3DDevice *iface);
+    HRESULT (*set_shader)(IWineD3DDevice *iface, const struct GlPixelFormatDesc *format_desc,
+            GLenum textype, UINT width, UINT height);
+    void (*unset_shader)(IWineD3DDevice *iface);
+    BOOL (*color_fixup_supported)(struct color_fixup_desc fixup);
+};
+
+extern const struct blit_shader ffp_blit;
+extern const struct blit_shader arbfp_blit;
 
 typedef enum ContextUsage {
@@ -1275,15 +1315,22 @@
 } ContextUsage;
 
-void ActivateContext(IWineD3DDeviceImpl *device, IWineD3DSurface *target, ContextUsage usage);
-WineD3DContext *getActiveContext(void);
-WineD3DContext *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, HWND win, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms);
-void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context);
+struct wined3d_context *ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, enum ContextUsage usage);
+struct wined3d_context *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, HWND win,
+        BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms);
+void DestroyContext(IWineD3DDeviceImpl *This, struct wined3d_context *context);
+void context_alloc_event_query(struct wined3d_context *context, struct wined3d_event_query *query);
+void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query);
 void context_resource_released(IWineD3DDevice *iface, IWineD3DResource *resource, WINED3DRESOURCETYPE type);
-void context_bind_fbo(struct WineD3DContext *context, GLenum target, GLuint *fbo);
-void context_attach_depth_stencil_fbo(struct WineD3DContext *context,
+void context_bind_fbo(struct wined3d_context *context, GLenum target, GLuint *fbo);
+void context_attach_depth_stencil_fbo(struct wined3d_context *context,
         GLenum fbo_target, IWineD3DSurface *depth_stencil, BOOL use_render_buffer);
-void context_attach_surface_fbo(const struct WineD3DContext *context,
+void context_attach_surface_fbo(const struct wined3d_context *context,
         GLenum fbo_target, DWORD idx, IWineD3DSurface *surface);
-void context_set_last_device(IWineD3DDeviceImpl *device);
+void context_free_event_query(struct wined3d_event_query *query);
+void context_free_occlusion_query(struct wined3d_occlusion_query *query);
+struct wined3d_context *context_get_current(void);
+DWORD context_get_tls_idx(void);
+BOOL context_set_current(struct wined3d_context *ctx);
+void context_set_tls_idx(DWORD idx);
 
 void delete_opengl_contexts(IWineD3DDevice *iface, IWineD3DSwapChain *swapchain);
@@ -1393,4 +1440,5 @@
  */
 #define ARG_UNUSED          0xff
+
 struct texture_stage_op
 {
@@ -1453,10 +1501,4 @@
 
 BOOL InitAdapters(IWineD3DImpl *This);
-
-/* TODO: setup some flags in the registry to enable, disable pbuffer support
-(since it will break quite a few things until contexts are managed properly!) */
-extern BOOL pbuffer_support;
-/* allocate one pbuffer per surface */
-extern BOOL pbuffer_per_surface;
 
 /* A helper function that dumps a resource list */
@@ -1513,5 +1555,4 @@
     WORD isRecordingState : 1;
     WORD isInDraw : 1;
-    WORD render_offscreen : 1;
     WORD bCursorVisible : 1;
     WORD haveHardwareCursor : 1;
@@ -1521,5 +1562,5 @@
     WORD useDrawStridedSlow : 1;
     WORD instancedDraw : 1;
-    WORD padding : 3;
+    WORD padding : 4;
 
     BYTE fixed_function_usage_map;      /* MAX_TEXTURES, 8 */
@@ -1549,8 +1590,4 @@
     IWineD3DSurface        *auto_depth_stencil_buffer;
     IWineD3DSurface        *stencilBufferTarget;
-
-    /* Caches to avoid unneeded context changes */
-    IWineD3DSurface        *lastActiveRenderTarget;
-    IWineD3DSwapChain      *lastActiveSwapChain;
 
     /* palettes texture management */
@@ -1601,9 +1638,7 @@
 
     /* Context management */
-    WineD3DContext          **contexts;                  /* Dynamic array containing pointers to context structures */
-    WineD3DContext          *activeContext;
-    DWORD                   lastThread;
+    struct wined3d_context **contexts;
     UINT                    numContexts;
-    WineD3DContext          *pbufferContext;             /* The context that has a pbuffer as drawable */
+    struct wined3d_context *pbufferContext;              /* The context that has a pbuffer as drawable */
     DWORD                   pbufferWidth, pbufferHeight; /* Size of the buffer drawable */
 
@@ -1628,5 +1663,6 @@
 void IWineD3DDeviceImpl_FindTexUnitMap(IWineD3DDeviceImpl *This);
 void IWineD3DDeviceImpl_MarkStateDirty(IWineD3DDeviceImpl *This, DWORD state);
-static inline BOOL isStateDirty(WineD3DContext *context, DWORD state) {
+static inline BOOL isStateDirty(struct wined3d_context *context, DWORD state)
+{
     DWORD idx = state >> 5;
     BYTE shift = state & 0x1f;
@@ -1779,8 +1815,4 @@
 DWORD basetexture_set_lod(IWineD3DBaseTexture *iface, DWORD new_lod);
 void basetexture_unload(IWineD3DBaseTexture *iface);
-static inline void basetexture_setsrgbcache(IWineD3DBaseTexture *iface, BOOL srgb) {
-    IWineD3DBaseTextureImpl *This = (IWineD3DBaseTextureImpl *)iface;
-    This->baseTexture.is_srgb = srgb;
-}
 
 /*****************************************************************************
@@ -1944,5 +1976,5 @@
 
     /* A method to retrieve the drawable size. Not in the Vtable to make it changeable */
-    void (*get_drawable_size)(IWineD3DSurfaceImpl *This, UINT *width, UINT *height);
+    void (*get_drawable_size)(struct wined3d_context *context, UINT *width, UINT *height);
 
     /* Oversized texture */
@@ -2038,8 +2070,8 @@
 const void *WINAPI IWineD3DBaseSurfaceImpl_GetData(IWineD3DSurface *iface);
 
-void get_drawable_size_swapchain(IWineD3DSurfaceImpl *This, UINT *width, UINT *height);
-void get_drawable_size_backbuffer(IWineD3DSurfaceImpl *This, UINT *width, UINT *height);
-void get_drawable_size_pbuffer(IWineD3DSurfaceImpl *This, UINT *width, UINT *height);
-void get_drawable_size_fbo(IWineD3DSurfaceImpl *This, UINT *width, UINT *height);
+void get_drawable_size_swapchain(struct wined3d_context *context, UINT *width, UINT *height);
+void get_drawable_size_backbuffer(struct wined3d_context *context, UINT *width, UINT *height);
+void get_drawable_size_pbuffer(struct wined3d_context *context, UINT *width, UINT *height);
+void get_drawable_size_fbo(struct wined3d_context *context, UINT *width, UINT *height);
 
 void flip_surface(IWineD3DSurfaceImpl *front, IWineD3DSurfaceImpl *back);
@@ -2365,15 +2397,4 @@
 extern const IWineD3DQueryVtbl IWineD3DOcclusionQuery_Vtbl;
 
-/* Datastructures for IWineD3DQueryImpl.extendedData */
-typedef struct  WineQueryOcclusionData {
-    GLuint  queryId;
-    WineD3DContext *ctx;
-} WineQueryOcclusionData;
-
-typedef struct  WineQueryEventData {
-    GLuint  fenceId;
-    WineD3DContext *ctx;
-} WineQueryEventData;
-
 /* IWineD3DBuffer */
 
@@ -2462,5 +2483,5 @@
     unsigned int vSyncCounter;
 
-    WineD3DContext        **context; /* Later a array for multithreading */
+    struct wined3d_context **context;
     unsigned int            num_contexts;
 
@@ -2485,5 +2506,5 @@
 HRESULT WINAPI IWineD3DBaseSwapChainImpl_GetGammaRamp(IWineD3DSwapChain *iface, WINED3DGAMMARAMP *pRamp);
 
-WineD3DContext *IWineD3DSwapChainImpl_CreateContextForThread(IWineD3DSwapChain *iface);
+struct wined3d_context *IWineD3DSwapChainImpl_CreateContextForThread(IWineD3DSwapChain *iface);
 
 /*****************************************************************************
@@ -2520,16 +2541,16 @@
 void   set_tex_op_nvrc(IWineD3DDevice *iface, BOOL is_alpha, int stage, WINED3DTEXTUREOP op, DWORD arg1, DWORD arg2, DWORD arg3, INT texture_idx, DWORD dst);
 void   set_texture_matrix(const float *smat, DWORD flags, BOOL calculatedCoords, BOOL transformed, DWORD coordtype, BOOL ffp_can_disable_proj);
-void texture_activate_dimensions(DWORD stage, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context);
-void sampler_texdim(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context);
-void tex_alphaop(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context);
-void apply_pixelshader(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context);
-void state_fogcolor(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context);
-void state_fogdensity(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context);
-void state_fogstartend(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context);
-void state_fog_fragpart(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context);
+void texture_activate_dimensions(DWORD stage, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context);
+void sampler_texdim(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context);
+void tex_alphaop(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context);
+void apply_pixelshader(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context);
+void state_fogcolor(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context);
+void state_fogdensity(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context);
+void state_fogstartend(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context);
+void state_fog_fragpart(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context);
 
 void surface_add_dirty_rect(IWineD3DSurface *iface, const RECT *dirty_rect);
 GLenum surface_get_gl_buffer(IWineD3DSurface *iface, IWineD3DSwapChain *swapchain);
-void surface_load_ds_location(IWineD3DSurface *iface, DWORD location);
+void surface_load_ds_location(IWineD3DSurface *iface, struct wined3d_context *context, DWORD location);
 void surface_modify_ds_location(IWineD3DSurface *iface, DWORD location);
 void surface_set_compatible_renderbuffer(IWineD3DSurface *iface, unsigned int width, unsigned int height);
