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