wined3d: Call glFlush outside the GL lock.
[wine] / dlls / wined3d / surface_base.c
1 /*
2  * IWineD3DSurface Implementation of management(non-rendering) functions
3  *
4  * Copyright 1998 Lionel Ulmer
5  * Copyright 2000-2001 TransGaming Technologies Inc.
6  * Copyright 2002-2005 Jason Edmeades
7  * Copyright 2002-2003 Raphael Junqueira
8  * Copyright 2004 Christian Costa
9  * Copyright 2005 Oliver Stieber
10  * Copyright 2006-2008 Stefan Dösinger for CodeWeavers
11  * Copyright 2007 Henri Verbeet
12  * Copyright 2006-2007 Roderick Colenbrander
13  *
14  * This library is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU Lesser General Public
16  * License as published by the Free Software Foundation; either
17  * version 2.1 of the License, or (at your option) any later version.
18  *
19  * This library is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22  * Lesser General Public License for more details.
23  *
24  * You should have received a copy of the GNU Lesser General Public
25  * License along with this library; if not, write to the Free Software
26  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27  */
28
29 #include "config.h"
30 #include "wine/port.h"
31 #include "wined3d_private.h"
32
33 #include <assert.h>
34
35 WINE_DEFAULT_DEBUG_CHANNEL(d3d_surface);
36
37 /* See also float_16_to_32() in wined3d_private.h */
38 static inline unsigned short float_32_to_16(const float *in)
39 {
40     int exp = 0;
41     float tmp = fabs(*in);
42     unsigned int mantissa;
43     unsigned short ret;
44
45     /* Deal with special numbers */
46     if(*in == 0.0) return 0x0000;
47     if(isnan(*in)) return 0x7C01;
48     if(isinf(*in)) return (*in < 0.0 ? 0xFC00 : 0x7c00);
49
50     if(tmp < pow(2, 10)) {
51         do
52         {
53             tmp = tmp * 2.0;
54             exp--;
55         }while(tmp < pow(2, 10));
56     } else if(tmp >= pow(2, 11)) {
57         do
58         {
59             tmp /= 2.0;
60             exp++;
61         }while(tmp >= pow(2, 11));
62     }
63
64     mantissa = (unsigned int) tmp;
65     if(tmp - mantissa >= 0.5) mantissa++; /* round to nearest, away from zero */
66
67     exp += 10;  /* Normalize the mantissa */
68     exp += 15;  /* Exponent is encoded with excess 15 */
69
70     if(exp > 30) { /* too big */
71         ret = 0x7c00; /* INF */
72     } else if(exp <= 0) {
73         /* exp == 0: Non-normalized mantissa. Returns 0x0000 (=0.0) for too small numbers */
74         while(exp <= 0) {
75             mantissa = mantissa >> 1;
76             exp++;
77         }
78         ret = mantissa & 0x3ff;
79     } else {
80         ret = (exp << 10) | (mantissa & 0x3ff);
81     }
82
83     ret |= ((*in < 0.0 ? 1 : 0) << 15); /* Add the sign */
84     return ret;
85 }
86
87
88 /* Do NOT define GLINFO_LOCATION in this file. THIS CODE MUST NOT USE IT */
89
90 /* *******************************************
91    IWineD3DSurface IUnknown parts follow
92    ******************************************* */
93 HRESULT WINAPI IWineD3DBaseSurfaceImpl_QueryInterface(IWineD3DSurface *iface, REFIID riid, LPVOID *ppobj)
94 {
95     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
96     /* Warn ,but be nice about things */
97     TRACE("(%p)->(%s,%p)\n", This,debugstr_guid(riid),ppobj);
98
99     if (IsEqualGUID(riid, &IID_IUnknown)
100         || IsEqualGUID(riid, &IID_IWineD3DBase)
101         || IsEqualGUID(riid, &IID_IWineD3DResource)
102         || IsEqualGUID(riid, &IID_IWineD3DSurface)) {
103         IUnknown_AddRef((IUnknown*)iface);
104         *ppobj = This;
105         return S_OK;
106         }
107         *ppobj = NULL;
108         return E_NOINTERFACE;
109 }
110
111 ULONG WINAPI IWineD3DBaseSurfaceImpl_AddRef(IWineD3DSurface *iface) {
112     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
113     ULONG ref = InterlockedIncrement(&This->resource.ref);
114     TRACE("(%p) : AddRef increasing from %d\n", This,ref - 1);
115     return ref;
116 }
117
118 /* ****************************************************
119    IWineD3DSurface IWineD3DResource parts follow
120    **************************************************** */
121 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetDevice(IWineD3DSurface *iface, IWineD3DDevice** ppDevice) {
122     return IWineD3DResourceImpl_GetDevice((IWineD3DResource *)iface, ppDevice);
123 }
124
125 HRESULT WINAPI IWineD3DBaseSurfaceImpl_SetPrivateData(IWineD3DSurface *iface, REFGUID refguid, CONST void* pData, DWORD SizeOfData, DWORD Flags) {
126     return IWineD3DResourceImpl_SetPrivateData((IWineD3DResource *)iface, refguid, pData, SizeOfData, Flags);
127 }
128
129 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetPrivateData(IWineD3DSurface *iface, REFGUID refguid, void* pData, DWORD* pSizeOfData) {
130     return IWineD3DResourceImpl_GetPrivateData((IWineD3DResource *)iface, refguid, pData, pSizeOfData);
131 }
132
133 HRESULT WINAPI IWineD3DBaseSurfaceImpl_FreePrivateData(IWineD3DSurface *iface, REFGUID refguid) {
134     return IWineD3DResourceImpl_FreePrivateData((IWineD3DResource *)iface, refguid);
135 }
136
137 DWORD   WINAPI IWineD3DBaseSurfaceImpl_SetPriority(IWineD3DSurface *iface, DWORD PriorityNew) {
138     return IWineD3DResourceImpl_SetPriority((IWineD3DResource *)iface, PriorityNew);
139 }
140
141 DWORD   WINAPI IWineD3DBaseSurfaceImpl_GetPriority(IWineD3DSurface *iface) {
142     return IWineD3DResourceImpl_GetPriority((IWineD3DResource *)iface);
143 }
144
145 WINED3DRESOURCETYPE WINAPI IWineD3DBaseSurfaceImpl_GetType(IWineD3DSurface *iface) {
146     TRACE("(%p) : calling resourceimpl_GetType\n", iface);
147     return IWineD3DResourceImpl_GetType((IWineD3DResource *)iface);
148 }
149
150 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetParent(IWineD3DSurface *iface, IUnknown **pParent) {
151     TRACE("(%p) : calling resourceimpl_GetParent\n", iface);
152     return IWineD3DResourceImpl_GetParent((IWineD3DResource *)iface, pParent);
153 }
154
155 /* ******************************************************
156    IWineD3DSurface IWineD3DSurface parts follow
157    ****************************************************** */
158
159 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetContainer(IWineD3DSurface* iface, REFIID riid, void** ppContainer) {
160     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
161     IWineD3DBase *container = 0;
162
163     TRACE("(This %p, riid %s, ppContainer %p)\n", This, debugstr_guid(riid), ppContainer);
164
165     if (!ppContainer) {
166         ERR("Called without a valid ppContainer.\n");
167     }
168
169     /** From MSDN:
170      * If the surface is created using CreateImageSurface/CreateOffscreenPlainSurface, CreateRenderTarget,
171      * or CreateDepthStencilSurface, the surface is considered stand alone. In this case,
172      * GetContainer will return the Direct3D device used to create the surface.
173      */
174     if (This->container) {
175         container = This->container;
176     } else {
177         container = (IWineD3DBase *)This->resource.wineD3DDevice;
178     }
179
180     TRACE("Relaying to QueryInterface\n");
181     return IUnknown_QueryInterface(container, riid, ppContainer);
182 }
183
184 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetDesc(IWineD3DSurface *iface, WINED3DSURFACE_DESC *pDesc) {
185     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
186
187     TRACE("(%p) : copying into %p\n", This, pDesc);
188     if(pDesc->Format != NULL)             *(pDesc->Format) = This->resource.format;
189     if(pDesc->Type != NULL)               *(pDesc->Type)   = This->resource.resourceType;
190     if(pDesc->Usage != NULL)              *(pDesc->Usage)              = This->resource.usage;
191     if(pDesc->Pool != NULL)               *(pDesc->Pool)               = This->resource.pool;
192     if(pDesc->Size != NULL)               *(pDesc->Size)               = This->resource.size;   /* dx8 only */
193     if(pDesc->MultiSampleType != NULL)    *(pDesc->MultiSampleType)    = This->currentDesc.MultiSampleType;
194     if(pDesc->MultiSampleQuality != NULL) *(pDesc->MultiSampleQuality) = This->currentDesc.MultiSampleQuality;
195     if(pDesc->Width != NULL)              *(pDesc->Width)              = This->currentDesc.Width;
196     if(pDesc->Height != NULL)             *(pDesc->Height)             = This->currentDesc.Height;
197     return WINED3D_OK;
198 }
199
200 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetBltStatus(IWineD3DSurface *iface, DWORD Flags) {
201     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
202     TRACE("(%p)->(%x)\n", This, Flags);
203
204     switch (Flags)
205     {
206         case WINEDDGBS_CANBLT:
207         case WINEDDGBS_ISBLTDONE:
208             return WINED3D_OK;
209
210         default:
211             return WINED3DERR_INVALIDCALL;
212     }
213 }
214
215 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetFlipStatus(IWineD3DSurface *iface, DWORD Flags) {
216     /* XXX: DDERR_INVALIDSURFACETYPE */
217
218     TRACE("(%p)->(%08x)\n",iface,Flags);
219     switch (Flags) {
220         case WINEDDGFS_CANFLIP:
221         case WINEDDGFS_ISFLIPDONE:
222             return WINED3D_OK;
223
224         default:
225             return WINED3DERR_INVALIDCALL;
226     }
227 }
228
229 HRESULT WINAPI IWineD3DBaseSurfaceImpl_IsLost(IWineD3DSurface *iface) {
230     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
231     TRACE("(%p)\n", This);
232
233     /* D3D8 and 9 loose full devices, ddraw only surfaces */
234     return This->Flags & SFLAG_LOST ? WINED3DERR_DEVICELOST : WINED3D_OK;
235 }
236
237 HRESULT WINAPI IWineD3DBaseSurfaceImpl_Restore(IWineD3DSurface *iface) {
238     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
239     TRACE("(%p)\n", This);
240
241     /* So far we don't lose anything :) */
242     This->Flags &= ~SFLAG_LOST;
243     return WINED3D_OK;
244 }
245
246 HRESULT WINAPI IWineD3DBaseSurfaceImpl_SetPalette(IWineD3DSurface *iface, IWineD3DPalette *Pal) {
247     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
248     IWineD3DPaletteImpl *PalImpl = (IWineD3DPaletteImpl *) Pal;
249     TRACE("(%p)->(%p)\n", This, Pal);
250
251     if(This->palette == PalImpl) {
252         TRACE("Nop palette change\n");
253         return WINED3D_OK;
254     }
255
256     if(This->palette != NULL)
257         if(This->resource.usage & WINED3DUSAGE_RENDERTARGET)
258             This->palette->Flags &= ~WINEDDPCAPS_PRIMARYSURFACE;
259
260     This->palette = PalImpl;
261
262     if(PalImpl != NULL) {
263         if(This->resource.usage & WINED3DUSAGE_RENDERTARGET) {
264             (PalImpl)->Flags |= WINEDDPCAPS_PRIMARYSURFACE;
265         }
266
267         return IWineD3DSurface_RealizePalette(iface);
268     }
269     else return WINED3D_OK;
270 }
271
272 HRESULT WINAPI IWineD3DBaseSurfaceImpl_SetColorKey(IWineD3DSurface *iface, DWORD Flags, WINEDDCOLORKEY *CKey) {
273     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
274     TRACE("(%p)->(%08x,%p)\n", This, Flags, CKey);
275
276     if ((Flags & WINEDDCKEY_COLORSPACE) != 0) {
277         FIXME(" colorkey value not supported (%08x) !\n", Flags);
278         return WINED3DERR_INVALIDCALL;
279     }
280
281     /* Dirtify the surface, but only if a key was changed */
282     if(CKey) {
283         switch (Flags & ~WINEDDCKEY_COLORSPACE) {
284             case WINEDDCKEY_DESTBLT:
285                 This->DestBltCKey = *CKey;
286                 This->CKeyFlags |= WINEDDSD_CKDESTBLT;
287                 break;
288
289             case WINEDDCKEY_DESTOVERLAY:
290                 This->DestOverlayCKey = *CKey;
291                 This->CKeyFlags |= WINEDDSD_CKDESTOVERLAY;
292                 break;
293
294             case WINEDDCKEY_SRCOVERLAY:
295                 This->SrcOverlayCKey = *CKey;
296                 This->CKeyFlags |= WINEDDSD_CKSRCOVERLAY;
297                 break;
298
299             case WINEDDCKEY_SRCBLT:
300                 This->SrcBltCKey = *CKey;
301                 This->CKeyFlags |= WINEDDSD_CKSRCBLT;
302                 break;
303         }
304     }
305     else {
306         switch (Flags & ~WINEDDCKEY_COLORSPACE) {
307             case WINEDDCKEY_DESTBLT:
308                 This->CKeyFlags &= ~WINEDDSD_CKDESTBLT;
309                 break;
310
311             case WINEDDCKEY_DESTOVERLAY:
312                 This->CKeyFlags &= ~WINEDDSD_CKDESTOVERLAY;
313                 break;
314
315             case WINEDDCKEY_SRCOVERLAY:
316                 This->CKeyFlags &= ~WINEDDSD_CKSRCOVERLAY;
317                 break;
318
319             case WINEDDCKEY_SRCBLT:
320                 This->CKeyFlags &= ~WINEDDSD_CKSRCBLT;
321                 break;
322         }
323     }
324
325     return WINED3D_OK;
326 }
327
328 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetPalette(IWineD3DSurface *iface, IWineD3DPalette **Pal) {
329     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
330     TRACE("(%p)->(%p)\n", This, Pal);
331
332     *Pal = (IWineD3DPalette *) This->palette;
333     return WINED3D_OK;
334 }
335
336 DWORD WINAPI IWineD3DBaseSurfaceImpl_GetPitch(IWineD3DSurface *iface) {
337     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
338     DWORD ret;
339     TRACE("(%p)\n", This);
340
341     /* DXTn formats don't have exact pitches as they are to the new row of blocks,
342     where each block is 4x4 pixels, 8 bytes (dxt1) and 16 bytes (dxt2/3/4/5)
343     ie pitch = (width/4) * bytes per block                                  */
344     if (This->resource.format == WINED3DFMT_DXT1) /* DXT1 is 8 bytes per block */
345         ret = ((This->currentDesc.Width + 3) >> 2) << 3;
346     else if (This->resource.format == WINED3DFMT_DXT2 || This->resource.format == WINED3DFMT_DXT3 ||
347              This->resource.format == WINED3DFMT_DXT4 || This->resource.format == WINED3DFMT_DXT5) /* DXT2/3/4/5 is 16 bytes per block */
348         ret = ((This->currentDesc.Width + 3) >> 2) << 4;
349     else {
350         unsigned char alignment = This->resource.wineD3DDevice->surface_alignment;
351         ret = This->bytesPerPixel * This->currentDesc.Width;  /* Bytes / row */
352         ret = (ret + alignment - 1) & ~(alignment - 1);
353     }
354     TRACE("(%p) Returning %d\n", This, ret);
355     return ret;
356 }
357
358 HRESULT WINAPI IWineD3DBaseSurfaceImpl_SetOverlayPosition(IWineD3DSurface *iface, LONG X, LONG Y) {
359     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
360
361     FIXME("(%p)->(%d,%d) Stub!\n", This, X, Y);
362
363     if(!(This->resource.usage & WINED3DUSAGE_OVERLAY))
364     {
365         TRACE("(%p): Not an overlay surface\n", This);
366         return WINEDDERR_NOTAOVERLAYSURFACE;
367     }
368
369     return WINED3D_OK;
370 }
371
372 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetOverlayPosition(IWineD3DSurface *iface, LONG *X, LONG *Y) {
373     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
374
375     FIXME("(%p)->(%p,%p) Stub!\n", This, X, Y);
376
377     if(!(This->resource.usage & WINED3DUSAGE_OVERLAY))
378     {
379         TRACE("(%p): Not an overlay surface\n", This);
380         return WINEDDERR_NOTAOVERLAYSURFACE;
381     }
382
383     return WINED3D_OK;
384 }
385
386 HRESULT WINAPI IWineD3DBaseSurfaceImpl_UpdateOverlayZOrder(IWineD3DSurface *iface, DWORD Flags, IWineD3DSurface *Ref) {
387     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
388     IWineD3DSurfaceImpl *RefImpl = (IWineD3DSurfaceImpl *) Ref;
389
390     FIXME("(%p)->(%08x,%p) Stub!\n", This, Flags, RefImpl);
391
392     if(!(This->resource.usage & WINED3DUSAGE_OVERLAY))
393     {
394         TRACE("(%p): Not an overlay surface\n", This);
395         return WINEDDERR_NOTAOVERLAYSURFACE;
396     }
397
398     return WINED3D_OK;
399 }
400
401 HRESULT WINAPI IWineD3DBaseSurfaceImpl_UpdateOverlay(IWineD3DSurface *iface, RECT *SrcRect, IWineD3DSurface *DstSurface, RECT *DstRect, DWORD Flags, WINEDDOVERLAYFX *FX) {
402     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
403     IWineD3DSurfaceImpl *Dst = (IWineD3DSurfaceImpl *) DstSurface;
404     FIXME("(%p)->(%p, %p, %p, %08x, %p)\n", This, SrcRect, Dst, DstRect, Flags, FX);
405
406     if(!(This->resource.usage & WINED3DUSAGE_OVERLAY))
407     {
408         TRACE("(%p): Not an overlay surface\n", This);
409         return WINEDDERR_NOTAOVERLAYSURFACE;
410     }
411
412     return WINED3D_OK;
413 }
414
415 HRESULT WINAPI IWineD3DBaseSurfaceImpl_SetClipper(IWineD3DSurface *iface, IWineD3DClipper *clipper)
416 {
417     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
418     TRACE("(%p)->(%p)\n", This, clipper);
419
420     This->clipper = clipper;
421     return WINED3D_OK;
422 }
423
424 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetClipper(IWineD3DSurface *iface, IWineD3DClipper **clipper)
425 {
426     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
427     TRACE("(%p)->(%p)\n", This, clipper);
428
429     *clipper = This->clipper;
430     if(*clipper) {
431         IWineD3DClipper_AddRef(*clipper);
432     }
433     return WINED3D_OK;
434 }
435
436 HRESULT WINAPI IWineD3DBaseSurfaceImpl_SetContainer(IWineD3DSurface *iface, IWineD3DBase *container) {
437     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
438
439     TRACE("This %p, container %p\n", This, container);
440
441     /* We can't keep a reference to the container, since the container already keeps a reference to us. */
442
443     TRACE("Setting container to %p from %p\n", container, This->container);
444     This->container = container;
445
446     return WINED3D_OK;
447 }
448
449 HRESULT WINAPI IWineD3DBaseSurfaceImpl_SetFormat(IWineD3DSurface *iface, WINED3DFORMAT format) {
450     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
451     const StaticPixelFormatDesc *formatEntry = getFormatDescEntry(format, NULL, NULL);
452
453     if (This->resource.format != WINED3DFMT_UNKNOWN) {
454         FIXME("(%p) : The format of the surface must be WINED3DFORMAT_UNKNOWN\n", This);
455         return WINED3DERR_INVALIDCALL;
456     }
457
458     TRACE("(%p) : Setting texture format to (%d,%s)\n", This, format, debug_d3dformat(format));
459     if (format == WINED3DFMT_UNKNOWN) {
460         This->resource.size = 0;
461     } else if (format == WINED3DFMT_DXT1) {
462         /* DXT1 is half byte per pixel */
463         This->resource.size = ((max(This->pow2Width, 4) * formatEntry->bpp) * max(This->pow2Height, 4)) >> 1;
464
465     } else if (format == WINED3DFMT_DXT2 || format == WINED3DFMT_DXT3 ||
466                format == WINED3DFMT_DXT4 || format == WINED3DFMT_DXT5) {
467         This->resource.size = ((max(This->pow2Width, 4) * formatEntry->bpp) * max(This->pow2Height, 4));
468     } else {
469         unsigned char alignment = This->resource.wineD3DDevice->surface_alignment;
470         This->resource.size = ((This->pow2Width * formatEntry->bpp) + alignment - 1) & ~(alignment - 1);
471         This->resource.size *= This->pow2Height;
472     }
473
474     if (format != WINED3DFMT_UNKNOWN) {
475         This->bytesPerPixel = formatEntry->bpp;
476     } else {
477         This->bytesPerPixel = 0;
478     }
479
480     This->Flags |= (WINED3DFMT_D16_LOCKABLE == format) ? SFLAG_LOCKABLE : 0;
481
482     This->resource.format = format;
483
484     TRACE("(%p) : Size %d, bytesPerPixel %d\n", This, This->resource.size, This->bytesPerPixel);
485
486     return WINED3D_OK;
487 }
488
489 HRESULT IWineD3DBaseSurfaceImpl_CreateDIBSection(IWineD3DSurface *iface) {
490     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
491     int extraline = 0;
492     SYSTEM_INFO sysInfo;
493     BITMAPINFO* b_info;
494     HDC ddc;
495     DWORD *masks;
496     const StaticPixelFormatDesc *formatEntry = getFormatDescEntry(This->resource.format, NULL, NULL);
497     UINT usage;
498
499     switch (This->bytesPerPixel) {
500         case 2:
501         case 4:
502             /* Allocate extra space to store the RGB bit masks. */
503             b_info = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BITMAPINFOHEADER) + 3 * sizeof(DWORD));
504             break;
505
506         case 3:
507             b_info = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BITMAPINFOHEADER));
508             break;
509
510         default:
511             /* Allocate extra space for a palette. */
512             b_info = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
513                                sizeof(BITMAPINFOHEADER)
514                                + sizeof(RGBQUAD)
515                                * (1 << (This->bytesPerPixel * 8)));
516             break;
517     }
518
519     if (!b_info)
520         return E_OUTOFMEMORY;
521
522         /* Some apps access the surface in via DWORDs, and do not take the necessary care at the end of the
523     * surface. So we need at least extra 4 bytes at the end of the surface. Check against the page size,
524     * if the last page used for the surface has at least 4 spare bytes we're safe, otherwise
525     * add an extra line to the dib section
526         */
527     GetSystemInfo(&sysInfo);
528     if( ((This->resource.size + 3) % sysInfo.dwPageSize) < 4) {
529         extraline = 1;
530         TRACE("Adding an extra line to the dib section\n");
531     }
532
533     b_info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
534     /* TODO: Is there a nicer way to force a specific alignment? (8 byte for ddraw) */
535     b_info->bmiHeader.biWidth = IWineD3DSurface_GetPitch(iface) / This->bytesPerPixel;
536     b_info->bmiHeader.biHeight = -This->currentDesc.Height -extraline;
537     b_info->bmiHeader.biSizeImage = ( This->currentDesc.Height + extraline) * IWineD3DSurface_GetPitch(iface);
538     b_info->bmiHeader.biPlanes = 1;
539     b_info->bmiHeader.biBitCount = This->bytesPerPixel * 8;
540
541     b_info->bmiHeader.biXPelsPerMeter = 0;
542     b_info->bmiHeader.biYPelsPerMeter = 0;
543     b_info->bmiHeader.biClrUsed = 0;
544     b_info->bmiHeader.biClrImportant = 0;
545
546     /* Get the bit masks */
547     masks = (DWORD *)b_info->bmiColors;
548     switch (This->resource.format) {
549         case WINED3DFMT_R8G8B8:
550             usage = DIB_RGB_COLORS;
551             b_info->bmiHeader.biCompression = BI_RGB;
552             break;
553
554         case WINED3DFMT_X1R5G5B5:
555         case WINED3DFMT_A1R5G5B5:
556         case WINED3DFMT_A4R4G4B4:
557         case WINED3DFMT_X4R4G4B4:
558         case WINED3DFMT_R3G3B2:
559         case WINED3DFMT_A8R3G3B2:
560         case WINED3DFMT_A2B10G10R10:
561         case WINED3DFMT_A8B8G8R8:
562         case WINED3DFMT_X8B8G8R8:
563         case WINED3DFMT_A2R10G10B10:
564         case WINED3DFMT_R5G6B5:
565         case WINED3DFMT_A16B16G16R16:
566             usage = 0;
567             b_info->bmiHeader.biCompression = BI_BITFIELDS;
568             masks[0] = formatEntry->redMask;
569             masks[1] = formatEntry->greenMask;
570             masks[2] = formatEntry->blueMask;
571             break;
572
573         default:
574             /* Don't know palette */
575             b_info->bmiHeader.biCompression = BI_RGB;
576             usage = 0;
577             break;
578     }
579
580     ddc = GetDC(0);
581     if (ddc == 0) {
582         HeapFree(GetProcessHeap(), 0, b_info);
583         return HRESULT_FROM_WIN32(GetLastError());
584     }
585
586     TRACE("Creating a DIB section with size %dx%dx%d, size=%d\n", b_info->bmiHeader.biWidth, b_info->bmiHeader.biHeight, b_info->bmiHeader.biBitCount, b_info->bmiHeader.biSizeImage);
587     This->dib.DIBsection = CreateDIBSection(ddc, b_info, usage, &This->dib.bitmap_data, 0 /* Handle */, 0 /* Offset */);
588     ReleaseDC(0, ddc);
589
590     if (!This->dib.DIBsection) {
591         ERR("CreateDIBSection failed!\n");
592         HeapFree(GetProcessHeap(), 0, b_info);
593         return HRESULT_FROM_WIN32(GetLastError());
594     }
595
596     TRACE("DIBSection at : %p\n", This->dib.bitmap_data);
597     /* copy the existing surface to the dib section */
598     if(This->resource.allocatedMemory) {
599         memcpy(This->dib.bitmap_data, This->resource.allocatedMemory,  This->currentDesc.Height * IWineD3DSurface_GetPitch(iface));
600     } else {
601         /* This is to make LockRect read the gl Texture although memory is allocated */
602         This->Flags &= ~SFLAG_INSYSMEM;
603     }
604     This->dib.bitmap_size = b_info->bmiHeader.biSizeImage;
605
606     HeapFree(GetProcessHeap(), 0, b_info);
607
608     /* Now allocate a HDC */
609     This->hDC = CreateCompatibleDC(0);
610     This->dib.holdbitmap = SelectObject(This->hDC, This->dib.DIBsection);
611     TRACE("using wined3d palette %p\n", This->palette);
612     SelectPalette(This->hDC,
613                   This->palette ? This->palette->hpal : 0,
614                   FALSE);
615
616     This->Flags |= SFLAG_DIBSECTION;
617
618     HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
619     This->resource.heapMemory = NULL;
620
621     return WINED3D_OK;
622 }
623
624 void convert_r32f_r16f(BYTE *src, BYTE *dst, DWORD pitch_in, DWORD pitch_out, unsigned int w, unsigned int h) {
625     unsigned int x, y;
626     float *src_f;
627     unsigned short *dst_s;
628
629     TRACE("Converting %dx%d pixels, pitches %d %d\n", w, h, pitch_in, pitch_out);
630     for(y = 0; y < h; y++) {
631         src_f = (float *) (src + y * pitch_in);
632         dst_s = (unsigned short *) (dst + y * pitch_out);
633         for(x = 0; x < w; x++) {
634             dst_s[x] = float_32_to_16(src_f + x);
635         }
636     }
637 }
638
639 struct d3dfmt_convertor_desc {
640     WINED3DFORMAT from, to;
641     void (*convert)(BYTE *src, BYTE *dst, DWORD pitch_in, DWORD pitch_out, unsigned int w, unsigned int h);
642 };
643
644 struct d3dfmt_convertor_desc convertors[] = {
645     {WINED3DFMT_R32F,       WINED3DFMT_R16F,        convert_r32f_r16f},
646 };
647
648 static inline struct d3dfmt_convertor_desc *find_convertor(WINED3DFORMAT from, WINED3DFORMAT to) {
649     unsigned int i;
650     for(i = 0; i < (sizeof(convertors) / sizeof(convertors[0])); i++) {
651         if(convertors[i].from == from && convertors[i].to == to) {
652             return &convertors[i];
653         }
654     }
655     return NULL;
656 }
657
658 /*****************************************************************************
659  * surface_convert_format
660  *
661  * Creates a duplicate of a surface in a different format. Is used by Blt to
662  * blit between surfaces with different formats
663  *
664  * Parameters
665  *  source: Source surface
666  *  fmt: Requested destination format
667  *
668  *****************************************************************************/
669 IWineD3DSurfaceImpl *surface_convert_format(IWineD3DSurfaceImpl *source, WINED3DFORMAT to_fmt) {
670     IWineD3DSurface *ret = NULL;
671     struct d3dfmt_convertor_desc *conv;
672     WINED3DLOCKED_RECT lock_src, lock_dst;
673     HRESULT hr;
674
675     conv = find_convertor(source->resource.format, to_fmt);
676     if(!conv) {
677         FIXME("Cannot find a conversion function from format %s to %s\n",
678               debug_d3dformat(source->resource.format), debug_d3dformat(to_fmt));
679         return NULL;
680     }
681
682     IWineD3DDevice_CreateSurface((IWineD3DDevice *) source->resource.wineD3DDevice,
683                                  source->currentDesc.Width,
684                                  source->currentDesc.Height,
685                                  to_fmt,
686                                  TRUE,  /* lockable */
687                                  TRUE,  /* discard  */
688                                  0,     /* level */
689                                  &ret,
690                                  WINED3DRTYPE_SURFACE,
691                                  0,     /* usage */
692                                  WINED3DPOOL_SCRATCH,
693                                  WINED3DMULTISAMPLE_NONE,   /* TODO: Multisampled conversion */
694                                  0,     /* MultiSampleQuality */
695                                  NULL,  /* SharedHandle */
696                                  IWineD3DSurface_GetImplType((IWineD3DSurface *) source),
697                                  NULL); /* parent */
698     if(!ret) {
699         ERR("Failed to create a destination surface for conversion\n");
700         return NULL;
701     }
702
703     memset(&lock_src, 0, sizeof(lock_src));
704     memset(&lock_dst, 0, sizeof(lock_dst));
705
706     hr = IWineD3DSurface_LockRect((IWineD3DSurface *) source, &lock_src, NULL, WINED3DLOCK_READONLY);
707     if(FAILED(hr)) {
708         ERR("Failed to lock the source surface\n");
709         IWineD3DSurface_Release(ret);
710         return NULL;
711     }
712     hr = IWineD3DSurface_LockRect(ret, &lock_dst, NULL, WINED3DLOCK_READONLY);
713     if(FAILED(hr)) {
714         ERR("Failed to lock the dest surface\n");
715         IWineD3DSurface_UnlockRect((IWineD3DSurface *) source);
716         IWineD3DSurface_Release(ret);
717         return NULL;
718     }
719
720     conv->convert(lock_src.pBits, lock_dst.pBits, lock_src.Pitch, lock_dst.Pitch,
721                   source->currentDesc.Width, source->currentDesc.Height);
722
723     IWineD3DSurface_UnlockRect(ret);
724     IWineD3DSurface_UnlockRect((IWineD3DSurface *) source);
725
726     return (IWineD3DSurfaceImpl *) ret;
727 }
728
729 /*****************************************************************************
730  * _Blt_ColorFill
731  *
732  * Helper function that fills a memory area with a specific color
733  *
734  * Params:
735  *  buf: memory address to start filling at
736  *  width, height: Dimensions of the area to fill
737  *  bpp: Bit depth of the surface
738  *  lPitch: pitch of the surface
739  *  color: Color to fill with
740  *
741  *****************************************************************************/
742 static HRESULT
743         _Blt_ColorFill(BYTE *buf,
744                        int width, int height,
745                        int bpp, LONG lPitch,
746                        DWORD color)
747 {
748     int x, y;
749     LPBYTE first;
750
751     /* Do first row */
752
753 #define COLORFILL_ROW(type) \
754     { \
755     type *d = (type *) buf; \
756     for (x = 0; x < width; x++) \
757     d[x] = (type) color; \
758     break; \
759 }
760     switch(bpp)
761     {
762         case 1: COLORFILL_ROW(BYTE)
763                 case 2: COLORFILL_ROW(WORD)
764         case 3:
765         {
766             BYTE *d = buf;
767             for (x = 0; x < width; x++,d+=3)
768             {
769                 d[0] = (color    ) & 0xFF;
770                 d[1] = (color>> 8) & 0xFF;
771                 d[2] = (color>>16) & 0xFF;
772             }
773             break;
774         }
775         case 4: COLORFILL_ROW(DWORD)
776         default:
777             FIXME("Color fill not implemented for bpp %d!\n", bpp*8);
778             return WINED3DERR_NOTAVAILABLE;
779     }
780
781 #undef COLORFILL_ROW
782
783     /* Now copy first row */
784     first = buf;
785     for (y = 1; y < height; y++)
786     {
787         buf += lPitch;
788         memcpy(buf, first, width * bpp);
789     }
790     return WINED3D_OK;
791 }
792
793 /*****************************************************************************
794  * IWineD3DSurface::Blt, SW emulation version
795  *
796  * Performs blits to a surface, eigher from a source of source-less blts
797  * This is the main functionality of DirectDraw
798  *
799  * Params:
800  *  DestRect: Destination rectangle to write to
801  *  SrcSurface: Source surface, can be NULL
802  *  SrcRect: Source rectangle
803  *****************************************************************************/
804 HRESULT WINAPI
805 IWineD3DBaseSurfaceImpl_Blt(IWineD3DSurface *iface,
806                             RECT *DestRect,
807                             IWineD3DSurface *SrcSurface,
808                             RECT *SrcRect,
809                             DWORD Flags,
810                             WINEDDBLTFX *DDBltFx,
811                             WINED3DTEXTUREFILTERTYPE Filter)
812 {
813     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
814     IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
815     RECT        xdst,xsrc;
816     HRESULT     ret = WINED3D_OK;
817     WINED3DLOCKED_RECT  dlock, slock;
818     WINED3DFORMAT       dfmt = WINED3DFMT_UNKNOWN, sfmt = WINED3DFMT_UNKNOWN;
819     int bpp, srcheight, srcwidth, dstheight, dstwidth, width;
820     int x, y;
821     const StaticPixelFormatDesc *sEntry, *dEntry;
822     LPBYTE dbuf, sbuf;
823     TRACE("(%p)->(%p,%p,%p,%x,%p)\n", This, DestRect, Src, SrcRect, Flags, DDBltFx);
824
825     if (TRACE_ON(d3d_surface))
826     {
827         if (DestRect) TRACE("\tdestrect :%dx%d-%dx%d\n",
828             DestRect->left, DestRect->top, DestRect->right, DestRect->bottom);
829         if (SrcRect) TRACE("\tsrcrect  :%dx%d-%dx%d\n",
830             SrcRect->left, SrcRect->top, SrcRect->right, SrcRect->bottom);
831 #if 0
832         TRACE("\tflags: ");
833                       DDRAW_dump_DDBLT(Flags);
834                       if (Flags & WINEDDBLT_DDFX)
835               {
836                       TRACE("\tblitfx: ");
837                       DDRAW_dump_DDBLTFX(DDBltFx->dwDDFX);
838     }
839 #endif
840     }
841
842     if ( (This->Flags & SFLAG_LOCKED) || ((Src != NULL) && (Src->Flags & SFLAG_LOCKED)))
843     {
844         WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
845         return WINEDDERR_SURFACEBUSY;
846     }
847
848     if(Filter != WINED3DTEXF_NONE && Filter != WINED3DTEXF_POINT) {
849         /* Can happen when d3d9 apps do a StretchRect call which isn't handled in gl */
850         FIXME("Filters not supported in software blit\n");
851     }
852
853     /* First check for the validity of source / destination rectangles. This was
854      * verified using a test application + by MSDN.
855      */
856     if ((Src != NULL) && (SrcRect != NULL) &&
857          ((SrcRect->bottom > Src->currentDesc.Height)||(SrcRect->bottom < 0) ||
858          (SrcRect->top     > Src->currentDesc.Height)||(SrcRect->top    < 0) ||
859          (SrcRect->left    > Src->currentDesc.Width) ||(SrcRect->left   < 0) ||
860          (SrcRect->right   > Src->currentDesc.Width) ||(SrcRect->right  < 0) ||
861          (SrcRect->right   < SrcRect->left)          ||(SrcRect->bottom < SrcRect->top)))
862     {
863         WARN("Application gave us bad source rectangle for Blt.\n");
864         return WINEDDERR_INVALIDRECT;
865     }
866     /* For the Destination rect, it can be out of bounds on the condition that a clipper
867      * is set for the given surface.
868      */
869     if ((/*This->clipper == NULL*/ TRUE) && (DestRect) &&
870          ((DestRect->bottom > This->currentDesc.Height)||(DestRect->bottom < 0) ||
871          (DestRect->top     > This->currentDesc.Height)||(DestRect->top    < 0) ||
872          (DestRect->left    > This->currentDesc.Width) ||(DestRect->left   < 0) ||
873          (DestRect->right   > This->currentDesc.Width) ||(DestRect->right  < 0) ||
874          (DestRect->right   < DestRect->left)          ||(DestRect->bottom < DestRect->top)))
875     {
876         WARN("Application gave us bad destination rectangle for Blt without a clipper set.\n");
877         return WINEDDERR_INVALIDRECT;
878     }
879
880     /* Now handle negative values in the rectangles. Warning: only supported for now
881     in the 'simple' cases (ie not in any stretching / rotation cases).
882
883     First, the case where nothing is to be done.
884     */
885     if ((DestRect && ((DestRect->bottom <= 0) || (DestRect->right <= 0)  ||
886           (DestRect->top    >= (int) This->currentDesc.Height) ||
887           (DestRect->left   >= (int) This->currentDesc.Width))) ||
888           ((Src != NULL) && (SrcRect != NULL) &&
889           ((SrcRect->bottom <= 0) || (SrcRect->right <= 0)     ||
890           (SrcRect->top >= (int) Src->currentDesc.Height) ||
891           (SrcRect->left >= (int) Src->currentDesc.Width))  ))
892     {
893         TRACE("Nothing to be done !\n");
894         return  WINED3D_OK;
895     }
896
897     if (DestRect)
898     {
899         xdst = *DestRect;
900     }
901     else
902     {
903         xdst.top    = 0;
904         xdst.bottom = This->currentDesc.Height;
905         xdst.left   = 0;
906         xdst.right  = This->currentDesc.Width;
907     }
908
909     if (SrcRect)
910     {
911         xsrc = *SrcRect;
912     }
913     else
914     {
915         if (Src)
916         {
917             xsrc.top    = 0;
918             xsrc.bottom = Src->currentDesc.Height;
919             xsrc.left   = 0;
920             xsrc.right  = Src->currentDesc.Width;
921         }
922         else
923         {
924             memset(&xsrc,0,sizeof(xsrc));
925         }
926     }
927
928     /* The easy case : the source-less blits.... */
929     if (Src == NULL && DestRect)
930     {
931         RECT full_rect;
932         RECT temp_rect; /* No idea if intersect rect can be the same as one of the source rect */
933
934         full_rect.left   = 0;
935         full_rect.top    = 0;
936         full_rect.right  = This->currentDesc.Width;
937         full_rect.bottom = This->currentDesc.Height;
938         IntersectRect(&temp_rect, &full_rect, DestRect);
939         xdst = temp_rect;
940     }
941     else if (DestRect)
942     {
943         /* Only handle clipping on the destination rectangle */
944         int clip_horiz = (DestRect->left < 0) || (DestRect->right  > (int) This->currentDesc.Width );
945         int clip_vert  = (DestRect->top  < 0) || (DestRect->bottom > (int) This->currentDesc.Height);
946         if (clip_vert || clip_horiz)
947         {
948             /* Now check if this is a special case or not... */
949             if ((((DestRect->bottom - DestRect->top ) != (xsrc.bottom - xsrc.top )) && clip_vert ) ||
950                    (((DestRect->right  - DestRect->left) != (xsrc.right  - xsrc.left)) && clip_horiz) ||
951                    (Flags & WINEDDBLT_DDFX))
952             {
953                 WARN("Out of screen rectangle in special case. Not handled right now.\n");
954                 return  WINED3D_OK;
955             }
956
957             if (clip_horiz)
958             {
959                 if (DestRect->left < 0) { xsrc.left -= DestRect->left; xdst.left = 0; }
960                 if (DestRect->right > This->currentDesc.Width)
961                 {
962                     xsrc.right -= (DestRect->right - (int) This->currentDesc.Width);
963                     xdst.right = (int) This->currentDesc.Width;
964                 }
965             }
966             if (clip_vert)
967             {
968                 if (DestRect->top < 0)
969                 {
970                     xsrc.top -= DestRect->top;
971                     xdst.top = 0;
972                 }
973                 if (DestRect->bottom > This->currentDesc.Height)
974                 {
975                     xsrc.bottom -= (DestRect->bottom - (int) This->currentDesc.Height);
976                     xdst.bottom = (int) This->currentDesc.Height;
977                 }
978             }
979             /* And check if after clipping something is still to be done... */
980             if ((xdst.bottom <= 0)   || (xdst.right <= 0)       ||
981                  (xdst.top   >= (int) This->currentDesc.Height)  ||
982                  (xdst.left  >= (int) This->currentDesc.Width)   ||
983                  (xsrc.bottom <= 0)   || (xsrc.right <= 0)       ||
984                  (xsrc.top >= (int) Src->currentDesc.Height)     ||
985                  (xsrc.left >= (int) Src->currentDesc.Width))
986             {
987                 TRACE("Nothing to be done after clipping !\n");
988                 return  WINED3D_OK;
989             }
990         }
991     }
992
993     if (Src == This)
994     {
995         IWineD3DSurface_LockRect(iface, &dlock, NULL, 0);
996         dfmt = This->resource.format;
997         slock = dlock;
998         sfmt = dfmt;
999         sEntry = getFormatDescEntry(sfmt, NULL, NULL);
1000         dEntry = sEntry;
1001     }
1002     else
1003     {
1004         dfmt = This->resource.format;
1005         dEntry = getFormatDescEntry(dfmt, NULL, NULL);
1006         if (Src)
1007         {
1008             if(This->resource.format != Src->resource.format) {
1009                 Src = surface_convert_format(Src, dfmt);
1010                 if(!Src) {
1011                     /* The conv function writes a FIXME */
1012                     WARN("Cannot convert source surface format to dest format\n");
1013                     goto release;
1014                 }
1015             }
1016             IWineD3DSurface_LockRect((IWineD3DSurface *) Src, &slock, NULL, WINED3DLOCK_READONLY);
1017             sfmt = Src->resource.format;
1018         }
1019         sEntry = getFormatDescEntry(sfmt, NULL, NULL);
1020         if (DestRect)
1021             IWineD3DSurface_LockRect(iface, &dlock, &xdst, 0);
1022         else
1023             IWineD3DSurface_LockRect(iface, &dlock, NULL, 0);
1024     }
1025
1026     if (!DDBltFx || !(DDBltFx->dwDDFX)) Flags &= ~WINEDDBLT_DDFX;
1027
1028     if (sEntry->isFourcc && dEntry->isFourcc)
1029     {
1030         if (!DestRect || Src == This)
1031         {
1032             memcpy(dlock.pBits, slock.pBits, This->resource.size);
1033             goto release;
1034         }
1035     }
1036
1037     bpp = This->bytesPerPixel;
1038     srcheight = xsrc.bottom - xsrc.top;
1039     srcwidth = xsrc.right - xsrc.left;
1040     dstheight = xdst.bottom - xdst.top;
1041     dstwidth = xdst.right - xdst.left;
1042     width = (xdst.right - xdst.left) * bpp;
1043
1044     assert(width <= dlock.Pitch);
1045
1046     if (DestRect && Src != This)
1047         dbuf = (BYTE*)dlock.pBits;
1048     else
1049         dbuf = (BYTE*)dlock.pBits+(xdst.top*dlock.Pitch)+(xdst.left*bpp);
1050
1051     if (Flags & WINEDDBLT_WAIT)
1052     {
1053         Flags &= ~WINEDDBLT_WAIT;
1054     }
1055     if (Flags & WINEDDBLT_ASYNC)
1056     {
1057         static BOOL displayed = FALSE;
1058         if (!displayed)
1059             FIXME("Can't handle WINEDDBLT_ASYNC flag right now.\n");
1060         displayed = TRUE;
1061         Flags &= ~WINEDDBLT_ASYNC;
1062     }
1063     if (Flags & WINEDDBLT_DONOTWAIT)
1064     {
1065         /* WINEDDBLT_DONOTWAIT appeared in DX7 */
1066         static BOOL displayed = FALSE;
1067         if (!displayed)
1068             FIXME("Can't handle WINEDDBLT_DONOTWAIT flag right now.\n");
1069         displayed = TRUE;
1070         Flags &= ~WINEDDBLT_DONOTWAIT;
1071     }
1072
1073     /* First, all the 'source-less' blits */
1074     if (Flags & WINEDDBLT_COLORFILL)
1075     {
1076         ret = _Blt_ColorFill(dbuf, dstwidth, dstheight, bpp,
1077                              dlock.Pitch, DDBltFx->u5.dwFillColor);
1078         Flags &= ~WINEDDBLT_COLORFILL;
1079     }
1080
1081     if (Flags & WINEDDBLT_DEPTHFILL)
1082     {
1083         FIXME("DDBLT_DEPTHFILL needs to be implemented!\n");
1084     }
1085     if (Flags & WINEDDBLT_ROP)
1086     {
1087         /* Catch some degenerate cases here */
1088         switch(DDBltFx->dwROP)
1089         {
1090             case BLACKNESS:
1091                 ret = _Blt_ColorFill(dbuf,dstwidth,dstheight,bpp,dlock.Pitch,0);
1092                 break;
1093                 case 0xAA0029: /* No-op */
1094                     break;
1095             case WHITENESS:
1096                 ret = _Blt_ColorFill(dbuf,dstwidth,dstheight,bpp,dlock.Pitch,~0);
1097                 break;
1098                 case SRCCOPY: /* well, we do that below ? */
1099                     break;
1100             default:
1101                 FIXME("Unsupported raster op: %08x  Pattern: %p\n", DDBltFx->dwROP, DDBltFx->u5.lpDDSPattern);
1102                 goto error;
1103         }
1104         Flags &= ~WINEDDBLT_ROP;
1105     }
1106     if (Flags & WINEDDBLT_DDROPS)
1107     {
1108         FIXME("\tDdraw Raster Ops: %08x  Pattern: %p\n", DDBltFx->dwDDROP, DDBltFx->u5.lpDDSPattern);
1109     }
1110     /* Now the 'with source' blits */
1111     if (Src)
1112     {
1113         LPBYTE sbase;
1114         int sx, xinc, sy, yinc;
1115
1116         if (!dstwidth || !dstheight) /* hmm... stupid program ? */
1117             goto release;
1118         sbase = (BYTE*)slock.pBits+(xsrc.top*slock.Pitch)+xsrc.left*bpp;
1119         xinc = (srcwidth << 16) / dstwidth;
1120         yinc = (srcheight << 16) / dstheight;
1121
1122         if (!Flags)
1123         {
1124             /* No effects, we can cheat here */
1125             if (dstwidth == srcwidth)
1126             {
1127                 if (dstheight == srcheight)
1128                 {
1129                     /* No stretching in either direction. This needs to be as
1130                     * fast as possible */
1131                     sbuf = sbase;
1132
1133                     /* check for overlapping surfaces */
1134                     if (Src != This || xdst.top < xsrc.top ||
1135                         xdst.right <= xsrc.left || xsrc.right <= xdst.left)
1136                     {
1137                         /* no overlap, or dst above src, so copy from top downwards */
1138                         for (y = 0; y < dstheight; y++)
1139                         {
1140                             memcpy(dbuf, sbuf, width);
1141                             sbuf += slock.Pitch;
1142                             dbuf += dlock.Pitch;
1143                         }
1144                     }
1145                     else if (xdst.top > xsrc.top)  /* copy from bottom upwards */
1146                     {
1147                         sbuf += (slock.Pitch*dstheight);
1148                         dbuf += (dlock.Pitch*dstheight);
1149                         for (y = 0; y < dstheight; y++)
1150                         {
1151                             sbuf -= slock.Pitch;
1152                             dbuf -= dlock.Pitch;
1153                             memcpy(dbuf, sbuf, width);
1154                         }
1155                     }
1156                     else /* src and dst overlapping on the same line, use memmove */
1157                     {
1158                         for (y = 0; y < dstheight; y++)
1159                         {
1160                             memmove(dbuf, sbuf, width);
1161                             sbuf += slock.Pitch;
1162                             dbuf += dlock.Pitch;
1163                         }
1164                     }
1165                 } else {
1166                     /* Stretching in Y direction only */
1167                     for (y = sy = 0; y < dstheight; y++, sy += yinc) {
1168                         sbuf = sbase + (sy >> 16) * slock.Pitch;
1169                         memcpy(dbuf, sbuf, width);
1170                         dbuf += dlock.Pitch;
1171                     }
1172                 }
1173             }
1174             else
1175             {
1176                 /* Stretching in X direction */
1177                 int last_sy = -1;
1178                 for (y = sy = 0; y < dstheight; y++, sy += yinc)
1179                 {
1180                     sbuf = sbase + (sy >> 16) * slock.Pitch;
1181
1182                     if ((sy >> 16) == (last_sy >> 16))
1183                     {
1184                         /* this sourcerow is the same as last sourcerow -
1185                         * copy already stretched row
1186                         */
1187                         memcpy(dbuf, dbuf - dlock.Pitch, width);
1188                     }
1189                     else
1190                     {
1191 #define STRETCH_ROW(type) { \
1192                         type *s = (type *) sbuf, *d = (type *) dbuf; \
1193                         for (x = sx = 0; x < dstwidth; x++, sx += xinc) \
1194                         d[x] = s[sx >> 16]; \
1195                         break; }
1196
1197                         switch(bpp)
1198                         {
1199                             case 1: STRETCH_ROW(BYTE)
1200                                     case 2: STRETCH_ROW(WORD)
1201                                             case 4: STRETCH_ROW(DWORD)
1202                             case 3:
1203                             {
1204                                 LPBYTE s,d = dbuf;
1205                                 for (x = sx = 0; x < dstwidth; x++, sx+= xinc)
1206                                 {
1207                                     DWORD pixel;
1208
1209                                     s = sbuf+3*(sx>>16);
1210                                     pixel = s[0]|(s[1]<<8)|(s[2]<<16);
1211                                     d[0] = (pixel    )&0xff;
1212                                     d[1] = (pixel>> 8)&0xff;
1213                                     d[2] = (pixel>>16)&0xff;
1214                                     d+=3;
1215                                 }
1216                                 break;
1217                             }
1218                             default:
1219                                 FIXME("Stretched blit not implemented for bpp %d!\n", bpp*8);
1220                                 ret = WINED3DERR_NOTAVAILABLE;
1221                                 goto error;
1222                         }
1223 #undef STRETCH_ROW
1224                     }
1225                     dbuf += dlock.Pitch;
1226                     last_sy = sy;
1227                 }
1228             }
1229         }
1230         else
1231         {
1232             LONG dstyinc = dlock.Pitch, dstxinc = bpp;
1233             DWORD keylow = 0xFFFFFFFF, keyhigh = 0, keymask = 0xFFFFFFFF;
1234             DWORD destkeylow = 0x0, destkeyhigh = 0xFFFFFFFF, destkeymask = 0xFFFFFFFF;
1235             if (Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYDEST | WINEDDBLT_KEYSRCOVERRIDE | WINEDDBLT_KEYDESTOVERRIDE))
1236             {
1237                 /* The color keying flags are checked for correctness in ddraw */
1238                 if (Flags & WINEDDBLT_KEYSRC)
1239                 {
1240                     keylow  = Src->SrcBltCKey.dwColorSpaceLowValue;
1241                     keyhigh = Src->SrcBltCKey.dwColorSpaceHighValue;
1242                 }
1243                 else  if (Flags & WINEDDBLT_KEYSRCOVERRIDE)
1244                 {
1245                     keylow  = DDBltFx->ddckSrcColorkey.dwColorSpaceLowValue;
1246                     keyhigh = DDBltFx->ddckSrcColorkey.dwColorSpaceHighValue;
1247                 }
1248
1249                 if (Flags & WINEDDBLT_KEYDEST)
1250                 {
1251                     /* Destination color keys are taken from the source surface ! */
1252                     destkeylow  = Src->DestBltCKey.dwColorSpaceLowValue;
1253                     destkeyhigh = Src->DestBltCKey.dwColorSpaceHighValue;
1254                 }
1255                 else if (Flags & WINEDDBLT_KEYDESTOVERRIDE)
1256                 {
1257                     destkeylow  = DDBltFx->ddckDestColorkey.dwColorSpaceLowValue;
1258                     destkeyhigh = DDBltFx->ddckDestColorkey.dwColorSpaceHighValue;
1259                 }
1260
1261                 if(bpp == 1)
1262                 {
1263                     keymask = 0xff;
1264                 }
1265                 else
1266                 {
1267                     keymask = sEntry->redMask   |
1268                             sEntry->greenMask |
1269                             sEntry->blueMask;
1270                 }
1271                 Flags &= ~(WINEDDBLT_KEYSRC | WINEDDBLT_KEYDEST | WINEDDBLT_KEYSRCOVERRIDE | WINEDDBLT_KEYDESTOVERRIDE);
1272             }
1273
1274             if (Flags & WINEDDBLT_DDFX)
1275             {
1276                 LPBYTE dTopLeft, dTopRight, dBottomLeft, dBottomRight, tmp;
1277                 LONG tmpxy;
1278                 dTopLeft     = dbuf;
1279                 dTopRight    = dbuf+((dstwidth-1)*bpp);
1280                 dBottomLeft  = dTopLeft+((dstheight-1)*dlock.Pitch);
1281                 dBottomRight = dBottomLeft+((dstwidth-1)*bpp);
1282
1283                 if (DDBltFx->dwDDFX & WINEDDBLTFX_ARITHSTRETCHY)
1284                 {
1285                     /* I don't think we need to do anything about this flag */
1286                     WARN("Flags=DDBLT_DDFX nothing done for WINEDDBLTFX_ARITHSTRETCHY\n");
1287                 }
1288                 if (DDBltFx->dwDDFX & WINEDDBLTFX_MIRRORLEFTRIGHT)
1289                 {
1290                     tmp          = dTopRight;
1291                     dTopRight    = dTopLeft;
1292                     dTopLeft     = tmp;
1293                     tmp          = dBottomRight;
1294                     dBottomRight = dBottomLeft;
1295                     dBottomLeft  = tmp;
1296                     dstxinc = dstxinc *-1;
1297                 }
1298                 if (DDBltFx->dwDDFX & WINEDDBLTFX_MIRRORUPDOWN)
1299                 {
1300                     tmp          = dTopLeft;
1301                     dTopLeft     = dBottomLeft;
1302                     dBottomLeft  = tmp;
1303                     tmp          = dTopRight;
1304                     dTopRight    = dBottomRight;
1305                     dBottomRight = tmp;
1306                     dstyinc = dstyinc *-1;
1307                 }
1308                 if (DDBltFx->dwDDFX & WINEDDBLTFX_NOTEARING)
1309                 {
1310                     /* I don't think we need to do anything about this flag */
1311                     WARN("Flags=DDBLT_DDFX nothing done for WINEDDBLTFX_NOTEARING\n");
1312                 }
1313                 if (DDBltFx->dwDDFX & WINEDDBLTFX_ROTATE180)
1314                 {
1315                     tmp          = dBottomRight;
1316                     dBottomRight = dTopLeft;
1317                     dTopLeft     = tmp;
1318                     tmp          = dBottomLeft;
1319                     dBottomLeft  = dTopRight;
1320                     dTopRight    = tmp;
1321                     dstxinc = dstxinc * -1;
1322                     dstyinc = dstyinc * -1;
1323                 }
1324                 if (DDBltFx->dwDDFX & WINEDDBLTFX_ROTATE270)
1325                 {
1326                     tmp          = dTopLeft;
1327                     dTopLeft     = dBottomLeft;
1328                     dBottomLeft  = dBottomRight;
1329                     dBottomRight = dTopRight;
1330                     dTopRight    = tmp;
1331                     tmpxy   = dstxinc;
1332                     dstxinc = dstyinc;
1333                     dstyinc = tmpxy;
1334                     dstxinc = dstxinc * -1;
1335                 }
1336                 if (DDBltFx->dwDDFX & WINEDDBLTFX_ROTATE90)
1337                 {
1338                     tmp          = dTopLeft;
1339                     dTopLeft     = dTopRight;
1340                     dTopRight    = dBottomRight;
1341                     dBottomRight = dBottomLeft;
1342                     dBottomLeft  = tmp;
1343                     tmpxy   = dstxinc;
1344                     dstxinc = dstyinc;
1345                     dstyinc = tmpxy;
1346                     dstyinc = dstyinc * -1;
1347                 }
1348                 if (DDBltFx->dwDDFX & WINEDDBLTFX_ZBUFFERBASEDEST)
1349                 {
1350                     /* I don't think we need to do anything about this flag */
1351                     WARN("Flags=WINEDDBLT_DDFX nothing done for WINEDDBLTFX_ZBUFFERBASEDEST\n");
1352                 }
1353                 dbuf = dTopLeft;
1354                 Flags &= ~(WINEDDBLT_DDFX);
1355             }
1356
1357 #define COPY_COLORKEY_FX(type) { \
1358             type *s, *d = (type *) dbuf, *dx, tmp; \
1359             for (y = sy = 0; y < dstheight; y++, sy += yinc) { \
1360             s = (type*)(sbase + (sy >> 16) * slock.Pitch); \
1361             dx = d; \
1362             for (x = sx = 0; x < dstwidth; x++, sx += xinc) { \
1363             tmp = s[sx >> 16]; \
1364             if (((tmp & keymask) < keylow || (tmp & keymask) > keyhigh) && \
1365             ((dx[0] & destkeymask) >= destkeylow && (dx[0] & destkeymask) <= destkeyhigh)) { \
1366             dx[0] = tmp; \
1367         } \
1368             dx = (type*)(((LPBYTE)dx)+dstxinc); \
1369         } \
1370             d = (type*)(((LPBYTE)d)+dstyinc); \
1371         } \
1372             break; }
1373
1374             switch (bpp) {
1375                 case 1: COPY_COLORKEY_FX(BYTE)
1376                         case 2: COPY_COLORKEY_FX(WORD)
1377                                 case 4: COPY_COLORKEY_FX(DWORD)
1378                 case 3:
1379                 {
1380                     LPBYTE s,d = dbuf, dx;
1381                     for (y = sy = 0; y < dstheight; y++, sy += yinc)
1382                     {
1383                         sbuf = sbase + (sy >> 16) * slock.Pitch;
1384                         dx = d;
1385                         for (x = sx = 0; x < dstwidth; x++, sx+= xinc)
1386                         {
1387                             DWORD pixel, dpixel = 0;
1388                             s = sbuf+3*(sx>>16);
1389                             pixel = s[0]|(s[1]<<8)|(s[2]<<16);
1390                             dpixel = dx[0]|(dx[1]<<8)|(dx[2]<<16);
1391                             if (((pixel & keymask) < keylow || (pixel & keymask) > keyhigh) &&
1392                                   ((dpixel & keymask) >= destkeylow || (dpixel & keymask) <= keyhigh))
1393                             {
1394                                 dx[0] = (pixel    )&0xff;
1395                                 dx[1] = (pixel>> 8)&0xff;
1396                                 dx[2] = (pixel>>16)&0xff;
1397                             }
1398                             dx+= dstxinc;
1399                         }
1400                         d += dstyinc;
1401                     }
1402                     break;
1403                 }
1404                 default:
1405                     FIXME("%s color-keyed blit not implemented for bpp %d!\n",
1406                           (Flags & WINEDDBLT_KEYSRC) ? "Source" : "Destination", bpp*8);
1407                     ret = WINED3DERR_NOTAVAILABLE;
1408                     goto error;
1409 #undef COPY_COLORKEY_FX
1410             }
1411         }
1412     }
1413
1414 error:
1415     if (Flags && FIXME_ON(d3d_surface))
1416     {
1417         FIXME("\tUnsupported flags: %08x\n", Flags);
1418     }
1419
1420 release:
1421     IWineD3DSurface_UnlockRect(iface);
1422     if (Src && Src != This) IWineD3DSurface_UnlockRect((IWineD3DSurface *) Src);
1423     /* Release the converted surface if any */
1424     if (Src && SrcSurface != (IWineD3DSurface *) Src) IWineD3DSurface_Release((IWineD3DSurface *) Src);
1425     return ret;
1426 }
1427
1428 /*****************************************************************************
1429  * IWineD3DSurface::BltFast, SW emulation version
1430  *
1431  * This is the software implementation of BltFast, as used by GDI surfaces
1432  * and as a fallback for OpenGL surfaces. This code is taken from the old
1433  * DirectDraw code, and was originally written by TransGaming.
1434  *
1435  * Params:
1436  *  dstx:
1437  *  dsty:
1438  *  Source: Source surface to copy from
1439  *  rsrc: Source rectangle
1440  *  trans: Some Flags
1441  *
1442  * Returns:
1443  *  WINED3D_OK on success
1444  *
1445  *****************************************************************************/
1446 HRESULT WINAPI
1447 IWineD3DBaseSurfaceImpl_BltFast(IWineD3DSurface *iface,
1448                                 DWORD dstx,
1449                                 DWORD dsty,
1450                                 IWineD3DSurface *Source,
1451                                 RECT *rsrc,
1452                                 DWORD trans)
1453 {
1454     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
1455     IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) Source;
1456
1457     int                 bpp, w, h, x, y;
1458     WINED3DLOCKED_RECT  dlock,slock;
1459     HRESULT             ret = WINED3D_OK;
1460     RECT                rsrc2;
1461     RECT                lock_src, lock_dst, lock_union;
1462     BYTE                *sbuf, *dbuf;
1463     const StaticPixelFormatDesc *sEntry, *dEntry;
1464
1465     if (TRACE_ON(d3d_surface))
1466     {
1467         TRACE("(%p)->(%d,%d,%p,%p,%08x)\n", This,dstx,dsty,Src,rsrc,trans);
1468
1469         if (rsrc)
1470         {
1471             TRACE("\tsrcrect: %dx%d-%dx%d\n",rsrc->left,rsrc->top,
1472                   rsrc->right,rsrc->bottom);
1473         }
1474         else
1475         {
1476             TRACE(" srcrect: NULL\n");
1477         }
1478     }
1479
1480     if ((This->Flags & SFLAG_LOCKED) ||
1481          ((Src != NULL) && (Src->Flags & SFLAG_LOCKED)))
1482     {
1483         WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
1484         return WINEDDERR_SURFACEBUSY;
1485     }
1486
1487     if (!rsrc)
1488     {
1489         WARN("rsrc is NULL!\n");
1490         rsrc = &rsrc2;
1491         rsrc->left = 0;
1492         rsrc->top = 0;
1493         rsrc->right = Src->currentDesc.Width;
1494         rsrc->bottom = Src->currentDesc.Height;
1495     }
1496
1497     /* Check source rect for validity. Copied from normal Blt. Fixes Baldur's Gate.*/
1498     if ((rsrc->bottom > Src->currentDesc.Height) || (rsrc->bottom < 0) ||
1499          (rsrc->top    > Src->currentDesc.Height) || (rsrc->top    < 0) ||
1500          (rsrc->left   > Src->currentDesc.Width)  || (rsrc->left   < 0) ||
1501          (rsrc->right  > Src->currentDesc.Width)  || (rsrc->right  < 0) ||
1502          (rsrc->right  < rsrc->left)              || (rsrc->bottom < rsrc->top))
1503     {
1504         WARN("Application gave us bad source rectangle for BltFast.\n");
1505         return WINEDDERR_INVALIDRECT;
1506     }
1507
1508     h = rsrc->bottom - rsrc->top;
1509     if (h > This->currentDesc.Height-dsty) h = This->currentDesc.Height-dsty;
1510     if (h > Src->currentDesc.Height-rsrc->top) h=Src->currentDesc.Height-rsrc->top;
1511     if (h <= 0) return WINEDDERR_INVALIDRECT;
1512
1513     w = rsrc->right - rsrc->left;
1514     if (w > This->currentDesc.Width-dstx) w = This->currentDesc.Width-dstx;
1515     if (w > Src->currentDesc.Width-rsrc->left) w = Src->currentDesc.Width-rsrc->left;
1516     if (w <= 0) return WINEDDERR_INVALIDRECT;
1517
1518     /* Now compute the locking rectangle... */
1519     lock_src.left = rsrc->left;
1520     lock_src.top = rsrc->top;
1521     lock_src.right = lock_src.left + w;
1522     lock_src.bottom = lock_src.top + h;
1523
1524     lock_dst.left = dstx;
1525     lock_dst.top = dsty;
1526     lock_dst.right = dstx + w;
1527     lock_dst.bottom = dsty + h;
1528
1529     bpp = This->bytesPerPixel;
1530
1531     /* We need to lock the surfaces, or we won't get refreshes when done. */
1532     if (Src == This)
1533     {
1534         int pitch;
1535
1536         UnionRect(&lock_union, &lock_src, &lock_dst);
1537
1538         /* Lock the union of the two rectangles */
1539         ret = IWineD3DSurface_LockRect(iface, &dlock, &lock_union, 0);
1540         if(ret != WINED3D_OK) goto error;
1541
1542         pitch = dlock.Pitch;
1543         slock.Pitch = dlock.Pitch;
1544
1545         /* Since slock was originally copied from this surface's description, we can just reuse it */
1546         assert(This->resource.allocatedMemory != NULL);
1547         sbuf = This->resource.allocatedMemory + lock_src.top * pitch + lock_src.left * bpp;
1548         dbuf = This->resource.allocatedMemory + lock_dst.top * pitch + lock_dst.left * bpp;
1549         sEntry = getFormatDescEntry(Src->resource.format, NULL, NULL);
1550         dEntry = sEntry;
1551     }
1552     else
1553     {
1554         ret = IWineD3DSurface_LockRect(Source, &slock, &lock_src, WINED3DLOCK_READONLY);
1555         if(ret != WINED3D_OK) goto error;
1556         ret = IWineD3DSurface_LockRect(iface, &dlock, &lock_dst, 0);
1557         if(ret != WINED3D_OK) goto error;
1558
1559         sbuf = slock.pBits;
1560         dbuf = dlock.pBits;
1561         TRACE("Dst is at %p, Src is at %p\n", dbuf, sbuf);
1562
1563         sEntry = getFormatDescEntry(Src->resource.format, NULL, NULL);
1564         dEntry = getFormatDescEntry(This->resource.format, NULL, NULL);
1565     }
1566
1567     /* Handle first the FOURCC surfaces... */
1568     if (sEntry->isFourcc && dEntry->isFourcc)
1569     {
1570         TRACE("Fourcc -> Fourcc copy\n");
1571         if (trans)
1572             FIXME("trans arg not supported when a FOURCC surface is involved\n");
1573         if (dstx || dsty)
1574             FIXME("offset for destination surface is not supported\n");
1575         if (Src->resource.format != This->resource.format)
1576         {
1577             FIXME("FOURCC->FOURCC copy only supported for the same type of surface\n");
1578             ret = WINED3DERR_WRONGTEXTUREFORMAT;
1579             goto error;
1580         }
1581         /* FIXME: Watch out that the size is correct for FOURCC surfaces */
1582         memcpy(dbuf, sbuf, This->resource.size);
1583         goto error;
1584     }
1585     if (sEntry->isFourcc && !dEntry->isFourcc)
1586     {
1587         /* TODO: Use the libtxc_dxtn.so shared library to do
1588          * software decompression
1589          */
1590         ERR("DXTC decompression not supported by now\n");
1591         goto error;
1592     }
1593
1594     if (trans & (WINEDDBLTFAST_SRCCOLORKEY | WINEDDBLTFAST_DESTCOLORKEY))
1595     {
1596         DWORD keylow, keyhigh;
1597         TRACE("Color keyed copy\n");
1598         if (trans & WINEDDBLTFAST_SRCCOLORKEY)
1599         {
1600             keylow  = Src->SrcBltCKey.dwColorSpaceLowValue;
1601             keyhigh = Src->SrcBltCKey.dwColorSpaceHighValue;
1602         }
1603         else
1604         {
1605             /* I'm not sure if this is correct */
1606             FIXME("WINEDDBLTFAST_DESTCOLORKEY not fully supported yet.\n");
1607             keylow  = This->DestBltCKey.dwColorSpaceLowValue;
1608             keyhigh = This->DestBltCKey.dwColorSpaceHighValue;
1609         }
1610
1611 #define COPYBOX_COLORKEY(type) { \
1612         type *d, *s, tmp; \
1613         s = (type *) sbuf; \
1614         d = (type *) dbuf; \
1615         for (y = 0; y < h; y++) { \
1616         for (x = 0; x < w; x++) { \
1617         tmp = s[x]; \
1618         if (tmp < keylow || tmp > keyhigh) d[x] = tmp; \
1619     } \
1620         s = (type *)((BYTE *)s + slock.Pitch); \
1621         d = (type *)((BYTE *)d + dlock.Pitch); \
1622     } \
1623         break; \
1624     }
1625
1626         switch (bpp) {
1627             case 1: COPYBOX_COLORKEY(BYTE)
1628                     case 2: COPYBOX_COLORKEY(WORD)
1629                             case 4: COPYBOX_COLORKEY(DWORD)
1630             case 3:
1631             {
1632                 BYTE *d, *s;
1633                 DWORD tmp;
1634                 s = sbuf;
1635                 d = dbuf;
1636                 for (y = 0; y < h; y++)
1637                 {
1638                     for (x = 0; x < w * 3; x += 3)
1639                     {
1640                         tmp = (DWORD)s[x] + ((DWORD)s[x + 1] << 8) + ((DWORD)s[x + 2] << 16);
1641                         if (tmp < keylow || tmp > keyhigh)
1642                         {
1643                             d[x + 0] = s[x + 0];
1644                             d[x + 1] = s[x + 1];
1645                             d[x + 2] = s[x + 2];
1646                         }
1647                     }
1648                     s += slock.Pitch;
1649                     d += dlock.Pitch;
1650                 }
1651                 break;
1652             }
1653             default:
1654                 FIXME("Source color key blitting not supported for bpp %d\n",bpp*8);
1655                 ret = WINED3DERR_NOTAVAILABLE;
1656                 goto error;
1657         }
1658 #undef COPYBOX_COLORKEY
1659         TRACE("Copy Done\n");
1660     }
1661     else
1662     {
1663         int width = w * bpp;
1664         INT sbufpitch, dbufpitch;
1665
1666         TRACE("NO color key copy\n");
1667         /* Handle overlapping surfaces */
1668         if (sbuf < dbuf)
1669         {
1670             sbuf += (h - 1) * slock.Pitch;
1671             dbuf += (h - 1) * dlock.Pitch;
1672             sbufpitch = -slock.Pitch;
1673             dbufpitch = -dlock.Pitch;
1674         }
1675         else
1676         {
1677             sbufpitch = slock.Pitch;
1678             dbufpitch = dlock.Pitch;
1679         }
1680         for (y = 0; y < h; y++)
1681         {
1682             /* This is pretty easy, a line for line memcpy */
1683             memmove(dbuf, sbuf, width);
1684             sbuf += sbufpitch;
1685             dbuf += dbufpitch;
1686         }
1687         TRACE("Copy done\n");
1688     }
1689
1690 error:
1691     if (Src == This)
1692     {
1693         IWineD3DSurface_UnlockRect(iface);
1694     }
1695     else
1696     {
1697         IWineD3DSurface_UnlockRect(iface);
1698         IWineD3DSurface_UnlockRect(Source);
1699     }
1700
1701     return ret;
1702 }
1703
1704 HRESULT WINAPI IWineD3DBaseSurfaceImpl_LockRect(IWineD3DSurface *iface, WINED3DLOCKED_RECT* pLockedRect, CONST RECT* pRect, DWORD Flags)
1705 {
1706     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1707
1708     TRACE("(%p) : rect@%p flags(%08x), output lockedRect@%p, memory@%p\n",
1709           This, pRect, Flags, pLockedRect, This->resource.allocatedMemory);
1710
1711     pLockedRect->Pitch = IWineD3DSurface_GetPitch(iface);
1712
1713     if (NULL == pRect)
1714     {
1715         pLockedRect->pBits = This->resource.allocatedMemory;
1716         This->lockedRect.left   = 0;
1717         This->lockedRect.top    = 0;
1718         This->lockedRect.right  = This->currentDesc.Width;
1719         This->lockedRect.bottom = This->currentDesc.Height;
1720
1721         TRACE("Locked Rect (%p) = l %d, t %d, r %d, b %d\n",
1722               &This->lockedRect, This->lockedRect.left, This->lockedRect.top,
1723               This->lockedRect.right, This->lockedRect.bottom);
1724     }
1725     else
1726     {
1727         TRACE("Lock Rect (%p) = l %d, t %d, r %d, b %d\n",
1728               pRect, pRect->left, pRect->top, pRect->right, pRect->bottom);
1729
1730         /* DXTn textures are based on compressed blocks of 4x4 pixels, each
1731          * 16 bytes large (8 bytes in case of DXT1). Because of that Pitch has
1732          * slightly different meaning compared to regular textures. For DXTn
1733          * textures Pitch is the size of a row of blocks, 4 high and "width"
1734          * long. The x offset is calculated differently as well, since moving 4
1735          * pixels to the right actually moves an entire 4x4 block to right, ie
1736          * 16 bytes (8 in case of DXT1). */
1737         if (This->resource.format == WINED3DFMT_DXT1)
1738         {
1739             pLockedRect->pBits = This->resource.allocatedMemory + (pLockedRect->Pitch * pRect->top / 4) + (pRect->left * 2);
1740         }
1741         else if (This->resource.format == WINED3DFMT_DXT2 || This->resource.format == WINED3DFMT_DXT3 ||
1742                     This->resource.format == WINED3DFMT_DXT4 || This->resource.format == WINED3DFMT_DXT5)
1743         {
1744             pLockedRect->pBits = This->resource.allocatedMemory + (pLockedRect->Pitch * pRect->top / 4) + (pRect->left * 4);
1745         }
1746         else
1747         {
1748             pLockedRect->pBits = This->resource.allocatedMemory +
1749                     (pLockedRect->Pitch * pRect->top) +
1750                     (pRect->left * This->bytesPerPixel);
1751         }
1752         This->lockedRect.left   = pRect->left;
1753         This->lockedRect.top    = pRect->top;
1754         This->lockedRect.right  = pRect->right;
1755         This->lockedRect.bottom = pRect->bottom;
1756     }
1757
1758     /* No dirtifying is needed for this surface implementation */
1759     TRACE("returning memory@%p, pitch(%d)\n", pLockedRect->pBits, pLockedRect->Pitch);
1760
1761     return WINED3D_OK;
1762 }
1763
1764 void WINAPI IWineD3DBaseSurfaceImpl_BindTexture(IWineD3DSurface *iface) {
1765     ERR("Should not be called on base texture\n");
1766     return;
1767 }