explain more
[xonotic/xonotic.git] / misc / tools / fft-normalmap-to-heightmap.c
1 /*
2  *  FFT based normalmap to heightmap converter
3  *  Copyright (C) 2010  Rudolf Polzer
4  *
5  *  This program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; either version 2 of the License, or
8  *  (at your option) any later version.
9  *
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with this program; if not, write to the Free Software
17  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  */
19
20 #undef C99
21 #if __STDC_VERSION__ >= 199901L
22 #define C99
23 #endif
24
25 #ifdef C99
26 #include <complex.h>
27 #endif
28
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <math.h>
33
34 #include <fftw3.h>
35
36 #define TWO_PI (4*atan2(1,1) * 2)
37
38 void nmap_to_hmap(unsigned char *map, const unsigned char *refmap, int w, int h, double scale, double offset)
39 {
40         int x, y;
41         int fx, fy;
42         double ffx, ffy;
43         double nx, ny, nz;
44         double v, vmin, vmax;
45 #ifndef C99
46         double save;
47 #endif
48
49         fftw_complex *imgspace1 = fftw_malloc(w*h * sizeof(fftw_complex));
50         fftw_complex *imgspace2 = fftw_malloc(w*h * sizeof(fftw_complex));
51         fftw_complex *freqspace1 = fftw_malloc(w*h * sizeof(fftw_complex));
52         fftw_complex *freqspace2 = fftw_malloc(w*h * sizeof(fftw_complex));
53         fftw_plan i12f1 = fftw_plan_dft_2d(h, w, imgspace1, freqspace1, FFTW_FORWARD, FFTW_ESTIMATE);
54         fftw_plan i22f2 = fftw_plan_dft_2d(h, w, imgspace2, freqspace2, FFTW_FORWARD, FFTW_ESTIMATE);
55         fftw_plan f12i1 = fftw_plan_dft_2d(h, w, freqspace1, imgspace1, FFTW_BACKWARD, FFTW_ESTIMATE);
56
57         for(y = 0; y < h; ++y)
58         for(x = 0; x < w; ++x)
59         {
60                 /*
61                  * unnormalized normals:
62                  * n_x = -dh/dx
63                  * n_y = -dh/dy
64                  * n_z = -dh/dh = -1
65                  * BUT: darkplaces uses inverted normals, n_y actually is dh/dy by image pixel coordinates
66                  */
67                 nx = ((int)map[(w*y+x)*4+2] - 127.5) / 128;
68                 ny = ((int)map[(w*y+x)*4+1] - 127.5) / 128;
69                 nz = ((int)map[(w*y+x)*4+0] - 127.5) / 128;
70
71                 /* reconstruct the derivatives from here */
72 #ifdef C99
73                 imgspace1[(w*y+x)] =  nx / nz * w; /* = dz/dx */
74                 imgspace2[(w*y+x)] = -ny / nz * h; /* = dz/dy */
75 #else
76                 imgspace1[(w*y+x)][0] =  nx / nz; /* = dz/dx */
77                 imgspace1[(w*y+x)][1] = 0;
78                 imgspace2[(w*y+x)][0] = -ny / nz; /* = dz/dy */
79                 imgspace2[(w*y+x)][1] = 0;
80 #endif
81         }
82
83         /* see http://www.gamedev.net/community/forums/topic.asp?topic_id=561430 */
84
85         fftw_execute(i12f1);
86         fftw_execute(i22f2);
87         
88         for(y = 0; y < h; ++y)
89         for(x = 0; x < w; ++x)
90         {
91                 fx = x;
92                 fy = y;
93                 if(fx > w/2)
94                         fx -= w;
95                 if(fy > h/2)
96                         fy -= h;
97                 /* these must have the same sign as fx and fy (so ffx*fx + ffy*fy is nonzero), otherwise do not matter */
98                 /* it basically decides how artifacts are distributed */
99                 ffx = fx;
100                 ffy = fy;
101 #ifdef C99
102                 if(fx||fy)
103                         freqspace1[(w*y+x)] = _Complex_I * (ffx * freqspace1[(w*y+x)] + ffy * freqspace2[(w*y+x)]) / (ffx*fx + ffy*fy) / TWO_PI;
104                 else
105                         freqspace1[(w*y+x)] = 0;
106 #else
107                 if(fx||fy)
108                 {
109                         save = freqspace1[(w*y+x)][0];
110                         freqspace1[(w*y+x)][0] = -(ffx * freqspace1[(w*y+x)][1] + ffy * freqspace2[(w*y+x)][1]) / (ffx*fx + ffy*fy) / TWO_PI;
111                         freqspace1[(w*y+x)][1] =  (ffx * save + ffy * freqspace2[(w*y+x)][0]) / (ffx*fx + ffy*fy) / TWO_PI;
112                 }
113                 else
114                 {
115                         freqspace1[(w*y+x)][0] = 0;
116                         freqspace1[(w*y+x)][1] = 0;
117                 }
118 #endif
119         }
120
121         fftw_execute(f12i1);
122
123         /* renormalize, find min/max */
124         vmin = vmax = 0;
125         for(y = 0; y < h; ++y)
126         for(x = 0; x < w; ++x)
127         {
128 #ifdef C99
129                 v = creal(imgspace1[(w*y+x)] /= (w*h));
130 #else
131                 v = (imgspace1[(w*y+x)][0] /= (w*h));
132                 imgspace1[(w*y+x)][1] /= (w*h);
133 #endif
134                 if(v < vmin || (x == 0 && y == 0))
135                         vmin = v;
136                 if(v > vmax || (x == 0 && y == 0))
137                         vmax = v;
138         }
139
140         if(refmap)
141         {
142                 double f, a;
143                 double o, s;
144                 double sa, sfa, sffa, sfva, sva;
145                 double mi, ma;
146                 sa = sfa = sffa = sfva = sva = 0;
147                 mi = 1;
148                 ma = -1;
149                 for(y = 0; y < h; ++y)
150                 for(x = 0; x < w; ++x)
151                 {
152                         a = (int)refmap[(w*y+x)*4+3];
153                         v = (refmap[(w*y+x)*4+0]*0.114 + refmap[(w*y+x)*4+1]*0.587 + refmap[(w*y+x)*4+2]*0.299);
154                         v = (v - 128.0) / 127.0;
155 #ifdef C99
156                         f = creal(imgspace1[(w*y+x)]);
157 #else
158                         f = imgspace1[(w*y+x)][0];
159 #endif
160                         if(a <= 0)
161                                 continue;
162                         if(v < mi)
163                                 mi = v;
164                         if(v > ma)
165                                 ma = v;
166                         sa += a;
167                         sfa += f*a;
168                         sffa += f*f*a;
169                         sfva += f*v*a;
170                         sva += v*a;
171                 }
172                 if(mi < ma)
173                 {
174                         /* linear regression ftw */
175                         o = (sfa*sfva - sffa*sva) / (sfa*sfa-sa*sffa);
176                         s = (sfa*sva - sa*sfva) / (sfa*sfa-sa*sffa);
177                 }
178                 else /* all values of v are equal, so we cannot get scale; we can still get offset */
179                 {
180                         o = ((sva - sfa) / sa);
181                         s = 1;
182                 }
183
184                 /*
185                  * now apply user-given offset and scale to these values
186                  * (x * s + o) * scale + offset
187                  * x * s * scale + o * scale + offset
188                  */
189                 offset += o * scale;
190                 scale *= s;
191         }
192         else if(scale == 0)
193         {
194                 /*
195                  * map vmin to -1
196                  * map vmax to +1
197                  */
198                 scale = 2 / (vmax - vmin);
199                 offset = -(vmax + vmin) / (vmax - vmin);
200         }
201
202         printf("Min: %f\nAvg: %f\nMax: %f\nScale: %f\nOffset: %f\nScaled-Min: %f\nScaled-Avg: %f\nScaled-Max: %f\n", 
203                 vmin, 0.0, vmax, scale, offset, vmin * scale + offset, offset, vmax * scale + offset);
204
205         for(y = 0; y < h; ++y)
206         for(x = 0; x < w; ++x)
207         {
208 #ifdef C99
209                 v = creal(imgspace1[(w*y+x)]);
210 #else
211                 v = imgspace1[(w*y+x)][0];
212 #endif
213                 v = v * scale + offset;
214                 if(v < -1)
215                         v = -1;
216                 if(v > 1)
217                         v = 1;
218                 map[(w*y+x)*4+3] = floor(128.5 + 127 * v);
219         }
220
221         fftw_destroy_plan(i12f1);
222         fftw_destroy_plan(i22f2);
223         fftw_destroy_plan(f12i1);
224
225         fftw_free(freqspace2);
226         fftw_free(freqspace1);
227         fftw_free(imgspace2);
228         fftw_free(imgspace1);
229 }
230
231 void hmap_to_nmap(unsigned char *map, int w, int h, int src_chan, double scale)
232 {
233         int x, y;
234         double nx, ny, nz;
235         double v;
236 #ifndef C99
237         double save;
238 #endif
239
240         fftw_complex *imgspace1 = fftw_malloc(w*h * sizeof(fftw_complex));
241         fftw_complex *imgspace2 = fftw_malloc(w*h * sizeof(fftw_complex));
242         fftw_complex *freqspace1 = fftw_malloc(w*h * sizeof(fftw_complex));
243         fftw_complex *freqspace2 = fftw_malloc(w*h * sizeof(fftw_complex));
244         fftw_plan i12f1 = fftw_plan_dft_2d(h, w, imgspace1, freqspace1, FFTW_FORWARD, FFTW_ESTIMATE);
245         fftw_plan f12i1 = fftw_plan_dft_2d(h, w, freqspace1, imgspace1, FFTW_BACKWARD, FFTW_ESTIMATE);
246         fftw_plan f22i2 = fftw_plan_dft_2d(h, w, freqspace2, imgspace2, FFTW_BACKWARD, FFTW_ESTIMATE);
247
248         for(y = 0; y < h; ++y)
249         for(x = 0; x < w; ++x)
250         {
251                 switch(src_chan)
252                 {
253                         case 0:
254                         case 1:
255                         case 2:
256                         case 3:
257                                 v = map[(w*y+x)*4+src_chan];
258                                 break;
259                         case 4:
260                                 v = (map[(w*y+x)*4+0] + map[(w*y+x)*4+1] + map[(w*y+x)*4+2]) / 3;
261                                 break;
262                         default:
263                         case 5:
264                                 v = (map[(w*y+x)*4+0]*0.114 + map[(w*y+x)*4+1]*0.587 + map[(w*y+x)*4+2]*0.299);
265                                 break;
266                 }
267 #ifdef C99
268                 imgspace1[(w*y+x)] = (v - 128.0) / 127.0;
269 #else
270                 imgspace1[(w*y+x)][0] = (v - 128.0) / 127.0;
271                 imgspace1[(w*y+x)][1] = 0;
272 #endif
273                 map[(w*y+x)*4+3] = floor(v + 0.5);
274         }
275
276         /* see http://www.gamedev.net/community/forums/topic.asp?topic_id=561430 */
277
278         fftw_execute(i12f1);
279         
280         for(y = 0; y < h; ++y)
281         for(x = 0; x < w; ++x)
282         {
283                 int fx = x;
284                 int fy = y;
285                 if(fx > w/2)
286                         fx -= w;
287                 if(fy > h/2)
288                         fy -= h;
289 #ifdef C99
290                 /* a lowpass to prevent the worst */
291                 freqspace1[(w*y+x)] *= 1 - pow(abs(fx) / (double)(w/2), 1);
292                 freqspace1[(w*y+x)] *= 1 - pow(abs(fy) / (double)(h/2), 1);
293
294                 freqspace2[(w*y+x)] = TWO_PI*_Complex_I * fy * freqspace1[(w*y+x)]; /* y derivative */
295                 freqspace1[(w*y+x)] = TWO_PI*_Complex_I * fx * freqspace1[(w*y+x)]; /* x derivative */
296 #else
297                 /* a lowpass to prevent the worst */
298                 freqspace1[(w*y+x)][0] *= 1 - pow(abs(fx) / (double)(w/2), 1);
299                 freqspace1[(w*y+x)][1] *= 1 - pow(abs(fx) / (double)(w/2), 1);
300                 freqspace1[(w*y+x)][0] *= 1 - pow(abs(fy) / (double)(h/2), 1);
301                 freqspace1[(w*y+x)][1] *= 1 - pow(abs(fy) / (double)(h/2), 1);
302
303                 freqspace2[(w*y+x)][0] = -TWO_PI * fy * freqspace1[(w*y+x)][1]; /* y derivative */
304                 freqspace2[(w*y+x)][1] =  TWO_PI * fy * freqspace1[(w*y+x)][0];
305                 save = freqspace1[(w*y+x)][0];
306                 freqspace1[(w*y+x)][0] = -TWO_PI * fx * freqspace1[(w*y+x)][1]; /* x derivative */
307                 freqspace1[(w*y+x)][1] =  TWO_PI * fx * save;
308 #endif
309         }
310
311         fftw_execute(f12i1);
312         fftw_execute(f22i2);
313
314         scale /= (w*h);
315
316         for(y = 0; y < h; ++y)
317         for(x = 0; x < w; ++x)
318         {
319 #ifdef C99
320                 nx = creal(imgspace1[(w*y+x)]);
321                 ny = creal(imgspace2[(w*y+x)]);
322 #else
323                 nx = imgspace1[(w*y+x)][0];
324                 ny = imgspace2[(w*y+x)][0];
325 #endif
326                 nx /= w;
327                 ny /= h;
328                 nz = -1 / scale;
329                 v = -sqrt(nx*nx + ny*ny + nz*nz);
330                 nx /= v;
331                 ny /= v;
332                 nz /= v;
333                 ny = -ny; /* DP inverted normals */
334                 map[(w*y+x)*4+2] = floor(128 + 127.5 * nx);
335                 map[(w*y+x)*4+1] = floor(128 + 127.5 * ny);
336                 map[(w*y+x)*4+0] = floor(128 + 127.5 * nz);
337         }
338
339         fftw_destroy_plan(i12f1);
340         fftw_destroy_plan(f12i1);
341         fftw_destroy_plan(f22i2);
342
343         fftw_free(freqspace2);
344         fftw_free(freqspace1);
345         fftw_free(imgspace2);
346         fftw_free(imgspace1);
347 }
348
349 void hmap_to_nmap_local(unsigned char *map, int w, int h, int src_chan, double scale)
350 {
351         int x, y;
352         double nx, ny, nz;
353         double v;
354         int i, j;
355         double *img_reduced = malloc(w*h * sizeof(double));
356         static const double filter[3][3] = { /* filter to derive one component */
357                 { -1, 0, 1 },
358                 { -2, 0, 2 },
359                 { -1, 0, 1 }
360         };
361         static const double filter_mult = 0.125;
362
363         for(y = 0; y < h; ++y)
364         for(x = 0; x < w; ++x)
365         {
366                 switch(src_chan)
367                 {
368                         case 0:
369                         case 1:
370                         case 2:
371                         case 3:
372                                 v = map[(w*y+x)*4+src_chan];
373                                 break;
374                         case 4:
375                                 v = (map[(w*y+x)*4+0] + map[(w*y+x)*4+1] + map[(w*y+x)*4+2]) / 3;
376                                 break;
377                         default:
378                         case 5:
379                                 v = (map[(w*y+x)*4+0]*0.114 + map[(w*y+x)*4+1]*0.587 + map[(w*y+x)*4+2]*0.299);
380                                 break;
381                 }
382                 img_reduced[(w*y+x)] = (v - 128.0) / 127.0;
383                 map[(w*y+x)*4+3] = floor(v + 0.5);
384         }
385
386         for(y = 0; y < h; ++y)
387         for(x = 0; x < w; ++x)
388         {
389                 nz = -1 / (scale * filter_mult);
390                 nx = ny = 0;
391
392                 for(i = -(int)(sizeof(filter) / sizeof(*filter)) / 2; i <= (int)(sizeof(filter) / sizeof(*filter)) / 2; ++i)
393                         for(j = -(int)(sizeof(*filter) / sizeof(**filter)) / 2; j <= (int)(sizeof(*filter) / sizeof(**filter)) / 2; ++j)
394                         {
395                                 nx += img_reduced[w*((y+i+h)%h)+(x+j+w)%w] * filter[i+(sizeof(filter) / sizeof(*filter)) / 2][j+(sizeof(*filter) / sizeof(**filter)) / 2];
396                                 ny += img_reduced[w*((y+j+h)%h)+(x+i+w)%w] * filter[i+(sizeof(filter) / sizeof(*filter)) / 2][j+(sizeof(*filter) / sizeof(**filter)) / 2];
397                         }
398
399                 v = -sqrt(nx*nx + ny*ny + nz*nz);
400                 nx /= v;
401                 ny /= v;
402                 nz /= v;
403                 ny = -ny; /* DP inverted normals */
404                 map[(w*y+x)*4+2] = floor(128 + 127.5 * nx);
405                 map[(w*y+x)*4+1] = floor(128 + 127.5 * ny);
406                 map[(w*y+x)*4+0] = floor(128 + 127.5 * nz);
407         }
408
409         free(img_reduced);
410 }
411
412 unsigned char *FS_LoadFile(const char *fn, int *len)
413 {
414         unsigned char *buf = NULL;
415         int n;
416         FILE *f = fopen(fn, "rb");
417         *len = 0;
418         if(!f)
419                 return NULL;
420         for(;;)
421         {
422                 buf = realloc(buf, *len + 65536);
423                 if(!buf)
424                 {
425                         fclose(f);
426                         free(buf);
427                         *len = 0;
428                         return NULL;
429                 }
430                 n = fread(buf + *len, 1, 65536, f);
431                 if(n < 0)
432                 {
433                         fclose(f);
434                         free(buf);
435                         *len = 0;
436                         return NULL;
437                 }
438                 *len += n;
439                 if(n < 65536)
440                         break;
441         }
442         return buf;
443 }
444
445 int FS_WriteFile(const char *fn, unsigned char *data, int len)
446 {
447         FILE *f = fopen(fn, "wb");
448         if(!f)
449                 return 0;
450         if(fwrite(data, len, 1, f) != 1)
451         {
452                 fclose(f);
453                 return 0;
454         }
455         if(fclose(f))
456                 return 0;
457         return 1;
458 }
459
460 /* START stuff that originates from image.c in DarkPlaces */
461 int image_width, image_height;
462
463 typedef struct _TargaHeader
464 {
465         unsigned char   id_length, colormap_type, image_type;
466         unsigned short  colormap_index, colormap_length;
467         unsigned char   colormap_size;
468         unsigned short  x_origin, y_origin, width, height;
469         unsigned char   pixel_size, attributes;
470 }
471 TargaHeader;
472
473 void PrintTargaHeader(TargaHeader *t)
474 {
475         printf("TargaHeader:\nuint8 id_length = %i;\nuint8 colormap_type = %i;\nuint8 image_type = %i;\nuint16 colormap_index = %i;\nuint16 colormap_length = %i;\nuint8 colormap_size = %i;\nuint16 x_origin = %i;\nuint16 y_origin = %i;\nuint16 width = %i;\nuint16 height = %i;\nuint8 pixel_size = %i;\nuint8 attributes = %i;\n", t->id_length, t->colormap_type, t->image_type, t->colormap_index, t->colormap_length, t->colormap_size, t->x_origin, t->y_origin, t->width, t->height, t->pixel_size, t->attributes);
476 }
477
478 unsigned char *LoadTGA_BGRA (const unsigned char *f, int filesize)
479 {
480         int x, y, pix_inc, row_inci, runlen, alphabits;
481         unsigned char *image_buffer;
482         unsigned int *pixbufi;
483         const unsigned char *fin, *enddata;
484         TargaHeader targa_header;
485         unsigned int palettei[256];
486         union
487         {
488                 unsigned int i;
489                 unsigned char b[4];
490         }
491         bgra;
492
493         if (filesize < 19)
494                 return NULL;
495
496         enddata = f + filesize;
497
498         targa_header.id_length = f[0];
499         targa_header.colormap_type = f[1];
500         targa_header.image_type = f[2];
501
502         targa_header.colormap_index = f[3] + f[4] * 256;
503         targa_header.colormap_length = f[5] + f[6] * 256;
504         targa_header.colormap_size = f[7];
505         targa_header.x_origin = f[8] + f[9] * 256;
506         targa_header.y_origin = f[10] + f[11] * 256;
507         targa_header.width = image_width = f[12] + f[13] * 256;
508         targa_header.height = image_height = f[14] + f[15] * 256;
509         targa_header.pixel_size = f[16];
510         targa_header.attributes = f[17];
511
512         if (image_width > 32768 || image_height > 32768 || image_width <= 0 || image_height <= 0)
513         {
514                 printf("LoadTGA: invalid size\n");
515                 PrintTargaHeader(&targa_header);
516                 return NULL;
517         }
518
519         /* advance to end of header */
520         fin = f + 18;
521
522         /* skip TARGA image comment (usually 0 bytes) */
523         fin += targa_header.id_length;
524
525         /* read/skip the colormap if present (note: according to the TARGA spec it */
526         /* can be present even on 1color or greyscale images, just not used by */
527         /* the image data) */
528         if (targa_header.colormap_type)
529         {
530                 if (targa_header.colormap_length > 256)
531                 {
532                         printf("LoadTGA: only up to 256 colormap_length supported\n");
533                         PrintTargaHeader(&targa_header);
534                         return NULL;
535                 }
536                 if (targa_header.colormap_index)
537                 {
538                         printf("LoadTGA: colormap_index not supported\n");
539                         PrintTargaHeader(&targa_header);
540                         return NULL;
541                 }
542                 if (targa_header.colormap_size == 24)
543                 {
544                         for (x = 0;x < targa_header.colormap_length;x++)
545                         {
546                                 bgra.b[0] = *fin++;
547                                 bgra.b[1] = *fin++;
548                                 bgra.b[2] = *fin++;
549                                 bgra.b[3] = 255;
550                                 palettei[x] = bgra.i;
551                         }
552                 }
553                 else if (targa_header.colormap_size == 32)
554                 {
555                         memcpy(palettei, fin, targa_header.colormap_length*4);
556                         fin += targa_header.colormap_length * 4;
557                 }
558                 else
559                 {
560                         printf("LoadTGA: Only 32 and 24 bit colormap_size supported\n");
561                         PrintTargaHeader(&targa_header);
562                         return NULL;
563                 }
564         }
565
566         /* check our pixel_size restrictions according to image_type */
567         switch (targa_header.image_type & ~8)
568         {
569         case 2:
570                 if (targa_header.pixel_size != 24 && targa_header.pixel_size != 32)
571                 {
572                         printf("LoadTGA: only 24bit and 32bit pixel sizes supported for type 2 and type 10 images\n");
573                         PrintTargaHeader(&targa_header);
574                         return NULL;
575                 }
576                 break;
577         case 3:
578                 /* set up a palette to make the loader easier */
579                 for (x = 0;x < 256;x++)
580                 {
581                         bgra.b[0] = bgra.b[1] = bgra.b[2] = x;
582                         bgra.b[3] = 255;
583                         palettei[x] = bgra.i;
584                 }
585                 /* fall through to colormap case */
586         case 1:
587                 if (targa_header.pixel_size != 8)
588                 {
589                         printf("LoadTGA: only 8bit pixel size for type 1, 3, 9, and 11 images supported\n");
590                         PrintTargaHeader(&targa_header);
591                         return NULL;
592                 }
593                 break;
594         default:
595                 printf("LoadTGA: Only type 1, 2, 3, 9, 10, and 11 targa RGB images supported, image_type = %i\n", targa_header.image_type);
596                 PrintTargaHeader(&targa_header);
597                 return NULL;
598         }
599
600         if (targa_header.attributes & 0x10)
601         {
602                 printf("LoadTGA: origin must be in top left or bottom left, top right and bottom right are not supported\n");
603                 return NULL;
604         }
605
606         /* number of attribute bits per pixel, we only support 0 or 8 */
607         alphabits = targa_header.attributes & 0x0F;
608         if (alphabits != 8 && alphabits != 0)
609         {
610                 printf("LoadTGA: only 0 or 8 attribute (alpha) bits supported\n");
611                 return NULL;
612         }
613
614         image_buffer = (unsigned char *)malloc(image_width * image_height * 4);
615         if (!image_buffer)
616         {
617                 printf("LoadTGA: not enough memory for %i by %i image\n", image_width, image_height);
618                 return NULL;
619         }
620
621         /* If bit 5 of attributes isn't set, the image has been stored from bottom to top */
622         if ((targa_header.attributes & 0x20) == 0)
623         {
624                 pixbufi = (unsigned int*)image_buffer + (image_height - 1)*image_width;
625                 row_inci = -image_width*2;
626         }
627         else
628         {
629                 pixbufi = (unsigned int*)image_buffer;
630                 row_inci = 0;
631         }
632
633         x = 0;
634         y = 0;
635         pix_inc = 1;
636         if ((targa_header.image_type & ~8) == 2)
637                 pix_inc = (targa_header.pixel_size + 7) / 8;
638         switch (targa_header.image_type)
639         {
640         case 1: /* colormapped, uncompressed */
641         case 3: /* greyscale, uncompressed */
642                 if (fin + image_width * image_height * pix_inc > enddata)
643                         break;
644                 for (y = 0;y < image_height;y++, pixbufi += row_inci)
645                         for (x = 0;x < image_width;x++)
646                                 *pixbufi++ = palettei[*fin++];
647                 break;
648         case 2:
649                 /* BGR or BGRA, uncompressed */
650                 if (fin + image_width * image_height * pix_inc > enddata)
651                         break;
652                 if (targa_header.pixel_size == 32 && alphabits)
653                 {
654                         for (y = 0;y < image_height;y++)
655                                 memcpy(pixbufi + y * (image_width + row_inci), fin + y * image_width * pix_inc, image_width*4);
656                 }
657                 else
658                 {
659                         for (y = 0;y < image_height;y++, pixbufi += row_inci)
660                         {
661                                 for (x = 0;x < image_width;x++, fin += pix_inc)
662                                 {
663                                         bgra.b[0] = fin[0];
664                                         bgra.b[1] = fin[1];
665                                         bgra.b[2] = fin[2];
666                                         bgra.b[3] = 255;
667                                         *pixbufi++ = bgra.i;
668                                 }
669                         }
670                 }
671                 break;
672         case 9: /* colormapped, RLE */
673         case 11: /* greyscale, RLE */
674                 for (y = 0;y < image_height;y++, pixbufi += row_inci)
675                 {
676                         for (x = 0;x < image_width;)
677                         {
678                                 if (fin >= enddata)
679                                         break; /* error - truncated file */
680                                 runlen = *fin++;
681                                 if (runlen & 0x80)
682                                 {
683                                         /* RLE - all pixels the same color */
684                                         runlen += 1 - 0x80;
685                                         if (fin + pix_inc > enddata)
686                                                 break; /* error - truncated file */
687                                         if (x + runlen > image_width)
688                                                 break; /* error - line exceeds width */
689                                         bgra.i = palettei[*fin++];
690                                         for (;runlen--;x++)
691                                                 *pixbufi++ = bgra.i;
692                                 }
693                                 else
694                                 {
695                                         /* uncompressed - all pixels different color */
696                                         runlen++;
697                                         if (fin + pix_inc * runlen > enddata)
698                                                 break; /* error - truncated file */
699                                         if (x + runlen > image_width)
700                                                 break; /* error - line exceeds width */
701                                         for (;runlen--;x++)
702                                                 *pixbufi++ = palettei[*fin++];
703                                 }
704                         }
705
706                         if (x != image_width)
707                         {
708                                 /* pixbufi is useless now */
709                                 printf("LoadTGA: corrupt file\n");
710                                 break;
711                         }
712                 }
713                 break;
714         case 10:
715                 /* BGR or BGRA, RLE */
716                 if (targa_header.pixel_size == 32 && alphabits)
717                 {
718                         for (y = 0;y < image_height;y++, pixbufi += row_inci)
719                         {
720                                 for (x = 0;x < image_width;)
721                                 {
722                                         if (fin >= enddata)
723                                                 break; /* error - truncated file */
724                                         runlen = *fin++;
725                                         if (runlen & 0x80)
726                                         {
727                                                 /* RLE - all pixels the same color */
728                                                 runlen += 1 - 0x80;
729                                                 if (fin + pix_inc > enddata)
730                                                         break; /* error - truncated file */
731                                                 if (x + runlen > image_width)
732                                                         break; /* error - line exceeds width */
733                                                 bgra.b[0] = fin[0];
734                                                 bgra.b[1] = fin[1];
735                                                 bgra.b[2] = fin[2];
736                                                 bgra.b[3] = fin[3];
737                                                 fin += pix_inc;
738                                                 for (;runlen--;x++)
739                                                         *pixbufi++ = bgra.i;
740                                         }
741                                         else
742                                         {
743                                                 /* uncompressed - all pixels different color */
744                                                 runlen++;
745                                                 if (fin + pix_inc * runlen > enddata)
746                                                         break; /* error - truncated file */
747                                                 if (x + runlen > image_width)
748                                                         break; /* error - line exceeds width */
749                                                 for (;runlen--;x++)
750                                                 {
751                                                         bgra.b[0] = fin[0];
752                                                         bgra.b[1] = fin[1];
753                                                         bgra.b[2] = fin[2];
754                                                         bgra.b[3] = fin[3];
755                                                         fin += pix_inc;
756                                                         *pixbufi++ = bgra.i;
757                                                 }
758                                         }
759                                 }
760
761                                 if (x != image_width)
762                                 {
763                                         /* pixbufi is useless now */
764                                         printf("LoadTGA: corrupt file\n");
765                                         break;
766                                 }
767                         }
768                 }
769                 else
770                 {
771                         for (y = 0;y < image_height;y++, pixbufi += row_inci)
772                         {
773                                 for (x = 0;x < image_width;)
774                                 {
775                                         if (fin >= enddata)
776                                                 break; /* error - truncated file */
777                                         runlen = *fin++;
778                                         if (runlen & 0x80)
779                                         {
780                                                 /* RLE - all pixels the same color */
781                                                 runlen += 1 - 0x80;
782                                                 if (fin + pix_inc > enddata)
783                                                         break; /* error - truncated file */
784                                                 if (x + runlen > image_width)
785                                                         break; /* error - line exceeds width */
786                                                 bgra.b[0] = fin[0];
787                                                 bgra.b[1] = fin[1];
788                                                 bgra.b[2] = fin[2];
789                                                 bgra.b[3] = 255;
790                                                 fin += pix_inc;
791                                                 for (;runlen--;x++)
792                                                         *pixbufi++ = bgra.i;
793                                         }
794                                         else
795                                         {
796                                                 /* uncompressed - all pixels different color */
797                                                 runlen++;
798                                                 if (fin + pix_inc * runlen > enddata)
799                                                         break; /* error - truncated file */
800                                                 if (x + runlen > image_width)
801                                                         break; /* error - line exceeds width */
802                                                 for (;runlen--;x++)
803                                                 {
804                                                         bgra.b[0] = fin[0];
805                                                         bgra.b[1] = fin[1];
806                                                         bgra.b[2] = fin[2];
807                                                         bgra.b[3] = 255;
808                                                         fin += pix_inc;
809                                                         *pixbufi++ = bgra.i;
810                                                 }
811                                         }
812                                 }
813
814                                 if (x != image_width)
815                                 {
816                                         /* pixbufi is useless now */
817                                         printf("LoadTGA: corrupt file\n");
818                                         break;
819                                 }
820                         }
821                 }
822                 break;
823         default:
824                 /* unknown image_type */
825                 break;
826         }
827
828         return image_buffer;
829 }
830
831 int Image_WriteTGABGRA (const char *filename, int width, int height, const unsigned char *data)
832 {
833         int y;
834         unsigned char *buffer, *out;
835         const unsigned char *in, *end;
836         int ret;
837
838         buffer = (unsigned char *)malloc(width*height*4 + 18);
839
840         memset (buffer, 0, 18);
841         buffer[2] = 2;          /* uncompressed type */
842         buffer[12] = (width >> 0) & 0xFF;
843         buffer[13] = (width >> 8) & 0xFF;
844         buffer[14] = (height >> 0) & 0xFF;
845         buffer[15] = (height >> 8) & 0xFF;
846
847         for (y = 3;y < width*height*4;y += 4)
848                 if (data[y] < 255)
849                         break;
850
851         if (y < width*height*4)
852         {
853                 /* save the alpha channel */
854                 buffer[16] = 32;        /* pixel size */
855                 buffer[17] = 8; /* 8 bits of alpha */
856
857                 /* flip upside down */
858                 out = buffer + 18;
859                 for (y = height - 1;y >= 0;y--)
860                 {
861                         memcpy(out, data + y * width * 4, width * 4);
862                         out += width*4;
863                 }
864         }
865         else
866         {
867                 /* save only the color channels */
868                 buffer[16] = 24;        /* pixel size */
869                 buffer[17] = 0; /* 8 bits of alpha */
870
871                 /* truncate bgra to bgr and flip upside down */
872                 out = buffer + 18;
873                 for (y = height - 1;y >= 0;y--)
874                 {
875                         in = data + y * width * 4;
876                         end = in + width * 4;
877                         for (;in < end;in += 4)
878                         {
879                                 *out++ = in[0];
880                                 *out++ = in[1];
881                                 *out++ = in[2];
882                         }
883                 }
884         }
885         ret = FS_WriteFile (filename, buffer, out - buffer);
886
887         free(buffer);
888
889         return ret;
890 }
891 /* START stuff that originates from image.c in DarkPlaces */
892
893 int usage(const char *me)
894 {
895         printf("Usage: %s <infile_norm.tga> <outfile_normandheight.tga> [<scale> [<offset> [<infile_ref.tga>]]] (get heightmap from normalmap)\n", me);
896         printf("or:    %s <infile_height.tga> <outfile_normandheight.tga> -1 [<scale>] (read from B, Diff)\n", me);
897         printf("or:    %s <infile_height.tga> <outfile_normandheight.tga> -2 [<scale>] (read from G, Diff)\n", me);
898         printf("or:    %s <infile_height.tga> <outfile_normandheight.tga> -3 [<scale>] (read from R, Diff)\n", me);
899         printf("or:    %s <infile_height.tga> <outfile_normandheight.tga> -4 [<scale>] (read from A, Diff)\n", me);
900         printf("or:    %s <infile_height.tga> <outfile_normandheight.tga> -5 [<scale>] (read from (R+G+B)/3, Diff)\n", me);
901         printf("or:    %s <infile_height.tga> <outfile_normandheight.tga> -6 [<scale>] (read from Y, Diff)\n", me);
902         printf("or:    %s <infile_height.tga> <outfile_normandheight.tga> -7 [<scale>] (read from B, FFT)\n", me);
903         printf("or:    %s <infile_height.tga> <outfile_normandheight.tga> -8 [<scale>] (read from G, FFT)\n", me);
904         printf("or:    %s <infile_height.tga> <outfile_normandheight.tga> -9 [<scale>] (read from R, FFT)\n", me);
905         printf("or:    %s <infile_height.tga> <outfile_normandheight.tga> -10 [<scale>] (read from A, FFT)\n", me);
906         printf("or:    %s <infile_height.tga> <outfile_normandheight.tga> -11 [<scale>] (read from (R+G+B)/3, FFT)\n", me);
907         printf("or:    %s <infile_height.tga> <outfile_normandheight.tga> -12 [<scale>] (read from Y, FFT)\n", me);
908         return 1;
909 }
910
911 int main(int argc, char **argv)
912 {
913         const char *infile, *outfile, *reffile;
914         double scale, offset;
915         int nmaplen, w, h;
916         unsigned char *nmapdata, *nmap, *refmap;
917
918         if(argc > 1)
919                 infile = argv[1];
920         else
921                 return usage(*argv);
922
923         if(argc > 2)
924                 outfile = argv[2];
925         else
926                 return usage(*argv);
927         
928         if(argc > 3)
929                 scale = atof(argv[3]);
930         else
931                 scale = 0;
932
933         if(argc > 4)
934                 offset = atof(argv[4]);
935         else
936                 offset = (scale<0) ? 1 : 0;
937
938         if(argc > 5)
939                 reffile = argv[5];
940         else
941                 reffile = NULL;
942
943         nmapdata = FS_LoadFile(infile, &nmaplen);
944         if(!nmapdata)
945         {
946                 printf("FS_LoadFile failed\n");
947                 return 2;
948         }
949         nmap = LoadTGA_BGRA(nmapdata, nmaplen);
950         free(nmapdata);
951         if(!nmap)
952         {
953                 printf("LoadTGA_BGRA failed\n");
954                 return 2;
955         }
956         w = image_width;
957         h = image_height;
958
959         if(reffile)
960         {
961                 nmapdata = FS_LoadFile(reffile, &nmaplen);
962                 if(!nmapdata)
963                 {
964                         printf("FS_LoadFile failed\n");
965                         return 2;
966                 }
967                 refmap = LoadTGA_BGRA(nmapdata, nmaplen);
968                 free(nmapdata);
969                 if(!refmap)
970                 {
971                         printf("LoadTGA_BGRA failed\n");
972                         return 2;
973                 }
974                 if(image_width != w || image_height != h)
975                 {
976                         printf("reference map must have same size as input normalmap\n");
977                         return 2;
978                 }
979         }
980         else
981                 refmap = NULL;
982
983         if(scale < -6)
984                 hmap_to_nmap(nmap, image_width, image_height, -scale-7, offset);
985         else if(scale < 0)
986                 hmap_to_nmap_local(nmap, image_width, image_height, -scale-1, offset);
987         else
988                 nmap_to_hmap(nmap, refmap, image_width, image_height, scale, offset);
989         if(!Image_WriteTGABGRA(outfile, image_width, image_height, nmap))
990         {
991                 printf("Image_WriteTGABGRA failed\n");
992                 free(nmap);
993                 return 2;
994         }
995         free(nmap);
996         return 0;
997 }