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