wined3d: Get rid of the local_constant typedef.
[wine] / dlls / d3dx9_36 / surface.c
1 /*
2  * Copyright (C) 2009-2010 Tony Wasserka
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17  *
18  */
19
20 #include "wine/debug.h"
21 #include "wine/unicode.h"
22 #include "d3dx9_36_private.h"
23
24 #include "initguid.h"
25 #include "wincodec.h"
26
27 WINE_DEFAULT_DEBUG_CHANNEL(d3dx);
28
29
30 /* Wine-specific WIC GUIDs */
31
32 DEFINE_GUID(GUID_WineContainerFormatTga, 0x0c44fda1,0xa5c5,0x4298,0x96,0x85,0x47,0x3f,0xc1,0x7c,0xd3,0x22);
33
34 /************************************************************
35  * D3DXGetImageInfoFromFileInMemory
36  *
37  * Fills a D3DXIMAGE_INFO structure with info about an image
38  *
39  * PARAMS
40  *   data     [I] pointer to the image file data
41  *   datasize [I] size of the passed data
42  *   info     [O] pointer to the destination structure
43  *
44  * RETURNS
45  *   Success: D3D_OK, if info is not NULL and data and datasize make up a valid image file or
46  *                    if info is NULL and data and datasize are not NULL
47  *   Failure: D3DXERR_INVALIDDATA, if data is no valid image file and datasize and info are not NULL
48  *            D3DERR_INVALIDCALL, if data is NULL or
49  *                                if datasize is 0
50  *
51  * NOTES
52  *   datasize may be bigger than the actual file size
53  *
54  */
55 HRESULT WINAPI D3DXGetImageInfoFromFileInMemory(LPCVOID data, UINT datasize, D3DXIMAGE_INFO *info)
56 {
57     IWICImagingFactory *factory;
58     IWICBitmapDecoder *decoder = NULL;
59     IWICStream *stream;
60     HRESULT hr;
61     HRESULT initresult;
62     static int warn_once;
63
64     if (!warn_once++)
65         FIXME("(%p, %d, %p): partially implemented\n", data, datasize, info);
66
67     /* TODO: Add support for (or at least detect) TGA, DDS, PPM and DIB */
68
69     if (!data || !datasize)
70         return D3DERR_INVALIDCALL;
71
72     if (!info)
73         return D3D_OK;
74
75     initresult = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
76
77     hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, &IID_IWICImagingFactory, (void**)&factory);
78
79     if (SUCCEEDED(hr)) {
80         IWICImagingFactory_CreateStream(factory, &stream);
81         IWICStream_InitializeFromMemory(stream, (BYTE*)data, datasize);
82         hr = IWICImagingFactory_CreateDecoderFromStream(factory, (IStream*)stream, NULL, 0, &decoder);
83         IStream_Release(stream);
84         IWICImagingFactory_Release(factory);
85     }
86
87     if (SUCCEEDED(hr)) {
88         GUID container_format;
89         UINT frame_count;
90
91         hr = IWICBitmapDecoder_GetContainerFormat(decoder, &container_format);
92         if (SUCCEEDED(hr)) {
93             if (IsEqualGUID(&container_format, &GUID_ContainerFormatBmp)) {
94                 TRACE("File type is BMP\n");
95                 info->ImageFileFormat = D3DXIFF_BMP;
96             } else if (IsEqualGUID(&container_format, &GUID_ContainerFormatPng)) {
97                 TRACE("File type is PNG\n");
98                 info->ImageFileFormat = D3DXIFF_PNG;
99             } else if(IsEqualGUID(&container_format, &GUID_ContainerFormatJpeg)) {
100                 TRACE("File type is JPG\n");
101                 info->ImageFileFormat = D3DXIFF_JPG;
102             } else if(IsEqualGUID(&container_format, &GUID_WineContainerFormatTga)) {
103                 TRACE("File type is TGA\n");
104                 info->ImageFileFormat = D3DXIFF_TGA;
105             } else {
106                 WARN("Unsupported image file format %s\n", debugstr_guid(&container_format));
107                 hr = D3DXERR_INVALIDDATA;
108             }
109         }
110
111         if (SUCCEEDED(hr))
112             hr = IWICBitmapDecoder_GetFrameCount(decoder, &frame_count);
113         if (SUCCEEDED(hr) && !frame_count)
114             hr = D3DXERR_INVALIDDATA;
115
116         if (SUCCEEDED(hr)) {
117             IWICBitmapFrameDecode *frame = NULL;
118
119             hr = IWICBitmapDecoder_GetFrame(decoder, 0, &frame);
120
121             if (SUCCEEDED(hr))
122                 hr = IWICBitmapFrameDecode_GetSize(frame, &info->Width, &info->Height);
123
124             if (SUCCEEDED(hr)) {
125                 WICPixelFormatGUID pixel_format;
126
127                 hr = IWICBitmapFrameDecode_GetPixelFormat(frame, &pixel_format);
128                 if (SUCCEEDED(hr)) {
129                     if (IsEqualGUID(&pixel_format, &GUID_WICPixelFormat1bppIndexed))
130                         info->Format = D3DFMT_L8;
131                     else if (IsEqualGUID(&pixel_format, &GUID_WICPixelFormat4bppIndexed))
132                         info->Format = D3DFMT_L8;
133                     else if (IsEqualGUID(&pixel_format, &GUID_WICPixelFormat8bppIndexed))
134                         info->Format = D3DFMT_L8;
135                     else if (IsEqualGUID(&pixel_format, &GUID_WICPixelFormat16bppBGR555))
136                         info->Format = D3DFMT_X1R5G5B5;
137                     else if (IsEqualGUID(&pixel_format, &GUID_WICPixelFormat24bppBGR))
138                         info->Format = D3DFMT_R8G8B8;
139                     else if (IsEqualGUID(&pixel_format, &GUID_WICPixelFormat32bppBGR))
140                         info->Format = D3DFMT_X8R8G8B8;
141                     else if (IsEqualGUID(&pixel_format, &GUID_WICPixelFormat32bppBGRA))
142                         info->Format = D3DFMT_A8R8G8B8;
143                     else {
144                         WARN("Unsupported pixel format %s\n", debugstr_guid(&pixel_format));
145                         hr = D3DXERR_INVALIDDATA;
146                     }
147                 }
148             }
149
150             if (frame)
151                  IWICBitmapFrameDecode_Release(frame);
152
153             info->Depth = 1;
154             info->MipLevels = 1;
155             info->ResourceType = D3DRTYPE_TEXTURE;
156         }
157     }
158
159     if (decoder)
160         IWICBitmapDecoder_Release(decoder);
161
162     if (SUCCEEDED(initresult))
163         CoUninitialize();
164
165     if (FAILED(hr)) {
166         /* Missing formats are not detected yet and will fail silently without the FIXME */
167         FIXME("Invalid or unsupported image file\n");
168         return D3DXERR_INVALIDDATA;
169     }
170
171     return D3D_OK;
172 }
173
174 /************************************************************
175  * D3DXGetImageInfoFromFile
176  *
177  * RETURNS
178  *   Success: D3D_OK, if we successfully load a valid image file or
179  *                    if we successfully load a file which is no valid image and info is NULL
180  *   Failure: D3DXERR_INVALIDDATA, if we fail to load file or
181  *                                 if file is not a valid image file and info is not NULL
182  *            D3DERR_INVALIDCALL, if file is NULL
183  *
184  */
185 HRESULT WINAPI D3DXGetImageInfoFromFileA(LPCSTR file, D3DXIMAGE_INFO *info)
186 {
187     LPWSTR widename;
188     HRESULT hr;
189     int strlength;
190
191     TRACE("(%s, %p): relay\n", debugstr_a(file), info);
192
193     if( !file ) return D3DERR_INVALIDCALL;
194
195     strlength = MultiByteToWideChar(CP_ACP, 0, file, -1, NULL, 0);
196     widename = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, strlength * sizeof(WCHAR));
197     MultiByteToWideChar(CP_ACP, 0, file, -1, widename, strlength);
198
199     hr = D3DXGetImageInfoFromFileW(widename, info);
200     HeapFree(GetProcessHeap(), 0, widename);
201
202     return hr;
203 }
204
205 HRESULT WINAPI D3DXGetImageInfoFromFileW(LPCWSTR file, D3DXIMAGE_INFO *info)
206 {
207     HRESULT hr;
208     DWORD size;
209     LPVOID buffer;
210
211     TRACE("(%s, %p): relay\n", debugstr_w(file), info);
212
213     if( !file ) return D3DERR_INVALIDCALL;
214
215     hr = map_view_of_file(file, &buffer, &size);
216     if(FAILED(hr)) return D3DXERR_INVALIDDATA;
217
218     hr = D3DXGetImageInfoFromFileInMemory(buffer, size, info);
219     UnmapViewOfFile(buffer);
220
221     return hr;
222 }
223
224 /************************************************************
225  * D3DXGetImageInfoFromResource
226  *
227  * RETURNS
228  *   Success: D3D_OK, if resource is a valid image file
229  *   Failure: D3DXERR_INVALIDDATA, if resource is no valid image file or NULL or
230  *                                 if we fail to load resource
231  *
232  */
233 HRESULT WINAPI D3DXGetImageInfoFromResourceA(HMODULE module, LPCSTR resource, D3DXIMAGE_INFO *info)
234 {
235     HRSRC resinfo;
236
237     TRACE("(%p, %s, %p)\n", module, debugstr_a(resource), info);
238
239     resinfo = FindResourceA(module, resource, (LPCSTR)RT_RCDATA);
240     if(resinfo) {
241         LPVOID buffer;
242         HRESULT hr;
243         DWORD size;
244
245         hr = load_resource_into_memory(module, resinfo, &buffer, &size);
246         if(FAILED(hr)) return D3DXERR_INVALIDDATA;
247         return D3DXGetImageInfoFromFileInMemory(buffer, size, info);
248     }
249
250     resinfo = FindResourceA(module, resource, (LPCSTR)RT_BITMAP);
251     if(resinfo) {
252         FIXME("Implement loading bitmaps from resource type RT_BITMAP\n");
253         return E_NOTIMPL;
254     }
255     return D3DXERR_INVALIDDATA;
256 }
257
258 HRESULT WINAPI D3DXGetImageInfoFromResourceW(HMODULE module, LPCWSTR resource, D3DXIMAGE_INFO *info)
259 {
260     HRSRC resinfo;
261
262     TRACE("(%p, %s, %p)\n", module, debugstr_w(resource), info);
263
264     resinfo = FindResourceW(module, resource, (LPCWSTR)RT_RCDATA);
265     if(resinfo) {
266         LPVOID buffer;
267         HRESULT hr;
268         DWORD size;
269
270         hr = load_resource_into_memory(module, resinfo, &buffer, &size);
271         if(FAILED(hr)) return D3DXERR_INVALIDDATA;
272         return D3DXGetImageInfoFromFileInMemory(buffer, size, info);
273     }
274
275     resinfo = FindResourceW(module, resource, (LPCWSTR)RT_BITMAP);
276     if(resinfo) {
277         FIXME("Implement loading bitmaps from resource type RT_BITMAP\n");
278         return E_NOTIMPL;
279     }
280     return D3DXERR_INVALIDDATA;
281 }
282
283 /************************************************************
284  * D3DXLoadSurfaceFromFileInMemory
285  *
286  * Loads data from a given buffer into a surface and fills a given
287  * D3DXIMAGE_INFO structure with info about the source data.
288  *
289  * PARAMS
290  *   pDestSurface [I] pointer to the surface
291  *   pDestPalette [I] palette to use
292  *   pDestRect    [I] to be filled area of the surface
293  *   pSrcData     [I] pointer to the source data
294  *   SrcDataSize  [I] size of the source data in bytes
295  *   pSrcRect     [I] area of the source data to load
296  *   dwFilter     [I] filter to apply on stretching
297  *   Colorkey     [I] colorkey
298  *   pSrcInfo     [O] pointer to a D3DXIMAGE_INFO structure
299  *
300  * RETURNS
301  *   Success: D3D_OK
302  *   Failure: D3DERR_INVALIDCALL, if pDestSurface or pSrcData or SrcDataSize are NULL
303  *            D3DXERR_INVALIDDATA, if pSrcData is no valid image file
304  *
305  */
306 HRESULT WINAPI D3DXLoadSurfaceFromFileInMemory(LPDIRECT3DSURFACE9 pDestSurface,
307                                                CONST PALETTEENTRY *pDestPalette,
308                                                CONST RECT *pDestRect,
309                                                LPCVOID pSrcData,
310                                                UINT SrcDataSize,
311                                                CONST RECT *pSrcRect,
312                                                DWORD dwFilter,
313                                                D3DCOLOR Colorkey,
314                                                D3DXIMAGE_INFO *pSrcInfo)
315 {
316     D3DXIMAGE_INFO imginfo;
317     HRESULT hr;
318
319     IWICImagingFactory *factory;
320     IWICBitmapDecoder *decoder;
321     IWICBitmapFrameDecode *bitmapframe;
322     IWICStream *stream;
323
324     const PixelFormatDesc *formatdesc;
325     WICRect wicrect;
326     RECT rect;
327
328     TRACE("(%p, %p, %p, %p, %d, %p, %d, %x, %p)\n", pDestSurface, pDestPalette, pDestRect, pSrcData,
329         SrcDataSize, pSrcRect, dwFilter, Colorkey, pSrcInfo);
330
331     if (!pDestSurface || !pSrcData || !SrcDataSize)
332         return D3DERR_INVALIDCALL;
333
334     hr = D3DXGetImageInfoFromFileInMemory(pSrcData, SrcDataSize, &imginfo);
335
336     if (FAILED(hr))
337         return hr;
338
339     CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
340
341     if (FAILED(CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, &IID_IWICImagingFactory, (void**)&factory)))
342         goto cleanup_err;
343
344     if (FAILED(IWICImagingFactory_CreateStream(factory, &stream)))
345     {
346         IWICImagingFactory_Release(factory);
347         goto cleanup_err;
348     }
349
350     IWICStream_InitializeFromMemory(stream, (BYTE*)pSrcData, SrcDataSize);
351
352     hr = IWICImagingFactory_CreateDecoderFromStream(factory, (IStream*)stream, NULL, 0, &decoder);
353
354     IStream_Release(stream);
355     IWICImagingFactory_Release(factory);
356
357     if (FAILED(hr))
358         goto cleanup_err;
359
360     hr = IWICBitmapDecoder_GetFrame(decoder, 0, &bitmapframe);
361
362     if (FAILED(hr))
363         goto cleanup_bmp;
364
365     if (pSrcRect)
366     {
367         wicrect.X = pSrcRect->left;
368         wicrect.Y = pSrcRect->top;
369         wicrect.Width = pSrcRect->right - pSrcRect->left;
370         wicrect.Height = pSrcRect->bottom - pSrcRect->top;
371     }
372     else
373     {
374         wicrect.X = 0;
375         wicrect.Y = 0;
376         wicrect.Width = imginfo.Width;
377         wicrect.Height = imginfo.Height;
378     }
379
380     SetRect(&rect, 0, 0, wicrect.Width, wicrect.Height);
381
382     formatdesc = get_format_info(imginfo.Format);
383
384     if (formatdesc->format == D3DFMT_UNKNOWN)
385     {
386         FIXME("Unsupported pixel format\n");
387         hr = D3DXERR_INVALIDDATA;
388     }
389     else
390     {
391         BYTE *buffer;
392         DWORD pitch;
393
394         pitch = formatdesc->bytes_per_pixel * wicrect.Width;
395         buffer = HeapAlloc(GetProcessHeap(), 0, pitch * wicrect.Height);
396
397         hr = IWICBitmapFrameDecode_CopyPixels(bitmapframe, &wicrect, pitch,
398                                               pitch * wicrect.Height, buffer);
399
400         if (SUCCEEDED(hr))
401         {
402             hr = D3DXLoadSurfaceFromMemory(pDestSurface, pDestPalette, pDestRect,
403                                            buffer, imginfo.Format, pitch,
404                                            NULL, &rect, dwFilter, Colorkey);
405         }
406
407         HeapFree(GetProcessHeap(), 0, buffer);
408     }
409
410     IWICBitmapFrameDecode_Release(bitmapframe);
411
412 cleanup_bmp:
413     IWICBitmapDecoder_Release(decoder);
414
415 cleanup_err:
416     CoUninitialize();
417
418     if (FAILED(hr))
419         return D3DXERR_INVALIDDATA;
420
421     if (pSrcInfo)
422         *pSrcInfo = imginfo;
423
424     return D3D_OK;
425 }
426
427 /************************************************************
428  * D3DXLoadSurfaceFromFile
429  */
430 HRESULT WINAPI D3DXLoadSurfaceFromFileA(LPDIRECT3DSURFACE9 pDestSurface,
431                                         CONST PALETTEENTRY *pDestPalette,
432                                         CONST RECT *pDestRect,
433                                         LPCSTR pSrcFile,
434                                         CONST RECT *pSrcRect,
435                                         DWORD dwFilter,
436                                         D3DCOLOR Colorkey,
437                                         D3DXIMAGE_INFO *pSrcInfo)
438 {
439     LPWSTR pWidename;
440     HRESULT hr;
441     int strlength;
442
443     TRACE("(%p, %p, %p, %s, %p, %u, %#x, %p): relay\n", pDestSurface, pDestPalette, pDestRect, debugstr_a(pSrcFile),
444         pSrcRect, dwFilter, Colorkey, pSrcInfo);
445
446     if( !pSrcFile || !pDestSurface ) return D3DERR_INVALIDCALL;
447
448     strlength = MultiByteToWideChar(CP_ACP, 0, pSrcFile, -1, NULL, 0);
449     pWidename = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, strlength * sizeof(WCHAR));
450     MultiByteToWideChar(CP_ACP, 0, pSrcFile, -1, pWidename, strlength);
451
452     hr = D3DXLoadSurfaceFromFileW(pDestSurface, pDestPalette, pDestRect, pWidename, pSrcRect, dwFilter, Colorkey, pSrcInfo);
453     HeapFree(GetProcessHeap(), 0, pWidename);
454
455     return hr;
456 }
457
458 HRESULT WINAPI D3DXLoadSurfaceFromFileW(LPDIRECT3DSURFACE9 pDestSurface,
459                                         CONST PALETTEENTRY *pDestPalette,
460                                         CONST RECT *pDestRect,
461                                         LPCWSTR pSrcFile,
462                                         CONST RECT *pSrcRect,
463                                         DWORD Filter,
464                                         D3DCOLOR Colorkey,
465                                         D3DXIMAGE_INFO *pSrcInfo)
466 {
467     HRESULT hr;
468     DWORD dwSize;
469     LPVOID pBuffer;
470
471     TRACE("(%p, %p, %p, %s, %p, %u, %#x, %p): relay\n", pDestSurface, pDestPalette, pDestRect, debugstr_w(pSrcFile),
472         pSrcRect, Filter, Colorkey, pSrcInfo);
473
474     if( !pSrcFile || !pDestSurface ) return D3DERR_INVALIDCALL;
475
476     hr = map_view_of_file(pSrcFile, &pBuffer, &dwSize);
477     if(FAILED(hr)) return D3DXERR_INVALIDDATA;
478
479     hr = D3DXLoadSurfaceFromFileInMemory(pDestSurface, pDestPalette, pDestRect, pBuffer, dwSize, pSrcRect, Filter, Colorkey, pSrcInfo);
480     UnmapViewOfFile(pBuffer);
481
482     return hr;
483 }
484
485 /************************************************************
486  * D3DXLoadSurfaceFromResource
487  */
488 HRESULT WINAPI D3DXLoadSurfaceFromResourceA(LPDIRECT3DSURFACE9 pDestSurface,
489                                             CONST PALETTEENTRY *pDestPalette,
490                                             CONST RECT *pDestRect,
491                                             HMODULE hSrcModule,
492                                             LPCSTR pResource,
493                                             CONST RECT *pSrcRect,
494                                             DWORD dwFilter,
495                                             D3DCOLOR Colorkey,
496                                             D3DXIMAGE_INFO *pSrcInfo)
497 {
498     HRSRC hResInfo;
499
500     TRACE("(%p, %p, %p, %p, %s, %p, %u, %#x, %p): relay\n", pDestSurface, pDestPalette, pDestRect, hSrcModule,
501         debugstr_a(pResource), pSrcRect, dwFilter, Colorkey, pSrcInfo);
502
503     if( !pDestSurface ) return D3DERR_INVALIDCALL;
504
505     hResInfo = FindResourceA(hSrcModule, pResource, (LPCSTR)RT_RCDATA);
506     if(hResInfo) {
507         LPVOID pBuffer;
508         HRESULT hr;
509         DWORD dwSize;
510
511         hr = load_resource_into_memory(hSrcModule, hResInfo, &pBuffer, &dwSize);
512         if(FAILED(hr)) return D3DXERR_INVALIDDATA;
513         return D3DXLoadSurfaceFromFileInMemory(pDestSurface, pDestPalette, pDestRect, pBuffer, dwSize, pSrcRect, dwFilter, Colorkey, pSrcInfo);
514     }
515
516     hResInfo = FindResourceA(hSrcModule, pResource, (LPCSTR)RT_BITMAP);
517     if(hResInfo) {
518         FIXME("Implement loading bitmaps from resource type RT_BITMAP\n");
519         return E_NOTIMPL;
520     }
521     return D3DXERR_INVALIDDATA;
522 }
523
524 HRESULT WINAPI D3DXLoadSurfaceFromResourceW(LPDIRECT3DSURFACE9 pDestSurface,
525                                             CONST PALETTEENTRY *pDestPalette,
526                                             CONST RECT *pDestRect,
527                                             HMODULE hSrcModule,
528                                             LPCWSTR pResource,
529                                             CONST RECT *pSrcRect,
530                                             DWORD dwFilter,
531                                             D3DCOLOR Colorkey,
532                                             D3DXIMAGE_INFO *pSrcInfo)
533 {
534     HRSRC hResInfo;
535
536     TRACE("(%p, %p, %p, %p, %s, %p, %u, %#x, %p): relay\n", pDestSurface, pDestPalette, pDestRect, hSrcModule,
537         debugstr_w(pResource), pSrcRect, dwFilter, Colorkey, pSrcInfo);
538
539     if( !pDestSurface ) return D3DERR_INVALIDCALL;
540
541     hResInfo = FindResourceW(hSrcModule, pResource, (LPCWSTR)RT_RCDATA);
542     if(hResInfo) {
543         LPVOID pBuffer;
544         HRESULT hr;
545         DWORD dwSize;
546
547         hr = load_resource_into_memory(hSrcModule, hResInfo, &pBuffer, &dwSize);
548         if(FAILED(hr)) return D3DXERR_INVALIDDATA;
549         return D3DXLoadSurfaceFromFileInMemory(pDestSurface, pDestPalette, pDestRect, pBuffer, dwSize, pSrcRect, dwFilter, Colorkey, pSrcInfo);
550     }
551
552     hResInfo = FindResourceW(hSrcModule, pResource, (LPCWSTR)RT_BITMAP);
553     if(hResInfo) {
554         FIXME("Implement loading bitmaps from resource type RT_BITMAP\n");
555         return E_NOTIMPL;
556     }
557     return D3DXERR_INVALIDDATA;
558 }
559
560
561 /************************************************************
562  * helper functions for D3DXLoadSurfaceFromMemory
563  */
564 struct argb_conversion_info
565 {
566     CONST PixelFormatDesc *srcformat;
567     CONST PixelFormatDesc *destformat;
568     DWORD srcshift[4], destshift[4];
569     DWORD srcmask[4], destmask[4];
570     BOOL process_channel[4];
571     DWORD channelmask;
572 };
573
574 static void init_argb_conversion_info(CONST PixelFormatDesc *srcformat, CONST PixelFormatDesc *destformat, struct argb_conversion_info *info)
575 {
576     UINT i;
577     ZeroMemory(info->process_channel, 4 * sizeof(BOOL));
578     info->channelmask = 0;
579
580     info->srcformat  =  srcformat;
581     info->destformat = destformat;
582
583     for(i = 0;i < 4;i++) {
584         /* srcshift is used to extract the _relevant_ components */
585         info->srcshift[i]  =  srcformat->shift[i] + max( srcformat->bits[i] - destformat->bits[i], 0);
586
587         /* destshift is used to move the components to the correct position */
588         info->destshift[i] = destformat->shift[i] + max(destformat->bits[i] -  srcformat->bits[i], 0);
589
590         info->srcmask[i]  = ((1 <<  srcformat->bits[i]) - 1) <<  srcformat->shift[i];
591         info->destmask[i] = ((1 << destformat->bits[i]) - 1) << destformat->shift[i];
592
593         /* channelmask specifies bits which aren't used in the source format but in the destination one */
594         if(destformat->bits[i]) {
595             if(srcformat->bits[i]) info->process_channel[i] = TRUE;
596             else info->channelmask |= info->destmask[i];
597         }
598     }
599 }
600
601 static DWORD dword_from_bytes(CONST BYTE *src, UINT bytes_per_pixel)
602 {
603     DWORD ret = 0;
604     static BOOL fixme_once;
605
606     if(bytes_per_pixel > sizeof(DWORD)) {
607         if(!fixme_once++) FIXME("Unsupported image: %u bytes per pixel\n", bytes_per_pixel);
608         bytes_per_pixel = sizeof(DWORD);
609     }
610
611     memcpy(&ret, src, bytes_per_pixel);
612     return ret;
613 }
614
615 static void dword_to_bytes(BYTE *dst, DWORD dword, UINT bytes_per_pixel)
616 {
617     static BOOL fixme_once;
618
619     if(bytes_per_pixel > sizeof(DWORD)) {
620         if(!fixme_once++) FIXME("Unsupported image: %u bytes per pixel\n", bytes_per_pixel);
621         ZeroMemory(dst, bytes_per_pixel);
622         bytes_per_pixel = sizeof(DWORD);
623     }
624
625     memcpy(dst, &dword, bytes_per_pixel);
626 }
627
628 /************************************************************
629  * get_relevant_argb_components
630  *
631  * Extracts the relevant components from the source color and
632  * drops the less significant bits if they aren't used by the destination format.
633  */
634 static void get_relevant_argb_components(CONST struct argb_conversion_info *info, CONST DWORD col, DWORD *out)
635 {
636     UINT i = 0;
637     for(;i < 4;i++)
638         if(info->process_channel[i])
639             out[i] = (col & info->srcmask[i]) >> info->srcshift[i];
640 }
641
642 /************************************************************
643  * make_argb_color
644  *
645  * Recombines the output of get_relevant_argb_components and converts
646  * it to the destination format.
647  */
648 static DWORD make_argb_color(CONST struct argb_conversion_info *info, CONST DWORD *in)
649 {
650     UINT i;
651     DWORD val = 0;
652
653     for(i = 0;i < 4;i++) {
654         if(info->process_channel[i]) {
655             /* necessary to make sure that e.g. an X4R4G4B4 white maps to an R8G8B8 white instead of 0xf0f0f0 */
656             signed int shift;
657             for(shift = info->destshift[i]; shift > info->destformat->shift[i]; shift -= info->srcformat->bits[i]) val |= in[i] << shift;
658             val |= (in[i] >> (info->destformat->shift[i] - shift)) << info->destformat->shift[i];
659         }
660     }
661     val |= info->channelmask;   /* new channels are set to their maximal value */
662     return val;
663 }
664
665 /************************************************************
666  * copy_simple_data
667  *
668  * Copies the source buffer to the destination buffer, performing
669  * any necessary format conversion and color keying.
670  * Pixels outsize the source rect are blacked out.
671  * Works only for ARGB formats with 1 - 4 bytes per pixel.
672  */
673 static void copy_simple_data(CONST BYTE *src, UINT srcpitch, POINT srcsize,
674                              CONST PixelFormatDesc *srcformat,
675                              BYTE *dest, UINT destpitch, POINT destsize,
676                              CONST PixelFormatDesc *destformat,
677                              D3DCOLOR colorkey)
678 {
679     struct argb_conversion_info conv_info, ck_conv_info;
680     DWORD channels[4], pixel;
681     UINT minwidth, minheight;
682     UINT x, y;
683
684     ZeroMemory(channels, sizeof(channels));
685     init_argb_conversion_info(srcformat, destformat, &conv_info);
686
687     minwidth  = (srcsize.x < destsize.x) ? srcsize.x : destsize.x;
688     minheight = (srcsize.y < destsize.y) ? srcsize.y : destsize.y;
689
690     if(colorkey) {
691         /* color keys are always represented in D3DFMT_A8R8G8B8 format */
692         const PixelFormatDesc *ckformatdesc;
693
694         ckformatdesc = get_format_info(D3DFMT_A8R8G8B8);
695         init_argb_conversion_info(srcformat, ckformatdesc, &ck_conv_info);
696     }
697
698     for(y = 0;y < minheight;y++) {
699         const BYTE *srcptr = src + y * srcpitch;
700         BYTE *destptr = dest + y * destpitch;
701         DWORD val = 0;
702
703         for(x = 0;x < minwidth;x++) {
704             /* extract source color components */
705             pixel = dword_from_bytes(srcptr, srcformat->bytes_per_pixel);
706             get_relevant_argb_components(&conv_info, pixel, channels);
707
708             /* recombine the components */
709             val = make_argb_color(&conv_info, channels);
710
711             if(colorkey) {
712                 get_relevant_argb_components(&ck_conv_info, pixel, channels);
713                 pixel = make_argb_color(&ck_conv_info, channels);
714                 if(pixel == colorkey)
715                     /* make this pixel transparent */
716                     val &= ~conv_info.destmask[0];
717             }
718
719             dword_to_bytes(destptr, val, destformat->bytes_per_pixel);
720             srcptr  +=  srcformat->bytes_per_pixel;
721             destptr += destformat->bytes_per_pixel;
722         }
723
724         if(srcsize.x < destsize.x) /* black out remaining pixels */
725             ZeroMemory(destptr, destformat->bytes_per_pixel * (destsize.x - srcsize.x));
726     }
727     if(srcsize.y < destsize.y) /* black out remaining pixels */
728         ZeroMemory(dest + srcsize.y * destpitch, destpitch * (destsize.y - srcsize.y));
729 }
730
731 /************************************************************
732  * point_filter_simple_data
733  *
734  * Copies the source buffer to the destination buffer, performing
735  * any necessary format conversion, color keying and stretching
736  * using a point filter.
737  * Works only for ARGB formats with 1 - 4 bytes per pixel.
738  */
739 static void point_filter_simple_data(CONST BYTE *src, UINT srcpitch, POINT srcsize,
740                                      CONST PixelFormatDesc *srcformat,
741                                      BYTE *dest, UINT destpitch, POINT destsize,
742                                      CONST PixelFormatDesc *destformat,
743                                      D3DCOLOR colorkey)
744 {
745     struct argb_conversion_info conv_info, ck_conv_info;
746     DWORD channels[4], pixel;
747
748     UINT x, y;
749
750     ZeroMemory(channels, sizeof(channels));
751     init_argb_conversion_info(srcformat, destformat, &conv_info);
752
753     if(colorkey) {
754         /* color keys are always represented in D3DFMT_A8R8G8B8 format */
755         const PixelFormatDesc *ckformatdesc;
756
757         ckformatdesc = get_format_info(D3DFMT_A8R8G8B8);
758         init_argb_conversion_info(srcformat, ckformatdesc, &ck_conv_info);
759     }
760
761     for(y = 0;y < destsize.y;y++) {
762         BYTE *destptr = dest + y * destpitch;
763         const BYTE *bufptr = src + srcpitch * (y * srcsize.y / destsize.y);
764
765         for(x = 0;x < destsize.x;x++) {
766             const BYTE *srcptr = bufptr + (x * srcsize.x / destsize.x) * srcformat->bytes_per_pixel;
767             DWORD val = 0;
768
769             /* extract source color components */
770             pixel = dword_from_bytes(srcptr, srcformat->bytes_per_pixel);
771             get_relevant_argb_components(&conv_info, pixel, channels);
772
773             /* recombine the components */
774             val = make_argb_color(&conv_info, channels);
775
776             if(colorkey) {
777                 get_relevant_argb_components(&ck_conv_info, pixel, channels);
778                 pixel = make_argb_color(&ck_conv_info, channels);
779                 if(pixel == colorkey)
780                     /* make this pixel transparent */
781                     val &= ~conv_info.destmask[0];
782             }
783
784             dword_to_bytes(destptr, val, destformat->bytes_per_pixel);
785             destptr += destformat->bytes_per_pixel;
786         }
787     }
788 }
789
790 /************************************************************
791  * D3DXLoadSurfaceFromMemory
792  *
793  * Loads data from a given memory chunk into a surface,
794  * applying any of the specified filters.
795  *
796  * PARAMS
797  *   pDestSurface [I] pointer to the surface
798  *   pDestPalette [I] palette to use
799  *   pDestRect    [I] to be filled area of the surface
800  *   pSrcMemory   [I] pointer to the source data
801  *   SrcFormat    [I] format of the source pixel data
802  *   SrcPitch     [I] number of bytes in a row
803  *   pSrcPalette  [I] palette used in the source image
804  *   pSrcRect     [I] area of the source data to load
805  *   dwFilter     [I] filter to apply on stretching
806  *   Colorkey     [I] colorkey
807  *
808  * RETURNS
809  *   Success: D3D_OK, if we successfully load the pixel data into our surface or
810  *                    if pSrcMemory is NULL but the other parameters are valid
811  *   Failure: D3DERR_INVALIDCALL, if pDestSurface, SrcPitch or pSrcRect are NULL or
812  *                                if SrcFormat is an invalid format (other than D3DFMT_UNKNOWN) or
813  *                                if DestRect is invalid
814  *            D3DXERR_INVALIDDATA, if we fail to lock pDestSurface
815  *            E_FAIL, if SrcFormat is D3DFMT_UNKNOWN or the dimensions of pSrcRect are invalid
816  *
817  * NOTES
818  *   pSrcRect specifies the dimensions of the source data;
819  *   negative values for pSrcRect are allowed as we're only looking at the width and height anyway.
820  *
821  */
822 HRESULT WINAPI D3DXLoadSurfaceFromMemory(LPDIRECT3DSURFACE9 pDestSurface,
823                                          CONST PALETTEENTRY *pDestPalette,
824                                          CONST RECT *pDestRect,
825                                          LPCVOID pSrcMemory,
826                                          D3DFORMAT SrcFormat,
827                                          UINT SrcPitch,
828                                          CONST PALETTEENTRY *pSrcPalette,
829                                          CONST RECT *pSrcRect,
830                                          DWORD dwFilter,
831                                          D3DCOLOR Colorkey)
832 {
833     CONST PixelFormatDesc *srcformatdesc, *destformatdesc;
834     D3DSURFACE_DESC surfdesc;
835     D3DLOCKED_RECT lockrect;
836     POINT srcsize, destsize;
837     HRESULT hr;
838
839     TRACE("(%p, %p, %p, %p, %x, %u, %p, %p %u, %#x)\n", pDestSurface, pDestPalette, pDestRect, pSrcMemory,
840         SrcFormat, SrcPitch, pSrcPalette, pSrcRect, dwFilter, Colorkey);
841
842     if( !pDestSurface || !pSrcMemory || !pSrcRect ) return D3DERR_INVALIDCALL;
843     if(SrcFormat == D3DFMT_UNKNOWN || pSrcRect->left >= pSrcRect->right || pSrcRect->top >= pSrcRect->bottom) return E_FAIL;
844
845     if(dwFilter == D3DX_DEFAULT) dwFilter = D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER;
846
847     IDirect3DSurface9_GetDesc(pDestSurface, &surfdesc);
848
849     srcformatdesc = get_format_info(SrcFormat);
850     destformatdesc = get_format_info(surfdesc.Format);
851     if( srcformatdesc->type == FORMAT_UNKNOWN ||  srcformatdesc->bytes_per_pixel > 4) return E_NOTIMPL;
852     if(destformatdesc->type == FORMAT_UNKNOWN || destformatdesc->bytes_per_pixel > 4) return E_NOTIMPL;
853
854     srcsize.x = pSrcRect->right - pSrcRect->left;
855     srcsize.y = pSrcRect->bottom - pSrcRect->top;
856     if( !pDestRect ) {
857         destsize.x = surfdesc.Width;
858         destsize.y = surfdesc.Height;
859     } else {
860         if(pDestRect->left > pDestRect->right || pDestRect->right > surfdesc.Width) return D3DERR_INVALIDCALL;
861         if(pDestRect->top > pDestRect->bottom || pDestRect->bottom > surfdesc.Height) return D3DERR_INVALIDCALL;
862         if(pDestRect->left < 0 || pDestRect->top < 0) return D3DERR_INVALIDCALL;
863         destsize.x = pDestRect->right - pDestRect->left;
864         destsize.y = pDestRect->bottom - pDestRect->top;
865         if(destsize.x == 0 || destsize.y == 0) return D3D_OK;
866     }
867
868     hr = IDirect3DSurface9_LockRect(pDestSurface, &lockrect, pDestRect, 0);
869     if(FAILED(hr)) return D3DXERR_INVALIDDATA;
870
871     if((dwFilter & 0xF) == D3DX_FILTER_NONE) {
872         copy_simple_data(pSrcMemory, SrcPitch, srcsize, srcformatdesc,
873                          lockrect.pBits, lockrect.Pitch, destsize, destformatdesc,
874                          Colorkey);
875     } else /*if((dwFilter & 0xF) == D3DX_FILTER_POINT) */ {
876         /* always apply a point filter until D3DX_FILTER_LINEAR, D3DX_FILTER_TRIANGLE and D3DX_FILTER_BOX are implemented */
877         point_filter_simple_data(pSrcMemory, SrcPitch, srcsize, srcformatdesc,
878                                  lockrect.pBits, lockrect.Pitch, destsize, destformatdesc,
879                                  Colorkey);
880     }
881
882     IDirect3DSurface9_UnlockRect(pDestSurface);
883     return D3D_OK;
884 }
885
886 /************************************************************
887  * D3DXLoadSurfaceFromSurface
888  *
889  * Copies the contents from one surface to another, performing any required
890  * format conversion, resizing or filtering.
891  *
892  * PARAMS
893  *   pDestSurface [I] pointer to the destination surface
894  *   pDestPalette [I] palette to use
895  *   pDestRect    [I] to be filled area of the surface
896  *   pSrcSurface  [I] pointer to the source surface
897  *   pSrcPalette  [I] palette used for the source surface
898  *   pSrcRect     [I] area of the source data to load
899  *   dwFilter     [I] filter to apply on resizing
900  *   Colorkey     [I] any ARGB value or 0 to disable color-keying
901  *
902  * RETURNS
903  *   Success: D3D_OK
904  *   Failure: D3DERR_INVALIDCALL, if pDestSurface or pSrcSurface are NULL
905  *            D3DXERR_INVALIDDATA, if one of the surfaces is not lockable
906  *
907  */
908 HRESULT WINAPI D3DXLoadSurfaceFromSurface(LPDIRECT3DSURFACE9 pDestSurface,
909                                           CONST PALETTEENTRY *pDestPalette,
910                                           CONST RECT *pDestRect,
911                                           LPDIRECT3DSURFACE9 pSrcSurface,
912                                           CONST PALETTEENTRY *pSrcPalette,
913                                           CONST RECT *pSrcRect,
914                                           DWORD dwFilter,
915                                           D3DCOLOR Colorkey)
916 {
917     RECT rect;
918     D3DLOCKED_RECT lock;
919     D3DSURFACE_DESC SrcDesc;
920     HRESULT hr;
921
922     TRACE("(%p, %p, %p, %p, %p, %p, %u, %#x): relay\n", pDestSurface, pDestPalette, pDestRect,
923         pSrcSurface, pSrcPalette, pSrcRect, dwFilter, Colorkey);
924
925     if( !pDestSurface || !pSrcSurface ) return D3DERR_INVALIDCALL;
926
927     IDirect3DSurface9_GetDesc(pSrcSurface, &SrcDesc);
928
929     if( !pSrcRect ) SetRect(&rect, 0, 0, SrcDesc.Width, SrcDesc.Height);
930     else rect = *pSrcRect;
931
932     hr = IDirect3DSurface9_LockRect(pSrcSurface, &lock, NULL, D3DLOCK_READONLY);
933     if(FAILED(hr)) return D3DXERR_INVALIDDATA;
934
935     hr = D3DXLoadSurfaceFromMemory(pDestSurface, pDestPalette, pDestRect,
936                                    lock.pBits, SrcDesc.Format, lock.Pitch,
937                                    pSrcPalette, &rect, dwFilter, Colorkey);
938
939     IDirect3DSurface9_UnlockRect(pSrcSurface);
940     return hr;
941 }
942
943
944 HRESULT WINAPI D3DXSaveSurfaceToFileA(LPCSTR pDestFile, D3DXIMAGE_FILEFORMAT DestFormat,
945         LPDIRECT3DSURFACE9 pSrcSurface, const PALETTEENTRY* pSrcPalette, const RECT* pSrcRect)
946 {
947     FIXME("(%p, %d, %p, %p, %p): stub\n", pDestFile, DestFormat, pSrcSurface, pSrcPalette, pSrcRect);
948     return D3DERR_INVALIDCALL;
949 }
950
951 HRESULT WINAPI D3DXSaveSurfaceToFileW(LPCWSTR pDestFile, D3DXIMAGE_FILEFORMAT DestFormat,
952         LPDIRECT3DSURFACE9 pSrcSurface, const PALETTEENTRY* pSrcPalette, const RECT* pSrcRect)
953 {
954     FIXME("(%p, %d, %p, %p, %p): stub\n", pDestFile, DestFormat, pSrcSurface, pSrcPalette, pSrcRect);
955     return D3DERR_INVALIDCALL;
956 }