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