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