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