]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/g_world.qc
More detailed suggestmap confirmation
[divverent/nexuiz.git] / data / qcsrc / server / g_world.qc
1 float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
2 string redirection_target;
3
4 string GetMapname();
5 void GotoNextMap();
6 void ShuffleMaplist()
7 float() DoNextMapOverride;
8
9 void SetDefaultAlpha()
10 {
11         if(cvar("g_running_guns"))
12         {
13                 default_player_alpha = -1;
14                 default_weapon_alpha = +1;
15         }
16         else if(g_cloaked)
17         {
18                 default_player_alpha = cvar("g_balance_cloaked_alpha");
19                 default_weapon_alpha = default_player_alpha;
20         }
21         else
22         {
23                 default_player_alpha = cvar("g_player_alpha");
24                 if(default_player_alpha <= 0)
25                         default_player_alpha = 1;
26                 default_weapon_alpha = default_player_alpha;
27         }
28 }
29
30 void fteqcc_testbugs()
31 {
32         float a, b;
33
34         if(!cvar("developer_fteqccbugs"))
35                 return;
36
37         dprint("*** fteqcc test: checking for bugs...\n");
38
39         a = 1;
40         b = 5;
41         if(sqrt(a) - sqrt(b - a) == 0)
42                 dprint("*** fteqcc test: found same-function-twice bug\n");
43         else
44                 dprint("*** fteqcc test: same-function-twice bug got FINALLY FIXED! HOORAY!\n");
45
46         world.frags = -10;
47         world.enemy = world;
48         world.enemy.frags += 10;
49         if(world.frags > 0.2 || world.frags < -0.2) // don't error out if it's just roundoff errors
50                 dprint("*** fteqcc test: found += bug\n");
51         else
52                 dprint("*** fteqcc test: += bug got FINALLY FIXED! HOORAY!\n");
53         world.frags = 0;
54 }
55
56 void GotoFirstMap()
57 {
58         if(cvar("_sv_init"))
59         {
60                 cvar_set("_sv_init", "0");
61                 if(cvar("g_maplist_shuffle"))
62                         ShuffleMaplist();
63 #ifdef MAPINFO
64                 tokenizebyseparator(cvar_string("g_maplist"), " ");
65 #else
66                 tokenize(cvar_string("g_maplist"));
67 #endif
68                 if(argv(0) != GetMapname())
69                 {
70                         cvar_set("nextmap", argv(0));
71
72 #ifdef MAPINFO
73                         MapInfo_Enumerate();
74                         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 0);
75 #endif
76
77                         if(!DoNextMapOverride())
78                                 GotoNextMap();
79                 }
80         }
81 }
82
83 float world_already_spawned;
84 void worldspawn (void)
85 {
86         float globhandle, i, n;
87
88         dprint_load(); // load dprint status from cvar
89
90         if(world_already_spawned)
91                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
92         world_already_spawned = TRUE;
93
94         sv_cheats = cvar("sv_cheats");
95
96         /*
97         TODO sound pack system
98         // initialize sound pack system
99         soundpack = cvar_string("g_soundpack");
100         if(soundpack != "")
101                 soundpack = strcat(soundpack, "/");
102         soundpack = strzone(soundpack);
103         */
104
105         // gamemode related things
106         precache_model ("models/misc/chatbubble.spr");
107         precache_model ("models/misc/teambubble.spr");
108         if (cvar("g_runematch"))
109         {
110                 precache_model ("models/runematch/curse.mdl");
111                 precache_model ("models/runematch/rune.mdl");
112         }
113
114         // Precache all player models if desired
115         if (cvar("sv_precacheplayermodels"))
116         {
117                 globhandle = search_begin("models/player/*.zym", TRUE, FALSE);
118                 n = search_getsize(globhandle);
119                 for(i = 0; i < n; ++i)
120                 {
121                         //print(search_getfilename(globhandle, i), "\n");
122                         precache_model(search_getfilename(globhandle, i));
123                 }
124                 search_end(globhandle);
125                 //precache_model("models/player/carni.zym");
126                 //precache_model("models/player/crash.zym");
127                 //precache_model("models/player/grunt.zym");
128                 //precache_model("models/player/headhunter.zym");
129                 //precache_model("models/player/insurrectionist.zym");
130                 //precache_model("models/player/jeandarc.zym");
131                 //precache_model("models/player/lurk.zym");
132                 //precache_model("models/player/lycanthrope.zym");
133                 //precache_model("models/player/marine.zym");
134                 //precache_model("models/player/nexus.zym");
135                 //precache_model("models/player/pyria.zym");
136                 //precache_model("models/player/shock.zym");
137                 //precache_model("models/player/skadi.zym");
138                 //precache_model("models/player/specop.zym");
139                 //precache_model("models/player/visitant.zym");
140         }
141
142         if (g_footsteps)
143         {
144                 precache_sound ("misc/footstep01.wav");
145                 precache_sound ("misc/footstep02.wav");
146                 precache_sound ("misc/footstep03.wav");
147                 precache_sound ("misc/footstep04.wav");
148                 precache_sound ("misc/footstep05.wav");
149                 precache_sound ("misc/footstep06.wav");
150         }
151
152         // gore and miscellaneous sounds
153         //precache_sound ("misc/h2ohit.wav");
154         precache_model ("models/gibs/bloodyskull.md3");
155         precache_model ("models/gibs/chunk.mdl");
156         precache_model ("models/gibs/eye.md3");
157         precache_model ("models/gibs/gib1.md3");
158         precache_model ("models/gibs/gib1.mdl");
159         precache_model ("models/gibs/gib2.mdl");
160         precache_model ("models/gibs/gib3.mdl");
161         precache_model ("models/gibs/gib5.md3");
162         precache_model ("models/hook.md3");
163         precache_sound ("misc/armorimpact.wav");
164         precache_sound ("misc/bodyimpact1.wav");
165         precache_sound ("misc/bodyimpact2.wav");
166         precache_sound ("misc/gib.wav");
167         precache_sound ("misc/gib_splat01.wav");
168         precache_sound ("misc/gib_splat02.wav");
169         precache_sound ("misc/gib_splat03.wav");
170         precache_sound ("misc/gib_splat04.wav");
171         precache_sound ("misc/hit.wav");
172         precache_sound ("misc/hitground1.wav");
173         precache_sound ("misc/hitground2.wav");
174         precache_sound ("misc/hitground3.wav");
175         precache_sound ("misc/hitground4.wav");
176         precache_sound ("misc/null.wav");
177         precache_sound ("misc/spawn.wav");
178         precache_sound ("misc/talk.wav");
179         precache_sound ("misc/teleport.wav");
180         precache_sound ("player/lava.wav");
181         precache_sound ("player/slime.wav");
182
183         // announcer sounds - male
184         //precache_sound ("announcer/male/electrobitch.wav");
185         precache_sound ("announcer/male/03kills.wav");
186         precache_sound ("announcer/male/05kills.wav");
187         precache_sound ("announcer/male/10kills.wav");
188         precache_sound ("announcer/male/15kills.wav");
189         precache_sound ("announcer/male/20kills.wav");
190         precache_sound ("announcer/male/25kills.wav");
191         precache_sound ("announcer/male/30kills.wav");
192         precache_sound ("announcer/male/botlike.wav");
193         precache_sound ("announcer/male/yoda.wav");
194
195         // announcer sounds - robotic
196         precache_sound ("announcer/robotic/1fragleft.wav");
197         precache_sound ("announcer/robotic/1minuteremains.wav");
198         precache_sound ("announcer/robotic/2fragsleft.wav");
199         precache_sound ("announcer/robotic/3fragsleft.wav");
200         if (g_minstagib)
201         {
202                 precache_sound ("announcer/robotic/lastsecond.wav");
203                 precache_sound ("announcer/robotic/narrowly.wav");
204                 precache_sound ("announcer/robotic/1.wav");
205                 precache_sound ("announcer/robotic/2.wav");
206                 precache_sound ("announcer/robotic/3.wav");
207                 precache_sound ("announcer/robotic/4.wav");
208                 precache_sound ("announcer/robotic/5.wav");
209                 precache_sound ("announcer/robotic/6.wav");
210                 precache_sound ("announcer/robotic/7.wav");
211                 precache_sound ("announcer/robotic/8.wav");
212                 precache_sound ("announcer/robotic/9.wav");
213                 precache_sound ("announcer/robotic/10.wav");
214         }
215
216         // common weapon precaches
217         precache_sound ("weapons/weapon_switch.wav");
218         precache_sound ("weapons/weaponpickup.wav");
219         if (g_grappling_hook)
220         {
221                 precache_sound ("weapons/hook_fire.wav"); // hook
222                 precache_sound ("weapons/hook_impact.wav"); // hook
223         }
224
225         if (cvar("sv_precacheweapons") || g_nixnex)
226         {
227                 //precache weapon models/sounds
228                 local float wep;
229                 wep = WEP_FIRST;
230                 while (wep <= WEP_LAST)
231                 {
232                         weapon_action(wep, WR_PRECACHE);
233                         wep = wep + 1;
234                 }
235         }
236
237         // plays music for the level if there is any
238         if (self.noise)
239         {
240                 precache_sound (self.noise);
241                 ambientsound ('0 0 0', self.noise, 1.00, ATTN_NONE);
242         }
243
244         // 0 normal
245         lightstyle(0, "m");
246
247         // 1 FLICKER (first variety)
248         lightstyle(1, "mmnmmommommnonmmonqnmmo");
249
250         // 2 SLOW STRONG PULSE
251         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
252
253         // 3 CANDLE (first variety)
254         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
255
256         // 4 FAST STROBE
257         lightstyle(4, "mamamamamama");
258
259         // 5 GENTLE PULSE 1
260         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
261
262         // 6 FLICKER (second variety)
263         lightstyle(6, "nmonqnmomnmomomno");
264
265         // 7 CANDLE (second variety)
266         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
267
268         // 8 CANDLE (third variety)
269         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
270
271         // 9 SLOW STROBE (fourth variety)
272         lightstyle(9, "aaaaaaaazzzzzzzz");
273
274         // 10 FLUORESCENT FLICKER
275         lightstyle(10, "mmamammmmammamamaaamammma");
276
277         // 11 SLOW PULSE NOT FADE TO BLACK
278         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
279
280         // styles 32-62 are assigned by the light program for switchable lights
281
282         // 63 testing
283         lightstyle(63, "a");
284
285         player_count = 0;
286         lms_lowest_lives = 0;
287         lms_next_place = 0;
288
289         GotoFirstMap();
290
291         bot_waypoints_for_items = cvar("g_waypoints_for_items");
292         if(bot_waypoints_for_items == 1)
293                 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
294                         bot_waypoints_for_items = 0;
295
296         if(cvar("g_campaign"))
297                 CampaignPreInit();
298
299         InitGameplayMode();
300
301         WaypointSprite_Init();
302
303         //if (cvar("g_domination"))
304         //      dom_init();
305
306         local entity head;
307         head = nextent(world);
308         maxclients = 0;
309         while(head)
310         {
311                 maxclients++;
312                 head = nextent(head);
313         }
314
315         GameLogInit(); // prepare everything
316         if(cvar("sv_eventlog"))
317         {
318                 local string s;
319                 GameLogEcho(":logversion:2", FALSE);
320                 s = strcat(cvar_string("sv_eventlog_files_counter"), ".");
321                 s = strcat(s, ftos(random()));
322                 GameLogEcho(strcat(":gamestart:", GetMapname(), ":", s), FALSE);
323                 s = ":gameinfo:mutators:LIST";
324                 if(g_grappling_hook)
325                         s = strcat(s, ":grappling_hook");
326                 if(!cvar("g_use_ammunition"))
327                         s = strcat(s, ":no_use_ammunition");
328                 if(!cvar("g_pickup_items"))
329                         s = strcat(s, ":no_pickup_items");
330                 if(g_instagib)
331                         s = strcat(s, ":instagib");
332                 if(g_rocketarena)
333                         s = strcat(s, ":rockerarena");
334                 if(g_nixnex)
335                         s = strcat(s, ":nixnex");
336                 if(g_vampire)
337                         s = strcat(s, ":vampire");
338                 if(g_laserguided_missile)
339                         s = strcat(s, ":laserguided_missile");
340                 if(g_norecoil)
341                         s = strcat(s, ":norecoil");
342                 if(g_midair)
343                         s = strcat(s, ":midair");
344                 if(g_minstagib)
345                         s = strcat(s, ":minstagib");
346                 GameLogEcho(s, FALSE);
347                 GameLogEcho(":gameinfo:end", FALSE);
348         }
349
350         cvar_set("nextmap", "");
351
352         SetDefaultAlpha();
353
354         if(cvar("g_campaign"))
355                 CampaignPostInit();
356
357         fteqcc_testbugs();
358
359         readlevelcvars();
360
361         Ban_LoadBans();
362
363 #ifdef MAPINFO
364         MapInfo_Enumerate();
365         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 1);
366 #endif
367 }
368
369 void light (void)
370 {
371         //makestatic (self); // Who the f___ did that?
372         remove(self);
373 }
374
375 float( string pFilename ) TryFile =
376 {
377         local float lHandle;
378         dprint("TryFile(\"", pFilename, "\")\n");
379         lHandle = fopen( pFilename, FILE_READ );
380         if( lHandle != -1 ) {
381                 fclose( lHandle );
382                 return TRUE;
383         } else {
384                 return FALSE;
385         }
386 };
387
388 string GetGametype()
389 {
390         if (game == GAME_DEATHMATCH)
391                 return "dm";
392         else if (game == GAME_TEAM_DEATHMATCH)
393                 return "tdm";
394         else if (game == GAME_DOMINATION)
395                 return "dom";
396         else if (game == GAME_CTF)
397                 return "ctf";
398         else if (game == GAME_RUNEMATCH)
399                 return "rune";
400         else if (game == GAME_LMS)
401                 return "lms";
402         else if (game == GAME_KEYHUNT)
403                 return "kh";
404         else if (game == GAME_ONSLAUGHT)
405                 return "ons";
406         else if (game == GAME_ASSAULT)
407                 return "as";
408         return "dm";
409 }
410
411 float IsSameGametype(string mapcfgname)
412 {
413 #ifdef MAPINFO
414         return TRUE; // can't change game type by map name here
415 #else
416         string gt;
417         gt = GetGametype();
418         if(substring(mapcfgname, 0, strlen(gt) + 1) == strcat(gt, "_"))
419                 return TRUE;
420         return FALSE;
421 #endif
422 }
423
424 string getmapname_stored;
425 string GetMapname()
426 {
427 #ifdef MAPINFO
428         return mapname;
429 #else
430         if(getmapname_stored == "")
431                 getmapname_stored = strzone(strcat(GetGametype(), "_", mapname));
432         return getmapname_stored;
433 #endif
434 }
435
436 float Map_Count, Map_Current;
437 string Map_Current_Name;
438
439 // NOTE: this now expects the map list to be already tokenize()d and the count in Map_Count
440 float GetMaplistPosition()
441 {
442         float pos, idx;
443         string map;
444
445         map = GetMapname();
446         idx = cvar("g_maplist_index");
447
448         if(idx >= 0)
449                 if(idx < Map_Count)
450                         if(map == argv(idx))
451                                 return idx;
452
453         for(pos = 0; pos < Map_Count; ++pos)
454                 if(map == argv(pos))
455                         return pos;
456
457         // resume normal maplist rotation if current map is not in g_maplist
458         return idx;
459 }
460
461 float MapHasRightSize(string map)
462 {
463         // open map size restriction file
464         float fh;
465         dprint("opensize "); dprint(map);
466         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
467         if(fh >= 0)
468         {
469                 float mapmin, mapmax;
470                 dprint(": ok, ");
471                 mapmin = stof(fgets(fh));
472                 mapmax = stof(fgets(fh));
473                 fclose(fh);
474                 if(player_count < mapmin)
475                 {
476                         dprint("not enough\n");
477                         return FALSE;
478                 }
479                 if(player_count > mapmax)
480                 {
481                         dprint("too many\n");
482                         return FALSE;
483                 }
484                 dprint("right size\n");
485                 return TRUE;
486         }
487         dprint(": not found\n");
488         return TRUE;
489 }
490
491 #ifdef MAPINFO
492 #else
493 string Map_Filename(float position)
494 {
495         // FIXME unused
496         return strcat("maps/", argv(position), ".mapcfg");
497 }
498 #endif
499
500 string strwords(string s, float w)
501 {
502         float endpos;
503         for(endpos = 0; w && endpos >= 0; --w)
504                 endpos = strstrofs(s, " ", endpos + 1);
505         if(endpos < 0)
506                 return s;
507         else
508                 return substring(s, 0, endpos);
509 }
510
511 float strhasword(string s, string w)
512 {
513         return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
514 }
515
516 void Map_MarkAsRecent(string m)
517 {
518         cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", cvar_string("g_maplist_mostrecent")), cvar("g_maplist_mostrecent_count")));
519 }
520
521 float Map_IsRecent(string m)
522 {
523         return strhasword(cvar_string("g_maplist_mostrecent"), m);
524 }
525
526 float(float position, float pass) Map_Check =
527 {
528         string filename;
529         string map_next;
530         map_next = argv(position);
531         if(pass <= 1)
532         {
533                 if(map_next == Map_Current_Name) // same map again in first pass?
534                         return 0;
535                 if(Map_IsRecent(map_next))
536                         return 0;
537         }
538 #ifdef MAPINFO
539         if(MapInfo_CheckMap(argv(position)))
540 #else
541         filename = Map_Filename(position);
542         if(TryFile(filename))
543 #endif
544         {
545                 if(pass == 2)
546                         return 1;
547                 if(MapHasRightSize(argv(position)))
548                         return 1;
549                 return 0;
550         }
551         else
552                 dprint( "Couldn't find '", filename, "'..\n" );
553
554         return 0;
555 }
556
557 void(string nextmapname) Map_Goto_SetStr =
558 {
559         if(getmapname_stored != "")
560                 strunzone(getmapname_stored);
561         if(nextmapname == "")
562                 getmapname_stored = "";
563         else
564                 getmapname_stored = strzone(nextmapname);
565 }
566
567 void(float position) Map_Goto_SetFloat =
568 {
569         cvar_set("g_maplist_index", ftos(position));
570         Map_Goto_SetStr(argv(position));
571 }
572
573 void() GameResetCfg =
574 {
575 #ifdef MAPINFO
576         // settings persist, except...
577         if(cvar("g_campaign"))
578                 localcmd("\nexec mutator_reset.cfg\n");
579         localcmd("\nsettemp_restore\n");
580 #else
581         // if an exit cfg is defined by exiting map, exec it.
582         string exit_cfg;
583         exit_cfg = cvar_string("exit_cfg");
584         if(exit_cfg != "")
585                 localcmd(strcat("exec \"", exit_cfg, "\"\n"));
586
587         localcmd("exec game_reset.cfg\n");
588 #endif
589
590         Ban_SaveBans();
591 };
592
593 void() Map_Goto =
594 {
595         Map_MarkAsRecent(getmapname_stored);
596         GameResetCfg();
597 #ifdef MAPINFO
598         MapInfo_LoadMap(getmapname_stored);
599 #else
600         localcmd(strcat("exec \"maps/", getmapname_stored ,".mapcfg\"\n"));
601 #endif
602 }
603
604 // return codes of map selectors:
605 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
606 //   -2 = permanent failure
607 float() MaplistMethod_Iterate = // usual method
608 {
609         float pass, i;
610
611         for(pass = 1; pass <= 2; ++pass)
612         {
613                 for(i = 1; i < Map_Count; ++i)
614                 {
615                         float mapindex;
616                         mapindex = math_mod(i + Map_Current, Map_Count);
617                         if(Map_Check(mapindex, pass))
618                                 return mapindex;
619                 }
620         }
621         return -1;
622 }
623
624 float() MaplistMethod_Repeat = // fallback method
625 {
626         if(Map_Check(Map_Current, 2))
627                 return Map_Current;
628         return -2;
629 }
630
631 float() MaplistMethod_Random = // random map selection
632 {
633         float i, imax;
634
635         imax = 42;
636
637         for(i = 0; i <= imax; ++i)
638         {
639                 float mapindex;
640                 mapindex = math_mod(Map_Current + ceil(random() * (Map_Count - 1)), Map_Count); // any OTHER map
641                 if(Map_Check(mapindex, 1))
642                         return mapindex;
643         }
644         return -1;
645 }
646
647 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
648 // the exponent sets a bias on the map selection:
649 // the higher the exponent, the less likely "shortly repeated" same maps are
650 {
651         float i, j, imax, insertpos;
652
653         imax = 42;
654
655         if(Map_Count <= 1)
656                 return 0; // only one map, then always play this one
657
658         for(i = 0; i <= imax; ++i)
659         {
660                 string newlist;
661
662                 // now reinsert this at another position
663                 insertpos = pow(random(), 1 / exponent);       // ]0, 1]
664                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
665                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
666                 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
667
668                 // insert the current map there
669                 newlist = "";
670 #ifdef MAPINFO
671                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
672                         newlist = strcat(newlist, " ", argv(j));
673                 newlist = strcat(newlist, " ", argv(0));       // now insert the just selected map
674                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
675                         newlist = strcat(newlist, " ", argv(j));
676                 newlist = substring(newlist, 1, strlen(newlist) - 1);
677 #else
678                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
679                         newlist = strcat(newlist, "'", argv(j), "'");
680                 newlist = strcat(newlist, "'", argv(0), "'");  // now insert the just selected map
681                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
682                         newlist = strcat(newlist, "'", argv(j), "'");
683 #endif
684                 cvar_set("g_maplist", newlist);
685 #ifdef MAPINFO
686                 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
687 #else
688                 Map_Count = tokenize(newlist);
689 #endif
690
691                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
692                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
693                 if(Map_Check(Map_Current, 1))
694                         return Map_Current;
695         }
696         return -1;
697 }
698
699 void() Maplist_Init =
700 {
701         string temp;
702         temp = cvar_string("g_maplist");
703 #ifdef MAPINFO
704         Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
705 #else
706         Map_Count = tokenize(temp);
707 #endif
708         if(Map_Count == 0)
709         {
710                 bprint( "Maplist is empty!  Resetting it to default map list.\n" );
711 #ifdef MAPINFO
712                 cvar_set("g_maplist", temp = MapInfo_ListAllowedMaps());
713                 localcmd("\nmenu_cmd sync\n");
714                 Map_Count = tokenizebyseparator(temp, " ");
715 #else
716                 cvar_set("g_maplist", temp = cvar_string("g_maplist_defaultlist"));
717                 Map_Count = tokenize(temp);
718 #endif
719         }
720         if(Map_Count == 0)
721                 error("empty maplist, cannot select a new map");
722         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
723
724         Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
725         // this may or may not be correct, but who cares, in the worst case a map
726         // isn't chosen in the first pass that should have been
727 }
728
729 string() GetNextMap =
730 {
731         float nextMap;
732
733         Maplist_Init();
734         nextMap = -1;
735
736         if(nextMap == -1)
737                 if(cvar("g_maplist_shuffle") > 0)
738                         nextMap = MaplistMethod_Shuffle(cvar("g_maplist_shuffle") + 1);
739
740         if(nextMap == -1)
741                 if(cvar("g_maplist_selectrandom"))
742                         nextMap = MaplistMethod_Random();
743
744         if(nextMap == -1)
745                 nextMap = MaplistMethod_Iterate();
746
747         if(nextMap == -1)
748                 nextMap = MaplistMethod_Repeat();
749
750         if(nextMap >= 0)
751         {
752                 Map_Goto_SetFloat(nextMap);
753                 return getmapname_stored;
754         }
755
756         return "";
757 };
758
759 float() DoNextMapOverride =
760 {
761         Ban_SaveBans();
762
763         if(cvar("g_campaign"))
764         {
765                 CampaignPostIntermission();
766                 alreadychangedlevel = TRUE;
767                 return TRUE;
768         }
769         if(cvar("quit_when_empty"))
770         {
771                 if(player_count <= currentbots)
772                 {
773                         localcmd("quit\n");
774                         alreadychangedlevel = TRUE;
775                         return TRUE;
776                 }
777         }
778         if(cvar_string("quit_and_redirect") != "")
779         {
780                 redirection_target = strzone(cvar_string("quit_and_redirect"));
781                 alreadychangedlevel = TRUE;
782                 return TRUE;
783         }
784         if (cvar("samelevel")) // if samelevel is set, stay on same level
785         {
786                 // this does not work because it tries to exec maps/nexdm01.mapcfg (which doesn't exist, it should be trying maps/dm_nexdm01.mapcfg for example)
787                 //localcmd(strcat("exec \"maps/", mapname, ".mapcfg\"\n"));
788                 // so instead just restart the current map using the restart command (DOES NOT WORK PROPERLY WITH exit_cfg STUFF)
789                 localcmd("restart\n");
790                 //changelevel (mapname);
791                 alreadychangedlevel = TRUE;
792                 return TRUE;
793         }
794         if(cvar_string("nextmap") != "")
795 #ifdef MAPINFO
796                 if(MapInfo_CheckMap(cvar_string("nextmap")))
797 #else
798                 if(TryFile(strcat("maps/", cvar_string("nextmap"), ".mapcfg")))
799 #endif
800                 {
801                         Map_Goto_SetStr(cvar_string("nextmap"));
802                         Map_Goto();
803                         alreadychangedlevel = TRUE;
804                         return TRUE;
805                 }
806         if(cvar("lastlevel"))
807         {
808                 GameResetCfg();
809                 localcmd("set lastlevel 0\ntogglemenu\n");
810                 alreadychangedlevel = TRUE;
811                 return TRUE;
812         }
813         return FALSE;
814 };
815
816 void() GotoNextMap =
817 {
818         //local string nextmap;
819         //local float n, nummaps;
820         //local string s;
821         if (alreadychangedlevel)
822                 return;
823         alreadychangedlevel = TRUE;
824
825         {
826                 string nextMap;
827                 float allowReset;
828
829                 for(allowReset = 1; allowReset >= 0; --allowReset)
830                 {
831                         nextMap = GetNextMap();
832                         if(nextMap != "")
833                                 break;
834
835                         if(allowReset)
836                         {
837                                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
838 #ifdef MAPINFO
839                                 cvar_set("g_maplist", MapInfo_ListAllowedMaps());
840                                 localcmd("\nmenu_cmd sync\n");
841 #else
842                                 cvar_set("g_maplist", cvar_string("g_maplist_defaultlist"));
843 #endif
844                         }
845                         else
846                         {
847                                 error("Everything is broken - not even the default map list works. Please report this to the developers.");
848                         }
849                 }
850                 Map_Goto();
851         }
852 };
853
854
855 /*
856 ============
857 IntermissionThink
858
859 When the player presses attack or jump, change to the next level
860 ============
861 */
862 .float autoscreenshot;
863 void() MapVote_Start;
864 void() MapVote_Think;
865 float mapvote_initialized;
866 void() IntermissionThink =
867 {
868         FixIntermissionClient(self);
869
870         if(cvar("sv_autoscreenshot"))
871         if(self.autoscreenshot > 0)
872         if(time > self.autoscreenshot)
873         {
874                 self.autoscreenshot = -1;
875                 if(clienttype(self) == CLIENTTYPE_REAL)
876                         stuffcmd(self, "\nscreenshot\necho \"^5A screenshot has been taken at request of the server.\"\n");
877                 return;
878         }
879
880         if (time < intermission_exittime)
881                 return;
882
883         if(!mapvote_initialized)
884                 if (time < intermission_exittime + 10 && !self.button0 && !self.button2 && !self.button3 && !self.button6 && !self.buttonuse)
885                         return;
886
887         MapVote_Start();
888 };
889
890 /*
891 ============
892 FindIntermission
893
894 Returns the entity to view from
895 ============
896 */
897 /*
898 entity() FindIntermission =
899 {
900         local   entity spot;
901         local   float cyc;
902
903 // look for info_intermission first
904         spot = find (world, classname, "info_intermission");
905         if (spot)
906         {       // pick a random one
907                 cyc = random() * 4;
908                 while (cyc > 1)
909                 {
910                         spot = find (spot, classname, "info_intermission");
911                         if (!spot)
912                                 spot = find (spot, classname, "info_intermission");
913                         cyc = cyc - 1;
914                 }
915                 return spot;
916         }
917
918 // then look for the start position
919         spot = find (world, classname, "info_player_start");
920         if (spot)
921                 return spot;
922
923 // testinfo_player_start is only found in regioned levels
924         spot = find (world, classname, "testplayerstart");
925         if (spot)
926                 return spot;
927
928 // then look for the start position
929         spot = find (world, classname, "info_player_deathmatch");
930         if (spot)
931                 return spot;
932
933         //objerror ("FindIntermission: no spot");
934         return world;
935 };
936 */
937
938 /*
939 ===============================================================================
940
941 RULES
942
943 ===============================================================================
944 */
945
946 void(float final) DumpStats =
947 {
948         local float file;
949         local string s;
950         local float to_console;
951         local float to_eventlog;
952         local float to_file;
953
954         to_console = cvar("sv_logscores_console");
955         to_eventlog = cvar("sv_eventlog");
956         to_file = cvar("sv_logscores_file");
957
958         if(!final)
959         {
960                 to_console = TRUE; // always print printstats replies
961                 to_eventlog = FALSE; // but never print them to the event log
962         }
963
964         if(to_eventlog)
965                 if(cvar("sv_eventlog_console"))
966                         to_console = FALSE; // otherwise we get the output twice
967
968         if(final)
969                 s = ":scores:";
970         else
971                 s = ":status:";
972         s = strcat(s, GetMapname(), ":", ftos(rint(time)));
973
974         if(to_console)
975                 ServerConsoleEcho(s, FALSE);
976         if(to_eventlog)
977                 GameLogEcho(s, FALSE);
978         if(to_file)
979         {
980                 file = fopen(cvar_string("sv_logscores_filename"), FILE_APPEND);
981                 if(file == -1)
982                         to_file = FALSE;
983                 else
984                         fputs(file, strcat(s, "\n"));
985         }
986
987         FOR_EACH_CLIENT(other)
988         {
989                 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && cvar("sv_logscores_bots")))
990                 {
991                         s = strcat(":player:", ftos(other.frags), ":");
992                         s = strcat(s, ftos(other.deaths), ":");
993                         s = strcat(s, ftos(rint(time - other.jointime)), ":");
994                         s = strcat(s, ftos(other.team), ":");
995
996                         if(to_console)
997                                 ServerConsoleEcho(strcat(s, other.netname), TRUE);
998                         if(to_eventlog)
999                                 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname), TRUE);
1000                         if(to_file)
1001                                 fputs(file, strcat(s, other.netname, "\n"));
1002                 }
1003         }
1004
1005         if(to_console)
1006                 ServerConsoleEcho(":end", FALSE);
1007         if(to_eventlog)
1008                 GameLogEcho(":end", FALSE);
1009         if(to_file)
1010         {
1011                 fputs(file, ":end\n");
1012                 fclose(file);
1013         }
1014 }
1015
1016 void FixIntermissionClient(entity e)
1017 {
1018         if(!e.autoscreenshot) // initial call
1019         {
1020                 e.angles = e.v_angle;
1021                 e.angles_x = -e.angles_x;
1022                 e.autoscreenshot = time + 0.8;  // used for autoscreenshot
1023                 e.health = -2342;
1024                 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1025                 e.solid = SOLID_NOT;
1026                 e.movetype = MOVETYPE_NONE;
1027                 e.takedamage = DAMAGE_NO;
1028                 if(e.weaponentity)
1029                         e.weaponentity.effects = EF_NODRAW;
1030                 stuffcmd(e, "\nscr_printspeed 1000000\n");
1031                 if(clienttype(e) == CLIENTTYPE_REAL)
1032                 {
1033                         msg_entity = e;
1034                         WriteByte(MSG_ONE, SVC_INTERMISSION);
1035                 }
1036         }
1037
1038         //e.velocity = '0 0 0';
1039         //e.fixangle = TRUE;
1040
1041         // TODO halt weapon animation
1042 }
1043
1044
1045 /*
1046 go to the next level for deathmatch
1047 only called if a time or frag limit has expired
1048 */
1049 void() NextLevel =
1050 {
1051         float minTotalFrags;
1052         float maxTotalFrags;
1053         float score;
1054         float f;
1055
1056         gameover = TRUE;
1057
1058         intermission_running = 1;
1059
1060 // enforce a wait time before allowing changelevel
1061         if(player_count > 0)
1062                 intermission_exittime = time + cvar("sv_mapchange_delay");
1063         else
1064                 intermission_exittime = -1;
1065
1066         WriteByte (MSG_ALL, SVC_CDTRACK);
1067         WriteByte (MSG_ALL, 3);
1068         WriteByte (MSG_ALL, 3);
1069
1070         //pos = FindIntermission ();
1071
1072         VoteReset();
1073
1074         DumpStats(TRUE);
1075
1076         if(cvar("sv_eventlog"))
1077                 GameLogEcho(":gameover", FALSE);
1078
1079         GameLogClose();
1080
1081         FOR_EACH_CLIENT(other)
1082         {
1083                 FixIntermissionClient(other);
1084
1085                 if(other.winning)
1086                         bprint(other.netname, " ^7wins.\n");
1087         }
1088
1089         minTotalFrags = 0;
1090         maxTotalFrags = 0;
1091         FOR_EACH_PLAYER(other)
1092         {
1093                 if(maxTotalFrags < other.totalfrags)
1094                         maxTotalFrags = other.totalfrags;
1095                 if(minTotalFrags > other.totalfrags)
1096                         minTotalFrags = other.totalfrags;
1097         }
1098
1099         if(!currentbots)
1100         {
1101                 FOR_EACH_PLAYER(other)
1102                 {
1103                         score = (other.totalfrags - minTotalFrags) / max(maxTotalFrags - minTotalFrags, 1);
1104                         f = bound(0, other.play_time / max(time, 1), 1);
1105                         // store some statistics?
1106                 }
1107         }
1108
1109         if(cvar("g_campaign"))
1110                 CampaignPreIntermission();
1111
1112         // WriteByte (MSG_ALL, SVC_INTERMISSION);
1113 };
1114
1115 /*
1116 ============
1117 CheckRules_Player
1118
1119 Exit deathmatch games upon conditions
1120 ============
1121 */
1122 void() CheckRules_Player =
1123 {
1124         if (gameover)   // someone else quit the game already
1125                 return;
1126
1127         if(self.deadflag == DEAD_NO)
1128                 self.play_time += frametime;
1129
1130         // fixme: don't check players; instead check dom_team and ctf_team entities
1131         //   (div0: and that in CheckRules_World please)
1132 };
1133
1134 float checkrules_oneminutewarning;
1135 float checkrules_leaderfrags;
1136 float tdm_max_score, tdm_old_score;
1137
1138 float checkrules_equality;
1139 float checkrules_overtimewarning;
1140 float checkrules_overtimeend;
1141
1142 void() InitiateOvertime =
1143 {
1144         if(!checkrules_overtimeend)
1145                 checkrules_overtimeend = time + 60 * cvar("timelimit_maxovertime");
1146 }
1147
1148 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1149 float WINNING_YES = 1; // winner found
1150 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1151 float WINNING_STARTOVERTIME = 3; // no winner, enter overtime NOW
1152
1153 float(float fraglimitreached, float equality) GetWinningCode =
1154 {
1155         if(equality)
1156                 if(fraglimitreached)
1157                         return WINNING_STARTOVERTIME;
1158                 else
1159                         return WINNING_NEVER;
1160         else
1161                 if(fraglimitreached)
1162                         return WINNING_YES;
1163                 else
1164                         return WINNING_NO;
1165 }
1166
1167 // set the .winning flag for exactly those players with a given field value
1168 void(.float field, float value) SetWinners =
1169 {
1170         entity head;
1171         FOR_EACH_PLAYER(head)
1172                 head.winning = (head.field == value);
1173 }
1174
1175 // set the .winning flag for those players with a given field value
1176 void(.float field, float value) AddWinners =
1177 {
1178         entity head;
1179         FOR_EACH_PLAYER(head)
1180                 if(head.field == value)
1181                         head.winning = 1;
1182 }
1183
1184 // clear the .winning flags
1185 void(void) ClearWinners =
1186 {
1187         entity head;
1188         FOR_EACH_PLAYER(head)
1189                 head.winning = 0;
1190 }
1191
1192 // Onslaught winning condition:
1193 // game terminates if only one team has a working generator (or none)
1194 float() WinningCondition_Onslaught =
1195 {
1196         entity head;
1197         local float t1, t2, t3, t4;
1198         // first check if the game has ended
1199         t1 = t2 = t3 = t4 = 0;
1200         head = find(world, classname, "onslaught_generator");
1201         while (head)
1202         {
1203                 if (head.health > 0)
1204                 {
1205                         if (head.team == COLOR_TEAM1) t1 = 1;
1206                         if (head.team == COLOR_TEAM2) t2 = 1;
1207                         if (head.team == COLOR_TEAM3) t3 = 1;
1208                         if (head.team == COLOR_TEAM4) t4 = 1;
1209                 }
1210                 head = find(head, classname, "onslaught_generator");
1211         }
1212         if (t1 + t2 + t3 + t4 < 2)
1213         {
1214                 // game over, only one team remains (or none)
1215                 ClearWinners();
1216                 if (t1) SetWinners(team, COLOR_TEAM1);
1217                 if (t2) SetWinners(team, COLOR_TEAM2);
1218                 if (t3) SetWinners(team, COLOR_TEAM3);
1219                 if (t4) SetWinners(team, COLOR_TEAM4);
1220                 dprint("Have a winner, ending game.\n");
1221                 return WINNING_YES;
1222         }
1223
1224         // Two or more teams remain
1225         return WINNING_NO;
1226 }
1227
1228 float() LMS_NewPlayerLives =
1229 {
1230         float fl;
1231         fl = cvar("fraglimit");
1232         if(fl == 0)
1233                 fl = 999;
1234
1235         // first player has left the game for dying too much? Nobody else can get in.
1236         if(lms_lowest_lives < 1)
1237                 return FALSE;
1238
1239         if(!cvar("g_lms_join_anytime"))
1240                 if(lms_lowest_lives < fl - cvar("g_lms_last_join"))
1241                         return FALSE;
1242
1243         return bound(1, lms_lowest_lives, fl);
1244 }
1245
1246 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1247 // they win. Otherwise the defending team wins once the timelimit passes.
1248 void assault_new_round();
1249 float() WinningCondition_Assault =
1250 {
1251         local float status;
1252         status = WINNING_NO;
1253
1254         // as the timelimit has not yet passed just assume the defending team will win
1255         if(assault_attacker_team == COLOR_TEAM1)
1256         {
1257                 SetWinners(team, COLOR_TEAM2);
1258         }
1259         else
1260         {
1261                 SetWinners(team, COLOR_TEAM1);
1262         }       
1263                 
1264         local entity ent;
1265         ent = find(world, classname, "target_assault_roundend");
1266         if(ent)
1267         {
1268                 if(ent.winning) // round end has been triggered by attacking team
1269                 {
1270                         SetWinners(team, assault_attacker_team);
1271                         if(assault_attacker_team == COLOR_TEAM1)
1272                         {
1273                                 team1_score = team1_score + 50;
1274                         }
1275                         else
1276                         {
1277                                 team2_score = team2_score + 50;
1278                         }
1279
1280                         if(ent.cnt == 1) // this was the second round
1281                         {
1282                                 status = WINNING_YES;
1283                         }
1284                         else
1285                         {
1286                                 cvar_set("timelimit", ftos((2*time)/60));
1287                                 assault_new_round();
1288                         }
1289                 }               
1290         }
1291
1292         return status;
1293
1294 }
1295
1296
1297 // LMS winning condition: game terminates if and only if there's at most one
1298 // one player who's living lives. Top two scores being equal cancels the time
1299 // limit.
1300 float() WinningCondition_LMS =
1301 {
1302         entity head;
1303         float have_player;
1304         float have_players;
1305         float l;
1306
1307         have_player = FALSE;
1308         have_players = FALSE;
1309         l = LMS_NewPlayerLives();
1310
1311         head = find(world, classname, "player");
1312         if(head)
1313                 have_player = TRUE;
1314         head = find(head, classname, "player");
1315         if(head)
1316                 have_players = TRUE;
1317
1318         if(have_player)
1319         {
1320                 // we have at least one player
1321                 if(have_players)
1322                 {
1323                         // two or more active players - continue with the game
1324                 }
1325                 else
1326                 {
1327                         // exactly one player?
1328                         if(l)
1329                         {
1330                                 // but no game has taken place yet
1331                         }
1332                         else
1333                         {
1334                                 // a winner!
1335                                 ClearWinners(); SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1336                                 dprint("Have a winner, ending game.\n");
1337                                 return WINNING_YES;
1338                         }
1339                 }
1340         }
1341         else
1342         {
1343                 // nobody is playing at all...
1344                 if(l)
1345                 {
1346                         // wait for players...
1347                 }
1348                 else
1349                 {
1350                         // SNAFU (maybe a draw game?)
1351                         ClearWinners();
1352                         dprint("No players, ending game.\n");
1353                         return WINNING_YES;
1354                 }
1355         }
1356
1357         // When we get here, we have at least two players who are actually LIVING,
1358         // or one player who is still waiting for a victim to join the server. Now
1359         // check if the top two players have equal score.
1360
1361         checkrules_leaderfrags = 0;
1362         checkrules_equality = FALSE;
1363         FOR_EACH_PLAYER(head)
1364         {
1365                 if(head.frags > checkrules_leaderfrags)
1366                 {
1367                         checkrules_leaderfrags = head.frags;
1368                         checkrules_equality = FALSE;
1369                 }
1370                 else if(head.frags > 0 && head.frags == checkrules_leaderfrags)
1371                         checkrules_equality = TRUE;
1372         }
1373
1374         SetWinners(frags, checkrules_leaderfrags);
1375
1376         // The top two players have the same amount of lives? No timelimit then,
1377         // enter overtime...
1378
1379         if(checkrules_equality)
1380                 return WINNING_NEVER;
1381
1382         // Top two have different scores? Way to go for our beloved TIMELIMIT!
1383         return WINNING_NO;
1384 }
1385
1386 // DM winning condition: game terminates if a player reached the fraglimit,
1387 // unless the first two players have the same score. The latter case also
1388 // breaks the time limit.
1389 float(float fraglimit) WinningCondition_MaxIndividualScore =
1390 {
1391         float checkrules_oldleaderfrags;
1392         entity head;
1393
1394         checkrules_oldleaderfrags = checkrules_leaderfrags;
1395         checkrules_leaderfrags = 0;
1396         checkrules_equality = FALSE;
1397         FOR_EACH_PLAYER(head)
1398         {
1399                 if(head.frags > checkrules_leaderfrags)
1400                 {
1401                         checkrules_leaderfrags = head.frags;
1402                         checkrules_equality = FALSE;
1403                 }
1404                 else if(head.frags > 0 && head.frags == checkrules_leaderfrags)
1405                         checkrules_equality = TRUE;
1406         }
1407
1408         if(checkrules_leaderfrags > 0)
1409                 SetWinners(frags, checkrules_leaderfrags);
1410         else
1411                 ClearWinners();
1412
1413         if (!cvar("g_runematch"))
1414                 if (checkrules_leaderfrags != checkrules_oldleaderfrags)
1415                 {
1416                         if (checkrules_leaderfrags == fraglimit - 1)
1417                                 sound(world, CHAN_AUTO, "announcer/robotic/1fragleft.wav", 1, ATTN_NONE);
1418                         else if (checkrules_leaderfrags == fraglimit - 2)
1419                                 sound(world, CHAN_AUTO, "announcer/robotic/2fragsleft.wav", 1, ATTN_NONE);
1420                         else if (checkrules_leaderfrags == fraglimit - 3)
1421                                 sound(world, CHAN_AUTO, "announcer/robotic/3fragsleft.wav", 1, ATTN_NONE);
1422                 }
1423
1424         return GetWinningCode(fraglimit && checkrules_leaderfrags >= fraglimit, checkrules_equality);
1425 }
1426
1427 float(float fraglimit) WinningConditionBase_Teamplay =
1428 {
1429         tdm_old_score = tdm_max_score;
1430         tdm_max_score = max4(team1_score, team2_score, team3_score, team4_score);
1431
1432         checkrules_equality =
1433         (
1434                 (tdm_max_score > 0)
1435                 &&
1436                 (
1437                           (team1_score == tdm_max_score)
1438                         + (team2_score == tdm_max_score)
1439                         + (team3_score == tdm_max_score)
1440                         + (team4_score == tdm_max_score)
1441                         >= 2));
1442
1443         ClearWinners();
1444         if(tdm_max_score > 0)
1445         {
1446                 if(team1_score == tdm_max_score)
1447                         AddWinners(team, COLOR_TEAM1);
1448                 if(team2_score == tdm_max_score)
1449                         AddWinners(team, COLOR_TEAM2);
1450                 if(team3_score == tdm_max_score)
1451                         AddWinners(team, COLOR_TEAM3);
1452                 if(team4_score == tdm_max_score)
1453                         AddWinners(team, COLOR_TEAM4);
1454         }
1455
1456         if(!cvar("g_runematch") && !cvar("g_domination"))
1457                 if(tdm_max_score != tdm_old_score)
1458                 {
1459                         if(tdm_max_score == fraglimit - 1)
1460                                 sound(world, CHAN_AUTO, "announcer/robotic/1fragleft.wav", 1, ATTN_NONE);
1461                         else if(tdm_max_score == fraglimit - 2)
1462                                 sound(world, CHAN_AUTO, "announcer/robotic/2fragsleft.wav", 1, ATTN_NONE);
1463                         else if(tdm_max_score == fraglimit - 3)
1464                                 sound(world, CHAN_AUTO, "announcer/robotic/3fragsleft.wav", 1, ATTN_NONE);
1465                 }
1466
1467         return GetWinningCode(fraglimit && tdm_max_score >= fraglimit, checkrules_equality);
1468 }
1469
1470 // TDM winning condition: game terminates if a team's score sum reached the
1471 // fraglimit, unless the first two teams have the same total score. The latter
1472 // case also breaks the time limit.
1473 float(float fraglimit) WinningCondition_MaxTeamSum =
1474 {
1475         entity head;
1476
1477         team1_score = team2_score = team3_score = team4_score = 0;
1478
1479         FOR_EACH_PLAYER(head)
1480         {
1481                 if(head.team == COLOR_TEAM1)
1482                         team1_score += head.frags;
1483                 else if(head.team == COLOR_TEAM2)
1484                         team2_score += head.frags;
1485                 else if(head.team == COLOR_TEAM3)
1486                         team3_score += head.frags;
1487                 else if(head.team == COLOR_TEAM4)
1488                         team4_score += head.frags;
1489         }
1490
1491         return WinningConditionBase_Teamplay(fraglimit);
1492 }
1493
1494 // DOM/CTF winning condition: game terminates if the max of a team's players'
1495 // score reached the fraglimit, unless the first two teams have the same
1496 // maximum score. The latter case also breaks the time limit.
1497 float(float fraglimit) WinningCondition_MaxTeamMax =
1498 {
1499         entity head;
1500
1501         team1_score = team2_score = team3_score = team4_score = 0;
1502
1503         FOR_EACH_PLAYER(head)
1504         {
1505                 if(head.team == COLOR_TEAM1)
1506                 {
1507                         if(head.frags > team1_score)
1508                                 team1_score = head.frags;
1509                 }
1510                 else if(head.team == COLOR_TEAM2)
1511                 {
1512                         if(head.frags > team2_score)
1513                                 team2_score = head.frags;
1514                 }
1515                 else if(head.team == COLOR_TEAM3)
1516                 {
1517                         if(head.frags > team3_score)
1518                                 team3_score = head.frags;
1519                 }
1520                 else if(head.team == COLOR_TEAM4)
1521                 {
1522                         if(head.frags > team4_score)
1523                                 team4_score = head.frags;
1524                 }
1525         }
1526
1527         return WinningConditionBase_Teamplay(fraglimit);
1528 }
1529
1530 void print_to(entity e, string s)
1531 {
1532         if(e)
1533                 sprint(e, strcat(s, "\n"));
1534         else
1535                 ServerConsoleEcho(s, TRUE);
1536 }
1537
1538 void PrintScoreboardFor(entity e, string name, string colorcode, float whichteam)
1539 {
1540         entity head;
1541         float v;
1542         float teamvalue;
1543         float fragtotal;
1544         string s;
1545         float found;
1546         found = FALSE;
1547         teamvalue = 0;
1548         FOR_EACH_PLAYER(head)
1549         {
1550                 if(!whichteam || head.team == whichteam)
1551                 {
1552                         if(name != "")
1553                                 if(!found)
1554                                         print_to(e, strcat(" ", colorcode, name, ":"));
1555                         found = TRUE;
1556                         fragtotal = fragtotal + head.frags;
1557                         s = ftos(head.frags);
1558                         s = strcat(s, "/", ftos(head.deaths));
1559                         s = strcat(s, " @ ", ftos(head.ping));
1560                         if(clienttype(head) == CLIENTTYPE_BOT)
1561                                 s = strcat(s, "botms");
1562                         else
1563                                 s = strcat(s, "ms");
1564                         v = PlayerValue(head);
1565                         teamvalue += v;
1566                         s = strcat(s, " / ", ftos(v));
1567                         print_to(e, strcat("  ", colorcode, head.netname, colorcode, " (", s, ")"));
1568                 }
1569         }
1570         if(whichteam && found)
1571         {
1572                 s = ftos(fragtotal);
1573                 s = strcat(s, " / ", ftos(teamvalue));
1574                 print_to(e, strcat(colorcode, "  (total: ", s, ")"));
1575         }
1576 }
1577
1578 void PrintScoreboard(entity e)
1579 {
1580         print_to(e, strcat("Time:      ", ftos(time / 60)));
1581         print_to(e, strcat("Timelimit: ", ftos(cvar("timelimit"))));
1582         print_to(e, strcat("Fraglimit: ", ftos(cvar("fraglimit"))));
1583         print_to(e, "Scoreboard:");
1584         if(teams_matter)
1585         {
1586                 PrintScoreboardFor(e, "Red", "^1", COLOR_TEAM1);
1587                 PrintScoreboardFor(e, "Blue", "^4", COLOR_TEAM2);
1588                 PrintScoreboardFor(e, "Yellow", "^3", COLOR_TEAM3);
1589                 PrintScoreboardFor(e, "Pink", "^6", COLOR_TEAM4);
1590         }
1591         else
1592         {
1593                 PrintScoreboardFor(e, "", "^7", 0);
1594         }
1595         print_to(e, ".");
1596 }
1597
1598 void ShuffleMaplist()
1599 {
1600         string result;
1601         float start;
1602         float litems;
1603         float selected;
1604         float i;
1605
1606         result = cvar_string("g_maplist");
1607 #ifdef MAPINFO
1608         litems = tokenizebyseparator(result, " ");
1609 #else
1610         litems = tokenize(result);
1611 #endif
1612
1613         for(start = 0; start < litems - 1; ++start)
1614         {
1615                 result = "";
1616
1617                 // select a random item
1618                 selected = ceil(random() * (litems - start) + start) - 1;
1619
1620                 // shift this item to the place start
1621 #ifdef MAPINFO
1622                 for(i = 0; i < start; ++i)
1623                         result = strcat(result, " ", argv(i));
1624                 result = strcat(result, " ", argv(selected));
1625                 for(i = start; i < litems; ++i)
1626                         if(i != selected)
1627                                 result = strcat(result, " ", argv(i));
1628                 result = substring(result, 1, strlen(result) - 1);
1629
1630                 litems = tokenizebyseparator(result, " ");
1631 #else
1632                 for(i = 0; i < start; ++i)
1633                         result = strcat(result, "'", argv(i), "'");
1634                 result = strcat(result, "'", argv(selected), "'");
1635                 for(i = start; i < litems; ++i)
1636                         if(i != selected)
1637                                 result = strcat(result, "'", argv(i), "'");
1638
1639                 litems = tokenize(result);
1640 #endif
1641
1642                 //dprint(result, "\n");
1643         }
1644
1645         cvar_set("g_maplist", result);
1646 }
1647
1648 /*
1649 ============
1650 CheckRules_World
1651
1652 Exit deathmatch games upon conditions
1653 ============
1654 */
1655 void() CheckRules_World =
1656 {
1657         local float status;
1658         local float timelimit;
1659         local float fraglimit;
1660
1661         VoteThink();
1662         MapVote_Think();
1663
1664         SetDefaultAlpha();
1665
1666         /*
1667         MapVote_Think should now do that part
1668         if (intermission_running)
1669                 if (time >= intermission_exittime + 60)
1670                 {
1671                         if(!DoNextMapOverride())
1672                                 GotoNextMap();
1673                         return;
1674                 }
1675         */
1676
1677         if (gameover)   // someone else quit the game already
1678         {
1679                 if(player_count == 0) // Nobody there? Then let's go to the next map
1680                         MapVote_Start();
1681                         // this will actually check the player count in the next frame
1682                         // again, but this shouldn't hurt
1683                 return;
1684         }
1685
1686         timelimit = cvar("timelimit") * 60;
1687         fraglimit = cvar("fraglimit");
1688
1689         if(checkrules_overtimeend)
1690         {
1691                 if(!checkrules_overtimewarning)
1692                 {
1693                         checkrules_overtimewarning = TRUE;
1694                         //sound(world, CHAN_AUTO, "announcer/robotic/1minuteremains.wav", 1, ATTN_NONE);
1695                         bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
1696                 }
1697         }
1698         else
1699         {
1700                 if (timelimit && time >= timelimit)
1701                         InitiateOvertime();
1702         }
1703
1704         if (checkrules_overtimeend && time >= checkrules_overtimeend)
1705         {
1706                 NextLevel();
1707                 return;
1708         }
1709
1710         if (!checkrules_oneminutewarning && timelimit > 0 && time > timelimit - 60)
1711         {
1712                 checkrules_oneminutewarning = TRUE;
1713                 sound(world, CHAN_AUTO, "announcer/robotic/1minuteremains.wav", 1, ATTN_NONE);
1714         }
1715
1716         status = WINNING_NO;
1717         if(g_assault)
1718         {
1719                 status = WinningCondition_Assault();
1720         }
1721         else if(g_lms)
1722         {
1723                 status = WinningCondition_LMS();
1724         }
1725         else if (g_onslaught)
1726         {
1727                 status = WinningCondition_Onslaught();
1728         }
1729         else
1730         {
1731                 if(teams_matter)
1732                 {
1733                         if(g_tdm || cvar("g_runematch") || g_ctf || cvar("g_domination") || g_keyhunt)
1734                                 status = WinningCondition_MaxTeamSum(fraglimit);
1735                         //else if()
1736                         //      status = WinningCondition_MaxTeamMax(fraglimit);
1737                         else
1738                         {
1739                                 dprint("div0: How can this happen?\n");
1740                                 status = WinningCondition_MaxTeamMax(fraglimit);
1741                         }
1742                 }
1743                 else
1744                         status = WinningCondition_MaxIndividualScore(fraglimit);
1745         }
1746
1747         if(status == WINNING_STARTOVERTIME)
1748         {
1749                 status = WINNING_NEVER;
1750                 InitiateOvertime();
1751         }
1752
1753         if(status == WINNING_NEVER)
1754                 // equality cases! Nobody wins if the overtime ends in a draw.
1755                 ClearWinners();
1756
1757         if(checkrules_overtimeend)
1758                 if(status != WINNING_NEVER || time >= checkrules_overtimeend)
1759                         status = WINNING_YES;
1760
1761         if(status == WINNING_YES)
1762                 NextLevel();
1763 };
1764
1765 float randsel_value;
1766 float randsel_priority;
1767 float randsel_count;
1768 void RandSel_Init()
1769 {
1770         randsel_value = -1;
1771         randsel_priority = -1;
1772         randsel_count = -1;
1773 }
1774 void RandSel_Add(float priority, float value)
1775 {
1776         if(priority > randsel_priority)
1777         {
1778                 randsel_priority = priority;
1779                 randsel_value = value;
1780                 randsel_count = 1;
1781         }
1782         else if(priority == randsel_priority)
1783         {
1784                 randsel_count += 1;
1785                 if(ceil(random() * randsel_count) == 1)
1786                         randsel_value = value;
1787         }
1788 }
1789
1790 float mapvote_nextthink;
1791 float mapvote_initialized;
1792 float mapvote_keeptwotime;
1793 float mapvote_timeout;
1794 string mapvote_message;
1795
1796 #define MAPVOTE_COUNT 10
1797 float mapvote_count;
1798 string mapvote_maps[MAPVOTE_COUNT];
1799 float mapvote_maps_suggested[MAPVOTE_COUNT];
1800 string mapvote_suggestions[MAPVOTE_COUNT];
1801 float mapvote_suggestion_ptr;
1802 float mapvote_maxlen;
1803 float mapvote_voters;
1804 float mapvote_votes[MAPVOTE_COUNT];
1805 float mapvote_run;
1806 .float mapvote;
1807
1808 void MapVote_ClearAllVotes()
1809 {
1810         FOR_EACH_CLIENT(other)
1811                 other.mapvote = 0;
1812 }
1813
1814 string MapVote_Suggest(string m)
1815 {
1816         float i;
1817         if(m == "")
1818                 return "That's not how to use this command.";
1819         if(!cvar("g_maplist_votable_suggestions"))
1820                 return "Suggestions are not accepted on this server.";
1821         if(mapvote_initialized)
1822                 return "Can't suggest - voting is already in progress!";
1823 #ifdef MAPINFO
1824         m = MapInfo_FixName(m);
1825         if(!m)
1826                 return "The map you suggested is not available on this server.";
1827 #endif
1828         if(!cvar("g_maplist_votable_suggestions_change_gametype"))
1829                 if(!IsSameGametype(m))
1830                         return "This server does not allow changing the game type by map suggestions.";
1831         if(!cvar("g_maplist_votable_override_mostrecent"))
1832                 if(Map_IsRecent(m))
1833                         return "This server does not allow for recent maps to be played again. Please be patient for some rounds.";
1834
1835 #ifdef MAPINFO
1836         if(!MapInfo_CheckMap(m))
1837                 return "The map you suggested does not support the current game mode.";
1838 #else
1839         if(!TryFile(strcat("maps/", m, ".mapcfg")))
1840                 return "The map you suggested is not available on this server.";
1841 #endif
1842         for(i = 0; i < mapvote_suggestion_ptr; ++i)
1843                 if(mapvote_suggestions[i] == m)
1844                         return "This map was already suggested.";
1845         if(mapvote_suggestion_ptr >= MAPVOTE_COUNT)
1846         {
1847                 i = ceil(random() * mapvote_suggestion_ptr) - 1;
1848         }
1849         else
1850         {
1851                 i = mapvote_suggestion_ptr;
1852                 mapvote_suggestion_ptr += 1;
1853         }
1854         if(mapvote_suggestions[i] != "")
1855                 strunzone(mapvote_suggestions[i]);
1856         mapvote_suggestions[i] = strzone(m);
1857         GameLogEcho(strcat(":vote:suggested:", m, ":", ftos(self.playerid), ":", self.netname), TRUE);
1858         return strcat("Suggestion of ", m, " accepted.");
1859 }
1860
1861 void MapVote_AddVotable(string nextMap, float isSuggestion)
1862 {
1863         float j;
1864         if(nextMap == "")
1865                 return;
1866         for(j = 0; j < mapvote_count; ++j)
1867                 if(mapvote_maps[j] == nextMap)
1868                         return;
1869         if(strlen(nextMap) > mapvote_maxlen)
1870                 mapvote_maxlen = strlen(nextMap);
1871         mapvote_maps[mapvote_count] = strzone(nextMap);
1872         mapvote_maps_suggested[mapvote_count] = isSuggestion;
1873         mapvote_count += 1;
1874 }
1875
1876 void MapVote_Init()
1877 {
1878         float i;
1879         float nmax, smax;
1880
1881         MapVote_ClearAllVotes();
1882
1883         nmax = min(MAPVOTE_COUNT, cvar("g_maplist_votable"));
1884         smax = min(nmax, cvar("g_maplist_votable_suggestions"));
1885         mapvote_count = 0;
1886
1887         for(i = 0; i < 100 && mapvote_count < smax; ++i)
1888                 MapVote_AddVotable(mapvote_suggestions[ceil(random() * mapvote_suggestion_ptr) - 1], TRUE);
1889
1890         for(i = 0; i < 100 && mapvote_count < nmax; ++i)
1891                 MapVote_AddVotable(GetNextMap(), FALSE);
1892
1893         if(mapvote_count == 0)
1894         {
1895                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
1896 #ifdef MAPINFO
1897                 cvar_set("g_maplist", MapInfo_ListAllowedMaps());
1898                 localcmd("\nmenu_cmd sync\n");
1899 #else
1900                 cvar_set("g_maplist", cvar_string("g_maplist_defaultlist"));
1901 #endif
1902                 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
1903                         MapVote_AddVotable(GetNextMap(), FALSE);
1904         }
1905
1906         //dprint("mapvote count is ", ftos(mapvote_count), "\n");
1907
1908         mapvote_keeptwotime = time + cvar("g_maplist_votable_keeptwotime");
1909         mapvote_timeout = time + cvar("g_maplist_votable_timeout");
1910         if(mapvote_count < 3 || mapvote_keeptwotime <= time)
1911                 mapvote_keeptwotime = 0;
1912         mapvote_message = "Choose a map and press its key!";
1913 }
1914 float MapVote_Finished(float mappos)
1915 {
1916         string result;
1917         float i;
1918
1919         result = strcat(":vote:finished:", mapvote_maps[mappos]);
1920         result = strcat(result, ":", ftos(mapvote_votes[mappos]), "::");
1921         for(i = 0; i < mapvote_count; ++i)
1922                 if(i != mappos)
1923                         if(mapvote_maps[i] != "")
1924                         {
1925                                 result = strcat(result, ":", mapvote_maps[i]);
1926                                 result = strcat(result, ":", ftos(mapvote_votes[i]));
1927                         }
1928         GameLogEcho(result, FALSE);
1929         if(mapvote_maps_suggested[mappos])
1930                 GameLogEcho(strcat(":vote:suggestion_accepted:", mapvote_maps[mappos]), FALSE);
1931
1932         FOR_EACH_REALCLIENT(other)
1933                 FixClientCvars(other);
1934
1935         Map_Goto_SetStr(mapvote_maps[mappos]);
1936         Map_Goto();
1937         alreadychangedlevel = TRUE;
1938         return TRUE;
1939 }
1940 void MapVote_CheckRules_1()
1941 {
1942         float i;
1943
1944         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
1945         {
1946                 //dprint("Map ", ftos(i), ": "); dprint(mapvote_maps[i], "\n");
1947                 mapvote_votes[i] = 0;
1948         }
1949
1950         mapvote_voters = 0;
1951         FOR_EACH_REALCLIENT(other)
1952         {
1953                 ++mapvote_voters;
1954                 if(other.mapvote)
1955                 {
1956                         i = other.mapvote - 1;
1957                         //dprint("Player ", other.netname, " vote = ", ftos(other.mapvote - 1), "\n");
1958                         mapvote_votes[i] = mapvote_votes[i] + 1;
1959                 }
1960         }
1961 }
1962
1963 float MapVote_CheckRules_2()
1964 {
1965         float i;
1966         float firstPlace, secondPlace;
1967         float firstPlaceVotes, secondPlaceVotes;
1968         string result;
1969
1970         RandSel_Init();
1971         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
1972                 RandSel_Add(mapvote_votes[i], i);
1973         firstPlace = randsel_value;
1974         firstPlaceVotes = randsel_priority;
1975         //dprint("First place: ", ftos(firstPlace), "\n");
1976         //dprint("First place votes: ", ftos(firstPlaceVotes), "\n");
1977
1978         RandSel_Init();
1979         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
1980                 if(i != firstPlace)
1981                         RandSel_Add(mapvote_votes[i], i);
1982         secondPlace = randsel_value;
1983         secondPlaceVotes = randsel_priority;
1984         //dprint("Second place: ", ftos(secondPlace), "\n");
1985         //dprint("Second place votes: ", ftos(secondPlaceVotes), "\n");
1986
1987         if(firstPlace == -1)
1988                 error("No first place in map vote... WTF?");
1989
1990         if(secondPlace == -1 || time > mapvote_timeout || (mapvote_voters - firstPlaceVotes) < firstPlaceVotes)
1991                 return MapVote_Finished(firstPlace);
1992
1993         if(mapvote_keeptwotime)
1994                 if(time > mapvote_keeptwotime || (mapvote_voters - firstPlaceVotes - secondPlaceVotes) < secondPlaceVotes)
1995                 {
1996                         mapvote_message = "Now decide between the TOP TWO!";
1997                         mapvote_keeptwotime = 0;
1998                         result = strcat(":vote:keeptwo:", mapvote_maps[firstPlace]);
1999                         result = strcat(result, ":", ftos(firstPlaceVotes));
2000                         result = strcat(result, ":", mapvote_maps[secondPlace]);
2001                         result = strcat(result, ":", ftos(secondPlaceVotes), "::");
2002                         for(i = 0; i < mapvote_count; ++i)
2003                                 if(i != firstPlace)
2004                                         if(i != secondPlace)
2005                                                 if(mapvote_maps[i] != "")
2006                                                 {
2007                                                         result = strcat(result, ":", mapvote_maps[i]);
2008                                                         result = strcat(result, ":", ftos(mapvote_votes[i]));
2009                                                         strunzone(mapvote_maps[i]);
2010                                                         mapvote_maps[i] = "";
2011                                                 }
2012                         GameLogEcho(result, FALSE);
2013                 }
2014
2015         return FALSE;
2016 }
2017 void MapVote_Tick()
2018 {
2019         string msgstr;
2020         string tmp;
2021         float i;
2022         float keeptwo;
2023
2024         keeptwo = mapvote_keeptwotime;
2025         MapVote_CheckRules_1(); // count
2026         if(MapVote_CheckRules_2()) // decide
2027                 return;
2028
2029         FOR_EACH_REALCLIENT(other)
2030         {
2031                 // hide scoreboard again
2032                 if(other.health != 2342)
2033                 {
2034                         other.health = 2342;
2035                         other.impulse = 0;
2036                         if(clienttype(other) == CLIENTTYPE_REAL)
2037                         {
2038                                 stuffcmd(other, "\nin_bind 7 1 \"impulse 1\"; in_bind 7 2 \"impulse 2\"; in_bind 7 3 \"impulse 3\"; in_bind 7 4 \"impulse 4\"; in_bind 7 5 \"impulse 5\"; in_bind 7 6 \"impulse 6\"; in_bind 7 7 \"impulse 7\"; in_bind 7 8 \"impulse 8\"; in_bind 7 9 \"impulse 9\"; in_bind 7 0 \"impulse 10\"; in_bind 7 KP_1 \"impulse 1\"; in_bind 7 KP_2 \"impulse 2\"; in_bind 7 KP_3 \"impulse 3\"; in_bind 7 KP_4 \"impulse 4\"; in_bind 7 KP_5 \"impulse 5\"; in_bind 7 KP_6 \"impulse 6\"; in_bind 7 KP_7 \"impulse 7\"; in_bind 7 KP_8 \"impulse 8\"; in_bind 7 KP_9 \"impulse 9\"; in_bind 7 KP_0 \"impulse 10\"; in_bindmap 7 0\n");
2039                                 msg_entity = other;
2040                                 WriteByte(MSG_ONE, SVC_FINALE);
2041                                 WriteString(MSG_ONE, "");
2042                                 /*
2043                                 for(i = 0; i < mapvote_count; ++i)
2044                                         if(mapvote_maps[i] != "")
2045                                         {
2046                                                 tmp = mapvote_maps[i];
2047                                                 sprint(other, strcat("map voting: type ^1impulse ", ftos(i+1), "^7 to vote for ", tmp, "\n"));
2048                                         }
2049                                 */
2050                         }
2051                 }
2052
2053                 // notify about keep-two
2054                 if(keeptwo != 0 && mapvote_keeptwotime == 0)
2055                         play2(other, "misc/invshot.wav");
2056
2057                 // clear possibly invalid votes
2058                 if(mapvote_maps[other.mapvote - 1] == "")
2059                         other.mapvote = 0;
2060                 // use impulses as new vote
2061                 if(other.impulse >= 1 && other.impulse <= mapvote_count)
2062                         if(mapvote_maps[other.impulse - 1] != "")
2063                                 other.mapvote = other.impulse;
2064                 other.impulse = 0;
2065         }
2066
2067         MapVote_CheckRules_1(); // just count
2068
2069         FOR_EACH_REALCLIENT(other)
2070         {
2071                 // display voting screen
2072                 msgstr = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
2073                 msgstr = substring(msgstr, 0, strlen(msgstr) - mapvote_count);
2074                 msgstr = strcat(msgstr, mapvote_message);
2075                 msgstr = strcat(msgstr, "\n\n");
2076                 for(i = 0; i < mapvote_count; ++i)
2077                         if(mapvote_maps[i] == "")
2078                                 msgstr = strcat(msgstr, "\n");
2079                         else
2080                         {
2081                                 tmp = mapvote_maps[i];
2082                                 tmp = strpad(mapvote_maxlen, tmp);
2083                                 tmp = strcat(ftos(math_mod(i + 1, 10)), ": ", tmp);
2084                                 tmp = strcat(tmp, " ^2(", ftos(mapvote_votes[i]), " vote");
2085                                 if(mapvote_votes[i] != 1)
2086                                         tmp = strcat(tmp, "s");
2087                                 tmp = strcat(tmp, ")");
2088                                 tmp = strpad(mapvote_maxlen + 15, tmp);
2089                                 if(other.mapvote == i + 1)
2090                                         msgstr = strcat(msgstr, "^3> ", tmp, "\n");
2091                                 else
2092                                         msgstr = strcat(msgstr, "^7  ", tmp, "\n");
2093                         }
2094                 i = ceil(mapvote_timeout - time);
2095                 msgstr = strcat(msgstr, "\n\n", ftos(i), " second");
2096                 if(i != 1)
2097                         msgstr = strcat(msgstr, "s");
2098                 msgstr = strcat(msgstr, " left");
2099
2100                 centerprint_atprio(other, CENTERPRIO_MAPVOTE, msgstr);
2101         }
2102 }
2103 void MapVote_Start()
2104 {
2105         if(mapvote_run)
2106                 return;
2107
2108 #ifdef MAPINFO
2109         MapInfo_Enumerate();
2110         if(MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 1))
2111 #endif
2112                 mapvote_run = TRUE;
2113 }
2114 void MapVote_Think()
2115 {
2116         if(!mapvote_run)
2117                 return;
2118
2119         if(alreadychangedlevel)
2120                 return;
2121
2122         if(time < mapvote_nextthink)
2123                 return;
2124         //dprint("tick\n");
2125
2126         mapvote_nextthink = time + 0.5;
2127
2128         if(!mapvote_initialized)
2129         {
2130                 mapvote_initialized = TRUE;
2131                 if(DoNextMapOverride())
2132                         return;
2133                 if(!cvar("g_maplist_votable") || player_count <= 0)
2134                 {
2135                         GotoNextMap();
2136                         return;
2137                 }
2138                 MapVote_Init();
2139         }
2140
2141         MapVote_Tick();
2142 };
2143
2144 string GotoMap(string m)
2145 {
2146 #ifdef MAPINFO
2147         if(!MapInfo_CheckMap(m))
2148 #else
2149         if(!TryFile(strcat("maps/", m, ".mapcfg")))
2150 #endif
2151                 return "The map you chose is not available on this server.";
2152         cvar_set("nextmap", m);
2153         cvar_set("timelimit", "-1");
2154         if(mapvote_initialized || alreadychangedlevel)
2155         {
2156                 if(DoNextMapOverride())
2157                         return "Map switch initiated.";
2158                 else
2159                         return "Hm... no. For some reason I like THIS map more.";
2160         }
2161         else
2162                 return "Map switch will happen after scoreboard.";
2163 }
2164
2165
2166 void EndFrame()
2167 {
2168         FOR_EACH_REALCLIENT(self)
2169         {
2170                 if(self.classname == "spectator")
2171                 {
2172                         if(self.enemy.hitsound)
2173                                 play2(self, "misc/hit.wav");
2174                 }
2175                 else
2176                 {
2177                         if(self.hitsound)
2178                                 play2(self, "misc/hit.wav");
2179                 }
2180         }
2181         FOR_EACH_CLIENT(self)
2182                 self.hitsound = FALSE;
2183 }
2184
2185
2186 /*
2187  * RedirectionThink:
2188  * returns TRUE if redirecting
2189  */
2190 float redirection_timeout;
2191 float redirection_nextthink;
2192 float RedirectionThink()
2193 {
2194         float clients_found;
2195
2196         if(redirection_target == "")
2197                 return FALSE;
2198
2199         if(!redirection_timeout)
2200         {
2201                 cvar_set("sv_public", "-2");
2202                 redirection_timeout = time + 0.5; // this will only try twice... should be able to keep more clients
2203                 if(redirection_target == "self")
2204                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2205                 else
2206                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2207         }
2208
2209         if(time < redirection_nextthink)
2210                 return TRUE;
2211
2212         redirection_nextthink = time + 1;
2213
2214         clients_found = 0;
2215         FOR_EACH_REALCLIENT(self)
2216         {
2217                 ServerConsoleEcho(strcat("Redirecting: sending connect command to ", self.netname), FALSE);
2218                 if(redirection_target == "self")
2219                         stuffcmd(self, "\ndisconnect; reconnect\n");
2220                 else
2221                         stuffcmd(self, strcat("\ndisconnect; connect ", redirection_target, "\n"));
2222                 ++clients_found;
2223         }
2224
2225         ServerConsoleEcho(strcat("Redirecting: ", ftos(clients_found), " clients left."), FALSE);
2226
2227         if(time > redirection_timeout || clients_found == 0)
2228                 localcmd("\nwait; wait; wait; quit\n");
2229
2230         return TRUE;
2231 }