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