]> icculus.org git repositories - divverent/darkplaces.git/blob - gl_textures.c
implemented .loc file support, including some editing (add command, and removenearest...
[divverent/darkplaces.git] / gl_textures.c
1
2 #include "quakedef.h"
3 #include "image.h"
4 #include "jpeg.h"
5 #include "image_png.h"
6
7 cvar_t gl_max_size = {CVAR_SAVE, "gl_max_size", "2048", "maximum allowed texture size, can be used to reduce video memory usage, note: this is automatically reduced to match video card capabilities (such as 256 on 3Dfx cards before Voodoo4/5)"};
8 cvar_t gl_picmip = {CVAR_SAVE, "gl_picmip", "0", "reduces resolution of textures by powers of 2, for example 1 will halve width/height, reducing texture memory usage by 75%"};
9 cvar_t r_lerpimages = {CVAR_SAVE, "r_lerpimages", "1", "bilinear filters images when scaling them up to power of 2 size (mode 1), looks better than glquake (mode 0)"};
10 cvar_t r_precachetextures = {CVAR_SAVE, "r_precachetextures", "1", "0 = never upload textures until used, 1 = upload most textures before use (exceptions: rarely used skin colormap layers), 2 = upload all textures before use (can increase texture memory usage significantly)"};
11 cvar_t gl_texture_anisotropy = {CVAR_SAVE, "gl_texture_anisotropy", "1", "anisotropic filtering quality (if supported by hardware), 1 sample (no anisotropy) and 8 sample (8 tap anisotropy) are recommended values"};
12
13 int             gl_filter_min = GL_LINEAR_MIPMAP_LINEAR;
14 int             gl_filter_mag = GL_LINEAR;
15
16
17 static mempool_t *texturemempool;
18
19 // note: this must not conflict with TEXF_ flags in r_textures.h
20 // cleared when a texture is uploaded
21 #define GLTEXF_UPLOAD 0x00010000
22 // bitmask for mismatch checking
23 #define GLTEXF_IMPORTANTBITS (0)
24 // set when image is uploaded and freed
25 #define GLTEXF_DESTROYED 0x00040000
26
27 typedef struct textypeinfo_s
28 {
29         int textype;
30         int inputbytesperpixel;
31         int internalbytesperpixel;
32         int glformat;
33         int glinternalformat;
34 }
35 textypeinfo_t;
36
37 static textypeinfo_t textype_palette       = {TEXTYPE_PALETTE, 1, 4, GL_RGBA   , 3};
38 static textypeinfo_t textype_rgb           = {TEXTYPE_RGB    , 3, 3, GL_RGB    , 3};
39 static textypeinfo_t textype_rgba          = {TEXTYPE_RGBA   , 4, 4, GL_RGBA   , 3};
40 static textypeinfo_t textype_palette_alpha = {TEXTYPE_PALETTE, 1, 4, GL_RGBA   , 4};
41 static textypeinfo_t textype_rgba_alpha    = {TEXTYPE_RGBA   , 4, 4, GL_RGBA   , 4};
42
43 #define GLTEXTURETYPE_1D 0
44 #define GLTEXTURETYPE_2D 1
45 #define GLTEXTURETYPE_3D 2
46 #define GLTEXTURETYPE_CUBEMAP 3
47
48 static int gltexturetypeenums[4] = {GL_TEXTURE_1D, GL_TEXTURE_2D, GL_TEXTURE_3D, GL_TEXTURE_CUBE_MAP_ARB};
49 static int gltexturetypebindingenums[4] = {GL_TEXTURE_BINDING_1D, GL_TEXTURE_BINDING_2D, GL_TEXTURE_BINDING_3D, GL_TEXTURE_BINDING_CUBE_MAP_ARB};
50 static int gltexturetypedimensions[4] = {1, 2, 3, 2};
51 static int cubemapside[6] =
52 {
53         GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB,
54         GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB,
55         GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB,
56         GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB,
57         GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB,
58         GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB
59 };
60
61 typedef struct gltexture_s
62 {
63         // this field is exposed to the R_GetTexture macro, for speed reasons
64         // (must be identical in rtexture_t)
65         int texnum; // GL texture slot number
66
67         // pointer to texturepool (check this to see if the texture is allocated)
68         struct gltexturepool_s *pool;
69         // pointer to next texture in texturepool chain
70         struct gltexture_s *chain;
71         // name of the texture (this might be removed someday), no duplicates
72         char identifier[32];
73         // original data size in *inputtexels
74         int inputwidth, inputheight, inputdepth;
75         // copy of the original texture(s) supplied to the upload function, for
76         // delayed uploads (non-precached)
77         unsigned char *inputtexels;
78         // original data size in *inputtexels
79         int inputdatasize;
80         // flags supplied to the LoadTexture function
81         // (might be altered to remove TEXF_ALPHA), and GLTEXF_ private flags
82         int flags;
83         // pointer to one of the textype_ structs
84         textypeinfo_t *textype;
85         // one of the GLTEXTURETYPE_ values
86         int texturetype;
87         // palette if the texture is TEXTYPE_PALETTE
88         const unsigned int *palette;
89         // actual stored texture size after gl_picmip and gl_max_size are applied
90         // (power of 2 if gl_support_arb_texture_non_power_of_two is not supported)
91         int tilewidth, tileheight, tiledepth;
92         // 1 or 6 depending on texturetype
93         int sides;
94         // bytes per pixel
95         int bytesperpixel;
96         // GL_RGB or GL_RGBA
97         int glformat;
98         // 3 or 4
99         int glinternalformat;
100 }
101 gltexture_t;
102
103 #define TEXTUREPOOL_SENTINEL 0xC0DEDBAD
104
105 typedef struct gltexturepool_s
106 {
107         unsigned int sentinel;
108         struct gltexture_s *gltchain;
109         struct gltexturepool_s *next;
110 }
111 gltexturepool_t;
112
113 static gltexturepool_t *gltexturepoolchain = NULL;
114
115 static unsigned char *resizebuffer = NULL, *colorconvertbuffer;
116 static int resizebuffersize = 0;
117 static unsigned char *texturebuffer;
118 static int texturebuffersize = 0;
119
120 static textypeinfo_t *R_GetTexTypeInfo(int textype, int flags)
121 {
122         if (flags & TEXF_ALPHA)
123         {
124                 switch(textype)
125                 {
126                 case TEXTYPE_PALETTE:
127                         return &textype_palette_alpha;
128                 case TEXTYPE_RGB:
129                         Host_Error("R_GetTexTypeInfo: RGB format has no alpha, TEXF_ALPHA not allowed");
130                         return NULL;
131                 case TEXTYPE_RGBA:
132                         return &textype_rgba_alpha;
133                 default:
134                         Host_Error("R_GetTexTypeInfo: unknown texture format");
135                         return NULL;
136                 }
137         }
138         else
139         {
140                 switch(textype)
141                 {
142                 case TEXTYPE_PALETTE:
143                         return &textype_palette;
144                 case TEXTYPE_RGB:
145                         return &textype_rgb;
146                 case TEXTYPE_RGBA:
147                         return &textype_rgba;
148                 default:
149                         Host_Error("R_GetTexTypeInfo: unknown texture format");
150                         return NULL;
151                 }
152         }
153 }
154
155 static void R_UploadTexture(gltexture_t *t);
156
157 static void R_PrecacheTexture(gltexture_t *glt)
158 {
159         int precache;
160         precache = false;
161         if (glt->flags & TEXF_ALWAYSPRECACHE)
162                 precache = true;
163         else if (r_precachetextures.integer >= 2)
164                 precache = true;
165         else if (r_precachetextures.integer >= 1)
166                 if (glt->flags & TEXF_PRECACHE)
167                         precache = true;
168
169         if (precache)
170                 R_UploadTexture(glt);
171 }
172
173 int R_RealGetTexture(rtexture_t *rt)
174 {
175         if (rt)
176         {
177                 gltexture_t *glt;
178                 glt = (gltexture_t *)rt;
179                 if (glt->flags & GLTEXF_UPLOAD)
180                         R_UploadTexture(glt);
181                 return glt->texnum;
182         }
183         else
184                 return 0;
185 }
186
187 void R_FreeTexture(rtexture_t *rt)
188 {
189         gltexture_t *glt, **gltpointer;
190
191         glt = (gltexture_t *)rt;
192         if (glt == NULL)
193                 Host_Error("R_FreeTexture: texture == NULL");
194
195         for (gltpointer = &glt->pool->gltchain;*gltpointer && *gltpointer != glt;gltpointer = &(*gltpointer)->chain);
196         if (*gltpointer == glt)
197                 *gltpointer = glt->chain;
198         else
199                 Host_Error("R_FreeTexture: texture \"%s\" not linked in pool", glt->identifier);
200
201         if (glt->texnum)
202         {
203                 CHECKGLERROR
204                 qglDeleteTextures(1, (GLuint *)&glt->texnum);CHECKGLERROR
205         }
206
207         if (glt->inputtexels)
208                 Mem_Free(glt->inputtexels);
209         Mem_Free(glt);
210 }
211
212 rtexturepool_t *R_AllocTexturePool(void)
213 {
214         gltexturepool_t *pool;
215         if (texturemempool == NULL)
216                 return NULL;
217         pool = (gltexturepool_t *)Mem_Alloc(texturemempool, sizeof(gltexturepool_t));
218         if (pool == NULL)
219                 return NULL;
220         pool->next = gltexturepoolchain;
221         gltexturepoolchain = pool;
222         pool->sentinel = TEXTUREPOOL_SENTINEL;
223         return (rtexturepool_t *)pool;
224 }
225
226 void R_FreeTexturePool(rtexturepool_t **rtexturepool)
227 {
228         gltexturepool_t *pool, **poolpointer;
229         if (rtexturepool == NULL)
230                 return;
231         if (*rtexturepool == NULL)
232                 return;
233         pool = (gltexturepool_t *)(*rtexturepool);
234         *rtexturepool = NULL;
235         if (pool->sentinel != TEXTUREPOOL_SENTINEL)
236                 Host_Error("R_FreeTexturePool: pool already freed");
237         for (poolpointer = &gltexturepoolchain;*poolpointer && *poolpointer != pool;poolpointer = &(*poolpointer)->next);
238         if (*poolpointer == pool)
239                 *poolpointer = pool->next;
240         else
241                 Host_Error("R_FreeTexturePool: pool not linked");
242         while (pool->gltchain)
243                 R_FreeTexture((rtexture_t *)pool->gltchain);
244         Mem_Free(pool);
245 }
246
247
248 typedef struct glmode_s
249 {
250         char *name;
251         int minification, magnification;
252 }
253 glmode_t;
254
255 static glmode_t modes[6] =
256 {
257         {"GL_NEAREST", GL_NEAREST, GL_NEAREST},
258         {"GL_LINEAR", GL_LINEAR, GL_LINEAR},
259         {"GL_NEAREST_MIPMAP_NEAREST", GL_NEAREST_MIPMAP_NEAREST, GL_NEAREST},
260         {"GL_LINEAR_MIPMAP_NEAREST", GL_LINEAR_MIPMAP_NEAREST, GL_LINEAR},
261         {"GL_NEAREST_MIPMAP_LINEAR", GL_NEAREST_MIPMAP_LINEAR, GL_NEAREST},
262         {"GL_LINEAR_MIPMAP_LINEAR", GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR}
263 };
264
265 static void GL_TextureMode_f (void)
266 {
267         int i;
268         GLint oldbindtexnum;
269         gltexture_t *glt;
270         gltexturepool_t *pool;
271
272         if (Cmd_Argc() == 1)
273         {
274                 for (i = 0;i < 6;i++)
275                 {
276                         if (gl_filter_min == modes[i].minification)
277                         {
278                                 Con_Printf("%s\n", modes[i].name);
279                                 return;
280                         }
281                 }
282                 Con_Print("current filter is unknown???\n");
283                 return;
284         }
285
286         for (i = 0;i < 6;i++)
287                 if (!strcasecmp (modes[i].name, Cmd_Argv(1) ) )
288                         break;
289         if (i == 6)
290         {
291                 Con_Print("bad filter name\n");
292                 return;
293         }
294
295         gl_filter_min = modes[i].minification;
296         gl_filter_mag = modes[i].magnification;
297
298         // change all the existing mipmap texture objects
299         // FIXME: force renderer(/client/something?) restart instead?
300         CHECKGLERROR
301         for (pool = gltexturepoolchain;pool;pool = pool->next)
302         {
303                 for (glt = pool->gltchain;glt;glt = glt->chain)
304                 {
305                         // only update already uploaded images
306                         if (!(glt->flags & (GLTEXF_UPLOAD | TEXF_FORCENEAREST | TEXF_FORCELINEAR)))
307                         {
308                                 qglGetIntegerv(gltexturetypebindingenums[glt->texturetype], &oldbindtexnum);CHECKGLERROR
309                                 qglBindTexture(gltexturetypeenums[glt->texturetype], glt->texnum);CHECKGLERROR
310                                 if (glt->flags & TEXF_MIPMAP)
311                                 {
312                                         qglTexParameteri(gltexturetypeenums[glt->texturetype], GL_TEXTURE_MIN_FILTER, gl_filter_min);CHECKGLERROR
313                                 }
314                                 else
315                                 {
316                                         qglTexParameteri(gltexturetypeenums[glt->texturetype], GL_TEXTURE_MIN_FILTER, gl_filter_mag);CHECKGLERROR
317                                 }
318                                 qglTexParameteri(gltexturetypeenums[glt->texturetype], GL_TEXTURE_MAG_FILTER, gl_filter_mag);CHECKGLERROR
319                                 qglBindTexture(gltexturetypeenums[glt->texturetype], oldbindtexnum);CHECKGLERROR
320                         }
321                 }
322         }
323 }
324
325 static void GL_Texture_CalcImageSize(int texturetype, int flags, int inwidth, int inheight, int indepth, int *outwidth, int *outheight, int *outdepth)
326 {
327         int picmip = 0, maxsize = 0, width2 = 1, height2 = 1, depth2 = 1;
328
329         if (gl_max_size.integer > gl_max_texture_size)
330                 Cvar_SetValue("gl_max_size", gl_max_texture_size);
331
332         switch (texturetype)
333         {
334         default:
335         case GLTEXTURETYPE_1D:
336         case GLTEXTURETYPE_2D:
337                 maxsize = gl_max_texture_size;
338                 break;
339         case GLTEXTURETYPE_3D:
340                 maxsize = gl_max_3d_texture_size;
341                 break;
342         case GLTEXTURETYPE_CUBEMAP:
343                 maxsize = gl_max_cube_map_texture_size;
344                 break;
345         }
346
347         if (flags & TEXF_PICMIP)
348         {
349                 maxsize = min(maxsize, gl_max_size.integer);
350                 picmip = gl_picmip.integer;
351         }
352
353         if (outwidth)
354         {
355                 if (gl_support_arb_texture_non_power_of_two)
356                         width2 = min(inwidth >> picmip, maxsize);
357                 else
358                 {
359                         for (width2 = 1;width2 < inwidth;width2 <<= 1);
360                         for (width2 >>= picmip;width2 > maxsize;width2 >>= 1);
361                 }
362                 *outwidth = max(1, width2);
363         }
364         if (outheight)
365         {
366                 if (gl_support_arb_texture_non_power_of_two)
367                         height2 = min(inheight >> picmip, maxsize);
368                 else
369                 {
370                         for (height2 = 1;height2 < inheight;height2 <<= 1);
371                         for (height2 >>= picmip;height2 > maxsize;height2 >>= 1);
372                 }
373                 *outheight = max(1, height2);
374         }
375         if (outdepth)
376         {
377                 if (gl_support_arb_texture_non_power_of_two)
378                         depth2 = min(indepth >> picmip, maxsize);
379                 else
380                 {
381                         for (depth2 = 1;depth2 < indepth;depth2 <<= 1);
382                         for (depth2 >>= picmip;depth2 > maxsize;depth2 >>= 1);
383                 }
384                 *outdepth = max(1, depth2);
385         }
386 }
387
388
389 static int R_CalcTexelDataSize (gltexture_t *glt)
390 {
391         int width2, height2, depth2, size;
392
393         GL_Texture_CalcImageSize(glt->texturetype, glt->flags, glt->inputwidth, glt->inputheight, glt->inputdepth, &width2, &height2, &depth2);
394
395         size = width2 * height2 * depth2;
396
397         if (glt->flags & TEXF_MIPMAP)
398         {
399                 while (width2 > 1 || height2 > 1 || depth2 > 1)
400                 {
401                         if (width2 > 1)
402                                 width2 >>= 1;
403                         if (height2 > 1)
404                                 height2 >>= 1;
405                         if (depth2 > 1)
406                                 depth2 >>= 1;
407                         size += width2 * height2 * depth2;
408                 }
409         }
410
411         return size * glt->textype->internalbytesperpixel * glt->sides;
412 }
413
414 void R_TextureStats_Print(qboolean printeach, qboolean printpool, qboolean printtotal)
415 {
416         int glsize;
417         int isloaded;
418         int pooltotal = 0, pooltotalt = 0, pooltotalp = 0, poolloaded = 0, poolloadedt = 0, poolloadedp = 0;
419         int sumtotal = 0, sumtotalt = 0, sumtotalp = 0, sumloaded = 0, sumloadedt = 0, sumloadedp = 0;
420         gltexture_t *glt;
421         gltexturepool_t *pool;
422         if (printeach)
423                 Con_Print("glsize input loaded mip alpha name\n");
424         for (pool = gltexturepoolchain;pool;pool = pool->next)
425         {
426                 pooltotal = 0;
427                 pooltotalt = 0;
428                 pooltotalp = 0;
429                 poolloaded = 0;
430                 poolloadedt = 0;
431                 poolloadedp = 0;
432                 for (glt = pool->gltchain;glt;glt = glt->chain)
433                 {
434                         glsize = R_CalcTexelDataSize(glt);
435                         isloaded = !(glt->flags & GLTEXF_UPLOAD);
436                         pooltotal++;
437                         pooltotalt += glsize;
438                         pooltotalp += glt->inputdatasize;
439                         if (isloaded)
440                         {
441                                 poolloaded++;
442                                 poolloadedt += glsize;
443                                 poolloadedp += glt->inputdatasize;
444                         }
445                         if (printeach)
446                                 Con_Printf("%c%4i%c%c%4i%c %s %s %s %s\n", isloaded ? '[' : ' ', (glsize + 1023) / 1024, isloaded ? ']' : ' ', glt->inputtexels ? '[' : ' ', (glt->inputdatasize + 1023) / 1024, glt->inputtexels ? ']' : ' ', isloaded ? "loaded" : "      ", (glt->flags & TEXF_MIPMAP) ? "mip" : "   ", (glt->flags & TEXF_ALPHA) ? "alpha" : "     ", glt->identifier);
447                 }
448                 if (printpool)
449                         Con_Printf("texturepool %10p total: %i (%.3fMB, %.3fMB original), uploaded %i (%.3fMB, %.3fMB original), upload on demand %i (%.3fMB, %.3fMB original)\n", pool, pooltotal, pooltotalt / 1048576.0, pooltotalp / 1048576.0, poolloaded, poolloadedt / 1048576.0, poolloadedp / 1048576.0, pooltotal - poolloaded, (pooltotalt - poolloadedt) / 1048576.0, (pooltotalp - poolloadedp) / 1048576.0);
450                 sumtotal += pooltotal;
451                 sumtotalt += pooltotalt;
452                 sumtotalp += pooltotalp;
453                 sumloaded += poolloaded;
454                 sumloadedt += poolloadedt;
455                 sumloadedp += poolloadedp;
456         }
457         if (printtotal)
458                 Con_Printf("textures total: %i (%.3fMB, %.3fMB original), uploaded %i (%.3fMB, %.3fMB original), upload on demand %i (%.3fMB, %.3fMB original)\n", sumtotal, sumtotalt / 1048576.0, sumtotalp / 1048576.0, sumloaded, sumloadedt / 1048576.0, sumloadedp / 1048576.0, sumtotal - sumloaded, (sumtotalt - sumloadedt) / 1048576.0, (sumtotalp - sumloadedp) / 1048576.0);
459 }
460
461 static void R_TextureStats_f(void)
462 {
463         R_TextureStats_Print(true, true, true);
464 }
465
466 static void r_textures_start(void)
467 {
468         // LordHavoc: allow any alignment
469         CHECKGLERROR
470         qglPixelStorei(GL_UNPACK_ALIGNMENT, 1);CHECKGLERROR
471         qglPixelStorei(GL_PACK_ALIGNMENT, 1);CHECKGLERROR
472
473         texturemempool = Mem_AllocPool("texture management", 0, NULL);
474
475         // Disable JPEG screenshots if the DLL isn't loaded
476         if (! JPEG_OpenLibrary ())
477                 Cvar_SetValueQuick (&scr_screenshot_jpeg, 0);
478         // TODO: support png screenshots?
479         PNG_OpenLibrary ();
480 }
481
482 static void r_textures_shutdown(void)
483 {
484         rtexturepool_t *temp;
485
486         JPEG_CloseLibrary ();
487
488         while(gltexturepoolchain)
489         {
490                 temp = (rtexturepool_t *) gltexturepoolchain;
491                 R_FreeTexturePool(&temp);
492         }
493
494         resizebuffersize = 0;
495         texturebuffersize = 0;
496         resizebuffer = NULL;
497         colorconvertbuffer = NULL;
498         texturebuffer = NULL;
499         Mem_FreePool(&texturemempool);
500 }
501
502 static void r_textures_newmap(void)
503 {
504 }
505
506 void R_Textures_Init (void)
507 {
508         Cmd_AddCommand("gl_texturemode", &GL_TextureMode_f, "set texture filtering mode (GL_NEAREST, GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, etc)");
509         Cmd_AddCommand("r_texturestats", R_TextureStats_f, "print information about all loaded textures and some statistics");
510         Cvar_RegisterVariable (&gl_max_size);
511         Cvar_RegisterVariable (&gl_picmip);
512         Cvar_RegisterVariable (&r_lerpimages);
513         Cvar_RegisterVariable (&r_precachetextures);
514         Cvar_RegisterVariable (&gl_texture_anisotropy);
515
516         R_RegisterModule("R_Textures", r_textures_start, r_textures_shutdown, r_textures_newmap);
517 }
518
519 void R_Textures_Frame (void)
520 {
521         static int old_aniso = 0;
522
523         // could do procedural texture animation here, if we keep track of which
524         // textures were accessed this frame...
525
526         // free the resize buffers
527         resizebuffersize = 0;
528         if (resizebuffer)
529         {
530                 Mem_Free(resizebuffer);
531                 resizebuffer = NULL;
532         }
533         if (colorconvertbuffer)
534         {
535                 Mem_Free(colorconvertbuffer);
536                 colorconvertbuffer = NULL;
537         }
538
539         if (old_aniso != gl_texture_anisotropy.integer)
540         {
541                 gltexture_t *glt;
542                 gltexturepool_t *pool;
543                 GLint oldbindtexnum;
544
545                 old_aniso = bound(1, gl_texture_anisotropy.integer, gl_max_anisotropy);
546
547                 Cvar_SetValueQuick(&gl_texture_anisotropy, old_aniso);
548
549                 CHECKGLERROR
550                 for (pool = gltexturepoolchain;pool;pool = pool->next)
551                 {
552                         for (glt = pool->gltchain;glt;glt = glt->chain)
553                         {
554                                 // only update already uploaded images
555                                 if ((glt->flags & (GLTEXF_UPLOAD | TEXF_MIPMAP)) == TEXF_MIPMAP)
556                                 {
557                                         qglGetIntegerv(gltexturetypebindingenums[glt->texturetype], &oldbindtexnum);CHECKGLERROR
558
559                                         qglBindTexture(gltexturetypeenums[glt->texturetype], glt->texnum);CHECKGLERROR
560                                         qglTexParameteri(gltexturetypeenums[glt->texturetype], GL_TEXTURE_MAX_ANISOTROPY_EXT, old_aniso);CHECKGLERROR
561
562                                         qglBindTexture(gltexturetypeenums[glt->texturetype], oldbindtexnum);CHECKGLERROR
563                                 }
564                         }
565                 }
566         }
567 }
568
569 void R_MakeResizeBufferBigger(int size)
570 {
571         if (resizebuffersize < size)
572         {
573                 resizebuffersize = size;
574                 if (resizebuffer)
575                         Mem_Free(resizebuffer);
576                 if (colorconvertbuffer)
577                         Mem_Free(colorconvertbuffer);
578                 resizebuffer = (unsigned char *)Mem_Alloc(texturemempool, resizebuffersize);
579                 colorconvertbuffer = (unsigned char *)Mem_Alloc(texturemempool, resizebuffersize);
580                 if (!resizebuffer || !colorconvertbuffer)
581                         Host_Error("R_Upload: out of memory");
582         }
583 }
584
585 static void GL_SetupTextureParameters(int flags, int texturetype)
586 {
587         int textureenum = gltexturetypeenums[texturetype];
588         int wrapmode = ((flags & TEXF_CLAMP) && gl_support_clamptoedge) ? GL_CLAMP_TO_EDGE : GL_REPEAT;
589
590         CHECKGLERROR
591
592         if (gl_support_anisotropy && (flags & TEXF_MIPMAP))
593         {
594                 int aniso = bound(1, gl_texture_anisotropy.integer, gl_max_anisotropy);
595                 if (gl_texture_anisotropy.integer != aniso)
596                         Cvar_SetValueQuick(&gl_texture_anisotropy, aniso);
597                 qglTexParameteri(textureenum, GL_TEXTURE_MAX_ANISOTROPY_EXT, aniso);CHECKGLERROR
598         }
599         qglTexParameteri(textureenum, GL_TEXTURE_WRAP_S, wrapmode);CHECKGLERROR
600         qglTexParameteri(textureenum, GL_TEXTURE_WRAP_T, wrapmode);CHECKGLERROR
601         if (gltexturetypedimensions[texturetype] >= 3)
602         {
603                 qglTexParameteri(textureenum, GL_TEXTURE_WRAP_R, wrapmode);CHECKGLERROR
604         }
605
606         CHECKGLERROR
607         if (flags & TEXF_FORCENEAREST)
608         {
609                 if (flags & TEXF_MIPMAP)
610                 {
611                         qglTexParameteri(textureenum, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);CHECKGLERROR
612                 }
613                 else
614                 {
615                         qglTexParameteri(textureenum, GL_TEXTURE_MIN_FILTER, GL_NEAREST);CHECKGLERROR
616                 }
617                 qglTexParameteri(textureenum, GL_TEXTURE_MAG_FILTER, GL_NEAREST);CHECKGLERROR
618         }
619         else if (flags & TEXF_FORCELINEAR)
620         {
621                 if (flags & TEXF_MIPMAP)
622                 {
623                         if (gl_filter_min == GL_NEAREST_MIPMAP_LINEAR || gl_filter_min == GL_LINEAR_MIPMAP_LINEAR)
624                         {
625                                 qglTexParameteri(textureenum, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);CHECKGLERROR
626                         }
627                         else
628                         {
629                                 qglTexParameteri(textureenum, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);CHECKGLERROR
630                         }
631                 }
632                 else
633                 {
634                         qglTexParameteri(textureenum, GL_TEXTURE_MIN_FILTER, GL_LINEAR);CHECKGLERROR
635                 }
636                 qglTexParameteri(textureenum, GL_TEXTURE_MAG_FILTER, GL_LINEAR);CHECKGLERROR
637         }
638         else
639         {
640                 if (flags & TEXF_MIPMAP)
641                 {
642                         qglTexParameteri(textureenum, GL_TEXTURE_MIN_FILTER, gl_filter_min);CHECKGLERROR
643                 }
644                 else
645                 {
646                         qglTexParameteri(textureenum, GL_TEXTURE_MIN_FILTER, gl_filter_mag);CHECKGLERROR
647                 }
648                 qglTexParameteri(textureenum, GL_TEXTURE_MAG_FILTER, gl_filter_mag);CHECKGLERROR
649         }
650
651         CHECKGLERROR
652 }
653
654 static void R_Upload(gltexture_t *glt, unsigned char *data, int fragx, int fragy, int fragz, int fragwidth, int fragheight, int fragdepth)
655 {
656         int i, mip, width, height, depth;
657         GLint oldbindtexnum;
658         unsigned char *prevbuffer;
659         prevbuffer = data;
660
661         CHECKGLERROR
662
663         // we need to restore the texture binding after finishing the upload
664         qglGetIntegerv(gltexturetypebindingenums[glt->texturetype], &oldbindtexnum);CHECKGLERROR
665         qglBindTexture(gltexturetypeenums[glt->texturetype], glt->texnum);CHECKGLERROR
666
667         // these are rounded up versions of the size to do better resampling
668         if (gl_support_arb_texture_non_power_of_two)
669         {
670                 width = glt->inputwidth;
671                 height = glt->inputheight;
672                 depth = glt->inputdepth;
673         }
674         else
675         {
676                 for (width  = 1;width  < glt->inputwidth ;width  <<= 1);
677                 for (height = 1;height < glt->inputheight;height <<= 1);
678                 for (depth  = 1;depth  < glt->inputdepth ;depth  <<= 1);
679         }
680
681         R_MakeResizeBufferBigger(width * height * depth * glt->sides * glt->bytesperpixel);
682         R_MakeResizeBufferBigger(fragwidth * fragheight * fragdepth * glt->sides * glt->bytesperpixel);
683
684         if (prevbuffer == NULL)
685         {
686                 memset(resizebuffer, 0, fragwidth * fragheight * fragdepth * glt->bytesperpixel);
687                 prevbuffer = resizebuffer;
688         }
689         else if (glt->textype->textype == TEXTYPE_PALETTE)
690         {
691                 // promote paletted to RGBA, so we only have to worry about RGB and
692                 // RGBA in the rest of this code
693                 Image_Copy8bitRGBA(prevbuffer, colorconvertbuffer, fragwidth * fragheight * fragdepth * glt->sides, glt->palette);
694                 prevbuffer = colorconvertbuffer;
695         }
696
697         if ((glt->flags & (TEXF_MIPMAP | TEXF_PICMIP | GLTEXF_UPLOAD)) == 0 && glt->inputwidth == glt->tilewidth && glt->inputheight == glt->tileheight && glt->inputdepth == glt->tiledepth)
698         {
699                 // update a portion of the image
700                 switch(glt->texturetype)
701                 {
702                 case GLTEXTURETYPE_1D:
703                         qglTexSubImage1D(GL_TEXTURE_1D, 0, fragx, fragwidth, glt->glformat, GL_UNSIGNED_BYTE, prevbuffer);CHECKGLERROR
704                         break;
705                 case GLTEXTURETYPE_2D:
706                         qglTexSubImage2D(GL_TEXTURE_2D, 0, fragx, fragy, fragwidth, fragheight, glt->glformat, GL_UNSIGNED_BYTE, prevbuffer);CHECKGLERROR
707                         break;
708                 case GLTEXTURETYPE_3D:
709                         qglTexSubImage3D(GL_TEXTURE_3D, 0, fragx, fragy, fragz, fragwidth, fragheight, fragdepth, glt->glformat, GL_UNSIGNED_BYTE, prevbuffer);CHECKGLERROR
710                         break;
711                 default:
712                         Host_Error("R_Upload: partial update of type other than 1D, 2D, or 3D");
713                         break;
714                 }
715         }
716         else
717         {
718                 if (fragx || fragy || fragz || glt->inputwidth != fragwidth || glt->inputheight != fragheight || glt->inputdepth != fragdepth)
719                         Host_Error("R_Upload: partial update not allowed on initial upload or in combination with PICMIP or MIPMAP\n");
720
721                 // upload the image for the first time
722                 glt->flags &= ~GLTEXF_UPLOAD;
723
724                 // cubemaps contain multiple images and thus get processed a bit differently
725                 if (glt->texturetype != GLTEXTURETYPE_CUBEMAP)
726                 {
727                         if (glt->inputwidth != width || glt->inputheight != height || glt->inputdepth != depth)
728                         {
729                                 Image_Resample(prevbuffer, glt->inputwidth, glt->inputheight, glt->inputdepth, resizebuffer, width, height, depth, glt->bytesperpixel, r_lerpimages.integer);
730                                 prevbuffer = resizebuffer;
731                         }
732                         // picmip/max_size
733                         while (width > glt->tilewidth || height > glt->tileheight || depth > glt->tiledepth)
734                         {
735                                 Image_MipReduce(prevbuffer, resizebuffer, &width, &height, &depth, glt->tilewidth, glt->tileheight, glt->tiledepth, glt->bytesperpixel);
736                                 prevbuffer = resizebuffer;
737                         }
738                 }
739                 mip = 0;
740                 switch(glt->texturetype)
741                 {
742                 case GLTEXTURETYPE_1D:
743                         qglTexImage1D(GL_TEXTURE_1D, mip++, glt->glinternalformat, width, 0, glt->glformat, GL_UNSIGNED_BYTE, prevbuffer);CHECKGLERROR
744                         if (glt->flags & TEXF_MIPMAP)
745                         {
746                                 while (width > 1 || height > 1 || depth > 1)
747                                 {
748                                         Image_MipReduce(prevbuffer, resizebuffer, &width, &height, &depth, 1, 1, 1, glt->bytesperpixel);
749                                         prevbuffer = resizebuffer;
750                                         qglTexImage1D(GL_TEXTURE_1D, mip++, glt->glinternalformat, width, 0, glt->glformat, GL_UNSIGNED_BYTE, prevbuffer);CHECKGLERROR
751                                 }
752                         }
753                         break;
754                 case GLTEXTURETYPE_2D:
755                         qglTexImage2D(GL_TEXTURE_2D, mip++, glt->glinternalformat, width, height, 0, glt->glformat, GL_UNSIGNED_BYTE, prevbuffer);CHECKGLERROR
756                         if (glt->flags & TEXF_MIPMAP)
757                         {
758                                 while (width > 1 || height > 1 || depth > 1)
759                                 {
760                                         Image_MipReduce(prevbuffer, resizebuffer, &width, &height, &depth, 1, 1, 1, glt->bytesperpixel);
761                                         prevbuffer = resizebuffer;
762                                         qglTexImage2D(GL_TEXTURE_2D, mip++, glt->glinternalformat, width, height, 0, glt->glformat, GL_UNSIGNED_BYTE, prevbuffer);CHECKGLERROR
763                                 }
764                         }
765                         break;
766                 case GLTEXTURETYPE_3D:
767                         qglTexImage3D(GL_TEXTURE_3D, mip++, glt->glinternalformat, width, height, depth, 0, glt->glformat, GL_UNSIGNED_BYTE, prevbuffer);CHECKGLERROR
768                         if (glt->flags & TEXF_MIPMAP)
769                         {
770                                 while (width > 1 || height > 1 || depth > 1)
771                                 {
772                                         Image_MipReduce(prevbuffer, resizebuffer, &width, &height, &depth, 1, 1, 1, glt->bytesperpixel);
773                                         prevbuffer = resizebuffer;
774                                         qglTexImage3D(GL_TEXTURE_3D, mip++, glt->glinternalformat, width, height, depth, 0, glt->glformat, GL_UNSIGNED_BYTE, prevbuffer);CHECKGLERROR
775                                 }
776                         }
777                         break;
778                 case GLTEXTURETYPE_CUBEMAP:
779                         // convert and upload each side in turn,
780                         // from a continuous block of input texels
781                         texturebuffer = prevbuffer;
782                         for (i = 0;i < 6;i++)
783                         {
784                                 prevbuffer = texturebuffer;
785                                 texturebuffer += glt->inputwidth * glt->inputheight * glt->inputdepth * glt->textype->inputbytesperpixel;
786                                 if (glt->inputwidth != width || glt->inputheight != height || glt->inputdepth != depth)
787                                 {
788                                         Image_Resample(prevbuffer, glt->inputwidth, glt->inputheight, glt->inputdepth, resizebuffer, width, height, depth, glt->bytesperpixel, r_lerpimages.integer);
789                                         prevbuffer = resizebuffer;
790                                 }
791                                 // picmip/max_size
792                                 while (width > glt->tilewidth || height > glt->tileheight || depth > glt->tiledepth)
793                                 {
794                                         Image_MipReduce(prevbuffer, resizebuffer, &width, &height, &depth, glt->tilewidth, glt->tileheight, glt->tiledepth, glt->bytesperpixel);
795                                         prevbuffer = resizebuffer;
796                                 }
797                                 mip = 0;
798                                 qglTexImage2D(cubemapside[i], mip++, glt->glinternalformat, width, height, 0, glt->glformat, GL_UNSIGNED_BYTE, prevbuffer);CHECKGLERROR
799                                 if (glt->flags & TEXF_MIPMAP)
800                                 {
801                                         while (width > 1 || height > 1 || depth > 1)
802                                         {
803                                                 Image_MipReduce(prevbuffer, resizebuffer, &width, &height, &depth, 1, 1, 1, glt->bytesperpixel);
804                                                 prevbuffer = resizebuffer;
805                                                 qglTexImage2D(cubemapside[i], mip++, glt->glinternalformat, width, height, 0, glt->glformat, GL_UNSIGNED_BYTE, prevbuffer);CHECKGLERROR
806                                         }
807                                 }
808                         }
809                         break;
810                 }
811                 GL_SetupTextureParameters(glt->flags, glt->texturetype);
812         }
813         qglBindTexture(gltexturetypeenums[glt->texturetype], oldbindtexnum);CHECKGLERROR
814 }
815
816 static void R_UploadTexture (gltexture_t *glt)
817 {
818         if (!(glt->flags & GLTEXF_UPLOAD))
819                 return;
820
821         CHECKGLERROR
822         qglGenTextures(1, (GLuint *)&glt->texnum);CHECKGLERROR
823         R_Upload(glt, glt->inputtexels, 0, 0, 0, glt->inputwidth, glt->inputheight, glt->inputdepth);
824         if (glt->inputtexels)
825         {
826                 Mem_Free(glt->inputtexels);
827                 glt->inputtexels = NULL;
828                 glt->flags |= GLTEXF_DESTROYED;
829         }
830         else if (glt->flags & GLTEXF_DESTROYED)
831                 Con_Printf("R_UploadTexture: Texture %s already uploaded and destroyed.  Can not upload original image again.  Uploaded blank texture.\n", glt->identifier);
832 }
833
834 static rtexture_t *R_SetupTexture(rtexturepool_t *rtexturepool, const char *identifier, int width, int height, int depth, int sides, int flags, int textype, int texturetype, const unsigned char *data, const unsigned int *palette)
835 {
836         int i, size;
837         gltexture_t *glt;
838         gltexturepool_t *pool = (gltexturepool_t *)rtexturepool;
839         textypeinfo_t *texinfo;
840
841         if (cls.state == ca_dedicated)
842                 return NULL;
843
844         if (texturetype == GLTEXTURETYPE_CUBEMAP && !gl_texturecubemap)
845         {
846                 Con_Printf ("R_LoadTexture: cubemap texture not supported by driver\n");
847                 return NULL;
848         }
849         if (texturetype == GLTEXTURETYPE_3D && !gl_texture3d)
850         {
851                 Con_Printf ("R_LoadTexture: 3d texture not supported by driver\n");
852                 return NULL;
853         }
854
855         texinfo = R_GetTexTypeInfo(textype, flags);
856         size = width * height * depth * sides * texinfo->inputbytesperpixel;
857         if (size < 1)
858         {
859                 Con_Printf ("R_LoadTexture: bogus texture size (%dx%dx%dx%dbppx%dsides = %d bytes)\n", width, height, depth, texinfo->inputbytesperpixel * 8, sides, size);
860                 return NULL;
861         }
862
863         // clear the alpha flag if the texture has no transparent pixels
864         switch(textype)
865         {
866         case TEXTYPE_PALETTE:
867                 if (flags & TEXF_ALPHA)
868                 {
869                         flags &= ~TEXF_ALPHA;
870                         if (data)
871                         {
872                                 for (i = 0;i < size;i++)
873                                 {
874                                         if (((unsigned char *)&palette[data[i]])[3] < 255)
875                                         {
876                                                 flags |= TEXF_ALPHA;
877                                                 break;
878                                         }
879                                 }
880                         }
881                 }
882                 break;
883         case TEXTYPE_RGB:
884                 if (flags & TEXF_ALPHA)
885                         Host_Error("R_LoadTexture: RGB has no alpha, don't specify TEXF_ALPHA");
886                 break;
887         case TEXTYPE_RGBA:
888                 if (flags & TEXF_ALPHA)
889                 {
890                         flags &= ~TEXF_ALPHA;
891                         if (data)
892                         {
893                                 for (i = 3;i < size;i += 4)
894                                 {
895                                         if (data[i] < 255)
896                                         {
897                                                 flags |= TEXF_ALPHA;
898                                                 break;
899                                         }
900                                 }
901                         }
902                 }
903                 break;
904         default:
905                 Host_Error("R_LoadTexture: unknown texture type");
906         }
907
908         glt = (gltexture_t *)Mem_Alloc(texturemempool, sizeof(gltexture_t));
909         if (identifier)
910                 strlcpy (glt->identifier, identifier, sizeof(glt->identifier));
911         glt->pool = pool;
912         glt->chain = pool->gltchain;
913         pool->gltchain = glt;
914         glt->inputwidth = width;
915         glt->inputheight = height;
916         glt->inputdepth = depth;
917         glt->flags = flags | GLTEXF_UPLOAD;
918         glt->textype = texinfo;
919         glt->texturetype = texturetype;
920         glt->inputdatasize = size;
921         glt->palette = palette;
922         glt->glinternalformat = texinfo->glinternalformat;
923         glt->glformat = texinfo->glformat;
924         glt->bytesperpixel = texinfo->internalbytesperpixel;
925         glt->sides = glt->texturetype == GLTEXTURETYPE_CUBEMAP ? 6 : 1;
926         glt->texnum = -1;
927
928         if (data)
929         {
930                 glt->inputtexels = (unsigned char *)Mem_Alloc(texturemempool, size);
931                 memcpy(glt->inputtexels, data, size);
932         }
933         else
934                 glt->inputtexels = NULL;
935
936         GL_Texture_CalcImageSize(glt->texturetype, glt->flags, glt->inputwidth, glt->inputheight, glt->inputdepth, &glt->tilewidth, &glt->tileheight, &glt->tiledepth);
937         R_PrecacheTexture(glt);
938
939         return (rtexture_t *)glt;
940 }
941
942 rtexture_t *R_LoadTexture1D(rtexturepool_t *rtexturepool, const char *identifier, int width, const unsigned char *data, int textype, int flags, const unsigned int *palette)
943 {
944         return R_SetupTexture(rtexturepool, identifier, width, 1, 1, 1, flags, textype, GLTEXTURETYPE_1D, data, palette);
945 }
946
947 rtexture_t *R_LoadTexture2D(rtexturepool_t *rtexturepool, const char *identifier, int width, int height, const unsigned char *data, int textype, int flags, const unsigned int *palette)
948 {
949         return R_SetupTexture(rtexturepool, identifier, width, height, 1, 1, flags, textype, GLTEXTURETYPE_2D, data, palette);
950 }
951
952 rtexture_t *R_LoadTexture3D(rtexturepool_t *rtexturepool, const char *identifier, int width, int height, int depth, const unsigned char *data, int textype, int flags, const unsigned int *palette)
953 {
954         return R_SetupTexture(rtexturepool, identifier, width, height, depth, 1, flags, textype, GLTEXTURETYPE_3D, data, palette);
955 }
956
957 rtexture_t *R_LoadTextureCubeMap(rtexturepool_t *rtexturepool, const char *identifier, int width, const unsigned char *data, int textype, int flags, const unsigned int *palette)
958 {
959         return R_SetupTexture(rtexturepool, identifier, width, width, 1, 6, flags, textype, GLTEXTURETYPE_CUBEMAP, data, palette);
960 }
961
962 int R_TextureHasAlpha(rtexture_t *rt)
963 {
964         return rt ? (((gltexture_t *)rt)->flags & TEXF_ALPHA) != 0 : false;
965 }
966
967 int R_TextureWidth(rtexture_t *rt)
968 {
969         return rt ? ((gltexture_t *)rt)->inputwidth : 0;
970 }
971
972 int R_TextureHeight(rtexture_t *rt)
973 {
974         return rt ? ((gltexture_t *)rt)->inputheight : 0;
975 }
976
977 void R_UpdateTexture(rtexture_t *rt, unsigned char *data, int x, int y, int width, int height)
978 {
979         gltexture_t *glt;
980         if (rt == NULL)
981                 Host_Error("R_UpdateTexture: no texture supplied");
982         if (data == NULL)
983                 Host_Error("R_UpdateTexture: no data supplied");
984         glt = (gltexture_t *)rt;
985
986         // we need it to be uploaded before we can update a part of it
987         if (glt->flags & GLTEXF_UPLOAD)
988                 R_UploadTexture(glt);
989
990         // update part of the texture
991         R_Upload(glt, data, x, y, 0, width, height, 1);
992 }
993