]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/g_world.qc
race: let everyone complete his lap when the race is over; players who have completed...
[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.cnt = -10;
51         world.enemy = world;
52         world.enemy.cnt += 10;
53         if(world.cnt > 0.2 || world.cnt < -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.cnt = 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                                 play2all("announcer/robotic/prepareforbattle.wav");
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         readlevelcvars();
266         InitGameplayMode();
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         local float i;
940
941         to_console = cvar("sv_logscores_console");
942         to_eventlog = cvar("sv_eventlog");
943         to_file = cvar("sv_logscores_file");
944
945         if(!final)
946         {
947                 to_console = TRUE; // always print printstats replies
948                 to_eventlog = FALSE; // but never print them to the event log
949         }
950
951         if(to_eventlog)
952                 if(cvar("sv_eventlog_console"))
953                         to_console = FALSE; // otherwise we get the output twice
954
955         if(final)
956                 s = ":scores:";
957         else
958                 s = ":status:";
959 #ifdef MAPINFO
960         s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
961 #else
962         s = strcat(s, GetMapname(), ":", ftos(rint(time)));
963 #endif
964
965         if(to_console)
966                 ServerConsoleEcho(s, FALSE);
967         if(to_eventlog)
968                 GameLogEcho(s, FALSE);
969         if(to_file)
970         {
971                 file = fopen(cvar_string("sv_logscores_filename"), FILE_APPEND);
972                 if(file == -1)
973                         to_file = FALSE;
974                 else
975                         fputs(file, strcat(s, "\n"));
976         }
977
978         s = strcat(":labels:player:", GetPlayerScoreString(world, 0));
979         if(to_console)
980                 ServerConsoleEcho(s, TRUE);
981         if(to_eventlog)
982                 GameLogEcho(s, TRUE);
983         if(to_file)
984                 fputs(file, strcat(s, "\n"));
985
986         FOR_EACH_CLIENT(other)
987         {
988                 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && cvar("sv_logscores_bots")))
989                 {
990                         s = strcat(":player:see-labels:", GetPlayerScoreString(other, 0), ":");
991                         s = strcat(s, ftos(rint(time - other.jointime)), ":");
992                         if(other.classname == "player" || g_arena || g_lms)
993                                 s = strcat(s, ftos(other.team), ":");
994                         else
995                                 s = strcat(s, "spectator:");
996
997                         if(to_console)
998                                 ServerConsoleEcho(strcat(s, other.netname), TRUE);
999                         if(to_eventlog)
1000                                 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname), TRUE);
1001                         if(to_file)
1002                                 fputs(file, strcat(s, other.netname, "\n"));
1003                 }
1004         }
1005
1006         if(teamplay)
1007         {
1008                 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1009                 if(to_console)
1010                         ServerConsoleEcho(s, TRUE);
1011                 if(to_eventlog)
1012                         GameLogEcho(s, TRUE);
1013                 if(to_file)
1014                         fputs(file, strcat(s, "\n"));
1015         
1016                 for(i = 1; i < 16; ++i)
1017                 {
1018                         s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1019                         s = strcat(s, ":", ftos(i));
1020                         if(to_console)
1021                                 ServerConsoleEcho(s, TRUE);
1022                         if(to_eventlog)
1023                                 GameLogEcho(s, TRUE);
1024                         if(to_file)
1025                                 fputs(file, strcat(s, "\n"));
1026                 }
1027         }
1028
1029         if(to_console)
1030                 ServerConsoleEcho(":end", FALSE);
1031         if(to_eventlog)
1032                 GameLogEcho(":end", FALSE);
1033         if(to_file)
1034         {
1035                 fputs(file, ":end\n");
1036                 fclose(file);
1037         }
1038 }
1039
1040 void FixIntermissionClient(entity e)
1041 {
1042         string s;
1043         if(!e.autoscreenshot) // initial call
1044         {
1045                 e.angles = e.v_angle;
1046                 e.angles_x = -e.angles_x;
1047                 e.autoscreenshot = time + 0.8;  // used for autoscreenshot
1048                 e.health = -2342;
1049                 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1050                 e.solid = SOLID_NOT;
1051                 e.movetype = MOVETYPE_NONE;
1052                 e.takedamage = DAMAGE_NO;
1053                 if(e.weaponentity)
1054                         e.weaponentity.effects = EF_NODRAW;
1055                 if(clienttype(e) == CLIENTTYPE_REAL)
1056                 {
1057                         stuffcmd(e, "\nscr_printspeed 1000000\n");
1058                         s = cvar_string("sv_intermission_cdtrack");
1059                         if(s != "")
1060                                 stuffcmd(e, strcat("\ncd loop ", s, "\n"));
1061                         msg_entity = e;
1062                         WriteByte(MSG_ONE, SVC_INTERMISSION);
1063                 }
1064         }
1065
1066         //e.velocity = '0 0 0';
1067         //e.fixangle = TRUE;
1068
1069         // TODO halt weapon animation
1070 }
1071
1072
1073 /*
1074 go to the next level for deathmatch
1075 only called if a time or frag limit has expired
1076 */
1077 void NextLevel()
1078 {
1079         float minTotalFrags;
1080         float maxTotalFrags;
1081         float score;
1082         float f;
1083
1084         gameover = TRUE;
1085
1086         intermission_running = 1;
1087
1088 // enforce a wait time before allowing changelevel
1089         if(player_count > 0)
1090                 intermission_exittime = time + cvar("sv_mapchange_delay");
1091         else
1092                 intermission_exittime = -1;
1093
1094         /*
1095         WriteByte (MSG_ALL, SVC_CDTRACK);
1096         WriteByte (MSG_ALL, 3);
1097         WriteByte (MSG_ALL, 3);
1098         // done in FixIntermission
1099         */
1100
1101         //pos = FindIntermission ();
1102
1103         VoteReset();
1104
1105         DumpStats(TRUE);
1106
1107         if(cvar("sv_eventlog"))
1108                 GameLogEcho(":gameover", FALSE);
1109
1110         GameLogClose();
1111
1112         FOR_EACH_CLIENT(other)
1113         {
1114                 FixIntermissionClient(other);
1115
1116                 if(other.winning)
1117                         bprint(other.netname, " ^7wins.\n");
1118         }
1119
1120         minTotalFrags = 0;
1121         maxTotalFrags = 0;
1122         FOR_EACH_PLAYER(other)
1123         {
1124                 if(maxTotalFrags < other.totalfrags)
1125                         maxTotalFrags = other.totalfrags;
1126                 if(minTotalFrags > other.totalfrags)
1127                         minTotalFrags = other.totalfrags;
1128         }
1129
1130         if(!currentbots)
1131         {
1132                 FOR_EACH_PLAYER(other)
1133                 {
1134                         score = (other.totalfrags - minTotalFrags) / max(maxTotalFrags - minTotalFrags, 1);
1135                         f = bound(0, other.play_time / max(time, 1), 1);
1136                         // store some statistics?
1137                 }
1138         }
1139
1140         if(cvar("g_campaign"))
1141                 CampaignPreIntermission();
1142
1143         // WriteByte (MSG_ALL, SVC_INTERMISSION);
1144 };
1145
1146 /*
1147 ============
1148 CheckRules_Player
1149
1150 Exit deathmatch games upon conditions
1151 ============
1152 */
1153 .float fogtime;
1154 void CheckRules_Player()
1155 {
1156         if (gameover)   // someone else quit the game already
1157                 return;
1158
1159         if(self.deadflag == DEAD_NO)
1160                 self.play_time += frametime;
1161
1162         if(sv_foginterval)
1163         if(world.fog)
1164         if(time > self.fogtime)
1165         {
1166                 stuffcmd(self, strcat("\nfog ", world.fog, "\nr_fog_exp2 0\nr_drawfog 1\n"));
1167                 self.fogtime = time + sv_foginterval;
1168         }
1169
1170         // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1171         //   (div0: and that in CheckRules_World please)
1172 };
1173
1174 float checkrules_oneminutewarning;
1175 float checkrules_leaderfrags;
1176 float tdm_max_score, tdm_old_score;
1177
1178 float checkrules_equality;
1179 float checkrules_overtimewarning;
1180 float checkrules_overtimeend;
1181
1182 void InitiateOvertime()
1183 {
1184         if(!checkrules_overtimeend)
1185                 checkrules_overtimeend = time + 60 * cvar("timelimit_maxovertime");
1186 }
1187
1188 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1189 float WINNING_YES = 1; // winner found
1190 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1191 float WINNING_STARTOVERTIME = 3; // no winner, enter overtime NOW
1192
1193 float GetWinningCode(float fraglimitreached, float equality)
1194 {
1195         if(equality)
1196                 if(fraglimitreached)
1197                         return WINNING_STARTOVERTIME;
1198                 else
1199                         return WINNING_NEVER;
1200         else
1201                 if(fraglimitreached)
1202                         return WINNING_YES;
1203                 else
1204                         return WINNING_NO;
1205 }
1206
1207 // set the .winning flag for exactly those players with a given field value
1208 void SetWinners(.float field, float value)
1209 {
1210         entity head;
1211         FOR_EACH_PLAYER(head)
1212                 head.winning = (head.field == value);
1213 }
1214
1215 // set the .winning flag for those players with a given field value
1216 void AddWinners(.float field, float value)
1217 {
1218         entity head;
1219         FOR_EACH_PLAYER(head)
1220                 if(head.field == value)
1221                         head.winning = 1;
1222 }
1223
1224 // clear the .winning flags
1225 void ClearWinners(void)
1226 {
1227         entity head;
1228         FOR_EACH_PLAYER(head)
1229                 head.winning = 0;
1230 }
1231
1232 // Onslaught winning condition:
1233 // game terminates if only one team has a working generator (or none)
1234 float WinningCondition_Onslaught()
1235 {
1236         entity head;
1237         local float t1, t2, t3, t4;
1238         // first check if the game has ended
1239         t1 = t2 = t3 = t4 = 0;
1240         head = find(world, classname, "onslaught_generator");
1241         while (head)
1242         {
1243                 if (head.health > 0)
1244                 {
1245                         if (head.team == COLOR_TEAM1) t1 = 1;
1246                         if (head.team == COLOR_TEAM2) t2 = 1;
1247                         if (head.team == COLOR_TEAM3) t3 = 1;
1248                         if (head.team == COLOR_TEAM4) t4 = 1;
1249                 }
1250                 head = find(head, classname, "onslaught_generator");
1251         }
1252         if (t1 + t2 + t3 + t4 < 2)
1253         {
1254                 // game over, only one team remains (or none)
1255                 ClearWinners();
1256                 if (t1) SetWinners(team, COLOR_TEAM1);
1257                 if (t2) SetWinners(team, COLOR_TEAM2);
1258                 if (t3) SetWinners(team, COLOR_TEAM3);
1259                 if (t4) SetWinners(team, COLOR_TEAM4);
1260                 dprint("Have a winner, ending game.\n");
1261                 return WINNING_YES;
1262         }
1263
1264         // Two or more teams remain
1265         return WINNING_NO;
1266 }
1267
1268 float LMS_NewPlayerLives()
1269 {
1270         float fl;
1271         fl = cvar("fraglimit");
1272         if(fl == 0)
1273                 fl = 999;
1274
1275         // first player has left the game for dying too much? Nobody else can get in.
1276         if(lms_lowest_lives < 1)
1277                 return 0;
1278
1279         if(!cvar("g_lms_join_anytime"))
1280                 if(lms_lowest_lives < fl - cvar("g_lms_last_join"))
1281                         return 0;
1282
1283         return bound(1, lms_lowest_lives, fl);
1284 }
1285
1286 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1287 // they win. Otherwise the defending team wins once the timelimit passes.
1288 void assault_new_round();
1289 float WinningCondition_Assault()
1290 {
1291         local float status;
1292         status = WINNING_NO;
1293
1294         // as the timelimit has not yet passed just assume the defending team will win
1295         if(assault_attacker_team == COLOR_TEAM1)
1296         {
1297                 SetWinners(team, COLOR_TEAM2);
1298         }
1299         else
1300         {
1301                 SetWinners(team, COLOR_TEAM1);
1302         }
1303
1304         local entity ent;
1305         ent = find(world, classname, "target_assault_roundend");
1306         if(ent)
1307         {
1308                 if(ent.winning) // round end has been triggered by attacking team
1309                 {
1310                         SetWinners(team, assault_attacker_team);
1311                         if(assault_attacker_team == COLOR_TEAM1)
1312                         {
1313                                 team1_score = team1_score + 50;
1314                         }
1315                         else
1316                         {
1317                                 team2_score = team2_score + 50;
1318                         }
1319
1320                         if(ent.cnt == 1) // this was the second round
1321                         {
1322                                 status = WINNING_YES;
1323                         }
1324                         else
1325                         {
1326                                 local entity oldself;
1327                                 oldself = self;
1328                                 self = ent;
1329                                 cvar_set("timelimit", ftos((2*time)/60));
1330                                 assault_new_round();
1331                                 self = oldself;
1332                         }
1333                 }
1334         }
1335
1336         return status;
1337
1338 }
1339
1340 // LMS winning condition: game terminates if and only if there's at most one
1341 // one player who's living lives. Top two scores being equal cancels the time
1342 // limit.
1343 float WinningCondition_LMS()
1344 {
1345         entity head, head2;
1346         float have_player;
1347         float have_players;
1348         float l;
1349
1350         have_player = FALSE;
1351         have_players = FALSE;
1352         l = LMS_NewPlayerLives();
1353
1354         head = find(world, classname, "player");
1355         if(head)
1356                 have_player = TRUE;
1357         head2 = find(head, classname, "player");
1358         if(head2)
1359                 have_players = TRUE;
1360
1361         if(have_player)
1362         {
1363                 // we have at least one player
1364                 if(have_players)
1365                 {
1366                         // two or more active players - continue with the game
1367                 }
1368                 else
1369                 {
1370                         // exactly one player?
1371
1372                         ClearWinners();
1373                         SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1374
1375                         if(l)
1376                         {
1377                                 // game still running (that is, nobody got removed from the game by a frag yet)? then continue
1378                                 return WINNING_NO;
1379                         }
1380                         else
1381                         {
1382                                 // a winner!
1383                                 // and assign him his first place
1384                                 PlayerScore_Add(head, SP_LMS_RANK, 1);
1385                                 return WINNING_YES;
1386                         }
1387                 }
1388         }
1389         else
1390         {
1391                 // nobody is playing at all...
1392                 if(l)
1393                 {
1394                         // wait for players...
1395                 }
1396                 else
1397                 {
1398                         // SNAFU (maybe a draw game?)
1399                         ClearWinners();
1400                         dprint("No players, ending game.\n");
1401                         return WINNING_YES;
1402                 }
1403         }
1404
1405         // When we get here, we have at least two players who are actually LIVING,
1406         // now check if the top two players have equal score.
1407         WinningConditionHelper();
1408
1409         ClearWinners();
1410         if(WinningConditionHelper_winner)
1411                 WinningConditionHelper_winner.winning = TRUE;
1412         if(WinningConditionHelper_equality)
1413                 return WINNING_NEVER;
1414
1415         // Top two have different scores? Way to go for our beloved TIMELIMIT!
1416         return WINNING_NO;
1417 }
1418
1419 void print_to(entity e, string s)
1420 {
1421         if(e)
1422                 sprint(e, strcat(s, "\n"));
1423         else
1424                 ServerConsoleEcho(s, TRUE);
1425 }
1426
1427 void ShuffleMaplist()
1428 {
1429         string result;
1430         float start;
1431         float litems;
1432         float selected;
1433         float i;
1434
1435         result = cvar_string("g_maplist");
1436 #ifdef MAPINFO
1437         litems = tokenizebyseparator(result, " ");
1438 #else
1439         litems = tokenize(result);
1440 #endif
1441
1442         for(start = 0; start < litems - 1; ++start)
1443         {
1444                 result = "";
1445
1446                 // select a random item
1447                 selected = ceil(random() * (litems - start) + start) - 1;
1448
1449                 // shift this item to the place start
1450 #ifdef MAPINFO
1451                 for(i = 0; i < start; ++i)
1452                         result = strcat(result, " ", argv(i));
1453                 result = strcat(result, " ", argv(selected));
1454                 for(i = start; i < litems; ++i)
1455                         if(i != selected)
1456                                 result = strcat(result, " ", argv(i));
1457                 result = substring(result, 1, strlen(result) - 1);
1458
1459                 litems = tokenizebyseparator(result, " ");
1460 #else
1461                 for(i = 0; i < start; ++i)
1462                         result = strcat(result, "'", argv(i), "'");
1463                 result = strcat(result, "'", argv(selected), "'");
1464                 for(i = start; i < litems; ++i)
1465                         if(i != selected)
1466                                 result = strcat(result, "'", argv(i), "'");
1467
1468                 litems = tokenize(result);
1469 #endif
1470
1471                 //dprint(result, "\n");
1472         }
1473
1474         cvar_set("g_maplist", result);
1475 }
1476
1477 float WinningCondition_Scores(float limit)
1478 {
1479         // TODO make everything use THIS winning condition (except LMS)
1480         WinningConditionHelper();
1481         
1482         ClearWinners();
1483         if(WinningConditionHelper_winner)
1484                 WinningConditionHelper_winner.winning = 1;
1485         if(WinningConditionHelper_winnerteam >= 0)
1486                 SetWinners(team, WinningConditionHelper_winnerteam);
1487
1488         if(WinningConditionHelper_topscore == 0)
1489                 WinningConditionHelper_equality = 0;
1490         
1491         if(WinningConditionHelper_lowerisbetter)
1492         {
1493                 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1494                 limit = -limit;
1495         }
1496         
1497         return GetWinningCode(limit && WinningConditionHelper_topscore && (WinningConditionHelper_topscore >= limit), WinningConditionHelper_equality);
1498 }
1499
1500 float WinningCondition_Race(float fraglimit)
1501 {
1502         float wc;
1503         entity p;
1504         wc = WinningCondition_Scores(fraglimit);
1505
1506         // ALWAYS initiate overtime, unless EVERYONE has finished the race!
1507         if(wc == WINNING_YES || wc == WINNING_STARTOVERTIME)
1508         // do NOT support equality when the laps are all raced!
1509         {
1510                 FOR_EACH_PLAYER(p)
1511                         if not(p.race_completed)
1512                                 return WINNING_STARTOVERTIME;
1513                 return WINNING_YES;
1514         }
1515         return wc;
1516 }
1517
1518 float WinningCondition_RanOutOfSpawns()
1519 {
1520         entity head;
1521
1522         if(!have_team_spawns)
1523                 return WINNING_NO;
1524
1525         if(!some_spawn_has_been_used)
1526                 return WINNING_NO;
1527
1528         team1_score = team2_score = team3_score = team4_score = 0;
1529
1530         FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
1531         {
1532                 if(head.team == COLOR_TEAM1)
1533                         team1_score = 1;
1534                 else if(head.team == COLOR_TEAM2)
1535                         team2_score = 1;
1536                 else if(head.team == COLOR_TEAM3)
1537                         team3_score = 1;
1538                 else if(head.team == COLOR_TEAM4)
1539                         team4_score = 1;
1540         }
1541
1542         for(head = world; (head = find(head, classname, "info_player_deathmatch")) != world; )
1543         {
1544                 if(head.team == COLOR_TEAM1)
1545                         team1_score = 1;
1546                 else if(head.team == COLOR_TEAM2)
1547                         team2_score = 1;
1548                 else if(head.team == COLOR_TEAM3)
1549                         team3_score = 1;
1550                 else if(head.team == COLOR_TEAM4)
1551                         team4_score = 1;
1552         }
1553
1554         ClearWinners();
1555         if(team1_score + team2_score + team3_score + team4_score == 0)
1556         {
1557                 checkrules_equality = TRUE;
1558                 return WINNING_YES;
1559         }
1560         else if(team1_score + team2_score + team3_score + team4_score == 1)
1561         {
1562                 float t, i;
1563                 if(team1_score) t = COLOR_TEAM1;
1564                 if(team2_score) t = COLOR_TEAM2;
1565                 if(team3_score) t = COLOR_TEAM3;
1566                 if(team4_score) t = COLOR_TEAM4;
1567                 CheckAllowedTeams(world);
1568                 for(i = 0; i < MAX_TEAMSCORE; ++i)
1569                 {
1570                         if(t != COLOR_TEAM1) if(c1 >= 0) TeamScore_AddToTeam(COLOR_TEAM1, i, -1000);
1571                         if(t != COLOR_TEAM2) if(c2 >= 0) TeamScore_AddToTeam(COLOR_TEAM2, i, -1000);
1572                         if(t != COLOR_TEAM3) if(c3 >= 0) TeamScore_AddToTeam(COLOR_TEAM3, i, -1000);
1573                         if(t != COLOR_TEAM4) if(c4 >= 0) TeamScore_AddToTeam(COLOR_TEAM4, i, -1000);
1574                 }
1575
1576                 AddWinners(team, t);
1577                 return WINNING_YES;
1578         }
1579         else
1580                 return WINNING_NO;
1581 }
1582
1583 /*
1584 ============
1585 CheckRules_World
1586
1587 Exit deathmatch games upon conditions
1588 ============
1589 */
1590 void CheckRules_World()
1591 {
1592         local float status;
1593         local float timelimit;
1594         local float fraglimit;
1595
1596         VoteThink();
1597         MapVote_Think();
1598
1599         SetDefaultAlpha();
1600
1601         /*
1602         MapVote_Think should now do that part
1603         if (intermission_running)
1604                 if (time >= intermission_exittime + 60)
1605                 {
1606                         if(!DoNextMapOverride())
1607                                 GotoNextMap();
1608                         return;
1609                 }
1610         */
1611
1612         if (gameover)   // someone else quit the game already
1613         {
1614                 if(player_count == 0) // Nobody there? Then let's go to the next map
1615                         MapVote_Start();
1616                         // this will actually check the player count in the next frame
1617                         // again, but this shouldn't hurt
1618                 return;
1619         }
1620
1621         timelimit = cvar("timelimit") * 60;
1622         fraglimit = cvar("fraglimit");
1623
1624         if(checkrules_overtimeend)
1625         {
1626                 if(!checkrules_overtimewarning)
1627                 {
1628                         checkrules_overtimewarning = TRUE;
1629                         //announceall("announcer/robotic/1minuteremains.wav");
1630                         if(!g_race_qualifying)
1631                                 bcenterprint("^3Everyone, finish your lap! The race is over!");
1632                         else
1633                                 bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
1634                 }
1635         }
1636         else
1637         {
1638                 if (timelimit && time >= timelimit)
1639                         InitiateOvertime();
1640         }
1641
1642         if (checkrules_overtimeend && time >= checkrules_overtimeend)
1643         {
1644                 NextLevel();
1645                 return;
1646         }
1647
1648         if (!checkrules_oneminutewarning && timelimit > 0 && time > timelimit - 60)
1649         {
1650                 checkrules_oneminutewarning = TRUE;
1651                 play2all("announcer/robotic/1minuteremains.wav");
1652         }
1653
1654         status = WinningCondition_RanOutOfSpawns();
1655         if(status == WINNING_YES)
1656         {
1657                 bprint("Hey! Someone ran out of spawns!\n");
1658         }
1659         else if(g_race && !g_race_qualifying)
1660         {
1661                 status = WinningCondition_Race(fraglimit);
1662         }
1663         else if(g_assault)
1664         {
1665                 status = WinningCondition_Assault(); // TODO remove this?
1666         }
1667         else if(g_lms)
1668         {
1669                 status = WinningCondition_LMS();
1670         }
1671         else if (g_onslaught)
1672         {
1673                 status = WinningCondition_Onslaught(); // TODO remove this?
1674         }
1675         else
1676         {
1677                 status = WinningCondition_Scores(fraglimit);
1678         }
1679
1680         if(status == WINNING_STARTOVERTIME)
1681         {
1682                 status = WINNING_NEVER;
1683                 InitiateOvertime();
1684         }
1685
1686         if(status == WINNING_NEVER)
1687                 // equality cases! Nobody wins if the overtime ends in a draw.
1688                 ClearWinners();
1689
1690         if(checkrules_overtimeend)
1691                 if(status != WINNING_NEVER || time >= checkrules_overtimeend)
1692                         status = WINNING_YES;
1693
1694         if(status == WINNING_YES)
1695                 NextLevel();
1696 };
1697
1698 float mapvote_nextthink;
1699 float mapvote_initialized;
1700 float mapvote_keeptwotime;
1701 float mapvote_timeout;
1702 string mapvote_message;
1703 string mapvote_screenshot_dir;
1704
1705 float mapvote_count;
1706 float mapvote_count_real;
1707 string mapvote_maps[MAPVOTE_COUNT];
1708 float mapvote_maps_suggested[MAPVOTE_COUNT];
1709 string mapvote_suggestions[MAPVOTE_COUNT];
1710 float mapvote_suggestion_ptr;
1711 float mapvote_maxlen;
1712 float mapvote_voters;
1713 float mapvote_votes[MAPVOTE_COUNT];
1714 float mapvote_run;
1715 float mapvote_detail;
1716 float mapvote_abstain;
1717 float mapvote_dirty;
1718 .float mapvote;
1719
1720 void MapVote_ClearAllVotes()
1721 {
1722         FOR_EACH_CLIENT(other)
1723                 other.mapvote = 0;
1724 }
1725
1726 string MapVote_Suggest(string m)
1727 {
1728         float i;
1729         if(m == "")
1730                 return "That's not how to use this command.";
1731         if(!cvar("g_maplist_votable_suggestions"))
1732                 return "Suggestions are not accepted on this server.";
1733         if(mapvote_initialized)
1734                 return "Can't suggest - voting is already in progress!";
1735 #ifdef MAPINFO
1736         m = MapInfo_FixName(m);
1737         if(!m)
1738                 return "The map you suggested is not available on this server.";
1739 #else
1740         if(!cvar("g_maplist_votable_suggestions_change_gametype"))
1741                 if(!IsSameGametype(m))
1742                         return "This server does not allow changing the game type by map suggestions.";
1743 #endif
1744         if(!cvar("g_maplist_votable_override_mostrecent"))
1745                 if(Map_IsRecent(m))
1746                         return "This server does not allow for recent maps to be played again. Please be patient for some rounds.";
1747
1748 #ifdef MAPINFO
1749         if(!MapInfo_CheckMap(m))
1750                 return "The map you suggested does not support the current game mode.";
1751 #else
1752         if(!TryFile(strcat("maps/", m, ".mapcfg")))
1753                 return "The map you suggested is not available on this server.";
1754 #endif
1755         for(i = 0; i < mapvote_suggestion_ptr; ++i)
1756                 if(mapvote_suggestions[i] == m)
1757                         return "This map was already suggested.";
1758         if(mapvote_suggestion_ptr >= MAPVOTE_COUNT)
1759         {
1760                 i = ceil(random() * mapvote_suggestion_ptr) - 1;
1761         }
1762         else
1763         {
1764                 i = mapvote_suggestion_ptr;
1765                 mapvote_suggestion_ptr += 1;
1766         }
1767         if(mapvote_suggestions[i] != "")
1768                 strunzone(mapvote_suggestions[i]);
1769         mapvote_suggestions[i] = strzone(m);
1770         if(cvar("sv_eventlog"))
1771                 GameLogEcho(strcat(":vote:suggested:", m, ":", ftos(self.playerid)), TRUE);
1772         return strcat("Suggestion of ", m, " accepted.");
1773 }
1774
1775 void MapVote_AddVotable(string nextMap, float isSuggestion)
1776 {
1777         float j;
1778         if(nextMap == "")
1779                 return;
1780         for(j = 0; j < mapvote_count; ++j)
1781                 if(mapvote_maps[j] == nextMap)
1782                         return;
1783         if(strlen(nextMap) > mapvote_maxlen)
1784                 mapvote_maxlen = strlen(nextMap);
1785         mapvote_maps[mapvote_count] = strzone(nextMap);
1786         mapvote_maps_suggested[mapvote_count] = isSuggestion;
1787         mapvote_count += 1;
1788 }
1789
1790 void MapVote_SendData(float target);
1791 void MapVote_Init()
1792 {
1793         float i;
1794         float nmax, smax;
1795
1796         MapVote_ClearAllVotes();
1797
1798         mapvote_count = 0;
1799         mapvote_detail = !cvar("g_maplist_votable_nodetail");
1800         mapvote_abstain = cvar("g_maplist_votable_abstain");
1801
1802         if(mapvote_abstain)
1803                 nmax = min(MAPVOTE_COUNT - 1, cvar("g_maplist_votable"));
1804         else
1805                 nmax = min(MAPVOTE_COUNT, cvar("g_maplist_votable"));
1806         smax = min3(nmax, cvar("g_maplist_votable_suggestions"), mapvote_suggestion_ptr);
1807
1808         if(mapvote_suggestion_ptr)
1809                 for(i = 0; i < 100 && mapvote_count < smax; ++i)
1810                         MapVote_AddVotable(mapvote_suggestions[ceil(random() * mapvote_suggestion_ptr) - 1], TRUE);
1811
1812         for(i = 0; i < 100 && mapvote_count < nmax; ++i)
1813                 MapVote_AddVotable(GetNextMap(), FALSE);
1814
1815         if(mapvote_count == 0)
1816         {
1817                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
1818 #ifdef MAPINFO
1819                 cvar_set("g_maplist", MapInfo_ListAllowedMaps());
1820                 localcmd("\nmenu_cmd sync\n");
1821 #else
1822                 cvar_set("g_maplist", cvar_string("g_maplist_defaultlist"));
1823 #endif
1824                 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
1825                         MapVote_AddVotable(GetNextMap(), FALSE);
1826         }
1827
1828         mapvote_count_real = mapvote_count;
1829         if(mapvote_abstain)
1830                 MapVote_AddVotable("don't care", 0);
1831
1832         //dprint("mapvote count is ", ftos(mapvote_count), "\n");
1833
1834         mapvote_keeptwotime = time + cvar("g_maplist_votable_keeptwotime");
1835         mapvote_timeout = time + cvar("g_maplist_votable_timeout");
1836         if(mapvote_count_real < 3 || mapvote_keeptwotime <= time)
1837                 mapvote_keeptwotime = 0;
1838         mapvote_message = "Choose a map and press its key!";
1839
1840         mapvote_screenshot_dir = cvar_string("g_maplist_votable_screenshot_dir");
1841         if(mapvote_screenshot_dir == "")
1842                 mapvote_screenshot_dir = "maps";
1843         mapvote_screenshot_dir = strzone(mapvote_screenshot_dir);
1844
1845         if(!cvar("g_maplist_textonly"))
1846                 MapVote_SendData(MSG_ALL);
1847 }
1848
1849 void MapVote_SendPicture(float id)
1850 {
1851         msg_entity = self;
1852         WriteByte(MSG_ONE, SVC_TEMPENTITY);
1853         WriteByte(MSG_ONE, TE_CSQC_MAPVOTE);
1854         WriteByte(MSG_ONE, MAPVOTE_NET_PIC);
1855         WriteByte(MSG_ONE, id);
1856         WritePicture(MSG_ONE, strcat(mapvote_screenshot_dir, "/", mapvote_maps[id]), 3072);
1857 }
1858
1859 float GameCommand_MapVote(string cmd)
1860 {
1861         if(!intermission_running)
1862                 return FALSE;
1863         if(!cvar("g_maplist_textonly"))
1864         {
1865                 if(cmd == "mv_getpic")
1866                 {
1867                         MapVote_SendPicture(stof(argv(1)));
1868                         return TRUE;
1869                 }
1870         }
1871
1872         return FALSE;
1873 }
1874
1875 float MapVote_GetMapMask()
1876 {
1877         float mask, i, power;
1878         mask = 0;
1879         for(i = 0, power = 1; i < mapvote_count; ++i, power *= 2)
1880                 if(mapvote_maps[i] != "")
1881                         mask |= power;
1882         return mask;
1883 }
1884
1885 void MapVote_SendData(float targ)
1886 {
1887         string mapfile, pakfile;
1888         float i, o;
1889         WriteByte(targ, SVC_TEMPENTITY);
1890         WriteByte(targ, TE_CSQC_CONFIG);
1891         WriteString(targ, "mv_screenshot_dir");
1892         WriteString(targ, mapvote_screenshot_dir);
1893
1894         WriteByte(targ, SVC_TEMPENTITY);
1895         WriteByte(targ, TE_CSQC_MAPVOTE);
1896         WriteByte(targ, MAPVOTE_NET_INIT);
1897
1898         WriteByte(targ, mapvote_count);
1899         WriteByte(targ, mapvote_abstain);
1900         WriteByte(targ, mapvote_detail);
1901         WriteCoord(targ, mapvote_timeout);
1902         if(mapvote_count <= 8)
1903                 WriteByte(targ, MapVote_GetMapMask());
1904         else
1905                 WriteShort(targ, MapVote_GetMapMask());
1906         for(i = 0; i < mapvote_count; ++i)
1907                 if(mapvote_maps[i] != "")
1908                 {
1909                         WriteString(targ, mapvote_maps[i]);
1910                         mapfile = strcat(mapvote_screenshot_dir, "/", mapvote_maps[i]);
1911                         pakfile = whichpack(strcat(mapfile, ".tga"));
1912                         if(pakfile == "")
1913                                 pakfile = whichpack(strcat(mapfile, ".jpg"));
1914                         if(pakfile == "")
1915                                 pakfile = whichpack(strcat(mapfile, ".png"));
1916                         print("pakfile is ", pakfile, "\n");
1917                         for(o = strstr(pakfile, "/", 0)+1; o > 0; o = strstr(pakfile, "/", 0)+1)
1918                                 pakfile = substring(pakfile, o, 999);
1919                         WriteString(targ, pakfile);
1920                 }
1921 }
1922
1923 void MapVote_UpdateData(float targ)
1924 {
1925         float i;
1926         WriteByte(targ, SVC_TEMPENTITY);
1927         WriteByte(targ, TE_CSQC_MAPVOTE);
1928         WriteByte(targ, MAPVOTE_NET_UPDATE);
1929         if(mapvote_count <= 8)
1930                 WriteByte(targ, MapVote_GetMapMask());
1931         else
1932                 WriteShort(targ, MapVote_GetMapMask());
1933         if(mapvote_detail)
1934                 for(i = 0; i < mapvote_count; ++i)
1935                         if(mapvote_maps[i] != "")
1936                                 WriteByte(targ, mapvote_votes[i]);
1937 }
1938
1939 void MapVote_TellVote(float targ, float vote)
1940 {
1941         WriteByte(targ, SVC_TEMPENTITY);
1942         WriteByte(targ, TE_CSQC_MAPVOTE);
1943         WriteByte(targ, MAPVOTE_NET_OWNVOTE);
1944         WriteByte(targ, vote);
1945 }
1946
1947 float MapVote_Finished(float mappos)
1948 {
1949         string result;
1950         float i;
1951         float didntvote;
1952
1953         if(cvar("sv_eventlog"))
1954         {
1955                 result = strcat(":vote:finished:", mapvote_maps[mappos]);
1956                 result = strcat(result, ":", ftos(mapvote_votes[mappos]), "::");
1957                 didntvote = mapvote_voters;
1958                 for(i = 0; i < mapvote_count; ++i)
1959                         if(mapvote_maps[i] != "")
1960                         {
1961                                 didntvote -= mapvote_votes[i];
1962                                 if(i != mappos)
1963                                 {
1964                                         result = strcat(result, ":", mapvote_maps[i]);
1965                                         result = strcat(result, ":", ftos(mapvote_votes[i]));
1966                                 }
1967                         }
1968                 result = strcat(result, ":didn't vote:", ftos(didntvote));
1969
1970                 GameLogEcho(result, FALSE);
1971                 if(mapvote_maps_suggested[mappos])
1972                         GameLogEcho(strcat(":vote:suggestion_accepted:", mapvote_maps[mappos]), FALSE);
1973         }
1974
1975         FOR_EACH_REALCLIENT(other)
1976                 FixClientCvars(other);
1977
1978         Map_Goto_SetStr(mapvote_maps[mappos]);
1979         Map_Goto();
1980         alreadychangedlevel = TRUE;
1981         return TRUE;
1982 }
1983 void MapVote_CheckRules_1()
1984 {
1985         float i;
1986
1987         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
1988         {
1989                 //dprint("Map ", ftos(i), ": "); dprint(mapvote_maps[i], "\n");
1990                 mapvote_votes[i] = 0;
1991         }
1992
1993         mapvote_voters = 0;
1994         FOR_EACH_REALCLIENT(other)
1995         {
1996                 ++mapvote_voters;
1997                 if(other.mapvote)
1998                 {
1999                         i = other.mapvote - 1;
2000                         //dprint("Player ", other.netname, " vote = ", ftos(other.mapvote - 1), "\n");
2001                         mapvote_votes[i] = mapvote_votes[i] + 1;
2002                 }
2003         }
2004 }
2005
2006 float MapVote_CheckRules_2()
2007 {
2008         float i;
2009         float firstPlace, secondPlace;
2010         float firstPlaceVotes, secondPlaceVotes;
2011         float mapvote_voters_real;
2012         string result;
2013
2014         mapvote_voters_real = mapvote_voters;
2015         if(mapvote_abstain)
2016                 mapvote_voters_real -= mapvote_votes[mapvote_count - 1];
2017
2018         RandomSelection_Init();
2019         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2020                 RandomSelection_Add(world, i, 1, mapvote_votes[i]);
2021         firstPlace = RandomSelection_chosen_float;
2022         firstPlaceVotes = RandomSelection_best_priority;
2023         //dprint("First place: ", ftos(firstPlace), "\n");
2024         //dprint("First place votes: ", ftos(firstPlaceVotes), "\n");
2025
2026         RandomSelection_Init();
2027         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2028                 if(i != firstPlace)
2029                         RandomSelection_Add(world, i, 1, mapvote_votes[i]);
2030         secondPlace = RandomSelection_chosen_float;
2031         secondPlaceVotes = RandomSelection_best_priority;
2032         //dprint("Second place: ", ftos(secondPlace), "\n");
2033         //dprint("Second place votes: ", ftos(secondPlaceVotes), "\n");
2034
2035         if(firstPlace == -1)
2036                 error("No first place in map vote... WTF?");
2037
2038         if(secondPlace == -1 || time > mapvote_timeout || (mapvote_voters_real - firstPlaceVotes) < firstPlaceVotes)
2039                 return MapVote_Finished(firstPlace);
2040
2041         if(mapvote_keeptwotime)
2042                 if(time > mapvote_keeptwotime || (mapvote_voters_real - firstPlaceVotes - secondPlaceVotes) < secondPlaceVotes)
2043                 {
2044                         float didntvote;
2045                         mapvote_dirty = TRUE;
2046                         mapvote_message = "Now decide between the TOP TWO!";
2047                         mapvote_keeptwotime = 0;
2048                         result = strcat(":vote:keeptwo:", mapvote_maps[firstPlace]);
2049                         result = strcat(result, ":", ftos(firstPlaceVotes));
2050                         result = strcat(result, ":", mapvote_maps[secondPlace]);
2051                         result = strcat(result, ":", ftos(secondPlaceVotes), "::");
2052                         didntvote = mapvote_voters;
2053                         for(i = 0; i < mapvote_count; ++i)
2054                                 if(mapvote_maps[i] != "")
2055                                 {
2056                                         didntvote -= mapvote_votes[i];
2057                                         if(i != firstPlace)
2058                                                 if(i != secondPlace)
2059                                                 {
2060                                                         result = strcat(result, ":", mapvote_maps[i]);
2061                                                         result = strcat(result, ":", ftos(mapvote_votes[i]));
2062                                                         if(i < mapvote_count_real)
2063                                                         {
2064                                                                 strunzone(mapvote_maps[i]);
2065                                                                 mapvote_maps[i] = "";
2066                                                         }
2067                                                 }
2068                                 }
2069                         result = strcat(result, ":didn't vote:", ftos(didntvote));
2070                         if(cvar("sv_eventlog"))
2071                                 GameLogEcho(result, FALSE);
2072                 }
2073
2074         return FALSE;
2075 }
2076 void MapVote_Tick()
2077 {
2078         string msgstr;
2079         string tmp;
2080         float i;
2081         float keeptwo;
2082         float totalvotes;
2083
2084         keeptwo = mapvote_keeptwotime;
2085         MapVote_CheckRules_1(); // count
2086         if(MapVote_CheckRules_2()) // decide
2087                 return;
2088
2089         totalvotes = 0;
2090         FOR_EACH_REALCLIENT(other)
2091         {
2092                 // hide scoreboard again
2093                 if(other.health != 2342)
2094                 {
2095                         other.health = 2342;
2096                         other.impulse = 0;
2097                         if(clienttype(other) == CLIENTTYPE_REAL)
2098                         {
2099                                 if(cvar("g_maplist_textonly"))
2100                                         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");
2101
2102                                 msg_entity = other;
2103                                 WriteByte(MSG_ONE, SVC_FINALE);
2104                                 WriteString(MSG_ONE, "");
2105                         }
2106                 }
2107
2108                 // notify about keep-two
2109                 if(keeptwo != 0 && mapvote_keeptwotime == 0)
2110                         play2(other, "misc/invshot.wav");
2111
2112                 // clear possibly invalid votes
2113                 if(mapvote_maps[other.mapvote - 1] == "")
2114                         other.mapvote = 0;
2115                 // use impulses as new vote
2116                 if(other.impulse >= 1 && other.impulse <= mapvote_count)
2117                         if(mapvote_maps[other.impulse - 1] != "")
2118                         {
2119                                 other.mapvote = other.impulse;
2120                                 if(mapvote_detail)
2121                                         mapvote_dirty = TRUE;
2122
2123                                 msg_entity = other;
2124                                 MapVote_TellVote(MSG_ONE, other.mapvote);
2125                         }
2126                 other.impulse = 0;
2127
2128                 if(other.mapvote)
2129                         ++totalvotes;
2130         }
2131
2132         MapVote_CheckRules_1(); // just count
2133
2134         if(!cvar("g_maplist_textonly"))
2135         if(mapvote_dirty) // 1 if "keeptwo" or "impulse" happened before
2136         {
2137                 MapVote_UpdateData(MSG_BROADCAST);
2138                 mapvote_dirty = FALSE;
2139         }
2140
2141         if(cvar("g_maplist_textonly"))
2142         {
2143                 FOR_EACH_REALCLIENT(other)
2144                 {
2145                         // display voting screen
2146                         msgstr = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
2147                         msgstr = substring(msgstr, 0, strlen(msgstr) - mapvote_count);
2148                         if(mapvote_abstain)
2149                                 msgstr = substring(msgstr, 1, strlen(msgstr) - 1);
2150                         msgstr = strcat(msgstr, mapvote_message);
2151                         msgstr = strcat(msgstr, "\n\n");
2152                         for(i = 0; i < mapvote_count; ++i)
2153                                 if(mapvote_maps[i] == "")
2154                                         msgstr = strcat(msgstr, "\n");
2155                                 else
2156                                 {
2157                                         tmp = mapvote_maps[i];
2158                                         tmp = strpad(mapvote_maxlen, tmp);
2159                                         tmp = strcat(ftos(mod(i + 1, 10)), ": ", tmp);
2160                                         if(mapvote_detail)
2161                                         {
2162                                                 tmp = strcat(tmp, " ^2(", ftos(mapvote_votes[i]), " vote");
2163                                                 if(mapvote_votes[i] != 1)
2164                                                         tmp = strcat(tmp, "s");
2165                                                 tmp = strcat(tmp, ")");
2166                                                 tmp = strpad(mapvote_maxlen + 15, tmp);
2167                                         }
2168                                         if(mapvote_abstain)
2169                                                 if(i == mapvote_count - 1)
2170                                                         msgstr = strcat(msgstr, "\n");
2171                                         if(other.mapvote == i + 1)
2172                                                 msgstr = strcat(msgstr, "^3> ", tmp, "\n");
2173                                         else
2174                                                 msgstr = strcat(msgstr, "^7  ", tmp, "\n");
2175                                 }
2176
2177                         msgstr = strcat(msgstr, "\n\n^2", ftos(totalvotes), " vote");
2178                         if(totalvotes != 1)
2179                                 msgstr = strcat(msgstr, "s");
2180                         msgstr = strcat(msgstr, " cast");
2181                         i = ceil(mapvote_timeout - time);
2182                         msgstr = strcat(msgstr, "\n", ftos(i), " second");
2183                         if(i != 1)
2184                                 msgstr = strcat(msgstr, "s");
2185                         msgstr = strcat(msgstr, " left");
2186
2187                         centerprint_atprio(other, CENTERPRIO_MAPVOTE, msgstr);
2188                 }
2189         }
2190 }
2191 void MapVote_Start()
2192 {
2193         if(mapvote_run)
2194                 return;
2195
2196 #ifdef MAPINFO
2197         MapInfo_Enumerate();
2198         if(MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 1))
2199 #endif
2200                 mapvote_run = TRUE;
2201 }
2202 void MapVote_Think()
2203 {
2204         if(!mapvote_run)
2205                 return;
2206
2207         if(alreadychangedlevel)
2208                 return;
2209
2210         if(time < mapvote_nextthink)
2211                 return;
2212         //dprint("tick\n");
2213
2214         mapvote_nextthink = time + 0.5;
2215
2216         if(!mapvote_initialized)
2217         {
2218                 mapvote_initialized = TRUE;
2219                 if(DoNextMapOverride())
2220                         return;
2221                 if(!cvar("g_maplist_votable") || player_count <= 0)
2222                 {
2223                         GotoNextMap();
2224                         return;
2225                 }
2226                 MapVote_Init();
2227         }
2228
2229         MapVote_Tick();
2230 };
2231
2232 string GotoMap(string m)
2233 {
2234 #ifdef MAPINFO
2235         if(!MapInfo_CheckMap(m))
2236 #else
2237         if(!TryFile(strcat("maps/", m, ".mapcfg")))
2238 #endif
2239                 return "The map you chose is not available on this server.";
2240         cvar_set("nextmap", m);
2241         cvar_set("timelimit", "-1");
2242         if(mapvote_initialized || alreadychangedlevel)
2243         {
2244                 if(DoNextMapOverride())
2245                         return "Map switch initiated.";
2246                 else
2247                         return "Hm... no. For some reason I like THIS map more.";
2248         }
2249         else
2250                 return "Map switch will happen after scoreboard.";
2251 }
2252
2253
2254 void EndFrame()
2255 {
2256         FOR_EACH_REALCLIENT(self)
2257         {
2258                 if(self.classname == "spectator")
2259                 {
2260                         if(self.enemy.hitsound)
2261                                 play2(self, "misc/hit.wav");
2262                 }
2263                 else
2264                 {
2265                         if(self.hitsound)
2266                                 play2(self, "misc/hit.wav");
2267                 }
2268         }
2269         FOR_EACH_CLIENT(self)
2270                 self.hitsound = FALSE;
2271 }
2272
2273
2274 /*
2275  * RedirectionThink:
2276  * returns TRUE if redirecting
2277  */
2278 float redirection_timeout;
2279 float redirection_nextthink;
2280 float RedirectionThink()
2281 {
2282         float clients_found;
2283
2284         if(redirection_target == "")
2285                 return FALSE;
2286
2287         if(!redirection_timeout)
2288         {
2289                 cvar_set("sv_public", "-2");
2290                 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2291                 if(redirection_target == "self")
2292                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2293                 else
2294                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2295         }
2296
2297         if(time < redirection_nextthink)
2298                 return TRUE;
2299
2300         redirection_nextthink = time + 1;
2301
2302         clients_found = 0;
2303         FOR_EACH_REALCLIENT(self)
2304         {
2305                 ServerConsoleEcho(strcat("Redirecting: sending connect command to ", self.netname), FALSE);
2306                 if(redirection_target == "self")
2307                         stuffcmd(self, "\ndisconnect; reconnect\n");
2308                 else
2309                         stuffcmd(self, strcat("\ndisconnect; connect ", redirection_target, "\n"));
2310                 ++clients_found;
2311         }
2312
2313         ServerConsoleEcho(strcat("Redirecting: ", ftos(clients_found), " clients left."), FALSE);
2314
2315         if(time > redirection_timeout || clients_found == 0)
2316                 localcmd("\nwait; wait; wait; quit\n");
2317
2318         return TRUE;
2319 }
2320
2321 void RestoreGame()
2322 {
2323         // Loaded from a save game
2324         // some things then break, so let's work around them...
2325
2326         // Progs DB (capture records)
2327         if(sv_cheats)
2328                 ServerProgsDB = db_create();
2329         else
2330                 ServerProgsDB = db_load("server.db");
2331
2332         // Mapinfo
2333 #ifdef MAPINFO
2334         MapInfo_Shutdown();
2335         MapInfo_Enumerate();
2336         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 1);
2337 #endif
2338 }
2339
2340 void SV_Shutdown()
2341 {
2342         if(world_initialized)
2343         {
2344                 world_initialized = 0;
2345                 print("Saving persistent data...\n");
2346                 Ban_SaveBans();
2347                 if(!sv_cheats)
2348                         db_save(ServerProgsDB, "server.db");
2349                 db_close(ServerProgsDB);
2350                 print("done!\n");
2351                 // tell the bot system the game is ending now
2352                 bot_endgame();
2353
2354                 MapInfo_Shutdown();
2355         }
2356         else
2357         {
2358                 print("NOTE: crashed before even initializing the world, not saving persistent data\n");
2359         }
2360 }