improved internal texture management error messages
[divverent/darkplaces.git] / gl_textures.c
1 #include "quakedef.h"
2
3 cvar_t  r_max_size = {CVAR_SAVE, "r_max_size", "2048"};
4 cvar_t  r_max_scrapsize = {CVAR_SAVE, "r_max_scrapsize", "256"};
5 cvar_t  r_picmip = {CVAR_SAVE, "r_picmip", "0"};
6 cvar_t  r_lerpimages = {CVAR_SAVE, "r_lerpimages", "1"};
7 cvar_t  r_precachetextures = {CVAR_SAVE, "r_precachetextures", "1"};
8
9 int             gl_filter_min = GL_LINEAR_MIPMAP_LINEAR; //NEAREST;
10 int             gl_filter_mag = GL_LINEAR;
11
12
13 static mempool_t *texturemempool;
14 static mempool_t *texturedatamempool;
15 static mempool_t *textureprocessingmempool;
16
17 // note: this must not conflict with TEXF_ flags in r_textures.h
18 // cleared when a texture is uploaded
19 #define GLTEXF_UPLOAD 0x00010000
20 // texture generated by code, also causes permanent GLTEXF_UPLOAD effect
21 #define GLTEXF_PROCEDURAL 0x00020000
22 // bitmask for mismatch checking
23 #define GLTEXF_IMPORTANTBITS (GLTEXF_PROCEDURAL)
24 // set when image is uploaded and freed
25 #define GLTEXF_DESTROYED 0x00040000
26
27 // size of images which hold fragment textures, ignores picmip and max_size
28 //#define BLOCK_SIZE 256
29 static int block_size;
30
31 // really this number only governs gltexnuminuse
32 #define MAX_GLTEXTURES 65536
33
34 // since there is only one set of GL texture numbers, we have to track them
35 // globally, everything else is per texture pool
36 static byte *gltexnuminuse;
37
38 typedef struct
39 {
40         int textype;
41         int inputbytesperpixel;
42         int internalbytesperpixel;
43         int glformat;
44         int glinternalformat;
45         int align;
46 }
47 textypeinfo_t;
48
49 static textypeinfo_t textype_qpalette       = {TEXTYPE_QPALETTE, 1, 4, GL_RGBA, 3, 1};
50 static textypeinfo_t textype_rgb            = {TEXTYPE_RGB     , 3, 3, GL_RGB , 3, 3};
51 static textypeinfo_t textype_rgba           = {TEXTYPE_RGBA    , 4, 4, GL_RGBA, 3, 1};
52 static textypeinfo_t textype_qpalette_alpha = {TEXTYPE_QPALETTE, 1, 4, GL_RGBA, 4, 1};
53 static textypeinfo_t textype_rgba_alpha     = {TEXTYPE_RGBA    , 4, 4, GL_RGBA, 4, 1};
54
55 // a tiling texture (most common type)
56 #define GLIMAGETYPE_TILE 0
57 // a fragments texture (contains one or more fragment textures)
58 #define GLIMAGETYPE_FRAGMENTS 1
59
60 // a gltextureimage can have one (or more if fragments) gltextures inside
61 typedef struct gltextureimage_s
62 {
63         struct gltextureimage_s *imagechain;
64         int texturecount;
65         int type; // one of the GLIMAGETYPE_ values
66         int texnum; // GL texture slot number
67         int width, height;
68         int bytesperpixel; // bytes per pixel
69         int glformat; // GL_RGB or GL_RGBA
70         int glinternalformat; // 3 or 4
71         int flags;
72         short *blockallocation; // fragment allocation
73 }
74 gltextureimage_t;
75
76 typedef struct gltexture_s
77 {
78         // pointer to texturepool (check this to see if the texture is allocated)
79         struct gltexturepool_s *pool;
80         // pointer to next texture in texturepool chain
81         struct gltexture_s *chain;
82         // pointer into gltextureimage array
83         gltextureimage_t *image;
84         // name of the texture (this might be removed someday), no duplicates
85         char *identifier;
86         // location in the image, and size
87         int x, y, width, height;
88         // copy of the original texture supplied to the upload function, for re-uploading or deferred uploads (non-precached)
89         byte *inputtexels;
90         // to identify cache mismatchs (this might be removed someday)
91         int crc;
92         // flags supplied to the LoadTexture/ProceduralTexture functions
93         // (might be altered to remove TEXF_ALPHA), and GLTEXF_ private flags
94         int flags;
95         // procedural texture generation function, called once per frame if the texture is used
96         int (*generate)(byte *buffer, int width, int height, void *parameterdata, int parameterdatasize);
97         // data provided to generate, persistent from call to call
98         byte *proceduraldata;
99         // size of data
100         int proceduraldatasize;
101         // used only to avoid updating the texture more than once per frame
102         int proceduralframecount;
103         // pointer to one of the textype_ structs
104         textypeinfo_t *textype;
105 }
106 gltexture_t;
107
108 #define TEXTUREPOOL_SENTINEL 0xC0DEDBAD
109
110 typedef struct gltexturepool_s
111 {
112         int sentinel;
113         struct gltextureimage_s *imagechain;
114         struct gltexture_s *gltchain;
115         struct gltexturepool_s *next;
116 }
117 gltexturepool_t;
118
119 static gltexturepool_t *gltexturepoolchain = NULL;
120
121 static byte *resamplerow1 = NULL, *resamplerow2 = NULL;
122 static int resamplerowsize = 0;
123 static byte *resizebuffer = NULL, *colorconvertbuffer;
124 static int resizebuffersize = 0;
125 static byte *texturebuffer;
126 static int texturebuffersize = 0;
127
128 static int realmaxsize = 0;
129
130 static textypeinfo_t *R_GetTexTypeInfo(int textype, int flags)
131 {
132         if (flags & TEXF_ALPHA)
133         {
134                 switch(textype)
135                 {
136                 case TEXTYPE_QPALETTE:
137                         return &textype_qpalette_alpha;
138                 case TEXTYPE_RGB:
139                         Host_Error("R_GetTexTypeInfo: RGB format has no alpha, TEXF_ALPHA not allowed\n");
140                         return NULL;
141                 case TEXTYPE_RGBA:
142                         return &textype_rgba_alpha;
143                 default:
144                         Host_Error("R_GetTexTypeInfo: unknown texture format\n");
145                         return NULL;
146                 }
147         }
148         else
149         {
150                 switch(textype)
151                 {
152                 case TEXTYPE_QPALETTE:
153                         return &textype_qpalette;
154                 case TEXTYPE_RGB:
155                         return &textype_rgb;
156                 case TEXTYPE_RGBA:
157                         return &textype_rgba;
158                 default:
159                         Host_Error("R_GetTexTypeInfo: unknown texture format\n");
160                         return NULL;
161                 }
162         }
163 }
164
165 static void R_UploadTexture(gltexture_t *t);
166
167 static void R_PrecacheTexture(gltexture_t *glt)
168 {
169         int precache;
170         precache = false;
171         if (glt->flags & TEXF_ALWAYSPRECACHE)
172                 precache = true;
173         else if (r_precachetextures.integer >= 2)
174                 precache = true;
175         else if (r_precachetextures.integer >= 1)
176                 if (glt->flags & TEXF_PRECACHE)
177                         precache = true;
178
179         if (precache)
180                 R_UploadTexture(glt);
181 }
182
183 int R_GetTexture(rtexture_t *rt)
184 {
185         gltexture_t *glt;
186         if (!rt)
187                 return 0;
188         glt = (gltexture_t *)rt;
189         if (glt->flags & (GLTEXF_UPLOAD | GLTEXF_PROCEDURAL))
190         {
191                 if (glt->flags & GLTEXF_PROCEDURAL)
192                 {
193                         if (glt->proceduralframecount != r_framecount)
194                         {
195                                 glt->proceduralframecount = r_framecount;
196                                 R_UploadTexture(glt);
197                         }
198                 }
199                 else
200                         R_UploadTexture(glt);
201         }
202         return glt->image->texnum;
203 }
204
205 static void R_FreeTexture(gltexture_t *glt)
206 {
207         gltexture_t **gltpointer;
208         gltextureimage_t *image, **gltimagepointer;
209         GLuint texnum;
210
211         if (glt == NULL)
212                 Host_Error("R_FreeTexture: texture == NULL\n");
213
214         for (gltpointer = &glt->pool->gltchain;*gltpointer && *gltpointer != glt;gltpointer = &(*gltpointer)->chain);
215         if (*gltpointer == glt)
216                 *gltpointer = glt->chain;
217         else
218                 Host_Error("R_FreeTexture: texture \"%s\" not linked in pool\n", glt->identifier);
219
220         // note: if freeing a fragment texture, this will not make the claimed
221         // space available for new textures unless all other fragments in the
222         // image are also freed
223         image = glt->image;
224         image->texturecount--;
225         if (image->texturecount < 1)
226         {
227                 for (gltimagepointer = &glt->pool->imagechain;*gltimagepointer && *gltimagepointer != image;gltimagepointer = &(*gltimagepointer)->imagechain);
228                 if (*gltimagepointer == image)
229                         *gltimagepointer = image->imagechain;
230                 else
231                         Host_Error("R_FreeTexture: image not linked in pool\n");
232                 if (image->texnum)
233                 {
234                         texnum = image->texnum;
235                         gltexnuminuse[image->texnum] = 0;
236                         glDeleteTextures(1, &texnum);
237                 }
238                 if (image->blockallocation)
239                         Mem_Free(image->blockallocation);
240                 Mem_Free(image);
241         }
242
243         if (glt->identifier)
244                 Mem_Free(glt->identifier);
245         if (glt->inputtexels)
246                 Mem_Free(glt->inputtexels);
247         if (glt->proceduraldata)
248                 Mem_Free(glt->proceduraldata);
249         Mem_Free(glt);
250 }
251
252 static gltexture_t *R_FindTexture (gltexturepool_t *pool, char *identifier)
253 {
254         gltexture_t     *glt;
255
256         if (!identifier)
257                 return NULL;
258
259         for (glt = pool->gltchain;glt;glt = glt->chain)
260                 if (glt->identifier && !strcmp (identifier, glt->identifier))
261                         return glt;
262
263         return NULL;
264 }
265
266 rtexturepool_t *R_AllocTexturePool(void)
267 {
268         gltexturepool_t *pool;
269         if (texturemempool == NULL)
270                 return NULL;
271         pool = Mem_Alloc(texturemempool, sizeof(gltexturepool_t));
272         if (pool == NULL)
273                 return NULL;
274         //memset(pool, 0, sizeof(gltexturepool_t));
275         pool->next = gltexturepoolchain;
276         gltexturepoolchain = pool;
277         pool->sentinel = TEXTUREPOOL_SENTINEL;
278         return (rtexturepool_t *)pool;
279 }
280
281 void R_FreeTexturePool(rtexturepool_t **rtexturepool)
282 {
283         gltexturepool_t *pool, **poolpointer;
284         if (rtexturepool == NULL)
285                 return;
286         if (*rtexturepool == NULL)
287                 return;
288         pool = (gltexturepool_t *)(*rtexturepool);
289         *rtexturepool = NULL;
290         if (pool->sentinel != TEXTUREPOOL_SENTINEL)
291                 Host_Error("R_FreeTexturePool: pool already freed\n");
292         for (poolpointer = &gltexturepoolchain;*poolpointer && *poolpointer != pool;poolpointer = &(*poolpointer)->next);
293         if (*poolpointer == pool)
294                 *poolpointer = pool->next;
295         else
296                 Host_Error("R_FreeTexturePool: pool not linked\n");
297         while (pool->gltchain)
298                 R_FreeTexture(pool->gltchain);
299         if (pool->imagechain)
300                 Sys_Error("R_FreeTexturePool: not all images freed\n");
301         Mem_Free(pool);
302 }
303
304
305 typedef struct
306 {
307         char *name;
308         int minification, magnification;
309 }
310 glmode_t;
311
312 static glmode_t modes[] =
313 {
314         {"GL_NEAREST", GL_NEAREST, GL_NEAREST},
315         {"GL_LINEAR", GL_LINEAR, GL_LINEAR},
316         {"GL_NEAREST_MIPMAP_NEAREST", GL_NEAREST_MIPMAP_NEAREST, GL_NEAREST},
317         {"GL_LINEAR_MIPMAP_NEAREST", GL_LINEAR_MIPMAP_NEAREST, GL_LINEAR},
318         {"GL_NEAREST_MIPMAP_LINEAR", GL_NEAREST_MIPMAP_LINEAR, GL_NEAREST},
319         {"GL_LINEAR_MIPMAP_LINEAR", GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR}
320 };
321
322 static void GL_TextureMode_f (void)
323 {
324         int i;
325         gltextureimage_t *image;
326         gltexturepool_t *pool;
327
328         if (Cmd_Argc() == 1)
329         {
330                 for (i = 0;i < 6;i++)
331                 {
332                         if (gl_filter_min == modes[i].minification)
333                         {
334                                 Con_Printf ("%s\n", modes[i].name);
335                                 return;
336                         }
337                 }
338                 Con_Printf ("current filter is unknown???\n");
339                 return;
340         }
341
342         for (i = 0;i < 6;i++)
343                 if (!Q_strcasecmp (modes[i].name, Cmd_Argv(1) ) )
344                         break;
345         if (i == 6)
346         {
347                 Con_Printf ("bad filter name\n");
348                 return;
349         }
350
351         gl_filter_min = modes[i].minification;
352         gl_filter_mag = modes[i].magnification;
353
354         // change all the existing mipmap texture objects
355         // FIXME: force renderer(/client/something?) restart instead?
356         for (pool = gltexturepoolchain;pool;pool = pool->next)
357         {
358                 for (image = pool->imagechain;image;image = image->imagechain)
359                 {
360                         // only update already uploaded images
361                         if (!(image->flags & GLTEXF_UPLOAD))
362                         {
363                                 glBindTexture(GL_TEXTURE_2D, image->texnum);
364                                 if (image->flags & TEXF_MIPMAP)
365                                         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min);
366                                 else
367                                         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_mag);
368                                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_mag);
369                         }
370                 }
371         }
372 }
373
374 static int R_CalcTexelDataSize (gltexture_t *glt)
375 {
376         int width2, height2, size;
377         if (glt->flags & TEXF_FRAGMENT)
378                 size = glt->width * glt->height;
379         else
380         {
381                 if (r_max_size.integer > realmaxsize)
382                         Cvar_SetValue("r_max_size", realmaxsize);
383                 // calculate final size
384                 for (width2 = 1;width2 < glt->width;width2 <<= 1);
385                 for (height2 = 1;height2 < glt->height;height2 <<= 1);
386                 for (width2 >>= r_picmip.integer;width2 > r_max_size.integer;width2 >>= 1);
387                 for (height2 >>= r_picmip.integer;height2 > r_max_size.integer;height2 >>= 1);
388                 if (width2 < 1) width2 = 1;
389                 if (height2 < 1) height2 = 1;
390
391                 size = 0;
392                 if (glt->flags & TEXF_MIPMAP)
393                 {
394                         while (width2 > 1 || height2 > 1)
395                         {
396                                 size += width2 * height2;
397                                 if (width2 > 1)
398                                         width2 >>= 1;
399                                 if (height2 > 1)
400                                         height2 >>= 1;
401                         }
402                         size++; // count the last 1x1 mipmap
403                 }
404                 else
405                         size = width2*height2;
406         }
407         size *= glt->textype->internalbytesperpixel;
408
409         return size;
410 }
411
412 void R_TextureStats_PrintTotal(void)
413 {
414         int glsize, inputsize, total = 0, totalt = 0, totalp = 0, loaded = 0, loadedt = 0, loadedp = 0;
415         gltexture_t *glt;
416         gltexturepool_t *pool;
417         for (pool = gltexturepoolchain;pool;pool = pool->next)
418         {
419                 for (glt = pool->gltchain;glt;glt = glt->chain)
420                 {
421                         glsize = R_CalcTexelDataSize(glt);
422                         inputsize = glt->width * glt->height * glt->textype->inputbytesperpixel;
423
424                         total++;
425                         totalt += glsize;
426                         totalp += inputsize;
427                         if (!(glt->flags & GLTEXF_UPLOAD))
428                         {
429                                 loaded++;
430                                 loadedt += glsize;
431                                 loadedp += inputsize;
432                         }
433                 }
434         }
435         Con_Printf("total: %i (%.3fMB, %.3fMB original), uploaded %i (%.3fMB, %.3fMB original), upload on demand %i (%.3fMB, %.3fMB original)\n", total, totalt / 1048576.0, totalp / 1048576.0, loaded, loadedt / 1048576.0, loadedp / 1048576.0, total - loaded, (totalt - loadedt) / 1048576.0, (totalp - loadedp) / 1048576.0);
436 }
437
438 static void R_TextureStats_f(void)
439 {
440         int loaded;
441         gltexture_t *glt;
442         gltexturepool_t *pool;
443         Con_Printf("glsize input crc  loaded mip alpha name\n");
444         for (pool = gltexturepoolchain;pool;pool = pool->next)
445         {
446                 for (glt = pool->gltchain;glt;glt = glt->chain)
447                 {
448                         loaded = !(glt->flags & GLTEXF_UPLOAD);
449                         if (glt->flags & GLTEXF_PROCEDURAL)
450                                 Con_Printf("%c%4i%c %4i  PROC %s %s %s %s\n"  , loaded ? '[' : ' ', (R_CalcTexelDataSize(glt) + 1023) / 1024, loaded ? ']' : ' ',                               (glt->width * glt->height * glt->textype->inputbytesperpixel + 1023) / 1024,                                         loaded ? "loaded" : "      ", (glt->flags & TEXF_MIPMAP) ? "mip" : "   ", (glt->flags & TEXF_ALPHA) ? "alpha" : "     ", glt->identifier ? glt->identifier : "<unnamed>");
451                         else
452                                 Con_Printf("%c%4i%c%c%4i%c %04X %s %s %s %s\n", loaded ? '[' : ' ', (R_CalcTexelDataSize(glt) + 1023) / 1024, loaded ? ']' : ' ', glt->inputtexels ? '[' : ' ', (glt->width * glt->height * glt->textype->inputbytesperpixel + 1023) / 1024, glt->inputtexels ? ']' : ' ', glt->crc, loaded ? "loaded" : "      ", (glt->flags & TEXF_MIPMAP) ? "mip" : "   ", (glt->flags & TEXF_ALPHA) ? "alpha" : "     ", glt->identifier ? glt->identifier : "<unnamed>");
453                 }
454                 Con_Printf("pool %10p\n", pool);
455         }
456         R_TextureStats_PrintTotal();
457 }
458
459 char engineversion[40];
460
461 static void r_textures_start(void)
462 {
463         // deal with size limits of various drivers (3dfx in particular)
464         glGetIntegerv(GL_MAX_TEXTURE_SIZE, &realmaxsize);
465         CHECKGLERROR
466
467         // use the largest scrap texture size we can (not sure if this is really a good idea)
468         for (block_size = 1;block_size < realmaxsize && block_size < r_max_scrapsize.integer;block_size <<= 1);
469
470         texturemempool = Mem_AllocPool("Texture Info");
471         texturedatamempool = Mem_AllocPool("Texture Storage (not yet uploaded)");
472         textureprocessingmempool = Mem_AllocPool("Texture Processing Buffers");
473         gltexnuminuse = Mem_Alloc(texturemempool, MAX_GLTEXTURES);
474         //memset(gltexnuminuse, 0, MAX_GLTEXTURES);
475 }
476
477 static void r_textures_shutdown(void)
478 {
479         rtexturepool_t *temp;
480         while(gltexturepoolchain)
481         {
482                 temp = (rtexturepool_t *) gltexturepoolchain;
483                 R_FreeTexturePool(&temp);
484         }
485
486         /*
487         if (resizebuffer) Mem_Free(resizebuffer);resizebuffer = NULL;
488         if (colorconvertbuffer) Mem_Free(colorconvertbuffer);colorconvertbuffer = NULL;
489         if (resamplerow1) Mem_Free(resamplerow1);resamplerow1 = NULL;
490         if (resamplerow2) Mem_Free(resamplerow2);resamplerow2 = NULL;
491         if (texturebuffer) Mem_Free(texturebuffer);texturebuffer = NULL;
492         if (gltexnuminuse) Mem_Free(gltexnuminuse);gltexnuminuse = NULL;
493         */
494         resizebuffersize = 0;
495         resamplerowsize = 0;
496         texturebuffersize = 0;
497         resizebuffer = NULL;
498         colorconvertbuffer = NULL;
499         resamplerow1 = NULL;
500         resamplerow2 = NULL;
501         texturebuffer = NULL;
502         gltexnuminuse = NULL;
503         Mem_FreePool(&texturemempool);
504         Mem_FreePool(&texturedatamempool);
505         Mem_FreePool(&textureprocessingmempool);
506 }
507
508 static void r_textures_newmap(void)
509 {
510 }
511
512 void R_Textures_Init (void)
513 {
514         Cmd_AddCommand ("gl_texturemode", &GL_TextureMode_f);
515         Cmd_AddCommand("r_texturestats", R_TextureStats_f);
516         Cvar_RegisterVariable (&r_max_scrapsize);
517         Cvar_RegisterVariable (&r_max_size);
518         Cvar_RegisterVariable (&r_picmip);
519         Cvar_RegisterVariable (&r_lerpimages);
520         Cvar_RegisterVariable (&r_precachetextures);
521         gltexnuminuse = NULL;
522
523         R_RegisterModule("R_Textures", r_textures_start, r_textures_shutdown, r_textures_newmap);
524 }
525
526 static void R_ResampleTextureLerpLine (byte *in, byte *out, int inwidth, int outwidth, int bytesperpixel)
527 {
528         int             j, xi, oldx = 0, f, fstep, endx, lerp;
529         fstep = (int) (inwidth*65536.0f/outwidth);
530         endx = (inwidth-1);
531         if (bytesperpixel == 4)
532         {
533                 for (j = 0,f = 0;j < outwidth;j++, f += fstep)
534                 {
535                         xi = f >> 16;
536                         if (xi != oldx)
537                         {
538                                 in += (xi - oldx) * 4;
539                                 oldx = xi;
540                         }
541                         if (xi < endx)
542                         {
543                                 lerp = f & 0xFFFF;
544                                 *out++ = (byte) ((((in[4] - in[0]) * lerp) >> 16) + in[0]);
545                                 *out++ = (byte) ((((in[5] - in[1]) * lerp) >> 16) + in[1]);
546                                 *out++ = (byte) ((((in[6] - in[2]) * lerp) >> 16) + in[2]);
547                                 *out++ = (byte) ((((in[7] - in[3]) * lerp) >> 16) + in[3]);
548                         }
549                         else // last pixel of the line has no pixel to lerp to
550                         {
551                                 *out++ = in[0];
552                                 *out++ = in[1];
553                                 *out++ = in[2];
554                                 *out++ = in[3];
555                         }
556                 }
557         }
558         else if (bytesperpixel == 3)
559         {
560                 for (j = 0,f = 0;j < outwidth;j++, f += fstep)
561                 {
562                         xi = f >> 16;
563                         if (xi != oldx)
564                         {
565                                 in += (xi - oldx) * 3;
566                                 oldx = xi;
567                         }
568                         if (xi < endx)
569                         {
570                                 lerp = f & 0xFFFF;
571                                 *out++ = (byte) ((((in[3] - in[0]) * lerp) >> 16) + in[0]);
572                                 *out++ = (byte) ((((in[4] - in[1]) * lerp) >> 16) + in[1]);
573                                 *out++ = (byte) ((((in[5] - in[2]) * lerp) >> 16) + in[2]);
574                         }
575                         else // last pixel of the line has no pixel to lerp to
576                         {
577                                 *out++ = in[0];
578                                 *out++ = in[1];
579                                 *out++ = in[2];
580                         }
581                 }
582         }
583         else
584                 Sys_Error("R_ResampleTextureLerpLine: unsupported bytesperpixel %i\n", bytesperpixel);
585 }
586
587 /*
588 ================
589 R_ResampleTexture
590 ================
591 */
592 static void R_ResampleTexture (void *indata, int inwidth, int inheight, void *outdata,  int outwidth, int outheight, int bytesperpixel)
593 {
594         if (resamplerowsize < outwidth*4)
595         {
596                 if (resamplerow1)
597                         Mem_Free(resamplerow1);
598                 if (resamplerow2)
599                         Mem_Free(resamplerow2);
600                 resamplerowsize = outwidth*4;
601                 resamplerow1 = Mem_Alloc(textureprocessingmempool, resamplerowsize);
602                 resamplerow2 = Mem_Alloc(textureprocessingmempool, resamplerowsize);
603         }
604 #define row1 resamplerow1
605 #define row2 resamplerow2
606         if (bytesperpixel == 4)
607         {
608                 if (r_lerpimages.integer)
609                 {
610                         int             i, j, yi, oldy, f, fstep, lerp, endy = (inheight-1), inwidth4 = inwidth*4, outwidth4 = outwidth*4;
611                         byte    *inrow, *out;
612                         out = outdata;
613                         fstep = (int) (inheight*65536.0f/outheight);
614
615                         inrow = indata;
616                         oldy = 0;
617                         R_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth, bytesperpixel);
618                         R_ResampleTextureLerpLine (inrow + inwidth4, row2, inwidth, outwidth, bytesperpixel);
619                         for (i = 0, f = 0;i < outheight;i++,f += fstep)
620                         {
621                                 yi = f >> 16;
622                                 if (yi < endy)
623                                 {
624                                         lerp = f & 0xFFFF;
625                                         if (yi != oldy)
626                                         {
627                                                 inrow = (byte *)indata + inwidth4*yi;
628                                                 if (yi == oldy+1)
629                                                         memcpy(row1, row2, outwidth4);
630                                                 else
631                                                         R_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth, bytesperpixel);
632                                                 R_ResampleTextureLerpLine (inrow + inwidth4, row2, inwidth, outwidth, bytesperpixel);
633                                                 oldy = yi;
634                                         }
635                                         j = outwidth - 4;
636                                         while(j >= 0)
637                                         {
638 #define LERPBYTE(i) out[i] = (byte) ((((row2[i] - row1[i]) * lerp) >> 16) + row1[i])
639                                                 LERPBYTE( 0);
640                                                 LERPBYTE( 1);
641                                                 LERPBYTE( 2);
642                                                 LERPBYTE( 3);
643                                                 LERPBYTE( 4);
644                                                 LERPBYTE( 5);
645                                                 LERPBYTE( 6);
646                                                 LERPBYTE( 7);
647                                                 LERPBYTE( 8);
648                                                 LERPBYTE( 9);
649                                                 LERPBYTE(10);
650                                                 LERPBYTE(11);
651                                                 LERPBYTE(12);
652                                                 LERPBYTE(13);
653                                                 LERPBYTE(14);
654                                                 LERPBYTE(15);
655                                                 out += 16;
656                                                 row1 += 16;
657                                                 row2 += 16;
658                                                 j -= 4;
659                                         }
660                                         if (j & 2)
661                                         {
662                                                 LERPBYTE( 0);
663                                                 LERPBYTE( 1);
664                                                 LERPBYTE( 2);
665                                                 LERPBYTE( 3);
666                                                 LERPBYTE( 4);
667                                                 LERPBYTE( 5);
668                                                 LERPBYTE( 6);
669                                                 LERPBYTE( 7);
670                                                 out += 8;
671                                                 row1 += 8;
672                                                 row2 += 8;
673                                         }
674                                         if (j & 1)
675                                         {
676                                                 LERPBYTE( 0);
677                                                 LERPBYTE( 1);
678                                                 LERPBYTE( 2);
679                                                 LERPBYTE( 3);
680                                                 out += 4;
681                                                 row1 += 4;
682                                                 row2 += 4;
683                                         }
684                                         row1 -= outwidth4;
685                                         row2 -= outwidth4;
686                                 }
687                                 else
688                                 {
689                                         if (yi != oldy)
690                                         {
691                                                 inrow = (byte *)indata + inwidth4*yi;
692                                                 if (yi == oldy+1)
693                                                         memcpy(row1, row2, outwidth4);
694                                                 else
695                                                         R_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth, bytesperpixel);
696                                                 oldy = yi;
697                                         }
698                                         memcpy(out, row1, outwidth4);
699                                 }
700                         }
701                 }
702                 else
703                 {
704                         int i, j;
705                         unsigned frac, fracstep;
706                         // relies on int being 4 bytes
707                         int *inrow, *out;
708                         out = outdata;
709
710                         fracstep = inwidth*0x10000/outwidth;
711                         for (i = 0;i < outheight;i++)
712                         {
713                                 inrow = (int *)indata + inwidth*(i*inheight/outheight);
714                                 frac = fracstep >> 1;
715                                 j = outwidth - 4;
716                                 while (j >= 0)
717                                 {
718                                         out[0] = inrow[frac >> 16];frac += fracstep;
719                                         out[1] = inrow[frac >> 16];frac += fracstep;
720                                         out[2] = inrow[frac >> 16];frac += fracstep;
721                                         out[3] = inrow[frac >> 16];frac += fracstep;
722                                         out += 4;
723                                         j -= 4;
724                                 }
725                                 if (j & 2)
726                                 {
727                                         out[0] = inrow[frac >> 16];frac += fracstep;
728                                         out[1] = inrow[frac >> 16];frac += fracstep;
729                                         out += 2;
730                                 }
731                                 if (j & 1)
732                                 {
733                                         out[0] = inrow[frac >> 16];frac += fracstep;
734                                         out += 1;
735                                 }
736                         }
737                 }
738         }
739         else if (bytesperpixel == 3)
740         {
741                 if (r_lerpimages.integer)
742                 {
743                         int             i, j, yi, oldy, f, fstep, lerp, endy = (inheight-1), inwidth3 = inwidth * 3, outwidth3 = outwidth * 3;
744                         byte    *inrow, *out;
745                         out = outdata;
746                         fstep = (int) (inheight*65536.0f/outheight);
747
748                         inrow = indata;
749                         oldy = 0;
750                         R_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth, bytesperpixel);
751                         R_ResampleTextureLerpLine (inrow + inwidth3, row2, inwidth, outwidth, bytesperpixel);
752                         for (i = 0, f = 0;i < outheight;i++,f += fstep)
753                         {
754                                 yi = f >> 16;
755                                 if (yi < endy)
756                                 {
757                                         lerp = f & 0xFFFF;
758                                         if (yi != oldy)
759                                         {
760                                                 inrow = (byte *)indata + inwidth3*yi;
761                                                 if (yi == oldy+1)
762                                                         memcpy(row1, row2, outwidth3);
763                                                 else
764                                                         R_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth, bytesperpixel);
765                                                 R_ResampleTextureLerpLine (inrow + inwidth3, row2, inwidth, outwidth, bytesperpixel);
766                                                 oldy = yi;
767                                         }
768                                         j = outwidth - 4;
769                                         while(j >= 0)
770                                         {
771 #define LERPBYTE(i) out[i] = (byte) ((((row2[i] - row1[i]) * lerp) >> 16) + row1[i])
772                                                 LERPBYTE( 0);
773                                                 LERPBYTE( 1);
774                                                 LERPBYTE( 2);
775                                                 LERPBYTE( 3);
776                                                 LERPBYTE( 4);
777                                                 LERPBYTE( 5);
778                                                 LERPBYTE( 6);
779                                                 LERPBYTE( 7);
780                                                 LERPBYTE( 8);
781                                                 LERPBYTE( 9);
782                                                 LERPBYTE(10);
783                                                 LERPBYTE(11);
784                                                 out += 12;
785                                                 row1 += 12;
786                                                 row2 += 12;
787                                                 j -= 4;
788                                         }
789                                         if (j & 2)
790                                         {
791                                                 LERPBYTE( 0);
792                                                 LERPBYTE( 1);
793                                                 LERPBYTE( 2);
794                                                 LERPBYTE( 3);
795                                                 LERPBYTE( 4);
796                                                 LERPBYTE( 5);
797                                                 out += 6;
798                                                 row1 += 6;
799                                                 row2 += 6;
800                                         }
801                                         if (j & 1)
802                                         {
803                                                 LERPBYTE( 0);
804                                                 LERPBYTE( 1);
805                                                 LERPBYTE( 2);
806                                                 out += 3;
807                                                 row1 += 3;
808                                                 row2 += 3;
809                                         }
810                                         row1 -= outwidth3;
811                                         row2 -= outwidth3;
812                                 }
813                                 else
814                                 {
815                                         if (yi != oldy)
816                                         {
817                                                 inrow = (byte *)indata + inwidth3*yi;
818                                                 if (yi == oldy+1)
819                                                         memcpy(row1, row2, outwidth3);
820                                                 else
821                                                         R_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth, bytesperpixel);
822                                                 oldy = yi;
823                                         }
824                                         memcpy(out, row1, outwidth3);
825                                 }
826                         }
827                 }
828                 else
829                 {
830                         int i, j, f, inwidth3 = inwidth * 3;
831                         unsigned frac, fracstep;
832                         byte *inrow, *out;
833                         out = outdata;
834
835                         fracstep = inwidth*0x10000/outwidth;
836                         for (i = 0;i < outheight;i++)
837                         {
838                                 inrow = (byte *)indata + inwidth3*(i*inheight/outheight);
839                                 frac = fracstep >> 1;
840                                 j = outwidth - 4;
841                                 while (j >= 0)
842                                 {
843                                         f = (frac >> 16)*3;*out++ = inrow[f+0];*out++ = inrow[f+1];*out++ = inrow[f+2];frac += fracstep;
844                                         f = (frac >> 16)*3;*out++ = inrow[f+0];*out++ = inrow[f+1];*out++ = inrow[f+2];frac += fracstep;
845                                         f = (frac >> 16)*3;*out++ = inrow[f+0];*out++ = inrow[f+1];*out++ = inrow[f+2];frac += fracstep;
846                                         f = (frac >> 16)*3;*out++ = inrow[f+0];*out++ = inrow[f+1];*out++ = inrow[f+2];frac += fracstep;
847                                         j -= 4;
848                                 }
849                                 if (j & 2)
850                                 {
851                                         f = (frac >> 16)*3;*out++ = inrow[f+0];*out++ = inrow[f+1];*out++ = inrow[f+2];frac += fracstep;
852                                         f = (frac >> 16)*3;*out++ = inrow[f+0];*out++ = inrow[f+1];*out++ = inrow[f+2];frac += fracstep;
853                                         out += 2;
854                                 }
855                                 if (j & 1)
856                                 {
857                                         f = (frac >> 16)*3;*out++ = inrow[f+0];*out++ = inrow[f+1];*out++ = inrow[f+2];frac += fracstep;
858                                         out += 1;
859                                 }
860                         }
861                 }
862         }
863         else
864                 Sys_Error("R_ResampleTexture: unsupported bytesperpixel %i\n", bytesperpixel);
865 #undef row1
866 #undef row2
867 }
868
869 // in can be the same as out
870 static void R_MipReduce(byte *in, byte *out, int *width, int *height, int destwidth, int destheight, int bytesperpixel)
871 {
872         int x, y, nextrow;
873         nextrow = *width * bytesperpixel;
874         if (*width > destwidth)
875         {
876                 *width >>= 1;
877                 if (*height > destheight)
878                 {
879                         // reduce both
880                         *height >>= 1;
881                         if (bytesperpixel == 4)
882                         {
883                                 for (y = 0;y < *height;y++)
884                                 {
885                                         for (x = 0;x < *width;x++)
886                                         {
887                                                 out[0] = (byte) ((in[0] + in[4] + in[nextrow  ] + in[nextrow+4]) >> 2);
888                                                 out[1] = (byte) ((in[1] + in[5] + in[nextrow+1] + in[nextrow+5]) >> 2);
889                                                 out[2] = (byte) ((in[2] + in[6] + in[nextrow+2] + in[nextrow+6]) >> 2);
890                                                 out[3] = (byte) ((in[3] + in[7] + in[nextrow+3] + in[nextrow+7]) >> 2);
891                                                 out += 4;
892                                                 in += 8;
893                                         }
894                                         in += nextrow; // skip a line
895                                 }
896                         }
897                         else if (bytesperpixel == 3)
898                         {
899                                 for (y = 0;y < *height;y++)
900                                 {
901                                         for (x = 0;x < *width;x++)
902                                         {
903                                                 out[0] = (byte) ((in[0] + in[3] + in[nextrow  ] + in[nextrow+3]) >> 2);
904                                                 out[1] = (byte) ((in[1] + in[4] + in[nextrow+1] + in[nextrow+4]) >> 2);
905                                                 out[2] = (byte) ((in[2] + in[5] + in[nextrow+2] + in[nextrow+5]) >> 2);
906                                                 out += 3;
907                                                 in += 6;
908                                         }
909                                         in += nextrow; // skip a line
910                                 }
911                         }
912                         else
913                                 Sys_Error("R_MipReduce: unsupported bytesperpixel %i\n", bytesperpixel);
914                 }
915                 else
916                 {
917                         // reduce width
918                         if (bytesperpixel == 4)
919                         {
920                                 for (y = 0;y < *height;y++)
921                                 {
922                                         for (x = 0;x < *width;x++)
923                                         {
924                                                 out[0] = (byte) ((in[0] + in[4]) >> 1);
925                                                 out[1] = (byte) ((in[1] + in[5]) >> 1);
926                                                 out[2] = (byte) ((in[2] + in[6]) >> 1);
927                                                 out[3] = (byte) ((in[3] + in[7]) >> 1);
928                                                 out += 4;
929                                                 in += 8;
930                                         }
931                                 }
932                         }
933                         else if (bytesperpixel == 3)
934                         {
935                                 for (y = 0;y < *height;y++)
936                                 {
937                                         for (x = 0;x < *width;x++)
938                                         {
939                                                 out[0] = (byte) ((in[0] + in[3]) >> 1);
940                                                 out[1] = (byte) ((in[1] + in[4]) >> 1);
941                                                 out[2] = (byte) ((in[2] + in[5]) >> 1);
942                                                 out += 3;
943                                                 in += 6;
944                                         }
945                                 }
946                         }
947                         else
948                                 Sys_Error("R_MipReduce: unsupported bytesperpixel %i\n", bytesperpixel);
949                 }
950         }
951         else
952         {
953                 if (*height > destheight)
954                 {
955                         // reduce height
956                         *height >>= 1;
957                         if (bytesperpixel == 4)
958                         {
959                                 for (y = 0;y < *height;y++)
960                                 {
961                                         for (x = 0;x < *width;x++)
962                                         {
963                                                 out[0] = (byte) ((in[0] + in[nextrow  ]) >> 1);
964                                                 out[1] = (byte) ((in[1] + in[nextrow+1]) >> 1);
965                                                 out[2] = (byte) ((in[2] + in[nextrow+2]) >> 1);
966                                                 out[3] = (byte) ((in[3] + in[nextrow+3]) >> 1);
967                                                 out += 4;
968                                                 in += 4;
969                                         }
970                                         in += nextrow; // skip a line
971                                 }
972                         }
973                         else if (bytesperpixel == 3)
974                         {
975                                 for (y = 0;y < *height;y++)
976                                 {
977                                         for (x = 0;x < *width;x++)
978                                         {
979                                                 out[0] = (byte) ((in[0] + in[nextrow  ]) >> 1);
980                                                 out[1] = (byte) ((in[1] + in[nextrow+1]) >> 1);
981                                                 out[2] = (byte) ((in[2] + in[nextrow+2]) >> 1);
982                                                 out += 3;
983                                                 in += 3;
984                                         }
985                                         in += nextrow; // skip a line
986                                 }
987                         }
988                         else
989                                 Sys_Error("R_MipReduce: unsupported bytesperpixel %i\n", bytesperpixel);
990                 }
991                 else
992                         Sys_Error("R_MipReduce: desired size already achieved\n");
993         }
994 }
995
996 static void R_Upload(gltexture_t *glt, byte *data)
997 {
998         int mip, width, height, internalformat;
999         byte *prevbuffer;
1000         prevbuffer = data;
1001
1002         glBindTexture(GL_TEXTURE_2D, glt->image->texnum);
1003         CHECKGLERROR
1004
1005         glt->flags &= ~GLTEXF_UPLOAD;
1006
1007         if (glt->flags & TEXF_FRAGMENT)
1008         {
1009                 if (resizebuffersize < glt->image->width * glt->image->height * glt->image->bytesperpixel)
1010                 {
1011                         resizebuffersize = glt->image->width * glt->image->height * glt->image->bytesperpixel;
1012                         if (resizebuffer)
1013                                 Mem_Free(resizebuffer);
1014                         if (colorconvertbuffer)
1015                                 Mem_Free(colorconvertbuffer);
1016                         resizebuffer = Mem_Alloc(textureprocessingmempool, resizebuffersize);
1017                         colorconvertbuffer = Mem_Alloc(textureprocessingmempool, resizebuffersize);
1018                         if (!resizebuffer || !colorconvertbuffer)
1019                                 Host_Error("R_Upload: out of memory\n");
1020                 }
1021
1022                 if (glt->image->flags & GLTEXF_UPLOAD)
1023                 {
1024                         Con_DPrintf("uploaded new fragments image\n");
1025                         glt->image->flags &= ~GLTEXF_UPLOAD;
1026                         memset(resizebuffer, 255, glt->image->width * glt->image->height * glt->image->bytesperpixel);
1027                         glTexImage2D (GL_TEXTURE_2D, 0, glt->image->glinternalformat, glt->image->width, glt->image->height, 0, glt->image->glformat, GL_UNSIGNED_BYTE, resizebuffer);
1028                         CHECKGLERROR
1029                         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_mag);
1030                         CHECKGLERROR
1031                         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_mag);
1032                         CHECKGLERROR
1033                 }
1034
1035                 if (prevbuffer == NULL)
1036                 {
1037                         memset(resizebuffer, 255, glt->width * glt->height * glt->image->bytesperpixel);
1038                         prevbuffer = resizebuffer;
1039                 }
1040                 else if (glt->textype->textype == TEXTYPE_QPALETTE)
1041                 {
1042                         // promote paletted to RGBA, so we only have to worry about RGB and
1043                         // RGBA in the rest of this code
1044                         Image_Copy8bitRGBA(prevbuffer, colorconvertbuffer, glt->width * glt->height, d_8to24table);
1045                         prevbuffer = colorconvertbuffer;
1046                 }
1047
1048                 glTexSubImage2D(GL_TEXTURE_2D, 0, glt->x, glt->y, glt->width, glt->height, glt->image->glformat, GL_UNSIGNED_BYTE, prevbuffer);
1049                 CHECKGLERROR
1050                 return;
1051         }
1052
1053         glt->image->flags &= ~GLTEXF_UPLOAD;
1054
1055         // these are rounded up versions of the size to do better resampling
1056         for (width = 1;width < glt->width;width <<= 1);
1057         for (height = 1;height < glt->height;height <<= 1);
1058
1059         if (resizebuffersize < width * height * glt->image->bytesperpixel)
1060         {
1061                 resizebuffersize = width * height * glt->image->bytesperpixel;
1062                 if (resizebuffer)
1063                         Mem_Free(resizebuffer);
1064                 if (colorconvertbuffer)
1065                         Mem_Free(colorconvertbuffer);
1066                 resizebuffer = Mem_Alloc(textureprocessingmempool, resizebuffersize);
1067                 colorconvertbuffer = Mem_Alloc(textureprocessingmempool, resizebuffersize);
1068                 if (!resizebuffer || !colorconvertbuffer)
1069                         Host_Error("R_Upload: out of memory\n");
1070         }
1071
1072         if (prevbuffer == NULL)
1073         {
1074                 width = glt->image->width;
1075                 height = glt->image->height;
1076                 memset(resizebuffer, 255, width * height * glt->image->bytesperpixel);
1077                 prevbuffer = resizebuffer;
1078         }
1079         else
1080         {
1081                 if (glt->textype->textype == TEXTYPE_QPALETTE)
1082                 {
1083                         // promote paletted to RGBA, so we only have to worry about RGB and
1084                         // RGBA in the rest of this code
1085                         Image_Copy8bitRGBA(prevbuffer, colorconvertbuffer, glt->width * glt->height, d_8to24table);
1086                         prevbuffer = colorconvertbuffer;
1087                 }
1088
1089                 if (glt->width != width || glt->height != height)
1090                 {
1091                         R_ResampleTexture(prevbuffer, glt->width, glt->height, resizebuffer, width, height, glt->image->bytesperpixel);
1092                         prevbuffer = resizebuffer;
1093                 }
1094
1095                 // apply picmip/max_size limitations
1096                 while (width > glt->image->width || height > glt->image->height)
1097                 {
1098                         R_MipReduce(prevbuffer, resizebuffer, &width, &height, glt->image->width, glt->image->height, glt->image->bytesperpixel);
1099                         prevbuffer = resizebuffer;
1100                 }
1101         }
1102
1103         // 3 and 4 are converted by the driver to it's preferred format for the current display mode
1104         internalformat = 3;
1105         if (glt->flags & TEXF_ALPHA)
1106                 internalformat = 4;
1107
1108         mip = 0;
1109         glTexImage2D(GL_TEXTURE_2D, mip++, internalformat, width, height, 0, glt->image->glformat, GL_UNSIGNED_BYTE, prevbuffer);
1110         CHECKGLERROR
1111         if (glt->flags & TEXF_MIPMAP)
1112         {
1113                 while (width > 1 || height > 1)
1114                 {
1115                         R_MipReduce(prevbuffer, resizebuffer, &width, &height, 1, 1, glt->image->bytesperpixel);
1116                         prevbuffer = resizebuffer;
1117
1118                         glTexImage2D(GL_TEXTURE_2D, mip++, internalformat, width, height, 0, glt->image->glformat, GL_UNSIGNED_BYTE, prevbuffer);
1119                         CHECKGLERROR
1120                 }
1121
1122                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min);
1123                 CHECKGLERROR
1124                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_mag);
1125                 CHECKGLERROR
1126         }
1127         else
1128         {
1129                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_mag);
1130                 CHECKGLERROR
1131                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_mag);
1132                 CHECKGLERROR
1133         }
1134 }
1135
1136 static void R_FindImageForTexture(gltexture_t *glt)
1137 {
1138         int i, j, best, best2, x, y, w, h;
1139         textypeinfo_t *texinfo;
1140         gltexturepool_t *pool;
1141         gltextureimage_t *image, **imagechainpointer;
1142         texinfo = glt->textype;
1143         pool = glt->pool;
1144
1145         x = 0;
1146         y = 0;
1147         w = glt->width;
1148         h = glt->height;
1149         if (glt->flags & TEXF_FRAGMENT)
1150         {
1151                 for (imagechainpointer = &pool->imagechain;*imagechainpointer;imagechainpointer = &(*imagechainpointer)->imagechain)
1152                 {
1153                         image = *imagechainpointer;
1154                         if (image->type != GLIMAGETYPE_FRAGMENTS)
1155                                 continue;
1156                         if (image->glformat != texinfo->glformat || image->glinternalformat != texinfo->glinternalformat)
1157                                 continue;
1158
1159                         // got a fragments texture, find a place in it if we can
1160                         best = block_size;
1161                         for (best = block_size, i = 0;i < block_size - w;i += texinfo->align)
1162                         {
1163                                 for (best2 = 0, j = 0;j < w;j++)
1164                                 {
1165                                         if (image->blockallocation[i+j] >= best)
1166                                                 break;
1167                                         if (best2 < image->blockallocation[i+j])
1168                                                 best2 = image->blockallocation[i+j];
1169                                 }
1170                                 if (j == w)
1171                                 {
1172                                         // this is a valid spot
1173                                         x = i;
1174                                         y = best = best2;
1175                                 }
1176                         }
1177
1178                         if (best + h > block_size)
1179                                 continue;
1180
1181                         for (i = 0;i < w;i++)
1182                                 image->blockallocation[x + i] = best + h;
1183
1184                         glt->x = x;
1185                         glt->y = y;
1186                         glt->image = image;
1187                         image->texturecount++;
1188                         return;
1189                 }
1190
1191                 image = Mem_Alloc(texturemempool, sizeof(gltextureimage_t));
1192                 if (image == NULL)
1193                         Sys_Error("R_FindImageForTexture: ran out of memory\n");
1194                 //memset(image, 0, sizeof(*image));
1195                 image->type = GLIMAGETYPE_FRAGMENTS;
1196                 image->width = block_size;
1197                 image->height = block_size;
1198                 image->blockallocation = Mem_Alloc(texturemempool, block_size * sizeof(short));
1199                 memset(image->blockallocation, 0, block_size * sizeof(short));
1200
1201                 x = 0;
1202                 y = 0;
1203                 for (i = 0;i < w;i++)
1204                         image->blockallocation[x + i] = y + h;
1205         }
1206         else
1207         {
1208                 for (imagechainpointer = &pool->imagechain;*imagechainpointer;imagechainpointer = &(*imagechainpointer)->imagechain);
1209
1210                 image = Mem_Alloc(texturemempool, sizeof(gltextureimage_t));
1211                 if (image == NULL)
1212                         Sys_Error("R_FindImageForTexture: ran out of memory\n");
1213                 //memset(image, 0, sizeof(*image));
1214                 image->type = GLIMAGETYPE_TILE;
1215                 image->blockallocation = NULL;
1216
1217                 // calculate final size
1218                 if (r_max_size.integer > realmaxsize)
1219                         Cvar_SetValue("r_max_size", realmaxsize);
1220                 for (image->width = 1;image->width < glt->width;image->width <<= 1);
1221                 for (image->height = 1;image->height < glt->height;image->height <<= 1);
1222                 for (image->width >>= r_picmip.integer;image->width > r_max_size.integer;image->width >>= 1);
1223                 for (image->height >>= r_picmip.integer;image->height > r_max_size.integer;image->height >>= 1);
1224                 if (image->width < 1) image->width = 1;
1225                 if (image->height < 1) image->height = 1;
1226         }
1227         image->glinternalformat = texinfo->glinternalformat;
1228         image->glformat = texinfo->glformat;
1229         image->flags = (glt->flags & (TEXF_MIPMAP | TEXF_ALPHA)) | GLTEXF_UPLOAD;
1230         image->bytesperpixel = texinfo->internalbytesperpixel;
1231         for (i = 1;i < MAX_GLTEXTURES;i++)
1232                 if (!gltexnuminuse[i])
1233                         break;
1234         if (i < MAX_GLTEXTURES)
1235                 gltexnuminuse[image->texnum = i] = true;
1236         else
1237                 Sys_Error("R_FindImageForTexture: ran out of GL textures\n");
1238         *imagechainpointer = image;
1239         image->texturecount++;
1240
1241         glt->x = x;
1242         glt->y = y;
1243         glt->image = image;
1244 }
1245
1246 // note: R_FindImageForTexture must be called before this
1247 static void R_UploadTexture (gltexture_t *glt)
1248 {
1249         if (!(glt->flags & (GLTEXF_UPLOAD | GLTEXF_PROCEDURAL)))
1250                 return;
1251
1252         if (glt->flags & GLTEXF_PROCEDURAL)
1253         {
1254                 if (glt->generate)
1255                 {
1256                         if (texturebuffersize < glt->width * glt->height * glt->textype->inputbytesperpixel)
1257                         {
1258                                 if (texturebuffer)
1259                                         Mem_Free(texturebuffer);
1260                                 texturebuffersize = glt->width * glt->height * glt->textype->inputbytesperpixel;
1261                                 texturebuffer = Mem_Alloc(textureprocessingmempool, texturebuffersize);
1262                         }
1263
1264                         glt->generate(texturebuffer, glt->width, glt->height, (void *)glt->proceduraldata, glt->proceduraldatasize);
1265                 }
1266         }
1267         else
1268         {
1269                 R_Upload(glt, glt->inputtexels);
1270                 if (glt->inputtexels)
1271                 {
1272                         Mem_Free(glt->inputtexels);
1273                         glt->inputtexels = NULL;
1274                         glt->flags |= GLTEXF_DESTROYED;
1275                 }
1276                 else if (glt->flags & GLTEXF_DESTROYED)
1277                         Con_Printf("R_UploadTexture: Texture %s already uploaded and destroyed.  Can not upload original image again.  Uploaded blank texture.\n", glt->identifier);
1278         }
1279 }
1280
1281 static gltexture_t *R_SetupTexture(gltexturepool_t *pool, char *identifier, int crc, int width, int height, int flags, textypeinfo_t *texinfo, byte *data, int (*generate)(byte *buffer, int width, int height, void *proceduraldata, int proceduraldatasize), void *proceduraldata, int proceduraldatasize)
1282 {
1283         gltexture_t *glt;
1284         glt = Mem_Alloc(texturemempool, sizeof(gltexture_t));
1285         //memset(glt, 0, sizeof(gltexture_t));
1286         if (identifier)
1287         {
1288                 glt->identifier = Mem_Alloc(texturemempool, strlen(identifier)+1);
1289                 strcpy (glt->identifier, identifier);
1290         }
1291         else
1292                 glt->identifier = NULL;
1293         glt->pool = pool;
1294         glt->chain = pool->gltchain;
1295         pool->gltchain = glt;
1296         glt->crc = crc;
1297         glt->width = width;
1298         glt->height = height;
1299         glt->flags = flags;
1300         glt->textype = texinfo;
1301
1302         if (data)
1303         {
1304                 glt->inputtexels = Mem_Alloc(texturedatamempool, glt->width * glt->height * texinfo->inputbytesperpixel);
1305                 if (glt->inputtexels == NULL)
1306                         Sys_Error("R_SetupTexture: out of memory\n");
1307                 memcpy(glt->inputtexels, data, glt->width * glt->height * texinfo->inputbytesperpixel);
1308         }
1309         else
1310                 glt->inputtexels = NULL;
1311
1312         glt->generate = generate;
1313         glt->proceduraldatasize = proceduraldatasize;
1314         if (proceduraldatasize)
1315         {
1316                 glt->proceduraldata = Mem_Alloc(texturemempool, proceduraldatasize);
1317                 if (glt->proceduraldata == NULL)
1318                         Sys_Error("R_SetupTexture: out of memory\n");
1319         }
1320         else
1321                 glt->proceduraldata = NULL;
1322
1323         R_FindImageForTexture(glt);
1324         R_PrecacheTexture(glt);
1325
1326         return glt;
1327 }
1328
1329 /*
1330 ================
1331 R_LoadTexture
1332 ================
1333 */
1334 rtexture_t *R_LoadTexture (rtexturepool_t *rtexturepool, char *identifier, int width, int height, byte *data, int textype, int flags)
1335 {
1336         int i;
1337         gltexture_t *glt;
1338         gltexturepool_t *pool = (gltexturepool_t *)rtexturepool;
1339         textypeinfo_t *texinfo;
1340         unsigned short crc;
1341
1342         if (cls.state == ca_dedicated)
1343                 return NULL;
1344
1345         texinfo = R_GetTexTypeInfo(textype, flags);
1346
1347         // data can be NULL
1348 //      if (data == NULL)
1349 //              Host_Error("R_LoadTexture: \"%s\" has no data\n", identifier);
1350
1351         if (flags & TEXF_FRAGMENT)
1352         {
1353                 if (width > block_size || height > block_size)
1354                         Host_Error("R_LoadTexture: fragment too big, must be no more than %dx%d\n", block_size, block_size);
1355                 if ((width * texinfo->internalbytesperpixel) & 3)
1356                         Host_Error("R_LoadTexture: incompatible width for fragment");
1357         }
1358
1359         // clear the alpha flag if the texture has no transparent pixels
1360         switch(textype)
1361         {
1362         case TEXTYPE_QPALETTE:
1363                 if (flags & TEXF_ALPHA)
1364                 {
1365                         flags &= ~TEXF_ALPHA;
1366                         for (i = 0;i < width * height;i++)
1367                         {
1368                                 if (data[i] == 255)
1369                                 {
1370                                         flags |= TEXF_ALPHA;
1371                                         break;
1372                                 }
1373                         }
1374                 }
1375                 break;
1376         case TEXTYPE_RGB:
1377                 if (flags & TEXF_ALPHA)
1378                         Host_Error("R_LoadTexture: RGB has no alpha, don't specify TEXF_ALPHA\n");
1379                 break;
1380         case TEXTYPE_RGBA:
1381                 if (flags & TEXF_ALPHA)
1382                 {
1383                         flags &= ~TEXF_ALPHA;
1384                         for (i = 0;i < width * height;i++)
1385                         {
1386                                 if (data[i * 4 + 3] < 255)
1387                                 {
1388                                         flags |= TEXF_ALPHA;
1389                                         break;
1390                                 }
1391                         }
1392                 }
1393                 break;
1394         default:
1395                 Host_Error("R_LoadTexture: unknown texture type\n");
1396         }
1397
1398         // LordHavoc: do a CRC to confirm the data really is the same as previous occurances.
1399         if (data == NULL)
1400                 crc = 0;
1401         else
1402                 crc = CRC_Block(data, width*height*texinfo->inputbytesperpixel);
1403
1404         // see if the texture is already present
1405         if (identifier && (glt = R_FindTexture(pool, identifier)))
1406         {
1407                 if (crc == glt->crc && width == glt->width && height == glt->height && texinfo == glt->textype && ((flags ^ glt->flags) & TEXF_IMPORTANTBITS) == 0 && ((flags ^ glt->flags) & GLTEXF_IMPORTANTBITS) == 0)
1408                 {
1409                         Con_Printf("R_LoadTexture: exact match with existing texture %s\n", identifier);
1410                         return (rtexture_t *)glt; // exact match, use existing
1411                 }
1412                 Con_Printf("R_LoadTexture: cache mismatch on %s, replacing old texture\n", identifier);
1413                 R_FreeTexture(glt);
1414         }
1415
1416         return (rtexture_t *)R_SetupTexture(pool, identifier, crc, width, height, flags | GLTEXF_UPLOAD, texinfo, data, NULL, NULL, 0);
1417 }
1418
1419 rtexture_t *R_ProceduralTexture (rtexturepool_t *rtexturepool, char *identifier, int width, int height, int textype, int flags, int (*generate)(byte *buffer, int width, int height, void *proceduraldata, int proceduraldatasize), void *proceduraldata, int proceduraldatasize)
1420 {
1421         gltexture_t             *glt;
1422         gltexturepool_t *pool = (gltexturepool_t *)rtexturepool;
1423         textypeinfo_t   *texinfo;
1424
1425         if (cls.state == ca_dedicated)
1426                 return NULL;
1427
1428         texinfo = R_GetTexTypeInfo(textype, flags);
1429
1430         // no function is supported, for odd uses
1431 //      if (generate == NULL)
1432 //              Host_Error("R_ProceduralTexture: \"%s\" has no generate function\n", identifier);
1433         if (flags & TEXF_FRAGMENT)
1434         {
1435                 if (width > block_size || height > block_size)
1436                         Host_Error("R_ProceduralTexture: fragment too big, must be no more than %dx%d\n", block_size, block_size);
1437                 if ((width * texinfo->internalbytesperpixel) & 3)
1438                         Host_Error("R_ProceduralTexture: incompatible width for fragment");
1439         }
1440
1441         // see if the texture is already present
1442         if (identifier && (glt = R_FindTexture(pool, identifier)))
1443         {
1444                 if (width == glt->width && height == glt->height && texinfo == glt->textype && ((flags ^ glt->flags) & TEXF_IMPORTANTBITS) == 0 && ((flags ^ glt->flags) & GLTEXF_IMPORTANTBITS) == 0)
1445                 {
1446                         Con_Printf("R_LoadTexture: exact match with existing texture %s\n", identifier);
1447                         return (rtexture_t *)glt; // exact match, use existing
1448                 }
1449                 Con_Printf("R_LoadTexture: cache mismatch, replacing old texture\n");
1450                 R_FreeTexture(glt);
1451         }
1452
1453         return (rtexture_t *)R_SetupTexture(pool, identifier, 0, width, height, flags | GLTEXF_PROCEDURAL | GLTEXF_UPLOAD, texinfo, NULL, generate, proceduraldata, proceduraldatasize);
1454 }
1455
1456 int R_TextureHasAlpha(rtexture_t *rt)
1457 {
1458         gltexture_t *glt;
1459         if (!rt)
1460                 return false;
1461         glt = (gltexture_t *)rt;
1462         return (glt->flags & TEXF_ALPHA) != 0;
1463 }
1464
1465 int R_TextureWidth(rtexture_t *rt)
1466 {
1467         if (!rt)
1468                 return false;
1469         return ((gltexture_t *)rt)->width;
1470 }
1471
1472 int R_TextureHeight(rtexture_t *rt)
1473 {
1474         if (!rt)
1475                 return false;
1476         return ((gltexture_t *)rt)->height;
1477 }
1478
1479 void R_FragmentLocation(rtexture_t *rt, int *x, int *y, float *fx1, float *fy1, float *fx2, float *fy2)
1480 {
1481         gltexture_t *glt;
1482         float iwidth, iheight;
1483         if (cls.state == ca_dedicated)
1484         {
1485                 if (x)
1486                         *x = 0;
1487                 if (y)
1488                         *y = 0;
1489                 if (fx1 || fy1 || fx2 || fy2)
1490                 {
1491                         if (fx1)
1492                                 *fx1 = 0;
1493                         if (fy1)
1494                                 *fy1 = 0;
1495                         if (fx2)
1496                                 *fx2 = 1;
1497                         if (fy2)
1498                                 *fy2 = 1;
1499                 }
1500                 return;
1501         }
1502         if (!rt)
1503                 Host_Error("R_FragmentLocation: no texture supplied\n");
1504         glt = (gltexture_t *)rt;
1505         if (glt->flags & TEXF_FRAGMENT)
1506         {
1507                 if (x)
1508                         *x = glt->x;
1509                 if (y)
1510                         *y = glt->y;
1511                 if (fx1 || fy1 || fx2 || fy2)
1512                 {
1513                         iwidth = 1.0f / glt->image->width;
1514                         iheight = 1.0f / glt->image->height;
1515                         if (fx1)
1516                                 *fx1 = glt->x * iwidth;
1517                         if (fy1)
1518                                 *fy1 = glt->y * iheight;
1519                         if (fx2)
1520                                 *fx2 = (glt->x + glt->width) * iwidth;
1521                         if (fy2)
1522                                 *fy2 = (glt->y + glt->height) * iheight;
1523                 }
1524         }
1525         else
1526         {
1527                 if (x)
1528                         *x = 0;
1529                 if (y)
1530                         *y = 0;
1531                 if (fx1 || fy1 || fx2 || fy2)
1532                 {
1533                         if (fx1)
1534                                 *fx1 = 0;
1535                         if (fy1)
1536                                 *fy1 = 0;
1537                         if (fx2)
1538                                 *fx2 = 1;
1539                         if (fy2)
1540                                 *fy2 = 1;
1541                 }
1542         }
1543 }
1544
1545 int R_CompatibleFragmentWidth(int width, int textype, int flags)
1546 {
1547         textypeinfo_t *texinfo = R_GetTexTypeInfo(textype, flags);
1548         while ((width * texinfo->internalbytesperpixel) & 3)
1549                 width++;
1550         return width;
1551 }
1552
1553 void R_UpdateTexture(rtexture_t *rt, byte *data)
1554 {
1555         gltexture_t *glt;
1556         if (rt == NULL)
1557                 Host_Error("R_UpdateTexture: no texture supplied\n");
1558         if (data == NULL)
1559                 Host_Error("R_UpdateTexture: no data supplied\n");
1560         glt = (gltexture_t *)rt;
1561         /*
1562         if (!(glt->flags & GLTEXF_PROCEDURAL))
1563         {
1564                 if (glt->inputtexels == NULL)
1565                 {
1566                         glt->inputtexels = Mem_Alloc(texturedatamempool, glt->width * glt->height * glt->textype->inputbytesperpixel);
1567                         if (glt->inputtexels == NULL)
1568                                 Host_Error("R_UpdateTexture: ran out of memory\n");
1569                 }
1570                 memcpy(glt->inputtexels, data, glt->width * glt->height * glt->textype->inputbytesperpixel);
1571         }
1572         R_Upload(glt, data);
1573         */
1574         // if it has not been uploaded yet, update the data that will be used when it is
1575         if (glt->inputtexels)
1576                 memcpy(glt->inputtexels, data, glt->width * glt->height * glt->textype->inputbytesperpixel);
1577         else
1578                 R_Upload(glt, data);
1579 }
1580