wined3d: Get rid of the now redundant SFLAG_SWAPCHAIN surface flag.
[wine] / dlls / wined3d / swapchain.c
1 /*
2  *IDirect3DSwapChain9 implementation
3  *
4  *Copyright 2002-2003 Jason Edmeades
5  *Copyright 2002-2003 Raphael Junqueira
6  *Copyright 2005 Oliver Stieber
7  *Copyright 2007-2008 Stefan Dösinger for CodeWeavers
8  *
9  *This library is free software; you can redistribute it and/or
10  *modify it under the terms of the GNU Lesser General Public
11  *License as published by the Free Software Foundation; either
12  *version 2.1 of the License, or (at your option) any later version.
13  *
14  *This library is distributed in the hope that it will be useful,
15  *but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  *Lesser General Public License for more details.
18  *
19  *You should have received a copy of the GNU Lesser General Public
20  *License along with this library; if not, write to the Free Software
21  *Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23
24 #include "config.h"
25 #include "wined3d_private.h"
26
27
28 /*TODO: some of the additional parameters may be required to
29     set the gamma ramp (for some weird reason microsoft have left swap gammaramp in device
30     but it operates on a swapchain, it may be a good idea to move it to IWineD3DSwapChain for IWineD3D)*/
31
32
33 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
34 WINE_DECLARE_DEBUG_CHANNEL(fps);
35
36 /*IWineD3DSwapChain parts follow: */
37 static void WINAPI IWineD3DSwapChainImpl_Destroy(IWineD3DSwapChain *iface)
38 {
39     IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *)iface;
40     WINED3DDISPLAYMODE mode;
41     unsigned int i;
42
43     TRACE("Destroying swapchain %p\n", iface);
44
45     IWineD3DSwapChain_SetGammaRamp(iface, 0, &This->orig_gamma);
46
47     /* Release the swapchain's draw buffers. Make sure This->back_buffers[0] is
48      * the last buffer to be destroyed, FindContext() depends on that. */
49     if (This->front_buffer)
50     {
51         surface_set_container(This->front_buffer, WINED3D_CONTAINER_NONE, NULL);
52         if (IWineD3DSurface_Release((IWineD3DSurface *)This->front_buffer))
53         {
54             WARN("(%p) Something's still holding the front buffer (%p).\n",
55                     This, This->front_buffer);
56         }
57         This->front_buffer = NULL;
58     }
59
60     if (This->back_buffers)
61     {
62         UINT i = This->presentParms.BackBufferCount;
63
64         while (i--)
65         {
66             surface_set_container(This->back_buffers[i], WINED3D_CONTAINER_NONE, NULL);
67             if (IWineD3DSurface_Release((IWineD3DSurface *)This->back_buffers[i]))
68                 WARN("(%p) Something's still holding back buffer %u (%p).\n",
69                         This, i, This->back_buffers[i]);
70         }
71         HeapFree(GetProcessHeap(), 0, This->back_buffers);
72         This->back_buffers = NULL;
73     }
74
75     for (i = 0; i < This->num_contexts; ++i)
76     {
77         context_destroy(This->device, This->context[i]);
78     }
79     /* Restore the screen resolution if we rendered in fullscreen
80      * This will restore the screen resolution to what it was before creating the swapchain. In case of d3d8 and d3d9
81      * this will be the original desktop resolution. In case of d3d7 this will be a NOP because ddraw sets the resolution
82      * before starting up Direct3D, thus orig_width and orig_height will be equal to the modes in the presentation params
83      */
84     if(This->presentParms.Windowed == FALSE && This->presentParms.AutoRestoreDisplayMode) {
85         mode.Width = This->orig_width;
86         mode.Height = This->orig_height;
87         mode.RefreshRate = 0;
88         mode.Format = This->orig_fmt;
89         IWineD3DDevice_SetDisplayMode((IWineD3DDevice *)This->device, 0, &mode);
90     }
91
92     HeapFree(GetProcessHeap(), 0, This->context);
93     HeapFree(GetProcessHeap(), 0, This);
94 }
95
96 /* A GL context is provided by the caller */
97 static void swapchain_blit(IWineD3DSwapChainImpl *This, struct wined3d_context *context,
98         const RECT *src_rect, const RECT *dst_rect)
99 {
100     IWineD3DDeviceImpl *device = This->device;
101     IWineD3DSurfaceImpl *backbuffer = This->back_buffers[0];
102     UINT src_w = src_rect->right - src_rect->left;
103     UINT src_h = src_rect->bottom - src_rect->top;
104     GLenum gl_filter;
105     const struct wined3d_gl_info *gl_info = context->gl_info;
106     RECT win_rect;
107     UINT win_h;
108
109     TRACE("swapchain %p, context %p, src_rect %s, dst_rect %s.\n",
110             This, context, wine_dbgstr_rect(src_rect), wine_dbgstr_rect(dst_rect));
111
112     if (src_w == dst_rect->right - dst_rect->left && src_h == dst_rect->bottom - dst_rect->top)
113         gl_filter = GL_NEAREST;
114     else
115         gl_filter = GL_LINEAR;
116
117     GetClientRect(This->win_handle, &win_rect);
118     win_h = win_rect.bottom - win_rect.top;
119
120     if (gl_info->fbo_ops.glBlitFramebuffer && is_identity_fixup(backbuffer->resource.format_desc->color_fixup))
121     {
122         ENTER_GL();
123         context_apply_fbo_state_blit(context, GL_READ_FRAMEBUFFER, backbuffer, NULL, SFLAG_INTEXTURE);
124         glReadBuffer(GL_COLOR_ATTACHMENT0);
125
126         context_bind_fbo(context, GL_DRAW_FRAMEBUFFER, NULL);
127         context_set_draw_buffer(context, GL_BACK);
128
129         glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
130         IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_COLORWRITEENABLE));
131         IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_COLORWRITEENABLE1));
132         IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_COLORWRITEENABLE2));
133         IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_COLORWRITEENABLE3));
134
135         glDisable(GL_SCISSOR_TEST);
136         IWineD3DDeviceImpl_MarkStateDirty(This->device, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE));
137
138         /* Note that the texture is upside down */
139         gl_info->fbo_ops.glBlitFramebuffer(src_rect->left, src_rect->top, src_rect->right, src_rect->bottom,
140                 dst_rect->left, win_h - dst_rect->top, dst_rect->right, win_h - dst_rect->bottom,
141                 GL_COLOR_BUFFER_BIT, gl_filter);
142         checkGLcall("Swapchain present blit(EXT_framebuffer_blit)\n");
143         LEAVE_GL();
144     }
145     else
146     {
147         struct wined3d_context *context2;
148         float tex_left = src_rect->left;
149         float tex_top = src_rect->top;
150         float tex_right = src_rect->right;
151         float tex_bottom = src_rect->bottom;
152
153         context2 = context_acquire(This->device, This->back_buffers[0]);
154         context_apply_blit_state(context2, device);
155
156         if(backbuffer->Flags & SFLAG_NORMCOORD)
157         {
158             tex_left /= src_w;
159             tex_right /= src_w;
160             tex_top /= src_h;
161             tex_bottom /= src_h;
162         }
163
164         if (is_complex_fixup(backbuffer->resource.format_desc->color_fixup))
165             gl_filter = GL_NEAREST;
166
167         ENTER_GL();
168         context_bind_fbo(context2, GL_DRAW_FRAMEBUFFER, NULL);
169
170         /* Set up the texture. The surface is not in a IWineD3D*Texture container,
171          * so there are no d3d texture settings to dirtify
172          */
173         device->blitter->set_shader((IWineD3DDevice *) device, backbuffer);
174         glTexParameteri(backbuffer->texture_target, GL_TEXTURE_MIN_FILTER, gl_filter);
175         glTexParameteri(backbuffer->texture_target, GL_TEXTURE_MAG_FILTER, gl_filter);
176
177         context_set_draw_buffer(context, GL_BACK);
178
179         /* Set the viewport to the destination rectandle, disable any projection
180          * transformation set up by context_apply_blit_state(), and draw a
181          * (-1,-1)-(1,1) quad.
182          *
183          * Back up viewport and matrix to avoid breaking last_was_blit
184          *
185          * Note that context_apply_blit_state() set up viewport and ortho to
186          * match the surface size - we want the GL drawable(=window) size. */
187         glPushAttrib(GL_VIEWPORT_BIT);
188         glViewport(dst_rect->left, win_h - dst_rect->bottom, dst_rect->right, win_h - dst_rect->top);
189         glMatrixMode(GL_PROJECTION);
190         glPushMatrix();
191         glLoadIdentity();
192
193         glBegin(GL_QUADS);
194             /* bottom left */
195             glTexCoord2f(tex_left, tex_bottom);
196             glVertex2i(-1, -1);
197
198             /* top left */
199             glTexCoord2f(tex_left, tex_top);
200             glVertex2i(-1, 1);
201
202             /* top right */
203             glTexCoord2f(tex_right, tex_top);
204             glVertex2i(1, 1);
205
206             /* bottom right */
207             glTexCoord2f(tex_right, tex_bottom);
208             glVertex2i(1, -1);
209         glEnd();
210
211         glPopMatrix();
212         glPopAttrib();
213
214         device->blitter->unset_shader((IWineD3DDevice *) device);
215         checkGLcall("Swapchain present blit(manual)\n");
216         LEAVE_GL();
217
218         context_release(context2);
219     }
220 }
221
222 static HRESULT WINAPI IWineD3DSwapChainImpl_Present(IWineD3DSwapChain *iface, CONST RECT *pSourceRect, CONST RECT *pDestRect, HWND hDestWindowOverride, CONST RGNDATA *pDirtyRegion, DWORD dwFlags) {
223     IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *)iface;
224     const struct wined3d_gl_info *gl_info;
225     struct wined3d_context *context;
226     RECT src_rect, dst_rect;
227     BOOL render_to_fbo;
228     unsigned int sync;
229     int retval;
230
231     IWineD3DSwapChain_SetDestWindowOverride(iface, hDestWindowOverride);
232
233     context = context_acquire(This->device, This->back_buffers[0]);
234     if (!context->valid)
235     {
236         context_release(context);
237         WARN("Invalid context, skipping present.\n");
238         return WINED3D_OK;
239     }
240
241     gl_info = context->gl_info;
242
243     /* Render the cursor onto the back buffer, using our nifty directdraw blitting code :-) */
244     if (This->device->bCursorVisible && This->device->cursorTexture)
245     {
246         IWineD3DSurfaceImpl cursor;
247         RECT destRect =
248         {
249             This->device->xScreenSpace - This->device->xHotSpot,
250             This->device->yScreenSpace - This->device->yHotSpot,
251             This->device->xScreenSpace + This->device->cursorWidth - This->device->xHotSpot,
252             This->device->yScreenSpace + This->device->cursorHeight - This->device->yHotSpot,
253         };
254         TRACE("Rendering the cursor. Creating fake surface at %p\n", &cursor);
255         /* Build a fake surface to call the Blitting code. It is not possible to use the interface passed by
256          * the application because we are only supposed to copy the information out. Using a fake surface
257          * allows to use the Blitting engine and avoid copying the whole texture -> render target blitting code.
258          */
259         memset(&cursor, 0, sizeof(cursor));
260         cursor.lpVtbl = &IWineD3DSurface_Vtbl;
261         cursor.resource.ref = 1;
262         cursor.resource.device = This->device;
263         cursor.resource.pool = WINED3DPOOL_SCRATCH;
264         cursor.resource.format_desc = getFormatDescEntry(WINED3DFMT_B8G8R8A8_UNORM, gl_info);
265         cursor.resource.resourceType = WINED3DRTYPE_SURFACE;
266         cursor.texture_name = This->device->cursorTexture;
267         cursor.texture_target = GL_TEXTURE_2D;
268         cursor.texture_level = 0;
269         cursor.currentDesc.Width = This->device->cursorWidth;
270         cursor.currentDesc.Height = This->device->cursorHeight;
271         /* The cursor must have pow2 sizes */
272         cursor.pow2Width = cursor.currentDesc.Width;
273         cursor.pow2Height = cursor.currentDesc.Height;
274         /* The surface is in the texture */
275         cursor.Flags |= SFLAG_INTEXTURE;
276         /* DDBLT_KEYSRC will cause BltOverride to enable the alpha test with GL_NOTEQUAL, 0.0,
277          * which is exactly what we want :-)
278          */
279         if (This->presentParms.Windowed) {
280             MapWindowPoints(NULL, This->win_handle, (LPPOINT)&destRect, 2);
281         }
282         IWineD3DSurface_Blt((IWineD3DSurface *)This->back_buffers[0], &destRect, (IWineD3DSurface *)&cursor,
283                 NULL, WINEDDBLT_KEYSRC, NULL, WINED3DTEXF_POINT);
284     }
285
286     if (This->device->logo_surface)
287     {
288         /* Blit the logo into the upper left corner of the drawable. */
289         IWineD3DSurface_BltFast((IWineD3DSurface *)This->back_buffers[0], 0, 0,
290                 This->device->logo_surface, NULL, WINEDDBLTFAST_SRCCOLORKEY);
291     }
292
293     TRACE("Presenting HDC %p.\n", context->hdc);
294
295     render_to_fbo = This->render_to_fbo;
296
297     if (pSourceRect)
298     {
299         src_rect = *pSourceRect;
300         if (!render_to_fbo && (src_rect.left || src_rect.top
301                 || src_rect.right != This->presentParms.BackBufferWidth
302                 || src_rect.bottom != This->presentParms.BackBufferHeight))
303         {
304             render_to_fbo = TRUE;
305         }
306     }
307     else
308     {
309         src_rect.left = 0;
310         src_rect.top = 0;
311         src_rect.right = This->presentParms.BackBufferWidth;
312         src_rect.bottom = This->presentParms.BackBufferHeight;
313     }
314
315     if (pDestRect) dst_rect = *pDestRect;
316     else GetClientRect(This->win_handle, &dst_rect);
317
318     if (!render_to_fbo && (dst_rect.left || dst_rect.top
319             || dst_rect.right != This->presentParms.BackBufferWidth
320             || dst_rect.bottom != This->presentParms.BackBufferHeight))
321     {
322         render_to_fbo = TRUE;
323     }
324
325     /* Rendering to a window of different size, presenting partial rectangles,
326      * or rendering to a different window needs help from FBO_blit or a textured
327      * draw. Render the swapchain to a FBO in the future.
328      *
329      * Note that FBO_blit from the backbuffer to the frontbuffer cannot solve
330      * all these issues - this fails if the window is smaller than the backbuffer.
331      */
332     if (!This->render_to_fbo && render_to_fbo && wined3d_settings.offscreen_rendering_mode == ORM_FBO)
333     {
334         surface_load_location(This->back_buffers[0], SFLAG_INTEXTURE, NULL);
335         surface_modify_location(This->back_buffers[0], SFLAG_INDRAWABLE, FALSE);
336         This->render_to_fbo = TRUE;
337     }
338
339     if(This->render_to_fbo)
340     {
341         /* This codepath should only be hit with the COPY swapeffect. Otherwise a backbuffer-
342          * window size mismatch is impossible(fullscreen) and src and dst rectangles are
343          * not allowed(they need the COPY swapeffect)
344          *
345          * The DISCARD swap effect is ok as well since any backbuffer content is allowed after
346          * the swap
347          */
348         if(This->presentParms.SwapEffect == WINED3DSWAPEFFECT_FLIP )
349         {
350             FIXME("Render-to-fbo with WINED3DSWAPEFFECT_FLIP\n");
351         }
352
353         swapchain_blit(This, context, &src_rect, &dst_rect);
354     }
355
356     if (This->num_contexts > 1) wglFinish();
357     SwapBuffers(context->hdc); /* TODO: cycle through the swapchain buffers */
358
359     TRACE("SwapBuffers called, Starting new frame\n");
360     /* FPS support */
361     if (TRACE_ON(fps))
362     {
363         DWORD time = GetTickCount();
364         This->frames++;
365         /* every 1.5 seconds */
366         if (time - This->prev_time > 1500) {
367             TRACE_(fps)("%p @ approx %.2ffps\n", This, 1000.0*This->frames/(time - This->prev_time));
368             This->prev_time = time;
369             This->frames = 0;
370         }
371     }
372
373     /* This is disabled, but the code left in for debug purposes.
374      *
375      * Since we're allowed to modify the new back buffer on a D3DSWAPEFFECT_DISCARD flip,
376      * we can clear it with some ugly color to make bad drawing visible and ease debugging.
377      * The Debug runtime does the same on Windows. However, a few games do not redraw the
378      * screen properly, like Max Payne 2, which leaves a few pixels undefined.
379      *
380      * Tests show that the content of the back buffer after a discard flip is indeed not
381      * reliable, so no game can depend on the exact content. However, it resembles the
382      * old contents in some way, for example by showing fragments at other locations. In
383      * general, the color theme is still intact. So Max payne, which draws rather dark scenes
384      * gets a dark background image. If we clear it with a bright ugly color, the game's
385      * bug shows up much more than it does on Windows, and the players see single pixels
386      * with wrong colors.
387      * (The Max Payne bug has been confirmed on Windows with the debug runtime)
388      */
389     if (FALSE && This->presentParms.SwapEffect == WINED3DSWAPEFFECT_DISCARD) {
390         TRACE("Clearing the color buffer with cyan color\n");
391
392         IWineD3DDevice_Clear((IWineD3DDevice *)This->device, 0, NULL,
393                 WINED3DCLEAR_TARGET, 0xff00ffff, 1.0f, 0);
394     }
395
396     if (!This->render_to_fbo && ((This->front_buffer->Flags & SFLAG_INSYSMEM)
397             || (This->back_buffers[0]->Flags & SFLAG_INSYSMEM)))
398     {
399         /* Both memory copies of the surfaces are ok, flip them around too instead of dirtifying
400          * Doesn't work with render_to_fbo because we're not flipping
401          */
402         IWineD3DSurfaceImpl *front = This->front_buffer;
403         IWineD3DSurfaceImpl *back = This->back_buffers[0];
404
405         if(front->resource.size == back->resource.size) {
406             DWORD fbflags;
407             flip_surface(front, back);
408
409             /* Tell the front buffer surface that is has been modified. However,
410              * the other locations were preserved during that, so keep the flags.
411              * This serves to update the emulated overlay, if any
412              */
413             fbflags = front->Flags;
414             surface_modify_location(front, SFLAG_INDRAWABLE, TRUE);
415             front->Flags = fbflags;
416         }
417         else
418         {
419             surface_modify_location(front, SFLAG_INDRAWABLE, TRUE);
420             surface_modify_location(back, SFLAG_INDRAWABLE, TRUE);
421         }
422     }
423     else
424     {
425         surface_modify_location(This->front_buffer, SFLAG_INDRAWABLE, TRUE);
426         /* If the swapeffect is DISCARD, the back buffer is undefined. That means the SYSMEM
427          * and INTEXTURE copies can keep their old content if they have any defined content.
428          * If the swapeffect is COPY, the content remains the same. If it is FLIP however,
429          * the texture / sysmem copy needs to be reloaded from the drawable
430          */
431         if (This->presentParms.SwapEffect == WINED3DSWAPEFFECT_FLIP)
432         {
433             surface_modify_location(This->back_buffers[0], SFLAG_INDRAWABLE, TRUE);
434         }
435     }
436
437     if (This->device->depth_stencil)
438     {
439         if (This->presentParms.Flags & WINED3DPRESENTFLAG_DISCARD_DEPTHSTENCIL
440                 || This->device->depth_stencil->Flags & SFLAG_DISCARD)
441         {
442             surface_modify_ds_location(This->device->depth_stencil, SFLAG_DS_DISCARDED,
443                     This->device->depth_stencil->currentDesc.Width,
444                     This->device->depth_stencil->currentDesc.Height);
445             if (This->device->depth_stencil == This->device->onscreen_depth_stencil)
446             {
447                 IWineD3DSurface_Release((IWineD3DSurface *)This->device->onscreen_depth_stencil);
448                 This->device->onscreen_depth_stencil = NULL;
449             }
450         }
451     }
452
453     if (This->presentParms.PresentationInterval != WINED3DPRESENT_INTERVAL_IMMEDIATE
454             && gl_info->supported[SGI_VIDEO_SYNC])
455     {
456         retval = GL_EXTCALL(glXGetVideoSyncSGI(&sync));
457         if(retval != 0) {
458             ERR("glXGetVideoSyncSGI failed(retval = %d\n", retval);
459         }
460
461         switch(This->presentParms.PresentationInterval) {
462             case WINED3DPRESENT_INTERVAL_DEFAULT:
463             case WINED3DPRESENT_INTERVAL_ONE:
464                 if(sync <= This->vSyncCounter) {
465                     retval = GL_EXTCALL(glXWaitVideoSyncSGI(1, 0, &This->vSyncCounter));
466                 } else {
467                     This->vSyncCounter = sync;
468                 }
469                 break;
470             case WINED3DPRESENT_INTERVAL_TWO:
471                 if(sync <= This->vSyncCounter + 1) {
472                     retval = GL_EXTCALL(glXWaitVideoSyncSGI(2, This->vSyncCounter & 0x1, &This->vSyncCounter));
473                 } else {
474                     This->vSyncCounter = sync;
475                 }
476                 break;
477             case WINED3DPRESENT_INTERVAL_THREE:
478                 if(sync <= This->vSyncCounter + 2) {
479                     retval = GL_EXTCALL(glXWaitVideoSyncSGI(3, This->vSyncCounter % 0x3, &This->vSyncCounter));
480                 } else {
481                     This->vSyncCounter = sync;
482                 }
483                 break;
484             case WINED3DPRESENT_INTERVAL_FOUR:
485                 if(sync <= This->vSyncCounter + 3) {
486                     retval = GL_EXTCALL(glXWaitVideoSyncSGI(4, This->vSyncCounter & 0x3, &This->vSyncCounter));
487                 } else {
488                     This->vSyncCounter = sync;
489                 }
490                 break;
491             default:
492                 FIXME("Unknown presentation interval %08x\n", This->presentParms.PresentationInterval);
493         }
494     }
495
496     context_release(context);
497
498     TRACE("returning\n");
499     return WINED3D_OK;
500 }
501
502 static HRESULT WINAPI IWineD3DSwapChainImpl_SetDestWindowOverride(IWineD3DSwapChain *iface, HWND window)
503 {
504     IWineD3DSwapChainImpl *swapchain = (IWineD3DSwapChainImpl *)iface;
505
506     if (!window) window = swapchain->device_window;
507     if (window == swapchain->win_handle) return WINED3D_OK;
508
509     TRACE("Setting swapchain %p window from %p to %p\n", swapchain, swapchain->win_handle, window);
510     swapchain->win_handle = window;
511
512     return WINED3D_OK;
513 }
514
515 static const IWineD3DSwapChainVtbl IWineD3DSwapChain_Vtbl =
516 {
517     /* IUnknown */
518     IWineD3DBaseSwapChainImpl_QueryInterface,
519     IWineD3DBaseSwapChainImpl_AddRef,
520     IWineD3DBaseSwapChainImpl_Release,
521     /* IWineD3DSwapChain */
522     IWineD3DBaseSwapChainImpl_GetParent,
523     IWineD3DSwapChainImpl_Destroy,
524     IWineD3DBaseSwapChainImpl_GetDevice,
525     IWineD3DSwapChainImpl_Present,
526     IWineD3DSwapChainImpl_SetDestWindowOverride,
527     IWineD3DBaseSwapChainImpl_GetFrontBufferData,
528     IWineD3DBaseSwapChainImpl_GetBackBuffer,
529     IWineD3DBaseSwapChainImpl_GetRasterStatus,
530     IWineD3DBaseSwapChainImpl_GetDisplayMode,
531     IWineD3DBaseSwapChainImpl_GetPresentParameters,
532     IWineD3DBaseSwapChainImpl_SetGammaRamp,
533     IWineD3DBaseSwapChainImpl_GetGammaRamp
534 };
535
536 static LONG fullscreen_style(LONG style)
537 {
538     /* Make sure the window is managed, otherwise we won't get keyboard input. */
539     style |= WS_POPUP | WS_SYSMENU;
540     style &= ~(WS_CAPTION | WS_THICKFRAME);
541
542     return style;
543 }
544
545 static LONG fullscreen_exstyle(LONG exstyle)
546 {
547     /* Filter out window decorations. */
548     exstyle &= ~(WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE);
549
550     return exstyle;
551 }
552
553 void swapchain_setup_fullscreen_window(IWineD3DSwapChainImpl *swapchain, UINT w, UINT h)
554 {
555     IWineD3DDeviceImpl *device = swapchain->device;
556     HWND window = swapchain->device_window;
557     BOOL filter_messages;
558     LONG style, exstyle;
559
560     TRACE("Setting up window %p for fullscreen mode.\n", window);
561
562     if (device->style || device->exStyle)
563     {
564         ERR("Changing the window style for window %p, but another style (%08x, %08x) is already stored.\n",
565                 window, device->style, device->exStyle);
566     }
567
568     device->style = GetWindowLongW(window, GWL_STYLE);
569     device->exStyle = GetWindowLongW(window, GWL_EXSTYLE);
570
571     style = fullscreen_style(device->style);
572     exstyle = fullscreen_exstyle(device->exStyle);
573
574     TRACE("Old style was %08x, %08x, setting to %08x, %08x.\n",
575             device->style, device->exStyle, style, exstyle);
576
577     filter_messages = device->filter_messages;
578     device->filter_messages = TRUE;
579
580     SetWindowLongW(window, GWL_STYLE, style);
581     SetWindowLongW(window, GWL_EXSTYLE, exstyle);
582     SetWindowPos(window, HWND_TOP, 0, 0, w, h, SWP_FRAMECHANGED | SWP_SHOWWINDOW | SWP_NOACTIVATE);
583
584     device->filter_messages = filter_messages;
585 }
586
587 void swapchain_restore_fullscreen_window(IWineD3DSwapChainImpl *swapchain)
588 {
589     IWineD3DDeviceImpl *device = swapchain->device;
590     HWND window = swapchain->device_window;
591     BOOL filter_messages;
592     LONG style, exstyle;
593
594     if (!device->style && !device->exStyle) return;
595
596     TRACE("Restoring window style of window %p to %08x, %08x.\n",
597             window, device->style, device->exStyle);
598
599     style = GetWindowLongW(window, GWL_STYLE);
600     exstyle = GetWindowLongW(window, GWL_EXSTYLE);
601
602     filter_messages = device->filter_messages;
603     device->filter_messages = TRUE;
604
605     /* Only restore the style if the application didn't modify it during the
606      * fullscreen phase. Some applications change it before calling Reset()
607      * when switching between windowed and fullscreen modes (HL2), some
608      * depend on the original style (Eve Online). */
609     if (style == fullscreen_style(device->style) && exstyle == fullscreen_exstyle(device->exStyle))
610     {
611         SetWindowLongW(window, GWL_STYLE, device->style);
612         SetWindowLongW(window, GWL_EXSTYLE, device->exStyle);
613     }
614     SetWindowPos(window, 0, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER);
615
616     device->filter_messages = filter_messages;
617
618     /* Delete the old values. */
619     device->style = 0;
620     device->exStyle = 0;
621 }
622
623
624 HRESULT swapchain_init(IWineD3DSwapChainImpl *swapchain, WINED3DSURFTYPE surface_type,
625         IWineD3DDeviceImpl *device, WINED3DPRESENT_PARAMETERS *present_parameters, IUnknown *parent)
626 {
627     const struct wined3d_adapter *adapter = device->adapter;
628     const struct wined3d_format_desc *format_desc;
629     BOOL displaymode_set = FALSE;
630     WINED3DDISPLAYMODE mode;
631     RECT client_rect;
632     HWND window;
633     HRESULT hr;
634     UINT i;
635
636     if (present_parameters->BackBufferCount > WINED3DPRESENT_BACK_BUFFER_MAX)
637     {
638         FIXME("The application requested %u back buffers, this is not supported.\n",
639                 present_parameters->BackBufferCount);
640         return WINED3DERR_INVALIDCALL;
641     }
642
643     if (present_parameters->BackBufferCount > 1)
644     {
645         FIXME("The application requested more than one back buffer, this is not properly supported.\n"
646                 "Please configure the application to use double buffering (1 back buffer) if possible.\n");
647     }
648
649     switch (surface_type)
650     {
651         case SURFACE_GDI:
652             swapchain->lpVtbl = &IWineGDISwapChain_Vtbl;
653             break;
654
655         case SURFACE_OPENGL:
656             swapchain->lpVtbl = &IWineD3DSwapChain_Vtbl;
657             break;
658
659         case SURFACE_UNKNOWN:
660             FIXME("Caller tried to create a SURFACE_UNKNOWN swapchain.\n");
661             return WINED3DERR_INVALIDCALL;
662     }
663
664     window = present_parameters->hDeviceWindow ? present_parameters->hDeviceWindow : device->createParms.hFocusWindow;
665
666     swapchain->device = device;
667     swapchain->parent = parent;
668     swapchain->ref = 1;
669     swapchain->win_handle = window;
670     swapchain->device_window = window;
671
672     if (!present_parameters->Windowed && window)
673     {
674         swapchain_setup_fullscreen_window(swapchain, present_parameters->BackBufferWidth,
675                 present_parameters->BackBufferHeight);
676     }
677
678     IWineD3D_GetAdapterDisplayMode(device->wined3d, adapter->ordinal, &mode);
679     swapchain->orig_width = mode.Width;
680     swapchain->orig_height = mode.Height;
681     swapchain->orig_fmt = mode.Format;
682     format_desc = getFormatDescEntry(mode.Format, &adapter->gl_info);
683
684     GetClientRect(window, &client_rect);
685     if (present_parameters->Windowed
686             && (!present_parameters->BackBufferWidth || !present_parameters->BackBufferHeight
687             || present_parameters->BackBufferFormat == WINED3DFMT_UNKNOWN))
688     {
689
690         if (!present_parameters->BackBufferWidth)
691         {
692             present_parameters->BackBufferWidth = client_rect.right;
693             TRACE("Updating width to %u.\n", present_parameters->BackBufferWidth);
694         }
695
696         if (!present_parameters->BackBufferHeight)
697         {
698             present_parameters->BackBufferHeight = client_rect.bottom;
699             TRACE("Updating height to %u.\n", present_parameters->BackBufferHeight);
700         }
701
702         if (present_parameters->BackBufferFormat == WINED3DFMT_UNKNOWN)
703         {
704             present_parameters->BackBufferFormat = swapchain->orig_fmt;
705             TRACE("Updating format to %s.\n", debug_d3dformat(swapchain->orig_fmt));
706         }
707     }
708     swapchain->presentParms = *present_parameters;
709
710     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO
711             && present_parameters->BackBufferCount
712             && (present_parameters->BackBufferWidth != client_rect.right
713             || present_parameters->BackBufferHeight != client_rect.bottom))
714     {
715         TRACE("Rendering to FBO. Backbuffer %ux%u, window %ux%u.\n",
716                 present_parameters->BackBufferWidth,
717                 present_parameters->BackBufferHeight,
718                 client_rect.right, client_rect.bottom);
719         swapchain->render_to_fbo = TRUE;
720     }
721
722     TRACE("Creating front buffer.\n");
723     hr = IWineD3DDeviceParent_CreateRenderTarget(device->device_parent, parent,
724             swapchain->presentParms.BackBufferWidth, swapchain->presentParms.BackBufferHeight,
725             swapchain->presentParms.BackBufferFormat, swapchain->presentParms.MultiSampleType,
726             swapchain->presentParms.MultiSampleQuality, TRUE /* Lockable */,
727             (IWineD3DSurface **)&swapchain->front_buffer);
728     if (FAILED(hr))
729     {
730         WARN("Failed to create front buffer, hr %#x.\n", hr);
731         goto err;
732     }
733
734     surface_set_container(swapchain->front_buffer, WINED3D_CONTAINER_SWAPCHAIN, (IWineD3DBase *)swapchain);
735     if (surface_type == SURFACE_OPENGL)
736     {
737         surface_modify_location(swapchain->front_buffer, SFLAG_INDRAWABLE, TRUE);
738     }
739
740     /* MSDN says we're only allowed a single fullscreen swapchain per device,
741      * so we should really check to see if there is a fullscreen swapchain
742      * already. Does a single head count as full screen? */
743
744     if (!present_parameters->Windowed)
745     {
746         WINED3DDISPLAYMODE mode;
747
748         /* Change the display settings */
749         mode.Width = present_parameters->BackBufferWidth;
750         mode.Height = present_parameters->BackBufferHeight;
751         mode.Format = present_parameters->BackBufferFormat;
752         mode.RefreshRate = present_parameters->FullScreen_RefreshRateInHz;
753
754         hr = IWineD3DDevice_SetDisplayMode((IWineD3DDevice *)device, 0, &mode);
755         if (FAILED(hr))
756         {
757             WARN("Failed to set display mode, hr %#x.\n", hr);
758             goto err;
759         }
760         displaymode_set = TRUE;
761     }
762
763     swapchain->context = HeapAlloc(GetProcessHeap(), 0, sizeof(swapchain->context));
764     if (!swapchain->context)
765     {
766         ERR("Failed to create the context array.\n");
767         hr = E_OUTOFMEMORY;
768         goto err;
769     }
770     swapchain->num_contexts = 1;
771
772     if (surface_type == SURFACE_OPENGL)
773     {
774         WINED3DFORMAT formats[] =
775         {
776             WINED3DFMT_D24_UNORM_S8_UINT,
777             WINED3DFMT_D32_UNORM,
778             WINED3DFMT_R24_UNORM_X8_TYPELESS,
779             WINED3DFMT_D16_UNORM,
780             WINED3DFMT_S1_UINT_D15_UNORM
781         };
782
783         const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
784
785         /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
786          * You are able to add a depth + stencil surface at a later stage when you need it.
787          * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
788          * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
789          * context, need torecreate shaders, textures and other resources.
790          *
791          * The context manager already takes care of the state problem and for the other tasks code from Reset
792          * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
793          * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
794          * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
795          * issue needs to be fixed. */
796         for (i = 0; i < (sizeof(formats) / sizeof(*formats)); i++)
797         {
798             swapchain->ds_format = getFormatDescEntry(formats[i], gl_info);
799             swapchain->context[0] = context_create(swapchain, swapchain->front_buffer, swapchain->ds_format);
800             if (swapchain->context[0]) break;
801             TRACE("Depth stencil format %s is not supported, trying next format\n",
802                   debug_d3dformat(formats[i]));
803         }
804
805         if (!swapchain->context[0])
806         {
807             WARN("Failed to create context.\n");
808             hr = WINED3DERR_NOTAVAILABLE;
809             goto err;
810         }
811
812         if (!present_parameters->EnableAutoDepthStencil
813                 || swapchain->presentParms.AutoDepthStencilFormat != swapchain->ds_format->format)
814         {
815             FIXME("Add OpenGL context recreation support to context_validate_onscreen_formats\n");
816         }
817         context_release(swapchain->context[0]);
818     }
819     else
820     {
821         swapchain->context[0] = NULL;
822     }
823
824     if (swapchain->presentParms.BackBufferCount > 0)
825     {
826         swapchain->back_buffers = HeapAlloc(GetProcessHeap(), 0,
827                 sizeof(*swapchain->back_buffers) * swapchain->presentParms.BackBufferCount);
828         if (!swapchain->back_buffers)
829         {
830             ERR("Failed to allocate backbuffer array memory.\n");
831             hr = E_OUTOFMEMORY;
832             goto err;
833         }
834
835         for (i = 0; i < swapchain->presentParms.BackBufferCount; ++i)
836         {
837             TRACE("Creating back buffer %u.\n", i);
838             hr = IWineD3DDeviceParent_CreateRenderTarget(device->device_parent, parent,
839                     swapchain->presentParms.BackBufferWidth, swapchain->presentParms.BackBufferHeight,
840                     swapchain->presentParms.BackBufferFormat, swapchain->presentParms.MultiSampleType,
841                     swapchain->presentParms.MultiSampleQuality, TRUE /* Lockable */,
842                     (IWineD3DSurface **)&swapchain->back_buffers[i]);
843             if (FAILED(hr))
844             {
845                 WARN("Failed to create back buffer %u, hr %#x.\n", i, hr);
846                 goto err;
847             }
848
849             surface_set_container(swapchain->back_buffers[i], WINED3D_CONTAINER_SWAPCHAIN, (IWineD3DBase *)swapchain);
850         }
851     }
852
853     /* Swapchains share the depth/stencil buffer, so only create a single depthstencil surface. */
854     if (present_parameters->EnableAutoDepthStencil && surface_type == SURFACE_OPENGL)
855     {
856         TRACE("Creating depth/stencil buffer.\n");
857         if (!device->auto_depth_stencil)
858         {
859             hr = IWineD3DDeviceParent_CreateDepthStencilSurface(device->device_parent, parent,
860                     swapchain->presentParms.BackBufferWidth, swapchain->presentParms.BackBufferHeight,
861                     swapchain->presentParms.AutoDepthStencilFormat, swapchain->presentParms.MultiSampleType,
862                     swapchain->presentParms.MultiSampleQuality, FALSE /* FIXME: Discard */,
863                     (IWineD3DSurface **)&device->auto_depth_stencil);
864             if (FAILED(hr))
865             {
866                 WARN("Failed to create the auto depth stencil, hr %#x.\n", hr);
867                 goto err;
868             }
869
870             surface_set_container(device->auto_depth_stencil, WINED3D_CONTAINER_NONE, NULL);
871         }
872     }
873
874     IWineD3DSwapChain_GetGammaRamp((IWineD3DSwapChain *)swapchain, &swapchain->orig_gamma);
875
876     return WINED3D_OK;
877
878 err:
879     if (displaymode_set)
880     {
881         DEVMODEW devmode;
882
883         ClipCursor(NULL);
884
885         /* Change the display settings */
886         memset(&devmode, 0, sizeof(devmode));
887         devmode.dmSize = sizeof(devmode);
888         devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
889         devmode.dmBitsPerPel = format_desc->byte_count * 8;
890         devmode.dmPelsWidth = swapchain->orig_width;
891         devmode.dmPelsHeight = swapchain->orig_height;
892         ChangeDisplaySettingsExW(adapter->DeviceName, &devmode, NULL, CDS_FULLSCREEN, NULL);
893     }
894
895     if (swapchain->back_buffers)
896     {
897         for (i = 0; i < swapchain->presentParms.BackBufferCount; ++i)
898         {
899             if (swapchain->back_buffers[i]) IWineD3DSurface_Release((IWineD3DSurface *)swapchain->back_buffers[i]);
900         }
901         HeapFree(GetProcessHeap(), 0, swapchain->back_buffers);
902     }
903
904     if (swapchain->context)
905     {
906         if (swapchain->context[0])
907         {
908             context_release(swapchain->context[0]);
909             context_destroy(device, swapchain->context[0]);
910             swapchain->num_contexts = 0;
911         }
912         HeapFree(GetProcessHeap(), 0, swapchain->context);
913     }
914
915     if (swapchain->front_buffer) IWineD3DSurface_Release((IWineD3DSurface *)swapchain->front_buffer);
916
917     return hr;
918 }
919
920 struct wined3d_context *swapchain_create_context_for_thread(IWineD3DSwapChain *iface)
921 {
922     IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *) iface;
923     struct wined3d_context **newArray;
924     struct wined3d_context *ctx;
925
926     TRACE("Creating a new context for swapchain %p, thread %d\n", This, GetCurrentThreadId());
927
928     if (!(ctx = context_create(This, This->front_buffer, This->ds_format)))
929     {
930         ERR("Failed to create a new context for the swapchain\n");
931         return NULL;
932     }
933     context_release(ctx);
934
935     newArray = HeapAlloc(GetProcessHeap(), 0, sizeof(*newArray) * (This->num_contexts + 1));
936     if(!newArray) {
937         ERR("Out of memory when trying to allocate a new context array\n");
938         context_destroy(This->device, ctx);
939         return NULL;
940     }
941     memcpy(newArray, This->context, sizeof(*newArray) * This->num_contexts);
942     HeapFree(GetProcessHeap(), 0, This->context);
943     newArray[This->num_contexts] = ctx;
944     This->context = newArray;
945     This->num_contexts++;
946
947     TRACE("Returning context %p\n", ctx);
948     return ctx;
949 }
950
951 void get_drawable_size_swapchain(struct wined3d_context *context, UINT *width, UINT *height)
952 {
953     /* The drawable size of an onscreen drawable is the surface size.
954      * (Actually: The window size, but the surface is created in window size) */
955     *width = context->current_rt->currentDesc.Width;
956     *height = context->current_rt->currentDesc.Height;
957 }