mshtml: DeleteMemberByDispID should return E_NOTIMPL.
[wine] / dlls / wined3d / swapchain.c
1 /*
2  * Copyright 2002-2003 Jason Edmeades
3  * Copyright 2002-2003 Raphael Junqueira
4  * Copyright 2005 Oliver Stieber
5  * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
6  * Copyright 2011 Henri Verbeet for CodeWeavers
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include "config.h"
24 #include "wined3d_private.h"
25
26 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
27 WINE_DECLARE_DEBUG_CHANNEL(fps);
28
29 /* Do not call while under the GL lock. */
30 static void swapchain_cleanup(struct wined3d_swapchain *swapchain)
31 {
32     WINED3DDISPLAYMODE mode;
33     UINT i;
34
35     TRACE("Destroying swapchain %p.\n", swapchain);
36
37     wined3d_swapchain_set_gamma_ramp(swapchain, 0, &swapchain->orig_gamma);
38
39     /* Release the swapchain's draw buffers. Make sure swapchain->back_buffers[0]
40      * is the last buffer to be destroyed, FindContext() depends on that. */
41     if (swapchain->front_buffer)
42     {
43         surface_set_container(swapchain->front_buffer, WINED3D_CONTAINER_NONE, NULL);
44         if (wined3d_surface_decref(swapchain->front_buffer))
45             WARN("Something's still holding the front buffer (%p).\n", swapchain->front_buffer);
46         swapchain->front_buffer = NULL;
47     }
48
49     if (swapchain->back_buffers)
50     {
51         i = swapchain->presentParms.BackBufferCount;
52
53         while (i--)
54         {
55             surface_set_container(swapchain->back_buffers[i], WINED3D_CONTAINER_NONE, NULL);
56             if (wined3d_surface_decref(swapchain->back_buffers[i]))
57                 WARN("Something's still holding back buffer %u (%p).\n", i, swapchain->back_buffers[i]);
58         }
59         HeapFree(GetProcessHeap(), 0, swapchain->back_buffers);
60         swapchain->back_buffers = NULL;
61     }
62
63     for (i = 0; i < swapchain->num_contexts; ++i)
64     {
65         context_destroy(swapchain->device, swapchain->context[i]);
66     }
67     HeapFree(GetProcessHeap(), 0, swapchain->context);
68
69     /* Restore the screen resolution if we rendered in fullscreen.
70      * This will restore the screen resolution to what it was before creating
71      * the swapchain. In case of d3d8 and d3d9 this will be the original
72      * desktop resolution. In case of d3d7 this will be a NOP because ddraw
73      * sets the resolution before starting up Direct3D, thus orig_width and
74      * orig_height will be equal to the modes in the presentation params. */
75     if (!swapchain->presentParms.Windowed && swapchain->presentParms.AutoRestoreDisplayMode)
76     {
77         mode.Width = swapchain->orig_width;
78         mode.Height = swapchain->orig_height;
79         mode.RefreshRate = 0;
80         mode.Format = swapchain->orig_fmt;
81         wined3d_device_set_display_mode(swapchain->device, 0, &mode);
82     }
83
84     if (swapchain->backup_dc)
85     {
86         TRACE("Destroying backup wined3d window %p, dc %p.\n", swapchain->backup_wnd, swapchain->backup_dc);
87
88         ReleaseDC(swapchain->backup_wnd, swapchain->backup_dc);
89         DestroyWindow(swapchain->backup_wnd);
90     }
91 }
92
93 ULONG CDECL wined3d_swapchain_incref(struct wined3d_swapchain *swapchain)
94 {
95     ULONG refcount = InterlockedIncrement(&swapchain->ref);
96
97     TRACE("%p increasing refcount to %u.\n", swapchain, refcount);
98
99     return refcount;
100 }
101
102 /* Do not call while under the GL lock. */
103 ULONG CDECL wined3d_swapchain_decref(struct wined3d_swapchain *swapchain)
104 {
105     ULONG refcount = InterlockedDecrement(&swapchain->ref);
106
107     TRACE("%p decreasing refcount to %u.\n", swapchain, refcount);
108
109     if (!refcount)
110     {
111         swapchain_cleanup(swapchain);
112         swapchain->parent_ops->wined3d_object_destroyed(swapchain->parent);
113         HeapFree(GetProcessHeap(), 0, swapchain);
114     }
115
116     return refcount;
117 }
118
119 void * CDECL wined3d_swapchain_get_parent(const struct wined3d_swapchain *swapchain)
120 {
121     TRACE("swapchain %p.\n", swapchain);
122
123     return swapchain->parent;
124 }
125
126 HRESULT CDECL wined3d_swapchain_set_window(struct wined3d_swapchain *swapchain, HWND window)
127 {
128     if (!window)
129         window = swapchain->device_window;
130     if (window == swapchain->win_handle)
131         return WINED3D_OK;
132
133     TRACE("Setting swapchain %p window from %p to %p.\n",
134             swapchain, swapchain->win_handle, window);
135     swapchain->win_handle = window;
136
137     return WINED3D_OK;
138 }
139
140 HRESULT CDECL wined3d_swapchain_present(struct wined3d_swapchain *swapchain,
141         const RECT *src_rect, const RECT *dst_rect, HWND dst_window_override,
142         const RGNDATA *dirty_region, DWORD flags)
143 {
144     TRACE("swapchain %p, src_rect %s, dst_rect %s, dst_window_override %p, dirty_region %p, flags %#x.\n",
145             swapchain, wine_dbgstr_rect(src_rect), wine_dbgstr_rect(dst_rect),
146             dst_window_override, dirty_region, flags);
147
148     wined3d_swapchain_set_window(swapchain, dst_window_override);
149
150     return swapchain->swapchain_ops->swapchain_present(swapchain,
151             src_rect, dst_rect, dirty_region, flags);
152 }
153
154 HRESULT CDECL wined3d_swapchain_get_front_buffer_data(const struct wined3d_swapchain *swapchain,
155         struct wined3d_surface *dst_surface)
156 {
157     POINT offset = {0, 0};
158
159     TRACE("swapchain %p, dst_surface %p.\n", swapchain, dst_surface);
160
161     if (swapchain->presentParms.Windowed)
162         MapWindowPoints(swapchain->win_handle, NULL, &offset, 1);
163
164     wined3d_surface_bltfast(dst_surface, offset.x, offset.y, swapchain->front_buffer, NULL, 0);
165
166     return WINED3D_OK;
167 }
168
169 HRESULT CDECL wined3d_swapchain_get_back_buffer(const struct wined3d_swapchain *swapchain,
170         UINT back_buffer_idx, WINED3DBACKBUFFER_TYPE type, struct wined3d_surface **back_buffer)
171 {
172     TRACE("swapchain %p, back_buffer_idx %u, type %#x, back_buffer %p.\n",
173             swapchain, back_buffer_idx, type, back_buffer);
174
175     /* Return invalid if there is no backbuffer array, otherwise it will
176      * crash when ddraw is used (there swapchain->back_buffers is always
177      * NULL). We need this because this function is called from
178      * stateblock_init_default_state() to get the default scissorrect
179      * dimensions. */
180     if (!swapchain->back_buffers || back_buffer_idx >= swapchain->presentParms.BackBufferCount)
181     {
182         WARN("Invalid back buffer index.\n");
183         /* Native d3d9 doesn't set NULL here, just as wine's d3d9. But set it
184          * here in wined3d to avoid problems in other libs. */
185         *back_buffer = NULL;
186         return WINED3DERR_INVALIDCALL;
187     }
188
189     *back_buffer = swapchain->back_buffers[back_buffer_idx];
190     if (*back_buffer)
191         wined3d_surface_incref(*back_buffer);
192
193     TRACE("Returning back buffer %p.\n", *back_buffer);
194
195     return WINED3D_OK;
196 }
197
198 HRESULT CDECL wined3d_swapchain_get_raster_status(const struct wined3d_swapchain *swapchain,
199         WINED3DRASTER_STATUS *raster_status)
200 {
201     static BOOL warned;
202     /* No OpenGL equivalent */
203     if (!warned)
204     {
205         FIXME("swapchain %p, raster_status %p stub!\n", swapchain, raster_status);
206         warned = TRUE;
207     }
208
209     /* Obtaining the raster status is a widely implemented but optional
210      * feature. When this method returns OK StarCraft 2 expects the
211      * raster_status->InVBlank value to actually change over time. To prevent
212      * StarCraft 2 from running in an infinite loop at startup this method
213      * returns INVALIDCALL. */
214     return WINED3DERR_INVALIDCALL;
215 }
216
217 HRESULT CDECL wined3d_swapchain_get_display_mode(const struct wined3d_swapchain *swapchain, WINED3DDISPLAYMODE *mode)
218 {
219     HRESULT hr;
220
221     TRACE("swapchain %p, mode %p.\n", swapchain, mode);
222
223     hr = wined3d_get_adapter_display_mode(swapchain->device->wined3d, swapchain->device->adapter->ordinal, mode);
224
225     TRACE("Returning w %u, h %u, refresh rate %u, format %s.\n",
226             mode->Width, mode->Height, mode->RefreshRate, debug_d3dformat(mode->Format));
227
228     return hr;
229 }
230
231 struct wined3d_device * CDECL wined3d_swapchain_get_device(const struct wined3d_swapchain *swapchain)
232 {
233     TRACE("swapchain %p.\n", swapchain);
234
235     return swapchain->device;
236 }
237
238 HRESULT CDECL wined3d_swapchain_get_present_parameters(const struct wined3d_swapchain *swapchain,
239         WINED3DPRESENT_PARAMETERS *present_parameters)
240 {
241     TRACE("swapchain %p, present_parameters %p.\n", swapchain, present_parameters);
242
243     *present_parameters = swapchain->presentParms;
244
245     return WINED3D_OK;
246 }
247
248 HRESULT CDECL wined3d_swapchain_set_gamma_ramp(const struct wined3d_swapchain *swapchain,
249         DWORD flags, const WINED3DGAMMARAMP *ramp)
250 {
251     HDC dc;
252
253     TRACE("swapchain %p, flags %#x, ramp %p.\n", swapchain, flags, ramp);
254
255     if (flags)
256         FIXME("Ignoring flags %#x.\n", flags);
257
258     dc = GetDC(swapchain->device_window);
259     SetDeviceGammaRamp(dc, (void *)ramp);
260     ReleaseDC(swapchain->device_window, dc);
261
262     return WINED3D_OK;
263 }
264
265 HRESULT CDECL wined3d_swapchain_get_gamma_ramp(const struct wined3d_swapchain *swapchain,
266         WINED3DGAMMARAMP *ramp)
267 {
268     HDC dc;
269
270     TRACE("swapchain %p, ramp %p.\n", swapchain, ramp);
271
272     dc = GetDC(swapchain->device_window);
273     GetDeviceGammaRamp(dc, ramp);
274     ReleaseDC(swapchain->device_window, dc);
275
276     return WINED3D_OK;
277 }
278
279 /* A GL context is provided by the caller */
280 static void swapchain_blit(const struct wined3d_swapchain *swapchain,
281         struct wined3d_context *context, const RECT *src_rect, const RECT *dst_rect)
282 {
283     struct wined3d_surface *backbuffer = swapchain->back_buffers[0];
284     UINT src_w = src_rect->right - src_rect->left;
285     UINT src_h = src_rect->bottom - src_rect->top;
286     GLenum gl_filter;
287     const struct wined3d_gl_info *gl_info = context->gl_info;
288     RECT win_rect;
289     UINT win_h;
290
291     TRACE("swapchain %p, context %p, src_rect %s, dst_rect %s.\n",
292             swapchain, context, wine_dbgstr_rect(src_rect), wine_dbgstr_rect(dst_rect));
293
294     if (src_w == dst_rect->right - dst_rect->left && src_h == dst_rect->bottom - dst_rect->top)
295         gl_filter = GL_NEAREST;
296     else
297         gl_filter = GL_LINEAR;
298
299     GetClientRect(swapchain->win_handle, &win_rect);
300     win_h = win_rect.bottom - win_rect.top;
301
302     if (gl_info->fbo_ops.glBlitFramebuffer && is_identity_fixup(backbuffer->resource.format->color_fixup))
303     {
304         ENTER_GL();
305         context_apply_fbo_state_blit(context, GL_READ_FRAMEBUFFER, backbuffer, NULL, SFLAG_INTEXTURE);
306         glReadBuffer(GL_COLOR_ATTACHMENT0);
307         context_check_fbo_status(context, GL_READ_FRAMEBUFFER);
308
309         context_apply_fbo_state_blit(context, GL_DRAW_FRAMEBUFFER, swapchain->front_buffer, NULL, SFLAG_INDRAWABLE);
310         context_set_draw_buffer(context, GL_BACK);
311         context_invalidate_state(context, STATE_FRAMEBUFFER);
312
313         glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
314         context_invalidate_state(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE));
315         context_invalidate_state(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE1));
316         context_invalidate_state(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE2));
317         context_invalidate_state(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE3));
318
319         glDisable(GL_SCISSOR_TEST);
320         context_invalidate_state(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE));
321
322         /* Note that the texture is upside down */
323         gl_info->fbo_ops.glBlitFramebuffer(src_rect->left, src_rect->top, src_rect->right, src_rect->bottom,
324                 dst_rect->left, win_h - dst_rect->top, dst_rect->right, win_h - dst_rect->bottom,
325                 GL_COLOR_BUFFER_BIT, gl_filter);
326         checkGLcall("Swapchain present blit(EXT_framebuffer_blit)\n");
327         LEAVE_GL();
328     }
329     else
330     {
331         struct wined3d_device *device = swapchain->device;
332         struct wined3d_context *context2;
333         float tex_left = src_rect->left;
334         float tex_top = src_rect->top;
335         float tex_right = src_rect->right;
336         float tex_bottom = src_rect->bottom;
337
338         context2 = context_acquire(device, swapchain->back_buffers[0]);
339         context_apply_blit_state(context2, device);
340
341         if (backbuffer->flags & SFLAG_NORMCOORD)
342         {
343             tex_left /= src_w;
344             tex_right /= src_w;
345             tex_top /= src_h;
346             tex_bottom /= src_h;
347         }
348
349         if (is_complex_fixup(backbuffer->resource.format->color_fixup))
350             gl_filter = GL_NEAREST;
351
352         ENTER_GL();
353         context_apply_fbo_state_blit(context2, GL_FRAMEBUFFER, swapchain->front_buffer, NULL, SFLAG_INDRAWABLE);
354
355         /* Set up the texture. The surface is not in a wined3d_texture
356          * container, so there are no D3D texture settings to dirtify. */
357         device->blitter->set_shader(device->blit_priv, context2->gl_info, backbuffer);
358         glTexParameteri(backbuffer->texture_target, GL_TEXTURE_MIN_FILTER, gl_filter);
359         glTexParameteri(backbuffer->texture_target, GL_TEXTURE_MAG_FILTER, gl_filter);
360
361         context_set_draw_buffer(context, GL_BACK);
362
363         /* Set the viewport to the destination rectandle, disable any projection
364          * transformation set up by context_apply_blit_state(), and draw a
365          * (-1,-1)-(1,1) quad.
366          *
367          * Back up viewport and matrix to avoid breaking last_was_blit
368          *
369          * Note that context_apply_blit_state() set up viewport and ortho to
370          * match the surface size - we want the GL drawable(=window) size. */
371         glPushAttrib(GL_VIEWPORT_BIT);
372         glViewport(dst_rect->left, win_h - dst_rect->bottom, dst_rect->right, win_h - dst_rect->top);
373         glMatrixMode(GL_PROJECTION);
374         glPushMatrix();
375         glLoadIdentity();
376
377         glBegin(GL_QUADS);
378             /* bottom left */
379             glTexCoord2f(tex_left, tex_bottom);
380             glVertex2i(-1, -1);
381
382             /* top left */
383             glTexCoord2f(tex_left, tex_top);
384             glVertex2i(-1, 1);
385
386             /* top right */
387             glTexCoord2f(tex_right, tex_top);
388             glVertex2i(1, 1);
389
390             /* bottom right */
391             glTexCoord2f(tex_right, tex_bottom);
392             glVertex2i(1, -1);
393         glEnd();
394
395         glPopMatrix();
396         glPopAttrib();
397
398         device->blitter->unset_shader(context->gl_info);
399         checkGLcall("Swapchain present blit(manual)\n");
400         LEAVE_GL();
401
402         context_release(context2);
403     }
404 }
405
406 static HRESULT swapchain_gl_present(struct wined3d_swapchain *swapchain, const RECT *src_rect_in,
407         const RECT *dst_rect_in, const RGNDATA *dirty_region, DWORD flags)
408 {
409     const struct wined3d_fb_state *fb = &swapchain->device->fb;
410     const struct wined3d_gl_info *gl_info;
411     struct wined3d_context *context;
412     RECT src_rect, dst_rect;
413     BOOL render_to_fbo;
414
415     context = context_acquire(swapchain->device, swapchain->back_buffers[0]);
416     if (!context->valid)
417     {
418         context_release(context);
419         WARN("Invalid context, skipping present.\n");
420         return WINED3D_OK;
421     }
422
423     gl_info = context->gl_info;
424
425     /* Render the cursor onto the back buffer, using our nifty directdraw blitting code :-) */
426     if (swapchain->device->bCursorVisible &&
427         swapchain->device->cursorTexture &&
428         !swapchain->device->hardwareCursor)
429     {
430         struct wined3d_surface cursor;
431         RECT destRect =
432         {
433             swapchain->device->xScreenSpace - swapchain->device->xHotSpot,
434             swapchain->device->yScreenSpace - swapchain->device->yHotSpot,
435             swapchain->device->xScreenSpace + swapchain->device->cursorWidth - swapchain->device->xHotSpot,
436             swapchain->device->yScreenSpace + swapchain->device->cursorHeight - swapchain->device->yHotSpot,
437         };
438         TRACE("Rendering the cursor. Creating fake surface at %p\n", &cursor);
439         /* Build a fake surface to call the Blitting code. It is not possible to use the interface passed by
440          * the application because we are only supposed to copy the information out. Using a fake surface
441          * allows to use the Blitting engine and avoid copying the whole texture -> render target blitting code.
442          */
443         memset(&cursor, 0, sizeof(cursor));
444         cursor.resource.ref = 1;
445         cursor.resource.device = swapchain->device;
446         cursor.resource.pool = WINED3DPOOL_SCRATCH;
447         cursor.resource.format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
448         cursor.resource.resourceType = WINED3DRTYPE_SURFACE;
449         cursor.texture_name = swapchain->device->cursorTexture;
450         cursor.texture_target = GL_TEXTURE_2D;
451         cursor.texture_level = 0;
452         cursor.resource.width = swapchain->device->cursorWidth;
453         cursor.resource.height = swapchain->device->cursorHeight;
454         /* The cursor must have pow2 sizes */
455         cursor.pow2Width = cursor.resource.width;
456         cursor.pow2Height = cursor.resource.height;
457         /* The surface is in the texture */
458         cursor.flags |= SFLAG_INTEXTURE;
459         /* DDBLT_KEYSRC will cause BltOverride to enable the alpha test with GL_NOTEQUAL, 0.0,
460          * which is exactly what we want :-)
461          */
462         if (swapchain->presentParms.Windowed)
463             MapWindowPoints(NULL, swapchain->win_handle, (LPPOINT)&destRect, 2);
464         wined3d_surface_blt(swapchain->back_buffers[0], &destRect,
465                 &cursor, NULL, WINEDDBLT_KEYSRC, NULL, WINED3DTEXF_POINT);
466     }
467
468     if (swapchain->device->logo_surface)
469     {
470         /* Blit the logo into the upper left corner of the drawable. */
471         wined3d_surface_bltfast(swapchain->back_buffers[0], 0, 0,
472                 swapchain->device->logo_surface, NULL, WINEDDBLTFAST_SRCCOLORKEY);
473     }
474
475     TRACE("Presenting HDC %p.\n", context->hdc);
476
477     render_to_fbo = swapchain->render_to_fbo;
478
479     if (src_rect_in)
480     {
481         src_rect = *src_rect_in;
482         if (!render_to_fbo && (src_rect.left || src_rect.top
483                 || src_rect.right != swapchain->presentParms.BackBufferWidth
484                 || src_rect.bottom != swapchain->presentParms.BackBufferHeight))
485         {
486             render_to_fbo = TRUE;
487         }
488     }
489     else
490     {
491         src_rect.left = 0;
492         src_rect.top = 0;
493         src_rect.right = swapchain->presentParms.BackBufferWidth;
494         src_rect.bottom = swapchain->presentParms.BackBufferHeight;
495     }
496
497     if (dst_rect_in)
498         dst_rect = *dst_rect_in;
499     else
500         GetClientRect(swapchain->win_handle, &dst_rect);
501
502     if (!render_to_fbo && (dst_rect.left || dst_rect.top
503             || dst_rect.right != swapchain->presentParms.BackBufferWidth
504             || dst_rect.bottom != swapchain->presentParms.BackBufferHeight))
505     {
506         render_to_fbo = TRUE;
507     }
508
509     /* Rendering to a window of different size, presenting partial rectangles,
510      * or rendering to a different window needs help from FBO_blit or a textured
511      * draw. Render the swapchain to a FBO in the future.
512      *
513      * Note that FBO_blit from the backbuffer to the frontbuffer cannot solve
514      * all these issues - this fails if the window is smaller than the backbuffer.
515      */
516     if (!swapchain->render_to_fbo && render_to_fbo && wined3d_settings.offscreen_rendering_mode == ORM_FBO)
517     {
518         surface_load_location(swapchain->back_buffers[0], SFLAG_INTEXTURE, NULL);
519         surface_modify_location(swapchain->back_buffers[0], SFLAG_INDRAWABLE, FALSE);
520         swapchain->render_to_fbo = TRUE;
521     }
522
523     if (swapchain->render_to_fbo)
524     {
525         /* This codepath should only be hit with the COPY swapeffect. Otherwise a backbuffer-
526          * window size mismatch is impossible(fullscreen) and src and dst rectangles are
527          * not allowed(they need the COPY swapeffect)
528          *
529          * The DISCARD swap effect is ok as well since any backbuffer content is allowed after
530          * the swap. */
531         if (swapchain->presentParms.SwapEffect == WINED3DSWAPEFFECT_FLIP)
532             FIXME("Render-to-fbo with WINED3DSWAPEFFECT_FLIP\n");
533
534         swapchain_blit(swapchain, context, &src_rect, &dst_rect);
535     }
536
537     if (swapchain->num_contexts > 1)
538         wglFinish();
539     SwapBuffers(context->hdc); /* TODO: cycle through the swapchain buffers */
540
541     TRACE("SwapBuffers called, Starting new frame\n");
542     /* FPS support */
543     if (TRACE_ON(fps))
544     {
545         DWORD time = GetTickCount();
546         ++swapchain->frames;
547
548         /* every 1.5 seconds */
549         if (time - swapchain->prev_time > 1500)
550         {
551             TRACE_(fps)("%p @ approx %.2ffps\n",
552                     swapchain, 1000.0 * swapchain->frames / (time - swapchain->prev_time));
553             swapchain->prev_time = time;
554             swapchain->frames = 0;
555         }
556     }
557
558     /* This is disabled, but the code left in for debug purposes.
559      *
560      * Since we're allowed to modify the new back buffer on a D3DSWAPEFFECT_DISCARD flip,
561      * we can clear it with some ugly color to make bad drawing visible and ease debugging.
562      * The Debug runtime does the same on Windows. However, a few games do not redraw the
563      * screen properly, like Max Payne 2, which leaves a few pixels undefined.
564      *
565      * Tests show that the content of the back buffer after a discard flip is indeed not
566      * reliable, so no game can depend on the exact content. However, it resembles the
567      * old contents in some way, for example by showing fragments at other locations. In
568      * general, the color theme is still intact. So Max payne, which draws rather dark scenes
569      * gets a dark background image. If we clear it with a bright ugly color, the game's
570      * bug shows up much more than it does on Windows, and the players see single pixels
571      * with wrong colors.
572      * (The Max Payne bug has been confirmed on Windows with the debug runtime) */
573     if (FALSE && swapchain->presentParms.SwapEffect == WINED3DSWAPEFFECT_DISCARD)
574     {
575         TRACE("Clearing the color buffer with cyan color\n");
576
577         wined3d_device_clear(swapchain->device, 0, NULL,
578                 WINED3DCLEAR_TARGET, 0xff00ffff, 1.0f, 0);
579     }
580
581     if (!swapchain->render_to_fbo && ((swapchain->front_buffer->flags & SFLAG_INSYSMEM)
582             || (swapchain->back_buffers[0]->flags & SFLAG_INSYSMEM)))
583     {
584         /* Both memory copies of the surfaces are ok, flip them around too instead of dirtifying
585          * Doesn't work with render_to_fbo because we're not flipping
586          */
587         struct wined3d_surface *front = swapchain->front_buffer;
588         struct wined3d_surface *back = swapchain->back_buffers[0];
589
590         if(front->resource.size == back->resource.size) {
591             DWORD fbflags;
592             flip_surface(front, back);
593
594             /* Tell the front buffer surface that is has been modified. However,
595              * the other locations were preserved during that, so keep the flags.
596              * This serves to update the emulated overlay, if any. */
597             fbflags = front->flags;
598             surface_modify_location(front, SFLAG_INDRAWABLE, TRUE);
599             front->flags = fbflags;
600         }
601         else
602         {
603             surface_modify_location(front, SFLAG_INDRAWABLE, TRUE);
604             surface_modify_location(back, SFLAG_INDRAWABLE, TRUE);
605         }
606     }
607     else
608     {
609         surface_modify_location(swapchain->front_buffer, SFLAG_INDRAWABLE, TRUE);
610         /* If the swapeffect is DISCARD, the back buffer is undefined. That means the SYSMEM
611          * and INTEXTURE copies can keep their old content if they have any defined content.
612          * If the swapeffect is COPY, the content remains the same. If it is FLIP however,
613          * the texture / sysmem copy needs to be reloaded from the drawable
614          */
615         if (swapchain->presentParms.SwapEffect == WINED3DSWAPEFFECT_FLIP)
616             surface_modify_location(swapchain->back_buffers[0], SFLAG_INDRAWABLE, TRUE);
617     }
618
619     if (fb->depth_stencil)
620     {
621         if (swapchain->presentParms.Flags & WINED3DPRESENTFLAG_DISCARD_DEPTHSTENCIL
622                 || fb->depth_stencil->flags & SFLAG_DISCARD)
623         {
624             surface_modify_ds_location(fb->depth_stencil, SFLAG_DS_DISCARDED,
625                     fb->depth_stencil->resource.width,
626                     fb->depth_stencil->resource.height);
627             if (fb->depth_stencil == swapchain->device->onscreen_depth_stencil)
628             {
629                 wined3d_surface_decref(swapchain->device->onscreen_depth_stencil);
630                 swapchain->device->onscreen_depth_stencil = NULL;
631             }
632         }
633     }
634
635     context_release(context);
636
637     TRACE("returning\n");
638     return WINED3D_OK;
639 }
640
641 static const struct wined3d_swapchain_ops swapchain_gl_ops =
642 {
643     swapchain_gl_present,
644 };
645
646 /* Helper function that blits the front buffer contents to the target window. */
647 void x11_copy_to_screen(const struct wined3d_swapchain *swapchain, const RECT *rect)
648 {
649     const struct wined3d_surface *front;
650     POINT offset = {0, 0};
651     HDC src_dc, dst_dc;
652     RECT draw_rect;
653     HWND window;
654
655     TRACE("swapchain %p, rect %s.\n", swapchain, wine_dbgstr_rect(rect));
656
657     front = swapchain->front_buffer;
658     if (!(front->resource.usage & WINED3DUSAGE_RENDERTARGET))
659         return;
660
661     TRACE("Copying surface %p to screen.\n", front);
662
663     src_dc = front->hDC;
664     window = swapchain->win_handle;
665     dst_dc = GetDCEx(window, 0, DCX_CLIPSIBLINGS | DCX_CACHE);
666
667     /* Front buffer coordinates are screen coordinates. Map them to the
668      * destination window if not fullscreened. */
669     if (swapchain->presentParms.Windowed)
670         ClientToScreen(window, &offset);
671
672     TRACE("offset %s.\n", wine_dbgstr_point(&offset));
673
674 #if 0
675     /* FIXME: This doesn't work... if users really want to run
676      * X in 8bpp, then we need to call directly into display.drv
677      * (or Wine's equivalent), and force a private colormap
678      * without default entries. */
679     if (front->palette)
680     {
681         SelectPalette(dst_dc, front->palette->hpal, FALSE);
682         RealizePalette(dst_dc); /* sends messages => deadlocks */
683     }
684 #endif
685
686     draw_rect.left = 0;
687     draw_rect.right = front->resource.width;
688     draw_rect.top = 0;
689     draw_rect.bottom = front->resource.height;
690
691 #if 0
692     /* TODO: Support clippers. */
693     if (front->clipper)
694     {
695         RECT xrc;
696         HWND hwnd = front->clipper->hWnd;
697         if (hwnd && GetClientRect(hwnd,&xrc))
698         {
699             OffsetRect(&xrc, offset.x, offset.y);
700             IntersectRect(&draw_rect, &draw_rect, &xrc);
701         }
702     }
703 #endif
704
705     if (!rect)
706     {
707         /* Only use this if the caller did not pass a rectangle, since
708          * due to double locking this could be the wrong one... */
709         if (front->lockedRect.left != front->lockedRect.right)
710             IntersectRect(&draw_rect, &draw_rect, &front->lockedRect);
711     }
712     else
713     {
714         IntersectRect(&draw_rect, &draw_rect, rect);
715     }
716
717     BitBlt(dst_dc, draw_rect.left - offset.x, draw_rect.top - offset.y,
718             draw_rect.right - draw_rect.left, draw_rect.bottom - draw_rect.top,
719             src_dc, draw_rect.left, draw_rect.top, SRCCOPY);
720     ReleaseDC(window, dst_dc);
721 }
722
723 static HRESULT swapchain_gdi_present(struct wined3d_swapchain *swapchain, const RECT *src_rect_in,
724         const RECT *dst_rect_in, const RGNDATA *dirty_region, DWORD flags)
725 {
726     struct wined3d_surface *front, *back;
727
728     if (!swapchain->back_buffers)
729     {
730         WARN("Swapchain doesn't have a backbuffer, returning WINED3DERR_INVALIDCALL\n");
731         return WINED3DERR_INVALIDCALL;
732     }
733     front = swapchain->front_buffer;
734     back = swapchain->back_buffers[0];
735
736     /* Flip the DC. */
737     {
738         HDC tmp;
739         tmp = front->hDC;
740         front->hDC = back->hDC;
741         back->hDC = tmp;
742     }
743
744     /* Flip the DIBsection. */
745     {
746         HBITMAP tmp;
747         tmp = front->dib.DIBsection;
748         front->dib.DIBsection = back->dib.DIBsection;
749         back->dib.DIBsection = tmp;
750     }
751
752     /* Flip the surface data. */
753     {
754         void *tmp;
755
756         tmp = front->dib.bitmap_data;
757         front->dib.bitmap_data = back->dib.bitmap_data;
758         back->dib.bitmap_data = tmp;
759
760         tmp = front->resource.allocatedMemory;
761         front->resource.allocatedMemory = back->resource.allocatedMemory;
762         back->resource.allocatedMemory = tmp;
763
764         if (front->resource.heapMemory)
765             ERR("GDI Surface %p has heap memory allocated.\n", front);
766
767         if (back->resource.heapMemory)
768             ERR("GDI Surface %p has heap memory allocated.\n", back);
769     }
770
771     /* Client_memory should not be different, but just in case. */
772     {
773         BOOL tmp;
774         tmp = front->dib.client_memory;
775         front->dib.client_memory = back->dib.client_memory;
776         back->dib.client_memory = tmp;
777     }
778
779     /* FPS support */
780     if (TRACE_ON(fps))
781     {
782         static LONG prev_time, frames;
783         DWORD time = GetTickCount();
784
785         ++frames;
786
787         /* every 1.5 seconds */
788         if (time - prev_time > 1500)
789         {
790             TRACE_(fps)("@ approx %.2ffps\n", 1000.0 * frames / (time - prev_time));
791             prev_time = time;
792             frames = 0;
793         }
794     }
795
796     x11_copy_to_screen(swapchain, NULL);
797
798     return WINED3D_OK;
799 }
800
801 static const struct wined3d_swapchain_ops swapchain_gdi_ops =
802 {
803     swapchain_gdi_present,
804 };
805
806 void swapchain_update_render_to_fbo(struct wined3d_swapchain *swapchain)
807 {
808     RECT client_rect;
809
810     if (wined3d_settings.offscreen_rendering_mode != ORM_FBO)
811         return;
812
813     if (!swapchain->presentParms.BackBufferCount)
814     {
815         TRACE("Single buffered rendering.\n");
816         swapchain->render_to_fbo = FALSE;
817         return;
818     }
819
820     GetClientRect(swapchain->win_handle, &client_rect);
821
822     TRACE("Backbuffer %ux%u, window %ux%u.\n",
823             swapchain->presentParms.BackBufferWidth,
824             swapchain->presentParms.BackBufferHeight,
825             client_rect.right, client_rect.bottom);
826
827     if (swapchain->presentParms.BackBufferWidth == client_rect.right
828             && swapchain->presentParms.BackBufferHeight == client_rect.bottom)
829     {
830         TRACE("Backbuffer dimensions match window dimensions, rendering onscreen.\n");
831         swapchain->render_to_fbo = FALSE;
832         return;
833     }
834
835     TRACE("Rendering to FBO.\n");
836     swapchain->render_to_fbo = TRUE;
837 }
838
839 /* Do not call while under the GL lock. */
840 static HRESULT swapchain_init(struct wined3d_swapchain *swapchain, WINED3DSURFTYPE surface_type,
841         struct wined3d_device *device, WINED3DPRESENT_PARAMETERS *present_parameters,
842         void *parent, const struct wined3d_parent_ops *parent_ops)
843 {
844     const struct wined3d_adapter *adapter = device->adapter;
845     const struct wined3d_format *format;
846     BOOL displaymode_set = FALSE;
847     WINED3DDISPLAYMODE mode;
848     RECT client_rect;
849     HWND window;
850     HRESULT hr;
851     UINT i;
852
853     if (present_parameters->BackBufferCount > WINED3DPRESENT_BACK_BUFFER_MAX)
854     {
855         FIXME("The application requested %u back buffers, this is not supported.\n",
856                 present_parameters->BackBufferCount);
857         return WINED3DERR_INVALIDCALL;
858     }
859
860     if (present_parameters->BackBufferCount > 1)
861     {
862         FIXME("The application requested more than one back buffer, this is not properly supported.\n"
863                 "Please configure the application to use double buffering (1 back buffer) if possible.\n");
864     }
865
866     switch (surface_type)
867     {
868         case SURFACE_GDI:
869             swapchain->swapchain_ops = &swapchain_gdi_ops;
870             break;
871
872         case SURFACE_OPENGL:
873             swapchain->swapchain_ops = &swapchain_gl_ops;
874             break;
875
876         case SURFACE_UNKNOWN:
877             FIXME("Caller tried to create a SURFACE_UNKNOWN swapchain.\n");
878             return WINED3DERR_INVALIDCALL;
879     }
880
881     window = present_parameters->hDeviceWindow ? present_parameters->hDeviceWindow : device->createParms.hFocusWindow;
882
883     swapchain->device = device;
884     swapchain->parent = parent;
885     swapchain->parent_ops = parent_ops;
886     swapchain->ref = 1;
887     swapchain->win_handle = window;
888     swapchain->device_window = window;
889
890     wined3d_get_adapter_display_mode(device->wined3d, adapter->ordinal, &mode);
891     swapchain->orig_width = mode.Width;
892     swapchain->orig_height = mode.Height;
893     swapchain->orig_fmt = mode.Format;
894     format = wined3d_get_format(&adapter->gl_info, mode.Format);
895
896     GetClientRect(window, &client_rect);
897     if (present_parameters->Windowed
898             && (!present_parameters->BackBufferWidth || !present_parameters->BackBufferHeight
899             || present_parameters->BackBufferFormat == WINED3DFMT_UNKNOWN))
900     {
901
902         if (!present_parameters->BackBufferWidth)
903         {
904             present_parameters->BackBufferWidth = client_rect.right;
905             TRACE("Updating width to %u.\n", present_parameters->BackBufferWidth);
906         }
907
908         if (!present_parameters->BackBufferHeight)
909         {
910             present_parameters->BackBufferHeight = client_rect.bottom;
911             TRACE("Updating height to %u.\n", present_parameters->BackBufferHeight);
912         }
913
914         if (present_parameters->BackBufferFormat == WINED3DFMT_UNKNOWN)
915         {
916             present_parameters->BackBufferFormat = swapchain->orig_fmt;
917             TRACE("Updating format to %s.\n", debug_d3dformat(swapchain->orig_fmt));
918         }
919     }
920     swapchain->presentParms = *present_parameters;
921     swapchain_update_render_to_fbo(swapchain);
922
923     TRACE("Creating front buffer.\n");
924     hr = device->device_parent->ops->create_rendertarget(device->device_parent, parent,
925             swapchain->presentParms.BackBufferWidth, swapchain->presentParms.BackBufferHeight,
926             swapchain->presentParms.BackBufferFormat, swapchain->presentParms.MultiSampleType,
927             swapchain->presentParms.MultiSampleQuality, TRUE /* Lockable */,
928             &swapchain->front_buffer);
929     if (FAILED(hr))
930     {
931         WARN("Failed to create front buffer, hr %#x.\n", hr);
932         goto err;
933     }
934
935     surface_set_container(swapchain->front_buffer, WINED3D_CONTAINER_SWAPCHAIN, swapchain);
936     if (surface_type == SURFACE_OPENGL)
937     {
938         surface_modify_location(swapchain->front_buffer, SFLAG_INDRAWABLE, TRUE);
939     }
940
941     /* MSDN says we're only allowed a single fullscreen swapchain per device,
942      * so we should really check to see if there is a fullscreen swapchain
943      * already. Does a single head count as full screen? */
944
945     if (!present_parameters->Windowed)
946     {
947         WINED3DDISPLAYMODE mode;
948
949         /* Change the display settings */
950         mode.Width = present_parameters->BackBufferWidth;
951         mode.Height = present_parameters->BackBufferHeight;
952         mode.Format = present_parameters->BackBufferFormat;
953         mode.RefreshRate = present_parameters->FullScreen_RefreshRateInHz;
954
955         hr = wined3d_device_set_display_mode(device, 0, &mode);
956         if (FAILED(hr))
957         {
958             WARN("Failed to set display mode, hr %#x.\n", hr);
959             goto err;
960         }
961         displaymode_set = TRUE;
962     }
963
964     if (surface_type == SURFACE_OPENGL)
965     {
966         static const enum wined3d_format_id formats[] =
967         {
968             WINED3DFMT_D24_UNORM_S8_UINT,
969             WINED3DFMT_D32_UNORM,
970             WINED3DFMT_R24_UNORM_X8_TYPELESS,
971             WINED3DFMT_D16_UNORM,
972             WINED3DFMT_S1_UINT_D15_UNORM
973         };
974
975         const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
976
977         swapchain->context = HeapAlloc(GetProcessHeap(), 0, sizeof(swapchain->context));
978         if (!swapchain->context)
979         {
980             ERR("Failed to create the context array.\n");
981             hr = E_OUTOFMEMORY;
982             goto err;
983         }
984         swapchain->num_contexts = 1;
985
986         /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
987          * You are able to add a depth + stencil surface at a later stage when you need it.
988          * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
989          * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
990          * context, need torecreate shaders, textures and other resources.
991          *
992          * The context manager already takes care of the state problem and for the other tasks code from Reset
993          * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
994          * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
995          * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
996          * issue needs to be fixed. */
997         for (i = 0; i < (sizeof(formats) / sizeof(*formats)); i++)
998         {
999             swapchain->ds_format = wined3d_get_format(gl_info, formats[i]);
1000             swapchain->context[0] = context_create(swapchain, swapchain->front_buffer, swapchain->ds_format);
1001             if (swapchain->context[0]) break;
1002             TRACE("Depth stencil format %s is not supported, trying next format\n",
1003                   debug_d3dformat(formats[i]));
1004         }
1005
1006         if (!swapchain->context[0])
1007         {
1008             WARN("Failed to create context.\n");
1009             hr = WINED3DERR_NOTAVAILABLE;
1010             goto err;
1011         }
1012
1013         if (!present_parameters->EnableAutoDepthStencil
1014                 || swapchain->presentParms.AutoDepthStencilFormat != swapchain->ds_format->id)
1015         {
1016             FIXME("Add OpenGL context recreation support to context_validate_onscreen_formats\n");
1017         }
1018         context_release(swapchain->context[0]);
1019     }
1020
1021     if (swapchain->presentParms.BackBufferCount > 0)
1022     {
1023         swapchain->back_buffers = HeapAlloc(GetProcessHeap(), 0,
1024                 sizeof(*swapchain->back_buffers) * swapchain->presentParms.BackBufferCount);
1025         if (!swapchain->back_buffers)
1026         {
1027             ERR("Failed to allocate backbuffer array memory.\n");
1028             hr = E_OUTOFMEMORY;
1029             goto err;
1030         }
1031
1032         for (i = 0; i < swapchain->presentParms.BackBufferCount; ++i)
1033         {
1034             TRACE("Creating back buffer %u.\n", i);
1035             hr = device->device_parent->ops->create_rendertarget(device->device_parent, parent,
1036                     swapchain->presentParms.BackBufferWidth, swapchain->presentParms.BackBufferHeight,
1037                     swapchain->presentParms.BackBufferFormat, swapchain->presentParms.MultiSampleType,
1038                     swapchain->presentParms.MultiSampleQuality, TRUE /* Lockable */,
1039                     &swapchain->back_buffers[i]);
1040             if (FAILED(hr))
1041             {
1042                 WARN("Failed to create back buffer %u, hr %#x.\n", i, hr);
1043                 goto err;
1044             }
1045
1046             surface_set_container(swapchain->back_buffers[i], WINED3D_CONTAINER_SWAPCHAIN, swapchain);
1047         }
1048     }
1049
1050     /* Swapchains share the depth/stencil buffer, so only create a single depthstencil surface. */
1051     if (present_parameters->EnableAutoDepthStencil && surface_type == SURFACE_OPENGL)
1052     {
1053         TRACE("Creating depth/stencil buffer.\n");
1054         if (!device->auto_depth_stencil)
1055         {
1056             hr = device->device_parent->ops->create_depth_stencil(device->device_parent,
1057                     swapchain->presentParms.BackBufferWidth, swapchain->presentParms.BackBufferHeight,
1058                     swapchain->presentParms.AutoDepthStencilFormat, swapchain->presentParms.MultiSampleType,
1059                     swapchain->presentParms.MultiSampleQuality, FALSE /* FIXME: Discard */,
1060                     &device->auto_depth_stencil);
1061             if (FAILED(hr))
1062             {
1063                 WARN("Failed to create the auto depth stencil, hr %#x.\n", hr);
1064                 goto err;
1065             }
1066
1067             surface_set_container(device->auto_depth_stencil, WINED3D_CONTAINER_NONE, NULL);
1068         }
1069     }
1070
1071     wined3d_swapchain_get_gamma_ramp(swapchain, &swapchain->orig_gamma);
1072
1073     return WINED3D_OK;
1074
1075 err:
1076     if (displaymode_set)
1077     {
1078         DEVMODEW devmode;
1079
1080         ClipCursor(NULL);
1081
1082         /* Change the display settings */
1083         memset(&devmode, 0, sizeof(devmode));
1084         devmode.dmSize = sizeof(devmode);
1085         devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
1086         devmode.dmBitsPerPel = format->byte_count * CHAR_BIT;
1087         devmode.dmPelsWidth = swapchain->orig_width;
1088         devmode.dmPelsHeight = swapchain->orig_height;
1089         ChangeDisplaySettingsExW(adapter->DeviceName, &devmode, NULL, CDS_FULLSCREEN, NULL);
1090     }
1091
1092     if (swapchain->back_buffers)
1093     {
1094         for (i = 0; i < swapchain->presentParms.BackBufferCount; ++i)
1095         {
1096             if (swapchain->back_buffers[i])
1097             {
1098                 surface_set_container(swapchain->back_buffers[i], WINED3D_CONTAINER_NONE, NULL);
1099                 wined3d_surface_decref(swapchain->back_buffers[i]);
1100             }
1101         }
1102         HeapFree(GetProcessHeap(), 0, swapchain->back_buffers);
1103     }
1104
1105     if (swapchain->context)
1106     {
1107         if (swapchain->context[0])
1108         {
1109             context_release(swapchain->context[0]);
1110             context_destroy(device, swapchain->context[0]);
1111             swapchain->num_contexts = 0;
1112         }
1113         HeapFree(GetProcessHeap(), 0, swapchain->context);
1114     }
1115
1116     if (swapchain->front_buffer)
1117     {
1118         surface_set_container(swapchain->front_buffer, WINED3D_CONTAINER_NONE, NULL);
1119         wined3d_surface_decref(swapchain->front_buffer);
1120     }
1121
1122     return hr;
1123 }
1124
1125 /* Do not call while under the GL lock. */
1126 HRESULT CDECL wined3d_swapchain_create(struct wined3d_device *device,
1127         WINED3DPRESENT_PARAMETERS *present_parameters, WINED3DSURFTYPE surface_type,
1128         void *parent, const struct wined3d_parent_ops *parent_ops,
1129         struct wined3d_swapchain **swapchain)
1130 {
1131     struct wined3d_swapchain *object;
1132     HRESULT hr;
1133
1134     TRACE("device %p, present_parameters %p, swapchain %p, parent %p, surface_type %#x.\n",
1135             device, present_parameters, swapchain, parent, surface_type);
1136
1137     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1138     if (!object)
1139     {
1140         ERR("Failed to allocate swapchain memory.\n");
1141         return E_OUTOFMEMORY;
1142     }
1143
1144     hr = swapchain_init(object, surface_type, device, present_parameters, parent, parent_ops);
1145     if (FAILED(hr))
1146     {
1147         WARN("Failed to initialize swapchain, hr %#x.\n", hr);
1148         HeapFree(GetProcessHeap(), 0, object);
1149         return hr;
1150     }
1151
1152     TRACE("Created swapchain %p.\n", object);
1153     *swapchain = object;
1154
1155     return WINED3D_OK;
1156 }
1157
1158 /* Do not call while under the GL lock. */
1159 static struct wined3d_context *swapchain_create_context(struct wined3d_swapchain *swapchain)
1160 {
1161     struct wined3d_context **newArray;
1162     struct wined3d_context *ctx;
1163
1164     TRACE("Creating a new context for swapchain %p, thread %u.\n", swapchain, GetCurrentThreadId());
1165
1166     if (!(ctx = context_create(swapchain, swapchain->front_buffer, swapchain->ds_format)))
1167     {
1168         ERR("Failed to create a new context for the swapchain\n");
1169         return NULL;
1170     }
1171     context_release(ctx);
1172
1173     newArray = HeapAlloc(GetProcessHeap(), 0, sizeof(*newArray) * (swapchain->num_contexts + 1));
1174     if(!newArray) {
1175         ERR("Out of memory when trying to allocate a new context array\n");
1176         context_destroy(swapchain->device, ctx);
1177         return NULL;
1178     }
1179     memcpy(newArray, swapchain->context, sizeof(*newArray) * swapchain->num_contexts);
1180     HeapFree(GetProcessHeap(), 0, swapchain->context);
1181     newArray[swapchain->num_contexts] = ctx;
1182     swapchain->context = newArray;
1183     swapchain->num_contexts++;
1184
1185     TRACE("Returning context %p\n", ctx);
1186     return ctx;
1187 }
1188
1189 void swapchain_destroy_contexts(struct wined3d_swapchain *swapchain)
1190 {
1191     unsigned int i;
1192
1193     for (i = 0; i < swapchain->num_contexts; ++i)
1194     {
1195         context_destroy(swapchain->device, swapchain->context[i]);
1196     }
1197     swapchain->num_contexts = 0;
1198 }
1199
1200 struct wined3d_context *swapchain_get_context(struct wined3d_swapchain *swapchain)
1201 {
1202     DWORD tid = GetCurrentThreadId();
1203     unsigned int i;
1204
1205     for (i = 0; i < swapchain->num_contexts; ++i)
1206     {
1207         if (swapchain->context[i]->tid == tid)
1208             return swapchain->context[i];
1209     }
1210
1211     /* Create a new context for the thread */
1212     return swapchain_create_context(swapchain);
1213 }
1214
1215 void get_drawable_size_swapchain(const struct wined3d_context *context, UINT *width, UINT *height)
1216 {
1217     /* The drawable size of an onscreen drawable is the surface size.
1218      * (Actually: The window size, but the surface is created in window size) */
1219     *width = context->current_rt->resource.width;
1220     *height = context->current_rt->resource.height;
1221 }
1222
1223 HDC swapchain_get_backup_dc(struct wined3d_swapchain *swapchain)
1224 {
1225     if (!swapchain->backup_dc)
1226     {
1227         TRACE("Creating the backup window for swapchain %p.\n", swapchain);
1228
1229         if (!(swapchain->backup_wnd = CreateWindowA(WINED3D_OPENGL_WINDOW_CLASS_NAME, "WineD3D fake window",
1230                 WS_OVERLAPPEDWINDOW, 10, 10, 10, 10, NULL, NULL, NULL, NULL)))
1231         {
1232             ERR("Failed to create a window.\n");
1233             return NULL;
1234         }
1235
1236         if (!(swapchain->backup_dc = GetDC(swapchain->backup_wnd)))
1237         {
1238             ERR("Failed to get a DC.\n");
1239             DestroyWindow(swapchain->backup_wnd);
1240             swapchain->backup_wnd = NULL;
1241             return NULL;
1242         }
1243     }
1244
1245     return swapchain->backup_dc;
1246 }