]> git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/common/mapinfo.qc
Store map flags as well when parsing .arena files
[xonotic/xonotic-data.pk3dir.git] / qcsrc / common / mapinfo.qc
1 #include "mapinfo.qh"
2 #if defined(CSQC)
3     #include "../client/defs.qh"
4     #include "util.qh"
5     #include <common/weapons/_all.qh>
6 #elif defined(MENUQC)
7 #elif defined(SVQC)
8     #include "util.qh"
9     #include <common/monsters/_mod.qh>
10 #endif
11
12 bool autocvar_g_mapinfo_arena_compat = true;
13 bool autocvar_g_mapinfo_arena_generate = false;
14
15 #ifdef MENUQC
16 #define WARN_COND false
17 #else
18 bool autocvar_g_mapinfo_ignore_warnings;
19 #define WARN_COND (!autocvar_g_mapinfo_ignore_warnings && MapInfo_Map_bspname == mi_shortname)
20 #endif
21
22 // generic string stuff
23
24 int _MapInfo_Cache_Active;
25 int _MapInfo_Cache_DB_NameToIndex;
26 int _MapInfo_Cache_Buf_IndexToMapData;
27
28 void MapInfo_Cache_Destroy()
29 {
30         if(!_MapInfo_Cache_Active)
31                 return;
32
33         db_close(_MapInfo_Cache_DB_NameToIndex);
34         buf_del(_MapInfo_Cache_Buf_IndexToMapData);
35         _MapInfo_Cache_Active = 0;
36 }
37
38 void MapInfo_Cache_Create()
39 {
40         MapInfo_Cache_Destroy();
41         _MapInfo_Cache_DB_NameToIndex = db_create();
42         _MapInfo_Cache_Buf_IndexToMapData = buf_create();
43         _MapInfo_Cache_Active = 1;
44 }
45
46 void MapInfo_Cache_Invalidate()
47 {
48         if(!_MapInfo_Cache_Active)
49                 return;
50
51         MapInfo_Cache_Create();
52 }
53
54 void MapInfo_Cache_Store()
55 {
56         float i;
57         string s;
58         if(!_MapInfo_Cache_Active)
59                 return;
60
61         s = db_get(_MapInfo_Cache_DB_NameToIndex, MapInfo_Map_bspname);
62         if(s == "")
63         {
64                 i = buf_getsize(_MapInfo_Cache_Buf_IndexToMapData);
65                 db_put(_MapInfo_Cache_DB_NameToIndex, MapInfo_Map_bspname, ftos(i));
66         }
67         else
68                 i = stof(s);
69
70         // now store all the stuff
71         bufstr_set(_MapInfo_Cache_Buf_IndexToMapData,   i, MapInfo_Map_bspname);
72         bufstr_set(_MapInfo_Cache_Buf_IndexToMapData, ++i, MapInfo_Map_title);
73         bufstr_set(_MapInfo_Cache_Buf_IndexToMapData, ++i, MapInfo_Map_titlestring);
74         bufstr_set(_MapInfo_Cache_Buf_IndexToMapData, ++i, MapInfo_Map_description);
75         bufstr_set(_MapInfo_Cache_Buf_IndexToMapData, ++i, MapInfo_Map_author);
76         bufstr_set(_MapInfo_Cache_Buf_IndexToMapData, ++i, ftos(MapInfo_Map_supportedGametypes));
77         bufstr_set(_MapInfo_Cache_Buf_IndexToMapData, ++i, ftos(MapInfo_Map_supportedFeatures));
78         bufstr_set(_MapInfo_Cache_Buf_IndexToMapData, ++i, ftos(MapInfo_Map_flags));
79 }
80
81 float MapInfo_Cache_Retrieve(string map)
82 {
83         float i;
84         string s;
85         if(!_MapInfo_Cache_Active)
86                 return 0;
87
88         s = db_get(_MapInfo_Cache_DB_NameToIndex, map);
89         if(s == "")
90                 return 0;
91         i = stof(s);
92
93         // now retrieve all the stuff
94         MapInfo_Map_bspname = bufstr_get(_MapInfo_Cache_Buf_IndexToMapData, i);
95         MapInfo_Map_title = bufstr_get(_MapInfo_Cache_Buf_IndexToMapData, ++i);
96         MapInfo_Map_titlestring = bufstr_get(_MapInfo_Cache_Buf_IndexToMapData, ++i);
97         MapInfo_Map_description = bufstr_get(_MapInfo_Cache_Buf_IndexToMapData, ++i);
98         MapInfo_Map_author = bufstr_get(_MapInfo_Cache_Buf_IndexToMapData, ++i);
99         MapInfo_Map_supportedGametypes = stof(bufstr_get(_MapInfo_Cache_Buf_IndexToMapData, ++i));
100         MapInfo_Map_supportedFeatures = stof(bufstr_get(_MapInfo_Cache_Buf_IndexToMapData, ++i));
101         MapInfo_Map_flags = stof(bufstr_get(_MapInfo_Cache_Buf_IndexToMapData, ++i));
102
103         return 1;
104 }
105
106 // GLOB HANDLING (for all BSP files)
107 float _MapInfo_globopen;
108 float _MapInfo_globcount;
109 float _MapInfo_globhandle;
110 string _MapInfo_GlobItem(float i)
111 {
112         string s;
113         if(!_MapInfo_globopen)
114                 return string_null;
115         s = search_getfilename(_MapInfo_globhandle, i);
116         return substring(s, 5, strlen(s) - 9); // without maps/ and .bsp
117 }
118
119 void MapInfo_Enumerate()
120 {
121         if(_MapInfo_globopen)
122         {
123                 search_end(_MapInfo_globhandle);
124                 _MapInfo_globopen = 0;
125         }
126         MapInfo_Cache_Invalidate();
127         _MapInfo_globhandle = search_begin("maps/*.bsp", true, true);
128         if(_MapInfo_globhandle >= 0)
129         {
130                 _MapInfo_globcount = search_getsize(_MapInfo_globhandle);
131                 _MapInfo_globopen = 1;
132         }
133         else
134                 _MapInfo_globcount = 0;
135 }
136
137 // filter the info by game type mask (updates MapInfo_count)
138 //
139 float _MapInfo_filtered;
140 float _MapInfo_filtered_allocated;
141 float MapInfo_FilterList_Lookup(float i)
142 {
143         return stof(bufstr_get(_MapInfo_filtered, i));
144 }
145
146 void _MapInfo_FilterList_swap(float i, float j, entity pass)
147 {
148         string h;
149         h = bufstr_get(_MapInfo_filtered, i);
150         bufstr_set(_MapInfo_filtered, i, bufstr_get(_MapInfo_filtered, j));
151         bufstr_set(_MapInfo_filtered, j, h);
152 }
153
154 float _MapInfo_FilterList_cmp(float i, float j, entity pass)
155 {
156         string a, b;
157         a = _MapInfo_GlobItem(stof(bufstr_get(_MapInfo_filtered, i)));
158         b = _MapInfo_GlobItem(stof(bufstr_get(_MapInfo_filtered, j)));
159         return strcasecmp(a, b);
160 }
161
162 float MapInfo_FilterGametype(Gametype pGametype, int pFeatures, int pFlagsRequired, int pFlagsForbidden, bool pAbortOnGenerate)
163 {
164         return _MapInfo_FilterGametype(pGametype.m_flags, pFeatures, pFlagsRequired, pFlagsForbidden, pAbortOnGenerate);
165 }
166 float _MapInfo_FilterGametype(int pGametype, int pFeatures, int pFlagsRequired, int pFlagsForbidden, bool pAbortOnGenerate)
167 {
168         float i, j;
169         if (!_MapInfo_filtered_allocated)
170         {
171                 _MapInfo_filtered_allocated = 1;
172                 _MapInfo_filtered = buf_create();
173         }
174         MapInfo_count = 0;
175         for(i = 0, j = -1; i < _MapInfo_globcount; ++i)
176         {
177                 if(MapInfo_Get_ByName(_MapInfo_GlobItem(i), 1, NULL) == 2) // if we generated one... BAIL OUT and let the caller continue in the next frame.
178                         if(pAbortOnGenerate)
179                         {
180                                 LOG_TRACE("Autogenerated a .mapinfo, doing the rest later.");
181                                 MapInfo_progress = i / _MapInfo_globcount;
182                                 return 0;
183                         }
184                 if((MapInfo_Map_supportedGametypes & pGametype) != 0)
185                 if((MapInfo_Map_supportedFeatures & pFeatures) == pFeatures)
186                 if((MapInfo_Map_flags & pFlagsForbidden) == 0)
187                 if((MapInfo_Map_flags & pFlagsRequired) == pFlagsRequired)
188                         bufstr_set(_MapInfo_filtered, ++j, ftos(i));
189         }
190         MapInfo_count = j + 1;
191         MapInfo_ClearTemps();
192
193         // sometimes the glob isn't sorted nicely, so fix it here...
194         heapsort(MapInfo_count, _MapInfo_FilterList_swap, _MapInfo_FilterList_cmp, NULL);
195
196         return 1;
197 }
198 void MapInfo_FilterString(string sf)
199 {
200         // this function further filters _MapInfo_filtered, which is prepared by MapInfo_FilterGametype by string
201         float i, j;
202         string title;
203
204         for(i = 0, j = -1; i < MapInfo_count; ++i)
205         {
206                 if (MapInfo_Get_ByID(i))
207                 {
208                         // prepare for keyword filter
209                         if (MapInfo_Map_title && strstrofs(MapInfo_Map_title, "<TITLE>", 0) == -1)
210                                 title = MapInfo_Map_title;
211                         else
212                                 title = MapInfo_Map_bspname;
213                         // keyword filter
214                         if((strstrofs(strtolower(title), strtolower(sf), 0)) >= 0)
215                                 bufstr_set(_MapInfo_filtered, ++j, bufstr_get(_MapInfo_filtered, i));
216                 }
217         }
218         MapInfo_count = j + 1;
219         MapInfo_ClearTemps();
220
221         // sometimes the glob isn't sorted nicely, so fix it here...
222         heapsort(MapInfo_count, _MapInfo_FilterList_swap, _MapInfo_FilterList_cmp, NULL);
223 }
224
225 void MapInfo_Filter_Free()
226 {
227         if(_MapInfo_filtered_allocated)
228         {
229                 buf_del(_MapInfo_filtered);
230                 _MapInfo_filtered_allocated = 0;
231         }
232 }
233
234 // load info about the i-th map into the MapInfo_Map_* globals
235 string MapInfo_BSPName_ByID(float i)
236 {
237         return _MapInfo_GlobItem(MapInfo_FilterList_Lookup(i));
238 }
239
240 string unquote(string s)
241 {
242         float l = strlen(s);
243         for(float i = 0; i < l; ++i)
244         {
245                 string ch = substring(s, i, 1);
246                 if((ch != " ") && (ch != "\""))
247                 {
248                         for(float j = l - i - 1; j > 0; --j)
249                         {
250                                 ch = substring(s, i+j, 1);
251                                 if(ch != " ") if(ch != "\"")
252                                         return substring(s, i, j+1);
253                         }
254                         return substring(s, i, 1);
255                 }
256         }
257         return "";
258 }
259
260 float MapInfo_Get_ByID(float i)
261 {
262         if(MapInfo_Get_ByName(MapInfo_BSPName_ByID(i), 0, NULL))
263                 return 1;
264         return 0;
265 }
266
267 string _MapInfo_Map_worldspawn_music;
268
269 float _MapInfo_Generate(string pFilename) // 0: failure, 1: ok ent, 2: ok bsp
270 {
271         string fn;
272         float fh;
273         string s, k, v;
274         vector o;
275         float i;
276         float inWorldspawn;
277         float r;
278         float diameter, spawnpoints;
279         float spawnplaces;
280
281         vector mapMins, mapMaxs;
282
283         r = 1;
284         fn = strcat("maps/", pFilename, ".ent");
285         fh = fopen(fn, FILE_READ);
286         if(fh < 0)
287         {
288                 r = 2;
289                 fn = strcat("maps/", pFilename, ".bsp");
290                 fh = fopen(fn, FILE_READ);
291         }
292         if(fh < 0)
293                 return 0;
294         LOG_INFO("Analyzing ", fn, " to generate initial mapinfo");
295
296         inWorldspawn = 2;
297         MapInfo_Map_flags = 0;
298         MapInfo_Map_supportedGametypes = 0;
299         spawnpoints = 0;
300         spawnplaces = 0;
301         _MapInfo_Map_worldspawn_music = "";
302         mapMins = '0 0 0';
303         mapMaxs = '0 0 0';
304
305         if(autocvar_g_mapinfo_arena_generate)
306         {
307                 // try for .arena or .defi files, as they may have more accurate information
308                 bool isdefi = false;
309                 string arena_fn = _MapInfo_FindArenaFile(pFilename, ".arena");
310                 int arena_fh = fopen(arena_fn, FILE_READ);
311                 if(arena_fh < 0)
312                 {
313                         isdefi = true;
314                         arena_fn = _MapInfo_FindArenaFile(pFilename, ".defi");
315                         arena_fh = fopen(arena_fn, FILE_READ);
316                 }
317                 if(arena_fh >= 0)
318                 {
319                         _MapInfo_ParseArena(arena_fn, arena_fh, pFilename, NULL, isdefi, true);
320                         fclose(arena_fh);
321                 }
322         }
323
324         for (;;)
325         {
326                 if (!((s = fgets(fh))))
327                         break;
328                 if(inWorldspawn == 1)
329                         if(startsWith(s, "}"))
330                                 inWorldspawn = 0;
331                 k = unquote(car(s));
332                 v = unquote(cdr(s));
333                 if(inWorldspawn)
334                 {
335                         if(k == "classname" && v == "worldspawn")
336                                 inWorldspawn = 1;
337                         else if(k == "author")
338                                 MapInfo_Map_author = v;
339                         else if(k == "_description")
340                                 MapInfo_Map_description = v;
341                         else if(k == "music")
342                                 _MapInfo_Map_worldspawn_music = v;
343                         else if(k == "noise")
344                                 _MapInfo_Map_worldspawn_music = v;
345                         else if(k == "message")
346                         {
347                                 i = strstrofs(v, " by ", 0);
348                                 if(MapInfo_Map_author == "<AUTHOR>" && i >= 0)
349                                 {
350                                         MapInfo_Map_title = substring(v, 0, i);
351                                         MapInfo_Map_author = substring(v, i + 4, strlen(v) - (i + 4));
352                                 }
353                                 else
354                                         MapInfo_Map_title = v;
355                         }
356                 }
357                 else
358                 {
359                         if(k == "origin")
360                         {
361                                 o = stov(strcat("'", v, "'"));
362                                 mapMins.x = min(mapMins.x, o.x);
363                                 mapMins.y = min(mapMins.y, o.y);
364                                 mapMins.z = min(mapMins.z, o.z);
365                                 mapMaxs.x = max(mapMaxs.x, o.x);
366                                 mapMaxs.y = max(mapMaxs.y, o.y);
367                                 mapMaxs.z = max(mapMaxs.z, o.z);
368                         }
369                         else if(k == "race_place")
370                         {
371                                 if(stof(v) > 0)
372                                         spawnplaces = 1;
373                         }
374                         else if(k == "classname")
375                         {
376                                 if(v == "info_player_team1")
377                                         ++spawnpoints;
378                                 else if(v == "info_player_team2")
379                                         ++spawnpoints;
380                                 else if(v == "info_player_start")
381                                         ++spawnpoints;
382                                 else if(v == "info_player_deathmatch")
383                                         ++spawnpoints;
384                                 else if(v == "weapon_nex")
385                                         { }
386                                 else if(v == "weapon_railgun")
387                                         { }
388                                 else if(startsWith(v, "weapon_"))
389                                         MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_WEAPONS;
390                                 else if(startsWith(v, "turret_"))
391                                         MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_TURRETS;
392                                 else if(startsWith(v, "vehicle_"))
393                                         MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_VEHICLES;
394                                 else if(startsWith(v, "monster_"))
395                                         MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_MONSTERS;
396                                 else if(v == "target_music" || v == "trigger_music")
397                                         _MapInfo_Map_worldspawn_music = string_null; // don't use regular BGM
398                                 else
399                                         FOREACH(Gametypes, true, it.m_generate_mapinfo(it, v));
400                         }
401                 }
402         }
403         if(inWorldspawn)
404         {
405                 LOG_WARN(fn, " ended still in worldspawn, BUG");
406                 return 0;
407         }
408         diameter = vlen(mapMaxs - mapMins);
409
410         int twoBaseModes = 0;
411         FOREACH(Gametypes, it.m_isTwoBaseMode(), twoBaseModes |= it.m_flags);
412         if(twoBaseModes && (twoBaseModes &= MapInfo_Map_supportedGametypes))
413         {
414                 // we have a symmetrical map, don't add the modes without bases
415         }
416         else
417         {
418                 FOREACH(Gametypes, it.m_isAlwaysSupported(it, spawnpoints, diameter), MapInfo_Map_supportedGametypes |= it.m_flags);
419         }
420
421         if(MapInfo_Map_supportedGametypes & MAPINFO_TYPE_RACE.m_flags)
422         if(!spawnplaces)
423         {
424                 MapInfo_Map_supportedGametypes &= ~MAPINFO_TYPE_RACE.m_flags;
425                 MapInfo_Map_supportedGametypes |= MAPINFO_TYPE_CTS.m_flags;
426         }
427
428         LOG_TRACE("-> diameter ",    ftos(diameter));
429         LOG_TRACE(";  spawnpoints ", ftos(spawnpoints));
430         LOG_TRACE(";  modes ",       ftos(MapInfo_Map_supportedGametypes));
431
432         fclose(fh);
433
434         return r;
435 }
436
437 void _MapInfo_Map_Reset()
438 {
439         MapInfo_Map_title = "<TITLE>";
440         MapInfo_Map_titlestring = "<TITLE>";
441         MapInfo_Map_description = "<DESCRIPTION>";
442         MapInfo_Map_author = "<AUTHOR>";
443         MapInfo_Map_supportedGametypes = 0;
444         MapInfo_Map_supportedFeatures = 0;
445         MapInfo_Map_flags = 0;
446         MapInfo_Map_clientstuff = "";
447         MapInfo_Map_fog = "";
448         MapInfo_Map_mins = '0 0 0';
449         MapInfo_Map_maxs = '0 0 0';
450 }
451
452 string _MapInfo_GetDefault(Gametype t)
453 {
454         return t.m_legacydefaults;
455 }
456
457 void _MapInfo_Map_ApplyGametype(string s, Gametype pWantedType, Gametype pThisType, int load_default)
458 {
459         string sa;
460         MapInfo_Map_supportedGametypes |= pThisType.m_flags;
461         if(!(pThisType.m_flags & pWantedType.m_flags))
462                 return;
463
464         if(load_default)
465                 _MapInfo_Map_ApplyGametype(_MapInfo_GetDefault(pThisType), pWantedType, pThisType, false);
466
467         if(!pWantedType.frags) // these modes don't use fraglimit
468         {
469                 cvar_set("fraglimit", "0");
470         }
471         else
472         {
473                 sa = car(s);
474                 if(sa != "")
475                         cvar_set("fraglimit", sa);
476                 s = cdr(s);
477         }
478
479         sa = car(s);
480         if(sa != "")
481                 cvar_set("timelimit", sa);
482         s = cdr(s);
483
484         if(pWantedType.m_setTeams)
485         {
486                 sa = car(s);
487                 if(sa != "")
488                         pWantedType.m_setTeams(sa);
489                 s = cdr(s);
490         }
491
492         // rc = timelimit timelimit_qualification laps laps_teamplay
493         if(pWantedType == MAPINFO_TYPE_RACE)
494         {
495                 cvar_set("fraglimit", "0"); // special case!
496
497                 sa = car(s); if(sa == "") sa = cvar_string("timelimit");
498                 cvar_set("g_race_qualifying_timelimit", sa);
499                 s = cdr(s);
500
501                 sa = car(s);
502                 if(sa != "")
503                         if(cvar("g_race_teams") < 2)
504                                 cvar_set("fraglimit", sa);
505                 s = cdr(s);
506
507                 sa = car(s);
508                 if(sa != "")
509                         if(cvar("g_race_teams") >= 2)
510                                 cvar_set("fraglimit", sa);
511                 s = cdr(s);
512         }
513
514         if(!pWantedType.frags) // these modes don't use fraglimit
515         {
516                 cvar_set("leadlimit", "0");
517         }
518         else
519         {
520                 sa = car(s);
521                 if(sa != "")
522                         cvar_set("leadlimit", sa);
523                 s = cdr(s);
524         }
525 }
526
527 string _MapInfo_GetDefaultEx(Gametype t)
528 {
529         return t ? t.model2 : "";
530 }
531
532 float _MapInfo_GetTeamPlayBool(Gametype t)
533 {
534         return t ? t.team : false;
535 }
536
537 void _MapInfo_Map_ApplyGametypeEx(string s, Gametype pWantedType, Gametype pThisType)
538 {
539         MapInfo_Map_supportedGametypes |= pThisType.m_flags;
540         if (!(pThisType.m_flags & pWantedType.m_flags))
541                 return;
542
543         // reset all the cvars to their defaults
544
545         cvar_set("timelimit", cvar_defstring("timelimit"));
546         cvar_set("leadlimit", cvar_defstring("leadlimit"));
547         cvar_set("fraglimit", cvar_defstring("fraglimit"));
548         FOREACH(Gametypes, true, it.m_parse_mapinfo(string_null, string_null));
549
550         string fraglimit_normal = string_null;
551         string fraglimit_teams = string_null;
552
553         for (s = strcat(_MapInfo_GetDefaultEx(pWantedType), " ", s); s != ""; s = cdr(s)) {
554                 string sa = car(s);
555                 if (sa == "") continue;
556                 int p = strstrofs(sa, "=", 0);
557                 if (p < 0) {
558                         if(WARN_COND)
559                                 LOG_WARNF("Invalid gametype setting in mapinfo for gametype %s: %s", MapInfo_Type_ToString(pWantedType), sa);
560                         continue;
561                 }
562                 string k = substring(sa, 0, p);
563                 string v = substring(sa, p + 1, -1);
564                 bool handled = true;
565                 switch (k) {
566                         case "timelimit":
567                         {
568                                 cvar_set("timelimit", v);
569                                 break;
570                         }
571                         case "leadlimit":
572                         {
573                                 cvar_set("leadlimit", v);
574                                 break;
575                         }
576                         case "pointlimit":
577                         case "fraglimit":
578                         case "lives":
579                         case "laplimit":
580                         case "caplimit":
581                         {
582                                 fraglimit_normal = v;
583                                 break;
584                         }
585                         case "teampointlimit":
586                         case "teamlaplimit":
587                         {
588                                 fraglimit_teams = v;
589                                 break;
590                         }
591                         default:
592                         {
593                             handled = false;
594                             break;
595                         }
596                 }
597                 FOREACH(Gametypes, true, handled |= it.m_parse_mapinfo(k, v));
598                 if (!handled && WARN_COND)
599             LOG_WARNF("Invalid gametype setting in mapinfo for gametype %s: %s", MapInfo_Type_ToString(pWantedType), sa);
600         }
601
602         if (pWantedType == MAPINFO_TYPE_RACE && cvar("g_race_teams") >= 2)
603         {
604                 if(fraglimit_teams)
605                         cvar_set("fraglimit", fraglimit_teams);
606         }
607         else
608         {
609                 if(fraglimit_normal)
610                         cvar_set("fraglimit", fraglimit_normal);
611         }
612 }
613
614 Gametype MapInfo_Type_FromString(string gtype, bool dowarn)
615 {
616         string replacement = "";
617         bool do_warn = true;
618         switch (gtype)
619         {
620                 case "nexball":   replacement = "nb"; break;
621                 case "freezetag": replacement = "ft"; break;
622                 case "keepaway":  replacement = "ka"; break;
623                 case "invasion":  replacement = "inv"; break;
624                 case "assault":   replacement = "as"; break;
625                 case "race":      replacement = "rc"; break;
626                 // quake 3 compat
627                 case "ffa":       replacement = "dm"; do_warn = false; break;
628                 case "cctf":
629                 case "oneflag":   replacement = "ctf"; do_warn = false; break;
630                 case "team":      replacement = "tdm"; do_warn = false; break;
631                 case "tourney":   replacement = "duel"; do_warn = false; break;
632         }
633         if (replacement != "")
634         {
635                 if (dowarn && WARN_COND)
636                         LOG_WARNF("MapInfo_Type_FromString (probably %s): using deprecated name '%s'. Should use '%s'.", MapInfo_Map_bspname, gtype, replacement);
637                 gtype = replacement;
638         }
639         FOREACH(Gametypes, it.mdl == gtype, return it);
640         return NULL;
641 }
642
643 string MapInfo_Type_Description(Gametype t)
644 {
645         return t ? t.gametype_description : "";
646 }
647
648 string MapInfo_Type_ToString(Gametype t)
649 {
650         return t ? t.mdl : "";
651 }
652
653 string MapInfo_Type_ToText(Gametype t)
654 {
655         /* xgettext:no-c-format */
656         return t ? t.message : _("@!#%'n Tuba Throwing");
657 }
658
659 void _MapInfo_Parse_Settemp(string pFilename, string acl, float type, string s, float recurse)
660 {
661         string t;
662         float fh, o;
663         t = car(s); s = cdr(s);
664
665         // limited support of "" and comments
666         //   remove trailing and leading " of t
667         if(substring(t, 0, 1) == "\"")
668         {
669                 if(substring(t, -1, 1) == "\"")
670                         t = substring(t, 1, -2);
671         }
672
673         //   remove leading " of s
674         if(substring(s, 0, 1) == "\"")
675         {
676                 s = substring(s, 1, -1);
677         }
678         //   remove trailing " of s, and all that follows (cvar description)
679         o = strstrofs(s, "\"", 0);
680         if(o >= 0)
681                 s = substring(s, 0, o);
682
683         //   remove // comments
684         o = strstrofs(s, "//", 0);
685         if(o >= 0)
686                 s = substring(s, 0, o);
687
688         //   remove trailing spaces
689         while(substring(s, -1, 1) == " ")
690                 s = substring(s, 0, -2);
691
692         if(t == "#include")
693         {
694                 if(recurse > 0)
695                 {
696                         fh = fopen(s, FILE_READ);
697                         if(fh < 0)
698                         {
699                                 if(WARN_COND)
700                                         LOG_WARN("Map ", pFilename, " references not existing config file ", s);
701                         }
702                         else
703                         {
704                                 while((s = fgets(fh)))
705                                 {
706                                         // catch different sorts of comments
707                                         if(s == "")                    // empty lines
708                                                 continue;
709                                         if(substring(s, 0, 1) == "#")  // UNIX style
710                                                 continue;
711                                         if(substring(s, 0, 2) == "//") // C++ style
712                                                 continue;
713                                         if(substring(s, 0, 1) == "_")  // q3map style
714                                                 continue;
715
716                                         if(substring(s, 0, 4) == "set ")
717                                                 s = substring(s, 4, -1);
718                                         if(substring(s, 0, 5) == "seta ")
719                                                 s = substring(s, 5, -1);
720
721                                         _MapInfo_Parse_Settemp(pFilename, acl, type, s, recurse - 1);
722                                 }
723                                 fclose(fh);
724                         }
725                 }
726                 else if(WARN_COND)
727                         LOG_WARN("Map ", pFilename, " uses too many levels of inclusion");
728         }
729         else if(t == ""
730                 || !cvar_value_issafe(t)
731                 || !cvar_value_issafe(s)
732                 || matchacl(MAPINFO_SETTEMP_ACL_SYSTEM, t) <= 0)
733         {
734                 if (WARN_COND)
735                         LOG_WARN("Map ", pFilename, " contains a potentially harmful setting, ignored");
736         }
737         else if(matchacl(acl, t) <= 0)
738         {
739                 if (WARN_COND)
740                         LOG_WARN("Map ", pFilename, " contains a denied setting, ignored");
741         }
742         else
743         {
744                 if(type == 0) // server set
745                 {
746                         LOG_TRACE("Applying temporary setting ", t, " := ", s);
747                 #if 0
748                         if(cvar("g_campaign"))
749                                 cvar_set(t, s); // this is a wrapper and is always temporary anyway; no need to backup old values then
750                         else
751                 #endif
752                                 cvar_settemp(t, s);
753                 }
754                 else
755                 {
756                         LOG_TRACE("Applying temporary client setting ", t, " := ", s);
757                         MapInfo_Map_clientstuff = strcat(
758                                         MapInfo_Map_clientstuff, "cl_cmd settemp \"", t, "\" \"", s, "\"\n"
759                                         );
760                 }
761         }
762 }
763
764 float MapInfo_isRedundant(string fn, string t)
765 {
766         // normalize file name
767         fn = strreplace("_", "", fn);
768         fn = strreplace("-", "", fn);
769
770         // normalize visible title
771         t = strreplace(":", "", t);
772         t = strreplace(" ", "", t);
773         t = strreplace("_", "", t);
774         t = strreplace("-", "", t);
775         t = strreplace("'", "", t);
776         t = strdecolorize(t);
777
778         // we allow the visible title to have punctuation the file name does
779         // not, but not vice versa
780         if(!strcasecmp(fn, t))
781                 return true;
782
783         return false;
784 }
785
786 bool _MapInfo_ParseArena(string arena_filename, int fh, string pFilename, Gametype pGametypeToSet, bool isdefi, bool isgenerator)
787 {
788         // NOTE: .arena files can hold more than 1 map's information!
789         // to handle this, we're going to store gathered information in local variables and save it if we encounter the correct map name
790         bool in_brackets = false; // testing a potential mapinfo section (within brackets)
791         bool dosave = (arena_filename == strcat("scripts/", pFilename, ((isdefi) ? ".defi" : ".arena"))); // if the map is using the fallback, just accept the first found mapinfo (it's probably correct!)
792         string stored_Map_description = "";
793         string stored_Map_title = "";
794         string stored_Map_author = "";
795         int stored_supportedGametypes = 0;
796         int stored_supportedFeatures = 0;
797         int stored_flags = 0;
798         string t, s;
799         for (;;)
800         {
801                 if (!((s = fgets(fh))))
802                         break;
803
804                 // catch different sorts of comments
805                 if(s == "")                    // empty lines
806                         continue;
807                 if(substring(s, 0, 1) == "#")  // UNIX style
808                         continue;
809                 if(substring(s, 0, 2) == "//") // C++ style
810                         continue;
811                 if(substring(s, 0, 1) == "_")  // q3map style
812                         continue;
813                 if(strstrofs(s, "{", 0) >= 0)
814                 {
815                         if(in_brackets)
816                                 return false; // edge case? already in a bracketed section!
817                         in_brackets = true;
818                         continue;
819                 }
820                 else if(!in_brackets)
821                 {
822                         // if we're not inside a bracket, don't process map info
823                         continue;
824                 }
825                 if(strstrofs(s, "}", 0) >= 0)
826                 {
827                         if(!in_brackets)
828                                 return false; // no starting bracket! let the mapinfo generation system handle it
829                         in_brackets = false;
830                         if(dosave)
831                         {
832                                 MapInfo_Map_description = stored_Map_description;
833                                 if(stored_Map_title != "")
834                                         MapInfo_Map_title = stored_Map_title;
835                                 MapInfo_Map_author = stored_Map_author;
836                                 if(isgenerator)
837                                         MapInfo_Map_supportedGametypes = stored_supportedGametypes;
838                                 else
839                                 {
840                                         FOREACH(Gametypes, it.m_flags & stored_supportedGametypes,
841                                         {
842                                                 _MapInfo_Map_ApplyGametype ("", pGametypeToSet, it, true);
843                                         });
844                                 }
845                                 MapInfo_Map_supportedFeatures = stored_supportedFeatures;
846                                 MapInfo_Map_flags = stored_flags;
847                                 return true; // no need to continue through the file, we have our map!
848                         }
849                         else
850                         {
851                                 // discard any gathered locals, we're not using the correct map!
852                                 stored_Map_description = "";
853                                 stored_Map_title = "";
854                                 stored_Map_author = "";
855                                 stored_supportedGametypes = 0;
856                                 stored_supportedFeatures = 0;
857                                 stored_flags = 0;
858                                 continue;
859                         }
860                 }
861
862                 s = strreplace("\t", " ", s);
863
864                 float p = strstrofs(s, "//", 0);
865                 if(p >= 0)
866                         s = substring(s, 0, p);
867
868                 // perform an initial trim to ensure the first argument is properly obtained
869                 //   remove leading spaces
870                 while(substring(s, 0, 1) == " ")
871                         s = substring(s, 1, -1);
872
873                 t = car(s); s = cdr(s);
874                 t = strtolower(t); // apparently some q3 maps use capitalized parameters
875
876                 //   remove trailing spaces
877                 while(substring(t, -1, 1) == " ")
878                         t = substring(t, 0, -2);
879
880                 //   remove trailing spaces
881                 while(substring(s, -1, 1) == " ")
882                         s = substring(s, 0, -2);
883                 //   remove leading spaces
884                 while(substring(s, 0, 1) == " ")
885                         s = substring(s, 1, -1);
886                 // limited support of ""
887                 //   remove trailing and leading " of s
888                 if(substring(s, 0, 1) == "\"")
889                 {
890                         if(substring(s, -1, 1) == "\"")
891                                 s = substring(s, 1, -2);
892                 }
893                 if(t == "longname")
894                         stored_Map_title = s;
895                 else if(t == "author")
896                         stored_Map_author = s;
897                 else if(t == "type")
898                 {
899                         // if there is a valid gametype in this .arena file, include it in the menu
900                         stored_supportedFeatures |= MAPINFO_FEATURE_WEAPONS;
901                         // type in quake 3 holds all the supported gametypes, so we must loop through all of them
902                         FOREACH_WORD(s, true,
903                         {
904                                 Gametype f = MapInfo_Type_FromString(it, false);
905                                 if(f)
906                                         stored_supportedGametypes |= f.m_flags;
907                         });
908                 }
909                 else if(t == "style" && isdefi)
910                 {
911                         // we have a defrag map on our hands, add CTS!
912                         // TODO: styles
913                         stored_supportedGametypes |= MAPINFO_TYPE_CTS.m_flags;
914                 }
915                 else if(t == "map")
916                 {
917                         if(strtolower(s) == strtolower(pFilename))
918                                 dosave = true; // yay, found our map!
919                 }
920                 else if(t == "quote")
921                         stored_Map_description = s;
922                 // TODO: fraglimit
923         }
924
925         // if the map wasn't found in the .arena, fall back to generated .mapinfo
926         return false;
927 }
928
929 #if defined(CSQC) || defined(MENUQC)
930 string(string filename) whichpack = #503;
931 #endif
932 string _MapInfo_FindArenaFile(string pFilename, string extension)
933 {
934         string fallback = strcat("scripts/", pFilename, extension);
935         if(!checkextension("DP_QC_FS_SEARCH_PACKFILE"))
936                 return fallback;
937         string base_pack = whichpack(strcat("maps/", pFilename, ".bsp"));
938         if(base_pack == "") // this map isn't packaged!
939                 return fallback;
940
941         int glob = search_packfile_begin(strcat("scripts/*", extension), true, true, base_pack);
942         if(glob < 0)
943                 return fallback;
944         int n = search_getsize(glob);
945         for(int j = 0; j < n; ++j)
946         {
947                 string file = search_getfilename(glob, j);
948
949                 int fh = fopen(file, FILE_READ);
950                 if(fh < 0)
951                         continue; // how?
952                 for(string s; (s = fgets(fh)); )
953                 {
954                         int offset = strstrofs(s, "map", 0);
955                         if(offset >= 0)
956                         {
957                                 if(strstrofs(strtolower(s), strcat("\"", strtolower(pFilename), "\""), offset) >= 0) // quake 3 is case insensitive
958                                 {
959                                         fclose(fh);
960                                         search_end(glob);
961                                         return file; // FOUND IT!
962                                 }
963                         }
964                 }
965                 fclose(fh);
966         }
967
968         search_end(glob);
969         return fallback; // if we get here, a valid .arena file could not be found
970 }
971
972 // load info about a map by name into the MapInfo_Map_* globals
973 float MapInfo_Get_ByName_NoFallbacks(string pFilename, int pAllowGenerate, Gametype pGametypeToSet)
974 {
975         string fn;
976         string s, t;
977         float fh;
978         int f, i;
979         float r, n;
980         string acl;
981
982         acl = MAPINFO_SETTEMP_ACL_USER;
983
984         if(strstrofs(pFilename, "/", 0) >= 0)
985         {
986                 LOG_WARN("Invalid character in map name, ignored");
987                 return 0;
988         }
989
990         if(pGametypeToSet == NULL)
991                 if(MapInfo_Cache_Retrieve(pFilename))
992                         return 1;
993
994         r = 1;
995
996         MapInfo_Map_bspname = pFilename;
997
998         // default all generic fields so they have "good" values in case something fails
999         fn = strcat("maps/", pFilename, ".mapinfo");
1000         fh = fopen(fn, FILE_READ);
1001         if(fh < 0)
1002         {
1003                 if(autocvar_g_mapinfo_arena_compat)
1004                 {
1005                         // try for .arena or .defi files if no .mapinfo exists
1006                         bool isdefi = false;
1007                         fn = _MapInfo_FindArenaFile(pFilename, ".arena");
1008                         fh = fopen(fn, FILE_READ);
1009                         if(fh < 0)
1010                         {
1011                                 isdefi = true;
1012                                 fn = _MapInfo_FindArenaFile(pFilename, ".defi");
1013                                 fh = fopen(fn, FILE_READ);
1014                         }
1015                         if(fh >= 0)
1016                         {
1017                                 _MapInfo_Map_Reset();
1018                                 if(_MapInfo_ParseArena(fn, fh, pFilename, pGametypeToSet, isdefi, false))
1019                                         goto mapinfo_handled; // skip generation
1020                         }
1021                 }
1022
1023                 fn = strcat("maps/autogenerated/", pFilename, ".mapinfo");
1024                 fh = fopen(fn, FILE_READ);
1025                 if(fh < 0)
1026                 {
1027                         if(!pAllowGenerate)
1028                                 return 0;
1029                         _MapInfo_Map_Reset();
1030                         r = _MapInfo_Generate(pFilename);
1031                         if(!r)
1032                                 return 0;
1033                         fh = fopen(fn, FILE_WRITE);
1034                         fputs(fh, strcat("title ", MapInfo_Map_title, "\n"));
1035                         fputs(fh, strcat("description ", MapInfo_Map_description, "\n"));
1036                         fputs(fh, strcat("author ", MapInfo_Map_author, "\n"));
1037                         if(_MapInfo_Map_worldspawn_music != "")
1038                         {
1039                                 if(
1040                                         substring(_MapInfo_Map_worldspawn_music, strlen(_MapInfo_Map_worldspawn_music) - 4, 4) == ".wav"
1041                                         ||
1042                                         substring(_MapInfo_Map_worldspawn_music, strlen(_MapInfo_Map_worldspawn_music) - 4, 4) == ".ogg"
1043                                 )
1044                                         fputs(fh, strcat("cdtrack ", substring(_MapInfo_Map_worldspawn_music, 0, strlen(_MapInfo_Map_worldspawn_music) - 4), "\n"));
1045                                 else
1046                                         fputs(fh, strcat("cdtrack ", _MapInfo_Map_worldspawn_music, "\n"));
1047                         }
1048                         else
1049                         {
1050                                 n = tokenize_console(cvar_string("g_cdtracks_remaplist"));
1051                                 s = strcat(" ", cvar_string("g_cdtracks_dontusebydefault"), " ");
1052                                 for (;;)
1053                                 {
1054                                         i = floor(random() * n);
1055                                         if(strstrofs(s, strcat(" ", argv(i), " "), 0) < 0)
1056                                                 break;
1057                                 }
1058                                 fputs(fh, strcat("cdtrack ", ftos(i + 1), "\n"));
1059                         }
1060                         if(MapInfo_Map_supportedFeatures & MAPINFO_FEATURE_WEAPONS)
1061                                 fputs(fh, "has weapons\n");
1062                         else
1063                                 fputs(fh, "// uncomment this if you added weapon pickups: has weapons\n");
1064                         if(MapInfo_Map_supportedFeatures & MAPINFO_FEATURE_TURRETS)
1065                                 fputs(fh, "has turrets\n");
1066                         else
1067                                 fputs(fh, "// uncomment this if you added turrets: has turrets\n");
1068                         if(MapInfo_Map_supportedFeatures & MAPINFO_FEATURE_VEHICLES)
1069                                 fputs(fh, "has vehicles\n");
1070                         else
1071                                 fputs(fh, "// uncomment this if you added vehicles: has vehicles\n");
1072                         if(MapInfo_Map_flags & MAPINFO_FLAG_FRUSTRATING)
1073                                 fputs(fh, "frustrating\n");
1074
1075                         FOREACH(Gametypes, MapInfo_Map_supportedGametypes & it.m_flags, {
1076                                 fputs(fh, sprintf("gametype %s // defaults: %s\n", MapInfo_Type_ToString(it), _MapInfo_GetDefaultEx(it)));
1077                         });
1078
1079                         fputs(fh, "// optional: fog density red green blue alpha mindist maxdist\n");
1080                         fputs(fh, "// optional: settemp_for_type (all|gametypename) cvarname value\n");
1081                         fputs(fh, "// optional: clientsettemp_for_type (all|gametypename) cvarname value\n");
1082                         fputs(fh, "// optional: size mins_x mins_y mins_z maxs_x maxs_y maxs_z\n");
1083                         fputs(fh, "// optional: hidden\n");
1084
1085                         fclose(fh);
1086                         r = 2;
1087                         // return r;
1088                         fh = fopen(fn, FILE_READ);
1089                         if(fh < 0)
1090                                 error("... but I just wrote it!");
1091                 }
1092
1093                 if(WARN_COND)
1094                         LOG_WARN("autogenerated mapinfo file ", fn, " has been loaded; please edit that file and move it to maps/", pFilename, ".mapinfo");
1095         }
1096
1097         _MapInfo_Map_Reset();
1098         for (;;)
1099         {
1100                 if (!((s = fgets(fh))))
1101                         break;
1102
1103                 // catch different sorts of comments
1104                 if(s == "")                    // empty lines
1105                         continue;
1106                 if(substring(s, 0, 1) == "#")  // UNIX style
1107                         continue;
1108                 if(substring(s, 0, 2) == "//") // C++ style
1109                         continue;
1110                 if(substring(s, 0, 1) == "_")  // q3map style
1111                         continue;
1112
1113                 float p = strstrofs(s, "//", 0);
1114                 if(p >= 0)
1115                         s = substring(s, 0, p);
1116
1117                 t = car(s); s = cdr(s);
1118                 if(t == "title")
1119                         MapInfo_Map_title = s;
1120                 else if(t == "description")
1121                         MapInfo_Map_description = s;
1122                 else if(t == "author")
1123                         MapInfo_Map_author = s;
1124                 else if(t == "has")
1125                 {
1126                         t = car(s); // s = cdr(s);
1127                         if     (t == "weapons") MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_WEAPONS;
1128                         else if(t == "turrets") MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_TURRETS;
1129                         else if(t == "vehicles") MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_VEHICLES;
1130                         else if(t == "monsters") MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_MONSTERS;
1131                         else if(t == "new_toys") MapInfo_Map_supportedFeatures |= MAPINFO_FEATURE_WEAPONS;
1132                         else if(WARN_COND)
1133                                 LOG_WARN("Map ", pFilename, " supports unknown feature ", t, ", ignored");
1134                 }
1135                 else if(t == "hidden")
1136                 {
1137                         MapInfo_Map_flags |= MAPINFO_FLAG_HIDDEN;
1138                 }
1139                 else if(t == "forbidden")
1140                 {
1141                         MapInfo_Map_flags |= MAPINFO_FLAG_FORBIDDEN;
1142                 }
1143                 else if(t == "frustrating")
1144                 {
1145                         MapInfo_Map_flags |= MAPINFO_FLAG_FRUSTRATING;
1146                 }
1147                 else if(t == "noautomaplist")
1148                 {
1149                         MapInfo_Map_flags |= MAPINFO_FLAG_NOAUTOMAPLIST;
1150                 }
1151                 else if(t == "gameversion_min")
1152                 {
1153                         if (cvar("gameversion") < stof(s))
1154                                 MapInfo_Map_flags |= MAPINFO_FLAG_NOAUTOMAPLIST;
1155                 }
1156                 else if(t == "type")
1157                 {
1158                         t = car(s); s = cdr(s);
1159                         Gametype f = MapInfo_Type_FromString(t, true);
1160                         //if(WARN_COND)
1161                                 //LOG_WARN("Map ", pFilename, " contains the legacy 'type' keyword which is deprecated and will be removed in the future. Please migrate the mapinfo file to 'gametype'.");
1162                         if(f)
1163                                 _MapInfo_Map_ApplyGametype (s, pGametypeToSet, f, true);
1164                         else if(WARN_COND)
1165                                 LOG_DEBUG("Map ", pFilename, " supports unknown game type ", t, ", ignored");
1166                 }
1167                 else if(t == "gametype")
1168                 {
1169                         t = car(s); s = cdr(s);
1170                         Gametype f = MapInfo_Type_FromString(t, true);
1171                         if(f)
1172                                 _MapInfo_Map_ApplyGametypeEx (s, pGametypeToSet, f);
1173                         else if(WARN_COND)
1174                                 LOG_DEBUG("Map ", pFilename, " supports unknown game type ", t, ", ignored");
1175                 }
1176                 else if(t == "size")
1177                 {
1178                         float a, b, c, d, e;
1179                         t = car(s); s = cdr(s); a = stof(t);
1180                         t = car(s); s = cdr(s); b = stof(t);
1181                         t = car(s); s = cdr(s); c = stof(t);
1182                         t = car(s); s = cdr(s); d = stof(t);
1183                         t = car(s); s = cdr(s); e = stof(t);
1184                         if(s == "")
1185                         {
1186                                 if(WARN_COND)
1187                                         LOG_WARN("Map ", pFilename, " contains an incorrect size line (not enough params), syntax: size mins_x mins_y mins_z maxs_x maxs_y maxs_z");
1188                         }
1189                         else
1190                         {
1191                                 t = car(s); s = cdr(s); f = stof(t);
1192                                 if(s != "")
1193                                 {
1194                                         if(WARN_COND)
1195                                                 LOG_WARN("Map ", pFilename, " contains an incorrect size line (too many params), syntax: size mins_x mins_y mins_z maxs_x maxs_y maxs_z");
1196                                 }
1197                                 else
1198                                 {
1199                                         if(a >= d || b >= e || c >= f)
1200                                         {
1201                                                 if(WARN_COND)
1202                                                         LOG_WARN("Map ", pFilename, " contains an incorrect size line, mins have to be < maxs");
1203                                         }
1204                                         else
1205                                         {
1206                                                 MapInfo_Map_mins.x = a;
1207                                                 MapInfo_Map_mins.y = b;
1208                                                 MapInfo_Map_mins.z = c;
1209                                                 MapInfo_Map_maxs.x = d;
1210                                                 MapInfo_Map_maxs.y = e;
1211                                                 MapInfo_Map_maxs.z = f;
1212                                         }
1213                                 }
1214                         }
1215                 }
1216                 else if(t == "settemp_for_type")
1217                 {
1218                         t = car(s); s = cdr(s);
1219                         bool all = t == "all";
1220                         Gametype f = NULL;
1221                         if(all || (f = MapInfo_Type_FromString(t, true)))
1222                         {
1223                                 if((all ? MAPINFO_TYPE_ALL : f.m_flags) & pGametypeToSet.m_flags)
1224                                 {
1225                                         _MapInfo_Parse_Settemp(pFilename, acl, 0, s, 1);
1226                                 }
1227                         }
1228                         else
1229                         {
1230                                 LOG_DEBUG("Map ", pFilename, " has a setting for unknown game type ", t, ", ignored");
1231                         }
1232                 }
1233                 else if(t == "clientsettemp_for_type")
1234                 {
1235                         t = car(s); s = cdr(s);
1236                         bool all = t == "all";
1237                         Gametype f = NULL;
1238                         if(all || (f = MapInfo_Type_FromString(t, true)))
1239                         {
1240                                 if((all ? MAPINFO_TYPE_ALL : f.m_flags) & pGametypeToSet.m_flags)
1241                                 {
1242                                         _MapInfo_Parse_Settemp(pFilename, acl, 1, s, 1);
1243                                 }
1244                         }
1245                         else
1246                         {
1247                                 LOG_DEBUG("Map ", pFilename, " has a client setting for unknown game type ", t, ", ignored");
1248                         }
1249                 }
1250                 else if(t == "fog")
1251                 {
1252                         if (!cvar_value_issafe(s))
1253                         {
1254                                 if(WARN_COND)
1255                                         LOG_WARN("Map ", pFilename, " contains a potentially harmful fog setting, ignored");
1256                         }
1257                         else
1258                                 MapInfo_Map_fog = s;
1259                 }
1260                 else if(t == "cdtrack")
1261                 {
1262                         t = car(s); s = cdr(s);
1263                         // We do this only if pGametypeToSet even though this
1264                         // content is theoretically game type independent,
1265                         // because MapInfo_Map_clientstuff contains otherwise
1266                         // game type dependent stuff. That way this value stays
1267                         // empty when not setting a game type to not set any
1268                         // false expectations.
1269                         if(pGametypeToSet)
1270                         {
1271                                 if (!cvar_value_issafe(t))
1272                                 {
1273                                         if(WARN_COND)
1274                                                 LOG_WARN("Map ", pFilename, " contains a potentially harmful cdtrack, ignored");
1275                                 }
1276                                 else
1277                                         MapInfo_Map_clientstuff = strcat(
1278                                                 MapInfo_Map_clientstuff, "cd loop \"", t, "\"\n"
1279                                         );
1280                         }
1281                 }
1282                 else if(WARN_COND)
1283                         LOG_WARN("Map ", pFilename, " provides unknown info item ", t, ", ignored");
1284         }
1285         LABEL(mapinfo_handled)
1286         fclose(fh);
1287
1288         if(MapInfo_Map_title == "<TITLE>")
1289                 MapInfo_Map_titlestring = MapInfo_Map_bspname;
1290         else if(MapInfo_isRedundant(MapInfo_Map_bspname, MapInfo_Map_title))
1291                 MapInfo_Map_titlestring = MapInfo_Map_title;
1292         else
1293                 MapInfo_Map_titlestring = sprintf("%s: %s", MapInfo_Map_bspname, MapInfo_Map_title);
1294
1295         MapInfo_Cache_Store();
1296         if(MapInfo_Map_supportedGametypes != 0)
1297                 return r;
1298         if (WARN_COND)
1299                 LOG_WARN("Map ", pFilename, " supports no game types, ignored");
1300         return 0;
1301 }
1302 int MapInfo_Get_ByName(string pFilename, float pAllowGenerate, Gametype pGametypeToSet)
1303 {
1304         int r = MapInfo_Get_ByName_NoFallbacks(pFilename, pAllowGenerate, pGametypeToSet);
1305
1306         FOREACH(Gametypes, it.m_isForcedSupported(it), _MapInfo_Map_ApplyGametypeEx("", pGametypeToSet, it));
1307
1308         if(pGametypeToSet)
1309         {
1310                 if(!(MapInfo_Map_supportedGametypes & pGametypeToSet.m_flags))
1311                 {
1312                         error("Can't select the requested game type. This should never happen as the caller should prevent it!\n");
1313                         //_MapInfo_Map_ApplyGametypeEx("", pGametypeToSet, MAPINFO_TYPE_DEATHMATCH);
1314                         //return;
1315                 }
1316         }
1317
1318         return r;
1319 }
1320
1321 float MapInfo_FindName(string s)
1322 {
1323         // if there is exactly one map of prefix s, return it
1324         // if not, return the null string
1325         // note that DP sorts glob results... so I can use a binary search
1326         float l, r, m, cmp;
1327         l = 0;
1328         r = MapInfo_count;
1329         // invariants: r is behind s, l-1 is equal or before
1330         while(l != r)
1331         {
1332                 m = floor((l + r) / 2);
1333                 MapInfo_FindName_match = _MapInfo_GlobItem(MapInfo_FilterList_Lookup(m));
1334                 cmp = strcasecmp(MapInfo_FindName_match, s);
1335                 if(cmp == 0)
1336                         return m; // found and good
1337                 if(cmp < 0)
1338                         l = m + 1; // l-1 is before s
1339                 else
1340                         r = m; // behind s
1341         }
1342         MapInfo_FindName_match = _MapInfo_GlobItem(MapInfo_FilterList_Lookup(l));
1343         MapInfo_FindName_firstResult = l;
1344         // r == l, so: l is behind s, l-1 is before
1345         // SO: if there is any, l is the one with the right prefix
1346         //     and l+1 may be one too
1347         if(l == MapInfo_count)
1348         {
1349                 MapInfo_FindName_match = string_null;
1350                 MapInfo_FindName_firstResult = -1;
1351                 return -1; // no MapInfo_FindName_match, behind last item
1352         }
1353         if(!startsWithNocase(MapInfo_FindName_match, s))
1354         {
1355                 MapInfo_FindName_match = string_null;
1356                 MapInfo_FindName_firstResult = -1;
1357                 return -1; // wrong prefix
1358         }
1359         if(l == MapInfo_count - 1)
1360                 return l; // last one, nothing can follow => unique
1361         if(startsWithNocase(_MapInfo_GlobItem(MapInfo_FilterList_Lookup(l + 1)), s))
1362         {
1363                 MapInfo_FindName_match = string_null;
1364                 return -1; // ambigous MapInfo_FindName_match
1365         }
1366         return l;
1367 }
1368
1369 string MapInfo_FixName(string s)
1370 {
1371         MapInfo_FindName(s);
1372         return MapInfo_FindName_match;
1373 }
1374
1375 int MapInfo_CurrentFeatures()
1376 {
1377         int req = 0;
1378     // TODO: find a better way to check if weapons are required on the map
1379         if(!(cvar("g_instagib") || cvar("g_overkill") || cvar("g_nix") || cvar("g_weaponarena") || !cvar("g_pickup_items") 
1380                 || cvar("g_race") || cvar("g_cts") || cvar("g_nexball") || cvar("g_ca") || cvar("g_freezetag") || cvar("g_lms")))
1381                 req |= MAPINFO_FEATURE_WEAPONS;
1382         return req;
1383 }
1384
1385 Gametype MapInfo_CurrentGametype()
1386 {
1387         Gametype prev = MapInfo_Type_FromString(cvar_string("gamecfg"), false);
1388         FOREACH(Gametypes, cvar(it.netname) && it != prev, return it);
1389         return prev ? prev : MAPINFO_TYPE_DEATHMATCH;
1390 }
1391
1392 float _MapInfo_CheckMap(string s, bool gametype_only) // returns 0 if the map can't be played with the current settings, 1 otherwise
1393 {
1394         if(!MapInfo_Get_ByName(s, 1, NULL))
1395                 return 0;
1396         if((MapInfo_Map_supportedGametypes & MapInfo_CurrentGametype().m_flags) == 0)
1397                 return 0;
1398         if (gametype_only)
1399                 return 1;
1400         if((MapInfo_Map_supportedFeatures & MapInfo_CurrentFeatures()) != MapInfo_CurrentFeatures())
1401                 return 0;
1402         return 1;
1403 }
1404
1405 float MapInfo_CheckMap(string s) // returns 0 if the map can't be played with the current settings, 1 otherwise
1406 {
1407         float r;
1408         r = _MapInfo_CheckMap(s, false);
1409         MapInfo_ClearTemps();
1410         return r;
1411 }
1412
1413 void MapInfo_SwitchGameType(Gametype t)
1414 {
1415         FOREACH(Gametypes, true, cvar_set(it.netname, (it == t) ? "1" : "0"));
1416 }
1417
1418 void MapInfo_LoadMap(string s, float reinit)
1419 {
1420         MapInfo_Map_supportedGametypes = 0;
1421         // we shouldn't need this, as LoadMapSettings already fixes the gametype
1422         //if(!MapInfo_CheckMap(s))
1423         //{
1424         //      print("EMERGENCY: can't play the selected map in the given game mode. Falling back to DM.\n");
1425         //      MapInfo_SwitchGameType(MAPINFO_TYPE_DEATHMATCH.m_flags);
1426         //}
1427
1428         LOG_INFO("Switching to map ", s);
1429
1430         cvar_settemp_restore();
1431         if(reinit)
1432                 localcmd(strcat("\nmap ", s, "\n"));
1433         else
1434                 localcmd(strcat("\nchangelevel ", s, "\n"));
1435 }
1436
1437 string MapInfo_ListAllowedMaps(Gametype type, float pRequiredFlags, float pForbiddenFlags)
1438 {
1439         string out;
1440
1441         // to make absolutely sure:
1442         MapInfo_Enumerate();
1443         MapInfo_FilterGametype(type, MapInfo_CurrentFeatures(), pRequiredFlags, pForbiddenFlags, 0);
1444
1445         out = "";
1446         for(float i = 0; i < MapInfo_count; ++i)
1447                 out = strcat(out, " ", _MapInfo_GlobItem(MapInfo_FilterList_Lookup(i)));
1448         return substring(out, 1, strlen(out) - 1);
1449 }
1450
1451 string MapInfo_ListAllAllowedMaps(float pRequiredFlags, float pForbiddenFlags)
1452 {
1453         string out;
1454
1455         // to make absolutely sure:
1456         MapInfo_Enumerate();
1457         _MapInfo_FilterGametype(MAPINFO_TYPE_ALL, 0, pRequiredFlags, pForbiddenFlags, 0);
1458
1459         out = "";
1460         for(float i = 0; i < MapInfo_count; ++i)
1461                 out = strcat(out, " ", _MapInfo_GlobItem(MapInfo_FilterList_Lookup(i)));
1462
1463         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), pRequiredFlags, pForbiddenFlags, 0);
1464
1465         return substring(out, 1, strlen(out) - 1);
1466 }
1467
1468 void MapInfo_LoadMapSettings_SaveGameType(Gametype t)
1469 {
1470         MapInfo_SwitchGameType(t);
1471         cvar_set("gamecfg", t.mdl);
1472         MapInfo_LoadedGametype = t;
1473 }
1474
1475 void MapInfo_LoadMapSettings(string s) // to be called from worldspawn
1476 {
1477         Gametype t = MapInfo_CurrentGametype();
1478         MapInfo_LoadMapSettings_SaveGameType(t);
1479
1480         if(!_MapInfo_CheckMap(s, true)) // with underscore, it keeps temps
1481         {
1482                 if(cvar("g_mapinfo_allow_unsupported_modes_and_let_stuff_break"))
1483                 {
1484                         LOG_SEVERE("can't play the selected map in the given game mode. Working with only the override settings.");
1485                         _MapInfo_Map_ApplyGametypeEx("", t, t);
1486                         return; // do not call Get_ByName!
1487                 }
1488
1489                 if(MapInfo_Map_supportedGametypes == 0)
1490                 {
1491                         RandomSelection_Init();
1492                         FOREACH(Gametypes, it.m_priority == 2, 
1493                         {
1494                                 MapInfo_Map_supportedGametypes |= it.m_flags;
1495                                 RandomSelection_AddEnt(it, 1, 1);
1496                         });
1497                         if(RandomSelection_chosen_ent)
1498                                 t = RandomSelection_chosen_ent;
1499                         LOG_SEVEREF("Mapinfo system is not functional at all. Falling back to a preferred mode (%s).", t.mdl);
1500                         MapInfo_LoadMapSettings_SaveGameType(t);
1501                         _MapInfo_Map_ApplyGametypeEx("", t, t);
1502                         return; // do not call Get_ByName!
1503                 }
1504
1505 #if 0
1506                 // find the lowest bit in the supported gametypes
1507                 // unnecessary now that we select one at random
1508                 int _t = 1;
1509                 while(!(MapInfo_Map_supportedGametypes & 1))
1510                 {
1511                         _t <<= 1;
1512                         MapInfo_Map_supportedGametypes = floor(MapInfo_Map_supportedGametypes >> 1);
1513                 }
1514 #endif
1515                 RandomSelection_Init();
1516                 Gametype t_prev = t;
1517                 FOREACH(Gametypes, MapInfo_Map_supportedGametypes & it.m_flags,
1518                 {
1519                         RandomSelection_AddEnt(it, 1, it.m_priority);
1520                 });
1521                 if(RandomSelection_chosen_ent)
1522                         t = RandomSelection_chosen_ent;
1523
1524                 // t is now a supported mode!
1525                 LOG_WARNF("can't play the selected map in the given game mode (%s). Falling back to a supported mode (%s).", t_prev.mdl, t.mdl);
1526                 MapInfo_LoadMapSettings_SaveGameType(t);
1527         }
1528         if(!_MapInfo_CheckMap(s, false)) { // with underscore, it keeps temps
1529                 LOG_WARNF("the selected map lacks features required by current settings; playing anyway.");
1530         }
1531         MapInfo_Get_ByName(s, 1, t);
1532 }
1533
1534 void MapInfo_ClearTemps()
1535 {
1536         MapInfo_Map_bspname = string_null;
1537         MapInfo_Map_title = string_null;
1538         MapInfo_Map_titlestring = string_null;
1539         MapInfo_Map_description = string_null;
1540         MapInfo_Map_author = string_null;
1541         MapInfo_Map_clientstuff = string_null;
1542         MapInfo_Map_supportedGametypes = 0;
1543         MapInfo_Map_supportedFeatures = 0;
1544 }
1545
1546 void MapInfo_Shutdown()
1547 {
1548         MapInfo_ClearTemps();
1549         MapInfo_Filter_Free();
1550         MapInfo_Cache_Destroy();
1551         if(_MapInfo_globopen)
1552         {
1553                 search_end(_MapInfo_globhandle);
1554                 _MapInfo_globhandle = -1;
1555                 _MapInfo_globopen = false;
1556         }
1557 }
1558
1559 int MapInfo_ForbiddenFlags()
1560 {
1561         int f = MAPINFO_FLAG_FORBIDDEN;
1562
1563 #ifdef GAMEQC
1564         if (!cvar("g_maplist_allow_hidden"))
1565 #endif
1566                 f |= MAPINFO_FLAG_HIDDEN;
1567
1568         if (!cvar("g_maplist_allow_frustrating"))
1569                 f |= MAPINFO_FLAG_FRUSTRATING;
1570
1571         return f;
1572 }
1573
1574 int MapInfo_RequiredFlags()
1575 {
1576         int f = 0;
1577
1578         if(cvar("g_maplist_allow_frustrating") > 1)
1579                 f |= MAPINFO_FLAG_FRUSTRATING;
1580
1581         return f;
1582 }