1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %                            DDDD   DDDD   SSSSS                              %
7 %                            D   D  D   D  SS                                 %
8 %                            D   D  D   D   SSS                               %
9 %                            D   D  D   D     SS                              %
10 %                            DDDD   DDDD   SSSSS                              %
11 %                                                                             %
12 %                                                                             %
13 %           Read/Write Microsoft Direct Draw Surface Image Format             %
14 %                                                                             %
15 %                              Software Design                                %
16 %                             Bianca van Schaik                               %
17 %                                March 2008                                   %
18 %                               Dirk Lemstra                                  %
19 %                              September 2013                                 %
20 %                                                                             %
21 %                                                                             %
22 %  Copyright 1999-2021 ImageMagick Studio LLC, a non-profit organization      %
23 %  dedicated to making software imaging solutions freely available.           %
24 %                                                                             %
25 %  You may not use this file except in compliance with the License.  You may  %
26 %  obtain a copy of the License at                                            %
27 %                                                                             %
28 %    https://imagemagick.org/script/license.php                               %
29 %                                                                             %
30 %  Unless required by applicable law or agreed to in writing, software        %
31 %  distributed under the License is distributed on an "AS IS" BASIS,          %
32 %  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
33 %  See the License for the specific language governing permissions and        %
34 %  limitations under the License.                                             %
35 %                                                                             %
36 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
37 %
38 %
39 */
40 
41 /*
42   Include declarations.
43 */
44 #include "magick/studio.h"
45 #include "magick/attribute.h"
46 #include "magick/blob.h"
47 #include "magick/blob-private.h"
48 #include "magick/cache.h"
49 #include "magick/colorspace.h"
50 #include "magick/colorspace-private.h"
51 #include "magick/exception.h"
52 #include "magick/exception-private.h"
53 #include "magick/image.h"
54 #include "magick/image-private.h"
55 #include "magick/list.h"
56 #include "magick/log.h"
57 #include "magick/magick.h"
58 #include "magick/memory_.h"
59 #include "magick/monitor.h"
60 #include "magick/monitor-private.h"
61 #include "magick/option.h"
62 #include "magick/pixel-accessor.h"
63 #include "magick/profile.h"
64 #include "magick/quantum.h"
65 #include "magick/quantum-private.h"
66 #include "magick/resource_.h"
67 #include "magick/static.h"
68 #include "magick/string_.h"
69 #include "magick/string-private.h"
70 #include "magick/module.h"
71 #include "magick/transform.h"
72 
73 /*
74   Definitions
75 */
76 #define DDSD_CAPS         0x00000001
77 #define DDSD_HEIGHT       0x00000002
78 #define DDSD_WIDTH        0x00000004
79 #define DDSD_PITCH        0x00000008
80 #define DDSD_PIXELFORMAT  0x00001000
81 #define DDSD_MIPMAPCOUNT  0x00020000
82 #define DDSD_LINEARSIZE   0x00080000
83 #define DDSD_DEPTH        0x00800000
84 
85 #define DDPF_ALPHAPIXELS  0x00000001
86 #define DDPF_FOURCC       0x00000004
87 #define DDPF_RGB          0x00000040
88 #define DDPF_LUMINANCE    0x00020000
89 
90 #define FOURCC_DXT1       0x31545844
91 #define FOURCC_DXT3       0x33545844
92 #define FOURCC_DXT5       0x35545844
93 
94 #define DDSCAPS_COMPLEX   0x00000008
95 #define DDSCAPS_TEXTURE   0x00001000
96 #define DDSCAPS_MIPMAP    0x00400000
97 
98 #define DDSCAPS2_CUBEMAP  0x00000200
99 #define DDSCAPS2_CUBEMAP_POSITIVEX  0x00000400
100 #define DDSCAPS2_CUBEMAP_NEGATIVEX  0x00000800
101 #define DDSCAPS2_CUBEMAP_POSITIVEY  0x00001000
102 #define DDSCAPS2_CUBEMAP_NEGATIVEY  0x00002000
103 #define DDSCAPS2_CUBEMAP_POSITIVEZ  0x00004000
104 #define DDSCAPS2_CUBEMAP_NEGATIVEZ  0x00008000
105 #define DDSCAPS2_VOLUME   0x00200000
106 
107 #ifndef SIZE_MAX
108 #define SIZE_MAX ((size_t) -1)
109 #endif
110 
111 /*
112   Structure declarations.
113 */
114 typedef struct _DDSPixelFormat
115 {
116   size_t
117     flags,
118     fourcc,
119     rgb_bitcount,
120     r_bitmask,
121     g_bitmask,
122     b_bitmask,
123     alpha_bitmask;
124 } DDSPixelFormat;
125 
126 typedef struct _DDSInfo
127 {
128   size_t
129     flags,
130     height,
131     width,
132     pitchOrLinearSize,
133     depth,
134     mipmapcount,
135     ddscaps1,
136     ddscaps2;
137 
138   DDSPixelFormat
139     pixelformat;
140 } DDSInfo;
141 
142 typedef struct _DDSColors
143 {
144   unsigned char
145     r[4],
146     g[4],
147     b[4],
148     a[4];
149 } DDSColors;
150 
151 typedef struct _DDSVector4
152 {
153   float
154     x,
155     y,
156     z,
157     w;
158 } DDSVector4;
159 
160 typedef struct _DDSVector3
161 {
162   float
163     x,
164     y,
165     z;
166 } DDSVector3;
167 
168 typedef struct _DDSSourceBlock
169 {
170   unsigned char
171     start,
172     end,
173     error;
174 } DDSSourceBlock;
175 
176 typedef struct _DDSSingleColourLookup
177 {
178   DDSSourceBlock sources[2];
179 } DDSSingleColourLookup;
180 
181 typedef MagickBooleanType
182   DDSDecoder(Image *, DDSInfo *, ExceptionInfo *);
183 
184 static const DDSSingleColourLookup DDSLookup_5_4[] =
185 {
186   { { { 0, 0, 0 }, { 0, 0, 0 } } },
187   { { { 0, 0, 1 }, { 0, 1, 1 } } },
188   { { { 0, 0, 2 }, { 0, 1, 0 } } },
189   { { { 0, 0, 3 }, { 0, 1, 1 } } },
190   { { { 0, 0, 4 }, { 0, 2, 1 } } },
191   { { { 1, 0, 3 }, { 0, 2, 0 } } },
192   { { { 1, 0, 2 }, { 0, 2, 1 } } },
193   { { { 1, 0, 1 }, { 0, 3, 1 } } },
194   { { { 1, 0, 0 }, { 0, 3, 0 } } },
195   { { { 1, 0, 1 }, { 1, 2, 1 } } },
196   { { { 1, 0, 2 }, { 1, 2, 0 } } },
197   { { { 1, 0, 3 }, { 0, 4, 0 } } },
198   { { { 1, 0, 4 }, { 0, 5, 1 } } },
199   { { { 2, 0, 3 }, { 0, 5, 0 } } },
200   { { { 2, 0, 2 }, { 0, 5, 1 } } },
201   { { { 2, 0, 1 }, { 0, 6, 1 } } },
202   { { { 2, 0, 0 }, { 0, 6, 0 } } },
203   { { { 2, 0, 1 }, { 2, 3, 1 } } },
204   { { { 2, 0, 2 }, { 2, 3, 0 } } },
205   { { { 2, 0, 3 }, { 0, 7, 0 } } },
206   { { { 2, 0, 4 }, { 1, 6, 1 } } },
207   { { { 3, 0, 3 }, { 1, 6, 0 } } },
208   { { { 3, 0, 2 }, { 0, 8, 0 } } },
209   { { { 3, 0, 1 }, { 0, 9, 1 } } },
210   { { { 3, 0, 0 }, { 0, 9, 0 } } },
211   { { { 3, 0, 1 }, { 0, 9, 1 } } },
212   { { { 3, 0, 2 }, { 0, 10, 1 } } },
213   { { { 3, 0, 3 }, { 0, 10, 0 } } },
214   { { { 3, 0, 4 }, { 2, 7, 1 } } },
215   { { { 4, 0, 4 }, { 2, 7, 0 } } },
216   { { { 4, 0, 3 }, { 0, 11, 0 } } },
217   { { { 4, 0, 2 }, { 1, 10, 1 } } },
218   { { { 4, 0, 1 }, { 1, 10, 0 } } },
219   { { { 4, 0, 0 }, { 0, 12, 0 } } },
220   { { { 4, 0, 1 }, { 0, 13, 1 } } },
221   { { { 4, 0, 2 }, { 0, 13, 0 } } },
222   { { { 4, 0, 3 }, { 0, 13, 1 } } },
223   { { { 4, 0, 4 }, { 0, 14, 1 } } },
224   { { { 5, 0, 3 }, { 0, 14, 0 } } },
225   { { { 5, 0, 2 }, { 2, 11, 1 } } },
226   { { { 5, 0, 1 }, { 2, 11, 0 } } },
227   { { { 5, 0, 0 }, { 0, 15, 0 } } },
228   { { { 5, 0, 1 }, { 1, 14, 1 } } },
229   { { { 5, 0, 2 }, { 1, 14, 0 } } },
230   { { { 5, 0, 3 }, { 0, 16, 0 } } },
231   { { { 5, 0, 4 }, { 0, 17, 1 } } },
232   { { { 6, 0, 3 }, { 0, 17, 0 } } },
233   { { { 6, 0, 2 }, { 0, 17, 1 } } },
234   { { { 6, 0, 1 }, { 0, 18, 1 } } },
235   { { { 6, 0, 0 }, { 0, 18, 0 } } },
236   { { { 6, 0, 1 }, { 2, 15, 1 } } },
237   { { { 6, 0, 2 }, { 2, 15, 0 } } },
238   { { { 6, 0, 3 }, { 0, 19, 0 } } },
239   { { { 6, 0, 4 }, { 1, 18, 1 } } },
240   { { { 7, 0, 3 }, { 1, 18, 0 } } },
241   { { { 7, 0, 2 }, { 0, 20, 0 } } },
242   { { { 7, 0, 1 }, { 0, 21, 1 } } },
243   { { { 7, 0, 0 }, { 0, 21, 0 } } },
244   { { { 7, 0, 1 }, { 0, 21, 1 } } },
245   { { { 7, 0, 2 }, { 0, 22, 1 } } },
246   { { { 7, 0, 3 }, { 0, 22, 0 } } },
247   { { { 7, 0, 4 }, { 2, 19, 1 } } },
248   { { { 8, 0, 4 }, { 2, 19, 0 } } },
249   { { { 8, 0, 3 }, { 0, 23, 0 } } },
250   { { { 8, 0, 2 }, { 1, 22, 1 } } },
251   { { { 8, 0, 1 }, { 1, 22, 0 } } },
252   { { { 8, 0, 0 }, { 0, 24, 0 } } },
253   { { { 8, 0, 1 }, { 0, 25, 1 } } },
254   { { { 8, 0, 2 }, { 0, 25, 0 } } },
255   { { { 8, 0, 3 }, { 0, 25, 1 } } },
256   { { { 8, 0, 4 }, { 0, 26, 1 } } },
257   { { { 9, 0, 3 }, { 0, 26, 0 } } },
258   { { { 9, 0, 2 }, { 2, 23, 1 } } },
259   { { { 9, 0, 1 }, { 2, 23, 0 } } },
260   { { { 9, 0, 0 }, { 0, 27, 0 } } },
261   { { { 9, 0, 1 }, { 1, 26, 1 } } },
262   { { { 9, 0, 2 }, { 1, 26, 0 } } },
263   { { { 9, 0, 3 }, { 0, 28, 0 } } },
264   { { { 9, 0, 4 }, { 0, 29, 1 } } },
265   { { { 10, 0, 3 }, { 0, 29, 0 } } },
266   { { { 10, 0, 2 }, { 0, 29, 1 } } },
267   { { { 10, 0, 1 }, { 0, 30, 1 } } },
268   { { { 10, 0, 0 }, { 0, 30, 0 } } },
269   { { { 10, 0, 1 }, { 2, 27, 1 } } },
270   { { { 10, 0, 2 }, { 2, 27, 0 } } },
271   { { { 10, 0, 3 }, { 0, 31, 0 } } },
272   { { { 10, 0, 4 }, { 1, 30, 1 } } },
273   { { { 11, 0, 3 }, { 1, 30, 0 } } },
274   { { { 11, 0, 2 }, { 4, 24, 0 } } },
275   { { { 11, 0, 1 }, { 1, 31, 1 } } },
276   { { { 11, 0, 0 }, { 1, 31, 0 } } },
277   { { { 11, 0, 1 }, { 1, 31, 1 } } },
278   { { { 11, 0, 2 }, { 2, 30, 1 } } },
279   { { { 11, 0, 3 }, { 2, 30, 0 } } },
280   { { { 11, 0, 4 }, { 2, 31, 1 } } },
281   { { { 12, 0, 4 }, { 2, 31, 0 } } },
282   { { { 12, 0, 3 }, { 4, 27, 0 } } },
283   { { { 12, 0, 2 }, { 3, 30, 1 } } },
284   { { { 12, 0, 1 }, { 3, 30, 0 } } },
285   { { { 12, 0, 0 }, { 4, 28, 0 } } },
286   { { { 12, 0, 1 }, { 3, 31, 1 } } },
287   { { { 12, 0, 2 }, { 3, 31, 0 } } },
288   { { { 12, 0, 3 }, { 3, 31, 1 } } },
289   { { { 12, 0, 4 }, { 4, 30, 1 } } },
290   { { { 13, 0, 3 }, { 4, 30, 0 } } },
291   { { { 13, 0, 2 }, { 6, 27, 1 } } },
292   { { { 13, 0, 1 }, { 6, 27, 0 } } },
293   { { { 13, 0, 0 }, { 4, 31, 0 } } },
294   { { { 13, 0, 1 }, { 5, 30, 1 } } },
295   { { { 13, 0, 2 }, { 5, 30, 0 } } },
296   { { { 13, 0, 3 }, { 8, 24, 0 } } },
297   { { { 13, 0, 4 }, { 5, 31, 1 } } },
298   { { { 14, 0, 3 }, { 5, 31, 0 } } },
299   { { { 14, 0, 2 }, { 5, 31, 1 } } },
300   { { { 14, 0, 1 }, { 6, 30, 1 } } },
301   { { { 14, 0, 0 }, { 6, 30, 0 } } },
302   { { { 14, 0, 1 }, { 6, 31, 1 } } },
303   { { { 14, 0, 2 }, { 6, 31, 0 } } },
304   { { { 14, 0, 3 }, { 8, 27, 0 } } },
305   { { { 14, 0, 4 }, { 7, 30, 1 } } },
306   { { { 15, 0, 3 }, { 7, 30, 0 } } },
307   { { { 15, 0, 2 }, { 8, 28, 0 } } },
308   { { { 15, 0, 1 }, { 7, 31, 1 } } },
309   { { { 15, 0, 0 }, { 7, 31, 0 } } },
310   { { { 15, 0, 1 }, { 7, 31, 1 } } },
311   { { { 15, 0, 2 }, { 8, 30, 1 } } },
312   { { { 15, 0, 3 }, { 8, 30, 0 } } },
313   { { { 15, 0, 4 }, { 10, 27, 1 } } },
314   { { { 16, 0, 4 }, { 10, 27, 0 } } },
315   { { { 16, 0, 3 }, { 8, 31, 0 } } },
316   { { { 16, 0, 2 }, { 9, 30, 1 } } },
317   { { { 16, 0, 1 }, { 9, 30, 0 } } },
318   { { { 16, 0, 0 }, { 12, 24, 0 } } },
319   { { { 16, 0, 1 }, { 9, 31, 1 } } },
320   { { { 16, 0, 2 }, { 9, 31, 0 } } },
321   { { { 16, 0, 3 }, { 9, 31, 1 } } },
322   { { { 16, 0, 4 }, { 10, 30, 1 } } },
323   { { { 17, 0, 3 }, { 10, 30, 0 } } },
324   { { { 17, 0, 2 }, { 10, 31, 1 } } },
325   { { { 17, 0, 1 }, { 10, 31, 0 } } },
326   { { { 17, 0, 0 }, { 12, 27, 0 } } },
327   { { { 17, 0, 1 }, { 11, 30, 1 } } },
328   { { { 17, 0, 2 }, { 11, 30, 0 } } },
329   { { { 17, 0, 3 }, { 12, 28, 0 } } },
330   { { { 17, 0, 4 }, { 11, 31, 1 } } },
331   { { { 18, 0, 3 }, { 11, 31, 0 } } },
332   { { { 18, 0, 2 }, { 11, 31, 1 } } },
333   { { { 18, 0, 1 }, { 12, 30, 1 } } },
334   { { { 18, 0, 0 }, { 12, 30, 0 } } },
335   { { { 18, 0, 1 }, { 14, 27, 1 } } },
336   { { { 18, 0, 2 }, { 14, 27, 0 } } },
337   { { { 18, 0, 3 }, { 12, 31, 0 } } },
338   { { { 18, 0, 4 }, { 13, 30, 1 } } },
339   { { { 19, 0, 3 }, { 13, 30, 0 } } },
340   { { { 19, 0, 2 }, { 16, 24, 0 } } },
341   { { { 19, 0, 1 }, { 13, 31, 1 } } },
342   { { { 19, 0, 0 }, { 13, 31, 0 } } },
343   { { { 19, 0, 1 }, { 13, 31, 1 } } },
344   { { { 19, 0, 2 }, { 14, 30, 1 } } },
345   { { { 19, 0, 3 }, { 14, 30, 0 } } },
346   { { { 19, 0, 4 }, { 14, 31, 1 } } },
347   { { { 20, 0, 4 }, { 14, 31, 0 } } },
348   { { { 20, 0, 3 }, { 16, 27, 0 } } },
349   { { { 20, 0, 2 }, { 15, 30, 1 } } },
350   { { { 20, 0, 1 }, { 15, 30, 0 } } },
351   { { { 20, 0, 0 }, { 16, 28, 0 } } },
352   { { { 20, 0, 1 }, { 15, 31, 1 } } },
353   { { { 20, 0, 2 }, { 15, 31, 0 } } },
354   { { { 20, 0, 3 }, { 15, 31, 1 } } },
355   { { { 20, 0, 4 }, { 16, 30, 1 } } },
356   { { { 21, 0, 3 }, { 16, 30, 0 } } },
357   { { { 21, 0, 2 }, { 18, 27, 1 } } },
358   { { { 21, 0, 1 }, { 18, 27, 0 } } },
359   { { { 21, 0, 0 }, { 16, 31, 0 } } },
360   { { { 21, 0, 1 }, { 17, 30, 1 } } },
361   { { { 21, 0, 2 }, { 17, 30, 0 } } },
362   { { { 21, 0, 3 }, { 20, 24, 0 } } },
363   { { { 21, 0, 4 }, { 17, 31, 1 } } },
364   { { { 22, 0, 3 }, { 17, 31, 0 } } },
365   { { { 22, 0, 2 }, { 17, 31, 1 } } },
366   { { { 22, 0, 1 }, { 18, 30, 1 } } },
367   { { { 22, 0, 0 }, { 18, 30, 0 } } },
368   { { { 22, 0, 1 }, { 18, 31, 1 } } },
369   { { { 22, 0, 2 }, { 18, 31, 0 } } },
370   { { { 22, 0, 3 }, { 20, 27, 0 } } },
371   { { { 22, 0, 4 }, { 19, 30, 1 } } },
372   { { { 23, 0, 3 }, { 19, 30, 0 } } },
373   { { { 23, 0, 2 }, { 20, 28, 0 } } },
374   { { { 23, 0, 1 }, { 19, 31, 1 } } },
375   { { { 23, 0, 0 }, { 19, 31, 0 } } },
376   { { { 23, 0, 1 }, { 19, 31, 1 } } },
377   { { { 23, 0, 2 }, { 20, 30, 1 } } },
378   { { { 23, 0, 3 }, { 20, 30, 0 } } },
379   { { { 23, 0, 4 }, { 22, 27, 1 } } },
380   { { { 24, 0, 4 }, { 22, 27, 0 } } },
381   { { { 24, 0, 3 }, { 20, 31, 0 } } },
382   { { { 24, 0, 2 }, { 21, 30, 1 } } },
383   { { { 24, 0, 1 }, { 21, 30, 0 } } },
384   { { { 24, 0, 0 }, { 24, 24, 0 } } },
385   { { { 24, 0, 1 }, { 21, 31, 1 } } },
386   { { { 24, 0, 2 }, { 21, 31, 0 } } },
387   { { { 24, 0, 3 }, { 21, 31, 1 } } },
388   { { { 24, 0, 4 }, { 22, 30, 1 } } },
389   { { { 25, 0, 3 }, { 22, 30, 0 } } },
390   { { { 25, 0, 2 }, { 22, 31, 1 } } },
391   { { { 25, 0, 1 }, { 22, 31, 0 } } },
392   { { { 25, 0, 0 }, { 24, 27, 0 } } },
393   { { { 25, 0, 1 }, { 23, 30, 1 } } },
394   { { { 25, 0, 2 }, { 23, 30, 0 } } },
395   { { { 25, 0, 3 }, { 24, 28, 0 } } },
396   { { { 25, 0, 4 }, { 23, 31, 1 } } },
397   { { { 26, 0, 3 }, { 23, 31, 0 } } },
398   { { { 26, 0, 2 }, { 23, 31, 1 } } },
399   { { { 26, 0, 1 }, { 24, 30, 1 } } },
400   { { { 26, 0, 0 }, { 24, 30, 0 } } },
401   { { { 26, 0, 1 }, { 26, 27, 1 } } },
402   { { { 26, 0, 2 }, { 26, 27, 0 } } },
403   { { { 26, 0, 3 }, { 24, 31, 0 } } },
404   { { { 26, 0, 4 }, { 25, 30, 1 } } },
405   { { { 27, 0, 3 }, { 25, 30, 0 } } },
406   { { { 27, 0, 2 }, { 28, 24, 0 } } },
407   { { { 27, 0, 1 }, { 25, 31, 1 } } },
408   { { { 27, 0, 0 }, { 25, 31, 0 } } },
409   { { { 27, 0, 1 }, { 25, 31, 1 } } },
410   { { { 27, 0, 2 }, { 26, 30, 1 } } },
411   { { { 27, 0, 3 }, { 26, 30, 0 } } },
412   { { { 27, 0, 4 }, { 26, 31, 1 } } },
413   { { { 28, 0, 4 }, { 26, 31, 0 } } },
414   { { { 28, 0, 3 }, { 28, 27, 0 } } },
415   { { { 28, 0, 2 }, { 27, 30, 1 } } },
416   { { { 28, 0, 1 }, { 27, 30, 0 } } },
417   { { { 28, 0, 0 }, { 28, 28, 0 } } },
418   { { { 28, 0, 1 }, { 27, 31, 1 } } },
419   { { { 28, 0, 2 }, { 27, 31, 0 } } },
420   { { { 28, 0, 3 }, { 27, 31, 1 } } },
421   { { { 28, 0, 4 }, { 28, 30, 1 } } },
422   { { { 29, 0, 3 }, { 28, 30, 0 } } },
423   { { { 29, 0, 2 }, { 30, 27, 1 } } },
424   { { { 29, 0, 1 }, { 30, 27, 0 } } },
425   { { { 29, 0, 0 }, { 28, 31, 0 } } },
426   { { { 29, 0, 1 }, { 29, 30, 1 } } },
427   { { { 29, 0, 2 }, { 29, 30, 0 } } },
428   { { { 29, 0, 3 }, { 29, 30, 1 } } },
429   { { { 29, 0, 4 }, { 29, 31, 1 } } },
430   { { { 30, 0, 3 }, { 29, 31, 0 } } },
431   { { { 30, 0, 2 }, { 29, 31, 1 } } },
432   { { { 30, 0, 1 }, { 30, 30, 1 } } },
433   { { { 30, 0, 0 }, { 30, 30, 0 } } },
434   { { { 30, 0, 1 }, { 30, 31, 1 } } },
435   { { { 30, 0, 2 }, { 30, 31, 0 } } },
436   { { { 30, 0, 3 }, { 30, 31, 1 } } },
437   { { { 30, 0, 4 }, { 31, 30, 1 } } },
438   { { { 31, 0, 3 }, { 31, 30, 0 } } },
439   { { { 31, 0, 2 }, { 31, 30, 1 } } },
440   { { { 31, 0, 1 }, { 31, 31, 1 } } },
441   { { { 31, 0, 0 }, { 31, 31, 0 } } }
442 };
443 
444 static const DDSSingleColourLookup DDSLookup_6_4[] =
445 {
446   { { { 0, 0, 0 }, { 0, 0, 0 } } },
447   { { { 0, 0, 1 }, { 0, 1, 0 } } },
448   { { { 0, 0, 2 }, { 0, 2, 0 } } },
449   { { { 1, 0, 1 }, { 0, 3, 1 } } },
450   { { { 1, 0, 0 }, { 0, 3, 0 } } },
451   { { { 1, 0, 1 }, { 0, 4, 0 } } },
452   { { { 1, 0, 2 }, { 0, 5, 0 } } },
453   { { { 2, 0, 1 }, { 0, 6, 1 } } },
454   { { { 2, 0, 0 }, { 0, 6, 0 } } },
455   { { { 2, 0, 1 }, { 0, 7, 0 } } },
456   { { { 2, 0, 2 }, { 0, 8, 0 } } },
457   { { { 3, 0, 1 }, { 0, 9, 1 } } },
458   { { { 3, 0, 0 }, { 0, 9, 0 } } },
459   { { { 3, 0, 1 }, { 0, 10, 0 } } },
460   { { { 3, 0, 2 }, { 0, 11, 0 } } },
461   { { { 4, 0, 1 }, { 0, 12, 1 } } },
462   { { { 4, 0, 0 }, { 0, 12, 0 } } },
463   { { { 4, 0, 1 }, { 0, 13, 0 } } },
464   { { { 4, 0, 2 }, { 0, 14, 0 } } },
465   { { { 5, 0, 1 }, { 0, 15, 1 } } },
466   { { { 5, 0, 0 }, { 0, 15, 0 } } },
467   { { { 5, 0, 1 }, { 0, 16, 0 } } },
468   { { { 5, 0, 2 }, { 1, 15, 0 } } },
469   { { { 6, 0, 1 }, { 0, 17, 0 } } },
470   { { { 6, 0, 0 }, { 0, 18, 0 } } },
471   { { { 6, 0, 1 }, { 0, 19, 0 } } },
472   { { { 6, 0, 2 }, { 3, 14, 0 } } },
473   { { { 7, 0, 1 }, { 0, 20, 0 } } },
474   { { { 7, 0, 0 }, { 0, 21, 0 } } },
475   { { { 7, 0, 1 }, { 0, 22, 0 } } },
476   { { { 7, 0, 2 }, { 4, 15, 0 } } },
477   { { { 8, 0, 1 }, { 0, 23, 0 } } },
478   { { { 8, 0, 0 }, { 0, 24, 0 } } },
479   { { { 8, 0, 1 }, { 0, 25, 0 } } },
480   { { { 8, 0, 2 }, { 6, 14, 0 } } },
481   { { { 9, 0, 1 }, { 0, 26, 0 } } },
482   { { { 9, 0, 0 }, { 0, 27, 0 } } },
483   { { { 9, 0, 1 }, { 0, 28, 0 } } },
484   { { { 9, 0, 2 }, { 7, 15, 0 } } },
485   { { { 10, 0, 1 }, { 0, 29, 0 } } },
486   { { { 10, 0, 0 }, { 0, 30, 0 } } },
487   { { { 10, 0, 1 }, { 0, 31, 0 } } },
488   { { { 10, 0, 2 }, { 9, 14, 0 } } },
489   { { { 11, 0, 1 }, { 0, 32, 0 } } },
490   { { { 11, 0, 0 }, { 0, 33, 0 } } },
491   { { { 11, 0, 1 }, { 2, 30, 0 } } },
492   { { { 11, 0, 2 }, { 0, 34, 0 } } },
493   { { { 12, 0, 1 }, { 0, 35, 0 } } },
494   { { { 12, 0, 0 }, { 0, 36, 0 } } },
495   { { { 12, 0, 1 }, { 3, 31, 0 } } },
496   { { { 12, 0, 2 }, { 0, 37, 0 } } },
497   { { { 13, 0, 1 }, { 0, 38, 0 } } },
498   { { { 13, 0, 0 }, { 0, 39, 0 } } },
499   { { { 13, 0, 1 }, { 5, 30, 0 } } },
500   { { { 13, 0, 2 }, { 0, 40, 0 } } },
501   { { { 14, 0, 1 }, { 0, 41, 0 } } },
502   { { { 14, 0, 0 }, { 0, 42, 0 } } },
503   { { { 14, 0, 1 }, { 6, 31, 0 } } },
504   { { { 14, 0, 2 }, { 0, 43, 0 } } },
505   { { { 15, 0, 1 }, { 0, 44, 0 } } },
506   { { { 15, 0, 0 }, { 0, 45, 0 } } },
507   { { { 15, 0, 1 }, { 8, 30, 0 } } },
508   { { { 15, 0, 2 }, { 0, 46, 0 } } },
509   { { { 16, 0, 2 }, { 0, 47, 0 } } },
510   { { { 16, 0, 1 }, { 1, 46, 0 } } },
511   { { { 16, 0, 0 }, { 0, 48, 0 } } },
512   { { { 16, 0, 1 }, { 0, 49, 0 } } },
513   { { { 16, 0, 2 }, { 0, 50, 0 } } },
514   { { { 17, 0, 1 }, { 2, 47, 0 } } },
515   { { { 17, 0, 0 }, { 0, 51, 0 } } },
516   { { { 17, 0, 1 }, { 0, 52, 0 } } },
517   { { { 17, 0, 2 }, { 0, 53, 0 } } },
518   { { { 18, 0, 1 }, { 4, 46, 0 } } },
519   { { { 18, 0, 0 }, { 0, 54, 0 } } },
520   { { { 18, 0, 1 }, { 0, 55, 0 } } },
521   { { { 18, 0, 2 }, { 0, 56, 0 } } },
522   { { { 19, 0, 1 }, { 5, 47, 0 } } },
523   { { { 19, 0, 0 }, { 0, 57, 0 } } },
524   { { { 19, 0, 1 }, { 0, 58, 0 } } },
525   { { { 19, 0, 2 }, { 0, 59, 0 } } },
526   { { { 20, 0, 1 }, { 7, 46, 0 } } },
527   { { { 20, 0, 0 }, { 0, 60, 0 } } },
528   { { { 20, 0, 1 }, { 0, 61, 0 } } },
529   { { { 20, 0, 2 }, { 0, 62, 0 } } },
530   { { { 21, 0, 1 }, { 8, 47, 0 } } },
531   { { { 21, 0, 0 }, { 0, 63, 0 } } },
532   { { { 21, 0, 1 }, { 1, 62, 0 } } },
533   { { { 21, 0, 2 }, { 1, 63, 0 } } },
534   { { { 22, 0, 1 }, { 10, 46, 0 } } },
535   { { { 22, 0, 0 }, { 2, 62, 0 } } },
536   { { { 22, 0, 1 }, { 2, 63, 0 } } },
537   { { { 22, 0, 2 }, { 3, 62, 0 } } },
538   { { { 23, 0, 1 }, { 11, 47, 0 } } },
539   { { { 23, 0, 0 }, { 3, 63, 0 } } },
540   { { { 23, 0, 1 }, { 4, 62, 0 } } },
541   { { { 23, 0, 2 }, { 4, 63, 0 } } },
542   { { { 24, 0, 1 }, { 13, 46, 0 } } },
543   { { { 24, 0, 0 }, { 5, 62, 0 } } },
544   { { { 24, 0, 1 }, { 5, 63, 0 } } },
545   { { { 24, 0, 2 }, { 6, 62, 0 } } },
546   { { { 25, 0, 1 }, { 14, 47, 0 } } },
547   { { { 25, 0, 0 }, { 6, 63, 0 } } },
548   { { { 25, 0, 1 }, { 7, 62, 0 } } },
549   { { { 25, 0, 2 }, { 7, 63, 0 } } },
550   { { { 26, 0, 1 }, { 16, 45, 0 } } },
551   { { { 26, 0, 0 }, { 8, 62, 0 } } },
552   { { { 26, 0, 1 }, { 8, 63, 0 } } },
553   { { { 26, 0, 2 }, { 9, 62, 0 } } },
554   { { { 27, 0, 1 }, { 16, 48, 0 } } },
555   { { { 27, 0, 0 }, { 9, 63, 0 } } },
556   { { { 27, 0, 1 }, { 10, 62, 0 } } },
557   { { { 27, 0, 2 }, { 10, 63, 0 } } },
558   { { { 28, 0, 1 }, { 16, 51, 0 } } },
559   { { { 28, 0, 0 }, { 11, 62, 0 } } },
560   { { { 28, 0, 1 }, { 11, 63, 0 } } },
561   { { { 28, 0, 2 }, { 12, 62, 0 } } },
562   { { { 29, 0, 1 }, { 16, 54, 0 } } },
563   { { { 29, 0, 0 }, { 12, 63, 0 } } },
564   { { { 29, 0, 1 }, { 13, 62, 0 } } },
565   { { { 29, 0, 2 }, { 13, 63, 0 } } },
566   { { { 30, 0, 1 }, { 16, 57, 0 } } },
567   { { { 30, 0, 0 }, { 14, 62, 0 } } },
568   { { { 30, 0, 1 }, { 14, 63, 0 } } },
569   { { { 30, 0, 2 }, { 15, 62, 0 } } },
570   { { { 31, 0, 1 }, { 16, 60, 0 } } },
571   { { { 31, 0, 0 }, { 15, 63, 0 } } },
572   { { { 31, 0, 1 }, { 24, 46, 0 } } },
573   { { { 31, 0, 2 }, { 16, 62, 0 } } },
574   { { { 32, 0, 2 }, { 16, 63, 0 } } },
575   { { { 32, 0, 1 }, { 17, 62, 0 } } },
576   { { { 32, 0, 0 }, { 25, 47, 0 } } },
577   { { { 32, 0, 1 }, { 17, 63, 0 } } },
578   { { { 32, 0, 2 }, { 18, 62, 0 } } },
579   { { { 33, 0, 1 }, { 18, 63, 0 } } },
580   { { { 33, 0, 0 }, { 27, 46, 0 } } },
581   { { { 33, 0, 1 }, { 19, 62, 0 } } },
582   { { { 33, 0, 2 }, { 19, 63, 0 } } },
583   { { { 34, 0, 1 }, { 20, 62, 0 } } },
584   { { { 34, 0, 0 }, { 28, 47, 0 } } },
585   { { { 34, 0, 1 }, { 20, 63, 0 } } },
586   { { { 34, 0, 2 }, { 21, 62, 0 } } },
587   { { { 35, 0, 1 }, { 21, 63, 0 } } },
588   { { { 35, 0, 0 }, { 30, 46, 0 } } },
589   { { { 35, 0, 1 }, { 22, 62, 0 } } },
590   { { { 35, 0, 2 }, { 22, 63, 0 } } },
591   { { { 36, 0, 1 }, { 23, 62, 0 } } },
592   { { { 36, 0, 0 }, { 31, 47, 0 } } },
593   { { { 36, 0, 1 }, { 23, 63, 0 } } },
594   { { { 36, 0, 2 }, { 24, 62, 0 } } },
595   { { { 37, 0, 1 }, { 24, 63, 0 } } },
596   { { { 37, 0, 0 }, { 32, 47, 0 } } },
597   { { { 37, 0, 1 }, { 25, 62, 0 } } },
598   { { { 37, 0, 2 }, { 25, 63, 0 } } },
599   { { { 38, 0, 1 }, { 26, 62, 0 } } },
600   { { { 38, 0, 0 }, { 32, 50, 0 } } },
601   { { { 38, 0, 1 }, { 26, 63, 0 } } },
602   { { { 38, 0, 2 }, { 27, 62, 0 } } },
603   { { { 39, 0, 1 }, { 27, 63, 0 } } },
604   { { { 39, 0, 0 }, { 32, 53, 0 } } },
605   { { { 39, 0, 1 }, { 28, 62, 0 } } },
606   { { { 39, 0, 2 }, { 28, 63, 0 } } },
607   { { { 40, 0, 1 }, { 29, 62, 0 } } },
608   { { { 40, 0, 0 }, { 32, 56, 0 } } },
609   { { { 40, 0, 1 }, { 29, 63, 0 } } },
610   { { { 40, 0, 2 }, { 30, 62, 0 } } },
611   { { { 41, 0, 1 }, { 30, 63, 0 } } },
612   { { { 41, 0, 0 }, { 32, 59, 0 } } },
613   { { { 41, 0, 1 }, { 31, 62, 0 } } },
614   { { { 41, 0, 2 }, { 31, 63, 0 } } },
615   { { { 42, 0, 1 }, { 32, 61, 0 } } },
616   { { { 42, 0, 0 }, { 32, 62, 0 } } },
617   { { { 42, 0, 1 }, { 32, 63, 0 } } },
618   { { { 42, 0, 2 }, { 41, 46, 0 } } },
619   { { { 43, 0, 1 }, { 33, 62, 0 } } },
620   { { { 43, 0, 0 }, { 33, 63, 0 } } },
621   { { { 43, 0, 1 }, { 34, 62, 0 } } },
622   { { { 43, 0, 2 }, { 42, 47, 0 } } },
623   { { { 44, 0, 1 }, { 34, 63, 0 } } },
624   { { { 44, 0, 0 }, { 35, 62, 0 } } },
625   { { { 44, 0, 1 }, { 35, 63, 0 } } },
626   { { { 44, 0, 2 }, { 44, 46, 0 } } },
627   { { { 45, 0, 1 }, { 36, 62, 0 } } },
628   { { { 45, 0, 0 }, { 36, 63, 0 } } },
629   { { { 45, 0, 1 }, { 37, 62, 0 } } },
630   { { { 45, 0, 2 }, { 45, 47, 0 } } },
631   { { { 46, 0, 1 }, { 37, 63, 0 } } },
632   { { { 46, 0, 0 }, { 38, 62, 0 } } },
633   { { { 46, 0, 1 }, { 38, 63, 0 } } },
634   { { { 46, 0, 2 }, { 47, 46, 0 } } },
635   { { { 47, 0, 1 }, { 39, 62, 0 } } },
636   { { { 47, 0, 0 }, { 39, 63, 0 } } },
637   { { { 47, 0, 1 }, { 40, 62, 0 } } },
638   { { { 47, 0, 2 }, { 48, 46, 0 } } },
639   { { { 48, 0, 2 }, { 40, 63, 0 } } },
640   { { { 48, 0, 1 }, { 41, 62, 0 } } },
641   { { { 48, 0, 0 }, { 41, 63, 0 } } },
642   { { { 48, 0, 1 }, { 48, 49, 0 } } },
643   { { { 48, 0, 2 }, { 42, 62, 0 } } },
644   { { { 49, 0, 1 }, { 42, 63, 0 } } },
645   { { { 49, 0, 0 }, { 43, 62, 0 } } },
646   { { { 49, 0, 1 }, { 48, 52, 0 } } },
647   { { { 49, 0, 2 }, { 43, 63, 0 } } },
648   { { { 50, 0, 1 }, { 44, 62, 0 } } },
649   { { { 50, 0, 0 }, { 44, 63, 0 } } },
650   { { { 50, 0, 1 }, { 48, 55, 0 } } },
651   { { { 50, 0, 2 }, { 45, 62, 0 } } },
652   { { { 51, 0, 1 }, { 45, 63, 0 } } },
653   { { { 51, 0, 0 }, { 46, 62, 0 } } },
654   { { { 51, 0, 1 }, { 48, 58, 0 } } },
655   { { { 51, 0, 2 }, { 46, 63, 0 } } },
656   { { { 52, 0, 1 }, { 47, 62, 0 } } },
657   { { { 52, 0, 0 }, { 47, 63, 0 } } },
658   { { { 52, 0, 1 }, { 48, 61, 0 } } },
659   { { { 52, 0, 2 }, { 48, 62, 0 } } },
660   { { { 53, 0, 1 }, { 56, 47, 0 } } },
661   { { { 53, 0, 0 }, { 48, 63, 0 } } },
662   { { { 53, 0, 1 }, { 49, 62, 0 } } },
663   { { { 53, 0, 2 }, { 49, 63, 0 } } },
664   { { { 54, 0, 1 }, { 58, 46, 0 } } },
665   { { { 54, 0, 0 }, { 50, 62, 0 } } },
666   { { { 54, 0, 1 }, { 50, 63, 0 } } },
667   { { { 54, 0, 2 }, { 51, 62, 0 } } },
668   { { { 55, 0, 1 }, { 59, 47, 0 } } },
669   { { { 55, 0, 0 }, { 51, 63, 0 } } },
670   { { { 55, 0, 1 }, { 52, 62, 0 } } },
671   { { { 55, 0, 2 }, { 52, 63, 0 } } },
672   { { { 56, 0, 1 }, { 61, 46, 0 } } },
673   { { { 56, 0, 0 }, { 53, 62, 0 } } },
674   { { { 56, 0, 1 }, { 53, 63, 0 } } },
675   { { { 56, 0, 2 }, { 54, 62, 0 } } },
676   { { { 57, 0, 1 }, { 62, 47, 0 } } },
677   { { { 57, 0, 0 }, { 54, 63, 0 } } },
678   { { { 57, 0, 1 }, { 55, 62, 0 } } },
679   { { { 57, 0, 2 }, { 55, 63, 0 } } },
680   { { { 58, 0, 1 }, { 56, 62, 1 } } },
681   { { { 58, 0, 0 }, { 56, 62, 0 } } },
682   { { { 58, 0, 1 }, { 56, 63, 0 } } },
683   { { { 58, 0, 2 }, { 57, 62, 0 } } },
684   { { { 59, 0, 1 }, { 57, 63, 1 } } },
685   { { { 59, 0, 0 }, { 57, 63, 0 } } },
686   { { { 59, 0, 1 }, { 58, 62, 0 } } },
687   { { { 59, 0, 2 }, { 58, 63, 0 } } },
688   { { { 60, 0, 1 }, { 59, 62, 1 } } },
689   { { { 60, 0, 0 }, { 59, 62, 0 } } },
690   { { { 60, 0, 1 }, { 59, 63, 0 } } },
691   { { { 60, 0, 2 }, { 60, 62, 0 } } },
692   { { { 61, 0, 1 }, { 60, 63, 1 } } },
693   { { { 61, 0, 0 }, { 60, 63, 0 } } },
694   { { { 61, 0, 1 }, { 61, 62, 0 } } },
695   { { { 61, 0, 2 }, { 61, 63, 0 } } },
696   { { { 62, 0, 1 }, { 62, 62, 1 } } },
697   { { { 62, 0, 0 }, { 62, 62, 0 } } },
698   { { { 62, 0, 1 }, { 62, 63, 0 } } },
699   { { { 62, 0, 2 }, { 63, 62, 0 } } },
700   { { { 63, 0, 1 }, { 63, 63, 1 } } },
701   { { { 63, 0, 0 }, { 63, 63, 0 } } }
702 };
703 
704 static const DDSSingleColourLookup*
705   DDS_LOOKUP[] =
706 {
707   DDSLookup_5_4,
708   DDSLookup_6_4,
709   DDSLookup_5_4
710 };
711 
712 /*
713   Macros
714 */
715 #define C565_r(x) (((x) & 0xF800) >> 11)
716 #define C565_g(x) (((x) & 0x07E0) >> 5)
717 #define C565_b(x)  ((x) & 0x001F)
718 
719 #define C565_red(x)   ( (C565_r(x) << 3 | C565_r(x) >> 2))
720 #define C565_green(x) ( (C565_g(x) << 2 | C565_g(x) >> 4))
721 #define C565_blue(x)  ( (C565_b(x) << 3 | C565_b(x) >> 2))
722 
723 #define DIV2(x)  ((x) > 1 ? ((x) >> 1) : 1)
724 
725 #define FixRange(min, max, steps) \
726 if (min > max) \
727   min = max; \
728 if ((ssize_t) max - min < steps) \
729   max = MagickMin(min + steps, 255); \
730 if ((ssize_t) max - min < steps) \
731   min = MagickMax(0, (ssize_t) max - steps)
732 
733 #define Dot(left, right) (left.x*right.x) + (left.y*right.y) + (left.z*right.z)
734 
735 #define VectorInit(vector, value) vector.x = vector.y = vector.z = vector.w \
736   = value
737 #define VectorInit3(vector, value) vector.x = vector.y = vector.z = value
738 
739 #define IsBitMask(mask, r, g, b, a) (mask.r_bitmask == r && mask.g_bitmask == \
740   g && mask.b_bitmask == b && mask.alpha_bitmask == a)
741 
742 /*
743   Forward declarations
744 */
745 static MagickBooleanType
746   ConstructOrdering(const size_t,const DDSVector4 *,const DDSVector3,
747     DDSVector4 *,DDSVector4 *,unsigned char *,size_t),
748   ReadDDSInfo(Image *,DDSInfo *),
749   ReadDXT1(Image *,DDSInfo *,ExceptionInfo *),
750   ReadDXT3(Image *,DDSInfo *,ExceptionInfo *),
751   ReadDXT5(Image *,DDSInfo *,ExceptionInfo *),
752   ReadUncompressedRGB(Image *,DDSInfo *,ExceptionInfo *),
753   ReadUncompressedRGBA(Image *,DDSInfo *,ExceptionInfo *),
754   SkipDXTMipmaps(Image *,DDSInfo *,int,ExceptionInfo *),
755   SkipRGBMipmaps(Image *,DDSInfo *,int,ExceptionInfo *),
756   WriteDDSImage(const ImageInfo *,Image *),
757   WriteMipmaps(Image *,const size_t,const size_t,const size_t,
758     const MagickBooleanType,const MagickBooleanType,ExceptionInfo *);
759 
760 static void
761   RemapIndices(const ssize_t *,const unsigned char *,unsigned char *),
762   WriteDDSInfo(Image *,const size_t,const size_t,const size_t),
763   WriteFourCC(Image *,const size_t,const MagickBooleanType,
764     const MagickBooleanType,ExceptionInfo *),
765   WriteImageData(Image *,const size_t,const size_t,const MagickBooleanType,
766     const MagickBooleanType,ExceptionInfo *),
767   WriteIndices(Image *,const DDSVector3,const DDSVector3, unsigned char *),
768   WriteSingleColorFit(Image *,const DDSVector4 *,const ssize_t *),
769   WriteUncompressed(Image *,ExceptionInfo *);
770 
VectorAdd(const DDSVector4 left,const DDSVector4 right,DDSVector4 * destination)771 static inline void VectorAdd(const DDSVector4 left, const DDSVector4 right,
772   DDSVector4 *destination)
773 {
774   destination->x = left.x + right.x;
775   destination->y = left.y + right.y;
776   destination->z = left.z + right.z;
777   destination->w = left.w + right.w;
778 }
779 
VectorClamp(DDSVector4 * value)780 static inline void VectorClamp(DDSVector4 *value)
781 {
782   value->x = MagickMin(1.0f,MagickMax(0.0f,value->x));
783   value->y = MagickMin(1.0f,MagickMax(0.0f,value->y));
784   value->z = MagickMin(1.0f,MagickMax(0.0f,value->z));
785   value->w = MagickMin(1.0f,MagickMax(0.0f,value->w));
786 }
787 
VectorClamp3(DDSVector3 * value)788 static inline void VectorClamp3(DDSVector3 *value)
789 {
790   value->x = MagickMin(1.0f,MagickMax(0.0f,value->x));
791   value->y = MagickMin(1.0f,MagickMax(0.0f,value->y));
792   value->z = MagickMin(1.0f,MagickMax(0.0f,value->z));
793 }
794 
VectorCopy43(const DDSVector4 source,DDSVector3 * destination)795 static inline void VectorCopy43(const DDSVector4 source,
796   DDSVector3 *destination)
797 {
798   destination->x = source.x;
799   destination->y = source.y;
800   destination->z = source.z;
801 }
802 
VectorCopy44(const DDSVector4 source,DDSVector4 * destination)803 static inline void VectorCopy44(const DDSVector4 source,
804   DDSVector4 *destination)
805 {
806   destination->x = source.x;
807   destination->y = source.y;
808   destination->z = source.z;
809   destination->w = source.w;
810 }
811 
VectorNegativeMultiplySubtract(const DDSVector4 a,const DDSVector4 b,const DDSVector4 c,DDSVector4 * destination)812 static inline void VectorNegativeMultiplySubtract(const DDSVector4 a,
813   const DDSVector4 b, const DDSVector4 c, DDSVector4 *destination)
814 {
815   destination->x = c.x - (a.x * b.x);
816   destination->y = c.y - (a.y * b.y);
817   destination->z = c.z - (a.z * b.z);
818   destination->w = c.w - (a.w * b.w);
819 }
820 
VectorMultiply(const DDSVector4 left,const DDSVector4 right,DDSVector4 * destination)821 static inline void VectorMultiply(const DDSVector4 left,
822   const DDSVector4 right, DDSVector4 *destination)
823 {
824   destination->x = left.x * right.x;
825   destination->y = left.y * right.y;
826   destination->z = left.z * right.z;
827   destination->w = left.w * right.w;
828 }
829 
VectorMultiply3(const DDSVector3 left,const DDSVector3 right,DDSVector3 * destination)830 static inline void VectorMultiply3(const DDSVector3 left,
831   const DDSVector3 right, DDSVector3 *destination)
832 {
833   destination->x = left.x * right.x;
834   destination->y = left.y * right.y;
835   destination->z = left.z * right.z;
836 }
837 
VectorMultiplyAdd(const DDSVector4 a,const DDSVector4 b,const DDSVector4 c,DDSVector4 * destination)838 static inline void VectorMultiplyAdd(const DDSVector4 a, const DDSVector4 b,
839   const DDSVector4 c, DDSVector4 *destination)
840 {
841   destination->x = (a.x * b.x) + c.x;
842   destination->y = (a.y * b.y) + c.y;
843   destination->z = (a.z * b.z) + c.z;
844   destination->w = (a.w * b.w) + c.w;
845 }
846 
VectorMultiplyAdd3(const DDSVector3 a,const DDSVector3 b,const DDSVector3 c,DDSVector3 * destination)847 static inline void VectorMultiplyAdd3(const DDSVector3 a, const DDSVector3 b,
848   const DDSVector3 c, DDSVector3 *destination)
849 {
850   destination->x = (a.x * b.x) + c.x;
851   destination->y = (a.y * b.y) + c.y;
852   destination->z = (a.z * b.z) + c.z;
853 }
854 
VectorReciprocal(const DDSVector4 value,DDSVector4 * destination)855 static inline void VectorReciprocal(const DDSVector4 value,
856   DDSVector4 *destination)
857 {
858   destination->x = 1.0f / value.x;
859   destination->y = 1.0f / value.y;
860   destination->z = 1.0f / value.z;
861   destination->w = 1.0f / value.w;
862 }
863 
VectorSubtract(const DDSVector4 left,const DDSVector4 right,DDSVector4 * destination)864 static inline void VectorSubtract(const DDSVector4 left,
865   const DDSVector4 right, DDSVector4 *destination)
866 {
867   destination->x = left.x - right.x;
868   destination->y = left.y - right.y;
869   destination->z = left.z - right.z;
870   destination->w = left.w - right.w;
871 }
872 
VectorSubtract3(const DDSVector3 left,const DDSVector3 right,DDSVector3 * destination)873 static inline void VectorSubtract3(const DDSVector3 left,
874   const DDSVector3 right, DDSVector3 *destination)
875 {
876   destination->x = left.x - right.x;
877   destination->y = left.y - right.y;
878   destination->z = left.z - right.z;
879 }
880 
VectorTruncate(DDSVector4 * value)881 static inline void VectorTruncate(DDSVector4 *value)
882 {
883   value->x = value->x > 0.0f ? floor(value->x) : ceil(value->x);
884   value->y = value->y > 0.0f ? floor(value->y) : ceil(value->y);
885   value->z = value->z > 0.0f ? floor(value->z) : ceil(value->z);
886   value->w = value->w > 0.0f ? floor(value->w) : ceil(value->w);
887 }
888 
VectorTruncate3(DDSVector3 * value)889 static inline void VectorTruncate3(DDSVector3 *value)
890 {
891   value->x = value->x > 0.0f ? floor(value->x) : ceil(value->x);
892   value->y = value->y > 0.0f ? floor(value->y) : ceil(value->y);
893   value->z = value->z > 0.0f ? floor(value->z) : ceil(value->z);
894 }
895 
CalculateColors(unsigned short c0,unsigned short c1,DDSColors * c,MagickBooleanType ignoreAlpha)896 static void CalculateColors(unsigned short c0, unsigned short c1,
897   DDSColors *c, MagickBooleanType ignoreAlpha)
898 {
899   c->a[0] = c->a[1] = c->a[2] = c->a[3] = 0;
900 
901   c->r[0] = (unsigned char) C565_red(c0);
902   c->g[0] = (unsigned char) C565_green(c0);
903   c->b[0] = (unsigned char) C565_blue(c0);
904 
905   c->r[1] = (unsigned char) C565_red(c1);
906   c->g[1] = (unsigned char) C565_green(c1);
907   c->b[1] = (unsigned char) C565_blue(c1);
908 
909   if (ignoreAlpha != MagickFalse || c0 > c1)
910     {
911       c->r[2] = (unsigned char) ((2 * c->r[0] + c->r[1]) / 3);
912       c->g[2] = (unsigned char) ((2 * c->g[0] + c->g[1]) / 3);
913       c->b[2] = (unsigned char) ((2 * c->b[0] + c->b[1]) / 3);
914 
915       c->r[3] = (unsigned char) ((c->r[0] + 2 * c->r[1]) / 3);
916       c->g[3] = (unsigned char) ((c->g[0] + 2 * c->g[1]) / 3);
917       c->b[3] = (unsigned char) ((c->b[0] + 2 * c->b[1]) / 3);
918     }
919   else
920     {
921       c->r[2] = (unsigned char) ((c->r[0] + c->r[1]) / 2);
922       c->g[2] = (unsigned char) ((c->g[0] + c->g[1]) / 2);
923       c->b[2] = (unsigned char) ((c->b[0] + c->b[1]) / 2);
924 
925       c->r[3] = c->g[3] = c->b[3] = 0;
926       c->a[3] = 255;
927     }
928 }
929 
CompressAlpha(const size_t min,const size_t max,const size_t steps,const ssize_t * alphas,unsigned char * indices)930 static size_t CompressAlpha(const size_t min, const size_t max,
931   const size_t steps, const ssize_t *alphas, unsigned char* indices)
932 {
933   unsigned char
934     codes[8];
935 
936   ssize_t
937     i;
938 
939   size_t
940     error,
941     index,
942     j,
943     least,
944     value;
945 
946   codes[0] = (unsigned char) min;
947   codes[1] = (unsigned char) max;
948   codes[6] = 0;
949   codes[7] = 255;
950 
951   for (i=1; i < (ssize_t) steps; i++)
952     codes[i+1] = (unsigned char) (((steps-i)*min + i*max) / steps);
953 
954   error = 0;
955   for (i=0; i<16; i++)
956   {
957     if (alphas[i] == -1)
958       {
959         indices[i] = 0;
960         continue;
961       }
962 
963     value = alphas[i];
964     least = SIZE_MAX;
965     index = 0;
966     for (j=0; j<8; j++)
967     {
968       size_t
969         dist;
970 
971       dist = value - (size_t)codes[j];
972       dist *= dist;
973 
974       if (dist < least)
975         {
976           least = dist;
977           index = j;
978         }
979     }
980 
981     indices[i] = (unsigned char)index;
982     error += least;
983   }
984 
985   return error;
986 }
987 
CompressClusterFit(const size_t count,const DDSVector4 * points,const ssize_t * map,const DDSVector3 principle,const DDSVector4 metric,DDSVector3 * start,DDSVector3 * end,unsigned char * indices)988 static void CompressClusterFit(const size_t count,
989   const DDSVector4 *points, const ssize_t *map, const DDSVector3 principle,
990   const DDSVector4 metric, DDSVector3 *start, DDSVector3 *end,
991   unsigned char *indices)
992 {
993   DDSVector3
994     axis;
995 
996   DDSVector4
997     grid,
998     gridrcp,
999     half,
1000     onethird_onethird2,
1001     pointsWeights[16],
1002     two,
1003     twonineths,
1004     twothirds_twothirds2,
1005     xSumwSum;
1006 
1007   float
1008     bestError = 1e+37f;
1009 
1010   size_t
1011     bestIteration = 0,
1012     besti = 0,
1013     bestj = 0,
1014     bestk = 0,
1015     iterationIndex;
1016 
1017   ssize_t
1018     i;
1019 
1020   unsigned char
1021     *o,
1022     order[128],
1023     unordered[16];
1024 
1025   VectorInit(half,0.5f);
1026   VectorInit(two,2.0f);
1027 
1028   VectorInit(onethird_onethird2,1.0f/3.0f);
1029   onethird_onethird2.w = 1.0f/9.0f;
1030   VectorInit(twothirds_twothirds2,2.0f/3.0f);
1031   twothirds_twothirds2.w = 4.0f/9.0f;
1032   VectorInit(twonineths,2.0f/9.0f);
1033 
1034   grid.x = 31.0f;
1035   grid.y = 63.0f;
1036   grid.z = 31.0f;
1037   grid.w = 0.0f;
1038 
1039   gridrcp.x = 1.0f/31.0f;
1040   gridrcp.y = 1.0f/63.0f;
1041   gridrcp.z = 1.0f/31.0f;
1042   gridrcp.w = 0.0f;
1043 
1044   xSumwSum.x = 0.0f;
1045   xSumwSum.y = 0.0f;
1046   xSumwSum.z = 0.0f;
1047   xSumwSum.w = 0.0f;
1048 
1049   ConstructOrdering(count,points,principle,pointsWeights,&xSumwSum,order,0);
1050 
1051   for (iterationIndex = 0;;)
1052   {
1053 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1054   #pragma omp parallel for schedule(dynamic,1) \
1055     num_threads(GetMagickResourceLimit(ThreadResource))
1056 #endif
1057     for (i=0; i < (ssize_t) count; i++)
1058     {
1059       DDSVector4
1060         part0,
1061         part1,
1062         part2;
1063 
1064       size_t
1065         ii,
1066         j,
1067         k,
1068         kmin;
1069 
1070       VectorInit(part0,0.0f);
1071       for(ii=0; ii < (size_t) i; ii++)
1072         VectorAdd(pointsWeights[ii],part0,&part0);
1073 
1074       VectorInit(part1,0.0f);
1075       for (j=(size_t) i;;)
1076       {
1077         if (j == 0)
1078           {
1079             VectorCopy44(pointsWeights[0],&part2);
1080             kmin = 1;
1081           }
1082           else
1083           {
1084             VectorInit(part2,0.0f);
1085             kmin = j;
1086           }
1087 
1088         for (k=kmin;;)
1089         {
1090           DDSVector4
1091             a,
1092             alpha2_sum,
1093             alphax_sum,
1094             alphabeta_sum,
1095             b,
1096             beta2_sum,
1097             betax_sum,
1098             e1,
1099             e2,
1100             factor,
1101             part3;
1102 
1103           float
1104             error;
1105 
1106           VectorSubtract(xSumwSum,part2,&part3);
1107           VectorSubtract(part3,part1,&part3);
1108           VectorSubtract(part3,part0,&part3);
1109 
1110           VectorMultiplyAdd(part1,twothirds_twothirds2,part0,&alphax_sum);
1111           VectorMultiplyAdd(part2,onethird_onethird2,alphax_sum,&alphax_sum);
1112           VectorInit(alpha2_sum,alphax_sum.w);
1113 
1114           VectorMultiplyAdd(part2,twothirds_twothirds2,part3,&betax_sum);
1115           VectorMultiplyAdd(part1,onethird_onethird2,betax_sum,&betax_sum);
1116           VectorInit(beta2_sum,betax_sum.w);
1117 
1118           VectorAdd(part1,part2,&alphabeta_sum);
1119           VectorInit(alphabeta_sum,alphabeta_sum.w);
1120           VectorMultiply(twonineths,alphabeta_sum,&alphabeta_sum);
1121 
1122           VectorMultiply(alpha2_sum,beta2_sum,&factor);
1123           VectorNegativeMultiplySubtract(alphabeta_sum,alphabeta_sum,factor,
1124             &factor);
1125           VectorReciprocal(factor,&factor);
1126 
1127           VectorMultiply(alphax_sum,beta2_sum,&a);
1128           VectorNegativeMultiplySubtract(betax_sum,alphabeta_sum,a,&a);
1129           VectorMultiply(a,factor,&a);
1130 
1131           VectorMultiply(betax_sum,alpha2_sum,&b);
1132           VectorNegativeMultiplySubtract(alphax_sum,alphabeta_sum,b,&b);
1133           VectorMultiply(b,factor,&b);
1134 
1135           VectorClamp(&a);
1136           VectorMultiplyAdd(grid,a,half,&a);
1137           VectorTruncate(&a);
1138           VectorMultiply(a,gridrcp,&a);
1139 
1140           VectorClamp(&b);
1141           VectorMultiplyAdd(grid,b,half,&b);
1142           VectorTruncate(&b);
1143           VectorMultiply(b,gridrcp,&b);
1144 
1145           VectorMultiply(b,b,&e1);
1146           VectorMultiply(e1,beta2_sum,&e1);
1147           VectorMultiply(a,a,&e2);
1148           VectorMultiplyAdd(e2,alpha2_sum,e1,&e1);
1149 
1150           VectorMultiply(a,b,&e2);
1151           VectorMultiply(e2,alphabeta_sum,&e2);
1152           VectorNegativeMultiplySubtract(a,alphax_sum,e2,&e2);
1153           VectorNegativeMultiplySubtract(b,betax_sum,e2,&e2);
1154           VectorMultiplyAdd(two,e2,e1,&e2);
1155           VectorMultiply(e2,metric,&e2);
1156 
1157           error = e2.x + e2.y + e2.z;
1158 
1159           if (error < bestError)
1160             {
1161 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1162               #pragma omp critical (DDS_CompressClusterFit)
1163 #endif
1164               {
1165                 if (error < bestError)
1166                   {
1167                     VectorCopy43(a,start);
1168                     VectorCopy43(b,end);
1169                     bestError = error;
1170                     besti = i;
1171                     bestj = j;
1172                     bestk = k;
1173                     bestIteration = iterationIndex;
1174                   }
1175               }
1176             }
1177 
1178           if (k == count)
1179             break;
1180 
1181           VectorAdd(pointsWeights[k],part2,&part2);
1182           k++;
1183         }
1184 
1185         if (j == count)
1186           break;
1187 
1188         VectorAdd(pointsWeights[j],part1,&part1);
1189         j++;
1190       }
1191     }
1192 
1193     if (bestIteration != iterationIndex)
1194       break;
1195 
1196     iterationIndex++;
1197     if (iterationIndex == 8)
1198       break;
1199 
1200     VectorSubtract3(*end,*start,&axis);
1201     if (ConstructOrdering(count,points,axis,pointsWeights,&xSumwSum,order,
1202       iterationIndex) == MagickFalse)
1203       break;
1204   }
1205 
1206   o = order + (16*bestIteration);
1207 
1208   for (i=0; i < (ssize_t) besti; i++)
1209     unordered[o[i]] = 0;
1210   for (i=besti; i < (ssize_t) bestj; i++)
1211     unordered[o[i]] = 2;
1212   for (i=bestj; i < (ssize_t) bestk; i++)
1213     unordered[o[i]] = 3;
1214   for (i=bestk; i < (ssize_t) count; i++)
1215     unordered[o[i]] = 1;
1216 
1217   RemapIndices(map,unordered,indices);
1218 }
1219 
CompressRangeFit(const size_t count,const DDSVector4 * points,const ssize_t * map,const DDSVector3 principle,const DDSVector4 metric,DDSVector3 * start,DDSVector3 * end,unsigned char * indices)1220 static void CompressRangeFit(const size_t count,
1221   const DDSVector4 *points, const ssize_t *map, const DDSVector3 principle,
1222   const DDSVector4 metric, DDSVector3 *start, DDSVector3 *end,
1223   unsigned char *indices)
1224 {
1225   float
1226     d,
1227     bestDist,
1228     max,
1229     min,
1230     val;
1231 
1232   DDSVector3
1233     codes[4],
1234     grid,
1235     gridrcp,
1236     half,
1237     dist;
1238 
1239   ssize_t
1240     i;
1241 
1242   size_t
1243     bestj,
1244     j;
1245 
1246   unsigned char
1247     closest[16];
1248 
1249   VectorInit3(half,0.5f);
1250 
1251   grid.x = 31.0f;
1252   grid.y = 63.0f;
1253   grid.z = 31.0f;
1254 
1255   gridrcp.x = 1.0f/31.0f;
1256   gridrcp.y = 1.0f/63.0f;
1257   gridrcp.z = 1.0f/31.0f;
1258 
1259   if (count > 0)
1260     {
1261       VectorCopy43(points[0],start);
1262       VectorCopy43(points[0],end);
1263 
1264       min = max = Dot(points[0],principle);
1265       for (i=1; i < (ssize_t) count; i++)
1266       {
1267         val = Dot(points[i],principle);
1268         if (val < min)
1269         {
1270           VectorCopy43(points[i],start);
1271           min = val;
1272         }
1273         else if (val > max)
1274         {
1275           VectorCopy43(points[i],end);
1276           max = val;
1277         }
1278       }
1279     }
1280 
1281   VectorClamp3(start);
1282   VectorMultiplyAdd3(grid,*start,half,start);
1283   VectorTruncate3(start);
1284   VectorMultiply3(*start,gridrcp,start);
1285 
1286   VectorClamp3(end);
1287   VectorMultiplyAdd3(grid,*end,half,end);
1288   VectorTruncate3(end);
1289   VectorMultiply3(*end,gridrcp,end);
1290 
1291   codes[0] = *start;
1292   codes[1] = *end;
1293   codes[2].x = (start->x * (2.0f/3.0f)) + (end->x * (1.0f/3.0f));
1294   codes[2].y = (start->y * (2.0f/3.0f)) + (end->y * (1.0f/3.0f));
1295   codes[2].z = (start->z * (2.0f/3.0f)) + (end->z * (1.0f/3.0f));
1296   codes[3].x = (start->x * (1.0f/3.0f)) + (end->x * (2.0f/3.0f));
1297   codes[3].y = (start->y * (1.0f/3.0f)) + (end->y * (2.0f/3.0f));
1298   codes[3].z = (start->z * (1.0f/3.0f)) + (end->z * (2.0f/3.0f));
1299 
1300   for (i=0; i < (ssize_t) count; i++)
1301   {
1302     bestDist = 1e+37f;
1303     bestj = 0;
1304     for (j=0; j < 4; j++)
1305     {
1306       dist.x = (points[i].x - codes[j].x) * metric.x;
1307       dist.y = (points[i].y - codes[j].y) * metric.y;
1308       dist.z = (points[i].z - codes[j].z) * metric.z;
1309 
1310       d = Dot(dist,dist);
1311       if (d < bestDist)
1312         {
1313           bestDist = d;
1314           bestj = j;
1315         }
1316     }
1317 
1318     closest[i] = (unsigned char) bestj;
1319   }
1320 
1321   RemapIndices(map, closest, indices);
1322 }
1323 
ComputeEndPoints(const DDSSingleColourLookup * lookup[],const unsigned char * color,DDSVector3 * start,DDSVector3 * end,unsigned char * index)1324 static void ComputeEndPoints(const DDSSingleColourLookup *lookup[],
1325   const unsigned char *color, DDSVector3 *start, DDSVector3 *end,
1326   unsigned char *index)
1327 {
1328   ssize_t
1329     i;
1330 
1331   size_t
1332     c,
1333     maxError = SIZE_MAX;
1334 
1335   for (i=0; i < 2; i++)
1336   {
1337     const DDSSourceBlock*
1338       sources[3];
1339 
1340       size_t
1341         error = 0;
1342 
1343     for (c=0; c < 3; c++)
1344     {
1345       sources[c] = &lookup[c][color[c]].sources[i];
1346       error += ((size_t) sources[c]->error) * ((size_t) sources[c]->error);
1347     }
1348 
1349     if (error > maxError)
1350       continue;
1351 
1352     start->x = (float) sources[0]->start / 31.0f;
1353     start->y = (float) sources[1]->start / 63.0f;
1354     start->z = (float) sources[2]->start / 31.0f;
1355 
1356     end->x = (float) sources[0]->end / 31.0f;
1357     end->y = (float) sources[1]->end / 63.0f;
1358     end->z = (float) sources[2]->end / 31.0f;
1359 
1360     *index = (unsigned char) (2*i);
1361     maxError = error;
1362   }
1363 }
1364 
ComputePrincipleComponent(const float * covariance,DDSVector3 * principle)1365 static void ComputePrincipleComponent(const float *covariance,
1366   DDSVector3 *principle)
1367 {
1368   DDSVector4
1369     row0,
1370     row1,
1371     row2,
1372     v;
1373 
1374   ssize_t
1375     i;
1376 
1377   row0.x = covariance[0];
1378   row0.y = covariance[1];
1379   row0.z = covariance[2];
1380   row0.w = 0.0f;
1381 
1382   row1.x = covariance[1];
1383   row1.y = covariance[3];
1384   row1.z = covariance[4];
1385   row1.w = 0.0f;
1386 
1387   row2.x = covariance[2];
1388   row2.y = covariance[4];
1389   row2.z = covariance[5];
1390   row2.w = 0.0f;
1391 
1392   VectorInit(v,1.0f);
1393 
1394   for (i=0; i < 8; i++)
1395   {
1396     DDSVector4
1397       w;
1398 
1399     float
1400       a;
1401 
1402     w.x = row0.x * v.x;
1403     w.y = row0.y * v.x;
1404     w.z = row0.z * v.x;
1405     w.w = row0.w * v.x;
1406 
1407     w.x = (row1.x * v.y) + w.x;
1408     w.y = (row1.y * v.y) + w.y;
1409     w.z = (row1.z * v.y) + w.z;
1410     w.w = (row1.w * v.y) + w.w;
1411 
1412     w.x = (row2.x * v.z) + w.x;
1413     w.y = (row2.y * v.z) + w.y;
1414     w.z = (row2.z * v.z) + w.z;
1415     w.w = (row2.w * v.z) + w.w;
1416 
1417     a = (float) PerceptibleReciprocal(MagickMax(w.x,MagickMax(w.y,w.z)));
1418 
1419     v.x = w.x * a;
1420     v.y = w.y * a;
1421     v.z = w.z * a;
1422     v.w = w.w * a;
1423   }
1424 
1425   VectorCopy43(v,principle);
1426 }
1427 
ComputeWeightedCovariance(const size_t count,const DDSVector4 * points,float * covariance)1428 static void ComputeWeightedCovariance(const size_t count,
1429   const DDSVector4 *points, float *covariance)
1430 {
1431   DDSVector3
1432     centroid;
1433 
1434   float
1435     total;
1436 
1437   size_t
1438     i;
1439 
1440   total = 0.0f;
1441   VectorInit3(centroid,0.0f);
1442 
1443   for (i=0; i < count; i++)
1444   {
1445     total += points[i].w;
1446     centroid.x += (points[i].x * points[i].w);
1447     centroid.y += (points[i].y * points[i].w);
1448     centroid.z += (points[i].z * points[i].w);
1449   }
1450 
1451   if( total > 1.192092896e-07F)
1452     {
1453       centroid.x /= total;
1454       centroid.y /= total;
1455       centroid.z /= total;
1456     }
1457 
1458   for (i=0; i < 6; i++)
1459     covariance[i] = 0.0f;
1460 
1461   for (i = 0; i < count; i++)
1462   {
1463     DDSVector3
1464       a,
1465       b;
1466 
1467     a.x = points[i].x - centroid.x;
1468     a.y = points[i].y - centroid.y;
1469     a.z = points[i].z - centroid.z;
1470 
1471     b.x = points[i].w * a.x;
1472     b.y = points[i].w * a.y;
1473     b.z = points[i].w * a.z;
1474 
1475     covariance[0] += a.x*b.x;
1476     covariance[1] += a.x*b.y;
1477     covariance[2] += a.x*b.z;
1478     covariance[3] += a.y*b.y;
1479     covariance[4] += a.y*b.z;
1480     covariance[5] += a.z*b.z;
1481   }
1482 }
1483 
ConstructOrdering(const size_t count,const DDSVector4 * points,const DDSVector3 axis,DDSVector4 * pointsWeights,DDSVector4 * xSumwSum,unsigned char * order,size_t iteration)1484 static MagickBooleanType ConstructOrdering(const size_t count,
1485   const DDSVector4 *points, const DDSVector3 axis, DDSVector4 *pointsWeights,
1486   DDSVector4 *xSumwSum, unsigned char *order, size_t iteration)
1487 {
1488   float
1489      dps[16],
1490      f;
1491 
1492   ssize_t
1493     i;
1494 
1495   size_t
1496     j;
1497 
1498   unsigned char
1499     c,
1500     *o,
1501     *p;
1502 
1503   o = order + (16*iteration);
1504 
1505   for (i=0; i < (ssize_t) count; i++)
1506   {
1507     dps[i] = Dot(points[i],axis);
1508     o[i] = (unsigned char)i;
1509   }
1510 
1511   for (i=0; i < (ssize_t) count; i++)
1512   {
1513     for (j=i; j > 0 && dps[j] < dps[j - 1]; j--)
1514     {
1515       f = dps[j];
1516       dps[j] = dps[j - 1];
1517       dps[j - 1] = f;
1518 
1519       c = o[j];
1520       o[j] = o[j - 1];
1521       o[j - 1] = c;
1522     }
1523   }
1524 
1525   for (i=0; i < (ssize_t) iteration; i++)
1526   {
1527     MagickBooleanType
1528       same;
1529 
1530     p = order + (16*i);
1531     same = MagickTrue;
1532 
1533     for (j=0; j < count; j++)
1534     {
1535       if (o[j] != p[j])
1536         {
1537           same = MagickFalse;
1538           break;
1539         }
1540     }
1541 
1542     if (same != MagickFalse)
1543       return MagickFalse;
1544   }
1545 
1546   xSumwSum->x = 0;
1547   xSumwSum->y = 0;
1548   xSumwSum->z = 0;
1549   xSumwSum->w = 0;
1550 
1551   for (i=0; i < (ssize_t) count; i++)
1552   {
1553     DDSVector4
1554       v;
1555 
1556     j = (size_t) o[i];
1557 
1558     v.x = points[j].w * points[j].x;
1559     v.y = points[j].w * points[j].y;
1560     v.z = points[j].w * points[j].z;
1561     v.w = points[j].w * 1.0f;
1562 
1563     VectorCopy44(v,&pointsWeights[i]);
1564     VectorAdd(*xSumwSum,v,xSumwSum);
1565   }
1566 
1567   return MagickTrue;
1568 }
1569 
1570 /*
1571 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1572 %                                                                             %
1573 %                                                                             %
1574 %                                                                             %
1575 %   I s D D S                                                                 %
1576 %                                                                             %
1577 %                                                                             %
1578 %                                                                             %
1579 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1580 %
1581 %  IsDDS() returns MagickTrue if the image format type, identified by the
1582 %  magick string, is DDS.
1583 %
1584 %  The format of the IsDDS method is:
1585 %
1586 %      MagickBooleanType IsDDS(const unsigned char *magick,const size_t length)
1587 %
1588 %  A description of each parameter follows:
1589 %
1590 %    o magick: compare image format pattern against these bytes.
1591 %
1592 %    o length: Specifies the length of the magick string.
1593 %
1594 */
IsDDS(const unsigned char * magick,const size_t length)1595 static MagickBooleanType IsDDS(const unsigned char *magick, const size_t length)
1596 {
1597   if (length < 4)
1598     return(MagickFalse);
1599   if (LocaleNCompare((char *) magick,"DDS ", 4) == 0)
1600     return(MagickTrue);
1601   return(MagickFalse);
1602 }
1603 
1604 /*
1605 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1606 %                                                                             %
1607 %                                                                             %
1608 %                                                                             %
1609 %   R e a d D D S I m a g e                                                   %
1610 %                                                                             %
1611 %                                                                             %
1612 %                                                                             %
1613 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1614 %
1615 %  ReadDDSImage() reads a DirectDraw Surface image file and returns it.  It
1616 %  allocates the memory necessary for the new Image structure and returns a
1617 %  pointer to the new image.
1618 %
1619 %  The format of the ReadDDSImage method is:
1620 %
1621 %      Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)
1622 %
1623 %  A description of each parameter follows:
1624 %
1625 %    o image_info: The image info.
1626 %
1627 %    o exception: return any errors or warnings in this structure.
1628 %
1629 */
1630 
ReadDDSImage(const ImageInfo * image_info,ExceptionInfo * exception)1631 static Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)
1632 {
1633   Image
1634     *image;
1635 
1636   MagickBooleanType
1637     status,
1638     cubemap = MagickFalse,
1639     volume = MagickFalse,
1640     matte;
1641 
1642   CompressionType
1643     compression;
1644 
1645   DDSInfo
1646     dds_info;
1647 
1648   DDSDecoder
1649     *decoder;
1650 
1651   size_t
1652     n,
1653     num_images;
1654 
1655   /*
1656     Open image file.
1657   */
1658   assert(image_info != (const ImageInfo *) NULL);
1659   assert(image_info->signature == MagickCoreSignature);
1660   if (image_info->debug != MagickFalse)
1661     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
1662       image_info->filename);
1663   assert(exception != (ExceptionInfo *) NULL);
1664   assert(exception->signature == MagickCoreSignature);
1665   image=AcquireImage(image_info);
1666   status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
1667   if (status == MagickFalse)
1668     {
1669       image=DestroyImageList(image);
1670       return((Image *) NULL);
1671     }
1672 
1673   /*
1674     Initialize image structure.
1675   */
1676   if (ReadDDSInfo(image, &dds_info) != MagickTrue)
1677     ThrowReaderException(CorruptImageError,"ImproperImageHeader");
1678 
1679   if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP)
1680     cubemap = MagickTrue;
1681 
1682   if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0)
1683     volume = MagickTrue;
1684 
1685   (void) SeekBlob(image, 128, SEEK_SET);
1686 
1687   /*
1688     Determine pixel format
1689   */
1690   if (dds_info.pixelformat.flags & DDPF_RGB)
1691     {
1692       compression = NoCompression;
1693       if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
1694         {
1695           matte = MagickTrue;
1696           decoder = ReadUncompressedRGBA;
1697         }
1698       else
1699         {
1700           matte = MagickTrue;
1701           decoder = ReadUncompressedRGB;
1702         }
1703     }
1704   else if (dds_info.pixelformat.flags & DDPF_LUMINANCE)
1705    {
1706       compression = NoCompression;
1707       if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
1708         {
1709           /* Not sure how to handle this */
1710           ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
1711         }
1712       else
1713         {
1714           matte = MagickFalse;
1715           decoder = ReadUncompressedRGB;
1716         }
1717     }
1718   else if (dds_info.pixelformat.flags & DDPF_FOURCC)
1719     {
1720       switch (dds_info.pixelformat.fourcc)
1721       {
1722         case FOURCC_DXT1:
1723         {
1724           matte = MagickFalse;
1725           compression = DXT1Compression;
1726           decoder = ReadDXT1;
1727           break;
1728         }
1729         case FOURCC_DXT3:
1730         {
1731           matte = MagickTrue;
1732           compression = DXT3Compression;
1733           decoder = ReadDXT3;
1734           break;
1735         }
1736         case FOURCC_DXT5:
1737         {
1738           matte = MagickTrue;
1739           compression = DXT5Compression;
1740           decoder = ReadDXT5;
1741           break;
1742         }
1743         default:
1744         {
1745           /* Unknown FOURCC */
1746           ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
1747         }
1748       }
1749     }
1750   else
1751     {
1752       /* Neither compressed nor uncompressed... thus unsupported */
1753       ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
1754     }
1755 
1756   num_images = 1;
1757   if (cubemap)
1758     {
1759       /*
1760         Determine number of faces defined in the cubemap
1761       */
1762       num_images = 0;
1763       if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEX) num_images++;
1764       if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) num_images++;
1765       if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEY) num_images++;
1766       if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) num_images++;
1767       if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) num_images++;
1768       if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) num_images++;
1769     }
1770 
1771   if (volume)
1772     num_images = dds_info.depth;
1773 
1774   if ((num_images == 0) || (num_images > GetBlobSize(image)))
1775     ThrowReaderException(CorruptImageError,"ImproperImageHeader");
1776 
1777   if (AcquireMagickResource(ListLengthResource,num_images) == MagickFalse)
1778     ThrowReaderException(ResourceLimitError,"ListLengthExceedsLimit");
1779 
1780   for (n = 0; n < num_images; n++)
1781   {
1782     if (n != 0)
1783       {
1784         if (EOFBlob(image) != MagickFalse)
1785           ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
1786         /* Start a new image */
1787         AcquireNextImage(image_info,image);
1788         if (GetNextImageInList(image) == (Image *) NULL)
1789           return(DestroyImageList(image));
1790         image=SyncNextImageInList(image);
1791       }
1792 
1793     image->matte = matte;
1794     image->compression = compression;
1795     image->columns = dds_info.width;
1796     image->rows = dds_info.height;
1797     image->storage_class = DirectClass;
1798     image->endian = LSBEndian;
1799     image->depth = 8;
1800     if (image_info->ping != MagickFalse)
1801       {
1802         (void) CloseBlob(image);
1803         return(GetFirstImageInList(image));
1804       }
1805     status=SetImageExtent(image,image->columns,image->rows);
1806     if (status == MagickFalse)
1807       {
1808         InheritException(exception,&image->exception);
1809         return(DestroyImageList(image));
1810       }
1811     (void) SetImageBackgroundColor(image);
1812     if ((decoder)(image, &dds_info, exception) != MagickTrue)
1813       {
1814         (void) CloseBlob(image);
1815         if (n == 0)
1816           return(DestroyImageList(image));
1817         return(GetFirstImageInList(image));
1818       }
1819   }
1820 
1821   (void) CloseBlob(image);
1822   return(GetFirstImageInList(image));
1823 }
1824 
ReadDDSInfo(Image * image,DDSInfo * dds_info)1825 static MagickBooleanType ReadDDSInfo(Image *image, DDSInfo *dds_info)
1826 {
1827   size_t
1828     hdr_size,
1829     required;
1830 
1831   /* Seek to start of header */
1832   (void) SeekBlob(image, 4, SEEK_SET);
1833 
1834   /* Check header field */
1835   hdr_size = ReadBlobLSBLong(image);
1836   if (hdr_size != 124)
1837     return MagickFalse;
1838 
1839   /* Fill in DDS info struct */
1840   dds_info->flags = ReadBlobLSBLong(image);
1841 
1842   /* Check required flags */
1843   required=(size_t) (DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT);
1844   if ((dds_info->flags & required) != required)
1845     return MagickFalse;
1846 
1847   dds_info->height = ReadBlobLSBLong(image);
1848   dds_info->width = ReadBlobLSBLong(image);
1849   dds_info->pitchOrLinearSize = ReadBlobLSBLong(image);
1850   dds_info->depth = ReadBlobLSBLong(image);
1851   dds_info->mipmapcount = ReadBlobLSBLong(image);
1852 
1853   (void) SeekBlob(image, 44, SEEK_CUR);   /* reserved region of 11 DWORDs */
1854 
1855   /* Read pixel format structure */
1856   hdr_size = ReadBlobLSBLong(image);
1857   if (hdr_size != 32)
1858     return MagickFalse;
1859 
1860   dds_info->pixelformat.flags = ReadBlobLSBLong(image);
1861   dds_info->pixelformat.fourcc = ReadBlobLSBLong(image);
1862   dds_info->pixelformat.rgb_bitcount = ReadBlobLSBLong(image);
1863   dds_info->pixelformat.r_bitmask = ReadBlobLSBLong(image);
1864   dds_info->pixelformat.g_bitmask = ReadBlobLSBLong(image);
1865   dds_info->pixelformat.b_bitmask = ReadBlobLSBLong(image);
1866   dds_info->pixelformat.alpha_bitmask = ReadBlobLSBLong(image);
1867 
1868   dds_info->ddscaps1 = ReadBlobLSBLong(image);
1869   dds_info->ddscaps2 = ReadBlobLSBLong(image);
1870   (void) SeekBlob(image, 12, SEEK_CUR); /* 3 reserved DWORDs */
1871 
1872   return MagickTrue;
1873 }
1874 
ReadDXT1(Image * image,DDSInfo * dds_info,ExceptionInfo * exception)1875 static MagickBooleanType ReadDXT1(Image *image,DDSInfo *dds_info,
1876   ExceptionInfo *exception)
1877 {
1878   DDSColors
1879     colors;
1880 
1881   PixelPacket
1882     *q;
1883 
1884   ssize_t
1885     i,
1886     x;
1887 
1888   size_t
1889     bits;
1890 
1891   ssize_t
1892     j,
1893     y;
1894 
1895   unsigned char
1896     code;
1897 
1898   unsigned short
1899     c0,
1900     c1;
1901 
1902   for (y = 0; y < (ssize_t) image->rows; y += 4)
1903   {
1904     for (x = 0; x < (ssize_t) image->columns; x += 4)
1905     {
1906       /* Get 4x4 patch of pixels to write on */
1907       q=QueueAuthenticPixels(image,x,y,MagickMin(4,image->columns-x),
1908         MagickMin(4,image->rows-y),exception);
1909 
1910       if (q == (PixelPacket *) NULL)
1911         return MagickFalse;
1912 
1913       /* Read 8 bytes of data from the image */
1914       c0 = ReadBlobLSBShort(image);
1915       c1 = ReadBlobLSBShort(image);
1916       bits = ReadBlobLSBLong(image);
1917 
1918       CalculateColors(c0, c1, &colors, MagickFalse);
1919       if (EOFBlob(image) != MagickFalse)
1920         break;
1921 
1922       /* Write the pixels */
1923       for (j = 0; j < 4; j++)
1924       {
1925         for (i = 0; i < 4; i++)
1926         {
1927           if (((x + i) < (ssize_t) image->columns) &&
1928               ((y + j) < (ssize_t) image->rows))
1929             {
1930               code=(unsigned char) ((bits >> ((j*4+i)*2)) & 0x3);
1931               SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
1932               SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
1933               SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
1934               SetPixelOpacity(q,ScaleCharToQuantum(colors.a[code]));
1935               if ((colors.a[code] != 0) && (image->matte == MagickFalse))
1936                 image->matte=MagickTrue; /* Correct matte */
1937               q++;
1938             }
1939         }
1940       }
1941 
1942       if (SyncAuthenticPixels(image,exception) == MagickFalse)
1943         return MagickFalse;
1944     }
1945     if (EOFBlob(image) != MagickFalse)
1946       break;
1947   }
1948 
1949   return(SkipDXTMipmaps(image,dds_info,8,exception));
1950 }
1951 
ReadDXT3(Image * image,DDSInfo * dds_info,ExceptionInfo * exception)1952 static MagickBooleanType ReadDXT3(Image *image, DDSInfo *dds_info,
1953   ExceptionInfo *exception)
1954 {
1955   DDSColors
1956     colors;
1957 
1958   ssize_t
1959     j,
1960     y;
1961 
1962   PixelPacket
1963     *q;
1964 
1965   ssize_t
1966     i,
1967     x;
1968 
1969   unsigned char
1970     alpha;
1971 
1972   size_t
1973     a0,
1974     a1,
1975     bits,
1976     code;
1977 
1978   unsigned short
1979     c0,
1980     c1;
1981 
1982   for (y = 0; y < (ssize_t) dds_info->height; y += 4)
1983   {
1984     for (x = 0; x < (ssize_t) dds_info->width; x += 4)
1985     {
1986       /* Get 4x4 patch of pixels to write on */
1987       q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x),
1988                          MagickMin(4, dds_info->height - y),exception);
1989 
1990       if (q == (PixelPacket *) NULL)
1991         return MagickFalse;
1992 
1993       /* Read alpha values (8 bytes) */
1994       a0 = ReadBlobLSBLong(image);
1995       a1 = ReadBlobLSBLong(image);
1996 
1997       /* Read 8 bytes of data from the image */
1998       c0 = ReadBlobLSBShort(image);
1999       c1 = ReadBlobLSBShort(image);
2000       bits = ReadBlobLSBLong(image);
2001 
2002       CalculateColors(c0, c1, &colors, MagickTrue);
2003       if (EOFBlob(image) != MagickFalse)
2004         break;
2005 
2006       /* Write the pixels */
2007       for (j = 0; j < 4; j++)
2008       {
2009         for (i = 0; i < 4; i++)
2010         {
2011           if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
2012             {
2013               code = (bits >> ((4*j+i)*2)) & 0x3;
2014               SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
2015               SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
2016               SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
2017               /*
2018                 Extract alpha value: multiply 0..15 by 17 to get range 0..255
2019               */
2020               if (j < 2)
2021                 alpha = 17U * (unsigned char) ((a0 >> (4*(4*j+i))) & 0xf);
2022               else
2023                 alpha = 17U * (unsigned char) ((a1 >> (4*(4*(j-2)+i))) & 0xf);
2024               SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
2025                 alpha));
2026               q++;
2027             }
2028         }
2029       }
2030 
2031       if (SyncAuthenticPixels(image,exception) == MagickFalse)
2032         return MagickFalse;
2033     }
2034     if (EOFBlob(image) != MagickFalse)
2035       break;
2036   }
2037 
2038   return(SkipDXTMipmaps(image,dds_info,16,exception));
2039 }
2040 
ReadDXT5(Image * image,DDSInfo * dds_info,ExceptionInfo * exception)2041 static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info,
2042   ExceptionInfo *exception)
2043 {
2044   DDSColors
2045     colors;
2046 
2047   ssize_t
2048     j,
2049     y;
2050 
2051   MagickSizeType
2052     alpha_bits;
2053 
2054   PixelPacket
2055     *q;
2056 
2057   ssize_t
2058     i,
2059     x;
2060 
2061   unsigned char
2062     a0,
2063     a1;
2064 
2065   size_t
2066     alpha,
2067     bits,
2068     code,
2069     alpha_code;
2070 
2071   unsigned short
2072     c0,
2073     c1;
2074 
2075   for (y = 0; y < (ssize_t) dds_info->height; y += 4)
2076   {
2077     for (x = 0; x < (ssize_t) dds_info->width; x += 4)
2078     {
2079       /* Get 4x4 patch of pixels to write on */
2080       q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x),
2081                          MagickMin(4, dds_info->height - y),exception);
2082 
2083       if (q == (PixelPacket *) NULL)
2084         return MagickFalse;
2085 
2086       /* Read alpha values (8 bytes) */
2087       a0 = (unsigned char) ReadBlobByte(image);
2088       a1 = (unsigned char) ReadBlobByte(image);
2089 
2090       alpha_bits = (MagickSizeType)ReadBlobLSBLong(image);
2091       alpha_bits = alpha_bits | ((MagickSizeType)ReadBlobLSBShort(image) << 32);
2092 
2093       /* Read 8 bytes of data from the image */
2094       c0 = ReadBlobLSBShort(image);
2095       c1 = ReadBlobLSBShort(image);
2096       bits = ReadBlobLSBLong(image);
2097 
2098       CalculateColors(c0, c1, &colors, MagickTrue);
2099       if (EOFBlob(image) != MagickFalse)
2100         break;
2101 
2102       /* Write the pixels */
2103       for (j = 0; j < 4; j++)
2104       {
2105         for (i = 0; i < 4; i++)
2106         {
2107           if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
2108             {
2109               code = (bits >> ((4*j+i)*2)) & 0x3;
2110               SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
2111               SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
2112               SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
2113               /* Extract alpha value */
2114               alpha_code = (size_t) (alpha_bits >> (3*(4*j+i))) & 0x7;
2115               if (alpha_code == 0)
2116                 alpha = a0;
2117               else if (alpha_code == 1)
2118                 alpha = a1;
2119               else if (a0 > a1)
2120                 alpha = ((8-alpha_code) * a0 + (alpha_code-1) * a1) / 7;
2121               else if (alpha_code == 6)
2122                 alpha = 0;
2123               else if (alpha_code == 7)
2124                 alpha = 255;
2125               else
2126                 alpha = (((6-alpha_code) * a0 + (alpha_code-1) * a1) / 5);
2127               SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
2128                 alpha));
2129               q++;
2130             }
2131         }
2132       }
2133 
2134       if (SyncAuthenticPixels(image,exception) == MagickFalse)
2135         return MagickFalse;
2136     }
2137     if (EOFBlob(image) != MagickFalse)
2138       break;
2139   }
2140 
2141   return(SkipDXTMipmaps(image,dds_info,16,exception));
2142 }
2143 
ReadUncompressedRGB(Image * image,DDSInfo * dds_info,ExceptionInfo * exception)2144 static MagickBooleanType ReadUncompressedRGB(Image *image, DDSInfo *dds_info,
2145   ExceptionInfo *exception)
2146 {
2147   PixelPacket
2148     *q;
2149 
2150   ssize_t
2151     x, y;
2152 
2153   unsigned short
2154     color;
2155 
2156   if (dds_info->pixelformat.rgb_bitcount == 8)
2157     (void) SetImageType(image,GrayscaleType);
2158   else if (dds_info->pixelformat.rgb_bitcount == 16 && !IsBitMask(
2159     dds_info->pixelformat,0xf800,0x07e0,0x001f,0x0000))
2160     ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported",
2161       image->filename);
2162 
2163   for (y = 0; y < (ssize_t) dds_info->height; y++)
2164   {
2165     q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception);
2166 
2167     if (q == (PixelPacket *) NULL)
2168       return MagickFalse;
2169 
2170     for (x = 0; x < (ssize_t) dds_info->width; x++)
2171     {
2172       if (dds_info->pixelformat.rgb_bitcount == 8)
2173         SetPixelGray(q,ScaleCharToQuantum(ReadBlobByte(image)));
2174       else if (dds_info->pixelformat.rgb_bitcount == 16)
2175         {
2176            color=ReadBlobShort(image);
2177            SetPixelRed(q,ScaleCharToQuantum((unsigned char)
2178              (((color >> 11)/31.0)*255)));
2179            SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
2180              ((((unsigned short)(color << 5) >> 10)/63.0)*255)));
2181            SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
2182              ((((unsigned short)(color << 11) >> 11)/31.0)*255)));
2183         }
2184       else
2185         {
2186           SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
2187             ReadBlobByte(image)));
2188           SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
2189             ReadBlobByte(image)));
2190           SetPixelRed(q,ScaleCharToQuantum((unsigned char)
2191             ReadBlobByte(image)));
2192           if (dds_info->pixelformat.rgb_bitcount == 32)
2193             (void) ReadBlobByte(image);
2194         }
2195       SetPixelAlpha(q,QuantumRange);
2196       q++;
2197     }
2198 
2199     if (SyncAuthenticPixels(image,exception) == MagickFalse)
2200       return MagickFalse;
2201   }
2202 
2203   return(SkipRGBMipmaps(image,dds_info,3,exception));
2204 }
2205 
ReadUncompressedRGBA(Image * image,DDSInfo * dds_info,ExceptionInfo * exception)2206 static MagickBooleanType ReadUncompressedRGBA(Image *image, DDSInfo *dds_info,
2207   ExceptionInfo *exception)
2208 {
2209   PixelPacket
2210     *q;
2211 
2212   ssize_t
2213     alphaBits,
2214     x,
2215     y;
2216 
2217   unsigned short
2218     color;
2219 
2220   alphaBits=0;
2221   if (dds_info->pixelformat.rgb_bitcount == 16)
2222     {
2223       if (IsBitMask(dds_info->pixelformat,0x7c00,0x03e0,0x001f,0x8000))
2224         alphaBits=1;
2225       else if (IsBitMask(dds_info->pixelformat,0x00ff,0x00ff,0x00ff,0xff00))
2226         {
2227           alphaBits=2;
2228           (void) SetImageType(image,GrayscaleMatteType);
2229         }
2230       else if (IsBitMask(dds_info->pixelformat,0x0f00,0x00f0,0x000f,0xf000))
2231         alphaBits=4;
2232       else
2233         ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported",
2234           image->filename);
2235     }
2236 
2237   for (y = 0; y < (ssize_t) dds_info->height; y++)
2238   {
2239     q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception);
2240 
2241     if (q == (PixelPacket *) NULL)
2242       return MagickFalse;
2243 
2244     for (x = 0; x < (ssize_t) dds_info->width; x++)
2245     {
2246       if (dds_info->pixelformat.rgb_bitcount == 16)
2247         {
2248            color=ReadBlobShort(image);
2249            if (alphaBits == 1)
2250              {
2251                SetPixelAlpha(q,(color & (1 << 15)) ? QuantumRange : 0);
2252                SetPixelRed(q,ScaleCharToQuantum((unsigned char)
2253                  ((((unsigned short)(color << 1) >> 11)/31.0)*255)));
2254                SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
2255                  ((((unsigned short)(color << 6) >> 11)/31.0)*255)));
2256                SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
2257                  ((((unsigned short)(color << 11) >> 11)/31.0)*255)));
2258              }
2259           else if (alphaBits == 2)
2260             {
2261                SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
2262                  (color >> 8)));
2263                SetPixelGray(q,ScaleCharToQuantum((unsigned char)color));
2264             }
2265           else
2266             {
2267                SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
2268                  (((color >> 12)/15.0)*255)));
2269                SetPixelRed(q,ScaleCharToQuantum((unsigned char)
2270                  ((((unsigned short)(color << 4) >> 12)/15.0)*255)));
2271                SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
2272                  ((((unsigned short)(color << 8) >> 12)/15.0)*255)));
2273                SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
2274                  ((((unsigned short)(color << 12) >> 12)/15.0)*255)));
2275             }
2276         }
2277       else
2278         {
2279           SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
2280             ReadBlobByte(image)));
2281           SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
2282             ReadBlobByte(image)));
2283           SetPixelRed(q,ScaleCharToQuantum((unsigned char)
2284             ReadBlobByte(image)));
2285           SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
2286             ReadBlobByte(image)));
2287         }
2288       q++;
2289     }
2290 
2291     if (SyncAuthenticPixels(image,exception) == MagickFalse)
2292       return MagickFalse;
2293   }
2294 
2295   return(SkipRGBMipmaps(image,dds_info,4,exception));
2296 }
2297 
2298 /*
2299 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2300 %                                                                             %
2301 %                                                                             %
2302 %                                                                             %
2303 %   R e g i s t e r D D S I m a g e                                           %
2304 %                                                                             %
2305 %                                                                             %
2306 %                                                                             %
2307 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2308 %
2309 %  RegisterDDSImage() adds attributes for the DDS image format to
2310 %  the list of supported formats.  The attributes include the image format
2311 %  tag, a method to read and/or write the format, whether the format
2312 %  supports the saving of more than one frame to the same file or blob,
2313 %  whether the format supports native in-memory I/O, and a brief
2314 %  description of the format.
2315 %
2316 %  The format of the RegisterDDSImage method is:
2317 %
2318 %      RegisterDDSImage(void)
2319 %
2320 */
RegisterDDSImage(void)2321 ModuleExport size_t RegisterDDSImage(void)
2322 {
2323   MagickInfo
2324     *entry;
2325 
2326   entry = SetMagickInfo("DDS");
2327   entry->decoder = (DecodeImageHandler *) ReadDDSImage;
2328   entry->encoder = (EncodeImageHandler *) WriteDDSImage;
2329   entry->magick = (IsImageFormatHandler *) IsDDS;
2330   entry->seekable_stream=MagickTrue;
2331   entry->description = ConstantString("Microsoft DirectDraw Surface");
2332   entry->magick_module = ConstantString("DDS");
2333   (void) RegisterMagickInfo(entry);
2334   entry = SetMagickInfo("DXT1");
2335   entry->decoder = (DecodeImageHandler *) ReadDDSImage;
2336   entry->encoder = (EncodeImageHandler *) WriteDDSImage;
2337   entry->magick = (IsImageFormatHandler *) IsDDS;
2338   entry->seekable_stream=MagickTrue;
2339   entry->description = ConstantString("Microsoft DirectDraw Surface");
2340   entry->magick_module = ConstantString("DDS");
2341   (void) RegisterMagickInfo(entry);
2342   entry = SetMagickInfo("DXT5");
2343   entry->decoder = (DecodeImageHandler *) ReadDDSImage;
2344   entry->encoder = (EncodeImageHandler *) WriteDDSImage;
2345   entry->magick = (IsImageFormatHandler *) IsDDS;
2346   entry->seekable_stream=MagickTrue;
2347   entry->description = ConstantString("Microsoft DirectDraw Surface");
2348   entry->magick_module = ConstantString("DDS");
2349   (void) RegisterMagickInfo(entry);
2350   return(MagickImageCoderSignature);
2351 }
2352 
RemapIndices(const ssize_t * map,const unsigned char * source,unsigned char * target)2353 static void RemapIndices(const ssize_t *map, const unsigned char *source,
2354   unsigned char *target)
2355 {
2356   ssize_t
2357     i;
2358 
2359   for (i = 0; i < 16; i++)
2360   {
2361     if (map[i] == -1)
2362       target[i] = 3;
2363     else
2364       target[i] = source[map[i]];
2365   }
2366 }
2367 
2368 /*
2369   Skip the mipmap images for compressed (DXTn) dds files
2370 */
SkipDXTMipmaps(Image * image,DDSInfo * dds_info,int texel_size,ExceptionInfo * exception)2371 static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info,
2372   int texel_size,ExceptionInfo *exception)
2373 {
2374   ssize_t
2375     i;
2376 
2377   MagickOffsetType
2378     offset;
2379 
2380   size_t
2381     h,
2382     w;
2383 
2384   /*
2385     Only skip mipmaps for textures and cube maps
2386   */
2387   if (EOFBlob(image) != MagickFalse)
2388     {
2389       ThrowFileException(exception,CorruptImageWarning,"UnexpectedEndOfFile",
2390         image->filename);
2391       return(MagickFalse);
2392     }
2393   if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
2394       && (dds_info->ddscaps1 & DDSCAPS_TEXTURE
2395           || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
2396     {
2397       w = DIV2(dds_info->width);
2398       h = DIV2(dds_info->height);
2399 
2400       /*
2401         Mipmapcount includes the main image, so start from one
2402       */
2403       for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
2404       {
2405         offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size;
2406         if (SeekBlob(image,offset,SEEK_CUR) < 0)
2407           break;
2408         if ((w == 1) && (h == 1))
2409           break;
2410         w = DIV2(w);
2411         h = DIV2(h);
2412       }
2413     }
2414   return(MagickTrue);
2415 }
2416 
2417 /*
2418   Skip the mipmap images for uncompressed (RGB or RGBA) dds files
2419 */
SkipRGBMipmaps(Image * image,DDSInfo * dds_info,int pixel_size,ExceptionInfo * exception)2420 static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info,
2421   int pixel_size,ExceptionInfo *exception)
2422 {
2423   MagickOffsetType
2424     offset;
2425 
2426   ssize_t
2427     i;
2428 
2429   size_t
2430     h,
2431     w;
2432 
2433   /*
2434     Only skip mipmaps for textures and cube maps
2435   */
2436   if (EOFBlob(image) != MagickFalse)
2437     {
2438       ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
2439         image->filename);
2440       return(MagickFalse);
2441     }
2442   if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
2443       && (dds_info->ddscaps1 & DDSCAPS_TEXTURE
2444           || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
2445     {
2446       w = DIV2(dds_info->width);
2447       h = DIV2(dds_info->height);
2448 
2449       /*
2450         Mipmapcount includes the main image, so start from one
2451       */
2452       for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
2453       {
2454         offset = (MagickOffsetType) w * h * pixel_size;
2455         if (SeekBlob(image,offset,SEEK_CUR) < 0)
2456           break;
2457         w = DIV2(w);
2458         h = DIV2(h);
2459         if ((w == 1) && (h == 1))
2460           break;
2461       }
2462     }
2463   return(MagickTrue);
2464 }
2465 
2466 /*
2467 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2468 %                                                                             %
2469 %                                                                             %
2470 %                                                                             %
2471 %   U n r e g i s t e r D D S I m a g e                                       %
2472 %                                                                             %
2473 %                                                                             %
2474 %                                                                             %
2475 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2476 %
2477 %  UnregisterDDSImage() removes format registrations made by the
2478 %  DDS module from the list of supported formats.
2479 %
2480 %  The format of the UnregisterDDSImage method is:
2481 %
2482 %      UnregisterDDSImage(void)
2483 %
2484 */
UnregisterDDSImage(void)2485 ModuleExport void UnregisterDDSImage(void)
2486 {
2487   (void) UnregisterMagickInfo("DDS");
2488   (void) UnregisterMagickInfo("DXT1");
2489   (void) UnregisterMagickInfo("DXT5");
2490 }
2491 
WriteAlphas(Image * image,const ssize_t * alphas,size_t min5,size_t max5,size_t min7,size_t max7)2492 static void WriteAlphas(Image *image, const ssize_t* alphas, size_t min5,
2493   size_t max5, size_t min7, size_t max7)
2494 {
2495   ssize_t
2496     i;
2497 
2498   size_t
2499     err5,
2500     err7,
2501     j;
2502 
2503   unsigned char
2504     indices5[16],
2505     indices7[16];
2506 
2507   FixRange(min5,max5,5);
2508   err5 = CompressAlpha(min5,max5,5,alphas,indices5);
2509 
2510   FixRange(min7,max7,7);
2511   err7 = CompressAlpha(min7,max7,7,alphas,indices7);
2512 
2513   if (err7 < err5)
2514   {
2515     for (i=0; i < 16; i++)
2516     {
2517       unsigned char
2518         index;
2519 
2520       index = indices7[i];
2521       if( index == 0 )
2522         indices5[i] = 1;
2523       else if (index == 1)
2524         indices5[i] = 0;
2525       else
2526         indices5[i] = 9 - index;
2527     }
2528 
2529     min5 = max7;
2530     max5 = min7;
2531   }
2532 
2533   (void) WriteBlobByte(image,(unsigned char) min5);
2534   (void) WriteBlobByte(image,(unsigned char) max5);
2535 
2536   for(i=0; i < 2; i++)
2537   {
2538     size_t
2539       value = 0;
2540 
2541     for (j=0; j < 8; j++)
2542     {
2543       size_t index = (size_t) indices5[j + i*8];
2544       value |= ( index << 3*j );
2545     }
2546 
2547     for (j=0; j < 3; j++)
2548     {
2549       size_t byte = (value >> 8*j) & 0xff;
2550       (void) WriteBlobByte(image,(unsigned char) byte);
2551     }
2552   }
2553 }
2554 
WriteCompressed(Image * image,const size_t count,DDSVector4 * points,const ssize_t * map,const MagickBooleanType clusterFit)2555 static void WriteCompressed(Image *image, const size_t count,
2556   DDSVector4* points, const ssize_t* map, const MagickBooleanType clusterFit)
2557 {
2558   float
2559     covariance[16];
2560 
2561   DDSVector3
2562     end,
2563     principle,
2564     start;
2565 
2566   DDSVector4
2567     metric;
2568 
2569   unsigned char
2570     indices[16];
2571 
2572   VectorInit(metric,1.0f);
2573   VectorInit3(start,0.0f);
2574   VectorInit3(end,0.0f);
2575 
2576   ComputeWeightedCovariance(count,points,covariance);
2577   ComputePrincipleComponent(covariance,&principle);
2578 
2579   if (clusterFit == MagickFalse || count == 0)
2580     CompressRangeFit(count,points,map,principle,metric,&start,&end,indices);
2581   else
2582     CompressClusterFit(count,points,map,principle,metric,&start,&end,indices);
2583 
2584   WriteIndices(image,start,end,indices);
2585 }
2586 
2587 /*
2588 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2589 %                                                                             %
2590 %                                                                             %
2591 %                                                                             %
2592 %   W r i t e D D S I m a g e                                                 %
2593 %                                                                             %
2594 %                                                                             %
2595 %                                                                             %
2596 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2597 %
2598 %  WriteDDSImage() writes a DirectDraw Surface image file in the DXT5 format.
2599 %
2600 %  The format of the WriteBMPImage method is:
2601 %
2602 %     MagickBooleanType WriteDDSImage(const ImageInfo *image_info,Image *image)
2603 %
2604 %  A description of each parameter follows.
2605 %
2606 %    o image_info: the image info.
2607 %
2608 %    o image:  The image.
2609 %
2610 */
WriteDDSImage(const ImageInfo * image_info,Image * image)2611 static MagickBooleanType WriteDDSImage(const ImageInfo *image_info,
2612   Image *image)
2613 {
2614   const char
2615     *option;
2616 
2617   size_t
2618     compression,
2619     columns,
2620     maxMipmaps,
2621     mipmaps,
2622     pixelFormat,
2623     rows;
2624 
2625   MagickBooleanType
2626     clusterFit,
2627     status,
2628     weightByAlpha;
2629 
2630   assert(image_info != (const ImageInfo *) NULL);
2631   assert(image_info->signature == MagickCoreSignature);
2632   assert(image != (Image *) NULL);
2633   assert(image->signature == MagickCoreSignature);
2634   if (image->debug != MagickFalse)
2635     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2636   status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
2637   if (status == MagickFalse)
2638     return(status);
2639   if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
2640     (void) TransformImageColorspace(image,sRGBColorspace);
2641   pixelFormat=DDPF_FOURCC;
2642   compression=FOURCC_DXT5;
2643   if (!image->matte)
2644     compression=FOURCC_DXT1;
2645   if (LocaleCompare(image_info->magick,"dxt1") == 0)
2646     compression=FOURCC_DXT1;
2647   if (image_info->compression == DXT1Compression)
2648     compression=FOURCC_DXT1;
2649   else if (image_info->compression == NoCompression)
2650     pixelFormat=DDPF_RGB;
2651   option=GetImageOption(image_info,"dds:compression");
2652   if (option != (char *) NULL)
2653     {
2654        if (LocaleCompare(option,"dxt1") == 0)
2655          compression=FOURCC_DXT1;
2656        if (LocaleCompare(option,"none") == 0)
2657          pixelFormat=DDPF_RGB;
2658     }
2659   clusterFit=MagickFalse;
2660   weightByAlpha=MagickFalse;
2661   if (pixelFormat == DDPF_FOURCC)
2662     {
2663       option=GetImageOption(image_info,"dds:cluster-fit");
2664       if (IsStringTrue(option) != MagickFalse)
2665         {
2666           clusterFit=MagickTrue;
2667           if (compression != FOURCC_DXT1)
2668             {
2669               option=GetImageOption(image_info,"dds:weight-by-alpha");
2670               if (IsStringTrue(option) != MagickFalse)
2671                 weightByAlpha=MagickTrue;
2672             }
2673         }
2674     }
2675   maxMipmaps=SIZE_MAX;
2676   mipmaps=0;
2677   if ((image->columns & (image->columns - 1)) == 0 &&
2678       (image->rows & (image->rows - 1)) == 0)
2679     {
2680       option=GetImageOption(image_info,"dds:mipmaps");
2681       if (option != (char *) NULL)
2682         maxMipmaps=StringToUnsignedLong(option);
2683 
2684       if (maxMipmaps != 0)
2685         {
2686           columns=image->columns;
2687           rows=image->rows;
2688           while ((columns != 1 || rows != 1) && mipmaps != maxMipmaps)
2689           {
2690             columns=DIV2(columns);
2691             rows=DIV2(rows);
2692             mipmaps++;
2693           }
2694         }
2695     }
2696   WriteDDSInfo(image,pixelFormat,compression,mipmaps);
2697   WriteImageData(image,pixelFormat,compression,clusterFit,weightByAlpha,
2698     &image->exception);
2699   if (mipmaps > 0 && WriteMipmaps(image,pixelFormat,compression,mipmaps,
2700         clusterFit,weightByAlpha,&image->exception) == MagickFalse)
2701     return(MagickFalse);
2702   (void) CloseBlob(image);
2703   return(MagickTrue);
2704 }
2705 
WriteDDSInfo(Image * image,const size_t pixelFormat,const size_t compression,const size_t mipmaps)2706 static void WriteDDSInfo(Image *image, const size_t pixelFormat,
2707   const size_t compression, const size_t mipmaps)
2708 {
2709   char
2710     software[MaxTextExtent];
2711 
2712   ssize_t
2713     i;
2714 
2715   unsigned int
2716     format,
2717     caps,
2718     flags;
2719 
2720   flags=(unsigned int) (DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT |
2721     DDSD_PIXELFORMAT);
2722   caps=(unsigned int) DDSCAPS_TEXTURE;
2723   format=(unsigned int) pixelFormat;
2724 
2725   if (format == DDPF_FOURCC)
2726       flags=flags | DDSD_LINEARSIZE;
2727   else
2728       flags=flags | DDSD_PITCH;
2729 
2730   if (mipmaps > 0)
2731     {
2732       flags=flags | (unsigned int) DDSD_MIPMAPCOUNT;
2733       caps=caps | (unsigned int) (DDSCAPS_MIPMAP | DDSCAPS_COMPLEX);
2734     }
2735 
2736   if (format != DDPF_FOURCC && image->matte)
2737     format=format | DDPF_ALPHAPIXELS;
2738 
2739   (void) WriteBlob(image,4,(unsigned char *) "DDS ");
2740   (void) WriteBlobLSBLong(image,124);
2741   (void) WriteBlobLSBLong(image,flags);
2742   (void) WriteBlobLSBLong(image,(unsigned int) image->rows);
2743   (void) WriteBlobLSBLong(image,(unsigned int) image->columns);
2744 
2745   if (pixelFormat == DDPF_FOURCC)
2746     {
2747       /* Compressed DDS requires linear compressed size of first image */
2748       if (compression == FOURCC_DXT1)
2749         (void) WriteBlobLSBLong(image,(unsigned int) (MagickMax(1,
2750           (image->columns+3)/4)*MagickMax(1,(image->rows+3)/4)*8));
2751       else /* DXT5 */
2752         (void) WriteBlobLSBLong(image,(unsigned int) (MagickMax(1,
2753           (image->columns+3)/4)*MagickMax(1,(image->rows+3)/4)*16));
2754     }
2755   else
2756     {
2757       /* Uncompressed DDS requires byte pitch of first image */
2758       if (image->matte != MagickFalse)
2759         (void) WriteBlobLSBLong(image,(unsigned int) (image->columns * 4));
2760       else
2761         (void) WriteBlobLSBLong(image,(unsigned int) (image->columns * 3));
2762     }
2763 
2764   (void) WriteBlobLSBLong(image,0x00);
2765   (void) WriteBlobLSBLong(image,(unsigned int) mipmaps+1);
2766   (void) memset(software,0,sizeof(software));
2767   (void) CopyMagickString(software,"IMAGEMAGICK",MaxTextExtent);
2768   (void) WriteBlob(image,44,(unsigned char *) software);
2769 
2770   (void) WriteBlobLSBLong(image,32);
2771   (void) WriteBlobLSBLong(image,format);
2772 
2773   if (pixelFormat == DDPF_FOURCC)
2774     {
2775       (void) WriteBlobLSBLong(image,(unsigned int) compression);
2776       for(i=0;i < 5;i++)  /* bitcount / masks */
2777         (void) WriteBlobLSBLong(image,0x00);
2778     }
2779   else
2780     {
2781       (void) WriteBlobLSBLong(image,0x00);
2782       if (image->matte != MagickFalse)
2783         {
2784           (void) WriteBlobLSBLong(image,32);
2785           (void) WriteBlobLSBLong(image,0xff0000);
2786           (void) WriteBlobLSBLong(image,0xff00);
2787           (void) WriteBlobLSBLong(image,0xff);
2788           (void) WriteBlobLSBLong(image,0xff000000);
2789         }
2790       else
2791         {
2792           (void) WriteBlobLSBLong(image,24);
2793           (void) WriteBlobLSBLong(image,0xff0000);
2794           (void) WriteBlobLSBLong(image,0xff00);
2795           (void) WriteBlobLSBLong(image,0xff);
2796           (void) WriteBlobLSBLong(image,0x00);
2797         }
2798     }
2799 
2800   (void) WriteBlobLSBLong(image,caps);
2801   for(i=0;i < 4;i++)  /* ddscaps2 + reserved region */
2802     (void) WriteBlobLSBLong(image,0x00);
2803 }
2804 
WriteFourCC(Image * image,const size_t compression,const MagickBooleanType clusterFit,const MagickBooleanType weightByAlpha,ExceptionInfo * exception)2805 static void WriteFourCC(Image *image, const size_t compression,
2806   const MagickBooleanType clusterFit, const MagickBooleanType weightByAlpha,
2807   ExceptionInfo *exception)
2808 {
2809   const PixelPacket
2810     *p;
2811 
2812   ssize_t
2813     x;
2814 
2815   ssize_t
2816     i,
2817     y,
2818     bx,
2819     by;
2820 
2821   for (y=0; y < (ssize_t) image->rows; y+=4)
2822   {
2823     for (x=0; x < (ssize_t) image->columns; x+=4)
2824     {
2825       MagickBooleanType
2826         match;
2827 
2828       DDSVector4
2829         point,
2830         points[16];
2831 
2832       size_t
2833         count = 0,
2834         max5 = 0,
2835         max7 = 0,
2836         min5 = 255,
2837         min7 = 255,
2838         columns = 4,
2839         rows = 4;
2840 
2841       ssize_t
2842         alphas[16],
2843         map[16];
2844 
2845       unsigned char
2846         alpha;
2847 
2848       if (x + columns >= image->columns)
2849         columns = image->columns - x;
2850 
2851       if (y + rows >= image->rows)
2852         rows = image->rows - y;
2853 
2854       p=GetVirtualPixels(image,x,y,columns,rows,exception);
2855       if (p == (const PixelPacket *) NULL)
2856         break;
2857 
2858       for (i=0; i<16; i++)
2859       {
2860         map[i] = -1;
2861         alphas[i] = -1;
2862       }
2863 
2864       for (by=0; by < (ssize_t) rows; by++)
2865       {
2866         for (bx=0; bx < (ssize_t) columns; bx++)
2867         {
2868           if (compression == FOURCC_DXT5)
2869             alpha = ScaleQuantumToChar(GetPixelAlpha(p));
2870           else
2871             alpha = 255;
2872 
2873           if (compression == FOURCC_DXT5)
2874             {
2875               if (alpha < min7)
2876                 min7 = alpha;
2877               if (alpha > max7)
2878                 max7 = alpha;
2879               if (alpha != 0 && alpha < min5)
2880                 min5 = alpha;
2881               if (alpha != 255 && alpha > max5)
2882                 max5 = alpha;
2883             }
2884 
2885           alphas[4*by + bx] = (size_t)alpha;
2886 
2887           point.x = (float)ScaleQuantumToChar(GetPixelRed(p)) / 255.0f;
2888           point.y = (float)ScaleQuantumToChar(GetPixelGreen(p)) / 255.0f;
2889           point.z = (float)ScaleQuantumToChar(GetPixelBlue(p)) / 255.0f;
2890           point.w = weightByAlpha ? (float)(alpha + 1) / 256.0f : 1.0f;
2891           p++;
2892 
2893           match = MagickFalse;
2894           for (i=0; i < (ssize_t) count; i++)
2895           {
2896             if ((points[i].x == point.x) &&
2897                 (points[i].y == point.y) &&
2898                 (points[i].z == point.z) &&
2899                 (alpha       >= 128 || compression == FOURCC_DXT5))
2900               {
2901                 points[i].w += point.w;
2902                 map[4*by + bx] = i;
2903                 match = MagickTrue;
2904                 break;
2905               }
2906           }
2907 
2908           if (match != MagickFalse)
2909             continue;
2910 
2911           points[count].x = point.x;
2912           points[count].y = point.y;
2913           points[count].z = point.z;
2914           points[count].w = point.w;
2915           map[4*by + bx] = count;
2916           count++;
2917         }
2918       }
2919 
2920       for (i=0; i < (ssize_t) count; i++)
2921         points[i].w = sqrt(points[i].w);
2922 
2923       if (compression == FOURCC_DXT5)
2924         WriteAlphas(image,alphas,min5,max5,min7,max7);
2925 
2926       if (count == 1)
2927         WriteSingleColorFit(image,points,map);
2928       else
2929         WriteCompressed(image,count,points,map,clusterFit);
2930     }
2931   }
2932 }
2933 
WriteImageData(Image * image,const size_t pixelFormat,const size_t compression,const MagickBooleanType clusterFit,const MagickBooleanType weightByAlpha,ExceptionInfo * exception)2934 static void WriteImageData(Image *image, const size_t pixelFormat,
2935   const size_t compression, const MagickBooleanType clusterFit,
2936   const MagickBooleanType weightByAlpha, ExceptionInfo *exception)
2937 {
2938   if (pixelFormat == DDPF_FOURCC)
2939     WriteFourCC(image,compression,clusterFit,weightByAlpha,exception);
2940   else
2941     WriteUncompressed(image,exception);
2942 }
2943 
ClampToLimit(const float value,const size_t limit)2944 static inline size_t ClampToLimit(const float value,
2945   const size_t limit)
2946 {
2947   size_t
2948     result = (int) (value + 0.5f);
2949 
2950   if (result < 0.0f)
2951     return(0);
2952   if (result > limit)
2953     return(limit);
2954   return result;
2955 }
2956 
ColorTo565(const DDSVector3 point)2957 static inline size_t ColorTo565(const DDSVector3 point)
2958 {
2959   size_t r = ClampToLimit(31.0f*point.x,31);
2960   size_t g = ClampToLimit(63.0f*point.y,63);
2961   size_t b = ClampToLimit(31.0f*point.z,31);
2962 
2963   return (r << 11) | (g << 5) | b;
2964 }
2965 
WriteIndices(Image * image,const DDSVector3 start,const DDSVector3 end,unsigned char * indices)2966 static void WriteIndices(Image *image, const DDSVector3 start,
2967   const DDSVector3 end, unsigned char* indices)
2968 {
2969   ssize_t
2970     i;
2971 
2972   size_t
2973     a,
2974     b;
2975 
2976   unsigned char
2977     remapped[16];
2978 
2979   const unsigned char
2980     *ind;
2981 
2982   a = ColorTo565(start);
2983   b = ColorTo565(end);
2984 
2985   for (i=0; i<16; i++)
2986   {
2987     if( a < b )
2988       remapped[i] = (indices[i] ^ 0x1) & 0x3;
2989     else if( a == b )
2990       remapped[i] = 0;
2991     else
2992       remapped[i] = indices[i];
2993   }
2994 
2995   if( a < b )
2996     Swap(a,b);
2997 
2998   (void) WriteBlobByte(image,(unsigned char) (a & 0xff));
2999   (void) WriteBlobByte(image,(unsigned char) (a >> 8));
3000   (void) WriteBlobByte(image,(unsigned char) (b & 0xff));
3001   (void) WriteBlobByte(image,(unsigned char) (b >> 8));
3002 
3003   for (i=0; i<4; i++)
3004   {
3005      ind = remapped + 4*i;
3006      (void) WriteBlobByte(image,ind[0] | (ind[1] << 2) | (ind[2] << 4) |
3007        (ind[3] << 6));
3008   }
3009 }
3010 
WriteMipmaps(Image * image,const size_t pixelFormat,const size_t compression,const size_t mipmaps,const MagickBooleanType clusterFit,const MagickBooleanType weightByAlpha,ExceptionInfo * exception)3011 static MagickBooleanType WriteMipmaps(Image *image, const size_t pixelFormat,
3012   const size_t compression, const size_t mipmaps,
3013   const MagickBooleanType clusterFit, const MagickBooleanType weightByAlpha,
3014   ExceptionInfo *exception)
3015 {
3016   Image*
3017     resize_image;
3018 
3019   ssize_t
3020     i;
3021 
3022   size_t
3023     columns,
3024     rows;
3025 
3026   columns = image->columns;
3027   rows = image->rows;
3028 
3029   for (i=0; i< (ssize_t) mipmaps; i++)
3030   {
3031     resize_image = ResizeImage(image,DIV2(columns),DIV2(rows),TriangleFilter,1.0,
3032       exception);
3033 
3034     if (resize_image == (Image *) NULL)
3035       return(MagickFalse);
3036 
3037     DestroyBlob(resize_image);
3038     resize_image->blob=ReferenceBlob(image->blob);
3039 
3040     WriteImageData(resize_image,pixelFormat,compression,weightByAlpha,
3041       clusterFit,exception);
3042 
3043     resize_image=DestroyImage(resize_image);
3044 
3045     columns = DIV2(columns);
3046     rows = DIV2(rows);
3047   }
3048 
3049   return(MagickTrue);
3050 }
3051 
WriteSingleColorFit(Image * image,const DDSVector4 * points,const ssize_t * map)3052 static void WriteSingleColorFit(Image *image, const DDSVector4* points,
3053   const ssize_t* map)
3054 {
3055   DDSVector3
3056     start,
3057     end;
3058 
3059   ssize_t
3060     i;
3061 
3062   unsigned char
3063     color[3],
3064     index,
3065     indexes[16],
3066     indices[16];
3067 
3068   color[0] = (unsigned char) ClampToLimit(255.0f*points->x,255);
3069   color[1] = (unsigned char) ClampToLimit(255.0f*points->y,255);
3070   color[2] = (unsigned char) ClampToLimit(255.0f*points->z,255);
3071 
3072   index=0;
3073   ComputeEndPoints(DDS_LOOKUP,color,&start,&end,&index);
3074 
3075   for (i=0; i< 16; i++)
3076     indexes[i]=index;
3077   RemapIndices(map,indexes,indices);
3078   WriteIndices(image,start,end,indices);
3079 }
3080 
WriteUncompressed(Image * image,ExceptionInfo * exception)3081 static void WriteUncompressed(Image *image, ExceptionInfo *exception)
3082 {
3083   const PixelPacket
3084     *p;
3085 
3086   ssize_t
3087     x;
3088 
3089   ssize_t
3090     y;
3091 
3092   for (y=0; y < (ssize_t) image->rows; y++)
3093   {
3094     p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3095     if (p == (const PixelPacket *) NULL)
3096       break;
3097 
3098     for (x=0; x < (ssize_t) image->columns; x++)
3099     {
3100       (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelBlue(p)));
3101       (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelGreen(p)));
3102       (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelRed(p)));
3103       if (image->matte)
3104         (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelAlpha(p)));
3105       p++;
3106     }
3107   }
3108 }
3109