/
gl_texmanager.cpp
3478 lines (2982 loc) · 114 KB
/
gl_texmanager.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file gl_texmanager.cpp GL-Texture management
*
* @todo This file needs to be split into smaller portions.
*
* @author Copyright © 1999-2012 Jaakko Keränen <jaakko.keranen@iki.fi>
* @author Copyright © 2005-2012 Daniel Swanson <danij@dengine.net>
* @author Copyright © 2002 Graham Jackson <no contact email published>
*
* @par License
* GPL: http://www.gnu.org/licenses/gpl.html
*
* <small>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. This program is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details. You should have received a copy of the GNU
* General Public License along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA</small>
*/
#include <cstdlib>
#include <cstring> // memset, memcpy
#include <cctype>
#include <cmath>
#ifdef UNIX
# include "de_platform.h"
#endif
#include "de_base.h"
#include "de_console.h"
#include "de_system.h"
#include "de_filesys.h"
#include "de_graphics.h"
#include "de_render.h"
#include "de_resource.h"
#include "de_play.h"
#include "de_ui.h"
#include "m_misc.h" // For M_Ceil/Floor/WeightPow2()
#include "def_main.h"
#include <QSize>
#include <de/ByteRefArray>
#include <de/memory.h>
#include <de/memoryzone.h>
using namespace de;
enum uploadcontentmethod_t
{
METHOD_IMMEDIATE = 0,
METHOD_DEFERRED
};
struct GraphicFileType
{
/// Symbolic name of the resource type.
String name;
/// Known file extension.
String ext;
bool (*interpretFunc)(de::FileHandle &hndl, String filePath, image_t &img);
char const *(*getLastErrorFunc)(); ///< Can be NULL.
};
struct texturevariantspecificationlist_node_t
{
texturevariantspecificationlist_node_t *next;
texturevariantspecification_t *spec;
};
typedef texturevariantspecificationlist_node_t variantspecificationlist_t;
D_CMD(LowRes);
D_CMD(MipMap);
D_CMD(TexReset);
void GL_DoResetDetailTextures();
void GL_DoTexReset();
void GL_DoUpdateTexGamma();
void GL_DoUpdateTexParams();
static int hashDetailVariantSpecification(detailvariantspecification_t const *spec);
static void calcGammaTable();
static bool interpretPcx(de::FileHandle &hndl, String filePath, image_t &img);
static bool interpretPng(de::FileHandle &hndl, String filePath, image_t &img);
static bool interpretJpg(de::FileHandle &hndl, String filePath, image_t &img);
static bool interpretTga(de::FileHandle &hndl, String filePath, image_t &img);
static TexSource loadExternalTexture(image_t &image, String searchPath, String optionalSuffix = "");
static TexSource loadFlat(image_t &image, de::FileHandle &file);
static TexSource loadPatch(image_t &image, de::FileHandle &file, int tclass = 0, int tmap = 0, int border = 0);
static TexSource loadDetail(image_t &image, de::FileHandle &file);
static TexSource loadRaw(image_t &image, rawtex_t const &raw);
static TexSource loadPatchComposite(image_t &image, de::Texture &tex,
bool zeroMask = false, bool useZeroOriginIfOneComponent = false);
int ratioLimit = 0; // Zero if none.
boolean fillOutlines = true;
int monochrome = 0; // desaturate a patch (average colours)
int upscaleAndSharpenPatches = 0;
int useSmartFilter = 0; // Smart filter mode (cvar: 1=hq2x)
int mipmapping = 5, filterUI = 1, texQuality = TEXQ_BEST;
int filterSprites = true;
int texMagMode = 1; // Linear.
int texAniso = -1; // Use best.
boolean noHighResTex = false;
boolean noHighResPatches = false;
boolean highResWithPWAD = false;
byte loadExtAlways = false; // Always check for extres (cvar)
float texGamma = 0;
byte gammaTable[256];
int glmode[6] = // Indexed by 'mipmapping'.
{
GL_NEAREST,
GL_LINEAR,
GL_NEAREST_MIPMAP_NEAREST,
GL_LINEAR_MIPMAP_NEAREST,
GL_NEAREST_MIPMAP_LINEAR,
GL_LINEAR_MIPMAP_LINEAR
};
// Names of the dynamic light textures.
ddtexture_t lightingTextures[NUM_LIGHTING_TEXTURES];
// Names of the flare textures (halos).
ddtexture_t sysFlareTextures[NUM_SYSFLARE_TEXTURES];
static boolean initedOk = false; // Init done.
// Graphic resource types.
static GraphicFileType const graphicTypes[] = {
{ "PNG", "png", interpretPng, 0 },
{ "JPG", "jpg", interpretJpg, 0 }, // TODO: add alternate "jpeg" extension
{ "TGA", "tga", interpretTga, TGA_LastError },
{ "PCX", "pcx", interpretPcx, PCX_LastError },
{ "", "", 0, 0 } // Terminate.
};
static variantspecificationlist_t *variantSpecs;
/// @c TST_DETAIL type specifications are stored separately into a set of
/// buckets. Bucket selection is determined by their quantized contrast value.
#define DETAILVARIANT_CONTRAST_HASHSIZE (DETAILTEXTURE_CONTRAST_QUANTIZATION_FACTOR+1)
static variantspecificationlist_t *detailVariantSpecs[DETAILVARIANT_CONTRAST_HASHSIZE];
void GL_TexRegister()
{
C_VAR_INT ("rend-tex", &renderTextures, CVF_NO_ARCHIVE, 0, 2);
C_VAR_INT ("rend-tex-detail", &r_detail, 0, 0, 1);
C_VAR_INT ("rend-tex-detail-multitex", &useMultiTexDetails, 0, 0, 1);
C_VAR_FLOAT ("rend-tex-detail-scale", &detailScale, CVF_NO_MIN | CVF_NO_MAX, 0, 0);
C_VAR_FLOAT2("rend-tex-detail-strength", &detailFactor, 0, 0, 10, GL_DoResetDetailTextures);
C_VAR_BYTE2 ("rend-tex-external-always", &loadExtAlways, 0, 0, 1, GL_DoTexReset);
C_VAR_INT ("rend-tex-filter-anisotropic", &texAniso, 0, -1, 4);
C_VAR_INT ("rend-tex-filter-mag", &texMagMode, 0, 0, 1);
C_VAR_INT2 ("rend-tex-filter-smart", &useSmartFilter, 0, 0, 1, GL_DoTexReset);
C_VAR_INT ("rend-tex-filter-sprite", &filterSprites, 0, 0, 1);
C_VAR_INT ("rend-tex-filter-ui", &filterUI, 0, 0, 1);
C_VAR_FLOAT2("rend-tex-gamma", &texGamma, 0, 0, 1, GL_DoUpdateTexGamma);
C_VAR_INT2 ("rend-tex-mipmap", &mipmapping, CVF_PROTECTED, 0, 5, GL_DoTexReset);
C_VAR_INT2 ("rend-tex-quality", &texQuality, 0, 0, 8, GL_DoTexReset);
C_CMD_FLAGS ("lowres", "", LowRes, CMDF_NO_DEDICATED);
C_CMD_FLAGS ("mipmap", "i", MipMap, CMDF_NO_DEDICATED);
C_CMD_FLAGS ("texreset", "", TexReset, CMDF_NO_DEDICATED);
Textures::consoleRegister();
}
static inline GLint glMinFilterForVariantSpec(variantspecification_t const *spec)
{
DENG_ASSERT(spec);
if(spec->minFilter >= 0) // Constant logical value.
{
return (spec->mipmapped? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST) + spec->minFilter;
}
// "No class" preference.
return spec->mipmapped? glmode[mipmapping] : GL_LINEAR;
}
static inline GLint glMagFilterForVariantSpec(variantspecification_t const *spec)
{
DENG_ASSERT(spec);
if(spec->magFilter >= 0) // Constant logical value.
{
return GL_NEAREST + spec->magFilter;
}
// Preference for texture class id.
switch(abs(spec->magFilter)-1)
{
case 1: // Sprite class.
return filterSprites? GL_LINEAR : GL_NEAREST;
case 2: // UI class.
return filterUI? GL_LINEAR : GL_NEAREST;
default: // "No class" preference.
return glmode[texMagMode];
}
}
static inline int logicalAnisoLevelForVariantSpec(variantspecification_t const *spec)
{
DENG_ASSERT(spec);
return spec->anisoFilter < 0? texAniso : spec->anisoFilter;
}
static texturevariantspecification_t *unlinkVariantSpecification(texturevariantspecification_t *spec)
{
variantspecificationlist_t **listHead;
DENG_ASSERT(initedOk && spec);
// Select list head according to variant specification type.
switch(spec->type)
{
case TST_GENERAL: listHead = &variantSpecs; break;
case TST_DETAIL: {
int hash = hashDetailVariantSpecification(TS_DETAIL(spec));
listHead = &detailVariantSpecs[hash];
break; }
default:
Con_Error("unlinkVariantSpecification: Invalid spec type %i.", spec->type);
exit(1); // Unreachable.
}
if(*listHead)
{
texturevariantspecificationlist_node_t *node = 0;
if((*listHead)->spec == spec)
{
node = (*listHead);
*listHead = (*listHead)->next;
}
else
{
// Find the previous node.
texturevariantspecificationlist_node_t *prevNode = (*listHead);
while(prevNode->next && prevNode->next->spec != spec)
{
prevNode = prevNode->next;
}
if(prevNode)
{
node = prevNode->next;
prevNode->next = prevNode->next->next;
}
}
M_Free(node);
}
return spec;
}
static void destroyVariantSpecification(texturevariantspecification_t *spec)
{
DENG_ASSERT(spec);
unlinkVariantSpecification(spec);
if(spec->type == TST_GENERAL && (TS_GENERAL(spec)->flags & TSF_HAS_COLORPALETTE_XLAT))
M_Free(TS_GENERAL(spec)->translated);
M_Free(spec);
}
static texturevariantspecification_t *copyVariantSpecification(
texturevariantspecification_t const *tpl)
{
texturevariantspecification_t *spec = (texturevariantspecification_t*) M_Malloc(sizeof(*spec));
if(!spec) Con_Error("Textures::copyVariantSpecification: Failed on allocation of %lu bytes for new TextureVariantSpecification.", (unsigned long) sizeof(*spec));
memcpy(spec, tpl, sizeof(texturevariantspecification_t));
if(TS_GENERAL(tpl)->flags & TSF_HAS_COLORPALETTE_XLAT)
{
colorpalettetranslationspecification_t *cpt = (colorpalettetranslationspecification_t *) M_Malloc(sizeof(*cpt));
if(!cpt) Con_Error("Textures::copyVariantSpecification: Failed on allocation of %lu bytes for new ColorPaletteTranslationSpecification.", (unsigned long) sizeof(*cpt));
memcpy(cpt, TS_GENERAL(tpl)->translated, sizeof(colorpalettetranslationspecification_t));
TS_GENERAL(spec)->translated = cpt;
}
return spec;
}
static texturevariantspecification_t *copyDetailVariantSpecification(
texturevariantspecification_t const *tpl)
{
texturevariantspecification_t *spec = (texturevariantspecification_t *) M_Malloc(sizeof(*spec));
if(!spec) Con_Error("Textures::copyDetailVariantSpecification: Failed on allocation of %lu bytes for new TextureVariantSpecification.", (unsigned long) sizeof(*spec));
memcpy(spec, tpl, sizeof(texturevariantspecification_t));
return spec;
}
/**
* @todo Magnification, Anisotropic filter level and GL texture wrap modes
* will be handled through dynamic changes to GL's texture environment state.
* Consequently they should be ignored here.
*/
static int compareVariantSpecifications(variantspecification_t const *a,
variantspecification_t const *b)
{
/// @todo We can be a bit cleverer here...
if(a->context != b->context) return 0;
if(a->flags != b->flags) return 0;
if(a->wrapS != b->wrapS || a->wrapT != b->wrapT) return 0;
//if(a->magFilter != b->magFilter) return 0;
//if(a->anisoFilter != b->anisoFilter) return 0;
if(a->mipmapped != b->mipmapped) return 0;
if(a->noStretch != b->noStretch) return 0;
if(a->gammaCorrection != b->gammaCorrection) return 0;
if(a->toAlpha != b->toAlpha) return 0;
if(a->border != b->border) return 0;
if(a->flags & TSF_HAS_COLORPALETTE_XLAT)
{
colorpalettetranslationspecification_t const *cptA = a->translated;
colorpalettetranslationspecification_t const *cptB = b->translated;
DENG_ASSERT(cptA && cptB);
if(cptA->tClass != cptB->tClass) return 0;
if(cptA->tMap != cptB->tMap) return 0;
}
return 1; // Equal.
}
static int compareDetailVariantSpecifications(detailvariantspecification_t const *a,
detailvariantspecification_t const *b)
{
if(a->contrast != b->contrast) return 0;
return 1; // Equal.
}
static colorpalettetranslationspecification_t *applyColorPaletteTranslationSpecification(
colorpalettetranslationspecification_t *spec, int tClass, int tMap)
{
DENG_ASSERT(initedOk && spec);
LOG_AS("applyColorPaletteTranslationSpecification");
spec->tClass = MAX_OF(0, tClass);
spec->tMap = MAX_OF(0, tMap);
#if _DEBUG
if(0 == tClass && 0 == tMap)
LOG_WARNING("Applied unnecessary zero-translation (tClass:0 tMap:0).");
#endif
return spec;
}
static variantspecification_t *applyVariantSpecification(
variantspecification_t *spec, texturevariantusagecontext_t tc, int flags,
byte border, colorpalettetranslationspecification_t *colorPaletteTranslationSpec,
int wrapS, int wrapT, int minFilter, int magFilter, int anisoFilter, boolean mipmapped,
boolean gammaCorrection, boolean noStretch, boolean toAlpha)
{
DENG_ASSERT(initedOk && spec && (tc == TC_UNKNOWN || VALID_TEXTUREVARIANTUSAGECONTEXT(tc)));
flags &= ~TSF_INTERNAL_MASK;
spec->context = tc;
spec->flags = flags;
spec->border = (flags & TSF_UPSCALE_AND_SHARPEN)? 1 : border;
spec->mipmapped = mipmapped;
spec->wrapS = wrapS;
spec->wrapT = wrapT;
spec->minFilter = MINMAX_OF(-1, minFilter, spec->mipmapped? 3:1);
spec->magFilter = MINMAX_OF(-3, magFilter, 1);
spec->anisoFilter = MINMAX_OF(-1, anisoFilter, 4);
spec->gammaCorrection = gammaCorrection;
spec->noStretch = noStretch;
spec->toAlpha = toAlpha;
if(colorPaletteTranslationSpec)
{
spec->flags |= TSF_HAS_COLORPALETTE_XLAT;
spec->translated = colorPaletteTranslationSpec;
}
else
{
spec->translated = NULL;
}
return spec;
}
static detailvariantspecification_t *applyDetailVariantSpecification(
detailvariantspecification_t *spec, float contrast)
{
int const quantFactor = DETAILTEXTURE_CONTRAST_QUANTIZATION_FACTOR;
DENG_ASSERT(spec);
spec->contrast = 255 * (int)MINMAX_OF(0, contrast * quantFactor + .5f, quantFactor) * (1 / float(quantFactor));
return spec;
}
static int hashDetailVariantSpecification(detailvariantspecification_t const *spec)
{
DENG_ASSERT(spec);
return (spec->contrast * (1/255.f) * DETAILTEXTURE_CONTRAST_QUANTIZATION_FACTOR + .5f);
}
static texturevariantspecification_t *linkVariantSpecification(
texturevariantspecificationtype_t type, texturevariantspecification_t *spec)
{
texturevariantspecificationlist_node_t *node;
DENG_ASSERT(initedOk && VALID_TEXTUREVARIANTSPECIFICATIONTYPE(type) && spec);
node = (texturevariantspecificationlist_node_t *) M_Malloc(sizeof(*node));
if(!node) Con_Error("Textures::linkVariantSpecification: Failed on allocation of %lu bytes for new TextureVariantSpecificationListNode.", (unsigned long) sizeof(*node));
node->spec = spec;
switch(type)
{
case TST_GENERAL:
node->next = variantSpecs;
variantSpecs = (variantspecificationlist_t *)node;
break;
case TST_DETAIL: {
int hash = hashDetailVariantSpecification(TS_DETAIL(spec));
node->next = detailVariantSpecs[hash];
detailVariantSpecs[hash] = (variantspecificationlist_t *)node;
break; }
}
return spec;
}
static texturevariantspecification_t *findVariantSpecification(
texturevariantspecificationtype_t type, texturevariantspecification_t const *tpl,
bool canCreate)
{
texturevariantspecificationlist_node_t *node;
DENG_ASSERT(initedOk && VALID_TEXTUREVARIANTSPECIFICATIONTYPE(type) && tpl);
// Select list head according to variant specification type.
switch(type)
{
case TST_GENERAL: node = variantSpecs; break;
case TST_DETAIL: {
int hash = hashDetailVariantSpecification(TS_DETAIL(tpl));
node = detailVariantSpecs[hash];
break; }
default:
Con_Error("findVariantSpecification: Invalid spec type %i.", type);
exit(1); // Unreachable.
}
// Do we already have a concrete version of the template specification?
for(; node; node = node->next)
{
if(GL_CompareTextureVariantSpecifications(node->spec, tpl))
return node->spec;
}
// Not found, can we create?
if(canCreate)
switch(type)
{
case TST_GENERAL: return linkVariantSpecification(type, copyVariantSpecification(tpl));
case TST_DETAIL: return linkVariantSpecification(type, copyDetailVariantSpecification(tpl));
}
return NULL;
}
static texturevariantspecification_t *getVariantSpecificationForContext(
texturevariantusagecontext_t tc, int flags, byte border, int tClass,
int tMap, int wrapS, int wrapT, int minFilter, int magFilter, int anisoFilter,
boolean mipmapped, boolean gammaCorrection, boolean noStretch, boolean toAlpha)
{
static texturevariantspecification_t tpl;
static colorpalettetranslationspecification_t cptTpl;
boolean haveCpt = false;
DENG_ASSERT(initedOk);
tpl.type = TST_GENERAL;
if(0 != tClass || 0 != tMap)
{
// A color palette translation spec is required.
applyColorPaletteTranslationSpecification(&cptTpl, tClass, tMap);
haveCpt = true;
}
applyVariantSpecification(TS_GENERAL(&tpl), tc, flags, border, haveCpt? &cptTpl : NULL,
wrapS, wrapT, minFilter, magFilter, anisoFilter, mipmapped, gammaCorrection,
noStretch, toAlpha);
// Retrieve a concrete version of the rationalized specification.
return findVariantSpecification(tpl.type, &tpl, true);
}
static texturevariantspecification_t *getDetailVariantSpecificationForContext(
float contrast)
{
static texturevariantspecification_t tpl;
DENG_ASSERT(initedOk);
tpl.type = TST_DETAIL;
applyDetailVariantSpecification(TS_DETAIL(&tpl), contrast);
return findVariantSpecification(tpl.type, &tpl, true);
}
static void emptyVariantSpecificationList(variantspecificationlist_t *list)
{
texturevariantspecificationlist_node_t* node = (texturevariantspecificationlist_node_t *) list;
DENG_ASSERT(initedOk);
while(node)
{
texturevariantspecificationlist_node_t *next = node->next;
destroyVariantSpecification(node->spec);
node = next;
}
}
static int findTextureUsingVariantSpecificationWorker(de::Texture &tex, void *parameters)
{
texturevariantspecification_t *spec = (texturevariantspecification_t *)parameters;
de::Texture::Variants variants = tex.variantList();
DENG2_FOR_EACH_CONST(de::Texture::Variants, i, variants)
{
if((*i)->spec() == spec)
{
return 1; // Found one; stop.
}
}
return 0; // Continue iteration.
}
static int pruneUnusedVariantSpecificationsInList(variantspecificationlist_t *list)
{
texturevariantspecificationlist_node_t *node = list;
int numPruned = 0;
while(node)
{
texturevariantspecificationlist_node_t *next = node->next;
if(!App_Textures()->iterate(findTextureUsingVariantSpecificationWorker, (void *)node->spec))
{
destroyVariantSpecification(node->spec);
++numPruned;
}
node = next;
}
return numPruned;
}
static int pruneUnusedVariantSpecifications(texturevariantspecificationtype_t specType)
{
DENG_ASSERT(initedOk);
switch(specType)
{
case TST_GENERAL: return pruneUnusedVariantSpecificationsInList(variantSpecs);
case TST_DETAIL: {
int numPruned = 0;
for(int i = 0; i < DETAILVARIANT_CONTRAST_HASHSIZE; ++i)
{
numPruned += pruneUnusedVariantSpecificationsInList(detailVariantSpecs[i]);
}
return numPruned; }
default:
Con_Error("Textures::pruneUnusedVariantSpecifications: Invalid variant spec type %i.", (int) specType);
exit(1); // Unreachable.
}
}
static void destroyVariantSpecifications()
{
DENG_ASSERT(initedOk);
emptyVariantSpecificationList(variantSpecs); variantSpecs = 0;
for(int i = 0; i < DETAILVARIANT_CONTRAST_HASHSIZE; ++i)
{
emptyVariantSpecificationList(detailVariantSpecs[i]); detailVariantSpecs[i] = 0;
}
}
static uploadcontentmethod_t chooseContentUploadMethod(texturecontent_t const *content)
{
// Must the operation be carried out immediately?
if((content->flags & TXCF_NEVER_DEFER) || !BusyMode_Active())
return METHOD_IMMEDIATE;
// We can defer.
return METHOD_DEFERRED;
}
typedef enum {
METHOD_MATCH = 0,
METHOD_FUZZY
} choosevariantmethod_t;
static de::TextureVariant *chooseVariant(choosevariantmethod_t method, de::Texture &tex,
texturevariantspecification_t const *spec)
{
DENG_ASSERT(initedOk && spec);
DENG2_FOR_EACH_CONST(de::Texture::Variants, i, tex.variantList())
{
de::TextureVariant *variant = *i;
texturevariantspecification_t const *cand = variant->spec();
switch(method)
{
case METHOD_MATCH:
if(cand == spec)
{
// This is the one we're looking for.
return variant;
}
break;
case METHOD_FUZZY:
if(GL_CompareTextureVariantSpecifications(cand, spec))
{
// This will do fine.
return variant;
}
break;
}
}
return 0;
}
static int releaseVariantGLTexture(de::TextureVariant *variant, void *parameters = 0)
{
texturevariantspecification_t *spec = (texturevariantspecification_t *)parameters;
if(!spec || spec == variant->spec())
{
if(variant->isUploaded())
{
// Delete and mark it not-loaded.
DGLuint glName = variant->glName();
glDeleteTextures(1, (GLuint const *) &glName);
variant->setGLName(0);
variant->flagUploaded(false);
}
if(spec) return true; // We're done.
}
return 0; // Continue iteration.
}
static void uploadContent(uploadcontentmethod_t uploadMethod, texturecontent_t const *content)
{
DENG_ASSERT(content);
if(METHOD_IMMEDIATE == uploadMethod)
{ // Do this right away. No need to take a copy.
GL_UploadTextureContent(content);
return;
}
GL_DeferTextureUpload(content);
}
static uploadcontentmethod_t uploadContentForVariant(uploadcontentmethod_t uploadMethod,
texturecontent_t const *content, de::TextureVariant *variant)
{
DENG_ASSERT(content && variant);
if(!novideo)
{
uploadContent(uploadMethod, content);
}
variant->flagUploaded(true);
return uploadMethod;
}
static void uploadContentUnmanaged(uploadcontentmethod_t uploadMethod,
texturecontent_t const *content)
{
DENG_ASSERT(content);
LOG_AS("uploadContentUnmanaged");
if(novideo) return;
if(METHOD_IMMEDIATE == uploadMethod)
{
#ifdef _DEBUG
LOG_VERBOSE("Uploading texture (%i:%ix%i) while not busy! Should be precached in busy mode?")
<< content->name << content->width << content->height;
#endif
}
uploadContent(uploadMethod, content);
}
static TexSource loadSourceImage(de::Texture &tex, texturevariantspecification_t const &baseSpec,
image_t &image)
{
variantspecification_t const *spec;
TexSource source = TEXS_NONE;
spec = TS_GENERAL(&baseSpec);
if(!tex.manifest().schemeName().compareWithoutCase("Textures"))
{
// Attempt to load an external replacement for this composite texture?
if(!noHighResTex && (loadExtAlways || highResWithPWAD || !tex.flags().testFlag(de::Texture::Custom)))
{
// First try the textures scheme.
de::Uri uri = tex.manifest().composeUri();
source = loadExternalTexture(image, uri.compose(), "-ck");
}
if(source == TEXS_NONE)
{
if(TC_SKYSPHERE_DIFFUSE != spec->context)
{
source = loadPatchComposite(image, tex);
}
else
{
bool const zeroMask = !!(spec->flags & TSF_ZEROMASK);
bool const useZeroOriginIfOneComponent = true;
source = loadPatchComposite(image, tex, zeroMask, useZeroOriginIfOneComponent);
}
}
}
else if(!tex.manifest().schemeName().compareWithoutCase("Flats"))
{
// Attempt to load an external replacement for this flat?
if(!noHighResTex && (loadExtAlways || highResWithPWAD || !tex.flags().testFlag(de::Texture::Custom)))
{
// First try the flats scheme.
de::Uri uri = tex.manifest().composeUri();
source = loadExternalTexture(image, uri.compose(), "-ck");
if(source == TEXS_NONE)
{
// How about the old-fashioned "flat-name" in the textures scheme?
source = loadExternalTexture(image, "Textures:flat-" + uri.path().toStringRef(), "-ck");
}
}
if(source == TEXS_NONE)
{
de::Uri const &resourceUri = tex.manifest().resourceUri();
if(!resourceUri.scheme().compareWithoutCase("LumpIndex"))
{
try
{
lumpnum_t lumpNum = resourceUri.path().toString().toInt();
de::File1 &lump = App_FileSystem()->nameIndex().lump(lumpNum);
de::FileHandle &hndl = App_FileSystem()->openLump(lump);
source = loadFlat(image, hndl);
App_FileSystem()->releaseFile(hndl.file());
delete &hndl;
}
catch(LumpIndex::NotFoundError const&)
{} // Ignore this error.
}
}
}
else if(!tex.manifest().schemeName().compareWithoutCase("Patches"))
{
int tclass = 0, tmap = 0;
if(spec->flags & TSF_HAS_COLORPALETTE_XLAT)
{
DENG_ASSERT(spec->translated);
tclass = spec->translated->tClass;
tmap = spec->translated->tMap;
}
// Attempt to load an external replacement for this patch?
if(!noHighResTex && (loadExtAlways || highResWithPWAD || !tex.flags().testFlag(de::Texture::Custom)))
{
de::Uri uri = tex.manifest().composeUri();
source = loadExternalTexture(image, uri.compose(), "-ck");
}
if(source == TEXS_NONE)
{
de::Uri const &resourceUri = tex.manifest().resourceUri();
if(!resourceUri.scheme().compareWithoutCase("LumpIndex"))
{
try
{
lumpnum_t lumpNum = resourceUri.path().toString().toInt();
de::File1 &lump = App_FileSystem()->nameIndex().lump(lumpNum);
de::FileHandle &hndl = App_FileSystem()->openLump(lump);
source = loadPatch(image, hndl, tclass, tmap, spec->border);
App_FileSystem()->releaseFile(hndl.file());
delete &hndl;
}
catch(LumpIndex::NotFoundError const&)
{} // Ignore this error.
}
}
}
else if(!tex.manifest().schemeName().compareWithoutCase("Sprites"))
{
int tclass = 0, tmap = 0;
if(spec->flags & TSF_HAS_COLORPALETTE_XLAT)
{
DENG_ASSERT(spec->translated);
tclass = spec->translated->tClass;
tmap = spec->translated->tMap;
}
// Attempt to load an external replacement for this sprite?
if(!noHighResPatches)
{
de::Uri uri = tex.manifest().composeUri();
// Prefer psprite or translated versions if available.
if(TC_PSPRITE_DIFFUSE == spec->context)
{
source = loadExternalTexture(image, "Patches:" + uri.path() + "-hud", "-ck");
}
else if(tclass || tmap)
{
source = loadExternalTexture(image, "Patches:" + uri.path() + String("-table%1%2").arg(tclass).arg(tmap), "-ck");
}
if(!source)
{
source = loadExternalTexture(image, "Patches:" + uri.path(), "-ck");
}
}
if(source == TEXS_NONE)
{
de::Uri const &resourceUri = tex.manifest().resourceUri();
if(!resourceUri.scheme().compareWithoutCase("LumpIndex"))
{
try
{
lumpnum_t lumpNum = resourceUri.path().toString().toInt();
de::File1 &lump = App_FileSystem()->nameIndex().lump(lumpNum);
de::FileHandle &hndl = App_FileSystem()->openLump(lump);
source = loadPatch(image, hndl, tclass, tmap, spec->border);
App_FileSystem()->releaseFile(hndl.file());
delete &hndl;
}
catch(LumpIndex::NotFoundError const&)
{} // Ignore this error.
}
}
}
else if(!tex.manifest().schemeName().compareWithoutCase("Details"))
{
de::Uri const &resourceUri = tex.manifest().resourceUri();
if(resourceUri.scheme().compareWithoutCase("Lumps"))
{
source = loadExternalTexture(image, resourceUri.compose());
}
else
{
lumpnum_t lumpNum = App_FileSystem()->lumpNumForName(resourceUri.path());
try
{
de::File1 &lump = App_FileSystem()->nameIndex().lump(lumpNum);
de::FileHandle &hndl = App_FileSystem()->openLump(lump);
source = loadDetail(image, hndl);
App_FileSystem()->releaseFile(hndl.file());
delete &hndl;
}
catch(LumpIndex::NotFoundError const&)
{} // Ignore this error.
}
}
else
{
de::Uri const &resourceUri = tex.manifest().resourceUri();
source = loadExternalTexture(image, resourceUri.compose());
}
return source;
}
static uploadcontentmethod_t prepareVariantFromImage(de::TextureVariant *tex, image_t *image)
{
DENG_ASSERT(image);
variantspecification_t const *spec = TS_GENERAL(tex->spec());
bool monochrome = (spec->flags & TSF_MONOCHROME) != 0;
bool noCompression = (spec->flags & TSF_NO_COMPRESSION) != 0;
bool scaleSharp = (spec->flags & TSF_UPSCALE_AND_SHARPEN) != 0;
int wrapS = spec->wrapS, wrapT = spec->wrapT;
int magFilter, minFilter, anisoFilter, flags = 0;
boolean noSmartFilter = false;
dgltexformat_t dglFormat;
texturecontent_t c;
float s, t;
if(spec->toAlpha)
{
if(0 != image->paletteId)
{
// Paletted.
uint8_t* newPixels = GL_ConvertBuffer(image->pixels, image->size.width, image->size.height,
((image->flags & IMGF_IS_MASKED)? 2 : 1),
R_ToColorPalette(image->paletteId), 3);
M_Free(image->pixels);
image->pixels = newPixels;
image->pixelSize = 3;
image->paletteId = 0;
image->flags &= ~IMGF_IS_MASKED;
}
Image_ConvertToLuminance(image, false);
long total = image->size.width * image->size.height;
for(long i = 0; i < total; ++i)
{
image->pixels[total + i] = image->pixels[i];
image->pixels[i] = 255;
}
image->pixelSize = 2;
}
else if(0 != image->paletteId)
{
if(fillOutlines && (image->flags & IMGF_IS_MASKED))
ColorOutlinesIdx(image->pixels, image->size.width, image->size.height);
if(monochrome && !scaleSharp)
GL_DeSaturatePalettedImage(image->pixels, R_ToColorPalette(image->paletteId),
image->size.width, image->size.height);
if(scaleSharp)
{
int scaleMethod = GL_ChooseSmartFilter(image->size.width, image->size.height, 0);
bool origMasked = (image->flags & IMGF_IS_MASKED) != 0;
colorpaletteid_t origPaletteId = image->paletteId;
uint8_t* newPixels = GL_ConvertBuffer(image->pixels, image->size.width, image->size.height,
((image->flags & IMGF_IS_MASKED)? 2 : 1),
R_ToColorPalette(image->paletteId), 4);
if(newPixels != image->pixels)
{
M_Free(image->pixels);
image->pixels = newPixels;
image->pixelSize = 4;
image->paletteId = 0;
image->flags &= ~IMGF_IS_MASKED;
}
if(monochrome)
Desaturate(image->pixels, image->size.width, image->size.height, image->pixelSize);
newPixels = GL_SmartFilter(scaleMethod, image->pixels, image->size.width, image->size.height,
0, &image->size.width, &image->size.height);
if(newPixels != image->pixels)
{
M_Free(image->pixels);
image->pixels = newPixels;
}
EnhanceContrast(image->pixels, image->size.width, image->size.height, image->pixelSize);
//SharpenPixels(image->pixels, image->size.width, image->size.height, image->pixelSize);
//BlackOutlines(image->pixels, image->size.width, image->size.height, image->pixelSize);
// Back to paletted+alpha?
if(monochrome)
{
// No. We'll convert from RGB(+A) to Luminance(+A) and upload as is.
// Replace the old buffer.
Image_ConvertToLuminance(image, true);
AmplifyLuma(image->pixels, image->size.width, image->size.height, image->pixelSize == 2);
}
else
{ // Yes. Quantize down from RGA(+A) to Paletted(+A), replacing the old image->
newPixels = GL_ConvertBuffer(image->pixels, image->size.width, image->size.height,
(origMasked? 2 : 1), R_ToColorPalette(origPaletteId), 4);
if(newPixels != image->pixels)
{
M_Free(image->pixels);
image->pixels = newPixels;
image->pixelSize = (origMasked? 2 : 1);
image->paletteId = origPaletteId;
if(origMasked)
image->flags |= IMGF_IS_MASKED;
}
}
// Lets not do this again.
noSmartFilter = true;
}
}
else if(image->pixelSize > 2)
{
if(monochrome)
{
Image_ConvertToLuminance(image, true);
AmplifyLuma(image->pixels, image->size.width, image->size.height, image->pixelSize == 2);
}
}
if(noCompression || (image->size.width < 128 || image->size.height < 128))
flags |= TXCF_NO_COMPRESSION;
if(spec->gammaCorrection) flags |= TXCF_APPLY_GAMMACORRECTION;