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