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