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