]> icculus.org git repositories - divverent/darkplaces.git/blob - gl_textures.c
added some (not yet used) key config menu code, part of a redesign for loading the...
[divverent/darkplaces.git] / gl_textures.c
1 #include "quakedef.h"
2
3 cvar_t  r_max_size = {CVAR_SAVE, "r_max_size", "2048"};
4 cvar_t  r_max_scrapsize = {CVAR_SAVE, "r_max_scrapsize", "256"};
5 cvar_t  r_picmip = {CVAR_SAVE, "r_picmip", "0"};
6 cvar_t  r_lerpimages = {CVAR_SAVE, "r_lerpimages", "1"};
7 cvar_t  r_precachetextures = {CVAR_SAVE, "r_precachetextures", "1"};
8
9 int             gl_filter_min = GL_LINEAR_MIPMAP_LINEAR; //NEAREST;
10 int             gl_filter_mag = GL_LINEAR;
11
12
13 static mempool_t *texturemempool;
14 static mempool_t *texturedatamempool;
15 static mempool_t *textureprocessingmempool;
16
17 // note: this must not conflict with TEXF_ flags in r_textures.h
18 // cleared when a texture is uploaded
19 #define GLTEXF_UPLOAD 0x00010000
20 // texture generated by code, also causes permanent GLTEXF_UPLOAD effect
21 #define GLTEXF_PROCEDURAL 0x00020000
22 // bitmask for mismatch checking
23 #define GLTEXF_IMPORTANTBITS (GLTEXF_PROCEDURAL)
24 // set when image is uploaded and freed
25 #define GLTEXF_DESTROYED 0x00040000
26
27 // size of images which hold fragment textures, ignores picmip and max_size
28 //#define BLOCK_SIZE 256
29 static int block_size;
30
31 // really this number only governs gltexnuminuse
32 #define MAX_GLTEXTURES 65536
33
34 // since there is only one set of GL texture numbers, we have to track them
35 // globally, everything else is per texture pool
36 static 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 static void R_FreeTexture(gltexture_t *glt)
204 {
205         gltexture_t **gltpointer;
206         gltextureimage_t *image, **gltimagepointer;
207         GLuint texnum;
208
209         if (glt == NULL)
210                 Host_Error("R_FreeTexture: texture == NULL\n");
211
212         for (gltpointer = &glt->pool->gltchain;*gltpointer && *gltpointer != glt;gltpointer = &(*gltpointer)->chain);
213         if (*gltpointer == glt)
214                 *gltpointer = glt->chain;
215         else
216                 Host_Error("R_FreeTexture: texture \"%s\" not linked in pool\n", glt->identifier);
217
218         // note: if freeing a fragment texture, this will not make the claimed
219         // space available for new textures unless all other fragments in the
220         // image are also freed
221         image = glt->image;
222         image->texturecount--;
223         if (image->texturecount < 1)
224         {
225                 for (gltimagepointer = &glt->pool->imagechain;*gltimagepointer && *gltimagepointer != image;gltimagepointer = &(*gltimagepointer)->imagechain);
226                 if (*gltimagepointer == image)
227                         *gltimagepointer = image->imagechain;
228                 else
229                         Host_Error("R_FreeTexture: image not linked in pool\n");
230                 if (image->texnum)
231                 {
232                         texnum = image->texnum;
233                         gltexnuminuse[image->texnum] = 0;
234                         glDeleteTextures(1, &texnum);
235                 }
236                 if (image->blockallocation)
237                         Mem_Free(image->blockallocation);
238                 Mem_Free(image);
239         }
240
241         if (glt->identifier)
242                 Mem_Free(glt->identifier);
243         if (glt->inputtexels)
244                 Mem_Free(glt->inputtexels);
245         if (glt->proceduraldata)
246                 Mem_Free(glt->proceduraldata);
247         Mem_Free(glt);
248 }
249
250 static gltexture_t *R_FindTexture (gltexturepool_t *pool, char *identifier)
251 {
252         gltexture_t     *glt;
253
254         if (!identifier)
255                 return NULL;
256
257         for (glt = pool->gltchain;glt;glt = glt->chain)
258                 if (glt->identifier && !strcmp (identifier, glt->identifier))
259                         return glt;
260
261         return NULL;
262 }
263
264 rtexturepool_t *R_AllocTexturePool(void)
265 {
266         gltexturepool_t *pool;
267         if (texturemempool == NULL)
268                 return NULL;
269         pool = Mem_Alloc(texturemempool, sizeof(gltexturepool_t));
270         if (pool == NULL)
271                 return NULL;
272         //memset(pool, 0, sizeof(gltexturepool_t));
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(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                                 glBindTexture(GL_TEXTURE_2D, image->texnum);
364                                 if (image->flags & TEXF_MIPMAP)
365                                         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min);
366                                 else
367                                         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_mag);
368                                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_mag);
369                         }
370                 }
371         }
372         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         glGetIntegerv(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         //memset(gltexnuminuse, 0, MAX_GLTEXTURES);
476 }
477
478 static void r_textures_shutdown(void)
479 {
480         rtexturepool_t *temp;
481         while(gltexturepoolchain)
482         {
483                 temp = (rtexturepool_t *) gltexturepoolchain;
484                 R_FreeTexturePool(&temp);
485         }
486
487         /*
488         if (resizebuffer) Mem_Free(resizebuffer);resizebuffer = NULL;
489         if (colorconvertbuffer) Mem_Free(colorconvertbuffer);colorconvertbuffer = NULL;
490         if (texturebuffer) Mem_Free(texturebuffer);texturebuffer = NULL;
491         if (gltexnuminuse) Mem_Free(gltexnuminuse);gltexnuminuse = NULL;
492         */
493         resizebuffersize = 0;
494         texturebuffersize = 0;
495         resizebuffer = NULL;
496         colorconvertbuffer = NULL;
497         texturebuffer = NULL;
498         gltexnuminuse = NULL;
499         Mem_FreePool(&texturemempool);
500         Mem_FreePool(&texturedatamempool);
501         Mem_FreePool(&textureprocessingmempool);
502 }
503
504 static void r_textures_newmap(void)
505 {
506 }
507
508 void R_Textures_Init (void)
509 {
510         Cmd_AddCommand ("gl_texturemode", &GL_TextureMode_f);
511         Cmd_AddCommand("r_texturestats", R_TextureStats_f);
512         Cvar_RegisterVariable (&r_max_scrapsize);
513         Cvar_RegisterVariable (&r_max_size);
514         Cvar_RegisterVariable (&r_picmip);
515         Cvar_RegisterVariable (&r_lerpimages);
516         Cvar_RegisterVariable (&r_precachetextures);
517         gltexnuminuse = NULL;
518
519         R_RegisterModule("R_Textures", r_textures_start, r_textures_shutdown, r_textures_newmap);
520 }
521
522 static void R_Upload(gltexture_t *glt, qbyte *data)
523 {
524         int mip, width, height, internalformat;
525         qbyte *prevbuffer;
526         prevbuffer = data;
527
528         glBindTexture(GL_TEXTURE_2D, glt->image->texnum);
529         CHECKGLERROR
530
531         gl_backend_rebindtextures = true;
532
533         glt->flags &= ~GLTEXF_UPLOAD;
534
535         if (glt->flags & TEXF_FRAGMENT)
536         {
537                 if (resizebuffersize < glt->image->width * glt->image->height * glt->image->bytesperpixel)
538                 {
539                         resizebuffersize = glt->image->width * glt->image->height * glt->image->bytesperpixel;
540                         if (resizebuffer)
541                                 Mem_Free(resizebuffer);
542                         if (colorconvertbuffer)
543                                 Mem_Free(colorconvertbuffer);
544                         resizebuffer = Mem_Alloc(textureprocessingmempool, resizebuffersize);
545                         colorconvertbuffer = Mem_Alloc(textureprocessingmempool, resizebuffersize);
546                         if (!resizebuffer || !colorconvertbuffer)
547                                 Host_Error("R_Upload: out of memory\n");
548                 }
549
550                 if (glt->image->flags & GLTEXF_UPLOAD)
551                 {
552                         Con_DPrintf("uploaded new fragments image\n");
553                         glt->image->flags &= ~GLTEXF_UPLOAD;
554                         memset(resizebuffer, 255, glt->image->width * glt->image->height * glt->image->bytesperpixel);
555                         glTexImage2D (GL_TEXTURE_2D, 0, glt->image->glinternalformat, glt->image->width, glt->image->height, 0, glt->image->glformat, GL_UNSIGNED_BYTE, resizebuffer);
556                         CHECKGLERROR
557                         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_mag);
558                         CHECKGLERROR
559                         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_mag);
560                         CHECKGLERROR
561                 }
562
563                 if (prevbuffer == NULL)
564                 {
565                         memset(resizebuffer, 255, glt->width * glt->height * glt->image->bytesperpixel);
566                         prevbuffer = resizebuffer;
567                 }
568                 else if (glt->textype->textype == TEXTYPE_QPALETTE)
569                 {
570                         // promote paletted to RGBA, so we only have to worry about RGB and
571                         // RGBA in the rest of this code
572                         Image_Copy8bitRGBA(prevbuffer, colorconvertbuffer, glt->width * glt->height, d_8to24table);
573                         prevbuffer = colorconvertbuffer;
574                 }
575
576                 glTexSubImage2D(GL_TEXTURE_2D, 0, glt->x, glt->y, glt->width, glt->height, glt->image->glformat, GL_UNSIGNED_BYTE, prevbuffer);
577                 CHECKGLERROR
578                 return;
579         }
580
581         glt->image->flags &= ~GLTEXF_UPLOAD;
582
583         // these are rounded up versions of the size to do better resampling
584         for (width = 1;width < glt->width;width <<= 1);
585         for (height = 1;height < glt->height;height <<= 1);
586
587         if (resizebuffersize < width * height * glt->image->bytesperpixel)
588         {
589                 resizebuffersize = width * height * glt->image->bytesperpixel;
590                 if (resizebuffer)
591                         Mem_Free(resizebuffer);
592                 if (colorconvertbuffer)
593                         Mem_Free(colorconvertbuffer);
594                 resizebuffer = Mem_Alloc(textureprocessingmempool, resizebuffersize);
595                 colorconvertbuffer = Mem_Alloc(textureprocessingmempool, resizebuffersize);
596                 if (!resizebuffer || !colorconvertbuffer)
597                         Host_Error("R_Upload: out of memory\n");
598         }
599
600         if (prevbuffer == NULL)
601         {
602                 width = glt->image->width;
603                 height = glt->image->height;
604                 memset(resizebuffer, 255, width * height * glt->image->bytesperpixel);
605                 prevbuffer = resizebuffer;
606         }
607         else
608         {
609                 if (glt->textype->textype == TEXTYPE_QPALETTE)
610                 {
611                         // promote paletted to RGBA, so we only have to worry about RGB and
612                         // RGBA in the rest of this code
613                         Image_Copy8bitRGBA(prevbuffer, colorconvertbuffer, glt->width * glt->height, d_8to24table);
614                         prevbuffer = colorconvertbuffer;
615                 }
616
617                 if (glt->width != width || glt->height != height)
618                 {
619                         Image_Resample(prevbuffer, glt->width, glt->height, resizebuffer, width, height, glt->image->bytesperpixel, r_lerpimages.integer);
620                         prevbuffer = resizebuffer;
621                 }
622
623                 // apply picmip/max_size limitations
624                 while (width > glt->image->width || height > glt->image->height)
625                 {
626                         Image_MipReduce(prevbuffer, resizebuffer, &width, &height, glt->image->width, glt->image->height, glt->image->bytesperpixel);
627                         prevbuffer = resizebuffer;
628                 }
629         }
630
631         // 3 and 4 are converted by the driver to it's preferred format for the current display mode
632         internalformat = 3;
633         if (glt->flags & TEXF_ALPHA)
634                 internalformat = 4;
635
636         mip = 0;
637         glTexImage2D(GL_TEXTURE_2D, mip++, internalformat, width, height, 0, glt->image->glformat, GL_UNSIGNED_BYTE, prevbuffer);
638         CHECKGLERROR
639         if (glt->flags & TEXF_MIPMAP)
640         {
641                 while (width > 1 || height > 1)
642                 {
643                         Image_MipReduce(prevbuffer, resizebuffer, &width, &height, 1, 1, glt->image->bytesperpixel);
644                         prevbuffer = resizebuffer;
645
646                         glTexImage2D(GL_TEXTURE_2D, mip++, internalformat, width, height, 0, glt->image->glformat, GL_UNSIGNED_BYTE, prevbuffer);
647                         CHECKGLERROR
648                 }
649
650                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min);
651                 CHECKGLERROR
652                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_mag);
653                 CHECKGLERROR
654         }
655         else
656         {
657                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_mag);
658                 CHECKGLERROR
659                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_mag);
660                 CHECKGLERROR
661         }
662 }
663
664 static void R_FindImageForTexture(gltexture_t *glt)
665 {
666         int i, j, best, best2, x, y, w, h;
667         textypeinfo_t *texinfo;
668         gltexturepool_t *pool;
669         gltextureimage_t *image, **imagechainpointer;
670         texinfo = glt->textype;
671         pool = glt->pool;
672
673         x = 0;
674         y = 0;
675         w = glt->width;
676         h = glt->height;
677         if (glt->flags & TEXF_FRAGMENT)
678         {
679                 for (imagechainpointer = &pool->imagechain;*imagechainpointer;imagechainpointer = &(*imagechainpointer)->imagechain)
680                 {
681                         image = *imagechainpointer;
682                         if (image->type != GLIMAGETYPE_FRAGMENTS)
683                                 continue;
684                         if (image->glformat != texinfo->glformat || image->glinternalformat != texinfo->glinternalformat)
685                                 continue;
686
687                         // got a fragments texture, find a place in it if we can
688                         best = block_size;
689                         for (best = block_size, i = 0;i < block_size - w;i += texinfo->align)
690                         {
691                                 for (best2 = 0, j = 0;j < w;j++)
692                                 {
693                                         if (image->blockallocation[i+j] >= best)
694                                                 break;
695                                         if (best2 < image->blockallocation[i+j])
696                                                 best2 = image->blockallocation[i+j];
697                                 }
698                                 if (j == w)
699                                 {
700                                         // this is a valid spot
701                                         x = i;
702                                         y = best = best2;
703                                 }
704                         }
705
706                         if (best + h > block_size)
707                                 continue;
708
709                         for (i = 0;i < w;i++)
710                                 image->blockallocation[x + i] = best + h;
711
712                         glt->x = x;
713                         glt->y = y;
714                         glt->image = image;
715                         image->texturecount++;
716                         return;
717                 }
718
719                 image = Mem_Alloc(texturemempool, sizeof(gltextureimage_t));
720                 if (image == NULL)
721                         Sys_Error("R_FindImageForTexture: ran out of memory\n");
722                 //memset(image, 0, sizeof(*image));
723                 image->type = GLIMAGETYPE_FRAGMENTS;
724                 image->width = block_size;
725                 image->height = block_size;
726                 image->blockallocation = Mem_Alloc(texturemempool, block_size * sizeof(short));
727                 memset(image->blockallocation, 0, block_size * sizeof(short));
728
729                 x = 0;
730                 y = 0;
731                 for (i = 0;i < w;i++)
732                         image->blockallocation[x + i] = y + h;
733         }
734         else
735         {
736                 for (imagechainpointer = &pool->imagechain;*imagechainpointer;imagechainpointer = &(*imagechainpointer)->imagechain);
737
738                 image = Mem_Alloc(texturemempool, sizeof(gltextureimage_t));
739                 if (image == NULL)
740                         Sys_Error("R_FindImageForTexture: ran out of memory\n");
741                 //memset(image, 0, sizeof(*image));
742                 image->type = GLIMAGETYPE_TILE;
743                 image->blockallocation = NULL;
744
745                 // calculate final size
746                 if (r_max_size.integer > realmaxsize)
747                         Cvar_SetValue("r_max_size", realmaxsize);
748                 for (image->width = 1;image->width < glt->width;image->width <<= 1);
749                 for (image->height = 1;image->height < glt->height;image->height <<= 1);
750                 for (image->width >>= r_picmip.integer;image->width > r_max_size.integer;image->width >>= 1);
751                 for (image->height >>= r_picmip.integer;image->height > r_max_size.integer;image->height >>= 1);
752                 if (image->width < 1) image->width = 1;
753                 if (image->height < 1) image->height = 1;
754         }
755         image->glinternalformat = texinfo->glinternalformat;
756         image->glformat = texinfo->glformat;
757         image->flags = (glt->flags & (TEXF_MIPMAP | TEXF_ALPHA)) | GLTEXF_UPLOAD;
758         image->bytesperpixel = texinfo->internalbytesperpixel;
759         for (i = 1;i < MAX_GLTEXTURES;i++)
760                 if (!gltexnuminuse[i])
761                         break;
762         if (i < MAX_GLTEXTURES)
763                 gltexnuminuse[image->texnum = i] = true;
764         else
765                 Sys_Error("R_FindImageForTexture: ran out of GL textures\n");
766         *imagechainpointer = image;
767         image->texturecount++;
768
769         glt->x = x;
770         glt->y = y;
771         glt->image = image;
772 }
773
774 // note: R_FindImageForTexture must be called before this
775 static void R_UploadTexture (gltexture_t *glt)
776 {
777         if (!(glt->flags & (GLTEXF_UPLOAD | GLTEXF_PROCEDURAL)))
778                 return;
779
780         if (glt->flags & GLTEXF_PROCEDURAL)
781         {
782                 if (glt->generate)
783                 {
784                         if (texturebuffersize < glt->width * glt->height * glt->textype->inputbytesperpixel)
785                         {
786                                 if (texturebuffer)
787                                         Mem_Free(texturebuffer);
788                                 texturebuffersize = glt->width * glt->height * glt->textype->inputbytesperpixel;
789                                 texturebuffer = Mem_Alloc(textureprocessingmempool, texturebuffersize);
790                         }
791
792                         glt->generate(texturebuffer, glt->width, glt->height, (void *)glt->proceduraldata, glt->proceduraldatasize);
793                 }
794         }
795         else
796         {
797                 R_Upload(glt, glt->inputtexels);
798                 if (glt->inputtexels)
799                 {
800                         Mem_Free(glt->inputtexels);
801                         glt->inputtexels = NULL;
802                         glt->flags |= GLTEXF_DESTROYED;
803                 }
804                 else if (glt->flags & GLTEXF_DESTROYED)
805                         Con_Printf("R_UploadTexture: Texture %s already uploaded and destroyed.  Can not upload original image again.  Uploaded blank texture.\n", glt->identifier);
806         }
807 }
808
809 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)
810 {
811         gltexture_t *glt;
812         glt = Mem_Alloc(texturemempool, sizeof(gltexture_t));
813         //memset(glt, 0, sizeof(gltexture_t));
814         if (identifier)
815         {
816                 glt->identifier = Mem_Alloc(texturemempool, strlen(identifier)+1);
817                 strcpy (glt->identifier, identifier);
818         }
819         else
820                 glt->identifier = NULL;
821         glt->pool = pool;
822         glt->chain = pool->gltchain;
823         pool->gltchain = glt;
824         glt->crc = crc;
825         glt->width = width;
826         glt->height = height;
827         glt->flags = flags;
828         glt->textype = texinfo;
829
830         if (data)
831         {
832                 glt->inputtexels = Mem_Alloc(texturedatamempool, glt->width * glt->height * texinfo->inputbytesperpixel);
833                 if (glt->inputtexels == NULL)
834                         Sys_Error("R_SetupTexture: out of memory\n");
835                 memcpy(glt->inputtexels, data, glt->width * glt->height * texinfo->inputbytesperpixel);
836         }
837         else
838                 glt->inputtexels = NULL;
839
840         glt->generate = generate;
841         glt->proceduraldatasize = proceduraldatasize;
842         if (proceduraldatasize)
843         {
844                 glt->proceduraldata = Mem_Alloc(texturemempool, proceduraldatasize);
845                 if (glt->proceduraldata == NULL)
846                         Sys_Error("R_SetupTexture: out of memory\n");
847         }
848         else
849                 glt->proceduraldata = NULL;
850
851         R_FindImageForTexture(glt);
852         R_PrecacheTexture(glt);
853
854         return glt;
855 }
856
857 /*
858 ================
859 R_LoadTexture
860 ================
861 */
862 rtexture_t *R_LoadTexture (rtexturepool_t *rtexturepool, char *identifier, int width, int height, qbyte *data, int textype, int flags)
863 {
864         int i;
865         gltexture_t *glt;
866         gltexturepool_t *pool = (gltexturepool_t *)rtexturepool;
867         textypeinfo_t *texinfo;
868         unsigned short crc;
869
870         if (cls.state == ca_dedicated)
871                 return NULL;
872
873         texinfo = R_GetTexTypeInfo(textype, flags);
874
875         // data can be NULL
876 //      if (data == NULL)
877 //              Host_Error("R_LoadTexture: \"%s\" has no data\n", identifier);
878
879         if (flags & TEXF_FRAGMENT)
880         {
881                 if (width > block_size || height > block_size)
882                         Host_Error("R_LoadTexture: fragment too big, must be no more than %dx%d\n", block_size, block_size);
883                 if ((width * texinfo->internalbytesperpixel) & 3)
884                         Host_Error("R_LoadTexture: incompatible width for fragment");
885         }
886
887         // clear the alpha flag if the texture has no transparent pixels
888         switch(textype)
889         {
890         case TEXTYPE_QPALETTE:
891                 if (flags & TEXF_ALPHA)
892                 {
893                         flags &= ~TEXF_ALPHA;
894                         for (i = 0;i < width * height;i++)
895                         {
896                                 if (data[i] == 255)
897                                 {
898                                         flags |= TEXF_ALPHA;
899                                         break;
900                                 }
901                         }
902                 }
903                 break;
904         case TEXTYPE_RGB:
905                 if (flags & TEXF_ALPHA)
906                         Host_Error("R_LoadTexture: RGB has no alpha, don't specify TEXF_ALPHA\n");
907                 break;
908         case TEXTYPE_RGBA:
909                 if (flags & TEXF_ALPHA)
910                 {
911                         flags &= ~TEXF_ALPHA;
912                         for (i = 0;i < width * height;i++)
913                         {
914                                 if (data[i * 4 + 3] < 255)
915                                 {
916                                         flags |= TEXF_ALPHA;
917                                         break;
918                                 }
919                         }
920                 }
921                 break;
922         default:
923                 Host_Error("R_LoadTexture: unknown texture type\n");
924         }
925
926         // LordHavoc: do a CRC to confirm the data really is the same as previous occurances.
927         if (data == NULL)
928                 crc = 0;
929         else
930                 crc = CRC_Block(data, width*height*texinfo->inputbytesperpixel);
931
932         // see if the texture is already present
933         if (identifier && (glt = R_FindTexture(pool, identifier)))
934         {
935                 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)
936                 {
937                         Con_Printf("R_LoadTexture: exact match with existing texture %s\n", identifier);
938                         return (rtexture_t *)glt; // exact match, use existing
939                 }
940                 Con_Printf("R_LoadTexture: cache mismatch on %s, replacing old texture\n", identifier);
941                 R_FreeTexture(glt);
942         }
943
944         return (rtexture_t *)R_SetupTexture(pool, identifier, crc, width, height, flags | GLTEXF_UPLOAD, texinfo, data, NULL, NULL, 0);
945 }
946
947 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)
948 {
949         gltexture_t             *glt;
950         gltexturepool_t *pool = (gltexturepool_t *)rtexturepool;
951         textypeinfo_t   *texinfo;
952
953         if (cls.state == ca_dedicated)
954                 return NULL;
955
956         texinfo = R_GetTexTypeInfo(textype, flags);
957
958         // no function is supported, for odd uses
959 //      if (generate == NULL)
960 //              Host_Error("R_ProceduralTexture: \"%s\" has no generate function\n", identifier);
961         if (flags & TEXF_FRAGMENT)
962         {
963                 if (width > block_size || height > block_size)
964                         Host_Error("R_ProceduralTexture: fragment too big, must be no more than %dx%d\n", block_size, block_size);
965                 if ((width * texinfo->internalbytesperpixel) & 3)
966                         Host_Error("R_ProceduralTexture: incompatible width for fragment");
967         }
968
969         // see if the texture is already present
970         if (identifier && (glt = R_FindTexture(pool, identifier)))
971         {
972                 if (width == glt->width && height == glt->height && texinfo == glt->textype && ((flags ^ glt->flags) & TEXF_IMPORTANTBITS) == 0 && ((flags ^ glt->flags) & GLTEXF_IMPORTANTBITS) == 0)
973                 {
974                         Con_Printf("R_LoadTexture: exact match with existing texture %s\n", identifier);
975                         return (rtexture_t *)glt; // exact match, use existing
976                 }
977                 Con_Printf("R_LoadTexture: cache mismatch, replacing old texture\n");
978                 R_FreeTexture(glt);
979         }
980
981         return (rtexture_t *)R_SetupTexture(pool, identifier, 0, width, height, flags | GLTEXF_PROCEDURAL | GLTEXF_UPLOAD, texinfo, NULL, generate, proceduraldata, proceduraldatasize);
982 }
983
984 int R_TextureHasAlpha(rtexture_t *rt)
985 {
986         gltexture_t *glt;
987         if (!rt)
988                 return false;
989         glt = (gltexture_t *)rt;
990         return (glt->flags & TEXF_ALPHA) != 0;
991 }
992
993 int R_TextureWidth(rtexture_t *rt)
994 {
995         if (!rt)
996                 return false;
997         return ((gltexture_t *)rt)->width;
998 }
999
1000 int R_TextureHeight(rtexture_t *rt)
1001 {
1002         if (!rt)
1003                 return false;
1004         return ((gltexture_t *)rt)->height;
1005 }
1006
1007 void R_FragmentLocation(rtexture_t *rt, int *x, int *y, float *fx1, float *fy1, float *fx2, float *fy2)
1008 {
1009         gltexture_t *glt;
1010         float iwidth, iheight;
1011         if (cls.state == ca_dedicated)
1012         {
1013                 if (x)
1014                         *x = 0;
1015                 if (y)
1016                         *y = 0;
1017                 if (fx1 || fy1 || fx2 || fy2)
1018                 {
1019                         if (fx1)
1020                                 *fx1 = 0;
1021                         if (fy1)
1022                                 *fy1 = 0;
1023                         if (fx2)
1024                                 *fx2 = 1;
1025                         if (fy2)
1026                                 *fy2 = 1;
1027                 }
1028                 return;
1029         }
1030         if (!rt)
1031                 Host_Error("R_FragmentLocation: no texture supplied\n");
1032         glt = (gltexture_t *)rt;
1033         if (glt->flags & TEXF_FRAGMENT)
1034         {
1035                 if (x)
1036                         *x = glt->x;
1037                 if (y)
1038                         *y = glt->y;
1039                 if (fx1 || fy1 || fx2 || fy2)
1040                 {
1041                         iwidth = 1.0f / glt->image->width;
1042                         iheight = 1.0f / glt->image->height;
1043                         if (fx1)
1044                                 *fx1 = glt->x * iwidth;
1045                         if (fy1)
1046                                 *fy1 = glt->y * iheight;
1047                         if (fx2)
1048                                 *fx2 = (glt->x + glt->width) * iwidth;
1049                         if (fy2)
1050                                 *fy2 = (glt->y + glt->height) * iheight;
1051                 }
1052         }
1053         else
1054         {
1055                 if (x)
1056                         *x = 0;
1057                 if (y)
1058                         *y = 0;
1059                 if (fx1 || fy1 || fx2 || fy2)
1060                 {
1061                         if (fx1)
1062                                 *fx1 = 0;
1063                         if (fy1)
1064                                 *fy1 = 0;
1065                         if (fx2)
1066                                 *fx2 = 1;
1067                         if (fy2)
1068                                 *fy2 = 1;
1069                 }
1070         }
1071 }
1072
1073 int R_CompatibleFragmentWidth(int width, int textype, int flags)
1074 {
1075         textypeinfo_t *texinfo = R_GetTexTypeInfo(textype, flags);
1076         while ((width * texinfo->internalbytesperpixel) & 3)
1077                 width++;
1078         return width;
1079 }
1080
1081 void R_UpdateTexture(rtexture_t *rt, qbyte *data)
1082 {
1083         gltexture_t *glt;
1084         if (rt == NULL)
1085                 Host_Error("R_UpdateTexture: no texture supplied\n");
1086         if (data == NULL)
1087                 Host_Error("R_UpdateTexture: no data supplied\n");
1088         glt = (gltexture_t *)rt;
1089         /*
1090         if (!(glt->flags & GLTEXF_PROCEDURAL))
1091         {
1092                 if (glt->inputtexels == NULL)
1093                 {
1094                         glt->inputtexels = Mem_Alloc(texturedatamempool, glt->width * glt->height * glt->textype->inputbytesperpixel);
1095                         if (glt->inputtexels == NULL)
1096                                 Host_Error("R_UpdateTexture: ran out of memory\n");
1097                 }
1098                 memcpy(glt->inputtexels, data, glt->width * glt->height * glt->textype->inputbytesperpixel);
1099         }
1100         R_Upload(glt, data);
1101         */
1102         // if it has not been uploaded yet, update the data that will be used when it is
1103         if (glt->inputtexels)
1104                 memcpy(glt->inputtexels, data, glt->width * glt->height * glt->textype->inputbytesperpixel);
1105         else
1106                 R_Upload(glt, data);
1107 }
1108