/
def_main.cpp
2012 lines (1723 loc) · 65.4 KB
/
def_main.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 def_main.cpp Definition subsystem.
*
* @authors Copyright © 2003-2017 Jaakko Keränen <jaakko.keranen@iki.fi>
* @authors Copyright © 2005-2015 Daniel Swanson <danij@dengine.net>
* @authors Copyright © 2006 Jamie Jones <jamie_jones_au@yahoo.com.au>
*
* @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>
*/
#define DENG_NO_API_MACROS_DEFINITIONS
#include "def_main.h"
#include <cctype>
#include <cstring>
#include <QMap>
#include <QTextStream>
#include <de/findfile.h>
#include <de/c_wrapper.h>
#include <de/App>
#include <de/PackageLoader>
#include <de/ScriptSystem>
#include <de/NativePath>
#include <de/RecordValue>
#include <doomsday/doomsdayapp.h>
#include <doomsday/console/cmd.h>
#include <doomsday/defs/decoration.h>
#include <doomsday/defs/dedfile.h>
#include <doomsday/defs/dedparser.h>
#include <doomsday/defs/material.h>
#include <doomsday/defs/sky.h>
#include <doomsday/defs/state.h>
#include <doomsday/filesys/fs_main.h>
#include <doomsday/filesys/fs_util.h>
#include <doomsday/resource/manifest.h>
#include <doomsday/resource/animgroups.h>
#include <doomsday/res/Bundles>
#include <doomsday/res/DoomsdayPackage>
#include <doomsday/res/Textures>
#include <doomsday/world/Materials>
#include <doomsday/world/MaterialManifest>
#include <doomsday/world/xg.h>
#include "dd_main.h"
#include "dd_def.h"
#include "api_def.h"
#include "api_sound.h"
#include "Generator"
#ifdef __CLIENT__
# include "render/rend_particle.h"
#endif
#include <doomsday/world/detailtexturemateriallayer.h>
#include <doomsday/world/shinetexturemateriallayer.h>
#include <doomsday/world/texturemateriallayer.h>
#ifdef __CLIENT__
# include "resource/lightmaterialdecoration.h"
#endif
using namespace de;
#define LOOPi(n) for (i = 0; i < (n); ++i)
#define LOOPk(n) for (k = 0; k < (n); ++k)
RuntimeDefs runtimeDefs;
static bool defsInited;
static mobjinfo_t *gettingFor;
static inline FS1 &fileSys()
{
return App_FileSystem();
}
void RuntimeDefs::clear()
{
for (dint i = 0; i < sounds.size(); ++i)
{
Str_Free(&sounds[i].external);
}
sounds.clear();
mobjInfo.clear();
states.clear();
texts.clear();
stateInfo.clear();
}
void Def_Init()
{
::runtimeDefs.clear();
DED_Definitions()->clear();
auto &defs = *DED_Definitions();
// Make the definitions visible in the global namespace.
App::app().scriptSystem().addNativeModule("Defs", defs.names);
// Constants for definitions.
DENG2_ADD_NUMBER_CONSTANT(defs.names, SN_SPAWN);
DENG2_ADD_NUMBER_CONSTANT(defs.names, SN_SEE);
DENG2_ADD_NUMBER_CONSTANT(defs.names, SN_PAIN);
DENG2_ADD_NUMBER_CONSTANT(defs.names, SN_MELEE);
DENG2_ADD_NUMBER_CONSTANT(defs.names, SN_MISSILE);
DENG2_ADD_NUMBER_CONSTANT(defs.names, SN_CRASH);
DENG2_ADD_NUMBER_CONSTANT(defs.names, SN_DEATH);
DENG2_ADD_NUMBER_CONSTANT(defs.names, SN_XDEATH);
DENG2_ADD_NUMBER_CONSTANT(defs.names, SN_RAISE);
DENG2_ADD_NUMBER_CONSTANT(defs.names, SDN_ACTIVE);
DENG2_ADD_NUMBER_CONSTANT(defs.names, SDN_ATTACK);
DENG2_ADD_NUMBER_CONSTANT(defs.names, SDN_DEATH);
DENG2_ADD_NUMBER_CONSTANT(defs.names, SDN_PAIN);
DENG2_ADD_NUMBER_CONSTANT(defs.names, SDN_SEE);
}
void Def_Destroy()
{
App::app().scriptSystem().removeNativeModule("Defs");
DED_Definitions()->clear();
// Destroy the databases.
::runtimeDefs.clear();
::defsInited = false;
}
state_t *Def_GetState(dint num)
{
if (num >= 0 && num < DED_Definitions()->states.size())
{
return &::runtimeDefs.states[num];
}
return nullptr; // Not found.
}
sfxinfo_t *Def_GetSoundInfo(dint soundId, dfloat *freq, dfloat *volume)
{
if (soundId <= 0 || soundId >= DED_Definitions()->sounds.size())
return nullptr;
dfloat dummy = 0;
if (!freq) freq = &dummy;
if (!volume) volume = &dummy;
// Traverse all links when getting the definition. (But only up to 10, which is
// certainly enough and prevents endless recursion.) Update the sound id at the
// same time. The links were checked in Def_Read() so there cannot be any bogus
// ones.
sfxinfo_t *info = &::runtimeDefs.sounds[soundId];
for (dint i = 0; info->link && i < 10;
info = info->link,
*freq = (info->linkPitch > 0 ? info->linkPitch / 128.0f : *freq),
*volume += (info->linkVolume != -1 ? info->linkVolume / 127.0f : 0),
soundId = ::runtimeDefs.sounds.indexOf(info),
++i)
{}
DENG2_ASSERT(soundId < DED_Definitions()->sounds.size());
return info;
}
bool Def_SoundIsRepeating(dint soundId)
{
if (sfxinfo_t *info = Def_GetSoundInfo(soundId, nullptr, nullptr))
{
return (info->flags & SF_REPEAT) != 0;
}
return false;
}
ded_compositefont_t *Def_GetCompositeFont(char const *uri)
{
return DED_Definitions()->getCompositeFont(uri);
}
/// @todo $revise-texture-animation
static ded_reflection_t *tryFindReflection(de::Uri const &uri, /* bool hasExternal,*/ bool isCustom)
{
for (dint i = DED_Definitions()->reflections.size() - 1; i >= 0; i--)
{
ded_reflection_t &def = DED_Definitions()->reflections[i];
if (!def.material || *def.material != uri) continue;
/*
if (hasExternal)
{
if (!(def.flags & REFF_EXTERNAL)) continue;
}
else */
if (!isCustom)
{
if (def.flags & REFF_NO_IWAD) continue;
}
else
{
if (!(def.flags & REFF_PWAD)) continue;
}
return &def;
}
return nullptr; // Not found.
}
/// @todo $revise-texture-animation
static ded_detailtexture_t *tryFindDetailTexture(de::Uri const &uri, /*bool hasExternal,*/ bool isCustom)
{
for (dint i = DED_Definitions()->details.size() - 1; i >= 0; i--)
{
ded_detailtexture_t &def = DED_Definitions()->details[i];
for (dint k = 0; k < 2; ++k)
{
de::Uri const *matUri = (k == 0 ? def.material1 : def.material2);
if (!matUri || *matUri != uri) continue;
/*if (hasExternal)
{
if (!(def.flags & DTLF_EXTERNAL)) continue;
}
else*/
if (!isCustom)
{
if (def.flags & DTLF_NO_IWAD) continue;
}
else
{
if (!(def.flags & DTLF_PWAD)) continue;
}
return &def;
}
}
return nullptr; // Not found.
}
ded_ptcgen_t *Def_GetGenerator(de::Uri const &uri)
{
if (uri.isEmpty()) return nullptr;
for (dint i = 0; i < DED_Definitions()->ptcGens.size(); ++i)
{
ded_ptcgen_t *def = &DED_Definitions()->ptcGens[i];
if (!def->material) continue;
// Is this suitable?
if (*def->material == uri)
return def;
#if 0 /// @todo $revise-texture-animation
if (def->flags & PGF_GROUP)
{
// Generator triggered by all materials in the (animation) group.
// A search is necessary only if we know both the used material and
// the specified material in this definition are in *a* group.
if (Material_IsGroupAnimated(defMat) && Material_IsGroupAnimated(mat) &&
&Material_AnimGroup(defMat) == &Material_AnimGroup(mat))
{
// Both are in this group! This def will do.
return def;
}
}
#endif
}
return nullptr; // None found.
}
ded_ptcgen_t *Def_GetGenerator(uri_s const *uri)
{
if (!uri) return nullptr;
return Def_GetGenerator(reinterpret_cast<de::Uri const &>(*uri));
}
ded_ptcgen_t *Def_GetDamageGenerator(int mobjType)
{
// Search for a suitable definition.
for (dint i = 0; i < DED_Definitions()->ptcGens.size(); ++i)
{
ded_ptcgen_t *def = &DED_Definitions()->ptcGens[i];
// It must be for this type of mobj.
if (def->damageNum == mobjType)
return def;
}
return nullptr;
}
/**
* The following escape sequences are un-escaped:
* <pre>
* \\n Newline
* \\r Carriage return
* \\t Tab
* \\\_ Space
* \\s Space
* </pre>
*/
static void Def_InitTextDef(ddtext_t *txt, char const *str)
{
DENG2_ASSERT(txt);
// Handle null pointers with "".
if (!str) str = "";
txt->text = (char *) M_Calloc(qstrlen(str) + 1);
char const *in = str;
char *out = txt->text;
for (; *in; out++, in++)
{
if (*in == '\\')
{
in++;
if (*in == 'n') *out = '\n'; // Newline.
else if (*in == 'r') *out = '\r'; // Carriage return.
else if (*in == 't') *out = '\t'; // Tab.
else if (*in == '_'
|| *in == 's') *out = ' '; // Space.
else
{
*out = *in;
}
}
else
{
*out = *in;
}
}
// Adjust buffer to fix exactly.
txt->text = (char *) M_Realloc(txt->text, qstrlen(txt->text) + 1);
}
/**
* Prints a count with a 2-space indentation.
*/
static String defCountMsg(dint count, String const &label)
{
if (!::verbose && !count)
return ""; // Don't print zeros if not verbose.
return String(_E(Ta) " %1 " _E(Tb) "%2\n").arg(count).arg(label);
}
/**
* Read all DD_DEFNS lumps in the primary lump index.
*/
static void Def_ReadLumpDefs()
{
LOG_AS("Def_ReadLumpDefs");
LumpIndex const &lumpIndex = fileSys().nameIndex();
LumpIndex::FoundIndices foundDefns;
lumpIndex.findAll("DD_DEFNS.lmp", foundDefns);
DENG2_FOR_EACH_CONST(LumpIndex::FoundIndices, i, foundDefns)
{
if (!DED_ReadLump(DED_Definitions(), *i))
{
QByteArray path = NativePath(lumpIndex[*i].container().composePath()).pretty().toUtf8();
App_Error("Def_ReadLumpDefs: Parse error reading \"%s:DD_DEFNS\".\n", path.constData());
}
}
dint const numProcessedLumps = foundDefns.size();
if (::verbose && numProcessedLumps > 0)
{
LOG_RES_NOTE("Processed %i %s")
<< numProcessedLumps << (numProcessedLumps != 1 ? "lumps" : "lump");
}
}
/**
* Uses gettingFor. Initializes the state-owners information.
*/
dint Def_StateForMobj(String const &state)
{
dint num = DED_Definitions()->getStateNum(state);
if (num < 0) num = 0;
// State zero is the NULL state.
if (num > 0)
{
::runtimeDefs.stateInfo[num].owner = ::gettingFor;
// Scan forward at most 'count' states, or until we hit a state with
// an owner, or the NULL state.
dint st, count = 16;
for (st = ::runtimeDefs.states[num].nextState;
st > 0 && count-- && !::runtimeDefs.stateInfo[st].owner;
st = ::runtimeDefs.states[st].nextState)
{
::runtimeDefs.stateInfo[st].owner = ::gettingFor;
}
}
return num;
}
static void readDefinitionFile(String path)
{
if (path.isEmpty()) return;
LOG_RES_VERBOSE("Reading \"%s\"") << NativePath(path).pretty();
Def_ReadProcessDED(DED_Definitions(), path);
}
#if 0
/**
* Attempt to prepend the current work path. If @a src is already absolute do nothing.
*
* @param dst Absolute path written here.
* @param src Original path.
*/
static void prependWorkPath(ddstring_t *dst, ddstring_t const *src)
{
DENG2_ASSERT(dst && src);
if (!F_IsAbsolute(src))
{
NativePath prepended = NativePath::workPath() / Str_Text(src);
//char *curPath = Dir_CurrentPath();
//Str_Prepend(dst, curPath.);
//Dir_CleanPathStr(dst);
//M_Free(curPath);
return;
}
// Do we need to copy anyway?
if (dst != src)
{
Str_Set(dst, Str_Text(src));
}
}
#endif
/**
* Returns a URN list (in load order) for all lumps whose name matches the pattern "MAPINFO.lmp".
*/
static QStringList allMapInfoUrns()
{
QStringList foundPaths;
// The game's main MAPINFO definitions should be processed first.
bool ignoreNonCustom = false;
try
{
String mainMapInfo = fileSys().findPath(de::Uri(App_CurrentGame().mainMapInfo()), RLF_MATCH_EXTENSION);
if (!mainMapInfo.isEmpty())
{
foundPaths << mainMapInfo;
ignoreNonCustom = true;
}
}
catch (FS1::NotFoundError const &)
{} // Ignore this error.
// Process all other lumps named MAPINFO.lmp
LumpIndex const &lumpIndex = fileSys().nameIndex();
LumpIndex::FoundIndices foundLumps;
lumpIndex.findAll("MAPINFO.lmp", foundLumps);
for (auto const &lumpNumber : foundLumps)
{
// Ignore MAPINFO definition data in IWADs?
if (ignoreNonCustom)
{
File1 const &file = lumpIndex[lumpNumber];
/// @todo Custom status for contained files is not inherited from the container?
if (file.isContained())
{
if (!file.container().hasCustom())
continue;
}
else if (!file.hasCustom())
continue;
}
foundPaths << String("LumpIndex:%1").arg(lumpNumber);
}
return foundPaths;
}
/**
* @param mapInfoUrns MAPINFO definitions to translate, in load order.
*/
static void translateMapInfos(QStringList const &mapInfoUrns, String &xlat, String &xlatCustom)
{
xlat.clear();
xlatCustom.clear();
String delimitedPaths = mapInfoUrns.join(";");
if (delimitedPaths.isEmpty()) return;
ddhook_mapinfo_convert_t parm;
Str_InitStd(&parm.paths);
Str_InitStd(&parm.translated);
Str_InitStd(&parm.translatedCustom);
try
{
Str_Set(&parm.paths, delimitedPaths.toUtf8().constData());
if (DoomsdayApp::plugins().callAllHooks(HOOK_MAPINFO_CONVERT, 0, &parm))
{
xlat = Str_Text(&parm.translated);
xlatCustom = Str_Text(&parm.translatedCustom);
}
}
catch (...)
{}
Str_Free(&parm.translatedCustom);
Str_Free(&parm.translated);
Str_Free(&parm.paths);
}
static void readAllDefinitions()
{
Time begunAt;
// Start with engine's own top-level definition file.
readDefinitionFile(App::packageLoader().package("net.dengine.base").root()
.locate<File const>("defs/doomsday.ded").path());
if (App_GameLoaded())
{
Game const &game = App_CurrentGame();
// Some games use definitions (MAPINFO lumps) that are translated to DED.
QStringList mapInfoUrns = allMapInfoUrns();
if (!mapInfoUrns.isEmpty())
{
String xlat, xlatCustom;
translateMapInfos(mapInfoUrns, xlat, xlatCustom);
if (!xlat.isEmpty())
{
LOGDEV_MAP_VERBOSE("Non-custom translated MAPINFO definitions:\n") << xlat;
if (!DED_ReadData(DED_Definitions(), xlat.toUtf8().constData(),
"[TranslatedMapInfos]", false /*not custom*/))
{
App_Error("readAllDefinitions: DED parse error:\n%s", DED_Error());
}
}
if (!xlatCustom.isEmpty())
{
LOGDEV_MAP_VERBOSE("Custom translated MAPINFO definitions:\n") << xlatCustom;
if (!DED_ReadData(DED_Definitions(), xlatCustom.toUtf8().constData(),
"[TranslatedMapInfos]", true /*custom*/))
{
App_Error("readAllDefinitions: DED parse error:\n%s", DED_Error());
}
}
}
// Now any startup definition files required by the game.
Game::Manifests const &gameResources = game.manifests();
dint packageIdx = 0;
for (Game::Manifests::const_iterator i = gameResources.find(RC_DEFINITION);
i != gameResources.end() && i.key() == RC_DEFINITION; ++i, ++packageIdx)
{
ResourceManifest &record = **i;
/// Try to locate this resource now.
String const &path = record.resolvedPath(true/*try to locate*/);
if (path.isEmpty())
{
QByteArray names = record.names().join(";").toUtf8();
App_Error("readAllDefinitions: Error, failed to locate required game definition \"%s\".", names.constData());
}
readDefinitionFile(path);
}
// Next are definition files in the games' /auto directory.
if (!CommandLine_Exists("-noauto"))
{
FS1::PathList foundPaths;
if (fileSys().findAllPaths(de::makeUri("$(App.DefsPath)/$(GamePlugin.Name)/auto/*.ded").resolved(), 0, foundPaths))
{
for (FS1::PathListItem const &found : foundPaths)
{
// Ignore directories.
if (found.attrib & A_SUBDIR) continue;
readDefinitionFile(found.path);
}
}
}
}
// Definitions from loaded data bundles.
for (DataBundle const *bundle : DataBundle::loadedBundles())
{
if (bundle->format() == DataBundle::Ded)
{
String const bundleRoot = bundle->rootPath();
for (Value const *path : bundle->packageMetadata().geta("dataFiles").elements())
{
readDefinitionFile(bundleRoot / path->asText());
}
}
}
// Definitions from loaded packages.
for (Package *pkg : App::packageLoader().loadedPackagesInOrder())
{
res::DoomsdayPackage ddPkg(*pkg);
if (ddPkg.hasDefinitions())
{
// Relative to package root.
Folder const &defsFolder = pkg->root().locate<Folder const>(ddPkg.defsPath());
// Read all the DED files found in this folder, in alphabetical order.
// Subfolders are not checked -- the DED files need to manually `Include`
// any files from subfolders.
defsFolder.forContents([] (String name, File &file)
{
if (!name.fileNameExtension().compareWithoutCase(".ded"))
{
readDefinitionFile(file.path());
}
return LoopContinue;
});
}
}
// Last are DD_DEFNS definition lumps from loaded add-ons.
/// @todo Shouldn't these be processed before definitions on the command line?
Def_ReadLumpDefs();
LOG_RES_VERBOSE("readAllDefinitions: Completed in %.2f seconds") << begunAt.since();
}
static void defineFlaremap(de::Uri const &resourceUri)
{
if (resourceUri.isEmpty()) return;
// Reference to none?
if (!resourceUri.path().toStringRef().compareWithoutCase("-")) return;
// Reference to a "built-in" flaremap?
String const &resourcePathStr = resourceUri.path().toStringRef();
if (resourcePathStr.length() == 1 &&
resourcePathStr.first() >= '0' && resourcePathStr.first() <= '4')
return;
res::Textures::get().defineTexture("Flaremaps", resourceUri);
}
static void defineLightmap(de::Uri const &resourceUri)
{
if (resourceUri.isEmpty()) return;
// Reference to none?
if (!resourceUri.path().toStringRef().compareWithoutCase("-")) return;
res::Textures::get().defineTexture("Lightmaps", resourceUri);
}
static void generateMaterialDefForTexture(res::TextureManifest const &manifest)
{
LOG_AS("generateMaterialDefForTexture");
Record &mat = DED_Definitions()->materials[DED_Definitions()->addMaterial()];
mat.set("autoGenerated", true);
de::Uri const texUri = manifest.composeUri();
mat.set("id", de::Uri(DD_MaterialSchemeNameForTextureScheme(texUri.scheme()), texUri.path()).compose());
if (manifest.hasTexture())
{
res::Texture &tex = manifest.texture();
mat.set("dimensions", new ArrayValue(tex.dimensions()));
mat.set("flags", dint(tex.isFlagged(res::Texture::NoDraw) ? MATF_NO_DRAW : 0));
}
else
{
LOGDEV_RES_MSG("Texture \"%s\" not yet defined, resultant Material will inherit dimensions") << texUri;
}
// The first layer and stage is implicit.
defn::Material matDef(mat);
defn::MaterialLayer layerDef(matDef.addLayer());
Record &st0 = layerDef.addStage();
st0.set("texture", texUri.compose());
// Is there an animation for this?
res::AnimGroup const *anim = res::AnimGroups::get().animGroupForTexture(manifest);
if (anim && anim->frameCount() > 1)
{
// Determine the start frame.
dint startFrame = 0;
while (&anim->frame(startFrame).textureManifest() != &manifest)
{
startFrame++;
}
// Just animate the first in the sequence?
if (startFrame && (anim->flags() & AGF_FIRST_ONLY))
return;
// Complete configuration of the first stage.
res::AnimGroupFrame const &animFrame0 = anim->frame(startFrame);
st0.set("tics", dint( animFrame0.tics() + animFrame0.randomTics()) );
if (animFrame0.randomTics())
{
st0.set("variance", animFrame0.randomTics() / st0.getf("tics"));
}
// Add further stages according to the animation group.
startFrame++;
for (dint i = 0; i < anim->frameCount() - 1; ++i)
{
res::AnimGroupFrame const &animFrame = anim->frame(de::wrap(startFrame + i, 0, anim->frameCount()));
res::TextureManifest const &frameManifest = animFrame.textureManifest();
Record &st = layerDef.addStage();
st.set("texture", frameManifest.composeUrn().compose());
st.set("tics", dint( animFrame.tics() + animFrame.randomTics() ));
if (animFrame.randomTics())
{
st.set("variance", animFrame.randomTics() / st.getf("tics"));
}
}
}
}
static void generateMaterialDefsForAllTexturesInScheme(res::TextureScheme &scheme)
{
PathTreeIterator<res::TextureScheme::Index> iter(scheme.index().leafNodes());
while (iter.hasNext()) generateMaterialDefForTexture(iter.next());
}
static inline void generateMaterialDefsForAllTexturesInScheme(String const &schemeName)
{
generateMaterialDefsForAllTexturesInScheme(res::Textures::get().textureScheme(schemeName));
}
static void generateMaterialDefs()
{
generateMaterialDefsForAllTexturesInScheme("Textures");
generateMaterialDefsForAllTexturesInScheme("Flats");
generateMaterialDefsForAllTexturesInScheme("Sprites");
}
#ifdef __CLIENT__
/**
* Returns @c true iff @a decorDef is compatible with the specified context.
*/
static bool decorationIsCompatible(Record const &decorDef, de::Uri const &textureUri,
bool materialIsCustom)
{
if (de::makeUri(decorDef.gets("texture")) != textureUri)
return false;
if (materialIsCustom)
{
return (decorDef.geti("flags") & DCRF_PWAD) != 0;
}
return (decorDef.geti("flags") & DCRF_NO_IWAD) == 0;
}
/**
* (Re)Decorate the given @a material according to definition @a def. Any existing
* decorations will be cleared in the process.
*
* @param material The material being (re)decorated.
* @param def Definition to apply.
*/
static void redecorateMaterial(ClientMaterial &material, Record const &def)
{
defn::Material matDef(def);
material.clearAllDecorations();
// Prefer decorations defined within the material.
for (dint i = 0; i < matDef.decorationCount(); ++i)
{
defn::MaterialDecoration decorDef(matDef.decoration(i));
for (dint k = 0; k < decorDef.stageCount(); ++k)
{
Record const &st = decorDef.stage(k);
defineLightmap(de::makeUri(st.gets("lightmapUp")));
defineLightmap(de::makeUri(st.gets("lightmapDown")));
defineLightmap(de::makeUri(st.gets("lightmapSide")));
defineFlaremap(de::makeUri(st.gets("haloTexture")));
}
material.addDecoration(LightMaterialDecoration::fromDef(decorDef.def()));
}
if (material.hasDecorations())
return;
// Perhaps old style linked decoration definitions?
if (material.layerCount())
{
// The animation configuration of layer0 determines decoration animation.
auto const &decorationsByTexture = DED_Definitions()->decorations.lookup("texture").elements();
auto const &layer0 = material.layer(0).as<world::TextureMaterialLayer>();
bool haveDecorations = false;
QVector<Record const *> stageDecorations(layer0.stageCount());
for (dint i = 0; i < layer0.stageCount(); ++i)
{
world::TextureMaterialLayer::AnimationStage const &stage = layer0.stage(i);
try
{
res::TextureManifest &texManifest = res::Textures::get().textureManifest(stage.texture);
de::Uri const texUri = texManifest.composeUri();
for (auto const &pair : decorationsByTexture)
{
Record const &rec = *pair.second->as<RecordValue>().record();
if (decorationIsCompatible(rec, texUri, material.manifest().isCustom()))
{
stageDecorations[i] = &rec;
haveDecorations = true;
break;
}
}
}
catch (Resources::MissingResourceManifestError const &)
{} // Ignore this error
}
if (!haveDecorations) return;
for (dint i = 0; i < layer0.stageCount(); ++i)
{
if (!stageDecorations[i]) continue;
defn::Decoration mainDef(*stageDecorations[i]);
for (dint k = 0; k < mainDef.lightCount(); ++k)
{
defn::MaterialDecoration decorDef(mainDef.light(k));
DENG2_ASSERT(decorDef.stageCount() == 1); // sanity check.
std::unique_ptr<LightMaterialDecoration> decor(
new LightMaterialDecoration(Vector2i(decorDef.geta("patternSkip")),
Vector2i(decorDef.geta("patternOffset")),
false /*don't use interpolation*/));
std::unique_ptr<LightMaterialDecoration::AnimationStage> definedDecorStage(
LightMaterialDecoration::AnimationStage::fromDef(decorDef.stage(0)));
definedDecorStage->tics = layer0.stage(i).tics;
for (dint m = 0; m < i; ++m)
{
LightMaterialDecoration::AnimationStage preStage(*definedDecorStage);
preStage.tics = layer0.stage(m).tics;
preStage.color = Vector3f();
decor->addStage(preStage); // makes a copy.
}
decor->addStage(*definedDecorStage);
for (dint m = i + 1; m < layer0.stageCount(); ++m)
{
LightMaterialDecoration::AnimationStage postStage(*definedDecorStage);
postStage.tics = layer0.stage(m).tics;
postStage.color = Vector3f();
decor->addStage(postStage);
}
material.addDecoration(decor.release()); // takes ownership.
}
}
}
}
#endif // __CLIENT__
static ded_group_t *findGroupForMaterialLayerAnimation(de::Uri const &uri)
{
if (uri.isEmpty()) return nullptr;
// Reverse iteration (later defs override earlier ones).
for (dint i = DED_Definitions()->groups.size(); i--> 0; )
{
ded_group_t &grp = DED_Definitions()->groups[i];
// We aren't interested in precache groups.
if (grp.flags & AGF_PRECACHE) continue;
// Or empty/single-frame groups.
if (grp.members.size() < 2) continue;
// The referenced material must be a member.
if (!grp.tryFindFirstMemberWithMaterial(uri)) continue;
// Only consider groups where each frame has a valid duration.
dint k;
for (k = 0; k < grp.members.size(); ++k)
{
if (grp.members[k].tics < 0) break;
}
if (k < grp.members.size()) continue;
// Found a suitable Group.
return &grp;
}
return nullptr; // Not found.
}
static void configureMaterial(world::Material &mat, Record const &definition)
{
defn::Material matDef(definition);
de::Uri const materialUri(matDef.gets("id"), RC_NULL);
// Reconfigure basic properties.
mat.setDimensions(Vector2ui(matDef.geta("dimensions")));
mat.markDontDraw((matDef.geti("flags") & MATF_NO_DRAW) != 0);
mat.markSkyMasked((matDef.geti("flags") & MATF_SKYMASK) != 0);
#ifdef __CLIENT__
static_cast<ClientMaterial &>(mat).setAudioEnvironment(S_AudioEnvironmentId(&materialUri));
#endif
// Reconfigure the layers.
mat.clearAllLayers();
for (dint i = 0; i < matDef.layerCount(); ++i)
{
mat.addLayerAt(world::TextureMaterialLayer::fromDef(matDef.layer(i)), mat.layerCount());
}
if (mat.layerCount() && mat.layer(0).stageCount())
{
auto &layer0 = mat.layer(0).as<world::TextureMaterialLayer>();
world::TextureMaterialLayer::AnimationStage &stage0 = layer0.stage(0);
if (!stage0.texture.isEmpty())
{
// We may need to interpret the layer animation from the now
// deprecated Group definitions.
if (matDef.getb(QStringLiteral("autoGenerated")) && layer0.stageCount() == 1)
{
de::Uri const &textureUri = stage0.texture;
// Possibly; see if there is a compatible definition with
// a member named similarly to the texture for layer #0.
if (ded_group_t const *grp = findGroupForMaterialLayerAnimation(textureUri))
{
// Determine the start frame.
dint startFrame = 0;
while (!grp->members[startFrame].material ||
*grp->members[startFrame].material != textureUri)
{
startFrame++;
}
// Configure the first stage.
ded_group_member_t const &gm0 = grp->members[startFrame];
stage0.tics = gm0.tics;
stage0.variance = de::max(gm0.randomTics, 0) / dfloat( gm0.tics );
// Add further stages for each frame in the group.
startFrame++;
for (dint i = 0; i < grp->members.size() - 1; ++i)
{
dint const frame = de::wrap(startFrame + i, 0, grp->members.size());
ded_group_member_t const &gm = grp->members[frame];
if (gm.material)
{
dint const tics = gm.tics;
dfloat const variance = de::max(gm.randomTics, 0) / dfloat( gm.tics );
layer0.addStage(world::TextureMaterialLayer::AnimationStage(*gm.material, tics, variance));
}
}
}
}