d3d: Move clippers from DDraw to wined3d.
[wine] / dlls / wined3d / surface_gdi.c
1 /*
2  * 2D Surface implementation without OpenGL
3  *
4  * Copyright 1997-2000 Marcus Meissner
5  * Copyright 1998-2000 Lionel Ulmer
6  * Copyright 2000-2001 TransGaming Technologies Inc.
7  * Copyright 2002-2005 Jason Edmeades
8  * Copyright 2002-2003 Raphael Junqueira
9  * Copyright 2004 Christian Costa
10  * Copyright 2005 Oliver Stieber
11  * Copyright 2006 Stefan Dösinger
12  *
13  * This library is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU Lesser General Public
15  * License as published by the Free Software Foundation; either
16  * version 2.1 of the License, or (at your option) any later version.
17  *
18  * This library is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21  * Lesser General Public License for more details.
22  *
23  * You should have received a copy of the GNU Lesser General Public
24  * License along with this library; if not, write to the Free Software
25  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26  */
27
28 #include "config.h"
29 #include "wine/port.h"
30 #include "wined3d_private.h"
31
32 #include <assert.h>
33 #include <stdio.h>
34
35 /* Use the d3d_surface debug channel to have one channel for all surfaces */
36 WINE_DEFAULT_DEBUG_CHANNEL(d3d_surface);
37 WINE_DECLARE_DEBUG_CHANNEL(fps);
38
39 /*****************************************************************************
40  * x11_copy_to_screen
41  *
42  * Helper function that blts the front buffer contents to the target window
43  *
44  * Params:
45  *  This: Surface to copy from
46  *  rc: Rectangle to copy
47  *
48  *****************************************************************************/
49 static void
50 x11_copy_to_screen(IWineD3DSurfaceImpl *This,
51                    LPRECT rc)
52 {
53     if(This->resource.usage & WINED3DUSAGE_RENDERTARGET)
54     {
55         POINT offset = {0,0};
56         HWND hDisplayWnd;
57         HDC hDisplayDC;
58         HDC hSurfaceDC = 0;
59         RECT drawrect;
60         TRACE("(%p)->(%p): Copying to screen\n", This, rc);
61
62         hSurfaceDC = This->hDC;
63
64         hDisplayWnd = This->resource.wineD3DDevice->ddraw_window;
65         hDisplayDC = GetDCEx(hDisplayWnd, 0, DCX_CLIPSIBLINGS|DCX_CACHE);
66         if(rc)
67         {
68             TRACE(" copying rect (%d,%d)->(%d,%d), offset (%d,%d)\n",
69             rc->left, rc->top, rc->right, rc->bottom, offset.x, offset.y);
70         }
71 #if 0
72         /* FIXME: this doesn't work... if users really want to run
73         * X in 8bpp, then we need to call directly into display.drv
74         * (or Wine's equivalent), and force a private colormap
75         * without default entries. */
76         if (This->palette) {
77             SelectPalette(hDisplayDC, This->palette->hpal, FALSE);
78             RealizePalette(hDisplayDC); /* sends messages => deadlocks */
79         }
80 #endif
81         drawrect.left   = 0;
82         drawrect.right  = This->currentDesc.Width;
83         drawrect.top    = 0;
84         drawrect.bottom = This->currentDesc.Height;
85
86 #if 0
87         /* TODO: Support clippers */
88         if (This->clipper)
89         {
90             RECT xrc;
91             HWND hwnd = This->clipper->hWnd;
92             if (hwnd && GetClientRect(hwnd,&xrc))
93             {
94                 OffsetRect(&xrc,offset.x,offset.y);
95                 IntersectRect(&drawrect,&drawrect,&xrc);
96             }
97         }
98 #endif
99         if (rc)
100         {
101             IntersectRect(&drawrect,&drawrect,rc);
102         }
103         else
104         {
105             /* Only use this if the caller did not pass a rectangle, since
106              * due to double locking this could be the wrong one ...
107              */
108             if (This->lockedRect.left != This->lockedRect.right)
109             {
110                 IntersectRect(&drawrect,&drawrect,&This->lockedRect);
111             }
112         }
113
114         BitBlt(hDisplayDC,
115                drawrect.left-offset.x, drawrect.top-offset.y,
116                drawrect.right-drawrect.left, drawrect.bottom-drawrect.top,
117                hSurfaceDC,
118                drawrect.left, drawrect.top,
119                SRCCOPY);
120         ReleaseDC(hDisplayWnd, hDisplayDC);
121     }
122 }
123
124 /*****************************************************************************
125  * IWineD3DSurface::PreLoad, GDI version
126  *
127  * This call is unsupported on GDI surfaces, if it's called something went
128  * wrong in the parent library. Write an informative warning
129  *
130  *****************************************************************************/
131 static void WINAPI
132 IWineGDISurfaceImpl_PreLoad(IWineD3DSurface *iface)
133 {
134     ERR("(%p): PreLoad is not supported on X11 surfaces!\n", iface);
135     ERR("(%p): Most likely the parent library did something wrong.\n", iface);
136     ERR("(%p): Please report to wine-devel\n", iface);
137 }
138
139 /*****************************************************************************
140  * IWineD3DSurface::LockRect, GDI version
141  *
142  * Locks the surface and returns a pointer to the surface memory
143  *
144  * Params:
145  *  pLockedRect: Address to return the locking info at
146  *  pRect: Rectangle to lock
147  *  Flags: Some flags
148  *
149  * Returns:
150  *  WINED3D_OK on success
151  *  WINED3DERR_INVALIDCALL on errors
152  *
153  *****************************************************************************/
154 static HRESULT WINAPI
155 IWineGDISurfaceImpl_LockRect(IWineD3DSurface *iface,
156                              WINED3DLOCKED_RECT* pLockedRect,
157                              CONST RECT* pRect,
158                              DWORD Flags)
159 {
160     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
161
162     /* Already locked? */
163     if(This->Flags & SFLAG_LOCKED)
164     {
165         ERR("(%p) Surface already locked\n", This);
166         /* What should I return here? */
167         return WINED3DERR_INVALIDCALL;
168     }
169
170     if (!(This->Flags & SFLAG_LOCKABLE))
171     {
172         /* This is some GL specific thing, see the OpenGL version of
173          * this method, but check for the flag and write a trace
174          */
175         TRACE("Warning: trying to lock unlockable surf@%p\n", This);
176     }
177
178     TRACE("(%p) : rect@%p flags(%08x), output lockedRect@%p, memory@%p\n",
179           This, pRect, Flags, pLockedRect, This->resource.allocatedMemory);
180
181     if(!This->resource.allocatedMemory) {
182         HDC hdc;
183         HRESULT hr;
184         /* This happens on gdi surfaces if the application set a user pointer and resets it.
185          * Recreate the DIB section
186          */
187         hr = IWineD3DSurface_GetDC(iface, &hdc);  /* will recursively call lockrect, do not set the LOCKED flag to this line */
188         if(hr != WINED3D_OK) return hr;
189         hr = IWineD3DSurface_ReleaseDC(iface, hdc);
190         if(hr != WINED3D_OK) return hr;
191     }
192
193     pLockedRect->Pitch = IWineD3DSurface_GetPitch(iface);
194
195     if (NULL == pRect)
196     {
197         pLockedRect->pBits = This->resource.allocatedMemory;
198         This->lockedRect.left   = 0;
199         This->lockedRect.top    = 0;
200         This->lockedRect.right  = This->currentDesc.Width;
201         This->lockedRect.bottom = This->currentDesc.Height;
202
203         TRACE("Locked Rect (%p) = l %d, t %d, r %d, b %d\n",
204         &This->lockedRect, This->lockedRect.left, This->lockedRect.top,
205         This->lockedRect.right, This->lockedRect.bottom);
206     }
207     else
208     {
209         TRACE("Lock Rect (%p) = l %d, t %d, r %d, b %d\n",
210               pRect, pRect->left, pRect->top, pRect->right, pRect->bottom);
211
212         if (This->resource.format == WINED3DFMT_DXT1)
213         {
214             /* DXT1 is half byte per pixel */
215             pLockedRect->pBits = This->resource.allocatedMemory +
216                                   (pLockedRect->Pitch * pRect->top) +
217                                   ((pRect->left * This->bytesPerPixel / 2));
218         }
219         else
220         {
221             pLockedRect->pBits = This->resource.allocatedMemory +
222                                  (pLockedRect->Pitch * pRect->top) +
223                                  (pRect->left * This->bytesPerPixel);
224         }
225         This->lockedRect.left   = pRect->left;
226         This->lockedRect.top    = pRect->top;
227         This->lockedRect.right  = pRect->right;
228         This->lockedRect.bottom = pRect->bottom;
229     }
230
231     /* No dirtifying is needed for this surface implementation */
232     TRACE("returning memory@%p, pitch(%d)\n", pLockedRect->pBits, pLockedRect->Pitch);
233
234     This->Flags |= SFLAG_LOCKED;
235     return WINED3D_OK;
236 }
237
238 /*****************************************************************************
239  * IWineD3DSurface::UnlockRect, GDI version
240  *
241  * Unlocks a surface. This implementation doesn't do much, except updating
242  * the window if the front buffer is unlocked
243  *
244  * Returns:
245  *  WINED3D_OK on success
246  *  WINED3DERR_INVALIDCALL on failure
247  *
248  *****************************************************************************/
249 static HRESULT WINAPI
250 IWineGDISurfaceImpl_UnlockRect(IWineD3DSurface *iface)
251 {
252     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
253     IWineD3DDeviceImpl *dev = (IWineD3DDeviceImpl *) This->resource.wineD3DDevice;
254     TRACE("(%p)\n", This);
255
256     if (!(This->Flags & SFLAG_LOCKED))
257     {
258         WARN("trying to Unlock an unlocked surf@%p\n", This);
259         return WINED3DERR_INVALIDCALL;
260     }
261
262     /* Can be useful for debugging */
263 #if 0
264         {
265             static unsigned int gen = 0;
266             char buffer[4096];
267             ++gen;
268             if ((gen % 10) == 0) {
269                 snprintf(buffer, sizeof(buffer), "/tmp/surface%p_type%u_level%u_%u.ppm", This, This->glDescription.target, This->glDescription.level, gen);
270                 IWineD3DSurfaceImpl_SaveSnapshot(iface, buffer);
271             }
272             /*
273              * debugging crash code
274             if (gen == 250) {
275               void** test = NULL;
276               *test = 0;
277             }
278             */
279         }
280 #endif
281
282     /* Update the screen */
283     if(This == (IWineD3DSurfaceImpl *) dev->ddraw_primary)
284     {
285         x11_copy_to_screen(This, &This->lockedRect);
286     }
287
288     This->Flags &= ~SFLAG_LOCKED;
289     memset(&This->lockedRect, 0, sizeof(RECT));
290     return WINED3D_OK;
291 }
292
293 /*****************************************************************************
294  * IWineD3DSurface::Flip, GDI version
295  *
296  * Flips 2 flipping enabled surfaces. Determining the 2 targets is done by
297  * the parent library. This implementation changes the data pointers of the
298  * surfaces and copies the new front buffer content to the screen
299  *
300  * Params:
301  *  override: Flipping target(e.g. back buffer)
302  *
303  * Returns:
304  *  WINED3D_OK on success
305  *
306  *****************************************************************************/
307 static HRESULT WINAPI
308 IWineGDISurfaceImpl_Flip(IWineD3DSurface *iface,
309                          IWineD3DSurface *override,
310                          DWORD Flags)
311 {
312     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
313     IWineD3DSurfaceImpl *Target = (IWineD3DSurfaceImpl *) override;
314     TRACE("(%p)->(%p,%x)\n", This, override, Flags);
315
316     TRACE("(%p) Flipping to surface %p\n", This, Target);
317
318     if(Target == NULL)
319     {
320         ERR("(%p): Can't flip without a target\n", This);
321         return WINED3DERR_INVALIDCALL;
322     }
323
324     /* Flip the DC */
325     {
326         HDC tmp;
327         tmp = This->hDC;
328         This->hDC = Target->hDC;
329         Target->hDC = tmp;
330     }
331
332     /* Flip the DIBsection */
333     {
334         HBITMAP tmp;
335         tmp = This->dib.DIBsection;
336         This->dib.DIBsection = Target->dib.DIBsection;
337         Target->dib.DIBsection = tmp;
338     }
339
340     /* Flip the surface data */
341     {
342         void* tmp;
343
344         tmp = This->dib.bitmap_data;
345         This->dib.bitmap_data = Target->dib.bitmap_data;
346         Target->dib.bitmap_data = tmp;
347
348         tmp = This->resource.allocatedMemory;
349         This->resource.allocatedMemory = Target->resource.allocatedMemory;
350         Target->resource.allocatedMemory = tmp;
351     }
352
353     /* client_memory should not be different, but just in case */
354     {
355         BOOL tmp;
356         tmp = This->dib.client_memory;
357         This->dib.client_memory = Target->dib.client_memory;
358         Target->dib.client_memory = tmp;
359     }
360
361     /* Useful for debugging */
362 #if 0
363         {
364             static unsigned int gen = 0;
365             char buffer[4096];
366             ++gen;
367             if ((gen % 10) == 0) {
368                 snprintf(buffer, sizeof(buffer), "/tmp/surface%p_type%u_level%u_%u.ppm", This, This->glDescription.target, This->glDescription.level, gen);
369                 IWineD3DSurfaceImpl_SaveSnapshot(iface, buffer);
370             }
371             /*
372              * debugging crash code
373             if (gen == 250) {
374               void** test = NULL;
375               *test = 0;
376             }
377             */
378         }
379 #endif
380
381     /* Update the screen */
382     x11_copy_to_screen(This, NULL);
383
384     /* FPS support */
385     if (TRACE_ON(fps))
386     {
387         static long prev_time, frames;
388
389         DWORD time = GetTickCount();
390         frames++;
391         /* every 1.5 seconds */
392         if (time - prev_time > 1500) {
393             TRACE_(fps)("@ approx %.2ffps\n", 1000.0*frames/(time - prev_time));
394             prev_time = time;
395             frames = 0;
396         }
397     }
398
399     return WINED3D_OK;
400 }
401
402 /*****************************************************************************
403  * _Blt_ColorFill
404  *
405  * Helper function that fills a memory area with a specific color
406  *
407  * Params:
408  *  buf: memory address to start filling at
409  *  width, height: Dimensions of the area to fill
410  *  bpp: Bit depth of the surface
411  *  lPitch: pitch of the surface
412  *  color: Color to fill with
413  *
414  *****************************************************************************/
415 static HRESULT
416 _Blt_ColorFill(BYTE *buf,
417                int width, int height,
418                int bpp, LONG lPitch,
419                DWORD color)
420 {
421     int x, y;
422     LPBYTE first;
423
424     /* Do first row */
425
426 #define COLORFILL_ROW(type) \
427 { \
428     type *d = (type *) buf; \
429     for (x = 0; x < width; x++) \
430         d[x] = (type) color; \
431     break; \
432 }
433     switch(bpp)
434     {
435         case 1: COLORFILL_ROW(BYTE)
436         case 2: COLORFILL_ROW(WORD)
437         case 3:
438         {
439             BYTE *d = (BYTE *) buf;
440             for (x = 0; x < width; x++,d+=3)
441             {
442                 d[0] = (color    ) & 0xFF;
443                 d[1] = (color>> 8) & 0xFF;
444                 d[2] = (color>>16) & 0xFF;
445             }
446             break;
447         }
448         case 4: COLORFILL_ROW(DWORD)
449         default:
450             FIXME("Color fill not implemented for bpp %d!\n", bpp*8);
451             return WINED3DERR_NOTAVAILABLE;
452     }
453
454 #undef COLORFILL_ROW
455
456     /* Now copy first row */
457     first = buf;
458     for (y = 1; y < height; y++)
459     {
460         buf += lPitch;
461         memcpy(buf, first, width * bpp);
462     }
463     return WINED3D_OK;
464 }
465
466 /*****************************************************************************
467  * IWineD3DSurface::Blt, GDI version
468  *
469  * Performs blits to a surface, eigher from a source of source-less blts
470  * This is the main functionality of DirectDraw
471  *
472  * Params:
473  *  DestRect: Destination rectangle to write to
474  *  SrcSurface: Source surface, can be NULL
475  *  SrcRect: Source rectangle
476  *****************************************************************************/
477 HRESULT WINAPI
478 IWineGDISurfaceImpl_Blt(IWineD3DSurface *iface,
479                         RECT *DestRect,
480                         IWineD3DSurface *SrcSurface,
481                         RECT *SrcRect,
482                         DWORD Flags,
483                         WINEDDBLTFX *DDBltFx,
484                         WINED3DTEXTUREFILTERTYPE Filter)
485 {
486     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
487     IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
488     RECT                xdst,xsrc;
489     HRESULT             ret = WINED3D_OK;
490     WINED3DLOCKED_RECT  dlock, slock;
491     WINED3DFORMAT       dfmt = WINED3DFMT_UNKNOWN, sfmt = WINED3DFMT_UNKNOWN;
492     int bpp, srcheight, srcwidth, dstheight, dstwidth, width;
493     int x, y;
494     const PixelFormatDesc *sEntry, *dEntry;
495     LPBYTE dbuf, sbuf;
496     TRACE("(%p)->(%p,%p,%p,%x,%p)\n", This, DestRect, Src, SrcRect, Flags, DDBltFx);
497
498     if (TRACE_ON(d3d_surface))
499     {
500         if (DestRect) TRACE("\tdestrect :%dx%d-%dx%d\n",
501         DestRect->left, DestRect->top, DestRect->right, DestRect->bottom);
502         if (SrcRect) TRACE("\tsrcrect  :%dx%d-%dx%d\n",
503         SrcRect->left, SrcRect->top, SrcRect->right, SrcRect->bottom);
504 #if 0
505         TRACE("\tflags: ");
506         DDRAW_dump_DDBLT(Flags);
507         if (Flags & WINEDDBLT_DDFX)
508         {
509             TRACE("\tblitfx: ");
510             DDRAW_dump_DDBLTFX(DDBltFx->dwDDFX);
511         }
512 #endif
513     }
514
515     if ( (This->Flags & SFLAG_LOCKED) || ((Src != NULL) && (Src->Flags & SFLAG_LOCKED)))
516     {
517         WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
518         return WINEDDERR_SURFACEBUSY;
519     }
520
521     if(Filter != WINED3DTEXF_NONE) {
522         /* Can happen when d3d9 apps do a StretchRect call which isn't handled in gl */
523         FIXME("Filters not supported in software blit\n");
524     }
525
526     if (Src == This)
527     {
528         IWineD3DSurface_LockRect(iface, &dlock, NULL, 0);
529         dfmt = This->resource.format;
530         slock = dlock;
531         sfmt = dfmt;
532         sEntry = getFormatDescEntry(sfmt);
533         dEntry = sEntry;
534     }
535     else
536     {
537         if (Src)
538         {
539             IWineD3DSurface_LockRect(SrcSurface, &slock, NULL, WINED3DLOCK_READONLY);
540             sfmt = Src->resource.format;
541         }
542         sEntry = getFormatDescEntry(sfmt);
543         dfmt = This->resource.format;
544         dEntry = getFormatDescEntry(dfmt);
545         IWineD3DSurface_LockRect(iface, &dlock,NULL,0);
546     }
547
548     if (!DDBltFx || !(DDBltFx->dwDDFX)) Flags &= ~WINEDDBLT_DDFX;
549
550     if (sEntry->isFourcc && dEntry->isFourcc)
551     {
552         if (sfmt != dfmt)
553         {
554             FIXME("FOURCC->FOURCC copy only supported for the same type of surface\n");
555             ret = WINED3DERR_WRONGTEXTUREFORMAT;
556             goto release;
557         }
558         memcpy(dlock.pBits, slock.pBits, This->resource.size);
559         goto release;
560     }
561
562     if (sEntry->isFourcc && !dEntry->isFourcc)
563     {
564         FIXME("DXTC decompression not supported right now\n");
565         goto release;
566     }
567
568     if (DestRect)
569     {
570         memcpy(&xdst,DestRect,sizeof(xdst));
571     }
572     else
573     {
574         xdst.top        = 0;
575         xdst.bottom     = This->currentDesc.Height;
576         xdst.left       = 0;
577         xdst.right      = This->currentDesc.Width;
578     }
579
580     if (SrcRect)
581     {
582         memcpy(&xsrc,SrcRect,sizeof(xsrc));
583     }
584     else
585     {
586         if (Src)
587         {
588             xsrc.top    = 0;
589             xsrc.bottom = Src->currentDesc.Height;
590             xsrc.left   = 0;
591             xsrc.right  = Src->currentDesc.Width;
592         }
593         else
594         {
595             memset(&xsrc,0,sizeof(xsrc));
596         }
597     }
598
599     /* First check for the validity of source / destination rectangles. This was
600       verified using a test application + by MSDN.
601     */
602     if ((Src != NULL) &&
603         ((xsrc.bottom > Src->currentDesc.Height) || (xsrc.bottom < 0) ||
604         (xsrc.top     > Src->currentDesc.Height) || (xsrc.top    < 0) ||
605         (xsrc.left    > Src->currentDesc.Width)  || (xsrc.left   < 0) ||
606         (xsrc.right   > Src->currentDesc.Width)  || (xsrc.right  < 0) ||
607         (xsrc.right   < xsrc.left)               || (xsrc.bottom < xsrc.top)))
608     {
609         WARN("Application gave us bad source rectangle for Blt.\n");
610         ret = WINEDDERR_INVALIDRECT;
611         goto release;
612     }
613     /* For the Destination rect, it can be out of bounds on the condition that a clipper
614       is set for the given surface.
615     */
616     if ((/*This->clipper == NULL*/ TRUE) &&
617         ((xdst.bottom  > This->currentDesc.Height) || (xdst.bottom < 0) ||
618         (xdst.top      > This->currentDesc.Height) || (xdst.top    < 0) ||
619         (xdst.left     > This->currentDesc.Width)  || (xdst.left   < 0) ||
620         (xdst.right    > This->currentDesc.Width)  || (xdst.right  < 0) ||
621         (xdst.right    < xdst.left)                || (xdst.bottom < xdst.top)))
622     {
623         WARN("Application gave us bad destination rectangle for Blt without a clipper set.\n");
624         ret = WINEDDERR_INVALIDRECT;
625         goto release;
626     }
627
628     /* Now handle negative values in the rectangles. Warning: only supported for now
629       in the 'simple' cases (ie not in any stretching / rotation cases).
630
631       First, the case where nothing is to be done.
632     */
633     if (((xdst.bottom <= 0) || (xdst.right <= 0)         ||
634          (xdst.top    >= (int) This->currentDesc.Height) ||
635          (xdst.left   >= (int) This->currentDesc.Width)) ||
636         ((Src != NULL) &&
637         ((xsrc.bottom <= 0) || (xsrc.right <= 0)     ||
638          (xsrc.top >= (int) Src->currentDesc.Height) ||
639          (xsrc.left >= (int) Src->currentDesc.Width))  ))
640     {
641         TRACE("Nothing to be done !\n");
642         goto release;
643     }
644
645     /* The easy case : the source-less blits.... */
646     if (Src == NULL)
647     {
648         RECT full_rect;
649         RECT temp_rect; /* No idea if intersect rect can be the same as one of the source rect */
650
651         full_rect.left   = 0;
652         full_rect.top    = 0;
653         full_rect.right  = This->currentDesc.Width;
654         full_rect.bottom = This->currentDesc.Height;
655         IntersectRect(&temp_rect, &full_rect, &xdst);
656         xdst = temp_rect;
657     }
658     else
659     {
660         /* Only handle clipping on the destination rectangle */
661         int clip_horiz = (xdst.left < 0) || (xdst.right  > (int) This->currentDesc.Width );
662         int clip_vert  = (xdst.top  < 0) || (xdst.bottom > (int) This->currentDesc.Height);
663         if (clip_vert || clip_horiz)
664         {
665             /* Now check if this is a special case or not... */
666             if ((((xdst.bottom - xdst.top ) != (xsrc.bottom - xsrc.top )) && clip_vert ) ||
667                 (((xdst.right  - xdst.left) != (xsrc.right  - xsrc.left)) && clip_horiz) ||
668                 (Flags & WINEDDBLT_DDFX))
669             {
670                 WARN("Out of screen rectangle in special case. Not handled right now.\n");
671                 goto release;
672             }
673
674             if (clip_horiz)
675             {
676                 if (xdst.left < 0) { xsrc.left -= xdst.left; xdst.left = 0; }
677                 if (xdst.right > This->currentDesc.Width)
678                 {
679                     xsrc.right -= (xdst.right - (int) This->currentDesc.Width);
680                     xdst.right = (int) This->currentDesc.Width;
681                 }
682             }
683             if (clip_vert)
684             {
685                 if (xdst.top < 0)
686                 {
687                     xsrc.top -= xdst.top;
688                     xdst.top = 0;
689                 }
690                 if (xdst.bottom > This->currentDesc.Height)
691                 {
692                     xsrc.bottom -= (xdst.bottom - (int) This->currentDesc.Height);
693                     xdst.bottom = (int) This->currentDesc.Height;
694                 }
695             }
696             /* And check if after clipping something is still to be done... */
697             if ((xdst.bottom <= 0)   || (xdst.right <= 0)       ||
698                 (xdst.top   >= (int) This->currentDesc.Height)  ||
699                 (xdst.left  >= (int) This->currentDesc.Width)   ||
700                 (xsrc.bottom <= 0)   || (xsrc.right <= 0)       ||
701                 (xsrc.top >= (int) Src->currentDesc.Height)     ||
702                 (xsrc.left >= (int) Src->currentDesc.Width))
703             {
704                 TRACE("Nothing to be done after clipping !\n");
705                 goto release;
706             }
707         }
708     }
709
710     bpp = This->bytesPerPixel;
711     srcheight = xsrc.bottom - xsrc.top;
712     srcwidth = xsrc.right - xsrc.left;
713     dstheight = xdst.bottom - xdst.top;
714     dstwidth = xdst.right - xdst.left;
715     width = (xdst.right - xdst.left) * bpp;
716
717     assert(width <= dlock.Pitch);
718
719     dbuf = (BYTE*)dlock.pBits+(xdst.top*dlock.Pitch)+(xdst.left*bpp);
720
721     if (Flags & WINEDDBLT_WAIT)
722     {
723         Flags &= ~WINEDDBLT_WAIT;
724     }
725     if (Flags & WINEDDBLT_ASYNC)
726     {
727         static BOOL displayed = FALSE;
728         if (!displayed)
729             FIXME("Can't handle WINEDDBLT_ASYNC flag right now.\n");
730         displayed = TRUE;
731         Flags &= ~WINEDDBLT_ASYNC;
732     }
733     if (Flags & WINEDDBLT_DONOTWAIT)
734     {
735         /* WINEDDBLT_DONOTWAIT appeared in DX7 */
736         static BOOL displayed = FALSE;
737         if (!displayed)
738             FIXME("Can't handle WINEDDBLT_DONOTWAIT flag right now.\n");
739         displayed = TRUE;
740         Flags &= ~WINEDDBLT_DONOTWAIT;
741     }
742
743     /* First, all the 'source-less' blits */
744     if (Flags & WINEDDBLT_COLORFILL)
745     {
746         ret = _Blt_ColorFill(dbuf, dstwidth, dstheight, bpp,
747                             dlock.Pitch, DDBltFx->u5.dwFillColor);
748         Flags &= ~WINEDDBLT_COLORFILL;
749     }
750
751     if (Flags & WINEDDBLT_DEPTHFILL)
752     {
753         FIXME("DDBLT_DEPTHFILL needs to be implemented!\n");
754     }
755     if (Flags & WINEDDBLT_ROP)
756     {
757         /* Catch some degenerate cases here */
758         switch(DDBltFx->dwROP)
759         {
760             case BLACKNESS:
761                 ret = _Blt_ColorFill(dbuf,dstwidth,dstheight,bpp,dlock.Pitch,0);
762                 break;
763             case 0xAA0029: /* No-op */
764                 break;
765             case WHITENESS:
766                 ret = _Blt_ColorFill(dbuf,dstwidth,dstheight,bpp,dlock.Pitch,~0);
767                 break;
768             case SRCCOPY: /* well, we do that below ? */
769                 break;
770             default:
771                 FIXME("Unsupported raster op: %08x  Pattern: %p\n", DDBltFx->dwROP, DDBltFx->u5.lpDDSPattern);
772                 goto error;
773         }
774         Flags &= ~WINEDDBLT_ROP;
775     }
776     if (Flags & WINEDDBLT_DDROPS)
777     {
778         FIXME("\tDdraw Raster Ops: %08x  Pattern: %p\n", DDBltFx->dwDDROP, DDBltFx->u5.lpDDSPattern);
779     }
780     /* Now the 'with source' blits */
781     if (Src)
782     {
783         LPBYTE sbase;
784         int sx, xinc, sy, yinc;
785
786         if (!dstwidth || !dstheight) /* hmm... stupid program ? */
787             goto release;
788         sbase = (BYTE*)slock.pBits+(xsrc.top*slock.Pitch)+xsrc.left*bpp;
789         xinc = (srcwidth << 16) / dstwidth;
790         yinc = (srcheight << 16) / dstheight;
791
792         if (!Flags)
793         {
794             /* No effects, we can cheat here */
795             if (dstwidth == srcwidth)
796             {
797                 if (dstheight == srcheight)
798                 {
799                     /* No stretching in either direction. This needs to be as
800                     * fast as possible */
801                     sbuf = sbase;
802
803                     /* check for overlapping surfaces */
804                     if (SrcSurface != iface || xdst.top < xsrc.top ||
805                         xdst.right <= xsrc.left || xsrc.right <= xdst.left)
806                     {
807                         /* no overlap, or dst above src, so copy from top downwards */
808                         for (y = 0; y < dstheight; y++)
809                         {
810                             memcpy(dbuf, sbuf, width);
811                             sbuf += slock.Pitch;
812                             dbuf += dlock.Pitch;
813                         }
814                     }
815                     else if (xdst.top > xsrc.top)  /* copy from bottom upwards */
816                     {
817                         sbuf += (slock.Pitch*dstheight);
818                         dbuf += (dlock.Pitch*dstheight);
819                         for (y = 0; y < dstheight; y++)
820                         {
821                             sbuf -= slock.Pitch;
822                             dbuf -= dlock.Pitch;
823                             memcpy(dbuf, sbuf, width);
824                         }
825                     }
826                     else /* src and dst overlapping on the same line, use memmove */
827                     {
828                         for (y = 0; y < dstheight; y++)
829                         {
830                             memmove(dbuf, sbuf, width);
831                             sbuf += slock.Pitch;
832                             dbuf += dlock.Pitch;
833                         }
834                     }
835                 } else {
836                     /* Stretching in Y direction only */
837                     for (y = sy = 0; y < dstheight; y++, sy += yinc) {
838                         sbuf = sbase + (sy >> 16) * slock.Pitch;
839                         memcpy(dbuf, sbuf, width);
840                         dbuf += dlock.Pitch;
841                     }
842                 }
843             }
844             else
845             {
846                 /* Stretching in X direction */
847                 int last_sy = -1;
848                 for (y = sy = 0; y < dstheight; y++, sy += yinc)
849                 {
850                     sbuf = sbase + (sy >> 16) * slock.Pitch;
851
852                     if ((sy >> 16) == (last_sy >> 16))
853                     {
854                         /* this sourcerow is the same as last sourcerow -
855                          * copy already stretched row
856                          */
857                         memcpy(dbuf, dbuf - dlock.Pitch, width);
858                     }
859                     else
860                     {
861 #define STRETCH_ROW(type) { \
862                     type *s = (type *) sbuf, *d = (type *) dbuf; \
863                     for (x = sx = 0; x < dstwidth; x++, sx += xinc) \
864                     d[x] = s[sx >> 16]; \
865                     break; }
866
867                     switch(bpp)
868                     {
869                         case 1: STRETCH_ROW(BYTE)
870                         case 2: STRETCH_ROW(WORD)
871                         case 4: STRETCH_ROW(DWORD)
872                         case 3:
873                         {
874                             LPBYTE s,d = dbuf;
875                             for (x = sx = 0; x < dstwidth; x++, sx+= xinc)
876                             {
877                                 DWORD pixel;
878
879                                 s = sbuf+3*(sx>>16);
880                                 pixel = s[0]|(s[1]<<8)|(s[2]<<16);
881                                 d[0] = (pixel    )&0xff;
882                                 d[1] = (pixel>> 8)&0xff;
883                                 d[2] = (pixel>>16)&0xff;
884                                 d+=3;
885                             }
886                             break;
887                     }
888                     default:
889                         FIXME("Stretched blit not implemented for bpp %d!\n", bpp*8);
890                         ret = WINED3DERR_NOTAVAILABLE;
891                         goto error;
892                     }
893 #undef STRETCH_ROW
894                     }
895                     dbuf += dlock.Pitch;
896                     last_sy = sy;
897                 }
898             }
899         }
900         else
901         {
902           LONG dstyinc = dlock.Pitch, dstxinc = bpp;
903           DWORD keylow = 0xFFFFFFFF, keyhigh = 0, keymask = 0xFFFFFFFF;
904           DWORD destkeylow = 0x0, destkeyhigh = 0xFFFFFFFF, destkeymask = 0xFFFFFFFF;
905           if (Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYDEST | WINEDDBLT_KEYSRCOVERRIDE | WINEDDBLT_KEYDESTOVERRIDE))
906           {
907               /* The color keying flags are checked for correctness in ddraw */
908               if (Flags & WINEDDBLT_KEYSRC)
909               {
910                 keylow  = Src->SrcBltCKey.dwColorSpaceLowValue;
911                 keyhigh = Src->SrcBltCKey.dwColorSpaceHighValue;
912               }
913               else  if (Flags & WINEDDBLT_KEYSRCOVERRIDE)
914               {
915                 keylow  = DDBltFx->ddckSrcColorkey.dwColorSpaceLowValue;
916                 keyhigh = DDBltFx->ddckSrcColorkey.dwColorSpaceHighValue;
917               }
918
919               if (Flags & WINEDDBLT_KEYDEST)
920               {
921                 /* Destination color keys are taken from the source surface ! */
922                 destkeylow  = Src->DestBltCKey.dwColorSpaceLowValue;
923                 destkeyhigh = Src->DestBltCKey.dwColorSpaceHighValue;
924               }
925               else if (Flags & WINEDDBLT_KEYDESTOVERRIDE)
926               {
927                 destkeylow  = DDBltFx->ddckDestColorkey.dwColorSpaceLowValue;
928                 destkeyhigh = DDBltFx->ddckDestColorkey.dwColorSpaceHighValue;
929               }
930
931               if(bpp == 1)
932               {
933                   keymask = 0xff;
934               }
935               else
936               {
937                   keymask = sEntry->redMask   |
938                             sEntry->greenMask |
939                             sEntry->blueMask;
940               }
941               Flags &= ~(WINEDDBLT_KEYSRC | WINEDDBLT_KEYDEST | WINEDDBLT_KEYSRCOVERRIDE | WINEDDBLT_KEYDESTOVERRIDE);
942           }
943
944           if (Flags & WINEDDBLT_DDFX)
945           {
946               LPBYTE dTopLeft, dTopRight, dBottomLeft, dBottomRight, tmp;
947               LONG tmpxy;
948               dTopLeft     = dbuf;
949               dTopRight    = dbuf+((dstwidth-1)*bpp);
950               dBottomLeft  = dTopLeft+((dstheight-1)*dlock.Pitch);
951               dBottomRight = dBottomLeft+((dstwidth-1)*bpp);
952
953               if (DDBltFx->dwDDFX & WINEDDBLTFX_ARITHSTRETCHY)
954               {
955                 /* I don't think we need to do anything about this flag */
956                 WARN("Flags=DDBLT_DDFX nothing done for WINEDDBLTFX_ARITHSTRETCHY\n");
957               }
958               if (DDBltFx->dwDDFX & WINEDDBLTFX_MIRRORLEFTRIGHT)
959               {
960                 tmp          = dTopRight;
961                 dTopRight    = dTopLeft;
962                 dTopLeft     = tmp;
963                 tmp          = dBottomRight;
964                 dBottomRight = dBottomLeft;
965                 dBottomLeft  = tmp;
966                 dstxinc = dstxinc *-1;
967               }
968               if (DDBltFx->dwDDFX & WINEDDBLTFX_MIRRORUPDOWN)
969               {
970                 tmp          = dTopLeft;
971                 dTopLeft     = dBottomLeft;
972                 dBottomLeft  = tmp;
973                 tmp          = dTopRight;
974                 dTopRight    = dBottomRight;
975                 dBottomRight = tmp;
976                 dstyinc = dstyinc *-1;
977               }
978               if (DDBltFx->dwDDFX & WINEDDBLTFX_NOTEARING)
979               {
980                 /* I don't think we need to do anything about this flag */
981                 WARN("Flags=DDBLT_DDFX nothing done for WINEDDBLTFX_NOTEARING\n");
982               }
983               if (DDBltFx->dwDDFX & WINEDDBLTFX_ROTATE180)
984               {
985                 tmp          = dBottomRight;
986                 dBottomRight = dTopLeft;
987                 dTopLeft     = tmp;
988                 tmp          = dBottomLeft;
989                 dBottomLeft  = dTopRight;
990                 dTopRight    = tmp;
991                 dstxinc = dstxinc * -1;
992                 dstyinc = dstyinc * -1;
993               }
994               if (DDBltFx->dwDDFX & WINEDDBLTFX_ROTATE270)
995               {
996                 tmp          = dTopLeft;
997                 dTopLeft     = dBottomLeft;
998                 dBottomLeft  = dBottomRight;
999                 dBottomRight = dTopRight;
1000                 dTopRight    = tmp;
1001                 tmpxy   = dstxinc;
1002                 dstxinc = dstyinc;
1003                 dstyinc = tmpxy;
1004                 dstxinc = dstxinc * -1;
1005               }
1006               if (DDBltFx->dwDDFX & WINEDDBLTFX_ROTATE90)
1007               {
1008                 tmp          = dTopLeft;
1009                 dTopLeft     = dTopRight;
1010                 dTopRight    = dBottomRight;
1011                 dBottomRight = dBottomLeft;
1012                 dBottomLeft  = tmp;
1013                 tmpxy   = dstxinc;
1014                 dstxinc = dstyinc;
1015                 dstyinc = tmpxy;
1016                 dstyinc = dstyinc * -1;
1017               }
1018               if (DDBltFx->dwDDFX & WINEDDBLTFX_ZBUFFERBASEDEST)
1019               {
1020                 /* I don't think we need to do anything about this flag */
1021                 WARN("Flags=WINEDDBLT_DDFX nothing done for WINEDDBLTFX_ZBUFFERBASEDEST\n");
1022               }
1023               dbuf = dTopLeft;
1024               Flags &= ~(WINEDDBLT_DDFX);
1025           }
1026
1027 #define COPY_COLORKEY_FX(type) { \
1028             type *s, *d = (type *) dbuf, *dx, tmp; \
1029             for (y = sy = 0; y < dstheight; y++, sy += yinc) { \
1030               s = (type*)(sbase + (sy >> 16) * slock.Pitch); \
1031               dx = d; \
1032               for (x = sx = 0; x < dstwidth; x++, sx += xinc) { \
1033                   tmp = s[sx >> 16]; \
1034                   if (((tmp & keymask) < keylow || (tmp & keymask) > keyhigh) && \
1035                       ((dx[0] & destkeymask) >= destkeylow && (dx[0] & destkeymask) <= destkeyhigh)) { \
1036                        dx[0] = tmp; \
1037                      } \
1038                   dx = (type*)(((LPBYTE)dx)+dstxinc); \
1039               } \
1040               d = (type*)(((LPBYTE)d)+dstyinc); \
1041             } \
1042             break; }
1043
1044             switch (bpp) {
1045             case 1: COPY_COLORKEY_FX(BYTE)
1046             case 2: COPY_COLORKEY_FX(WORD)
1047             case 4: COPY_COLORKEY_FX(DWORD)
1048             case 3:
1049             {
1050                 LPBYTE s,d = dbuf, dx;
1051                 for (y = sy = 0; y < dstheight; y++, sy += yinc)
1052                 {
1053                     sbuf = sbase + (sy >> 16) * slock.Pitch;
1054                     dx = d;
1055                     for (x = sx = 0; x < dstwidth; x++, sx+= xinc)
1056                     {
1057                         DWORD pixel, dpixel = 0;
1058                         s = sbuf+3*(sx>>16);
1059                         pixel = s[0]|(s[1]<<8)|(s[2]<<16);
1060                         dpixel = dx[0]|(dx[1]<<8)|(dx[2]<<16);
1061                         if (((pixel & keymask) < keylow || (pixel & keymask) > keyhigh) &&
1062                             ((dpixel & keymask) >= destkeylow || (dpixel & keymask) <= keyhigh))
1063                         {
1064                             dx[0] = (pixel    )&0xff;
1065                             dx[1] = (pixel>> 8)&0xff;
1066                             dx[2] = (pixel>>16)&0xff;
1067                         }
1068                         dx+= dstxinc;
1069                     }
1070                     d += dstyinc;
1071                 }
1072                 break;
1073             }
1074             default:
1075               FIXME("%s color-keyed blit not implemented for bpp %d!\n",
1076                   (Flags & WINEDDBLT_KEYSRC) ? "Source" : "Destination", bpp*8);
1077                   ret = WINED3DERR_NOTAVAILABLE;
1078                   goto error;
1079 #undef COPY_COLORKEY_FX
1080             }
1081         }
1082     }
1083
1084 error:
1085     if (Flags && FIXME_ON(d3d_surface))
1086     {
1087         FIXME("\tUnsupported flags: %08x\n", Flags);
1088     }
1089
1090 release:
1091     IWineD3DSurface_UnlockRect(iface);
1092     if (SrcSurface && SrcSurface != iface) IWineD3DSurface_UnlockRect(SrcSurface);
1093     return ret;
1094 }
1095
1096 /*****************************************************************************
1097  * IWineD3DSurface::BltFast, GDI version
1098  *
1099  * This is the software implementation of BltFast, as used by GDI surfaces
1100  * and as a fallback for OpenGL surfaces. This code is taken from the old
1101  * DirectDraw code, and was originally written by TransGaming.
1102  *
1103  * Params:
1104  *  dstx:
1105  *  dsty:
1106  *  Source: Source surface to copy from
1107  *  rsrc: Source rectangle
1108  *  trans: Some Flags
1109  *
1110  * Returns:
1111  *  WINED3D_OK on success
1112  *
1113  *****************************************************************************/
1114 HRESULT WINAPI
1115 IWineGDISurfaceImpl_BltFast(IWineD3DSurface *iface,
1116                             DWORD dstx,
1117                             DWORD dsty,
1118                             IWineD3DSurface *Source,
1119                             RECT *rsrc,
1120                             DWORD trans)
1121 {
1122     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
1123     IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) Source;
1124
1125     int                 bpp, w, h, x, y;
1126     WINED3DLOCKED_RECT  dlock,slock;
1127     HRESULT             ret = WINED3D_OK;
1128     RECT                rsrc2;
1129     RECT                lock_src, lock_dst, lock_union;
1130     BYTE                *sbuf, *dbuf;
1131     const PixelFormatDesc *sEntry, *dEntry;
1132
1133     if (TRACE_ON(d3d_surface))
1134     {
1135         TRACE("(%p)->(%d,%d,%p,%p,%08x)\n", This,dstx,dsty,Src,rsrc,trans);
1136
1137         if (rsrc)
1138         {
1139             TRACE("\tsrcrect: %dx%d-%dx%d\n",rsrc->left,rsrc->top,
1140                   rsrc->right,rsrc->bottom);
1141         }
1142         else
1143         {
1144             TRACE(" srcrect: NULL\n");
1145         }
1146     }
1147
1148     if ((This->Flags & SFLAG_LOCKED) ||
1149         ((Src != NULL) && (Src->Flags & SFLAG_LOCKED)))
1150     {
1151         WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
1152         return WINEDDERR_SURFACEBUSY;
1153     }
1154
1155     if (!rsrc)
1156     {
1157         WARN("rsrc is NULL!\n");
1158         rsrc = &rsrc2;
1159         rsrc->left = 0;
1160         rsrc->top = 0;
1161         rsrc->right = Src->currentDesc.Width;
1162         rsrc->bottom = Src->currentDesc.Height;
1163     }
1164
1165     /* Check source rect for validity. Copied from normal Blt. Fixes Baldur's Gate.*/
1166     if ((rsrc->bottom > Src->currentDesc.Height) || (rsrc->bottom < 0) ||
1167         (rsrc->top    > Src->currentDesc.Height) || (rsrc->top    < 0) ||
1168         (rsrc->left   > Src->currentDesc.Width)  || (rsrc->left   < 0) ||
1169         (rsrc->right  > Src->currentDesc.Width)  || (rsrc->right  < 0) ||
1170         (rsrc->right  < rsrc->left)              || (rsrc->bottom < rsrc->top))
1171     {
1172         WARN("Application gave us bad source rectangle for BltFast.\n");
1173         return WINEDDERR_INVALIDRECT;
1174     }
1175
1176     h = rsrc->bottom - rsrc->top;
1177     if (h > This->currentDesc.Height-dsty) h = This->currentDesc.Height-dsty;
1178     if (h > Src->currentDesc.Height-rsrc->top) h=Src->currentDesc.Height-rsrc->top;
1179     if (h <= 0) return WINEDDERR_INVALIDRECT;
1180
1181     w = rsrc->right - rsrc->left;
1182     if (w > This->currentDesc.Width-dstx) w = This->currentDesc.Width-dstx;
1183     if (w > Src->currentDesc.Width-rsrc->left) w = Src->currentDesc.Width-rsrc->left;
1184     if (w <= 0) return WINEDDERR_INVALIDRECT;
1185
1186     /* Now compute the locking rectangle... */
1187     lock_src.left = rsrc->left;
1188     lock_src.top = rsrc->top;
1189     lock_src.right = lock_src.left + w;
1190     lock_src.bottom = lock_src.top + h;
1191
1192     lock_dst.left = dstx;
1193     lock_dst.top = dsty;
1194     lock_dst.right = dstx + w;
1195     lock_dst.bottom = dsty + h;
1196
1197     bpp = This->bytesPerPixel;
1198
1199     /* We need to lock the surfaces, or we won't get refreshes when done. */
1200     if (Src == This)
1201     {
1202         int pitch;
1203
1204         UnionRect(&lock_union, &lock_src, &lock_dst);
1205
1206         /* Lock the union of the two rectangles */
1207         ret = IWineD3DSurface_LockRect(iface, &dlock, &lock_union, 0);
1208         if(ret != WINED3D_OK) goto error;
1209
1210         pitch = dlock.Pitch;
1211         slock.Pitch = dlock.Pitch;
1212
1213         /* Since slock was originally copied from this surface's description, we can just reuse it */
1214         assert(This->resource.allocatedMemory != NULL);
1215         sbuf = (BYTE *)This->resource.allocatedMemory + lock_src.top * pitch + lock_src.left * bpp;
1216         dbuf = (BYTE *)This->resource.allocatedMemory + lock_dst.top * pitch + lock_dst.left * bpp;
1217         sEntry = getFormatDescEntry(Src->resource.format);
1218         dEntry = sEntry;
1219     }
1220     else
1221     {
1222         ret = IWineD3DSurface_LockRect(Source, &slock, &lock_src, WINED3DLOCK_READONLY);
1223         if(ret != WINED3D_OK) goto error;
1224         ret = IWineD3DSurface_LockRect(iface, &dlock, &lock_dst, 0);
1225         if(ret != WINED3D_OK) goto error;
1226
1227         sbuf = slock.pBits;
1228         dbuf = dlock.pBits;
1229         TRACE("Dst is at %p, Src is at %p\n", dbuf, sbuf);
1230
1231         sEntry = getFormatDescEntry(Src->resource.format);
1232         dEntry = getFormatDescEntry(This->resource.format);
1233     }
1234
1235     /* Handle first the FOURCC surfaces... */
1236     if (sEntry->isFourcc && dEntry->isFourcc)
1237     {
1238         TRACE("Fourcc -> Fourcc copy\n");
1239         if (trans)
1240             FIXME("trans arg not supported when a FOURCC surface is involved\n");
1241         if (dstx || dsty)
1242             FIXME("offset for destination surface is not supported\n");
1243         if (Src->resource.format != This->resource.format)
1244         {
1245             FIXME("FOURCC->FOURCC copy only supported for the same type of surface\n");
1246             ret = WINED3DERR_WRONGTEXTUREFORMAT;
1247             goto error;
1248         }
1249         /* FIXME: Watch out that the size is correct for FOURCC surfaces */
1250         memcpy(dbuf, sbuf, This->resource.size);
1251         goto error;
1252     }
1253     if (sEntry->isFourcc && !dEntry->isFourcc)
1254     {
1255         /* TODO: Use the libtxc_dxtn.so shared library to do
1256          * software decompression
1257          */
1258         ERR("DXTC decompression not supported by now\n");
1259         goto error;
1260     }
1261
1262     if (trans & (WINEDDBLTFAST_SRCCOLORKEY | WINEDDBLTFAST_DESTCOLORKEY))
1263     {
1264         DWORD keylow, keyhigh;
1265         TRACE("Color keyed copy\n");
1266         if (trans & WINEDDBLTFAST_SRCCOLORKEY)
1267         {
1268             keylow  = Src->SrcBltCKey.dwColorSpaceLowValue;
1269             keyhigh = Src->SrcBltCKey.dwColorSpaceHighValue;
1270         }
1271         else
1272         {
1273             /* I'm not sure if this is correct */
1274             FIXME("WINEDDBLTFAST_DESTCOLORKEY not fully supported yet.\n");
1275             keylow  = This->DestBltCKey.dwColorSpaceLowValue;
1276             keyhigh = This->DestBltCKey.dwColorSpaceHighValue;
1277         }
1278
1279 #define COPYBOX_COLORKEY(type) { \
1280             type *d, *s, tmp; \
1281             s = (type *) sbuf; \
1282             d = (type *) dbuf; \
1283             for (y = 0; y < h; y++) { \
1284                 for (x = 0; x < w; x++) { \
1285                     tmp = s[x]; \
1286                     if (tmp < keylow || tmp > keyhigh) d[x] = tmp; \
1287                 } \
1288                 s = (type *)((BYTE *)s + slock.Pitch); \
1289                 d = (type *)((BYTE *)d + dlock.Pitch); \
1290             } \
1291             break; \
1292         }
1293
1294         switch (bpp) {
1295             case 1: COPYBOX_COLORKEY(BYTE)
1296             case 2: COPYBOX_COLORKEY(WORD)
1297             case 4: COPYBOX_COLORKEY(DWORD)
1298             case 3:
1299             {
1300                 BYTE *d, *s;
1301                 DWORD tmp;
1302                 s = (BYTE *) sbuf;
1303                 d = (BYTE *) dbuf;
1304                 for (y = 0; y < h; y++)
1305                 {
1306                     for (x = 0; x < w * 3; x += 3)
1307                     {
1308                         tmp = (DWORD)s[x] + ((DWORD)s[x + 1] << 8) + ((DWORD)s[x + 2] << 16);
1309                         if (tmp < keylow || tmp > keyhigh)
1310                         {
1311                             d[x + 0] = s[x + 0];
1312                             d[x + 1] = s[x + 1];
1313                             d[x + 2] = s[x + 2];
1314                         }
1315                     }
1316                     s += slock.Pitch;
1317                     d += dlock.Pitch;
1318                 }
1319                 break;
1320             }
1321             default:
1322                 FIXME("Source color key blitting not supported for bpp %d\n",bpp*8);
1323                 ret = WINED3DERR_NOTAVAILABLE;
1324                 goto error;
1325         }
1326 #undef COPYBOX_COLORKEY
1327         TRACE("Copy Done\n");
1328     }
1329     else
1330     {
1331         int width = w * bpp;
1332         TRACE("NO color key copy\n");
1333         for (y = 0; y < h; y++)
1334         {
1335             /* This is pretty easy, a line for line memcpy */
1336             memcpy(dbuf, sbuf, width);
1337             sbuf += slock.Pitch;
1338             dbuf += dlock.Pitch;
1339         }
1340         TRACE("Copy done\n");
1341     }
1342
1343 error:
1344     if (Src == This)
1345     {
1346         IWineD3DSurface_UnlockRect(iface);
1347     }
1348     else
1349     {
1350         IWineD3DSurface_UnlockRect(iface);
1351         IWineD3DSurface_UnlockRect(Source);
1352     }
1353
1354     return ret;
1355 }
1356
1357 /*****************************************************************************
1358  * IWineD3DSurface::LoadTexture, GDI version
1359  *
1360  * This is mutually unsupported by GDI surfaces
1361  *
1362  * Returns:
1363  *  D3DERR_INVALIDCALL
1364  *
1365  *****************************************************************************/
1366 HRESULT WINAPI
1367 IWineGDISurfaceImpl_LoadTexture(IWineD3DSurface *iface)
1368 {
1369     ERR("Unsupported on X11 surfaces\n");
1370     return WINED3DERR_INVALIDCALL;
1371 }
1372
1373 /*****************************************************************************
1374  * IWineD3DSurface::SaveSnapshot, GDI version
1375  *
1376  * This method writes the surface's contents to the in tga format to the
1377  * file specified in filename.
1378  *
1379  * Params:
1380  *  filename: File to write to
1381  *
1382  * Returns:
1383  *  WINED3DERR_INVALIDCALL if the file couldn't be opened
1384  *  WINED3D_OK on success
1385  *
1386  *****************************************************************************/
1387 static int get_shift(DWORD color_mask) {
1388     int shift = 0;
1389     while (color_mask > 0xFF) {
1390         color_mask >>= 1;
1391         shift += 1;
1392     }
1393     while ((color_mask & 0x80) == 0) {
1394         color_mask <<= 1;
1395         shift -= 1;
1396     }
1397     return shift;
1398 }
1399
1400
1401 HRESULT WINAPI
1402 IWineGDISurfaceImpl_SaveSnapshot(IWineD3DSurface *iface,
1403 const char* filename)
1404 {
1405     FILE* f = NULL;
1406     UINT y = 0, x = 0;
1407     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1408     static char *output = NULL;
1409     static int size = 0;
1410     const PixelFormatDesc *formatEntry = getFormatDescEntry(This->resource.format);
1411
1412     if (This->pow2Width > size) {
1413         output = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, This->pow2Width * 3);
1414         size = This->pow2Width;
1415     }
1416
1417
1418     f = fopen(filename, "w+");
1419     if (NULL == f) {
1420         ERR("opening of %s failed with\n", filename);
1421         return WINED3DERR_INVALIDCALL;
1422     }
1423     fprintf(f, "P6\n%d %d\n255\n", This->pow2Width, This->pow2Height);
1424
1425     if (This->resource.format == WINED3DFMT_P8) {
1426         unsigned char table[256][3];
1427         int i;
1428
1429         if (This->palette == NULL) {
1430             fclose(f);
1431             return WINED3DERR_INVALIDCALL;
1432         }
1433         for (i = 0; i < 256; i++) {
1434             table[i][0] = This->palette->palents[i].peRed;
1435             table[i][1] = This->palette->palents[i].peGreen;
1436             table[i][2] = This->palette->palents[i].peBlue;
1437         }
1438         for (y = 0; y < This->pow2Height; y++) {
1439             unsigned char *src = (unsigned char *) This->resource.allocatedMemory + (y * 1 * IWineD3DSurface_GetPitch(iface));
1440             for (x = 0; x < This->pow2Width; x++) {
1441                 unsigned char color = *src;
1442                 src += 1;
1443
1444                 output[3 * x + 0] = table[color][0];
1445                 output[3 * x + 1] = table[color][1];
1446                 output[3 * x + 2] = table[color][2];
1447             }
1448             fwrite(output, 3 * This->pow2Width, 1, f);
1449         }
1450     } else {
1451         int red_shift, green_shift, blue_shift, pix_width;
1452
1453         pix_width = This->bytesPerPixel;
1454
1455         red_shift = get_shift(formatEntry->redMask);
1456         green_shift = get_shift(formatEntry->greenMask);
1457         blue_shift = get_shift(formatEntry->blueMask);
1458
1459         for (y = 0; y < This->pow2Height; y++) {
1460             unsigned char *src = (unsigned char *) This->resource.allocatedMemory + (y * 1 * IWineD3DSurface_GetPitch(iface));
1461             for (x = 0; x < This->pow2Width; x++) {         
1462                 unsigned int color;
1463                 unsigned int comp;
1464                 int i;
1465
1466                 color = 0;
1467                 for (i = 0; i < pix_width; i++) {
1468                     color |= src[i] << (8 * i);
1469                 }
1470                 src += 1 * pix_width;
1471
1472                 comp = color & formatEntry->redMask;
1473                 output[3 * x + 0] = red_shift > 0 ? comp >> red_shift : comp << -red_shift;
1474                 comp = color & formatEntry->greenMask;
1475                 output[3 * x + 1] = green_shift > 0 ? comp >> green_shift : comp << -green_shift;
1476                 comp = color & formatEntry->blueMask;
1477                 output[3 * x + 2] = blue_shift > 0 ? comp >> blue_shift : comp << -blue_shift;
1478             }
1479             fwrite(output, 3 * This->pow2Width, 1, f);
1480         }
1481     }
1482     fclose(f);
1483     return WINED3D_OK;
1484 }
1485
1486 /*****************************************************************************
1487  * IWineD3DSurface::PrivateSetup, GDI version
1488  *
1489  * Initializes the GDI surface, aka creates the DIB section we render to
1490  * The DIB section creation is done by calling GetDC, which will create the
1491  * section and releasing the dc to allow the app to use it. The dib section
1492  * will stay until the surface is released
1493  *
1494  * GDI surfaces do not need to be a power of 2 in size, so the pow2 sizes
1495  * are set to the real sizes to save memory. The NONPOW2 flag is unset to
1496  * avoid confusion in the shared surface code.
1497  *
1498  * Returns:
1499  *  WINED3D_OK on success
1500  *  The return values of called methods on failure
1501  *
1502  *****************************************************************************/
1503 HRESULT WINAPI
1504 IWineGDISurfaceImpl_PrivateSetup(IWineD3DSurface *iface)
1505 {
1506     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
1507     HRESULT hr;
1508     HDC hdc;
1509     long oldsize = This->resource.size;
1510
1511     if(This->resource.usage & WINED3DUSAGE_OVERLAY)
1512     {
1513         ERR("(%p) Overlays not yet supported by GDI surfaces\n", This);
1514         return WINED3DERR_INVALIDCALL;
1515     }
1516     /* Sysmem textures have memory already allocated -
1517      * release it, this avoids an unnecessary memcpy
1518      */
1519     HeapFree(GetProcessHeap(), 0, This->resource.allocatedMemory);
1520     This->resource.allocatedMemory = NULL;
1521
1522     /* We don't mind the nonpow2 stuff in GDI */
1523     This->resource.size = IWineD3DSurface_GetPitch(iface) * This->currentDesc.Height;
1524     This->pow2Width = This->currentDesc.Width;
1525     This->pow2Height = This->currentDesc.Height;
1526     This->Flags &= ~SFLAG_NONPOW2;
1527
1528     /* Adjust the opengl mem counter */
1529     globalChangeGlRam(This->resource.size - oldsize);
1530
1531     /* Call GetDC to create a DIB section. We will use that
1532      * DIB section for rendering
1533      *
1534      * Release the DC afterwards to allow the app to use it
1535      */
1536     hr = IWineD3DSurface_GetDC(iface, &hdc);
1537     if(FAILED(hr))
1538     {
1539         ERR("(%p) IWineD3DSurface::GetDC failed with hr %08x\n", This, hr);
1540         return hr;
1541     }
1542     hr = IWineD3DSurface_ReleaseDC(iface, hdc);
1543     if(FAILED(hr))
1544     {
1545         ERR("(%p) IWineD3DSurface::ReleaseDC failed with hr %08x\n", This, hr);
1546         return hr;
1547     }
1548
1549     return WINED3D_OK;
1550 }
1551
1552 const IWineD3DSurfaceVtbl IWineGDISurface_Vtbl =
1553 {
1554     /* IUnknown */
1555     IWineD3DSurfaceImpl_QueryInterface,
1556     IWineD3DSurfaceImpl_AddRef,
1557     IWineD3DSurfaceImpl_Release,
1558     /* IWineD3DResource */
1559     IWineD3DSurfaceImpl_GetParent,
1560     IWineD3DSurfaceImpl_GetDevice,
1561     IWineD3DSurfaceImpl_SetPrivateData,
1562     IWineD3DSurfaceImpl_GetPrivateData,
1563     IWineD3DSurfaceImpl_FreePrivateData,
1564     IWineD3DSurfaceImpl_SetPriority,
1565     IWineD3DSurfaceImpl_GetPriority,
1566     IWineGDISurfaceImpl_PreLoad,
1567     IWineD3DSurfaceImpl_GetType,
1568     /* IWineD3DSurface */
1569     IWineD3DSurfaceImpl_GetContainer,
1570     IWineD3DSurfaceImpl_GetDesc,
1571     IWineGDISurfaceImpl_LockRect,
1572     IWineGDISurfaceImpl_UnlockRect,
1573     IWineD3DSurfaceImpl_GetDC,
1574     IWineD3DSurfaceImpl_ReleaseDC,
1575     IWineGDISurfaceImpl_Flip,
1576     IWineGDISurfaceImpl_Blt,
1577     IWineD3DSurfaceImpl_GetBltStatus,
1578     IWineD3DSurfaceImpl_GetFlipStatus,
1579     IWineD3DSurfaceImpl_IsLost,
1580     IWineD3DSurfaceImpl_Restore,
1581     IWineGDISurfaceImpl_BltFast,
1582     IWineD3DSurfaceImpl_GetPalette,
1583     IWineD3DSurfaceImpl_SetPalette,
1584     IWineD3DSurfaceImpl_RealizePalette,
1585     IWineD3DSurfaceImpl_SetColorKey,
1586     IWineD3DSurfaceImpl_GetPitch,
1587     IWineD3DSurfaceImpl_SetMem,
1588     IWineD3DSurfaceImpl_SetOverlayPosition,
1589     IWineD3DSurfaceImpl_GetOverlayPosition,
1590     IWineD3DSurfaceImpl_UpdateOverlayZOrder,
1591     IWineD3DSurfaceImpl_UpdateOverlay,
1592     IWineD3DSurfaceImpl_SetClipper,
1593     IWineD3DSurfaceImpl_GetClipper,
1594     /* Internal use: */
1595     IWineD3DSurfaceImpl_AddDirtyRect,
1596     IWineGDISurfaceImpl_LoadTexture,
1597     IWineGDISurfaceImpl_SaveSnapshot,
1598     IWineD3DSurfaceImpl_SetContainer,
1599     IWineD3DSurfaceImpl_SetGlTextureDesc,
1600     IWineD3DSurfaceImpl_GetGlDesc,
1601     IWineD3DSurfaceImpl_GetData,
1602     IWineD3DSurfaceImpl_SetFormat,
1603     IWineGDISurfaceImpl_PrivateSetup
1604 };