fragment images made for fragment textures will now always be big enough for the...
[divverent/darkplaces.git] / gl_textures.c
1
2 #include "quakedef.h"
3
4 cvar_t  r_max_size = {CVAR_SAVE, "r_max_size", "2048"};
5 cvar_t  r_max_scrapsize = {CVAR_SAVE, "r_max_scrapsize", "256"};
6 cvar_t  r_picmip = {CVAR_SAVE, "r_picmip", "0"};
7 cvar_t  r_lerpimages = {CVAR_SAVE, "r_lerpimages", "1"};
8 cvar_t  r_precachetextures = {CVAR_SAVE, "r_precachetextures", "1"};
9
10 int             gl_filter_min = GL_LINEAR_MIPMAP_LINEAR;
11 int             gl_filter_mag = GL_LINEAR;
12
13
14 static mempool_t *texturemempool;
15 static mempool_t *texturedatamempool;
16 static mempool_t *textureprocessingmempool;
17
18 // note: this must not conflict with TEXF_ flags in r_textures.h
19 // cleared when a texture is uploaded
20 #define GLTEXF_UPLOAD 0x00010000
21 // texture generated by code, also causes permanent GLTEXF_UPLOAD effect
22 #define GLTEXF_PROCEDURAL 0x00020000
23 // bitmask for mismatch checking
24 #define GLTEXF_IMPORTANTBITS (GLTEXF_PROCEDURAL)
25 // set when image is uploaded and freed
26 #define GLTEXF_DESTROYED 0x00040000
27
28 // size of images which hold fragment textures, ignores picmip and max_size
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 qbyte *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         qbyte *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)(qbyte *buffer, int width, int height, void *parameterdata, int parameterdatasize);
97         // data provided to generate, persistent from call to call
98         qbyte *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 qbyte *resizebuffer = NULL, *colorconvertbuffer;
122 static int resizebuffersize = 0;
123 static qbyte *texturebuffer;
124 static int texturebuffersize = 0;
125
126 static int realmaxsize = 0;
127
128 static textypeinfo_t *R_GetTexTypeInfo(int textype, int flags)
129 {
130         if (flags & TEXF_ALPHA)
131         {
132                 switch(textype)
133                 {
134                 case TEXTYPE_QPALETTE:
135                         return &textype_qpalette_alpha;
136                 case TEXTYPE_RGB:
137                         Host_Error("R_GetTexTypeInfo: RGB format has no alpha, TEXF_ALPHA not allowed\n");
138                         return NULL;
139                 case TEXTYPE_RGBA:
140                         return &textype_rgba_alpha;
141                 default:
142                         Host_Error("R_GetTexTypeInfo: unknown texture format\n");
143                         return NULL;
144                 }
145         }
146         else
147         {
148                 switch(textype)
149                 {
150                 case TEXTYPE_QPALETTE:
151                         return &textype_qpalette;
152                 case TEXTYPE_RGB:
153                         return &textype_rgb;
154                 case TEXTYPE_RGBA:
155                         return &textype_rgba;
156                 default:
157                         Host_Error("R_GetTexTypeInfo: unknown texture format\n");
158                         return NULL;
159                 }
160         }
161 }
162
163 static void R_UploadTexture(gltexture_t *t);
164
165 static void R_PrecacheTexture(gltexture_t *glt)
166 {
167         int precache;
168         precache = false;
169         if (glt->flags & TEXF_ALWAYSPRECACHE)
170                 precache = true;
171         else if (r_precachetextures.integer >= 2)
172                 precache = true;
173         else if (r_precachetextures.integer >= 1)
174                 if (glt->flags & TEXF_PRECACHE)
175                         precache = true;
176
177         if (precache)
178                 R_UploadTexture(glt);
179 }
180
181 int R_GetTexture(rtexture_t *rt)
182 {
183         gltexture_t *glt;
184         if (!rt)
185                 return 0;
186         glt = (gltexture_t *)rt;
187         if (glt->flags & (GLTEXF_UPLOAD | GLTEXF_PROCEDURAL))
188         {
189                 if (glt->flags & GLTEXF_PROCEDURAL)
190                 {
191                         if (glt->proceduralframecount != r_framecount)
192                         {
193                                 glt->proceduralframecount = r_framecount;
194                                 R_UploadTexture(glt);
195                         }
196                 }
197                 else
198                         R_UploadTexture(glt);
199         }
200         return glt->image->texnum;
201 }
202
203 void R_FreeTexture(rtexture_t *rt)
204 {
205         gltexture_t *glt, **gltpointer;
206         gltextureimage_t *image, **gltimagepointer;
207         GLuint texnum;
208
209         glt = (gltexture_t *)rt;
210         if (glt == NULL)
211                 Host_Error("R_FreeTexture: texture == NULL\n");
212
213         for (gltpointer = &glt->pool->gltchain;*gltpointer && *gltpointer != glt;gltpointer = &(*gltpointer)->chain);
214         if (*gltpointer == glt)
215                 *gltpointer = glt->chain;
216         else
217                 Host_Error("R_FreeTexture: texture \"%s\" not linked in pool\n", glt->identifier);
218
219         // note: if freeing a fragment texture, this will not make the claimed
220         // space available for new textures unless all other fragments in the
221         // image are also freed
222         image = glt->image;
223         image->texturecount--;
224         if (image->texturecount < 1)
225         {
226                 for (gltimagepointer = &glt->pool->imagechain;*gltimagepointer && *gltimagepointer != image;gltimagepointer = &(*gltimagepointer)->imagechain);
227                 if (*gltimagepointer == image)
228                         *gltimagepointer = image->imagechain;
229                 else
230                         Host_Error("R_FreeTexture: image not linked in pool\n");
231                 if (image->texnum)
232                 {
233                         texnum = image->texnum;
234                         gltexnuminuse[image->texnum] = 0;
235                         qglDeleteTextures(1, &texnum);
236                 }
237                 if (image->blockallocation)
238                         Mem_Free(image->blockallocation);
239                 Mem_Free(image);
240         }
241
242         if (glt->identifier)
243                 Mem_Free(glt->identifier);
244         if (glt->inputtexels)
245                 Mem_Free(glt->inputtexels);
246         if (glt->proceduraldata)
247                 Mem_Free(glt->proceduraldata);
248         Mem_Free(glt);
249 }
250
251 static gltexture_t *R_FindTexture (gltexturepool_t *pool, char *identifier)
252 {
253         gltexture_t     *glt;
254
255         if (!identifier)
256                 return NULL;
257
258         for (glt = pool->gltchain;glt;glt = glt->chain)
259                 if (glt->identifier && !strcmp (identifier, glt->identifier))
260                         return glt;
261
262         return NULL;
263 }
264
265 rtexturepool_t *R_AllocTexturePool(void)
266 {
267         gltexturepool_t *pool;
268         if (texturemempool == NULL)
269                 return NULL;
270         pool = Mem_Alloc(texturemempool, sizeof(gltexturepool_t));
271         if (pool == NULL)
272                 return NULL;
273         pool->next = gltexturepoolchain;
274         gltexturepoolchain = pool;
275         pool->sentinel = TEXTUREPOOL_SENTINEL;
276         return (rtexturepool_t *)pool;
277 }
278
279 void R_FreeTexturePool(rtexturepool_t **rtexturepool)
280 {
281         gltexturepool_t *pool, **poolpointer;
282         if (rtexturepool == NULL)
283                 return;
284         if (*rtexturepool == NULL)
285                 return;
286         pool = (gltexturepool_t *)(*rtexturepool);
287         *rtexturepool = NULL;
288         if (pool->sentinel != TEXTUREPOOL_SENTINEL)
289                 Host_Error("R_FreeTexturePool: pool already freed\n");
290         for (poolpointer = &gltexturepoolchain;*poolpointer && *poolpointer != pool;poolpointer = &(*poolpointer)->next);
291         if (*poolpointer == pool)
292                 *poolpointer = pool->next;
293         else
294                 Host_Error("R_FreeTexturePool: pool not linked\n");
295         while (pool->gltchain)
296                 R_FreeTexture((rtexture_t *)pool->gltchain);
297         if (pool->imagechain)
298                 Sys_Error("R_FreeTexturePool: not all images freed\n");
299         Mem_Free(pool);
300 }
301
302
303 typedef struct
304 {
305         char *name;
306         int minification, magnification;
307 }
308 glmode_t;
309
310 static glmode_t modes[] =
311 {
312         {"GL_NEAREST", GL_NEAREST, GL_NEAREST},
313         {"GL_LINEAR", GL_LINEAR, GL_LINEAR},
314         {"GL_NEAREST_MIPMAP_NEAREST", GL_NEAREST_MIPMAP_NEAREST, GL_NEAREST},
315         {"GL_LINEAR_MIPMAP_NEAREST", GL_LINEAR_MIPMAP_NEAREST, GL_LINEAR},
316         {"GL_NEAREST_MIPMAP_LINEAR", GL_NEAREST_MIPMAP_LINEAR, GL_NEAREST},
317         {"GL_LINEAR_MIPMAP_LINEAR", GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR}
318 };
319
320 extern int gl_backend_rebindtextures;
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                                 qglBindTexture(GL_TEXTURE_2D, image->texnum);
364                                 if (image->flags & TEXF_MIPMAP)
365                                         qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min);
366                                 else
367                                         qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_mag);
368                                 qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_mag);
369                         }
370                 }
371         }
372         gl_backend_rebindtextures = true;
373 }
374
375 static int R_CalcTexelDataSize (gltexture_t *glt)
376 {
377         int width2, height2, size;
378         if (glt->flags & TEXF_FRAGMENT)
379                 size = glt->width * glt->height;
380         else
381         {
382                 if (r_max_size.integer > realmaxsize)
383                         Cvar_SetValue("r_max_size", realmaxsize);
384                 // calculate final size
385                 for (width2 = 1;width2 < glt->width;width2 <<= 1);
386                 for (height2 = 1;height2 < glt->height;height2 <<= 1);
387                 for (width2 >>= r_picmip.integer;width2 > r_max_size.integer;width2 >>= 1);
388                 for (height2 >>= r_picmip.integer;height2 > r_max_size.integer;height2 >>= 1);
389                 if (width2 < 1) width2 = 1;
390                 if (height2 < 1) height2 = 1;
391
392                 size = 0;
393                 if (glt->flags & TEXF_MIPMAP)
394                 {
395                         while (width2 > 1 || height2 > 1)
396                         {
397                                 size += width2 * height2;
398                                 if (width2 > 1)
399                                         width2 >>= 1;
400                                 if (height2 > 1)
401                                         height2 >>= 1;
402                         }
403                         size++; // count the last 1x1 mipmap
404                 }
405                 else
406                         size = width2*height2;
407         }
408         size *= glt->textype->internalbytesperpixel;
409
410         return size;
411 }
412
413 void R_TextureStats_PrintTotal(void)
414 {
415         int glsize, inputsize, total = 0, totalt = 0, totalp = 0, loaded = 0, loadedt = 0, loadedp = 0;
416         gltexture_t *glt;
417         gltexturepool_t *pool;
418         for (pool = gltexturepoolchain;pool;pool = pool->next)
419         {
420                 for (glt = pool->gltchain;glt;glt = glt->chain)
421                 {
422                         glsize = R_CalcTexelDataSize(glt);
423                         inputsize = glt->width * glt->height * glt->textype->inputbytesperpixel;
424
425                         total++;
426                         totalt += glsize;
427                         totalp += inputsize;
428                         if (!(glt->flags & GLTEXF_UPLOAD))
429                         {
430                                 loaded++;
431                                 loadedt += glsize;
432                                 loadedp += inputsize;
433                         }
434                 }
435         }
436         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);
437 }
438
439 static void R_TextureStats_f(void)
440 {
441         int loaded;
442         gltexture_t *glt;
443         gltexturepool_t *pool;
444         Con_Printf("glsize input crc  loaded mip alpha name\n");
445         for (pool = gltexturepoolchain;pool;pool = pool->next)
446         {
447                 for (glt = pool->gltchain;glt;glt = glt->chain)
448                 {
449                         loaded = !(glt->flags & GLTEXF_UPLOAD);
450                         if (glt->flags & GLTEXF_PROCEDURAL)
451                                 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>");
452                         else
453                                 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>");
454                 }
455                 Con_Printf("pool %10p\n", pool);
456         }
457         R_TextureStats_PrintTotal();
458 }
459
460 char engineversion[40];
461
462 static void r_textures_start(void)
463 {
464         // deal with size limits of various drivers (3dfx in particular)
465         qglGetIntegerv(GL_MAX_TEXTURE_SIZE, &realmaxsize);
466         CHECKGLERROR
467
468         // use the largest scrap texture size we can (not sure if this is really a good idea)
469         for (block_size = 1;block_size < realmaxsize && block_size < r_max_scrapsize.integer;block_size <<= 1);
470
471         texturemempool = Mem_AllocPool("Texture Info");
472         texturedatamempool = Mem_AllocPool("Texture Storage (not yet uploaded)");
473         textureprocessingmempool = Mem_AllocPool("Texture Processing Buffers");
474         gltexnuminuse = Mem_Alloc(texturemempool, 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         resizebuffersize = 0;
487         texturebuffersize = 0;
488         resizebuffer = NULL;
489         colorconvertbuffer = NULL;
490         texturebuffer = NULL;
491         gltexnuminuse = NULL;
492         Mem_FreePool(&texturemempool);
493         Mem_FreePool(&texturedatamempool);
494         Mem_FreePool(&textureprocessingmempool);
495 }
496
497 static void r_textures_newmap(void)
498 {
499 }
500
501 void R_Textures_Init (void)
502 {
503         Cmd_AddCommand ("gl_texturemode", &GL_TextureMode_f);
504         Cmd_AddCommand("r_texturestats", R_TextureStats_f);
505         Cvar_RegisterVariable (&r_max_scrapsize);
506         Cvar_RegisterVariable (&r_max_size);
507         Cvar_RegisterVariable (&r_picmip);
508         Cvar_RegisterVariable (&r_lerpimages);
509         Cvar_RegisterVariable (&r_precachetextures);
510         gltexnuminuse = NULL;
511
512         R_RegisterModule("R_Textures", r_textures_start, r_textures_shutdown, r_textures_newmap);
513 }
514
515 static void R_Upload(gltexture_t *glt, qbyte *data)
516 {
517         int mip, width, height, internalformat;
518         qbyte *prevbuffer;
519         prevbuffer = data;
520
521         qglBindTexture(GL_TEXTURE_2D, glt->image->texnum);
522         CHECKGLERROR
523
524         gl_backend_rebindtextures = true;
525
526         glt->flags &= ~GLTEXF_UPLOAD;
527
528         if (glt->flags & TEXF_FRAGMENT)
529         {
530                 if (resizebuffersize < glt->image->width * glt->image->height * glt->image->bytesperpixel)
531                 {
532                         resizebuffersize = glt->image->width * glt->image->height * glt->image->bytesperpixel;
533                         if (resizebuffer)
534                                 Mem_Free(resizebuffer);
535                         if (colorconvertbuffer)
536                                 Mem_Free(colorconvertbuffer);
537                         resizebuffer = Mem_Alloc(textureprocessingmempool, resizebuffersize);
538                         colorconvertbuffer = Mem_Alloc(textureprocessingmempool, resizebuffersize);
539                         if (!resizebuffer || !colorconvertbuffer)
540                                 Host_Error("R_Upload: out of memory\n");
541                 }
542
543                 if (glt->image->flags & GLTEXF_UPLOAD)
544                 {
545                         Con_DPrintf("uploaded new fragments image\n");
546                         glt->image->flags &= ~GLTEXF_UPLOAD;
547                         memset(resizebuffer, 255, glt->image->width * glt->image->height * glt->image->bytesperpixel);
548                         qglTexImage2D (GL_TEXTURE_2D, 0, glt->image->glinternalformat, glt->image->width, glt->image->height, 0, glt->image->glformat, GL_UNSIGNED_BYTE, resizebuffer);
549                         CHECKGLERROR
550                         qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_mag);
551                         CHECKGLERROR
552                         qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_mag);
553                         CHECKGLERROR
554                 }
555
556                 if (prevbuffer == NULL)
557                 {
558                         memset(resizebuffer, 255, glt->width * glt->height * glt->image->bytesperpixel);
559                         prevbuffer = resizebuffer;
560                 }
561                 else if (glt->textype->textype == TEXTYPE_QPALETTE)
562                 {
563                         // promote paletted to RGBA, so we only have to worry about RGB and
564                         // RGBA in the rest of this code
565                         Image_Copy8bitRGBA(prevbuffer, colorconvertbuffer, glt->width * glt->height, d_8to24table);
566                         prevbuffer = colorconvertbuffer;
567                 }
568
569                 qglTexSubImage2D(GL_TEXTURE_2D, 0, glt->x, glt->y, glt->width, glt->height, glt->image->glformat, GL_UNSIGNED_BYTE, prevbuffer);
570                 CHECKGLERROR
571                 return;
572         }
573
574         glt->image->flags &= ~GLTEXF_UPLOAD;
575
576         // these are rounded up versions of the size to do better resampling
577         for (width = 1;width < glt->width;width <<= 1);
578         for (height = 1;height < glt->height;height <<= 1);
579
580         if (resizebuffersize < width * height * glt->image->bytesperpixel)
581         {
582                 resizebuffersize = width * height * glt->image->bytesperpixel;
583                 if (resizebuffer)
584                         Mem_Free(resizebuffer);
585                 if (colorconvertbuffer)
586                         Mem_Free(colorconvertbuffer);
587                 resizebuffer = Mem_Alloc(textureprocessingmempool, resizebuffersize);
588                 colorconvertbuffer = Mem_Alloc(textureprocessingmempool, resizebuffersize);
589                 if (!resizebuffer || !colorconvertbuffer)
590                         Host_Error("R_Upload: out of memory\n");
591         }
592
593         if (prevbuffer == NULL)
594         {
595                 width = glt->image->width;
596                 height = glt->image->height;
597                 memset(resizebuffer, 255, width * height * glt->image->bytesperpixel);
598                 prevbuffer = resizebuffer;
599         }
600         else
601         {
602                 if (glt->textype->textype == TEXTYPE_QPALETTE)
603                 {
604                         // promote paletted to RGBA, so we only have to worry about RGB and
605                         // RGBA in the rest of this code
606                         Image_Copy8bitRGBA(prevbuffer, colorconvertbuffer, glt->width * glt->height, d_8to24table);
607                         prevbuffer = colorconvertbuffer;
608                 }
609
610                 if (glt->width != width || glt->height != height)
611                 {
612                         Image_Resample(prevbuffer, glt->width, glt->height, resizebuffer, width, height, glt->image->bytesperpixel, r_lerpimages.integer);
613                         prevbuffer = resizebuffer;
614                 }
615
616                 // apply picmip/max_size limitations
617                 while (width > glt->image->width || height > glt->image->height)
618                 {
619                         Image_MipReduce(prevbuffer, resizebuffer, &width, &height, glt->image->width, glt->image->height, glt->image->bytesperpixel);
620                         prevbuffer = resizebuffer;
621                 }
622         }
623
624         // 3 and 4 are converted by the driver to it's preferred format for the current display mode
625         internalformat = 3;
626         if (glt->flags & TEXF_ALPHA)
627                 internalformat = 4;
628
629         mip = 0;
630         qglTexImage2D(GL_TEXTURE_2D, mip++, internalformat, width, height, 0, glt->image->glformat, GL_UNSIGNED_BYTE, prevbuffer);
631         CHECKGLERROR
632         if (glt->flags & TEXF_MIPMAP)
633         {
634                 while (width > 1 || height > 1)
635                 {
636                         Image_MipReduce(prevbuffer, resizebuffer, &width, &height, 1, 1, glt->image->bytesperpixel);
637                         prevbuffer = resizebuffer;
638
639                         qglTexImage2D(GL_TEXTURE_2D, mip++, internalformat, width, height, 0, glt->image->glformat, GL_UNSIGNED_BYTE, prevbuffer);
640                         CHECKGLERROR
641                 }
642
643                 qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min);
644                 CHECKGLERROR
645                 qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_mag);
646                 CHECKGLERROR
647         }
648         else
649         {
650                 qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_mag);
651                 CHECKGLERROR
652                 qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_mag);
653                 CHECKGLERROR
654         }
655 }
656
657 static void R_FindImageForTexture(gltexture_t *glt)
658 {
659         int i, j, best, best2, x, y, w, h;
660         textypeinfo_t *texinfo;
661         gltexturepool_t *pool;
662         gltextureimage_t *image, **imagechainpointer;
663         texinfo = glt->textype;
664         pool = glt->pool;
665
666         x = 0;
667         y = 0;
668         w = glt->width;
669         h = glt->height;
670         if (glt->flags & TEXF_FRAGMENT)
671         {
672                 for (imagechainpointer = &pool->imagechain;*imagechainpointer;imagechainpointer = &(*imagechainpointer)->imagechain)
673                 {
674                         image = *imagechainpointer;
675                         if (image->type != GLIMAGETYPE_FRAGMENTS)
676                                 continue;
677                         if (image->glformat != texinfo->glformat || image->glinternalformat != texinfo->glinternalformat)
678                                 continue;
679                         if (glt->width > image->width || glt->height > image->height)
680                                 continue;
681
682                         // got a fragments texture, find a place in it if we can
683                         for (best = image->width, i = 0;i < image->width - w;i += texinfo->align)
684                         {
685                                 for (best2 = 0, j = 0;j < w;j++)
686                                 {
687                                         if (image->blockallocation[i+j] >= best)
688                                                 break;
689                                         if (best2 < image->blockallocation[i+j])
690                                                 best2 = image->blockallocation[i+j];
691                                 }
692                                 if (j == w)
693                                 {
694                                         // this is a valid spot
695                                         x = i;
696                                         y = best = best2;
697                                 }
698                         }
699
700                         if (best + h > image->height)
701                                 continue;
702
703                         for (i = 0;i < w;i++)
704                                 image->blockallocation[x + i] = best + h;
705
706                         glt->x = x;
707                         glt->y = y;
708                         glt->image = image;
709                         image->texturecount++;
710                         return;
711                 }
712
713                 image = Mem_Alloc(texturemempool, sizeof(gltextureimage_t));
714                 if (image == NULL)
715                         Sys_Error("R_FindImageForTexture: ran out of memory\n");
716                 image->type = GLIMAGETYPE_FRAGMENTS;
717                 // make sure the created image is big enough for the fragment
718                 for (image->width = block_size;image->width < glt->width;image->width <<= 1);
719                 for (image->height = block_size;image->height < glt->height;image->height <<= 1);
720                 image->blockallocation = Mem_Alloc(texturemempool, image->width * sizeof(short));
721                 memset(image->blockallocation, 0, image->width * sizeof(short));
722
723                 x = 0;
724                 y = 0;
725                 for (i = 0;i < w;i++)
726                         image->blockallocation[x + i] = y + h;
727         }
728         else
729         {
730                 for (imagechainpointer = &pool->imagechain;*imagechainpointer;imagechainpointer = &(*imagechainpointer)->imagechain);
731
732                 image = Mem_Alloc(texturemempool, sizeof(gltextureimage_t));
733                 if (image == NULL)
734                         Sys_Error("R_FindImageForTexture: ran out of memory\n");
735                 image->type = GLIMAGETYPE_TILE;
736                 image->blockallocation = NULL;
737
738                 // calculate final size
739                 if (r_max_size.integer > realmaxsize)
740                         Cvar_SetValue("r_max_size", realmaxsize);
741                 for (image->width = 1;image->width < glt->width;image->width <<= 1);
742                 for (image->height = 1;image->height < glt->height;image->height <<= 1);
743                 for (image->width >>= r_picmip.integer;image->width > r_max_size.integer;image->width >>= 1);
744                 for (image->height >>= r_picmip.integer;image->height > r_max_size.integer;image->height >>= 1);
745                 if (image->width < 1) image->width = 1;
746                 if (image->height < 1) image->height = 1;
747         }
748         image->glinternalformat = texinfo->glinternalformat;
749         image->glformat = texinfo->glformat;
750         image->flags = (glt->flags & (TEXF_MIPMAP | TEXF_ALPHA)) | GLTEXF_UPLOAD;
751         image->bytesperpixel = texinfo->internalbytesperpixel;
752         for (i = 1;i < MAX_GLTEXTURES;i++)
753                 if (!gltexnuminuse[i])
754                         break;
755         if (i < MAX_GLTEXTURES)
756                 gltexnuminuse[image->texnum = i] = true;
757         else
758                 Sys_Error("R_FindImageForTexture: ran out of GL textures\n");
759         *imagechainpointer = image;
760         image->texturecount++;
761
762         glt->x = x;
763         glt->y = y;
764         glt->image = image;
765 }
766
767 // note: R_FindImageForTexture must be called before this
768 static void R_UploadTexture (gltexture_t *glt)
769 {
770         if (!(glt->flags & (GLTEXF_UPLOAD | GLTEXF_PROCEDURAL)))
771                 return;
772
773         if (glt->flags & GLTEXF_PROCEDURAL)
774         {
775                 if (glt->generate)
776                 {
777                         if (texturebuffersize < glt->width * glt->height * glt->textype->inputbytesperpixel)
778                         {
779                                 if (texturebuffer)
780                                         Mem_Free(texturebuffer);
781                                 texturebuffersize = glt->width * glt->height * glt->textype->inputbytesperpixel;
782                                 texturebuffer = Mem_Alloc(textureprocessingmempool, texturebuffersize);
783                         }
784
785                         glt->generate(texturebuffer, glt->width, glt->height, (void *)glt->proceduraldata, glt->proceduraldatasize);
786                 }
787         }
788         else
789         {
790                 R_Upload(glt, glt->inputtexels);
791                 if (glt->inputtexels)
792                 {
793                         Mem_Free(glt->inputtexels);
794                         glt->inputtexels = NULL;
795                         glt->flags |= GLTEXF_DESTROYED;
796                 }
797                 else if (glt->flags & GLTEXF_DESTROYED)
798                         Con_Printf("R_UploadTexture: Texture %s already uploaded and destroyed.  Can not upload original image again.  Uploaded blank texture.\n", glt->identifier);
799         }
800 }
801
802 static gltexture_t *R_SetupTexture(gltexturepool_t *pool, char *identifier, int crc, int width, int height, int flags, textypeinfo_t *texinfo, qbyte *data, int (*generate)(qbyte *buffer, int width, int height, void *proceduraldata, int proceduraldatasize), void *proceduraldata, int proceduraldatasize)
803 {
804         gltexture_t *glt;
805         glt = Mem_Alloc(texturemempool, sizeof(gltexture_t));
806         if (identifier)
807         {
808                 glt->identifier = Mem_Alloc(texturemempool, strlen(identifier)+1);
809                 strcpy (glt->identifier, identifier);
810         }
811         else
812                 glt->identifier = NULL;
813         glt->pool = pool;
814         glt->chain = pool->gltchain;
815         pool->gltchain = glt;
816         glt->crc = crc;
817         glt->width = width;
818         glt->height = height;
819         glt->flags = flags;
820         glt->textype = texinfo;
821
822         if (data)
823         {
824                 glt->inputtexels = Mem_Alloc(texturedatamempool, glt->width * glt->height * texinfo->inputbytesperpixel);
825                 if (glt->inputtexels == NULL)
826                         Sys_Error("R_SetupTexture: out of memory\n");
827                 memcpy(glt->inputtexels, data, glt->width * glt->height * texinfo->inputbytesperpixel);
828         }
829         else
830                 glt->inputtexels = NULL;
831
832         glt->generate = generate;
833         glt->proceduraldatasize = proceduraldatasize;
834         if (proceduraldatasize)
835         {
836                 glt->proceduraldata = Mem_Alloc(texturemempool, proceduraldatasize);
837                 if (glt->proceduraldata == NULL)
838                         Sys_Error("R_SetupTexture: out of memory\n");
839         }
840         else
841                 glt->proceduraldata = NULL;
842
843         R_FindImageForTexture(glt);
844         R_PrecacheTexture(glt);
845
846         return glt;
847 }
848
849 /*
850 ================
851 R_LoadTexture
852 ================
853 */
854 rtexture_t *R_LoadTexture (rtexturepool_t *rtexturepool, char *identifier, int width, int height, qbyte *data, int textype, int flags)
855 {
856         int i;
857         gltexture_t *glt;
858         gltexturepool_t *pool = (gltexturepool_t *)rtexturepool;
859         textypeinfo_t *texinfo;
860         unsigned short crc;
861
862         if (cls.state == ca_dedicated)
863                 return NULL;
864
865         texinfo = R_GetTexTypeInfo(textype, flags);
866
867         if (flags & TEXF_FRAGMENT)
868                 if ((width * texinfo->internalbytesperpixel) & 3)
869                         Host_Error("R_LoadTexture: incompatible width for fragment");
870
871         // clear the alpha flag if the texture has no transparent pixels
872         switch(textype)
873         {
874         case TEXTYPE_QPALETTE:
875                 if (flags & TEXF_ALPHA)
876                 {
877                         flags &= ~TEXF_ALPHA;
878                         for (i = 0;i < width * height;i++)
879                         {
880                                 if (data[i] == 255)
881                                 {
882                                         flags |= TEXF_ALPHA;
883                                         break;
884                                 }
885                         }
886                 }
887                 break;
888         case TEXTYPE_RGB:
889                 if (flags & TEXF_ALPHA)
890                         Host_Error("R_LoadTexture: RGB has no alpha, don't specify TEXF_ALPHA\n");
891                 break;
892         case TEXTYPE_RGBA:
893                 if (flags & TEXF_ALPHA)
894                 {
895                         flags &= ~TEXF_ALPHA;
896                         for (i = 0;i < width * height;i++)
897                         {
898                                 if (data[i * 4 + 3] < 255)
899                                 {
900                                         flags |= TEXF_ALPHA;
901                                         break;
902                                 }
903                         }
904                 }
905                 break;
906         default:
907                 Host_Error("R_LoadTexture: unknown texture type\n");
908         }
909
910         // LordHavoc: do a CRC to confirm the data really is the same as previous occurances.
911         if (data == NULL)
912                 crc = 0;
913         else
914                 crc = CRC_Block(data, width*height*texinfo->inputbytesperpixel);
915
916         // see if the texture is already present
917         if (identifier && (glt = R_FindTexture(pool, identifier)))
918         {
919                 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)
920                 {
921                         Con_Printf("R_LoadTexture: exact match with existing texture %s\n", identifier);
922                         return (rtexture_t *)glt; // exact match, use existing
923                 }
924                 Con_Printf("R_LoadTexture: cache mismatch on %s, replacing old texture\n", identifier);
925                 R_FreeTexture((rtexture_t *)glt);
926         }
927
928         return (rtexture_t *)R_SetupTexture(pool, identifier, crc, width, height, flags | GLTEXF_UPLOAD, texinfo, data, NULL, NULL, 0);
929 }
930
931 rtexture_t *R_ProceduralTexture (rtexturepool_t *rtexturepool, char *identifier, int width, int height, int textype, int flags, int (*generate)(qbyte *buffer, int width, int height, void *proceduraldata, int proceduraldatasize), void *proceduraldata, int proceduraldatasize)
932 {
933         gltexture_t             *glt;
934         gltexturepool_t *pool = (gltexturepool_t *)rtexturepool;
935         textypeinfo_t   *texinfo;
936
937         if (cls.state == ca_dedicated)
938                 return NULL;
939
940         texinfo = R_GetTexTypeInfo(textype, flags);
941
942         if (flags & TEXF_FRAGMENT)
943                 if ((width * texinfo->internalbytesperpixel) & 3)
944                         Host_Error("R_ProceduralTexture: incompatible width for fragment");
945
946         // see if the texture is already present
947         if (identifier && (glt = R_FindTexture(pool, identifier)))
948         {
949                 if (width == glt->width && height == glt->height && texinfo == glt->textype && ((flags ^ glt->flags) & TEXF_IMPORTANTBITS) == 0 && ((flags ^ glt->flags) & GLTEXF_IMPORTANTBITS) == 0)
950                 {
951                         Con_Printf("R_LoadTexture: exact match with existing texture %s\n", identifier);
952                         return (rtexture_t *)glt; // exact match, use existing
953                 }
954                 Con_Printf("R_LoadTexture: cache mismatch, replacing old texture\n");
955                 R_FreeTexture((rtexture_t *)glt);
956         }
957
958         return (rtexture_t *)R_SetupTexture(pool, identifier, 0, width, height, flags | GLTEXF_PROCEDURAL | GLTEXF_UPLOAD, texinfo, NULL, generate, proceduraldata, proceduraldatasize);
959 }
960
961 int R_TextureHasAlpha(rtexture_t *rt)
962 {
963         gltexture_t *glt;
964         if (!rt)
965                 return false;
966         glt = (gltexture_t *)rt;
967         return (glt->flags & TEXF_ALPHA) != 0;
968 }
969
970 int R_TextureWidth(rtexture_t *rt)
971 {
972         if (!rt)
973                 return false;
974         return ((gltexture_t *)rt)->width;
975 }
976
977 int R_TextureHeight(rtexture_t *rt)
978 {
979         if (!rt)
980                 return false;
981         return ((gltexture_t *)rt)->height;
982 }
983
984 void R_FragmentLocation(rtexture_t *rt, int *x, int *y, float *fx1, float *fy1, float *fx2, float *fy2)
985 {
986         gltexture_t *glt;
987         float iwidth, iheight;
988         if (cls.state == ca_dedicated)
989         {
990                 if (x)
991                         *x = 0;
992                 if (y)
993                         *y = 0;
994                 if (fx1 || fy1 || fx2 || fy2)
995                 {
996                         if (fx1)
997                                 *fx1 = 0;
998                         if (fy1)
999                                 *fy1 = 0;
1000                         if (fx2)
1001                                 *fx2 = 1;
1002                         if (fy2)
1003                                 *fy2 = 1;
1004                 }
1005                 return;
1006         }
1007         if (!rt)
1008                 Host_Error("R_FragmentLocation: no texture supplied\n");
1009         glt = (gltexture_t *)rt;
1010         if (glt->flags & TEXF_FRAGMENT)
1011         {
1012                 if (x)
1013                         *x = glt->x;
1014                 if (y)
1015                         *y = glt->y;
1016                 if (fx1 || fy1 || fx2 || fy2)
1017                 {
1018                         iwidth = 1.0f / glt->image->width;
1019                         iheight = 1.0f / glt->image->height;
1020                         if (fx1)
1021                                 *fx1 = glt->x * iwidth;
1022                         if (fy1)
1023                                 *fy1 = glt->y * iheight;
1024                         if (fx2)
1025                                 *fx2 = (glt->x + glt->width) * iwidth;
1026                         if (fy2)
1027                                 *fy2 = (glt->y + glt->height) * iheight;
1028                 }
1029         }
1030         else
1031         {
1032                 if (x)
1033                         *x = 0;
1034                 if (y)
1035                         *y = 0;
1036                 if (fx1 || fy1 || fx2 || fy2)
1037                 {
1038                         if (fx1)
1039                                 *fx1 = 0;
1040                         if (fy1)
1041                                 *fy1 = 0;
1042                         if (fx2)
1043                                 *fx2 = 1;
1044                         if (fy2)
1045                                 *fy2 = 1;
1046                 }
1047         }
1048 }
1049
1050 int R_CompatibleFragmentWidth(int width, int textype, int flags)
1051 {
1052         textypeinfo_t *texinfo = R_GetTexTypeInfo(textype, flags);
1053         while ((width * texinfo->internalbytesperpixel) & 3)
1054                 width++;
1055         return width;
1056 }
1057
1058 void R_UpdateTexture(rtexture_t *rt, qbyte *data)
1059 {
1060         gltexture_t *glt;
1061         if (rt == NULL)
1062                 Host_Error("R_UpdateTexture: no texture supplied\n");
1063         if (data == NULL)
1064                 Host_Error("R_UpdateTexture: no data supplied\n");
1065         glt = (gltexture_t *)rt;
1066
1067         // if it has not been uploaded yet, update the data that will be used when it is
1068         if (glt->inputtexels)
1069                 memcpy(glt->inputtexels, data, glt->width * glt->height * glt->textype->inputbytesperpixel);
1070         else
1071                 R_Upload(glt, data);
1072 }
1073