d3dx9/tests: Add tests for compressed pixel formats support in D3DXLoadSurface functions.
[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    if (header->caps2 & DDS_CAPS2_VOLUME)
338    {
339        info->Depth = header->depth;
340        info->ResourceType = D3DRTYPE_VOLUMETEXTURE;
341    }
342    else if (header->caps2 & DDS_CAPS2_CUBEMAP)
343    {
344        DWORD face;
345        for (face = DDS_CAPS2_CUBEMAP_POSITIVEX; face <= DDS_CAPS2_CUBEMAP_NEGATIVEZ; face <<= 1)
346        {
347            if (header->caps2 & face)
348                faces++;
349        }
350        info->ResourceType = D3DRTYPE_CUBETEXTURE;
351    }
352    else
353    {
354        faces = 1;
355        info->ResourceType = D3DRTYPE_TEXTURE;
356    }
357
358    /* calculate the expected length */
359    width = info->Width;
360    height = info->Height;
361    for (i = 0; i < info->MipLevels; i++)
362    {
363        UINT pitch, size = 0;
364        calculate_dds_surface_size(info, width, height, &pitch, &size);
365        expected_length += size;
366        width = max(1, width / 2);
367        height = max(1, width / 2);
368    }
369
370    expected_length *= faces;
371    expected_length += sizeof(*header);
372    if (length < expected_length)
373        return D3DXERR_INVALIDDATA;
374
375    info->ImageFileFormat = D3DXIFF_DDS;
376
377    return D3D_OK;
378 }
379
380 static HRESULT load_surface_from_dds(IDirect3DSurface9 *dst_surface, const PALETTEENTRY *dst_palette,
381     const RECT *dst_rect, const void *src_data, const RECT *src_rect, DWORD filter, D3DCOLOR color_key,
382     const D3DXIMAGE_INFO *src_info)
383 {
384     UINT size;
385     UINT src_pitch;
386     const struct dds_header *header = src_data;
387     const BYTE *pixels = (BYTE *)(header + 1);
388
389     if (src_info->ResourceType != D3DRTYPE_TEXTURE)
390         return D3DXERR_INVALIDDATA;
391
392     if (FAILED(calculate_dds_surface_size(src_info, src_info->Width, src_info->Height, &src_pitch, &size)))
393         return E_NOTIMPL;
394
395     return D3DXLoadSurfaceFromMemory(dst_surface, dst_palette, dst_rect, pixels, src_info->Format,
396         src_pitch, NULL, src_rect, filter, color_key);
397 }
398
399 HRESULT load_texture_from_dds(IDirect3DTexture9 *texture, const void *src_data, const PALETTEENTRY *palette,
400     DWORD filter, D3DCOLOR color_key, const D3DXIMAGE_INFO *src_info)
401
402 {
403     HRESULT hr;
404     RECT src_rect;
405     UINT src_pitch;
406     UINT mip_level;
407     UINT mip_levels;
408     UINT mip_level_size;
409     UINT width, height;
410     IDirect3DSurface9 *surface;
411     const struct dds_header *header = src_data;
412     const BYTE *pixels = (BYTE *)(header + 1);
413
414     if (src_info->ResourceType != D3DRTYPE_TEXTURE)
415         return D3DXERR_INVALIDDATA;
416
417     width = src_info->Width;
418     height = src_info->Height;
419     mip_levels = min(src_info->MipLevels, IDirect3DTexture9_GetLevelCount(texture));
420     for (mip_level = 0; mip_level < mip_levels; mip_level++)
421     {
422         hr = calculate_dds_surface_size(src_info, width, height, &src_pitch, &mip_level_size);
423         if (FAILED(hr)) return hr;
424
425         SetRect(&src_rect, 0, 0, width, height);
426
427         IDirect3DTexture9_GetSurfaceLevel(texture, mip_level, &surface);
428         hr = D3DXLoadSurfaceFromMemory(surface, palette, NULL, pixels, src_info->Format, src_pitch,
429             NULL, &src_rect, filter, color_key);
430         IDirect3DSurface9_Release(surface);
431         if (FAILED(hr)) return hr;
432
433         pixels += mip_level_size;
434         width = max(1, width / 2);
435         height = max(1, height / 2);
436     }
437
438     return D3D_OK;
439 }
440
441 HRESULT load_cube_texture_from_dds(IDirect3DCubeTexture9 *cube_texture, const void *src_data,
442     const PALETTEENTRY *palette, DWORD filter, DWORD color_key, const D3DXIMAGE_INFO *src_info)
443 {
444     HRESULT hr;
445     int face;
446     int mip_level;
447     UINT size;
448     RECT src_rect;
449     UINT src_pitch;
450     UINT mip_levels;
451     UINT mip_level_size;
452     IDirect3DSurface9 *surface;
453     const struct dds_header *header = src_data;
454     const BYTE *pixels = (BYTE *)(header + 1);
455
456     if (src_info->ResourceType != D3DRTYPE_CUBETEXTURE)
457         return D3DXERR_INVALIDDATA;
458
459     if ((header->caps2 & DDS_CAPS2_CUBEMAP_ALL_FACES) != DDS_CAPS2_CUBEMAP_ALL_FACES)
460     {
461         WARN("Only full cubemaps are supported\n");
462         return D3DXERR_INVALIDDATA;
463     }
464
465     mip_levels = min(src_info->MipLevels, IDirect3DCubeTexture9_GetLevelCount(cube_texture));
466     for (face = D3DCUBEMAP_FACE_POSITIVE_X; face <= D3DCUBEMAP_FACE_NEGATIVE_Z; face++)
467     {
468         size = src_info->Width;
469         for (mip_level = 0; mip_level < src_info->MipLevels; mip_level++)
470         {
471             hr = calculate_dds_surface_size(src_info, size, size, &src_pitch, &mip_level_size);
472             if (FAILED(hr)) return hr;
473
474             /* if texture has fewer mip levels than DDS file, skip excessive mip levels */
475             if (mip_level < mip_levels)
476             {
477                 SetRect(&src_rect, 0, 0, size, size);
478
479                 IDirect3DCubeTexture9_GetCubeMapSurface(cube_texture, face, mip_level, &surface);
480                 hr = D3DXLoadSurfaceFromMemory(surface, palette, NULL, pixels, src_info->Format, src_pitch,
481                     NULL, &src_rect, filter, color_key);
482                 IDirect3DSurface9_Release(surface);
483                 if (FAILED(hr)) return hr;
484             }
485
486             pixels += mip_level_size;
487             size = max(1, size / 2);
488         }
489     }
490
491     return D3D_OK;
492 }
493
494 /************************************************************
495  * D3DXGetImageInfoFromFileInMemory
496  *
497  * Fills a D3DXIMAGE_INFO structure with info about an image
498  *
499  * PARAMS
500  *   data     [I] pointer to the image file data
501  *   datasize [I] size of the passed data
502  *   info     [O] pointer to the destination structure
503  *
504  * RETURNS
505  *   Success: D3D_OK, if info is not NULL and data and datasize make up a valid image file or
506  *                    if info is NULL and data and datasize are not NULL
507  *   Failure: D3DXERR_INVALIDDATA, if data is no valid image file and datasize and info are not NULL
508  *            D3DERR_INVALIDCALL, if data is NULL or
509  *                                if datasize is 0
510  *
511  * NOTES
512  *   datasize may be bigger than the actual file size
513  *
514  */
515 HRESULT WINAPI D3DXGetImageInfoFromFileInMemory(LPCVOID data, UINT datasize, D3DXIMAGE_INFO *info)
516 {
517     IWICImagingFactory *factory;
518     IWICBitmapDecoder *decoder = NULL;
519     IWICStream *stream;
520     HRESULT hr;
521     HRESULT initresult;
522
523     TRACE("(%p, %d, %p)\n", data, datasize, info);
524
525     if (!data || !datasize)
526         return D3DERR_INVALIDCALL;
527
528     if (!info)
529         return D3D_OK;
530
531     if ((datasize >= 4) && !strncmp(data, "DDS ", 4))
532         return get_image_info_from_dds(data, datasize, info);
533
534     initresult = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
535
536     hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, &IID_IWICImagingFactory, (void**)&factory);
537
538     if (SUCCEEDED(hr)) {
539         IWICImagingFactory_CreateStream(factory, &stream);
540         IWICStream_InitializeFromMemory(stream, (BYTE*)data, datasize);
541         hr = IWICImagingFactory_CreateDecoderFromStream(factory, (IStream*)stream, NULL, 0, &decoder);
542         IStream_Release(stream);
543         IWICImagingFactory_Release(factory);
544     }
545
546     if (FAILED(hr)) {
547         if ((datasize >= 2) && (!strncmp(data, "P3", 2) || !strncmp(data, "P6", 2)))
548             FIXME("File type PPM is not supported yet\n");
549         else if ((datasize >= 2) && !strncmp(data, "BM", 2))
550             FIXME("File type DIB is not supported yet\n");
551         else if ((datasize >= 10) && !strncmp(data, "#?RADIANCE", 10))
552             FIXME("File type HDR is not supported yet\n");
553         else if ((datasize >= 2) && (!strncmp(data, "PF", 2) || !strncmp(data, "Pf", 2)))
554             FIXME("File type PFM is not supported yet\n");
555     }
556
557     if (SUCCEEDED(hr)) {
558         GUID container_format;
559         UINT frame_count;
560
561         hr = IWICBitmapDecoder_GetContainerFormat(decoder, &container_format);
562         if (SUCCEEDED(hr)) {
563             if (IsEqualGUID(&container_format, &GUID_ContainerFormatBmp)) {
564                 TRACE("File type is BMP\n");
565                 info->ImageFileFormat = D3DXIFF_BMP;
566             } else if (IsEqualGUID(&container_format, &GUID_ContainerFormatPng)) {
567                 TRACE("File type is PNG\n");
568                 info->ImageFileFormat = D3DXIFF_PNG;
569             } else if(IsEqualGUID(&container_format, &GUID_ContainerFormatJpeg)) {
570                 TRACE("File type is JPG\n");
571                 info->ImageFileFormat = D3DXIFF_JPG;
572             } else if(IsEqualGUID(&container_format, &GUID_WineContainerFormatTga)) {
573                 TRACE("File type is TGA\n");
574                 info->ImageFileFormat = D3DXIFF_TGA;
575             } else {
576                 WARN("Unsupported image file format %s\n", debugstr_guid(&container_format));
577                 hr = D3DXERR_INVALIDDATA;
578             }
579         }
580
581         if (SUCCEEDED(hr))
582             hr = IWICBitmapDecoder_GetFrameCount(decoder, &frame_count);
583         if (SUCCEEDED(hr) && !frame_count)
584             hr = D3DXERR_INVALIDDATA;
585
586         if (SUCCEEDED(hr)) {
587             IWICBitmapFrameDecode *frame = NULL;
588
589             hr = IWICBitmapDecoder_GetFrame(decoder, 0, &frame);
590
591             if (SUCCEEDED(hr))
592                 hr = IWICBitmapFrameDecode_GetSize(frame, &info->Width, &info->Height);
593
594             if (SUCCEEDED(hr)) {
595                 WICPixelFormatGUID pixel_format;
596
597                 hr = IWICBitmapFrameDecode_GetPixelFormat(frame, &pixel_format);
598                 if (SUCCEEDED(hr)) {
599                     info->Format = wic_guid_to_d3dformat(&pixel_format);
600                     if (info->Format == D3DFMT_UNKNOWN) {
601                         WARN("Unsupported pixel format %s\n", debugstr_guid(&pixel_format));
602                         hr = D3DXERR_INVALIDDATA;
603                     }
604                 }
605             }
606
607             if (frame)
608                  IWICBitmapFrameDecode_Release(frame);
609
610             info->Depth = 1;
611             info->MipLevels = 1;
612             info->ResourceType = D3DRTYPE_TEXTURE;
613         }
614     }
615
616     if (decoder)
617         IWICBitmapDecoder_Release(decoder);
618
619     if (SUCCEEDED(initresult))
620         CoUninitialize();
621
622     if (FAILED(hr)) {
623         TRACE("Invalid or unsupported image file\n");
624         return D3DXERR_INVALIDDATA;
625     }
626
627     return D3D_OK;
628 }
629
630 /************************************************************
631  * D3DXGetImageInfoFromFile
632  *
633  * RETURNS
634  *   Success: D3D_OK, if we successfully load a valid image file or
635  *                    if we successfully load a file which is no valid image and info is NULL
636  *   Failure: D3DXERR_INVALIDDATA, if we fail to load file or
637  *                                 if file is not a valid image file and info is not NULL
638  *            D3DERR_INVALIDCALL, if file is NULL
639  *
640  */
641 HRESULT WINAPI D3DXGetImageInfoFromFileA(LPCSTR file, D3DXIMAGE_INFO *info)
642 {
643     LPWSTR widename;
644     HRESULT hr;
645     int strlength;
646
647     TRACE("(%s, %p): relay\n", debugstr_a(file), info);
648
649     if( !file ) return D3DERR_INVALIDCALL;
650
651     strlength = MultiByteToWideChar(CP_ACP, 0, file, -1, NULL, 0);
652     widename = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, strlength * sizeof(WCHAR));
653     MultiByteToWideChar(CP_ACP, 0, file, -1, widename, strlength);
654
655     hr = D3DXGetImageInfoFromFileW(widename, info);
656     HeapFree(GetProcessHeap(), 0, widename);
657
658     return hr;
659 }
660
661 HRESULT WINAPI D3DXGetImageInfoFromFileW(LPCWSTR file, D3DXIMAGE_INFO *info)
662 {
663     HRESULT hr;
664     DWORD size;
665     LPVOID buffer;
666
667     TRACE("(%s, %p): relay\n", debugstr_w(file), info);
668
669     if( !file ) return D3DERR_INVALIDCALL;
670
671     hr = map_view_of_file(file, &buffer, &size);
672     if(FAILED(hr)) return D3DXERR_INVALIDDATA;
673
674     hr = D3DXGetImageInfoFromFileInMemory(buffer, size, info);
675     UnmapViewOfFile(buffer);
676
677     return hr;
678 }
679
680 /************************************************************
681  * D3DXGetImageInfoFromResource
682  *
683  * RETURNS
684  *   Success: D3D_OK, if resource is a valid image file
685  *   Failure: D3DXERR_INVALIDDATA, if resource is no valid image file or NULL or
686  *                                 if we fail to load resource
687  *
688  */
689 HRESULT WINAPI D3DXGetImageInfoFromResourceA(HMODULE module, LPCSTR resource, D3DXIMAGE_INFO *info)
690 {
691     HRSRC resinfo;
692
693     TRACE("(%p, %s, %p)\n", module, debugstr_a(resource), info);
694
695     resinfo = FindResourceA(module, resource, (LPCSTR)RT_RCDATA);
696     if(resinfo) {
697         LPVOID buffer;
698         HRESULT hr;
699         DWORD size;
700
701         hr = load_resource_into_memory(module, resinfo, &buffer, &size);
702         if(FAILED(hr)) return D3DXERR_INVALIDDATA;
703         return D3DXGetImageInfoFromFileInMemory(buffer, size, info);
704     }
705
706     resinfo = FindResourceA(module, resource, (LPCSTR)RT_BITMAP);
707     if(resinfo) {
708         FIXME("Implement loading bitmaps from resource type RT_BITMAP\n");
709         return E_NOTIMPL;
710     }
711     return D3DXERR_INVALIDDATA;
712 }
713
714 HRESULT WINAPI D3DXGetImageInfoFromResourceW(HMODULE module, LPCWSTR resource, D3DXIMAGE_INFO *info)
715 {
716     HRSRC resinfo;
717
718     TRACE("(%p, %s, %p)\n", module, debugstr_w(resource), info);
719
720     resinfo = FindResourceW(module, resource, (LPCWSTR)RT_RCDATA);
721     if(resinfo) {
722         LPVOID buffer;
723         HRESULT hr;
724         DWORD size;
725
726         hr = load_resource_into_memory(module, resinfo, &buffer, &size);
727         if(FAILED(hr)) return D3DXERR_INVALIDDATA;
728         return D3DXGetImageInfoFromFileInMemory(buffer, size, info);
729     }
730
731     resinfo = FindResourceW(module, resource, (LPCWSTR)RT_BITMAP);
732     if(resinfo) {
733         FIXME("Implement loading bitmaps from resource type RT_BITMAP\n");
734         return E_NOTIMPL;
735     }
736     return D3DXERR_INVALIDDATA;
737 }
738
739 /************************************************************
740  * D3DXLoadSurfaceFromFileInMemory
741  *
742  * Loads data from a given buffer into a surface and fills a given
743  * D3DXIMAGE_INFO structure with info about the source data.
744  *
745  * PARAMS
746  *   pDestSurface [I] pointer to the surface
747  *   pDestPalette [I] palette to use
748  *   pDestRect    [I] to be filled area of the surface
749  *   pSrcData     [I] pointer to the source data
750  *   SrcDataSize  [I] size of the source data in bytes
751  *   pSrcRect     [I] area of the source data to load
752  *   dwFilter     [I] filter to apply on stretching
753  *   Colorkey     [I] colorkey
754  *   pSrcInfo     [O] pointer to a D3DXIMAGE_INFO structure
755  *
756  * RETURNS
757  *   Success: D3D_OK
758  *   Failure: D3DERR_INVALIDCALL, if pDestSurface or pSrcData or SrcDataSize are NULL
759  *            D3DXERR_INVALIDDATA, if pSrcData is no valid image file
760  *
761  */
762 HRESULT WINAPI D3DXLoadSurfaceFromFileInMemory(LPDIRECT3DSURFACE9 pDestSurface,
763                                                CONST PALETTEENTRY *pDestPalette,
764                                                CONST RECT *pDestRect,
765                                                LPCVOID pSrcData,
766                                                UINT SrcDataSize,
767                                                CONST RECT *pSrcRect,
768                                                DWORD dwFilter,
769                                                D3DCOLOR Colorkey,
770                                                D3DXIMAGE_INFO *pSrcInfo)
771 {
772     D3DXIMAGE_INFO imginfo;
773     HRESULT hr;
774
775     IWICImagingFactory *factory;
776     IWICBitmapDecoder *decoder;
777     IWICBitmapFrameDecode *bitmapframe;
778     IWICStream *stream;
779
780     const PixelFormatDesc *formatdesc;
781     WICRect wicrect;
782     RECT rect;
783
784     TRACE("(%p, %p, %p, %p, %d, %p, %d, %x, %p)\n", pDestSurface, pDestPalette, pDestRect, pSrcData,
785         SrcDataSize, pSrcRect, dwFilter, Colorkey, pSrcInfo);
786
787     if (!pDestSurface || !pSrcData || !SrcDataSize)
788         return D3DERR_INVALIDCALL;
789
790     hr = D3DXGetImageInfoFromFileInMemory(pSrcData, SrcDataSize, &imginfo);
791
792     if (FAILED(hr))
793         return hr;
794
795     if (pSrcRect)
796     {
797         wicrect.X = pSrcRect->left;
798         wicrect.Y = pSrcRect->top;
799         wicrect.Width = pSrcRect->right - pSrcRect->left;
800         wicrect.Height = pSrcRect->bottom - pSrcRect->top;
801     }
802     else
803     {
804         wicrect.X = 0;
805         wicrect.Y = 0;
806         wicrect.Width = imginfo.Width;
807         wicrect.Height = imginfo.Height;
808     }
809
810     SetRect(&rect, 0, 0, wicrect.Width, wicrect.Height);
811
812     if (imginfo.ImageFileFormat == D3DXIFF_DDS)
813     {
814         hr = load_surface_from_dds(pDestSurface, pDestPalette, pDestRect, pSrcData, &rect,
815             dwFilter, Colorkey, &imginfo);
816         if (SUCCEEDED(hr) && pSrcInfo)
817             *pSrcInfo = imginfo;
818         return hr;
819     }
820
821     CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
822
823     if (FAILED(CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, &IID_IWICImagingFactory, (void**)&factory)))
824         goto cleanup_err;
825
826     if (FAILED(IWICImagingFactory_CreateStream(factory, &stream)))
827     {
828         IWICImagingFactory_Release(factory);
829         goto cleanup_err;
830     }
831
832     IWICStream_InitializeFromMemory(stream, (BYTE*)pSrcData, SrcDataSize);
833
834     hr = IWICImagingFactory_CreateDecoderFromStream(factory, (IStream*)stream, NULL, 0, &decoder);
835
836     IStream_Release(stream);
837     IWICImagingFactory_Release(factory);
838
839     if (FAILED(hr))
840         goto cleanup_err;
841
842     hr = IWICBitmapDecoder_GetFrame(decoder, 0, &bitmapframe);
843
844     if (FAILED(hr))
845         goto cleanup_bmp;
846
847     formatdesc = get_format_info(imginfo.Format);
848
849     if (formatdesc->format == D3DFMT_UNKNOWN)
850     {
851         FIXME("Unsupported pixel format\n");
852         hr = D3DXERR_INVALIDDATA;
853     }
854     else
855     {
856         BYTE *buffer;
857         DWORD pitch;
858
859         pitch = formatdesc->bytes_per_pixel * wicrect.Width;
860         buffer = HeapAlloc(GetProcessHeap(), 0, pitch * wicrect.Height);
861
862         hr = IWICBitmapFrameDecode_CopyPixels(bitmapframe, &wicrect, pitch,
863                                               pitch * wicrect.Height, buffer);
864
865         if (SUCCEEDED(hr))
866         {
867             hr = D3DXLoadSurfaceFromMemory(pDestSurface, pDestPalette, pDestRect,
868                                            buffer, imginfo.Format, pitch,
869                                            NULL, &rect, dwFilter, Colorkey);
870         }
871
872         HeapFree(GetProcessHeap(), 0, buffer);
873     }
874
875     IWICBitmapFrameDecode_Release(bitmapframe);
876
877 cleanup_bmp:
878     IWICBitmapDecoder_Release(decoder);
879
880 cleanup_err:
881     CoUninitialize();
882
883     if (FAILED(hr))
884         return D3DXERR_INVALIDDATA;
885
886     if (pSrcInfo)
887         *pSrcInfo = imginfo;
888
889     return D3D_OK;
890 }
891
892 /************************************************************
893  * D3DXLoadSurfaceFromFile
894  */
895 HRESULT WINAPI D3DXLoadSurfaceFromFileA(LPDIRECT3DSURFACE9 pDestSurface,
896                                         CONST PALETTEENTRY *pDestPalette,
897                                         CONST RECT *pDestRect,
898                                         LPCSTR pSrcFile,
899                                         CONST RECT *pSrcRect,
900                                         DWORD dwFilter,
901                                         D3DCOLOR Colorkey,
902                                         D3DXIMAGE_INFO *pSrcInfo)
903 {
904     LPWSTR pWidename;
905     HRESULT hr;
906     int strlength;
907
908     TRACE("(%p, %p, %p, %s, %p, %u, %#x, %p): relay\n", pDestSurface, pDestPalette, pDestRect, debugstr_a(pSrcFile),
909         pSrcRect, dwFilter, Colorkey, pSrcInfo);
910
911     if( !pSrcFile || !pDestSurface ) return D3DERR_INVALIDCALL;
912
913     strlength = MultiByteToWideChar(CP_ACP, 0, pSrcFile, -1, NULL, 0);
914     pWidename = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, strlength * sizeof(WCHAR));
915     MultiByteToWideChar(CP_ACP, 0, pSrcFile, -1, pWidename, strlength);
916
917     hr = D3DXLoadSurfaceFromFileW(pDestSurface, pDestPalette, pDestRect, pWidename, pSrcRect, dwFilter, Colorkey, pSrcInfo);
918     HeapFree(GetProcessHeap(), 0, pWidename);
919
920     return hr;
921 }
922
923 HRESULT WINAPI D3DXLoadSurfaceFromFileW(LPDIRECT3DSURFACE9 pDestSurface,
924                                         CONST PALETTEENTRY *pDestPalette,
925                                         CONST RECT *pDestRect,
926                                         LPCWSTR pSrcFile,
927                                         CONST RECT *pSrcRect,
928                                         DWORD Filter,
929                                         D3DCOLOR Colorkey,
930                                         D3DXIMAGE_INFO *pSrcInfo)
931 {
932     HRESULT hr;
933     DWORD dwSize;
934     LPVOID pBuffer;
935
936     TRACE("(%p, %p, %p, %s, %p, %u, %#x, %p): relay\n", pDestSurface, pDestPalette, pDestRect, debugstr_w(pSrcFile),
937         pSrcRect, Filter, Colorkey, pSrcInfo);
938
939     if( !pSrcFile || !pDestSurface ) return D3DERR_INVALIDCALL;
940
941     hr = map_view_of_file(pSrcFile, &pBuffer, &dwSize);
942     if(FAILED(hr)) return D3DXERR_INVALIDDATA;
943
944     hr = D3DXLoadSurfaceFromFileInMemory(pDestSurface, pDestPalette, pDestRect, pBuffer, dwSize, pSrcRect, Filter, Colorkey, pSrcInfo);
945     UnmapViewOfFile(pBuffer);
946
947     return hr;
948 }
949
950 /************************************************************
951  * D3DXLoadSurfaceFromResource
952  */
953 HRESULT WINAPI D3DXLoadSurfaceFromResourceA(LPDIRECT3DSURFACE9 pDestSurface,
954                                             CONST PALETTEENTRY *pDestPalette,
955                                             CONST RECT *pDestRect,
956                                             HMODULE hSrcModule,
957                                             LPCSTR pResource,
958                                             CONST RECT *pSrcRect,
959                                             DWORD dwFilter,
960                                             D3DCOLOR Colorkey,
961                                             D3DXIMAGE_INFO *pSrcInfo)
962 {
963     HRSRC hResInfo;
964
965     TRACE("(%p, %p, %p, %p, %s, %p, %u, %#x, %p): relay\n", pDestSurface, pDestPalette, pDestRect, hSrcModule,
966         debugstr_a(pResource), pSrcRect, dwFilter, Colorkey, pSrcInfo);
967
968     if( !pDestSurface ) return D3DERR_INVALIDCALL;
969
970     hResInfo = FindResourceA(hSrcModule, pResource, (LPCSTR)RT_RCDATA);
971     if(hResInfo) {
972         LPVOID pBuffer;
973         HRESULT hr;
974         DWORD dwSize;
975
976         hr = load_resource_into_memory(hSrcModule, hResInfo, &pBuffer, &dwSize);
977         if(FAILED(hr)) return D3DXERR_INVALIDDATA;
978         return D3DXLoadSurfaceFromFileInMemory(pDestSurface, pDestPalette, pDestRect, pBuffer, dwSize, pSrcRect, dwFilter, Colorkey, pSrcInfo);
979     }
980
981     hResInfo = FindResourceA(hSrcModule, pResource, (LPCSTR)RT_BITMAP);
982     if(hResInfo) {
983         FIXME("Implement loading bitmaps from resource type RT_BITMAP\n");
984         return E_NOTIMPL;
985     }
986     return D3DXERR_INVALIDDATA;
987 }
988
989 HRESULT WINAPI D3DXLoadSurfaceFromResourceW(LPDIRECT3DSURFACE9 pDestSurface,
990                                             CONST PALETTEENTRY *pDestPalette,
991                                             CONST RECT *pDestRect,
992                                             HMODULE hSrcModule,
993                                             LPCWSTR pResource,
994                                             CONST RECT *pSrcRect,
995                                             DWORD dwFilter,
996                                             D3DCOLOR Colorkey,
997                                             D3DXIMAGE_INFO *pSrcInfo)
998 {
999     HRSRC hResInfo;
1000
1001     TRACE("(%p, %p, %p, %p, %s, %p, %u, %#x, %p): relay\n", pDestSurface, pDestPalette, pDestRect, hSrcModule,
1002         debugstr_w(pResource), pSrcRect, dwFilter, Colorkey, pSrcInfo);
1003
1004     if( !pDestSurface ) return D3DERR_INVALIDCALL;
1005
1006     hResInfo = FindResourceW(hSrcModule, pResource, (LPCWSTR)RT_RCDATA);
1007     if(hResInfo) {
1008         LPVOID pBuffer;
1009         HRESULT hr;
1010         DWORD dwSize;
1011
1012         hr = load_resource_into_memory(hSrcModule, hResInfo, &pBuffer, &dwSize);
1013         if(FAILED(hr)) return D3DXERR_INVALIDDATA;
1014         return D3DXLoadSurfaceFromFileInMemory(pDestSurface, pDestPalette, pDestRect, pBuffer, dwSize, pSrcRect, dwFilter, Colorkey, pSrcInfo);
1015     }
1016
1017     hResInfo = FindResourceW(hSrcModule, pResource, (LPCWSTR)RT_BITMAP);
1018     if(hResInfo) {
1019         FIXME("Implement loading bitmaps from resource type RT_BITMAP\n");
1020         return E_NOTIMPL;
1021     }
1022     return D3DXERR_INVALIDDATA;
1023 }
1024
1025
1026 /************************************************************
1027  * helper functions for D3DXLoadSurfaceFromMemory
1028  */
1029 struct argb_conversion_info
1030 {
1031     CONST PixelFormatDesc *srcformat;
1032     CONST PixelFormatDesc *destformat;
1033     DWORD srcshift[4], destshift[4];
1034     DWORD srcmask[4], destmask[4];
1035     BOOL process_channel[4];
1036     DWORD channelmask;
1037 };
1038
1039 static void init_argb_conversion_info(CONST PixelFormatDesc *srcformat, CONST PixelFormatDesc *destformat, struct argb_conversion_info *info)
1040 {
1041     UINT i;
1042     ZeroMemory(info->process_channel, 4 * sizeof(BOOL));
1043     info->channelmask = 0;
1044
1045     info->srcformat  =  srcformat;
1046     info->destformat = destformat;
1047
1048     for(i = 0;i < 4;i++) {
1049         /* srcshift is used to extract the _relevant_ components */
1050         info->srcshift[i]  =  srcformat->shift[i] + max( srcformat->bits[i] - destformat->bits[i], 0);
1051
1052         /* destshift is used to move the components to the correct position */
1053         info->destshift[i] = destformat->shift[i] + max(destformat->bits[i] -  srcformat->bits[i], 0);
1054
1055         info->srcmask[i]  = ((1 <<  srcformat->bits[i]) - 1) <<  srcformat->shift[i];
1056         info->destmask[i] = ((1 << destformat->bits[i]) - 1) << destformat->shift[i];
1057
1058         /* channelmask specifies bits which aren't used in the source format but in the destination one */
1059         if(destformat->bits[i]) {
1060             if(srcformat->bits[i]) info->process_channel[i] = TRUE;
1061             else info->channelmask |= info->destmask[i];
1062         }
1063     }
1064 }
1065
1066 static DWORD dword_from_bytes(CONST BYTE *src, UINT bytes_per_pixel)
1067 {
1068     DWORD ret = 0;
1069     static BOOL fixme_once;
1070
1071     if(bytes_per_pixel > sizeof(DWORD)) {
1072         if(!fixme_once++) FIXME("Unsupported image: %u bytes per pixel\n", bytes_per_pixel);
1073         bytes_per_pixel = sizeof(DWORD);
1074     }
1075
1076     memcpy(&ret, src, bytes_per_pixel);
1077     return ret;
1078 }
1079
1080 static void dword_to_bytes(BYTE *dst, DWORD dword, UINT bytes_per_pixel)
1081 {
1082     static BOOL fixme_once;
1083
1084     if(bytes_per_pixel > sizeof(DWORD)) {
1085         if(!fixme_once++) FIXME("Unsupported image: %u bytes per pixel\n", bytes_per_pixel);
1086         ZeroMemory(dst, bytes_per_pixel);
1087         bytes_per_pixel = sizeof(DWORD);
1088     }
1089
1090     memcpy(dst, &dword, bytes_per_pixel);
1091 }
1092
1093 /************************************************************
1094  * get_relevant_argb_components
1095  *
1096  * Extracts the relevant components from the source color and
1097  * drops the less significant bits if they aren't used by the destination format.
1098  */
1099 static void get_relevant_argb_components(CONST struct argb_conversion_info *info, CONST DWORD col, DWORD *out)
1100 {
1101     UINT i = 0;
1102     for(;i < 4;i++)
1103         if(info->process_channel[i])
1104             out[i] = (col & info->srcmask[i]) >> info->srcshift[i];
1105 }
1106
1107 /************************************************************
1108  * make_argb_color
1109  *
1110  * Recombines the output of get_relevant_argb_components and converts
1111  * it to the destination format.
1112  */
1113 static DWORD make_argb_color(CONST struct argb_conversion_info *info, CONST DWORD *in)
1114 {
1115     UINT i;
1116     DWORD val = 0;
1117
1118     for(i = 0;i < 4;i++) {
1119         if(info->process_channel[i]) {
1120             /* necessary to make sure that e.g. an X4R4G4B4 white maps to an R8G8B8 white instead of 0xf0f0f0 */
1121             signed int shift;
1122             for(shift = info->destshift[i]; shift > info->destformat->shift[i]; shift -= info->srcformat->bits[i]) val |= in[i] << shift;
1123             val |= (in[i] >> (info->destformat->shift[i] - shift)) << info->destformat->shift[i];
1124         }
1125     }
1126     val |= info->channelmask;   /* new channels are set to their maximal value */
1127     return val;
1128 }
1129
1130 static void format_to_vec4(const PixelFormatDesc *format, const DWORD *src, struct vec4 *dst)
1131 {
1132     DWORD mask;
1133
1134     if (format->bits[1])
1135     {
1136         mask = (1 << format->bits[1]) - 1;
1137         dst->x = (float)((*src >> format->shift[1]) & mask) / mask;
1138     }
1139     else
1140         dst->x = 1.0f;
1141
1142     if (format->bits[2])
1143     {
1144         mask = (1 << format->bits[2]) - 1;
1145         dst->y = (float)((*src >> format->shift[2]) & mask) / mask;
1146     }
1147     else
1148         dst->y = 1.0f;
1149
1150     if (format->bits[3])
1151     {
1152         mask = (1 << format->bits[3]) - 1;
1153         dst->z = (float)((*src >> format->shift[3]) & mask) / mask;
1154     }
1155     else
1156         dst->z = 1.0f;
1157
1158     if (format->bits[0])
1159     {
1160         mask = (1 << format->bits[0]) - 1;
1161         dst->w = (float)((*src >> format->shift[0]) & mask) / mask;
1162     }
1163     else
1164         dst->w = 1.0f;
1165 }
1166
1167 static void format_from_vec4(const PixelFormatDesc *format, const struct vec4 *src, DWORD *dst)
1168 {
1169     *dst = 0;
1170
1171     if (format->bits[1])
1172         *dst |= (DWORD)(src->x * ((1 << format->bits[1]) - 1) + 0.5f) << format->shift[1];
1173     if (format->bits[2])
1174         *dst |= (DWORD)(src->y * ((1 << format->bits[2]) - 1) + 0.5f) << format->shift[2];
1175     if (format->bits[3])
1176         *dst |= (DWORD)(src->z * ((1 << format->bits[3]) - 1) + 0.5f) << format->shift[3];
1177     if (format->bits[0])
1178         *dst |= (DWORD)(src->w * ((1 << format->bits[0]) - 1) + 0.5f) << format->shift[0];
1179 }
1180
1181 /************************************************************
1182  * copy_simple_data
1183  *
1184  * Copies the source buffer to the destination buffer, performing
1185  * any necessary format conversion and color keying.
1186  * Pixels outsize the source rect are blacked out.
1187  * Works only for ARGB formats with 1 - 4 bytes per pixel.
1188  */
1189 static void copy_simple_data(const BYTE *src, UINT srcpitch, SIZE src_size, const PixelFormatDesc *srcformat,
1190         BYTE *dest, UINT destpitch, SIZE dst_size, const PixelFormatDesc *destformat, D3DCOLOR colorkey)
1191 {
1192     struct argb_conversion_info conv_info, ck_conv_info;
1193     const PixelFormatDesc *ck_format = NULL;
1194     DWORD channels[4], pixel;
1195     UINT minwidth, minheight;
1196     UINT x, y;
1197
1198     ZeroMemory(channels, sizeof(channels));
1199     init_argb_conversion_info(srcformat, destformat, &conv_info);
1200
1201     minwidth = (src_size.cx < dst_size.cx) ? src_size.cx : dst_size.cx;
1202     minheight = (src_size.cy < dst_size.cy) ? src_size.cy : dst_size.cy;
1203
1204     if (colorkey)
1205     {
1206         /* Color keys are always represented in D3DFMT_A8R8G8B8 format. */
1207         ck_format = get_format_info(D3DFMT_A8R8G8B8);
1208         init_argb_conversion_info(srcformat, ck_format, &ck_conv_info);
1209     }
1210
1211     for(y = 0;y < minheight;y++) {
1212         const BYTE *srcptr = src + y * srcpitch;
1213         BYTE *destptr = dest + y * destpitch;
1214         DWORD val;
1215
1216         for(x = 0;x < minwidth;x++) {
1217             /* extract source color components */
1218             pixel = dword_from_bytes(srcptr, srcformat->bytes_per_pixel);
1219
1220             if (!srcformat->to_rgba && !destformat->from_rgba)
1221             {
1222                 get_relevant_argb_components(&conv_info, pixel, channels);
1223                 val = make_argb_color(&conv_info, channels);
1224
1225                 if (colorkey)
1226                 {
1227                     get_relevant_argb_components(&ck_conv_info, pixel, channels);
1228                     pixel = make_argb_color(&ck_conv_info, channels);
1229                     if (pixel == colorkey)
1230                         val &= ~conv_info.destmask[0];
1231                 }
1232             }
1233             else
1234             {
1235                 struct vec4 color, tmp;
1236
1237                 format_to_vec4(srcformat, &pixel, &color);
1238                 if (srcformat->to_rgba)
1239                     srcformat->to_rgba(&color, &tmp);
1240                 else
1241                     tmp = color;
1242
1243                 if (ck_format)
1244                 {
1245                     format_from_vec4(ck_format, &tmp, &pixel);
1246                     if (pixel == colorkey)
1247                         tmp.w = 0.0f;
1248                 }
1249
1250                 if (destformat->from_rgba)
1251                     destformat->from_rgba(&tmp, &color);
1252                 else
1253                     color = tmp;
1254
1255                 format_from_vec4(destformat, &color, &val);
1256             }
1257
1258             dword_to_bytes(destptr, val, destformat->bytes_per_pixel);
1259             srcptr  +=  srcformat->bytes_per_pixel;
1260             destptr += destformat->bytes_per_pixel;
1261         }
1262
1263         if (src_size.cx < dst_size.cx) /* black out remaining pixels */
1264             memset(destptr, 0, destformat->bytes_per_pixel * (dst_size.cx - src_size.cx));
1265     }
1266     if (src_size.cy < dst_size.cy) /* black out remaining pixels */
1267         memset(dest + src_size.cy * destpitch, 0, destpitch * (dst_size.cy - src_size.cy));
1268 }
1269
1270 /************************************************************
1271  * point_filter_simple_data
1272  *
1273  * Copies the source buffer to the destination buffer, performing
1274  * any necessary format conversion, color keying and stretching
1275  * using a point filter.
1276  * Works only for ARGB formats with 1 - 4 bytes per pixel.
1277  */
1278 static void point_filter_simple_data(const BYTE *src, UINT srcpitch, SIZE src_size, const PixelFormatDesc *srcformat,
1279         BYTE *dest, UINT destpitch, SIZE dst_size, const PixelFormatDesc *destformat, D3DCOLOR colorkey)
1280 {
1281     struct argb_conversion_info conv_info, ck_conv_info;
1282     const PixelFormatDesc *ck_format = NULL;
1283     DWORD channels[4], pixel;
1284
1285     UINT x, y;
1286
1287     ZeroMemory(channels, sizeof(channels));
1288     init_argb_conversion_info(srcformat, destformat, &conv_info);
1289
1290     if (colorkey)
1291     {
1292         /* Color keys are always represented in D3DFMT_A8R8G8B8 format. */
1293         ck_format = get_format_info(D3DFMT_A8R8G8B8);
1294         init_argb_conversion_info(srcformat, ck_format, &ck_conv_info);
1295     }
1296
1297     for (y = 0; y < dst_size.cy; ++y)
1298     {
1299         BYTE *destptr = dest + y * destpitch;
1300         const BYTE *bufptr = src + srcpitch * (y * src_size.cy / dst_size.cy);
1301
1302         for (x = 0; x < dst_size.cx; ++x)
1303         {
1304             const BYTE *srcptr = bufptr + (x * src_size.cx / dst_size.cx) * srcformat->bytes_per_pixel;
1305             DWORD val;
1306
1307             /* extract source color components */
1308             pixel = dword_from_bytes(srcptr, srcformat->bytes_per_pixel);
1309
1310             if (!srcformat->to_rgba && !destformat->from_rgba)
1311             {
1312                 get_relevant_argb_components(&conv_info, pixel, channels);
1313                 val = make_argb_color(&conv_info, channels);
1314
1315                 if (colorkey)
1316                 {
1317                     get_relevant_argb_components(&ck_conv_info, pixel, channels);
1318                     pixel = make_argb_color(&ck_conv_info, channels);
1319                     if (pixel == colorkey)
1320                         val &= ~conv_info.destmask[0];
1321                 }
1322             }
1323             else
1324             {
1325                 struct vec4 color, tmp;
1326
1327                 format_to_vec4(srcformat, &pixel, &color);
1328                 if (srcformat->to_rgba)
1329                     srcformat->to_rgba(&color, &tmp);
1330                 else
1331                     tmp = color;
1332
1333                 if (ck_format)
1334                 {
1335                     format_from_vec4(ck_format, &tmp, &pixel);
1336                     if (pixel == colorkey)
1337                         tmp.w = 0.0f;
1338                 }
1339
1340                 if (destformat->from_rgba)
1341                     destformat->from_rgba(&tmp, &color);
1342                 else
1343                     color = tmp;
1344
1345                 format_from_vec4(destformat, &color, &val);
1346             }
1347
1348             dword_to_bytes(destptr, val, destformat->bytes_per_pixel);
1349             destptr += destformat->bytes_per_pixel;
1350         }
1351     }
1352 }
1353
1354 /************************************************************
1355  * D3DXLoadSurfaceFromMemory
1356  *
1357  * Loads data from a given memory chunk into a surface,
1358  * applying any of the specified filters.
1359  *
1360  * PARAMS
1361  *   pDestSurface [I] pointer to the surface
1362  *   pDestPalette [I] palette to use
1363  *   pDestRect    [I] to be filled area of the surface
1364  *   pSrcMemory   [I] pointer to the source data
1365  *   SrcFormat    [I] format of the source pixel data
1366  *   SrcPitch     [I] number of bytes in a row
1367  *   pSrcPalette  [I] palette used in the source image
1368  *   pSrcRect     [I] area of the source data to load
1369  *   dwFilter     [I] filter to apply on stretching
1370  *   Colorkey     [I] colorkey
1371  *
1372  * RETURNS
1373  *   Success: D3D_OK, if we successfully load the pixel data into our surface or
1374  *                    if pSrcMemory is NULL but the other parameters are valid
1375  *   Failure: D3DERR_INVALIDCALL, if pDestSurface, SrcPitch or pSrcRect are NULL or
1376  *                                if SrcFormat is an invalid format (other than D3DFMT_UNKNOWN) or
1377  *                                if DestRect is invalid
1378  *            D3DXERR_INVALIDDATA, if we fail to lock pDestSurface
1379  *            E_FAIL, if SrcFormat is D3DFMT_UNKNOWN or the dimensions of pSrcRect are invalid
1380  *
1381  * NOTES
1382  *   pSrcRect specifies the dimensions of the source data;
1383  *   negative values for pSrcRect are allowed as we're only looking at the width and height anyway.
1384  *
1385  */
1386 HRESULT WINAPI D3DXLoadSurfaceFromMemory(IDirect3DSurface9 *dst_surface,
1387         const PALETTEENTRY *dst_palette, const RECT *dst_rect, const void *src_memory,
1388         D3DFORMAT src_format, UINT src_pitch, const PALETTEENTRY *src_palette, const RECT *src_rect,
1389         DWORD filter, D3DCOLOR color_key)
1390 {
1391     CONST PixelFormatDesc *srcformatdesc, *destformatdesc;
1392     D3DSURFACE_DESC surfdesc;
1393     D3DLOCKED_RECT lockrect;
1394     SIZE src_size, dst_size;
1395     HRESULT hr;
1396
1397     TRACE("(%p, %p, %s, %p, %#x, %u, %p, %s %#x, 0x%08x)\n",
1398             dst_surface, dst_palette, wine_dbgstr_rect(dst_rect), src_memory, src_format,
1399             src_pitch, src_palette, wine_dbgstr_rect(src_rect), filter, color_key);
1400
1401     if (!dst_surface || !src_memory || !src_rect)
1402         return D3DERR_INVALIDCALL;
1403     if (src_format == D3DFMT_UNKNOWN
1404             || src_rect->left >= src_rect->right
1405             || src_rect->top >= src_rect->bottom)
1406         return E_FAIL;
1407
1408     if (filter == D3DX_DEFAULT)
1409         filter = D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER;
1410
1411     IDirect3DSurface9_GetDesc(dst_surface, &surfdesc);
1412
1413     src_size.cx = src_rect->right - src_rect->left;
1414     src_size.cy = src_rect->bottom - src_rect->top;
1415     if (!dst_rect)
1416     {
1417         dst_size.cx = surfdesc.Width;
1418         dst_size.cy = surfdesc.Height;
1419     }
1420     else
1421     {
1422         if (dst_rect->left > dst_rect->right || dst_rect->right > surfdesc.Width)
1423             return D3DERR_INVALIDCALL;
1424         if (dst_rect->top > dst_rect->bottom || dst_rect->bottom > surfdesc.Height)
1425             return D3DERR_INVALIDCALL;
1426         if (dst_rect->left < 0 || dst_rect->top < 0)
1427             return D3DERR_INVALIDCALL;
1428         dst_size.cx = dst_rect->right - dst_rect->left;
1429         dst_size.cy = dst_rect->bottom - dst_rect->top;
1430         if (!dst_size.cx || !dst_size.cy)
1431             return D3D_OK;
1432     }
1433
1434     srcformatdesc = get_format_info(src_format);
1435     if (srcformatdesc->type == FORMAT_UNKNOWN)
1436         return E_NOTIMPL;
1437
1438     destformatdesc = get_format_info(surfdesc.Format);
1439     if (destformatdesc->type == FORMAT_UNKNOWN)
1440         return E_NOTIMPL;
1441
1442     if (src_format == surfdesc.Format
1443             && dst_size.cx == src_size.cx
1444             && dst_size.cy == src_size.cy) /* Simple copy. */
1445     {
1446         UINT row_block_count = ((src_size.cx + srcformatdesc->block_width - 1) / srcformatdesc->block_width);
1447         UINT row_count = (src_size.cy + srcformatdesc->block_height - 1) / srcformatdesc->block_height;
1448         const BYTE *src_addr;
1449         BYTE *dst_addr;
1450         UINT row;
1451
1452         if (src_rect->left & (srcformatdesc->block_width - 1)
1453                 || src_rect->top & (srcformatdesc->block_height - 1)
1454                 || (src_rect->right & (srcformatdesc->block_width - 1)
1455                     && src_size.cx != surfdesc.Width)
1456                 || (src_rect->bottom & (srcformatdesc->block_height - 1)
1457                     && src_size.cy != surfdesc.Height))
1458         {
1459             WARN("Source rect %s is misaligned.\n", wine_dbgstr_rect(src_rect));
1460             return D3DXERR_INVALIDDATA;
1461         }
1462
1463         if (FAILED(hr = IDirect3DSurface9_LockRect(dst_surface, &lockrect, dst_rect, 0)))
1464             return D3DXERR_INVALIDDATA;
1465
1466         src_addr = src_memory;
1467         src_addr += (src_rect->top / srcformatdesc->block_height) * src_pitch;
1468         src_addr += (src_rect->left / srcformatdesc->block_width) * srcformatdesc->block_byte_count;
1469         dst_addr = lockrect.pBits;
1470
1471         for (row = 0; row < row_count; ++row)
1472         {
1473             memcpy(dst_addr, src_addr, row_block_count * srcformatdesc->block_byte_count);
1474             src_addr += src_pitch;
1475             dst_addr += lockrect.Pitch;
1476         }
1477
1478         IDirect3DSurface9_UnlockRect(dst_surface);
1479     }
1480     else /* Stretching or format conversion. */
1481     {
1482         if (srcformatdesc->bytes_per_pixel > 4)
1483             return E_NOTIMPL;
1484         if (destformatdesc->bytes_per_pixel > 4)
1485             return E_NOTIMPL;
1486         if (srcformatdesc->block_height != 1 || srcformatdesc->block_width != 1)
1487             return E_NOTIMPL;
1488         if (destformatdesc->block_height != 1 || destformatdesc->block_width != 1)
1489             return E_NOTIMPL;
1490
1491         if (FAILED(hr = IDirect3DSurface9_LockRect(dst_surface, &lockrect, dst_rect, 0)))
1492             return D3DXERR_INVALIDDATA;
1493
1494         if ((filter & 0xf) == D3DX_FILTER_NONE)
1495         {
1496             copy_simple_data(src_memory, src_pitch, src_size, srcformatdesc,
1497                     lockrect.pBits, lockrect.Pitch, dst_size, destformatdesc, color_key);
1498         }
1499         else /* if ((filter & 0xf) == D3DX_FILTER_POINT) */
1500         {
1501             if ((filter & 0xf) != D3DX_FILTER_POINT)
1502                 FIXME("Unhandled filter %#x.\n", filter);
1503
1504             /* Always apply a point filter until D3DX_FILTER_LINEAR,
1505              * D3DX_FILTER_TRIANGLE and D3DX_FILTER_BOX are implemented. */
1506             point_filter_simple_data(src_memory, src_pitch, src_size, srcformatdesc,
1507                     lockrect.pBits, lockrect.Pitch, dst_size, destformatdesc, color_key);
1508         }
1509
1510         IDirect3DSurface9_UnlockRect(dst_surface);
1511     }
1512
1513     return D3D_OK;
1514 }
1515
1516 /************************************************************
1517  * D3DXLoadSurfaceFromSurface
1518  *
1519  * Copies the contents from one surface to another, performing any required
1520  * format conversion, resizing or filtering.
1521  *
1522  * PARAMS
1523  *   pDestSurface [I] pointer to the destination surface
1524  *   pDestPalette [I] palette to use
1525  *   pDestRect    [I] to be filled area of the surface
1526  *   pSrcSurface  [I] pointer to the source surface
1527  *   pSrcPalette  [I] palette used for the source surface
1528  *   pSrcRect     [I] area of the source data to load
1529  *   dwFilter     [I] filter to apply on resizing
1530  *   Colorkey     [I] any ARGB value or 0 to disable color-keying
1531  *
1532  * RETURNS
1533  *   Success: D3D_OK
1534  *   Failure: D3DERR_INVALIDCALL, if pDestSurface or pSrcSurface are NULL
1535  *            D3DXERR_INVALIDDATA, if one of the surfaces is not lockable
1536  *
1537  */
1538 HRESULT WINAPI D3DXLoadSurfaceFromSurface(LPDIRECT3DSURFACE9 pDestSurface,
1539                                           CONST PALETTEENTRY *pDestPalette,
1540                                           CONST RECT *pDestRect,
1541                                           LPDIRECT3DSURFACE9 pSrcSurface,
1542                                           CONST PALETTEENTRY *pSrcPalette,
1543                                           CONST RECT *pSrcRect,
1544                                           DWORD dwFilter,
1545                                           D3DCOLOR Colorkey)
1546 {
1547     RECT rect;
1548     D3DLOCKED_RECT lock;
1549     D3DSURFACE_DESC SrcDesc;
1550     HRESULT hr;
1551
1552     TRACE("(%p, %p, %p, %p, %p, %p, %u, %#x): relay\n", pDestSurface, pDestPalette, pDestRect,
1553         pSrcSurface, pSrcPalette, pSrcRect, dwFilter, Colorkey);
1554
1555     if( !pDestSurface || !pSrcSurface ) return D3DERR_INVALIDCALL;
1556
1557     IDirect3DSurface9_GetDesc(pSrcSurface, &SrcDesc);
1558
1559     if( !pSrcRect ) SetRect(&rect, 0, 0, SrcDesc.Width, SrcDesc.Height);
1560     else rect = *pSrcRect;
1561
1562     hr = IDirect3DSurface9_LockRect(pSrcSurface, &lock, NULL, D3DLOCK_READONLY);
1563     if(FAILED(hr)) return D3DXERR_INVALIDDATA;
1564
1565     hr = D3DXLoadSurfaceFromMemory(pDestSurface, pDestPalette, pDestRect,
1566                                    lock.pBits, SrcDesc.Format, lock.Pitch,
1567                                    pSrcPalette, &rect, dwFilter, Colorkey);
1568
1569     IDirect3DSurface9_UnlockRect(pSrcSurface);
1570     return hr;
1571 }
1572
1573
1574 HRESULT WINAPI D3DXSaveSurfaceToFileA(const char *dst_filename, D3DXIMAGE_FILEFORMAT file_format,
1575         IDirect3DSurface9 *src_surface, const PALETTEENTRY *src_palette, const RECT *src_rect)
1576 {
1577     int len;
1578     WCHAR *filename;
1579     HRESULT hr;
1580
1581     TRACE("(%s, %#x, %p, %p, %s): relay\n",
1582             wine_dbgstr_a(dst_filename), file_format, src_surface, src_palette, wine_dbgstr_rect(src_rect));
1583
1584     if (!dst_filename) return D3DERR_INVALIDCALL;
1585
1586     len = MultiByteToWideChar(CP_ACP, 0, dst_filename, -1, NULL, 0);
1587     filename = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1588     if (!filename) return E_OUTOFMEMORY;
1589     MultiByteToWideChar(CP_ACP, 0, dst_filename, -1, filename, len);
1590
1591     hr = D3DXSaveSurfaceToFileW(filename, file_format, src_surface, src_palette, src_rect);
1592
1593     HeapFree(GetProcessHeap(), 0, filename);
1594     return hr;
1595 }
1596
1597 HRESULT WINAPI D3DXSaveSurfaceToFileW(const WCHAR *dst_filename, D3DXIMAGE_FILEFORMAT file_format,
1598         IDirect3DSurface9 *src_surface, const PALETTEENTRY *src_palette, const RECT *src_rect)
1599 {
1600     IWICImagingFactory *factory;
1601     IWICBitmapEncoder *encoder = NULL;
1602     IWICBitmapFrameEncode *frame = NULL;
1603     IPropertyBag2 *encoder_options = NULL;
1604     IWICStream *stream = NULL;
1605     HRESULT hr;
1606     HRESULT initresult;
1607     const CLSID *encoder_clsid;
1608     const GUID *pixel_format_guid;
1609     WICPixelFormatGUID wic_pixel_format;
1610     D3DFORMAT d3d_pixel_format;
1611     D3DSURFACE_DESC src_surface_desc;
1612     D3DLOCKED_RECT locked_rect;
1613     int width, height;
1614
1615     TRACE("(%s, %#x, %p, %p, %s)\n",
1616         wine_dbgstr_w(dst_filename), file_format, src_surface, src_palette, wine_dbgstr_rect(src_rect));
1617
1618     if (!dst_filename || !src_surface) return D3DERR_INVALIDCALL;
1619
1620     if (src_palette)
1621     {
1622         FIXME("Saving surfaces with palettized pixel formats not implemented yet\n");
1623         return D3DERR_INVALIDCALL;
1624     }
1625
1626     switch (file_format)
1627     {
1628         case D3DXIFF_BMP:
1629             encoder_clsid = &CLSID_WICBmpEncoder;
1630             break;
1631         case D3DXIFF_PNG:
1632             encoder_clsid = &CLSID_WICPngEncoder;
1633             break;
1634         case D3DXIFF_JPG:
1635             encoder_clsid = &CLSID_WICJpegEncoder;
1636             break;
1637         case D3DXIFF_DDS:
1638         case D3DXIFF_DIB:
1639         case D3DXIFF_HDR:
1640         case D3DXIFF_PFM:
1641         case D3DXIFF_TGA:
1642         case D3DXIFF_PPM:
1643             FIXME("File format %#x is not supported yet\n", file_format);
1644             return E_NOTIMPL;
1645         default:
1646             return D3DERR_INVALIDCALL;
1647     }
1648
1649     IDirect3DSurface9_GetDesc(src_surface, &src_surface_desc);
1650     if (src_rect)
1651     {
1652         if (src_rect->left == src_rect->right || src_rect->top == src_rect->bottom)
1653             return D3D_OK;
1654         if (src_rect->left < 0 || src_rect->top < 0)
1655             return D3DERR_INVALIDCALL;
1656         if (src_rect->left > src_rect->right || src_rect->top > src_rect->bottom)
1657             return D3DERR_INVALIDCALL;
1658         if (src_rect->right > src_surface_desc.Width || src_rect->bottom > src_surface_desc.Height)
1659             return D3DERR_INVALIDCALL;
1660
1661         width = src_rect->right - src_rect->left;
1662         height = src_rect->bottom - src_rect->top;
1663     }
1664     else
1665     {
1666         width = src_surface_desc.Width;
1667         height = src_surface_desc.Height;
1668     }
1669
1670     initresult = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
1671
1672     hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER,
1673         &IID_IWICImagingFactory, (void **)&factory);
1674     if (FAILED(hr)) goto cleanup_err;
1675
1676     hr = IWICImagingFactory_CreateStream(factory, &stream);
1677     IWICImagingFactory_Release(factory);
1678     if (FAILED(hr)) goto cleanup_err;
1679
1680     hr = IWICStream_InitializeFromFilename(stream, dst_filename, GENERIC_WRITE);
1681     if (FAILED(hr)) goto cleanup_err;
1682
1683     hr = CoCreateInstance(encoder_clsid, NULL, CLSCTX_INPROC_SERVER,
1684         &IID_IWICBitmapEncoder, (void **)&encoder);
1685     if (FAILED(hr)) goto cleanup_err;
1686
1687     hr = IWICBitmapEncoder_Initialize(encoder, (IStream *)stream, WICBitmapEncoderNoCache);
1688     IStream_Release((IStream *)stream);
1689     stream = NULL;
1690     if (FAILED(hr)) goto cleanup_err;
1691
1692     hr = IWICBitmapEncoder_CreateNewFrame(encoder, &frame, &encoder_options);
1693     if (FAILED(hr)) goto cleanup_err;
1694
1695     hr = IWICBitmapFrameEncode_Initialize(frame, encoder_options);
1696     if (FAILED(hr)) goto cleanup_err;
1697
1698     hr = IWICBitmapFrameEncode_SetSize(frame, width, height);
1699     if (FAILED(hr)) goto cleanup_err;
1700
1701     pixel_format_guid = d3dformat_to_wic_guid(src_surface_desc.Format);
1702     if (!pixel_format_guid)
1703     {
1704         FIXME("Pixel format %#x is not supported yet\n", src_surface_desc.Format);
1705         hr = E_NOTIMPL;
1706         goto cleanup;
1707     }
1708
1709     memcpy(&wic_pixel_format, pixel_format_guid, sizeof(GUID));
1710     hr = IWICBitmapFrameEncode_SetPixelFormat(frame, &wic_pixel_format);
1711     d3d_pixel_format = wic_guid_to_d3dformat(&wic_pixel_format);
1712     if (SUCCEEDED(hr) && d3d_pixel_format != D3DFMT_UNKNOWN)
1713     {
1714         TRACE("Using pixel format %s %#x\n", debugstr_guid(&wic_pixel_format), d3d_pixel_format);
1715
1716         if (src_surface_desc.Format == d3d_pixel_format) /* Simple copy */
1717         {
1718             hr = IDirect3DSurface9_LockRect(src_surface, &locked_rect, src_rect, D3DLOCK_READONLY);
1719             if (SUCCEEDED(hr))
1720             {
1721                 IWICBitmapFrameEncode_WritePixels(frame, height,
1722                     locked_rect.Pitch, height * locked_rect.Pitch, locked_rect.pBits);
1723                 IDirect3DSurface9_UnlockRect(src_surface);
1724             }
1725         }
1726         else /* Pixel format conversion */
1727         {
1728             const PixelFormatDesc *src_format_desc, *dst_format_desc;
1729             SIZE size;
1730             DWORD dst_pitch;
1731             void *dst_data;
1732
1733             src_format_desc = get_format_info(src_surface_desc.Format);
1734             dst_format_desc = get_format_info(d3d_pixel_format);
1735             if (src_format_desc->format == D3DFMT_UNKNOWN || dst_format_desc->format == D3DFMT_UNKNOWN)
1736             {
1737                 FIXME("Unsupported pixel format conversion %#x -> %#x\n",
1738                     src_surface_desc.Format, d3d_pixel_format);
1739                 hr = E_NOTIMPL;
1740                 goto cleanup;
1741             }
1742
1743             if (src_format_desc->bytes_per_pixel > 4
1744                 || dst_format_desc->bytes_per_pixel > 4
1745                 || src_format_desc->block_height != 1 || src_format_desc->block_width != 1
1746                 || dst_format_desc->block_height != 1 || dst_format_desc->block_width != 1)
1747             {
1748                 hr = E_NOTIMPL;
1749                 goto cleanup;
1750             }
1751
1752             size.cx = width;
1753             size.cy = height;
1754             dst_pitch = width * dst_format_desc->bytes_per_pixel;
1755             dst_data = HeapAlloc(GetProcessHeap(), 0, dst_pitch * height);
1756             if (!dst_data)
1757             {
1758                 hr = E_OUTOFMEMORY;
1759                 goto cleanup;
1760             }
1761
1762             hr = IDirect3DSurface9_LockRect(src_surface, &locked_rect, src_rect, D3DLOCK_READONLY);
1763             if (SUCCEEDED(hr))
1764             {
1765                 copy_simple_data(locked_rect.pBits, locked_rect.Pitch, size, src_format_desc,
1766                     dst_data, dst_pitch, size, dst_format_desc, 0);
1767                 IDirect3DSurface9_UnlockRect(src_surface);
1768             }
1769
1770             IWICBitmapFrameEncode_WritePixels(frame, height, dst_pitch, dst_pitch * height, dst_data);
1771             HeapFree(GetProcessHeap(), 0, dst_data);
1772         }
1773
1774         hr = IWICBitmapFrameEncode_Commit(frame);
1775         if (SUCCEEDED(hr)) hr = IWICBitmapEncoder_Commit(encoder);
1776     }
1777     else WARN("Unsupported pixel format %#x\n", src_surface_desc.Format);
1778
1779 cleanup_err:
1780     if (FAILED(hr)) hr = D3DERR_INVALIDCALL;
1781
1782 cleanup:
1783     if (stream) IStream_Release((IStream *)stream);
1784
1785     if (frame) IWICBitmapFrameEncode_Release(frame);
1786     if (encoder_options) IPropertyBag2_Release(encoder_options);
1787
1788     if (encoder) IWICBitmapEncoder_Release(encoder);
1789
1790     if (SUCCEEDED(initresult)) CoUninitialize();
1791
1792     return hr;
1793 }