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