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