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