d3dx9: Crop the input in ID3DXBaseEffect::SetBool().
[wine] / dlls / d3dx9_36 / surface.c
1 /*
2  * Copyright (C) 2009-2010 Tony Wasserka
3  * Copyright (C) 2012 Józef Kucia
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
18  *
19  */
20
21 #include "wine/debug.h"
22 #include "wine/unicode.h"
23 #include "d3dx9_36_private.h"
24
25 #include "initguid.h"
26 #include "wincodec.h"
27
28 WINE_DEFAULT_DEBUG_CHANNEL(d3dx);
29
30
31 /* Wine-specific WIC GUIDs */
32 DEFINE_GUID(GUID_WineContainerFormatTga, 0x0c44fda1,0xa5c5,0x4298,0x96,0x85,0x47,0x3f,0xc1,0x7c,0xd3,0x22);
33
34 static const struct
35 {
36     const GUID *wic_guid;
37     D3DFORMAT d3dformat;
38 } wic_pixel_formats[] = {
39     { &GUID_WICPixelFormat8bppIndexed, D3DFMT_L8 },
40     { &GUID_WICPixelFormat1bppIndexed, D3DFMT_L8 },
41     { &GUID_WICPixelFormat4bppIndexed, D3DFMT_L8 },
42     { &GUID_WICPixelFormat16bppBGR555, D3DFMT_X1R5G5B5 },
43     { &GUID_WICPixelFormat16bppBGR565, D3DFMT_R5G6B5 },
44     { &GUID_WICPixelFormat24bppBGR, D3DFMT_R8G8B8 },
45     { &GUID_WICPixelFormat32bppBGR, D3DFMT_X8R8G8B8 },
46     { &GUID_WICPixelFormat32bppBGRA, D3DFMT_A8R8G8B8 }
47 };
48
49 static D3DFORMAT wic_guid_to_d3dformat(const GUID *guid)
50 {
51     int i;
52
53     for (i = 0; i < sizeof(wic_pixel_formats) / sizeof(wic_pixel_formats[0]); i++)
54     {
55         if (IsEqualGUID(wic_pixel_formats[i].wic_guid, guid))
56             return wic_pixel_formats[i].d3dformat;
57     }
58
59     return D3DFMT_UNKNOWN;
60 }
61
62 static const GUID *d3dformat_to_wic_guid(D3DFORMAT format)
63 {
64     int i;
65
66     for (i = 0; i < sizeof(wic_pixel_formats) / sizeof(wic_pixel_formats[0]); i++)
67     {
68         if (wic_pixel_formats[i].d3dformat == format)
69             return wic_pixel_formats[i].wic_guid;
70     }
71
72     return NULL;
73 }
74
75 /* dds_header.flags */
76 #define DDS_CAPS 0x1
77 #define DDS_HEIGHT 0x2
78 #define DDS_WIDTH 0x2
79 #define DDS_PITCH 0x8
80 #define DDS_PIXELFORMAT 0x1000
81 #define DDS_MIPMAPCOUNT 0x20000
82 #define DDS_LINEARSIZE 0x80000
83 #define DDS_DEPTH 0x800000
84
85 /* dds_header.caps */
86 #define DDS_CAPS_COMPLEX 0x8
87 #define DDS_CAPS_TEXTURE 0x1000
88 #define DDS_CAPS_MIPMAP 0x400000
89
90 /* dds_header.caps2 */
91 #define DDS_CAPS2_CUBEMAP 0x200
92 #define DDS_CAPS2_CUBEMAP_POSITIVEX 0x400
93 #define DDS_CAPS2_CUBEMAP_NEGATIVEX 0x800
94 #define DDS_CAPS2_CUBEMAP_POSITIVEY 0x1000
95 #define DDS_CAPS2_CUBEMAP_NEGATIVEY 0x2000
96 #define DDS_CAPS2_CUBEMAP_POSITIVEZ 0x4000
97 #define DDS_CAPS2_CUBEMAP_NEGATIVEZ 0x8000
98 #define DDS_CAPS2_CUBEMAP_ALL_FACES ( DDS_CAPS2_CUBEMAP_POSITIVEX | DDS_CAPS2_CUBEMAP_NEGATIVEX \
99                                     | DDS_CAPS2_CUBEMAP_POSITIVEY | DDS_CAPS2_CUBEMAP_NEGATIVEY \
100                                     | DDS_CAPS2_CUBEMAP_POSITIVEZ | DDS_CAPS2_CUBEMAP_NEGATIVEZ )
101 #define DDS_CAPS2_VOLUME 0x200000
102
103 /* dds_pixel_format.flags */
104 #define DDS_PF_ALPHA 0x1
105 #define DDS_PF_ALPHA_ONLY 0x2
106 #define DDS_PF_FOURCC 0x4
107 #define DDS_PF_RGB 0x40
108 #define DDS_PF_YUV 0x200
109 #define DDS_PF_LUMINANCE 0x20000
110 #define DDS_PF_BUMPDUDV 0x80000
111
112 struct dds_pixel_format
113 {
114     DWORD size;
115     DWORD flags;
116     DWORD fourcc;
117     DWORD bpp;
118     DWORD rmask;
119     DWORD gmask;
120     DWORD bmask;
121     DWORD amask;
122 };
123
124 struct dds_header
125 {
126     DWORD signature;
127     DWORD size;
128     DWORD flags;
129     DWORD height;
130     DWORD width;
131     DWORD pitch_or_linear_size;
132     DWORD depth;
133     DWORD miplevels;
134     DWORD reserved[11];
135     struct dds_pixel_format pixel_format;
136     DWORD caps;
137     DWORD caps2;
138     DWORD caps3;
139     DWORD caps4;
140     DWORD reserved2;
141 };
142
143 static D3DFORMAT dds_fourcc_to_d3dformat(DWORD fourcc)
144 {
145     int i;
146     static const DWORD known_fourcc[] = {
147         MAKEFOURCC('U','Y','V','Y'),
148         MAKEFOURCC('Y','U','Y','2'),
149         MAKEFOURCC('R','G','B','G'),
150         MAKEFOURCC('G','R','G','B'),
151         MAKEFOURCC('D','X','T','1'),
152         MAKEFOURCC('D','X','T','2'),
153         MAKEFOURCC('D','X','T','3'),
154         MAKEFOURCC('D','X','T','4'),
155         MAKEFOURCC('D','X','T','5')
156     };
157
158     for (i = 0; i < sizeof(known_fourcc) / sizeof(known_fourcc[0]); i++)
159     {
160         if (known_fourcc[i] == fourcc)
161             return fourcc;
162     }
163
164     WARN("Unknown FourCC %#x\n", fourcc);
165     return D3DFMT_UNKNOWN;
166 }
167
168 static D3DFORMAT dds_rgb_to_d3dformat(const struct dds_pixel_format *pixel_format)
169 {
170     int i;
171     static const struct {
172         DWORD bpp;
173         DWORD rmask;
174         DWORD gmask;
175         DWORD bmask;
176         DWORD amask;
177         D3DFORMAT format;
178     } rgb_pixel_formats[] = {
179         { 8, 0xe0, 0x1c, 0x03, 0, D3DFMT_R3G3B2 },
180         { 16, 0xf800, 0x07e0, 0x001f, 0x0000, D3DFMT_R5G6B5 },
181         { 16, 0x7c00, 0x03e0, 0x001f, 0x8000, D3DFMT_A1R5G5B5 },
182         { 16, 0x7c00, 0x03e0, 0x001f, 0x0000, D3DFMT_X1R5G5B5 },
183         { 16, 0x0f00, 0x00f0, 0x000f, 0xf000, D3DFMT_A4R4G4B4 },
184         { 16, 0x0f00, 0x00f0, 0x000f, 0x0000, D3DFMT_X4R4G4B4 },
185         { 16, 0x00e0, 0x001c, 0x0003, 0xff00, D3DFMT_A8R3G3B2 },
186         { 24, 0xff0000, 0x00ff00, 0x0000ff, 0x000000, D3DFMT_R8G8B8 },
187         { 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000, D3DFMT_A8R8G8B8 },
188         { 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000, D3DFMT_X8R8G8B8 },
189         { 32, 0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000, D3DFMT_A2B10G10R10 },
190         { 32, 0x000003ff, 0x000ffc00, 0x3ff00000, 0xc0000000, D3DFMT_A2R10G10B10 },
191         { 32, 0x0000ffff, 0xffff0000, 0x00000000, 0x00000000, D3DFMT_G16R16 },
192     };
193
194     for (i = 0; i < sizeof(rgb_pixel_formats) / sizeof(rgb_pixel_formats[0]); i++)
195     {
196         if (rgb_pixel_formats[i].bpp == pixel_format->bpp
197             && rgb_pixel_formats[i].rmask == pixel_format->rmask
198             && rgb_pixel_formats[i].gmask == pixel_format->gmask
199             && rgb_pixel_formats[i].bmask == pixel_format->bmask)
200         {
201             if ((pixel_format->flags & DDS_PF_ALPHA) && rgb_pixel_formats[i].amask == pixel_format->amask)
202                 return rgb_pixel_formats[i].format;
203             if (rgb_pixel_formats[i].amask == 0)
204                 return rgb_pixel_formats[i].format;
205         }
206     }
207
208     WARN("Unknown RGB pixel format (%#x, %#x, %#x, %#x)\n",
209         pixel_format->rmask, pixel_format->gmask, pixel_format->bmask, pixel_format->amask);
210     return D3DFMT_UNKNOWN;
211 }
212
213 static D3DFORMAT dds_luminance_to_d3dformat(const struct dds_pixel_format *pixel_format)
214 {
215     if (pixel_format->bpp == 8)
216     {
217         if (pixel_format->rmask == 0xff)
218             return D3DFMT_L8;
219         if ((pixel_format->flags & DDS_PF_ALPHA) && pixel_format->rmask == 0x0f && pixel_format->amask == 0xf0)
220             return D3DFMT_A4L4;
221     }
222     if (pixel_format->bpp == 16)
223     {
224         if (pixel_format->rmask == 0xffff)
225             return D3DFMT_L16;
226         if ((pixel_format->flags & DDS_PF_ALPHA) && pixel_format->rmask == 0x00ff && pixel_format->amask == 0xff00)
227             return D3DFMT_A8L8;
228     }
229
230     WARN("Unknown luminance pixel format (bpp %#x, l %#x, a %#x)\n",
231         pixel_format->bpp, pixel_format->rmask, pixel_format->amask);
232     return D3DFMT_UNKNOWN;
233 }
234
235 static D3DFORMAT dds_alpha_to_d3dformat(const struct dds_pixel_format *pixel_format)
236 {
237     if (pixel_format->bpp == 8 && pixel_format->amask == 0xff)
238         return D3DFMT_A8;
239
240     WARN("Unknown Alpha pixel format (%#x, %#x)\n", pixel_format->bpp, pixel_format->rmask);
241     return D3DFMT_UNKNOWN;
242 }
243
244 static D3DFORMAT dds_bump_to_d3dformat(const struct dds_pixel_format *pixel_format)
245 {
246     if (pixel_format->bpp == 16 && pixel_format->rmask == 0x00ff && pixel_format->gmask == 0xff00)
247         return D3DFMT_V8U8;
248     if (pixel_format->bpp == 32 && pixel_format->rmask == 0x0000ffff && pixel_format->gmask == 0xffff0000)
249         return D3DFMT_V16U16;
250
251     WARN("Unknown bump pixel format (%#x, %#x, %#x, %#x, %#x)\n", pixel_format->bpp,
252         pixel_format->rmask, pixel_format->gmask, pixel_format->bmask, pixel_format->amask);
253     return D3DFMT_UNKNOWN;
254 }
255
256 static D3DFORMAT dds_pixel_format_to_d3dformat(const struct dds_pixel_format *pixel_format)
257 {
258     if (pixel_format->flags & DDS_PF_FOURCC)
259         return dds_fourcc_to_d3dformat(pixel_format->fourcc);
260     if (pixel_format->flags & DDS_PF_RGB)
261         return dds_rgb_to_d3dformat(pixel_format);
262     if (pixel_format->flags & DDS_PF_LUMINANCE)
263         return dds_luminance_to_d3dformat(pixel_format);
264     if (pixel_format->flags & DDS_PF_ALPHA_ONLY)
265         return dds_alpha_to_d3dformat(pixel_format);
266     if (pixel_format->flags & DDS_PF_BUMPDUDV)
267         return dds_bump_to_d3dformat(pixel_format);
268
269     WARN("Unknown pixel format (flags %#x, fourcc %#x, bpp %#x, r %#x, g %#x, b %#x, a %#x)\n",
270         pixel_format->flags, pixel_format->fourcc, pixel_format->bpp,
271         pixel_format->rmask, pixel_format->gmask, pixel_format->bmask, pixel_format->amask);
272     return D3DFMT_UNKNOWN;
273 }
274
275 static HRESULT calculate_dds_surface_size(const D3DXIMAGE_INFO *img_info,
276     UINT width, UINT height, UINT *pitch, UINT *size)
277 {
278     const PixelFormatDesc *format_desc = get_format_info(img_info->Format);
279     if (format_desc->format == D3DFMT_UNKNOWN)
280         return E_NOTIMPL;
281
282     if (format_desc->block_width != 1 || format_desc->block_height != 1)
283     {
284         *pitch = format_desc->block_byte_count
285             * max(1, (width + format_desc->block_width - 1) / format_desc->block_width);
286         *size = *pitch
287             * max(1, (height + format_desc->block_height - 1) / format_desc->block_height);
288     }
289     else
290     {
291         *pitch = width * format_desc->bytes_per_pixel;
292         *size = *pitch * height;
293     }
294
295     return D3D_OK;
296 }
297
298 /************************************************************
299 * get_image_info_from_dds
300 *
301 * Fills a D3DXIMAGE_INFO structure with information
302 * about a DDS file stored in the memory.
303 *
304 * PARAMS
305 *   buffer  [I] pointer to DDS data
306 *   length  [I] size of DDS data
307 *   info    [O] pointer to D3DXIMAGE_INFO structure
308 *
309 * RETURNS
310 *   Success: D3D_OK
311 *   Failure: D3DXERR_INVALIDDATA
312 *
313 */
314 static HRESULT get_image_info_from_dds(const void *buffer, UINT length, D3DXIMAGE_INFO *info)
315 {
316    UINT i;
317    UINT faces = 0;
318    UINT width, height;
319    const struct dds_header *header = buffer;
320    UINT expected_length = 0;
321
322    if (length < sizeof(*header) || !info)
323        return D3DXERR_INVALIDDATA;
324
325    if (header->pixel_format.size != sizeof(header->pixel_format))
326        return D3DXERR_INVALIDDATA;
327
328    info->Width = header->width;
329    info->Height = header->height;
330    info->Depth = 1;
331    info->MipLevels = (header->flags & DDS_MIPMAPCOUNT) ?  header->miplevels : 1;
332
333    info->Format = dds_pixel_format_to_d3dformat(&header->pixel_format);
334    if (info->Format == D3DFMT_UNKNOWN)
335        return D3DXERR_INVALIDDATA;
336
337    TRACE("Pixel format is %#x\n", info->Format);
338
339    if (header->caps2 & DDS_CAPS2_VOLUME)
340    {
341        info->Depth = header->depth;
342        info->ResourceType = D3DRTYPE_VOLUMETEXTURE;
343    }
344    else if (header->caps2 & DDS_CAPS2_CUBEMAP)
345    {
346        DWORD face;
347        for (face = DDS_CAPS2_CUBEMAP_POSITIVEX; face <= DDS_CAPS2_CUBEMAP_NEGATIVEZ; face <<= 1)
348        {
349            if (header->caps2 & face)
350                faces++;
351        }
352        info->ResourceType = D3DRTYPE_CUBETEXTURE;
353    }
354    else
355    {
356        faces = 1;
357        info->ResourceType = D3DRTYPE_TEXTURE;
358    }
359
360    /* calculate the expected length */
361    width = info->Width;
362    height = info->Height;
363    for (i = 0; i < info->MipLevels; i++)
364    {
365        UINT pitch, size = 0;
366        calculate_dds_surface_size(info, width, height, &pitch, &size);
367        expected_length += size;
368        width = max(1, width / 2);
369        height = max(1, height / 2);
370    }
371
372    expected_length *= faces;
373    expected_length += sizeof(*header);
374    if (length < expected_length)
375    {
376        WARN("File is too short %u, expected at least %u bytes\n", length, expected_length);
377        return D3DXERR_INVALIDDATA;
378    }
379
380    info->ImageFileFormat = D3DXIFF_DDS;
381
382    return D3D_OK;
383 }
384
385 static HRESULT load_surface_from_dds(IDirect3DSurface9 *dst_surface, const PALETTEENTRY *dst_palette,
386     const RECT *dst_rect, const void *src_data, const RECT *src_rect, DWORD filter, D3DCOLOR color_key,
387     const D3DXIMAGE_INFO *src_info)
388 {
389     UINT size;
390     UINT src_pitch;
391     const struct dds_header *header = src_data;
392     const BYTE *pixels = (BYTE *)(header + 1);
393
394     if (src_info->ResourceType != D3DRTYPE_TEXTURE)
395         return D3DXERR_INVALIDDATA;
396
397     if (FAILED(calculate_dds_surface_size(src_info, src_info->Width, src_info->Height, &src_pitch, &size)))
398         return E_NOTIMPL;
399
400     return D3DXLoadSurfaceFromMemory(dst_surface, dst_palette, dst_rect, pixels, src_info->Format,
401         src_pitch, NULL, src_rect, filter, color_key);
402 }
403
404 HRESULT load_texture_from_dds(IDirect3DTexture9 *texture, const void *src_data, const PALETTEENTRY *palette,
405     DWORD filter, D3DCOLOR color_key, const D3DXIMAGE_INFO *src_info)
406
407 {
408     HRESULT hr;
409     RECT src_rect;
410     UINT src_pitch;
411     UINT mip_level;
412     UINT mip_levels;
413     UINT mip_level_size;
414     UINT width, height;
415     IDirect3DSurface9 *surface;
416     const struct dds_header *header = src_data;
417     const BYTE *pixels = (BYTE *)(header + 1);
418
419     if (src_info->ResourceType != D3DRTYPE_TEXTURE)
420         return D3DXERR_INVALIDDATA;
421
422     width = src_info->Width;
423     height = src_info->Height;
424     mip_levels = min(src_info->MipLevels, IDirect3DTexture9_GetLevelCount(texture));
425     for (mip_level = 0; mip_level < mip_levels; mip_level++)
426     {
427         hr = calculate_dds_surface_size(src_info, width, height, &src_pitch, &mip_level_size);
428         if (FAILED(hr)) return hr;
429
430         SetRect(&src_rect, 0, 0, width, height);
431
432         IDirect3DTexture9_GetSurfaceLevel(texture, mip_level, &surface);
433         hr = D3DXLoadSurfaceFromMemory(surface, palette, NULL, pixels, src_info->Format, src_pitch,
434             NULL, &src_rect, filter, color_key);
435         IDirect3DSurface9_Release(surface);
436         if (FAILED(hr)) return hr;
437
438         pixels += mip_level_size;
439         width = max(1, width / 2);
440         height = max(1, height / 2);
441     }
442
443     return D3D_OK;
444 }
445
446 HRESULT load_cube_texture_from_dds(IDirect3DCubeTexture9 *cube_texture, const void *src_data,
447     const PALETTEENTRY *palette, DWORD filter, DWORD color_key, const D3DXIMAGE_INFO *src_info)
448 {
449     HRESULT hr;
450     int face;
451     int mip_level;
452     UINT size;
453     RECT src_rect;
454     UINT src_pitch;
455     UINT mip_levels;
456     UINT mip_level_size;
457     IDirect3DSurface9 *surface;
458     const struct dds_header *header = src_data;
459     const BYTE *pixels = (BYTE *)(header + 1);
460
461     if (src_info->ResourceType != D3DRTYPE_CUBETEXTURE)
462         return D3DXERR_INVALIDDATA;
463
464     if ((header->caps2 & DDS_CAPS2_CUBEMAP_ALL_FACES) != DDS_CAPS2_CUBEMAP_ALL_FACES)
465     {
466         WARN("Only full cubemaps are supported\n");
467         return D3DXERR_INVALIDDATA;
468     }
469
470     mip_levels = min(src_info->MipLevels, IDirect3DCubeTexture9_GetLevelCount(cube_texture));
471     for (face = D3DCUBEMAP_FACE_POSITIVE_X; face <= D3DCUBEMAP_FACE_NEGATIVE_Z; face++)
472     {
473         size = src_info->Width;
474         for (mip_level = 0; mip_level < src_info->MipLevels; mip_level++)
475         {
476             hr = calculate_dds_surface_size(src_info, size, size, &src_pitch, &mip_level_size);
477             if (FAILED(hr)) return hr;
478
479             /* if texture has fewer mip levels than DDS file, skip excessive mip levels */
480             if (mip_level < mip_levels)
481             {
482                 SetRect(&src_rect, 0, 0, size, size);
483
484                 IDirect3DCubeTexture9_GetCubeMapSurface(cube_texture, face, mip_level, &surface);
485                 hr = D3DXLoadSurfaceFromMemory(surface, palette, NULL, pixels, src_info->Format, src_pitch,
486                     NULL, &src_rect, filter, color_key);
487                 IDirect3DSurface9_Release(surface);
488                 if (FAILED(hr)) return hr;
489             }
490
491             pixels += mip_level_size;
492             size = max(1, size / 2);
493         }
494     }
495
496     return D3D_OK;
497 }
498
499 /************************************************************
500  * D3DXGetImageInfoFromFileInMemory
501  *
502  * Fills a D3DXIMAGE_INFO structure with info about an image
503  *
504  * PARAMS
505  *   data     [I] pointer to the image file data
506  *   datasize [I] size of the passed data
507  *   info     [O] pointer to the destination structure
508  *
509  * RETURNS
510  *   Success: D3D_OK, if info is not NULL and data and datasize make up a valid image file or
511  *                    if info is NULL and data and datasize are not NULL
512  *   Failure: D3DXERR_INVALIDDATA, if data is no valid image file and datasize and info are not NULL
513  *            D3DERR_INVALIDCALL, if data is NULL or
514  *                                if datasize is 0
515  *
516  * NOTES
517  *   datasize may be bigger than the actual file size
518  *
519  */
520 HRESULT WINAPI D3DXGetImageInfoFromFileInMemory(LPCVOID data, UINT datasize, D3DXIMAGE_INFO *info)
521 {
522     IWICImagingFactory *factory;
523     IWICBitmapDecoder *decoder = NULL;
524     IWICStream *stream;
525     HRESULT hr;
526     HRESULT initresult;
527
528     TRACE("(%p, %d, %p)\n", data, datasize, info);
529
530     if (!data || !datasize)
531         return D3DERR_INVALIDCALL;
532
533     if (!info)
534         return D3D_OK;
535
536     if ((datasize >= 4) && !strncmp(data, "DDS ", 4)) {
537         TRACE("File type is DDS\n");
538         return get_image_info_from_dds(data, datasize, info);
539     }
540
541     initresult = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
542
543     hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, &IID_IWICImagingFactory, (void**)&factory);
544
545     if (SUCCEEDED(hr)) {
546         IWICImagingFactory_CreateStream(factory, &stream);
547         IWICStream_InitializeFromMemory(stream, (BYTE*)data, datasize);
548         hr = IWICImagingFactory_CreateDecoderFromStream(factory, (IStream*)stream, NULL, 0, &decoder);
549         IStream_Release(stream);
550         IWICImagingFactory_Release(factory);
551     }
552
553     if (FAILED(hr)) {
554         if ((datasize >= 2) && (!strncmp(data, "P3", 2) || !strncmp(data, "P6", 2)))
555             FIXME("File type PPM is not supported yet\n");
556         else if ((datasize >= 2) && !strncmp(data, "BM", 2))
557             FIXME("File type DIB is not supported yet\n");
558         else if ((datasize >= 10) && !strncmp(data, "#?RADIANCE", 10))
559             FIXME("File type HDR is not supported yet\n");
560         else if ((datasize >= 2) && (!strncmp(data, "PF", 2) || !strncmp(data, "Pf", 2)))
561             FIXME("File type PFM is not supported yet\n");
562     }
563
564     if (SUCCEEDED(hr)) {
565         GUID container_format;
566         UINT frame_count;
567
568         hr = IWICBitmapDecoder_GetContainerFormat(decoder, &container_format);
569         if (SUCCEEDED(hr)) {
570             if (IsEqualGUID(&container_format, &GUID_ContainerFormatBmp)) {
571                 TRACE("File type is BMP\n");
572                 info->ImageFileFormat = D3DXIFF_BMP;
573             } else if (IsEqualGUID(&container_format, &GUID_ContainerFormatPng)) {
574                 TRACE("File type is PNG\n");
575                 info->ImageFileFormat = D3DXIFF_PNG;
576             } else if(IsEqualGUID(&container_format, &GUID_ContainerFormatJpeg)) {
577                 TRACE("File type is JPG\n");
578                 info->ImageFileFormat = D3DXIFF_JPG;
579             } else if(IsEqualGUID(&container_format, &GUID_WineContainerFormatTga)) {
580                 TRACE("File type is TGA\n");
581                 info->ImageFileFormat = D3DXIFF_TGA;
582             } else {
583                 WARN("Unsupported image file format %s\n", debugstr_guid(&container_format));
584                 hr = D3DXERR_INVALIDDATA;
585             }
586         }
587
588         if (SUCCEEDED(hr))
589             hr = IWICBitmapDecoder_GetFrameCount(decoder, &frame_count);
590         if (SUCCEEDED(hr) && !frame_count)
591             hr = D3DXERR_INVALIDDATA;
592
593         if (SUCCEEDED(hr)) {
594             IWICBitmapFrameDecode *frame = NULL;
595
596             hr = IWICBitmapDecoder_GetFrame(decoder, 0, &frame);
597
598             if (SUCCEEDED(hr))
599                 hr = IWICBitmapFrameDecode_GetSize(frame, &info->Width, &info->Height);
600
601             if (SUCCEEDED(hr)) {
602                 WICPixelFormatGUID pixel_format;
603
604                 hr = IWICBitmapFrameDecode_GetPixelFormat(frame, &pixel_format);
605                 if (SUCCEEDED(hr)) {
606                     info->Format = wic_guid_to_d3dformat(&pixel_format);
607                     if (info->Format == D3DFMT_UNKNOWN) {
608                         WARN("Unsupported pixel format %s\n", debugstr_guid(&pixel_format));
609                         hr = D3DXERR_INVALIDDATA;
610                     }
611                 }
612             }
613
614             if (frame)
615                  IWICBitmapFrameDecode_Release(frame);
616
617             info->Depth = 1;
618             info->MipLevels = 1;
619             info->ResourceType = D3DRTYPE_TEXTURE;
620         }
621     }
622
623     if (decoder)
624         IWICBitmapDecoder_Release(decoder);
625
626     if (SUCCEEDED(initresult))
627         CoUninitialize();
628
629     if (FAILED(hr)) {
630         TRACE("Invalid or unsupported image file\n");
631         return D3DXERR_INVALIDDATA;
632     }
633
634     return D3D_OK;
635 }
636
637 /************************************************************
638  * D3DXGetImageInfoFromFile
639  *
640  * RETURNS
641  *   Success: D3D_OK, if we successfully load a valid image file or
642  *                    if we successfully load a file which is no valid image and info is NULL
643  *   Failure: D3DXERR_INVALIDDATA, if we fail to load file or
644  *                                 if file is not a valid image file and info is not NULL
645  *            D3DERR_INVALIDCALL, if file is NULL
646  *
647  */
648 HRESULT WINAPI D3DXGetImageInfoFromFileA(LPCSTR file, D3DXIMAGE_INFO *info)
649 {
650     LPWSTR widename;
651     HRESULT hr;
652     int strlength;
653
654     TRACE("(%s, %p): relay\n", debugstr_a(file), info);
655
656     if( !file ) return D3DERR_INVALIDCALL;
657
658     strlength = MultiByteToWideChar(CP_ACP, 0, file, -1, NULL, 0);
659     widename = HeapAlloc(GetProcessHeap(), 0, strlength * sizeof(*widename));
660     MultiByteToWideChar(CP_ACP, 0, file, -1, widename, strlength);
661
662     hr = D3DXGetImageInfoFromFileW(widename, info);
663     HeapFree(GetProcessHeap(), 0, widename);
664
665     return hr;
666 }
667
668 HRESULT WINAPI D3DXGetImageInfoFromFileW(LPCWSTR file, D3DXIMAGE_INFO *info)
669 {
670     HRESULT hr;
671     DWORD size;
672     LPVOID buffer;
673
674     TRACE("(%s, %p): relay\n", debugstr_w(file), info);
675
676     if( !file ) return D3DERR_INVALIDCALL;
677
678     hr = map_view_of_file(file, &buffer, &size);
679     if(FAILED(hr)) return D3DXERR_INVALIDDATA;
680
681     hr = D3DXGetImageInfoFromFileInMemory(buffer, size, info);
682     UnmapViewOfFile(buffer);
683
684     return hr;
685 }
686
687 /************************************************************
688  * D3DXGetImageInfoFromResource
689  *
690  * RETURNS
691  *   Success: D3D_OK, if resource is a valid image file
692  *   Failure: D3DXERR_INVALIDDATA, if resource is no valid image file or NULL or
693  *                                 if we fail to load resource
694  *
695  */
696 HRESULT WINAPI D3DXGetImageInfoFromResourceA(HMODULE module, LPCSTR resource, D3DXIMAGE_INFO *info)
697 {
698     HRSRC resinfo;
699
700     TRACE("(%p, %s, %p)\n", module, debugstr_a(resource), info);
701
702     resinfo = FindResourceA(module, resource, (LPCSTR)RT_RCDATA);
703     if(resinfo) {
704         LPVOID buffer;
705         HRESULT hr;
706         DWORD size;
707
708         hr = load_resource_into_memory(module, resinfo, &buffer, &size);
709         if(FAILED(hr)) return D3DXERR_INVALIDDATA;
710         return D3DXGetImageInfoFromFileInMemory(buffer, size, info);
711     }
712
713     resinfo = FindResourceA(module, resource, (LPCSTR)RT_BITMAP);
714     if(resinfo) {
715         FIXME("Implement loading bitmaps from resource type RT_BITMAP\n");
716         return E_NOTIMPL;
717     }
718     return D3DXERR_INVALIDDATA;
719 }
720
721 HRESULT WINAPI D3DXGetImageInfoFromResourceW(HMODULE module, LPCWSTR resource, D3DXIMAGE_INFO *info)
722 {
723     HRSRC resinfo;
724
725     TRACE("(%p, %s, %p)\n", module, debugstr_w(resource), info);
726
727     resinfo = FindResourceW(module, resource, (LPCWSTR)RT_RCDATA);
728     if(resinfo) {
729         LPVOID buffer;
730         HRESULT hr;
731         DWORD size;
732
733         hr = load_resource_into_memory(module, resinfo, &buffer, &size);
734         if(FAILED(hr)) return D3DXERR_INVALIDDATA;
735         return D3DXGetImageInfoFromFileInMemory(buffer, size, info);
736     }
737
738     resinfo = FindResourceW(module, resource, (LPCWSTR)RT_BITMAP);
739     if(resinfo) {
740         FIXME("Implement loading bitmaps from resource type RT_BITMAP\n");
741         return E_NOTIMPL;
742     }
743     return D3DXERR_INVALIDDATA;
744 }
745
746 /************************************************************
747  * D3DXLoadSurfaceFromFileInMemory
748  *
749  * Loads data from a given buffer into a surface and fills a given
750  * D3DXIMAGE_INFO structure with info about the source data.
751  *
752  * PARAMS
753  *   pDestSurface [I] pointer to the surface
754  *   pDestPalette [I] palette to use
755  *   pDestRect    [I] to be filled area of the surface
756  *   pSrcData     [I] pointer to the source data
757  *   SrcDataSize  [I] size of the source data in bytes
758  *   pSrcRect     [I] area of the source data to load
759  *   dwFilter     [I] filter to apply on stretching
760  *   Colorkey     [I] colorkey
761  *   pSrcInfo     [O] pointer to a D3DXIMAGE_INFO structure
762  *
763  * RETURNS
764  *   Success: D3D_OK
765  *   Failure: D3DERR_INVALIDCALL, if pDestSurface or pSrcData or SrcDataSize are NULL
766  *            D3DXERR_INVALIDDATA, if pSrcData is no valid image file
767  *
768  */
769 HRESULT WINAPI D3DXLoadSurfaceFromFileInMemory(LPDIRECT3DSURFACE9 pDestSurface,
770                                                CONST PALETTEENTRY *pDestPalette,
771                                                CONST RECT *pDestRect,
772                                                LPCVOID pSrcData,
773                                                UINT SrcDataSize,
774                                                CONST RECT *pSrcRect,
775                                                DWORD dwFilter,
776                                                D3DCOLOR Colorkey,
777                                                D3DXIMAGE_INFO *pSrcInfo)
778 {
779     D3DXIMAGE_INFO imginfo;
780     HRESULT hr;
781
782     IWICImagingFactory *factory;
783     IWICBitmapDecoder *decoder;
784     IWICBitmapFrameDecode *bitmapframe;
785     IWICStream *stream;
786
787     const PixelFormatDesc *formatdesc;
788     WICRect wicrect;
789     RECT rect;
790
791     TRACE("(%p, %p, %p, %p, %d, %p, %d, %x, %p)\n", pDestSurface, pDestPalette, pDestRect, pSrcData,
792         SrcDataSize, pSrcRect, dwFilter, Colorkey, pSrcInfo);
793
794     if (!pDestSurface || !pSrcData || !SrcDataSize)
795         return D3DERR_INVALIDCALL;
796
797     hr = D3DXGetImageInfoFromFileInMemory(pSrcData, SrcDataSize, &imginfo);
798
799     if (FAILED(hr))
800         return hr;
801
802     if (pSrcRect)
803     {
804         wicrect.X = pSrcRect->left;
805         wicrect.Y = pSrcRect->top;
806         wicrect.Width = pSrcRect->right - pSrcRect->left;
807         wicrect.Height = pSrcRect->bottom - pSrcRect->top;
808     }
809     else
810     {
811         wicrect.X = 0;
812         wicrect.Y = 0;
813         wicrect.Width = imginfo.Width;
814         wicrect.Height = imginfo.Height;
815     }
816
817     SetRect(&rect, 0, 0, wicrect.Width, wicrect.Height);
818
819     if (imginfo.ImageFileFormat == D3DXIFF_DDS)
820     {
821         hr = load_surface_from_dds(pDestSurface, pDestPalette, pDestRect, pSrcData, &rect,
822             dwFilter, Colorkey, &imginfo);
823         if (SUCCEEDED(hr) && pSrcInfo)
824             *pSrcInfo = imginfo;
825         return hr;
826     }
827
828     CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
829
830     if (FAILED(CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, &IID_IWICImagingFactory, (void**)&factory)))
831         goto cleanup_err;
832
833     if (FAILED(IWICImagingFactory_CreateStream(factory, &stream)))
834     {
835         IWICImagingFactory_Release(factory);
836         goto cleanup_err;
837     }
838
839     IWICStream_InitializeFromMemory(stream, (BYTE*)pSrcData, SrcDataSize);
840
841     hr = IWICImagingFactory_CreateDecoderFromStream(factory, (IStream*)stream, NULL, 0, &decoder);
842
843     IStream_Release(stream);
844     IWICImagingFactory_Release(factory);
845
846     if (FAILED(hr))
847         goto cleanup_err;
848
849     hr = IWICBitmapDecoder_GetFrame(decoder, 0, &bitmapframe);
850
851     if (FAILED(hr))
852         goto cleanup_bmp;
853
854     formatdesc = get_format_info(imginfo.Format);
855
856     if (formatdesc->format == D3DFMT_UNKNOWN)
857     {
858         FIXME("Unsupported pixel format\n");
859         hr = D3DXERR_INVALIDDATA;
860     }
861     else
862     {
863         BYTE *buffer;
864         DWORD pitch;
865
866         pitch = formatdesc->bytes_per_pixel * wicrect.Width;
867         buffer = HeapAlloc(GetProcessHeap(), 0, pitch * wicrect.Height);
868
869         hr = IWICBitmapFrameDecode_CopyPixels(bitmapframe, &wicrect, pitch,
870                                               pitch * wicrect.Height, buffer);
871
872         if (SUCCEEDED(hr))
873         {
874             hr = D3DXLoadSurfaceFromMemory(pDestSurface, pDestPalette, pDestRect,
875                                            buffer, imginfo.Format, pitch,
876                                            NULL, &rect, dwFilter, Colorkey);
877         }
878
879         HeapFree(GetProcessHeap(), 0, buffer);
880     }
881
882     IWICBitmapFrameDecode_Release(bitmapframe);
883
884 cleanup_bmp:
885     IWICBitmapDecoder_Release(decoder);
886
887 cleanup_err:
888     CoUninitialize();
889
890     if (FAILED(hr))
891         return D3DXERR_INVALIDDATA;
892
893     if (pSrcInfo)
894         *pSrcInfo = imginfo;
895
896     return D3D_OK;
897 }
898
899 /************************************************************
900  * D3DXLoadSurfaceFromFile
901  */
902 HRESULT WINAPI D3DXLoadSurfaceFromFileA(LPDIRECT3DSURFACE9 pDestSurface,
903                                         CONST PALETTEENTRY *pDestPalette,
904                                         CONST RECT *pDestRect,
905                                         LPCSTR pSrcFile,
906                                         CONST RECT *pSrcRect,
907                                         DWORD dwFilter,
908                                         D3DCOLOR Colorkey,
909                                         D3DXIMAGE_INFO *pSrcInfo)
910 {
911     LPWSTR pWidename;
912     HRESULT hr;
913     int strlength;
914
915     TRACE("(%p, %p, %p, %s, %p, %u, %#x, %p): relay\n", pDestSurface, pDestPalette, pDestRect, debugstr_a(pSrcFile),
916         pSrcRect, dwFilter, Colorkey, pSrcInfo);
917
918     if( !pSrcFile || !pDestSurface ) return D3DERR_INVALIDCALL;
919
920     strlength = MultiByteToWideChar(CP_ACP, 0, pSrcFile, -1, NULL, 0);
921     pWidename = HeapAlloc(GetProcessHeap(), 0, strlength * sizeof(*pWidename));
922     MultiByteToWideChar(CP_ACP, 0, pSrcFile, -1, pWidename, strlength);
923
924     hr = D3DXLoadSurfaceFromFileW(pDestSurface, pDestPalette, pDestRect, pWidename, pSrcRect, dwFilter, Colorkey, pSrcInfo);
925     HeapFree(GetProcessHeap(), 0, pWidename);
926
927     return hr;
928 }
929
930 HRESULT WINAPI D3DXLoadSurfaceFromFileW(LPDIRECT3DSURFACE9 pDestSurface,
931                                         CONST PALETTEENTRY *pDestPalette,
932                                         CONST RECT *pDestRect,
933                                         LPCWSTR pSrcFile,
934                                         CONST RECT *pSrcRect,
935                                         DWORD Filter,
936                                         D3DCOLOR Colorkey,
937                                         D3DXIMAGE_INFO *pSrcInfo)
938 {
939     HRESULT hr;
940     DWORD dwSize;
941     LPVOID pBuffer;
942
943     TRACE("(%p, %p, %p, %s, %p, %u, %#x, %p): relay\n", pDestSurface, pDestPalette, pDestRect, debugstr_w(pSrcFile),
944         pSrcRect, Filter, Colorkey, pSrcInfo);
945
946     if( !pSrcFile || !pDestSurface ) return D3DERR_INVALIDCALL;
947
948     hr = map_view_of_file(pSrcFile, &pBuffer, &dwSize);
949     if(FAILED(hr)) return D3DXERR_INVALIDDATA;
950
951     hr = D3DXLoadSurfaceFromFileInMemory(pDestSurface, pDestPalette, pDestRect, pBuffer, dwSize, pSrcRect, Filter, Colorkey, pSrcInfo);
952     UnmapViewOfFile(pBuffer);
953
954     return hr;
955 }
956
957 /************************************************************
958  * D3DXLoadSurfaceFromResource
959  */
960 HRESULT WINAPI D3DXLoadSurfaceFromResourceA(LPDIRECT3DSURFACE9 pDestSurface,
961                                             CONST PALETTEENTRY *pDestPalette,
962                                             CONST RECT *pDestRect,
963                                             HMODULE hSrcModule,
964                                             LPCSTR pResource,
965                                             CONST RECT *pSrcRect,
966                                             DWORD dwFilter,
967                                             D3DCOLOR Colorkey,
968                                             D3DXIMAGE_INFO *pSrcInfo)
969 {
970     HRSRC hResInfo;
971
972     TRACE("(%p, %p, %p, %p, %s, %p, %u, %#x, %p): relay\n", pDestSurface, pDestPalette, pDestRect, hSrcModule,
973         debugstr_a(pResource), pSrcRect, dwFilter, Colorkey, pSrcInfo);
974
975     if( !pDestSurface ) return D3DERR_INVALIDCALL;
976
977     hResInfo = FindResourceA(hSrcModule, pResource, (LPCSTR)RT_RCDATA);
978     if(hResInfo) {
979         LPVOID pBuffer;
980         HRESULT hr;
981         DWORD dwSize;
982
983         hr = load_resource_into_memory(hSrcModule, hResInfo, &pBuffer, &dwSize);
984         if(FAILED(hr)) return D3DXERR_INVALIDDATA;
985         return D3DXLoadSurfaceFromFileInMemory(pDestSurface, pDestPalette, pDestRect, pBuffer, dwSize, pSrcRect, dwFilter, Colorkey, pSrcInfo);
986     }
987
988     hResInfo = FindResourceA(hSrcModule, pResource, (LPCSTR)RT_BITMAP);
989     if(hResInfo) {
990         FIXME("Implement loading bitmaps from resource type RT_BITMAP\n");
991         return E_NOTIMPL;
992     }
993     return D3DXERR_INVALIDDATA;
994 }
995
996 HRESULT WINAPI D3DXLoadSurfaceFromResourceW(LPDIRECT3DSURFACE9 pDestSurface,
997                                             CONST PALETTEENTRY *pDestPalette,
998                                             CONST RECT *pDestRect,
999                                             HMODULE hSrcModule,
1000                                             LPCWSTR pResource,
1001                                             CONST RECT *pSrcRect,
1002                                             DWORD dwFilter,
1003                                             D3DCOLOR Colorkey,
1004                                             D3DXIMAGE_INFO *pSrcInfo)
1005 {
1006     HRSRC hResInfo;
1007
1008     TRACE("(%p, %p, %p, %p, %s, %p, %u, %#x, %p): relay\n", pDestSurface, pDestPalette, pDestRect, hSrcModule,
1009         debugstr_w(pResource), pSrcRect, dwFilter, Colorkey, pSrcInfo);
1010
1011     if( !pDestSurface ) return D3DERR_INVALIDCALL;
1012
1013     hResInfo = FindResourceW(hSrcModule, pResource, (LPCWSTR)RT_RCDATA);
1014     if(hResInfo) {
1015         LPVOID pBuffer;
1016         HRESULT hr;
1017         DWORD dwSize;
1018
1019         hr = load_resource_into_memory(hSrcModule, hResInfo, &pBuffer, &dwSize);
1020         if(FAILED(hr)) return D3DXERR_INVALIDDATA;
1021         return D3DXLoadSurfaceFromFileInMemory(pDestSurface, pDestPalette, pDestRect, pBuffer, dwSize, pSrcRect, dwFilter, Colorkey, pSrcInfo);
1022     }
1023
1024     hResInfo = FindResourceW(hSrcModule, pResource, (LPCWSTR)RT_BITMAP);
1025     if(hResInfo) {
1026         FIXME("Implement loading bitmaps from resource type RT_BITMAP\n");
1027         return E_NOTIMPL;
1028     }
1029     return D3DXERR_INVALIDDATA;
1030 }
1031
1032
1033 /************************************************************
1034  * helper functions for D3DXLoadSurfaceFromMemory
1035  */
1036 struct argb_conversion_info
1037 {
1038     CONST PixelFormatDesc *srcformat;
1039     CONST PixelFormatDesc *destformat;
1040     DWORD srcshift[4], destshift[4];
1041     DWORD srcmask[4], destmask[4];
1042     BOOL process_channel[4];
1043     DWORD channelmask;
1044 };
1045
1046 static void init_argb_conversion_info(CONST PixelFormatDesc *srcformat, CONST PixelFormatDesc *destformat, struct argb_conversion_info *info)
1047 {
1048     UINT i;
1049     ZeroMemory(info->process_channel, 4 * sizeof(BOOL));
1050     info->channelmask = 0;
1051
1052     info->srcformat  =  srcformat;
1053     info->destformat = destformat;
1054
1055     for(i = 0;i < 4;i++) {
1056         /* srcshift is used to extract the _relevant_ components */
1057         info->srcshift[i]  =  srcformat->shift[i] + max( srcformat->bits[i] - destformat->bits[i], 0);
1058
1059         /* destshift is used to move the components to the correct position */
1060         info->destshift[i] = destformat->shift[i] + max(destformat->bits[i] -  srcformat->bits[i], 0);
1061
1062         info->srcmask[i]  = ((1 <<  srcformat->bits[i]) - 1) <<  srcformat->shift[i];
1063         info->destmask[i] = ((1 << destformat->bits[i]) - 1) << destformat->shift[i];
1064
1065         /* channelmask specifies bits which aren't used in the source format but in the destination one */
1066         if(destformat->bits[i]) {
1067             if(srcformat->bits[i]) info->process_channel[i] = TRUE;
1068             else info->channelmask |= info->destmask[i];
1069         }
1070     }
1071 }
1072
1073 static DWORD dword_from_bytes(CONST BYTE *src, UINT bytes_per_pixel)
1074 {
1075     DWORD ret = 0;
1076     static BOOL fixme_once;
1077
1078     if(bytes_per_pixel > sizeof(DWORD)) {
1079         if(!fixme_once++) FIXME("Unsupported image: %u bytes per pixel\n", bytes_per_pixel);
1080         bytes_per_pixel = sizeof(DWORD);
1081     }
1082
1083     memcpy(&ret, src, bytes_per_pixel);
1084     return ret;
1085 }
1086
1087 static void dword_to_bytes(BYTE *dst, DWORD dword, UINT bytes_per_pixel)
1088 {
1089     static BOOL fixme_once;
1090
1091     if(bytes_per_pixel > sizeof(DWORD)) {
1092         if(!fixme_once++) FIXME("Unsupported image: %u bytes per pixel\n", bytes_per_pixel);
1093         ZeroMemory(dst, bytes_per_pixel);
1094         bytes_per_pixel = sizeof(DWORD);
1095     }
1096
1097     memcpy(dst, &dword, bytes_per_pixel);
1098 }
1099
1100 /************************************************************
1101  * get_relevant_argb_components
1102  *
1103  * Extracts the relevant components from the source color and
1104  * drops the less significant bits if they aren't used by the destination format.
1105  */
1106 static void get_relevant_argb_components(CONST struct argb_conversion_info *info, CONST DWORD col, DWORD *out)
1107 {
1108     UINT i = 0;
1109     for(;i < 4;i++)
1110         if(info->process_channel[i])
1111             out[i] = (col & info->srcmask[i]) >> info->srcshift[i];
1112 }
1113
1114 /************************************************************
1115  * make_argb_color
1116  *
1117  * Recombines the output of get_relevant_argb_components and converts
1118  * it to the destination format.
1119  */
1120 static DWORD make_argb_color(CONST struct argb_conversion_info *info, CONST DWORD *in)
1121 {
1122     UINT i;
1123     DWORD val = 0;
1124
1125     for(i = 0;i < 4;i++) {
1126         if(info->process_channel[i]) {
1127             /* necessary to make sure that e.g. an X4R4G4B4 white maps to an R8G8B8 white instead of 0xf0f0f0 */
1128             signed int shift;
1129             for(shift = info->destshift[i]; shift > info->destformat->shift[i]; shift -= info->srcformat->bits[i]) val |= in[i] << shift;
1130             val |= (in[i] >> (info->destformat->shift[i] - shift)) << info->destformat->shift[i];
1131         }
1132     }
1133     val |= info->channelmask;   /* new channels are set to their maximal value */
1134     return val;
1135 }
1136
1137 static void format_to_vec4(const PixelFormatDesc *format, const DWORD *src, struct vec4 *dst)
1138 {
1139     DWORD mask;
1140
1141     if (format->bits[1])
1142     {
1143         mask = (1 << format->bits[1]) - 1;
1144         dst->x = (float)((*src >> format->shift[1]) & mask) / mask;
1145     }
1146     else
1147         dst->x = 1.0f;
1148
1149     if (format->bits[2])
1150     {
1151         mask = (1 << format->bits[2]) - 1;
1152         dst->y = (float)((*src >> format->shift[2]) & mask) / mask;
1153     }
1154     else
1155         dst->y = 1.0f;
1156
1157     if (format->bits[3])
1158     {
1159         mask = (1 << format->bits[3]) - 1;
1160         dst->z = (float)((*src >> format->shift[3]) & mask) / mask;
1161     }
1162     else
1163         dst->z = 1.0f;
1164
1165     if (format->bits[0])
1166     {
1167         mask = (1 << format->bits[0]) - 1;
1168         dst->w = (float)((*src >> format->shift[0]) & mask) / mask;
1169     }
1170     else
1171         dst->w = 1.0f;
1172 }
1173
1174 static void format_from_vec4(const PixelFormatDesc *format, const struct vec4 *src, DWORD *dst)
1175 {
1176     *dst = 0;
1177
1178     if (format->bits[1])
1179         *dst |= (DWORD)(src->x * ((1 << format->bits[1]) - 1) + 0.5f) << format->shift[1];
1180     if (format->bits[2])
1181         *dst |= (DWORD)(src->y * ((1 << format->bits[2]) - 1) + 0.5f) << format->shift[2];
1182     if (format->bits[3])
1183         *dst |= (DWORD)(src->z * ((1 << format->bits[3]) - 1) + 0.5f) << format->shift[3];
1184     if (format->bits[0])
1185         *dst |= (DWORD)(src->w * ((1 << format->bits[0]) - 1) + 0.5f) << format->shift[0];
1186 }
1187
1188 /************************************************************
1189  * copy_simple_data
1190  *
1191  * Copies the source buffer to the destination buffer, performing
1192  * any necessary format conversion and color keying.
1193  * Pixels outsize the source rect are blacked out.
1194  * Works only for ARGB formats with 1 - 4 bytes per pixel.
1195  */
1196 static void copy_simple_data(const BYTE *src, UINT srcpitch, SIZE src_size, const PixelFormatDesc *srcformat,
1197         BYTE *dest, UINT destpitch, SIZE dst_size, const PixelFormatDesc *destformat, D3DCOLOR colorkey)
1198 {
1199     struct argb_conversion_info conv_info, ck_conv_info;
1200     const PixelFormatDesc *ck_format = NULL;
1201     DWORD channels[4], pixel;
1202     UINT minwidth, minheight;
1203     UINT x, y;
1204
1205     ZeroMemory(channels, sizeof(channels));
1206     init_argb_conversion_info(srcformat, destformat, &conv_info);
1207
1208     minwidth = (src_size.cx < dst_size.cx) ? src_size.cx : dst_size.cx;
1209     minheight = (src_size.cy < dst_size.cy) ? src_size.cy : dst_size.cy;
1210
1211     if (colorkey)
1212     {
1213         /* Color keys are always represented in D3DFMT_A8R8G8B8 format. */
1214         ck_format = get_format_info(D3DFMT_A8R8G8B8);
1215         init_argb_conversion_info(srcformat, ck_format, &ck_conv_info);
1216     }
1217
1218     for(y = 0;y < minheight;y++) {
1219         const BYTE *srcptr = src + y * srcpitch;
1220         BYTE *destptr = dest + y * destpitch;
1221         DWORD val;
1222
1223         for(x = 0;x < minwidth;x++) {
1224             /* extract source color components */
1225             pixel = dword_from_bytes(srcptr, srcformat->bytes_per_pixel);
1226
1227             if (!srcformat->to_rgba && !destformat->from_rgba)
1228             {
1229                 get_relevant_argb_components(&conv_info, pixel, channels);
1230                 val = make_argb_color(&conv_info, channels);
1231
1232                 if (colorkey)
1233                 {
1234                     get_relevant_argb_components(&ck_conv_info, pixel, channels);
1235                     pixel = make_argb_color(&ck_conv_info, channels);
1236                     if (pixel == colorkey)
1237                         val &= ~conv_info.destmask[0];
1238                 }
1239             }
1240             else
1241             {
1242                 struct vec4 color, tmp;
1243
1244                 format_to_vec4(srcformat, &pixel, &color);
1245                 if (srcformat->to_rgba)
1246                     srcformat->to_rgba(&color, &tmp);
1247                 else
1248                     tmp = color;
1249
1250                 if (ck_format)
1251                 {
1252                     format_from_vec4(ck_format, &tmp, &pixel);
1253                     if (pixel == colorkey)
1254                         tmp.w = 0.0f;
1255                 }
1256
1257                 if (destformat->from_rgba)
1258                     destformat->from_rgba(&tmp, &color);
1259                 else
1260                     color = tmp;
1261
1262                 format_from_vec4(destformat, &color, &val);
1263             }
1264
1265             dword_to_bytes(destptr, val, destformat->bytes_per_pixel);
1266             srcptr  +=  srcformat->bytes_per_pixel;
1267             destptr += destformat->bytes_per_pixel;
1268         }
1269
1270         if (src_size.cx < dst_size.cx) /* black out remaining pixels */
1271             memset(destptr, 0, destformat->bytes_per_pixel * (dst_size.cx - src_size.cx));
1272     }
1273     if (src_size.cy < dst_size.cy) /* black out remaining pixels */
1274         memset(dest + src_size.cy * destpitch, 0, destpitch * (dst_size.cy - src_size.cy));
1275 }
1276
1277 /************************************************************
1278  * point_filter_simple_data
1279  *
1280  * Copies the source buffer to the destination buffer, performing
1281  * any necessary format conversion, color keying and stretching
1282  * using a point filter.
1283  * Works only for ARGB formats with 1 - 4 bytes per pixel.
1284  */
1285 static void point_filter_simple_data(const BYTE *src, UINT srcpitch, SIZE src_size, const PixelFormatDesc *srcformat,
1286         BYTE *dest, UINT destpitch, SIZE dst_size, const PixelFormatDesc *destformat, D3DCOLOR colorkey)
1287 {
1288     struct argb_conversion_info conv_info, ck_conv_info;
1289     const PixelFormatDesc *ck_format = NULL;
1290     DWORD channels[4], pixel;
1291
1292     UINT x, y;
1293
1294     ZeroMemory(channels, sizeof(channels));
1295     init_argb_conversion_info(srcformat, destformat, &conv_info);
1296
1297     if (colorkey)
1298     {
1299         /* Color keys are always represented in D3DFMT_A8R8G8B8 format. */
1300         ck_format = get_format_info(D3DFMT_A8R8G8B8);
1301         init_argb_conversion_info(srcformat, ck_format, &ck_conv_info);
1302     }
1303
1304     for (y = 0; y < dst_size.cy; ++y)
1305     {
1306         BYTE *destptr = dest + y * destpitch;
1307         const BYTE *bufptr = src + srcpitch * (y * src_size.cy / dst_size.cy);
1308
1309         for (x = 0; x < dst_size.cx; ++x)
1310         {
1311             const BYTE *srcptr = bufptr + (x * src_size.cx / dst_size.cx) * srcformat->bytes_per_pixel;
1312             DWORD val;
1313
1314             /* extract source color components */
1315             pixel = dword_from_bytes(srcptr, srcformat->bytes_per_pixel);
1316
1317             if (!srcformat->to_rgba && !destformat->from_rgba)
1318             {
1319                 get_relevant_argb_components(&conv_info, pixel, channels);
1320                 val = make_argb_color(&conv_info, channels);
1321
1322                 if (colorkey)
1323                 {
1324                     get_relevant_argb_components(&ck_conv_info, pixel, channels);
1325                     pixel = make_argb_color(&ck_conv_info, channels);
1326                     if (pixel == colorkey)
1327                         val &= ~conv_info.destmask[0];
1328                 }
1329             }
1330             else
1331             {
1332                 struct vec4 color, tmp;
1333
1334                 format_to_vec4(srcformat, &pixel, &color);
1335                 if (srcformat->to_rgba)
1336                     srcformat->to_rgba(&color, &tmp);
1337                 else
1338                     tmp = color;
1339
1340                 if (ck_format)
1341                 {
1342                     format_from_vec4(ck_format, &tmp, &pixel);
1343                     if (pixel == colorkey)
1344                         tmp.w = 0.0f;
1345                 }
1346
1347                 if (destformat->from_rgba)
1348                     destformat->from_rgba(&tmp, &color);
1349                 else
1350                     color = tmp;
1351
1352                 format_from_vec4(destformat, &color, &val);
1353             }
1354
1355             dword_to_bytes(destptr, val, destformat->bytes_per_pixel);
1356             destptr += destformat->bytes_per_pixel;
1357         }
1358     }
1359 }
1360
1361 /************************************************************
1362  * D3DXLoadSurfaceFromMemory
1363  *
1364  * Loads data from a given memory chunk into a surface,
1365  * applying any of the specified filters.
1366  *
1367  * PARAMS
1368  *   pDestSurface [I] pointer to the surface
1369  *   pDestPalette [I] palette to use
1370  *   pDestRect    [I] to be filled area of the surface
1371  *   pSrcMemory   [I] pointer to the source data
1372  *   SrcFormat    [I] format of the source pixel data
1373  *   SrcPitch     [I] number of bytes in a row
1374  *   pSrcPalette  [I] palette used in the source image
1375  *   pSrcRect     [I] area of the source data to load
1376  *   dwFilter     [I] filter to apply on stretching
1377  *   Colorkey     [I] colorkey
1378  *
1379  * RETURNS
1380  *   Success: D3D_OK, if we successfully load the pixel data into our surface or
1381  *                    if pSrcMemory is NULL but the other parameters are valid
1382  *   Failure: D3DERR_INVALIDCALL, if pDestSurface, SrcPitch or pSrcRect are NULL or
1383  *                                if SrcFormat is an invalid format (other than D3DFMT_UNKNOWN) or
1384  *                                if DestRect is invalid
1385  *            D3DXERR_INVALIDDATA, if we fail to lock pDestSurface
1386  *            E_FAIL, if SrcFormat is D3DFMT_UNKNOWN or the dimensions of pSrcRect are invalid
1387  *
1388  * NOTES
1389  *   pSrcRect specifies the dimensions of the source data;
1390  *   negative values for pSrcRect are allowed as we're only looking at the width and height anyway.
1391  *
1392  */
1393 HRESULT WINAPI D3DXLoadSurfaceFromMemory(IDirect3DSurface9 *dst_surface,
1394         const PALETTEENTRY *dst_palette, const RECT *dst_rect, const void *src_memory,
1395         D3DFORMAT src_format, UINT src_pitch, const PALETTEENTRY *src_palette, const RECT *src_rect,
1396         DWORD filter, D3DCOLOR color_key)
1397 {
1398     CONST PixelFormatDesc *srcformatdesc, *destformatdesc;
1399     D3DSURFACE_DESC surfdesc;
1400     D3DLOCKED_RECT lockrect;
1401     SIZE src_size, dst_size;
1402     HRESULT hr;
1403
1404     TRACE("(%p, %p, %s, %p, %#x, %u, %p, %s %#x, 0x%08x)\n",
1405             dst_surface, dst_palette, wine_dbgstr_rect(dst_rect), src_memory, src_format,
1406             src_pitch, src_palette, wine_dbgstr_rect(src_rect), filter, color_key);
1407
1408     if (!dst_surface || !src_memory || !src_rect)
1409         return D3DERR_INVALIDCALL;
1410     if (src_format == D3DFMT_UNKNOWN
1411             || src_rect->left >= src_rect->right
1412             || src_rect->top >= src_rect->bottom)
1413         return E_FAIL;
1414
1415     if (filter == D3DX_DEFAULT)
1416         filter = D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER;
1417
1418     IDirect3DSurface9_GetDesc(dst_surface, &surfdesc);
1419
1420     src_size.cx = src_rect->right - src_rect->left;
1421     src_size.cy = src_rect->bottom - src_rect->top;
1422     if (!dst_rect)
1423     {
1424         dst_size.cx = surfdesc.Width;
1425         dst_size.cy = surfdesc.Height;
1426     }
1427     else
1428     {
1429         if (dst_rect->left > dst_rect->right || dst_rect->right > surfdesc.Width)
1430             return D3DERR_INVALIDCALL;
1431         if (dst_rect->top > dst_rect->bottom || dst_rect->bottom > surfdesc.Height)
1432             return D3DERR_INVALIDCALL;
1433         if (dst_rect->left < 0 || dst_rect->top < 0)
1434             return D3DERR_INVALIDCALL;
1435         dst_size.cx = dst_rect->right - dst_rect->left;
1436         dst_size.cy = dst_rect->bottom - dst_rect->top;
1437         if (!dst_size.cx || !dst_size.cy)
1438             return D3D_OK;
1439     }
1440
1441     srcformatdesc = get_format_info(src_format);
1442     if (srcformatdesc->type == FORMAT_UNKNOWN)
1443         return E_NOTIMPL;
1444
1445     destformatdesc = get_format_info(surfdesc.Format);
1446     if (destformatdesc->type == FORMAT_UNKNOWN)
1447         return E_NOTIMPL;
1448
1449     if (src_format == surfdesc.Format
1450             && dst_size.cx == src_size.cx
1451             && dst_size.cy == src_size.cy) /* Simple copy. */
1452     {
1453         UINT row_block_count = ((src_size.cx + srcformatdesc->block_width - 1) / srcformatdesc->block_width);
1454         UINT row_count = (src_size.cy + srcformatdesc->block_height - 1) / srcformatdesc->block_height;
1455         const BYTE *src_addr;
1456         BYTE *dst_addr;
1457         UINT row;
1458
1459         if (src_rect->left & (srcformatdesc->block_width - 1)
1460                 || src_rect->top & (srcformatdesc->block_height - 1)
1461                 || (src_rect->right & (srcformatdesc->block_width - 1)
1462                     && src_size.cx != surfdesc.Width)
1463                 || (src_rect->bottom & (srcformatdesc->block_height - 1)
1464                     && src_size.cy != surfdesc.Height))
1465         {
1466             WARN("Source rect %s is misaligned.\n", wine_dbgstr_rect(src_rect));
1467             return D3DXERR_INVALIDDATA;
1468         }
1469
1470         if (FAILED(hr = IDirect3DSurface9_LockRect(dst_surface, &lockrect, dst_rect, 0)))
1471             return D3DXERR_INVALIDDATA;
1472
1473         src_addr = src_memory;
1474         src_addr += (src_rect->top / srcformatdesc->block_height) * src_pitch;
1475         src_addr += (src_rect->left / srcformatdesc->block_width) * srcformatdesc->block_byte_count;
1476         dst_addr = lockrect.pBits;
1477
1478         for (row = 0; row < row_count; ++row)
1479         {
1480             memcpy(dst_addr, src_addr, row_block_count * srcformatdesc->block_byte_count);
1481             src_addr += src_pitch;
1482             dst_addr += lockrect.Pitch;
1483         }
1484
1485         IDirect3DSurface9_UnlockRect(dst_surface);
1486     }
1487     else /* Stretching or format conversion. */
1488     {
1489         if (srcformatdesc->bytes_per_pixel > 4)
1490             return E_NOTIMPL;
1491         if (destformatdesc->bytes_per_pixel > 4)
1492             return E_NOTIMPL;
1493         if (srcformatdesc->block_height != 1 || srcformatdesc->block_width != 1)
1494             return E_NOTIMPL;
1495         if (destformatdesc->block_height != 1 || destformatdesc->block_width != 1)
1496             return E_NOTIMPL;
1497
1498         if (FAILED(hr = IDirect3DSurface9_LockRect(dst_surface, &lockrect, dst_rect, 0)))
1499             return D3DXERR_INVALIDDATA;
1500
1501         if ((filter & 0xf) == D3DX_FILTER_NONE)
1502         {
1503             copy_simple_data(src_memory, src_pitch, src_size, srcformatdesc,
1504                     lockrect.pBits, lockrect.Pitch, dst_size, destformatdesc, color_key);
1505         }
1506         else /* if ((filter & 0xf) == D3DX_FILTER_POINT) */
1507         {
1508             if ((filter & 0xf) != D3DX_FILTER_POINT)
1509                 FIXME("Unhandled filter %#x.\n", filter);
1510
1511             /* Always apply a point filter until D3DX_FILTER_LINEAR,
1512              * D3DX_FILTER_TRIANGLE and D3DX_FILTER_BOX are implemented. */
1513             point_filter_simple_data(src_memory, src_pitch, src_size, srcformatdesc,
1514                     lockrect.pBits, lockrect.Pitch, dst_size, destformatdesc, color_key);
1515         }
1516
1517         IDirect3DSurface9_UnlockRect(dst_surface);
1518     }
1519
1520     return D3D_OK;
1521 }
1522
1523 /************************************************************
1524  * D3DXLoadSurfaceFromSurface
1525  *
1526  * Copies the contents from one surface to another, performing any required
1527  * format conversion, resizing or filtering.
1528  *
1529  * PARAMS
1530  *   pDestSurface [I] pointer to the destination surface
1531  *   pDestPalette [I] palette to use
1532  *   pDestRect    [I] to be filled area of the surface
1533  *   pSrcSurface  [I] pointer to the source surface
1534  *   pSrcPalette  [I] palette used for the source surface
1535  *   pSrcRect     [I] area of the source data to load
1536  *   dwFilter     [I] filter to apply on resizing
1537  *   Colorkey     [I] any ARGB value or 0 to disable color-keying
1538  *
1539  * RETURNS
1540  *   Success: D3D_OK
1541  *   Failure: D3DERR_INVALIDCALL, if pDestSurface or pSrcSurface are NULL
1542  *            D3DXERR_INVALIDDATA, if one of the surfaces is not lockable
1543  *
1544  */
1545 HRESULT WINAPI D3DXLoadSurfaceFromSurface(LPDIRECT3DSURFACE9 pDestSurface,
1546                                           CONST PALETTEENTRY *pDestPalette,
1547                                           CONST RECT *pDestRect,
1548                                           LPDIRECT3DSURFACE9 pSrcSurface,
1549                                           CONST PALETTEENTRY *pSrcPalette,
1550                                           CONST RECT *pSrcRect,
1551                                           DWORD dwFilter,
1552                                           D3DCOLOR Colorkey)
1553 {
1554     RECT rect;
1555     D3DLOCKED_RECT lock;
1556     D3DSURFACE_DESC SrcDesc;
1557     HRESULT hr;
1558
1559     TRACE("(%p, %p, %p, %p, %p, %p, %u, %#x): relay\n", pDestSurface, pDestPalette, pDestRect,
1560         pSrcSurface, pSrcPalette, pSrcRect, dwFilter, Colorkey);
1561
1562     if( !pDestSurface || !pSrcSurface ) return D3DERR_INVALIDCALL;
1563
1564     IDirect3DSurface9_GetDesc(pSrcSurface, &SrcDesc);
1565
1566     if( !pSrcRect ) SetRect(&rect, 0, 0, SrcDesc.Width, SrcDesc.Height);
1567     else rect = *pSrcRect;
1568
1569     hr = IDirect3DSurface9_LockRect(pSrcSurface, &lock, NULL, D3DLOCK_READONLY);
1570     if(FAILED(hr)) return D3DXERR_INVALIDDATA;
1571
1572     hr = D3DXLoadSurfaceFromMemory(pDestSurface, pDestPalette, pDestRect,
1573                                    lock.pBits, SrcDesc.Format, lock.Pitch,
1574                                    pSrcPalette, &rect, dwFilter, Colorkey);
1575
1576     IDirect3DSurface9_UnlockRect(pSrcSurface);
1577     return hr;
1578 }
1579
1580
1581 HRESULT WINAPI D3DXSaveSurfaceToFileA(const char *dst_filename, D3DXIMAGE_FILEFORMAT file_format,
1582         IDirect3DSurface9 *src_surface, const PALETTEENTRY *src_palette, const RECT *src_rect)
1583 {
1584     int len;
1585     WCHAR *filename;
1586     HRESULT hr;
1587
1588     TRACE("(%s, %#x, %p, %p, %s): relay\n",
1589             wine_dbgstr_a(dst_filename), file_format, src_surface, src_palette, wine_dbgstr_rect(src_rect));
1590
1591     if (!dst_filename) return D3DERR_INVALIDCALL;
1592
1593     len = MultiByteToWideChar(CP_ACP, 0, dst_filename, -1, NULL, 0);
1594     filename = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1595     if (!filename) return E_OUTOFMEMORY;
1596     MultiByteToWideChar(CP_ACP, 0, dst_filename, -1, filename, len);
1597
1598     hr = D3DXSaveSurfaceToFileW(filename, file_format, src_surface, src_palette, src_rect);
1599
1600     HeapFree(GetProcessHeap(), 0, filename);
1601     return hr;
1602 }
1603
1604 HRESULT WINAPI D3DXSaveSurfaceToFileW(const WCHAR *dst_filename, D3DXIMAGE_FILEFORMAT file_format,
1605         IDirect3DSurface9 *src_surface, const PALETTEENTRY *src_palette, const RECT *src_rect)
1606 {
1607     IWICImagingFactory *factory;
1608     IWICBitmapEncoder *encoder = NULL;
1609     IWICBitmapFrameEncode *frame = NULL;
1610     IPropertyBag2 *encoder_options = NULL;
1611     IWICStream *stream = NULL;
1612     HRESULT hr;
1613     HRESULT initresult;
1614     const CLSID *encoder_clsid;
1615     const GUID *pixel_format_guid;
1616     WICPixelFormatGUID wic_pixel_format;
1617     D3DFORMAT d3d_pixel_format;
1618     D3DSURFACE_DESC src_surface_desc;
1619     D3DLOCKED_RECT locked_rect;
1620     int width, height;
1621
1622     TRACE("(%s, %#x, %p, %p, %s)\n",
1623         wine_dbgstr_w(dst_filename), file_format, src_surface, src_palette, wine_dbgstr_rect(src_rect));
1624
1625     if (!dst_filename || !src_surface) return D3DERR_INVALIDCALL;
1626
1627     if (src_palette)
1628     {
1629         FIXME("Saving surfaces with palettized pixel formats not implemented yet\n");
1630         return D3DERR_INVALIDCALL;
1631     }
1632
1633     switch (file_format)
1634     {
1635         case D3DXIFF_BMP:
1636             encoder_clsid = &CLSID_WICBmpEncoder;
1637             break;
1638         case D3DXIFF_PNG:
1639             encoder_clsid = &CLSID_WICPngEncoder;
1640             break;
1641         case D3DXIFF_JPG:
1642             encoder_clsid = &CLSID_WICJpegEncoder;
1643             break;
1644         case D3DXIFF_DDS:
1645         case D3DXIFF_DIB:
1646         case D3DXIFF_HDR:
1647         case D3DXIFF_PFM:
1648         case D3DXIFF_TGA:
1649         case D3DXIFF_PPM:
1650             FIXME("File format %#x is not supported yet\n", file_format);
1651             return E_NOTIMPL;
1652         default:
1653             return D3DERR_INVALIDCALL;
1654     }
1655
1656     IDirect3DSurface9_GetDesc(src_surface, &src_surface_desc);
1657     if (src_rect)
1658     {
1659         if (src_rect->left == src_rect->right || src_rect->top == src_rect->bottom)
1660             return D3D_OK;
1661         if (src_rect->left < 0 || src_rect->top < 0)
1662             return D3DERR_INVALIDCALL;
1663         if (src_rect->left > src_rect->right || src_rect->top > src_rect->bottom)
1664             return D3DERR_INVALIDCALL;
1665         if (src_rect->right > src_surface_desc.Width || src_rect->bottom > src_surface_desc.Height)
1666             return D3DERR_INVALIDCALL;
1667
1668         width = src_rect->right - src_rect->left;
1669         height = src_rect->bottom - src_rect->top;
1670     }
1671     else
1672     {
1673         width = src_surface_desc.Width;
1674         height = src_surface_desc.Height;
1675     }
1676
1677     initresult = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
1678
1679     hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER,
1680         &IID_IWICImagingFactory, (void **)&factory);
1681     if (FAILED(hr)) goto cleanup_err;
1682
1683     hr = IWICImagingFactory_CreateStream(factory, &stream);
1684     IWICImagingFactory_Release(factory);
1685     if (FAILED(hr)) goto cleanup_err;
1686
1687     hr = IWICStream_InitializeFromFilename(stream, dst_filename, GENERIC_WRITE);
1688     if (FAILED(hr)) goto cleanup_err;
1689
1690     hr = CoCreateInstance(encoder_clsid, NULL, CLSCTX_INPROC_SERVER,
1691         &IID_IWICBitmapEncoder, (void **)&encoder);
1692     if (FAILED(hr)) goto cleanup_err;
1693
1694     hr = IWICBitmapEncoder_Initialize(encoder, (IStream *)stream, WICBitmapEncoderNoCache);
1695     IStream_Release((IStream *)stream);
1696     stream = NULL;
1697     if (FAILED(hr)) goto cleanup_err;
1698
1699     hr = IWICBitmapEncoder_CreateNewFrame(encoder, &frame, &encoder_options);
1700     if (FAILED(hr)) goto cleanup_err;
1701
1702     hr = IWICBitmapFrameEncode_Initialize(frame, encoder_options);
1703     if (FAILED(hr)) goto cleanup_err;
1704
1705     hr = IWICBitmapFrameEncode_SetSize(frame, width, height);
1706     if (FAILED(hr)) goto cleanup_err;
1707
1708     pixel_format_guid = d3dformat_to_wic_guid(src_surface_desc.Format);
1709     if (!pixel_format_guid)
1710     {
1711         FIXME("Pixel format %#x is not supported yet\n", src_surface_desc.Format);
1712         hr = E_NOTIMPL;
1713         goto cleanup;
1714     }
1715
1716     memcpy(&wic_pixel_format, pixel_format_guid, sizeof(GUID));
1717     hr = IWICBitmapFrameEncode_SetPixelFormat(frame, &wic_pixel_format);
1718     d3d_pixel_format = wic_guid_to_d3dformat(&wic_pixel_format);
1719     if (SUCCEEDED(hr) && d3d_pixel_format != D3DFMT_UNKNOWN)
1720     {
1721         TRACE("Using pixel format %s %#x\n", debugstr_guid(&wic_pixel_format), d3d_pixel_format);
1722
1723         if (src_surface_desc.Format == d3d_pixel_format) /* Simple copy */
1724         {
1725             hr = IDirect3DSurface9_LockRect(src_surface, &locked_rect, src_rect, D3DLOCK_READONLY);
1726             if (SUCCEEDED(hr))
1727             {
1728                 IWICBitmapFrameEncode_WritePixels(frame, height,
1729                     locked_rect.Pitch, height * locked_rect.Pitch, locked_rect.pBits);
1730                 IDirect3DSurface9_UnlockRect(src_surface);
1731             }
1732         }
1733         else /* Pixel format conversion */
1734         {
1735             const PixelFormatDesc *src_format_desc, *dst_format_desc;
1736             SIZE size;
1737             DWORD dst_pitch;
1738             void *dst_data;
1739
1740             src_format_desc = get_format_info(src_surface_desc.Format);
1741             dst_format_desc = get_format_info(d3d_pixel_format);
1742             if (src_format_desc->format == D3DFMT_UNKNOWN || dst_format_desc->format == D3DFMT_UNKNOWN)
1743             {
1744                 FIXME("Unsupported pixel format conversion %#x -> %#x\n",
1745                     src_surface_desc.Format, d3d_pixel_format);
1746                 hr = E_NOTIMPL;
1747                 goto cleanup;
1748             }
1749
1750             if (src_format_desc->bytes_per_pixel > 4
1751                 || dst_format_desc->bytes_per_pixel > 4
1752                 || src_format_desc->block_height != 1 || src_format_desc->block_width != 1
1753                 || dst_format_desc->block_height != 1 || dst_format_desc->block_width != 1)
1754             {
1755                 hr = E_NOTIMPL;
1756                 goto cleanup;
1757             }
1758
1759             size.cx = width;
1760             size.cy = height;
1761             dst_pitch = width * dst_format_desc->bytes_per_pixel;
1762             dst_data = HeapAlloc(GetProcessHeap(), 0, dst_pitch * height);
1763             if (!dst_data)
1764             {
1765                 hr = E_OUTOFMEMORY;
1766                 goto cleanup;
1767             }
1768
1769             hr = IDirect3DSurface9_LockRect(src_surface, &locked_rect, src_rect, D3DLOCK_READONLY);
1770             if (SUCCEEDED(hr))
1771             {
1772                 copy_simple_data(locked_rect.pBits, locked_rect.Pitch, size, src_format_desc,
1773                     dst_data, dst_pitch, size, dst_format_desc, 0);
1774                 IDirect3DSurface9_UnlockRect(src_surface);
1775             }
1776
1777             IWICBitmapFrameEncode_WritePixels(frame, height, dst_pitch, dst_pitch * height, dst_data);
1778             HeapFree(GetProcessHeap(), 0, dst_data);
1779         }
1780
1781         hr = IWICBitmapFrameEncode_Commit(frame);
1782         if (SUCCEEDED(hr)) hr = IWICBitmapEncoder_Commit(encoder);
1783     }
1784     else WARN("Unsupported pixel format %#x\n", src_surface_desc.Format);
1785
1786 cleanup_err:
1787     if (FAILED(hr)) hr = D3DERR_INVALIDCALL;
1788
1789 cleanup:
1790     if (stream) IStream_Release((IStream *)stream);
1791
1792     if (frame) IWICBitmapFrameEncode_Release(frame);
1793     if (encoder_options) IPropertyBag2_Release(encoder_options);
1794
1795     if (encoder) IWICBitmapEncoder_Release(encoder);
1796
1797     if (SUCCEEDED(initresult)) CoUninitialize();
1798
1799     return hr;
1800 }