]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/g_world.qc
remove some more leaks
[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         if (game == GAME_DEATHMATCH)
386                 return "dm";
387         else if (game == GAME_TEAM_DEATHMATCH)
388                 return "tdm";
389         else if (game == GAME_DOMINATION)
390                 return "dom";
391         else if (game == GAME_CTF)
392                 return "ctf";
393         else if (game == GAME_RUNEMATCH)
394                 return "rune";
395         else if (game == GAME_LMS)
396                 return "lms";
397         else if (game == GAME_KEYHUNT)
398                 return "kh";
399         else if (game == GAME_ONSLAUGHT)
400                 return "ons";
401         else if (game == GAME_ASSAULT)
402                 return "as";
403         return "dm";
404 }
405
406 float IsSameGametype(string mapcfgname)
407 {
408 #ifdef MAPINFO
409         return TRUE; // can't change game type by map name here
410 #else
411         string gt;
412         gt = GetGametype();
413         if(substring(mapcfgname, 0, strlen(gt) + 1) == strcat(gt, "_"))
414                 return TRUE;
415         return FALSE;
416 #endif
417 }
418
419 string getmapname_stored;
420 string GetMapname()
421 {
422 #ifdef MAPINFO
423         return mapname;
424 #else
425         if(getmapname_stored == "")
426                 getmapname_stored = strzone(strcat(GetGametype(), "_", mapname));
427         return getmapname_stored;
428 #endif
429 }
430
431 float Map_Count, Map_Current;
432 string Map_Current_Name;
433
434 // NOTE: this now expects the map list to be already tokenize()d and the count in Map_Count
435 float GetMaplistPosition()
436 {
437         float pos, idx;
438         string map;
439
440         map = GetMapname();
441         idx = cvar("g_maplist_index");
442
443         if(idx >= 0)
444                 if(idx < Map_Count)
445                         if(map == argv(idx))
446                                 return idx;
447
448         for(pos = 0; pos < Map_Count; ++pos)
449                 if(map == argv(pos))
450                         return pos;
451
452         // resume normal maplist rotation if current map is not in g_maplist
453         return idx;
454 }
455
456 float MapHasRightSize(string map)
457 {
458         float fh;
459         if(currentbots || cvar("bot_number") || player_count < cvar("minplayers"))
460         if(cvar("g_maplist_check_waypoints"))
461         {
462                 dprint("checkwp "); dprint(map);
463                 fh = fopen(strcat("maps/", map, ".waypoints"), FILE_READ);
464                 if(fh < 0)
465                 {
466                         dprint(": no waypoints\n");
467                         return FALSE;
468                 }
469                 dprint(": has waypoints\n");
470                 fclose(fh);
471         }
472
473         // open map size restriction file
474         dprint("opensize "); dprint(map);
475         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
476         if(fh >= 0)
477         {
478                 float mapmin, mapmax;
479                 dprint(": ok, ");
480                 mapmin = stof(fgets(fh));
481                 mapmax = stof(fgets(fh));
482                 fclose(fh);
483                 if(player_count < mapmin)
484                 {
485                         dprint("not enough\n");
486                         return FALSE;
487                 }
488                 if(player_count > mapmax)
489                 {
490                         dprint("too many\n");
491                         return FALSE;
492                 }
493                 dprint("right size\n");
494                 return TRUE;
495         }
496         dprint(": not found\n");
497         return TRUE;
498 }
499
500 string Map_Filename(float position)
501 {
502 #ifdef MAPINFO
503         return strcat("maps/", argv(position), ".bsp");
504 #else
505         return strcat("maps/", argv(position), ".mapcfg");
506 #endif
507 }
508
509 string strwords(string s, float w)
510 {
511         float endpos;
512         for(endpos = 0; w && endpos >= 0; --w)
513                 endpos = strstrofs(s, " ", endpos + 1);
514         if(endpos < 0)
515                 return s;
516         else
517                 return substring(s, 0, endpos);
518 }
519
520 float strhasword(string s, string w)
521 {
522         return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
523 }
524
525 void Map_MarkAsRecent(string m)
526 {
527         cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", cvar_string("g_maplist_mostrecent")), cvar("g_maplist_mostrecent_count")));
528 }
529
530 float Map_IsRecent(string m)
531 {
532         return strhasword(cvar_string("g_maplist_mostrecent"), m);
533 }
534
535 float Map_Check(float position, float pass)
536 {
537         string filename;
538         string map_next;
539         map_next = argv(position);
540         if(pass <= 1)
541         {
542                 if(map_next == Map_Current_Name) // same map again in first pass?
543                         return 0;
544                 if(Map_IsRecent(map_next))
545                         return 0;
546         }
547         filename = Map_Filename(position);
548 #ifdef MAPINFO
549         if(MapInfo_CheckMap(map_next))
550 #else
551         if(TryFile(filename))
552 #endif
553         {
554                 if(pass == 2)
555                         return 1;
556                 if(MapHasRightSize(map_next))
557                         return 1;
558                 return 0;
559         }
560         else
561                 dprint( "Couldn't select '", filename, "'..\n" );
562
563         return 0;
564 }
565
566 void Map_Goto_SetStr(string nextmapname)
567 {
568         if(getmapname_stored != "")
569                 strunzone(getmapname_stored);
570         if(nextmapname == "")
571                 getmapname_stored = "";
572         else
573                 getmapname_stored = strzone(nextmapname);
574 }
575
576 void Map_Goto_SetFloat(float position)
577 {
578         cvar_set("g_maplist_index", ftos(position));
579         Map_Goto_SetStr(argv(position));
580 }
581
582 void GameResetCfg()
583 {
584 #ifdef MAPINFO
585         // settings persist, except...
586         if(cvar("g_campaign"))
587                 localcmd("\nexec mutator_reset.cfg\n");
588         localcmd("\nsettemp_restore\n");
589 #else
590         // if an exit cfg is defined by exiting map, exec it.
591         string exit_cfg;
592         exit_cfg = cvar_string("exit_cfg");
593         if(exit_cfg != "")
594                 localcmd(strcat("exec \"", exit_cfg, "\"\n"));
595
596         localcmd("exec game_reset.cfg\n");
597 #endif
598 };
599
600 void Map_Goto()
601 {
602         Map_MarkAsRecent(getmapname_stored);
603         GameResetCfg();
604 #ifdef MAPINFO
605         MapInfo_LoadMap(getmapname_stored);
606 #else
607         localcmd(strcat("exec \"maps/", getmapname_stored ,".mapcfg\"\n"));
608 #endif
609 }
610
611 // return codes of map selectors:
612 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
613 //   -2 = permanent failure
614 float() MaplistMethod_Iterate = // usual method
615 {
616         float pass, i;
617
618         for(pass = 1; pass <= 2; ++pass)
619         {
620                 for(i = 1; i < Map_Count; ++i)
621                 {
622                         float mapindex;
623                         mapindex = mod(i + Map_Current, Map_Count);
624                         if(Map_Check(mapindex, pass))
625                                 return mapindex;
626                 }
627         }
628         return -1;
629 }
630
631 float() MaplistMethod_Repeat = // fallback method
632 {
633         if(Map_Check(Map_Current, 2))
634                 return Map_Current;
635         return -2;
636 }
637
638 float() MaplistMethod_Random = // random map selection
639 {
640         float i, imax;
641
642         imax = 42;
643
644         for(i = 0; i <= imax; ++i)
645         {
646                 float mapindex;
647                 mapindex = mod(Map_Current + ceil(random() * (Map_Count - 1)), Map_Count); // any OTHER map
648                 if(Map_Check(mapindex, 1))
649                         return mapindex;
650         }
651         return -1;
652 }
653
654 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
655 // the exponent sets a bias on the map selection:
656 // the higher the exponent, the less likely "shortly repeated" same maps are
657 {
658         float i, j, imax, insertpos;
659
660         imax = 42;
661
662         for(i = 0; i <= imax; ++i)
663         {
664                 string newlist;
665
666                 // now reinsert this at another position
667                 insertpos = pow(random(), 1 / exponent);       // ]0, 1]
668                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
669                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
670                 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
671
672                 // insert the current map there
673                 newlist = "";
674 #ifdef MAPINFO
675                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
676                         newlist = strcat(newlist, " ", argv(j));
677                 newlist = strcat(newlist, " ", argv(0));       // now insert the just selected map
678                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
679                         newlist = strcat(newlist, " ", argv(j));
680                 newlist = substring(newlist, 1, strlen(newlist) - 1);
681 #else
682                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
683                         newlist = strcat(newlist, "'", argv(j), "'");
684                 newlist = strcat(newlist, "'", argv(0), "'");  // now insert the just selected map
685                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
686                         newlist = strcat(newlist, "'", argv(j), "'");
687 #endif
688                 cvar_set("g_maplist", newlist);
689 #ifdef MAPINFO
690                 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
691 #else
692                 Map_Count = tokenize(newlist);
693 #endif
694
695                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
696                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
697                 if(Map_Check(Map_Current, 1))
698                         return Map_Current;
699         }
700         return -1;
701 }
702
703 void Maplist_Init()
704 {
705         string temp;
706         temp = cvar_string("g_maplist");
707 #ifdef MAPINFO
708         Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
709 #else
710         Map_Count = tokenize(temp);
711 #endif
712         if(Map_Count == 0)
713         {
714                 bprint( "Maplist is empty!  Resetting it to default map list.\n" );
715 #ifdef MAPINFO
716                 cvar_set("g_maplist", temp = MapInfo_ListAllowedMaps());
717                 localcmd("\nmenu_cmd sync\n");
718                 Map_Count = tokenizebyseparator(temp, " ");
719 #else
720                 cvar_set("g_maplist", temp = cvar_string("g_maplist_defaultlist"));
721                 Map_Count = tokenize(temp);
722 #endif
723         }
724         if(Map_Count == 0)
725                 error("empty maplist, cannot select a new map");
726         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
727
728         if(Map_Current_Name)
729                 strunzone(Map_Current_Name);
730         Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
731         // this may or may not be correct, but who cares, in the worst case a map
732         // isn't chosen in the first pass that should have been
733 }
734
735 string GetNextMap()
736 {
737         float nextMap;
738
739         Maplist_Init();
740         nextMap = -1;
741
742         if(nextMap == -1)
743                 if(cvar("g_maplist_shuffle") > 0)
744                         nextMap = MaplistMethod_Shuffle(cvar("g_maplist_shuffle") + 1);
745
746         if(nextMap == -1)
747                 if(cvar("g_maplist_selectrandom"))
748                         nextMap = MaplistMethod_Random();
749
750         if(nextMap == -1)
751                 nextMap = MaplistMethod_Iterate();
752
753         if(nextMap == -1)
754                 nextMap = MaplistMethod_Repeat();
755
756         if(nextMap >= 0)
757         {
758                 Map_Goto_SetFloat(nextMap);
759                 return getmapname_stored;
760         }
761
762         return "";
763 };
764
765 float DoNextMapOverride()
766 {
767         if(cvar("g_campaign"))
768         {
769                 CampaignPostIntermission();
770                 alreadychangedlevel = TRUE;
771                 return TRUE;
772         }
773         if(cvar("quit_when_empty"))
774         {
775                 if(player_count <= currentbots)
776                 {
777                         localcmd("quit\n");
778                         alreadychangedlevel = TRUE;
779                         return TRUE;
780                 }
781         }
782         if(cvar_string("quit_and_redirect") != "")
783         {
784                 redirection_target = strzone(cvar_string("quit_and_redirect"));
785                 alreadychangedlevel = TRUE;
786                 return TRUE;
787         }
788         if (cvar("samelevel")) // if samelevel is set, stay on same level
789         {
790                 // 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)
791                 //localcmd(strcat("exec \"maps/", mapname, ".mapcfg\"\n"));
792                 // so instead just restart the current map using the restart command (DOES NOT WORK PROPERLY WITH exit_cfg STUFF)
793                 localcmd("restart\n");
794                 //changelevel (mapname);
795                 alreadychangedlevel = TRUE;
796                 return TRUE;
797         }
798         if(cvar_string("nextmap") != "")
799 #ifdef MAPINFO
800                 if(MapInfo_CheckMap(cvar_string("nextmap")))
801 #else
802                 if(TryFile(strcat("maps/", cvar_string("nextmap"), ".mapcfg")))
803 #endif
804                 {
805                         Map_Goto_SetStr(cvar_string("nextmap"));
806                         Map_Goto();
807                         alreadychangedlevel = TRUE;
808                         return TRUE;
809                 }
810         if(cvar("lastlevel"))
811         {
812                 GameResetCfg();
813                 localcmd("set lastlevel 0\ntogglemenu\n");
814                 alreadychangedlevel = TRUE;
815                 return TRUE;
816         }
817         return FALSE;
818 };
819
820 void GotoNextMap()
821 {
822         //local string nextmap;
823         //local float n, nummaps;
824         //local string s;
825         if (alreadychangedlevel)
826                 return;
827         alreadychangedlevel = TRUE;
828
829         {
830                 string nextMap;
831                 float allowReset;
832
833                 for(allowReset = 1; allowReset >= 0; --allowReset)
834                 {
835                         nextMap = GetNextMap();
836                         if(nextMap != "")
837                                 break;
838
839                         if(allowReset)
840                         {
841                                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
842 #ifdef MAPINFO
843                                 cvar_set("g_maplist", MapInfo_ListAllowedMaps());
844                                 localcmd("\nmenu_cmd sync\n");
845 #else
846                                 cvar_set("g_maplist", cvar_string("g_maplist_defaultlist"));
847 #endif
848                         }
849                         else
850                         {
851                                 error("Everything is broken - not even the default map list works. Please report this to the developers.");
852                         }
853                 }
854                 Map_Goto();
855         }
856 };
857
858
859 /*
860 ============
861 IntermissionThink
862
863 When the player presses attack or jump, change to the next level
864 ============
865 */
866 .float autoscreenshot;
867 void() MapVote_Start;
868 void() MapVote_Think;
869 float mapvote_initialized;
870 void IntermissionThink()
871 {
872         FixIntermissionClient(self);
873
874         if(cvar("sv_autoscreenshot"))
875         if(self.autoscreenshot > 0)
876         if(time > self.autoscreenshot)
877         {
878                 self.autoscreenshot = -1;
879                 if(clienttype(self) == CLIENTTYPE_REAL)
880                         stuffcmd(self, "\nscreenshot\necho \"^5A screenshot has been taken at request of the server.\"\n");
881                 return;
882         }
883
884         if (time < intermission_exittime)
885                 return;
886
887         if(!mapvote_initialized)
888                 if (time < intermission_exittime + 10 && !self.BUTTON_ATCK && !self.BUTTON_JUMP && !self.BUTTON_ATCK2 && !self.BUTTON_HOOK && !self.BUTTON_USE)
889                         return;
890
891         MapVote_Start();
892 };
893
894 /*
895 ============
896 FindIntermission
897
898 Returns the entity to view from
899 ============
900 */
901 /*
902 entity FindIntermission()
903 {
904         local   entity spot;
905         local   float cyc;
906
907 // look for info_intermission first
908         spot = find (world, classname, "info_intermission");
909         if (spot)
910         {       // pick a random one
911                 cyc = random() * 4;
912                 while (cyc > 1)
913                 {
914                         spot = find (spot, classname, "info_intermission");
915                         if (!spot)
916                                 spot = find (spot, classname, "info_intermission");
917                         cyc = cyc - 1;
918                 }
919                 return spot;
920         }
921
922 // then look for the start position
923         spot = find (world, classname, "info_player_start");
924         if (spot)
925                 return spot;
926
927 // testinfo_player_start is only found in regioned levels
928         spot = find (world, classname, "testplayerstart");
929         if (spot)
930                 return spot;
931
932 // then look for the start position
933         spot = find (world, classname, "info_player_deathmatch");
934         if (spot)
935                 return spot;
936
937         //objerror ("FindIntermission: no spot");
938         return world;
939 };
940 */
941
942 /*
943 ===============================================================================
944
945 RULES
946
947 ===============================================================================
948 */
949
950 void DumpStats(float final)
951 {
952         local float file;
953         local string s;
954         local float to_console;
955         local float to_eventlog;
956         local float to_file;
957
958         to_console = cvar("sv_logscores_console");
959         to_eventlog = cvar("sv_eventlog");
960         to_file = cvar("sv_logscores_file");
961
962         if(!final)
963         {
964                 to_console = TRUE; // always print printstats replies
965                 to_eventlog = FALSE; // but never print them to the event log
966         }
967
968         if(to_eventlog)
969                 if(cvar("sv_eventlog_console"))
970                         to_console = FALSE; // otherwise we get the output twice
971
972         if(final)
973                 s = ":scores:";
974         else
975                 s = ":status:";
976 #ifdef MAPINFO
977         s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
978 #else
979         s = strcat(s, GetMapname(), ":", ftos(rint(time)));
980 #endif
981
982         if(to_console)
983                 ServerConsoleEcho(s, FALSE);
984         if(to_eventlog)
985                 GameLogEcho(s, FALSE);
986         if(to_file)
987         {
988                 file = fopen(cvar_string("sv_logscores_filename"), FILE_APPEND);
989                 if(file == -1)
990                         to_file = FALSE;
991                 else
992                         fputs(file, strcat(s, "\n"));
993         }
994
995         FOR_EACH_CLIENT(other)
996         {
997                 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && cvar("sv_logscores_bots")))
998                 {
999                         s = strcat(":player:", ftos(other.frags), ":");
1000                         s = strcat(s, ftos(other.deaths), ":");
1001                         s = strcat(s, ftos(rint(time - other.jointime)), ":");
1002                         s = strcat(s, ftos(other.team), ":");
1003
1004                         if(to_console)
1005                                 ServerConsoleEcho(strcat(s, other.netname), TRUE);
1006                         if(to_eventlog)
1007                                 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname), TRUE);
1008                         if(to_file)
1009                                 fputs(file, strcat(s, other.netname, "\n"));
1010                 }
1011         }
1012
1013         if(to_console)
1014                 ServerConsoleEcho(":end", FALSE);
1015         if(to_eventlog)
1016                 GameLogEcho(":end", FALSE);
1017         if(to_file)
1018         {
1019                 fputs(file, ":end\n");
1020                 fclose(file);
1021         }
1022 }
1023
1024 void FixIntermissionClient(entity e)
1025 {
1026         string s;
1027         if(!e.autoscreenshot) // initial call
1028         {
1029                 e.angles = e.v_angle;
1030                 e.angles_x = -e.angles_x;
1031                 e.autoscreenshot = time + 0.8;  // used for autoscreenshot
1032                 e.health = -2342;
1033                 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1034                 e.solid = SOLID_NOT;
1035                 e.movetype = MOVETYPE_NONE;
1036                 e.takedamage = DAMAGE_NO;
1037                 if(e.weaponentity)
1038                         e.weaponentity.effects = EF_NODRAW;
1039                 if(clienttype(e) == CLIENTTYPE_REAL)
1040                 {
1041                         stuffcmd(e, "\nscr_printspeed 1000000\n");
1042                         s = cvar_string("sv_intermission_cdtrack");
1043                         if(s != "")
1044                                 stuffcmd(e, strcat("\ncd loop ", s, "\n"));
1045                         msg_entity = e;
1046                         WriteByte(MSG_ONE, SVC_INTERMISSION);
1047                 }
1048         }
1049
1050         //e.velocity = '0 0 0';
1051         //e.fixangle = TRUE;
1052
1053         // TODO halt weapon animation
1054 }
1055
1056
1057 /*
1058 go to the next level for deathmatch
1059 only called if a time or frag limit has expired
1060 */
1061 void NextLevel()
1062 {
1063         float minTotalFrags;
1064         float maxTotalFrags;
1065         float score;
1066         float f;
1067
1068         gameover = TRUE;
1069
1070         intermission_running = 1;
1071
1072 // enforce a wait time before allowing changelevel
1073         if(player_count > 0)
1074                 intermission_exittime = time + cvar("sv_mapchange_delay");
1075         else
1076                 intermission_exittime = -1;
1077
1078         /*
1079         WriteByte (MSG_ALL, SVC_CDTRACK);
1080         WriteByte (MSG_ALL, 3);
1081         WriteByte (MSG_ALL, 3);
1082         // done in FixIntermission
1083         */
1084
1085         //pos = FindIntermission ();
1086
1087         VoteReset();
1088
1089         DumpStats(TRUE);
1090
1091         if(cvar("sv_eventlog"))
1092                 GameLogEcho(":gameover", FALSE);
1093
1094         GameLogClose();
1095
1096         FOR_EACH_CLIENT(other)
1097         {
1098                 FixIntermissionClient(other);
1099
1100                 if(other.winning)
1101                         bprint(other.netname, " ^7wins.\n");
1102         }
1103
1104         minTotalFrags = 0;
1105         maxTotalFrags = 0;
1106         FOR_EACH_PLAYER(other)
1107         {
1108                 if(maxTotalFrags < other.totalfrags)
1109                         maxTotalFrags = other.totalfrags;
1110                 if(minTotalFrags > other.totalfrags)
1111                         minTotalFrags = other.totalfrags;
1112         }
1113
1114         if(!currentbots)
1115         {
1116                 FOR_EACH_PLAYER(other)
1117                 {
1118                         score = (other.totalfrags - minTotalFrags) / max(maxTotalFrags - minTotalFrags, 1);
1119                         f = bound(0, other.play_time / max(time, 1), 1);
1120                         // store some statistics?
1121                 }
1122         }
1123
1124         if(cvar("g_campaign"))
1125                 CampaignPreIntermission();
1126
1127         // WriteByte (MSG_ALL, SVC_INTERMISSION);
1128 };
1129
1130 /*
1131 ============
1132 CheckRules_Player
1133
1134 Exit deathmatch games upon conditions
1135 ============
1136 */
1137 .float fogtime;
1138 void CheckRules_Player()
1139 {
1140         if (gameover)   // someone else quit the game already
1141                 return;
1142
1143         if(self.deadflag == DEAD_NO)
1144                 self.play_time += frametime;
1145
1146         if(sv_foginterval)
1147         if(world.fog)
1148         if(time > self.fogtime)
1149         {
1150                 stuffcmd(self, strcat("\nfog ", world.fog, "\nr_fog_exp2 0\nr_drawfog 1\n"));
1151                 self.fogtime = time + sv_foginterval;
1152         }
1153
1154         // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1155         //   (div0: and that in CheckRules_World please)
1156 };
1157
1158 float checkrules_oneminutewarning;
1159 float checkrules_leaderfrags;
1160 float tdm_max_score, tdm_old_score;
1161
1162 float checkrules_equality;
1163 float checkrules_overtimewarning;
1164 float checkrules_overtimeend;
1165
1166 void InitiateOvertime()
1167 {
1168         if(!checkrules_overtimeend)
1169                 checkrules_overtimeend = time + 60 * cvar("timelimit_maxovertime");
1170 }
1171
1172 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1173 float WINNING_YES = 1; // winner found
1174 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1175 float WINNING_STARTOVERTIME = 3; // no winner, enter overtime NOW
1176
1177 float GetWinningCode(float fraglimitreached, float equality)
1178 {
1179         if(equality)
1180                 if(fraglimitreached)
1181                         return WINNING_STARTOVERTIME;
1182                 else
1183                         return WINNING_NEVER;
1184         else
1185                 if(fraglimitreached)
1186                         return WINNING_YES;
1187                 else
1188                         return WINNING_NO;
1189 }
1190
1191 // set the .winning flag for exactly those players with a given field value
1192 void SetWinners(.float field, float value)
1193 {
1194         entity head;
1195         FOR_EACH_PLAYER(head)
1196                 head.winning = (head.field == value);
1197 }
1198
1199 // set the .winning flag for those players with a given field value
1200 void AddWinners(.float field, float value)
1201 {
1202         entity head;
1203         FOR_EACH_PLAYER(head)
1204                 if(head.field == value)
1205                         head.winning = 1;
1206 }
1207
1208 // clear frags for all players but the team given (when they ran out of spawnpoints)
1209 void ClearFragsForEveryoneBut(.float field, float value)
1210 {
1211         entity head;
1212         FOR_EACH_PLAYER(head)
1213                 if(head.field != value)
1214                         head.frags = max(head.frags, 0);
1215 }
1216
1217 // clear the .winning flags
1218 void ClearWinners(void)
1219 {
1220         entity head;
1221         FOR_EACH_PLAYER(head)
1222                 head.winning = 0;
1223 }
1224
1225 // Onslaught winning condition:
1226 // game terminates if only one team has a working generator (or none)
1227 float WinningCondition_Onslaught()
1228 {
1229         entity head;
1230         local float t1, t2, t3, t4;
1231         // first check if the game has ended
1232         t1 = t2 = t3 = t4 = 0;
1233         head = find(world, classname, "onslaught_generator");
1234         while (head)
1235         {
1236                 if (head.health > 0)
1237                 {
1238                         if (head.team == COLOR_TEAM1) t1 = 1;
1239                         if (head.team == COLOR_TEAM2) t2 = 1;
1240                         if (head.team == COLOR_TEAM3) t3 = 1;
1241                         if (head.team == COLOR_TEAM4) t4 = 1;
1242                 }
1243                 head = find(head, classname, "onslaught_generator");
1244         }
1245         if (t1 + t2 + t3 + t4 < 2)
1246         {
1247                 // game over, only one team remains (or none)
1248                 ClearWinners();
1249                 if (t1) SetWinners(team, COLOR_TEAM1);
1250                 if (t2) SetWinners(team, COLOR_TEAM2);
1251                 if (t3) SetWinners(team, COLOR_TEAM3);
1252                 if (t4) SetWinners(team, COLOR_TEAM4);
1253                 dprint("Have a winner, ending game.\n");
1254                 return WINNING_YES;
1255         }
1256
1257         // Two or more teams remain
1258         return WINNING_NO;
1259 }
1260
1261 float LMS_NewPlayerLives()
1262 {
1263         float fl;
1264         fl = cvar("fraglimit");
1265         if(fl == 0)
1266                 fl = 999;
1267
1268         // first player has left the game for dying too much? Nobody else can get in.
1269         if(lms_lowest_lives < 1)
1270                 return FALSE;
1271
1272         if(!cvar("g_lms_join_anytime"))
1273                 if(lms_lowest_lives < fl - cvar("g_lms_last_join"))
1274                         return FALSE;
1275
1276         return bound(1, lms_lowest_lives, fl);
1277 }
1278
1279 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1280 // they win. Otherwise the defending team wins once the timelimit passes.
1281 void assault_new_round();
1282 float WinningCondition_Assault()
1283 {
1284         local float status;
1285         status = WINNING_NO;
1286
1287         // as the timelimit has not yet passed just assume the defending team will win
1288         if(assault_attacker_team == COLOR_TEAM1)
1289         {
1290                 SetWinners(team, COLOR_TEAM2);
1291         }
1292         else
1293         {
1294                 SetWinners(team, COLOR_TEAM1);
1295         }
1296
1297         local entity ent;
1298         ent = find(world, classname, "target_assault_roundend");
1299         if(ent)
1300         {
1301                 if(ent.winning) // round end has been triggered by attacking team
1302                 {
1303                         SetWinners(team, assault_attacker_team);
1304                         if(assault_attacker_team == COLOR_TEAM1)
1305                         {
1306                                 team1_score = team1_score + 50;
1307                         }
1308                         else
1309                         {
1310                                 team2_score = team2_score + 50;
1311                         }
1312
1313                         if(ent.cnt == 1) // this was the second round
1314                         {
1315                                 status = WINNING_YES;
1316                         }
1317                         else
1318                         {
1319                                 cvar_set("timelimit", ftos((2*time)/60));
1320                                 assault_new_round();
1321                         }
1322                 }
1323         }
1324
1325         return status;
1326
1327 }
1328
1329
1330 // LMS winning condition: game terminates if and only if there's at most one
1331 // one player who's living lives. Top two scores being equal cancels the time
1332 // limit.
1333 float WinningCondition_LMS()
1334 {
1335         entity head;
1336         float have_player;
1337         float have_players;
1338         float l;
1339
1340         have_player = FALSE;
1341         have_players = FALSE;
1342         l = LMS_NewPlayerLives();
1343
1344         head = find(world, classname, "player");
1345         if(head)
1346                 have_player = TRUE;
1347         head = find(head, classname, "player");
1348         if(head)
1349                 have_players = TRUE;
1350
1351         if(have_player)
1352         {
1353                 // we have at least one player
1354                 if(have_players)
1355                 {
1356                         // two or more active players - continue with the game
1357                 }
1358                 else
1359                 {
1360                         // exactly one player?
1361                         if(l)
1362                         {
1363                                 // but no game has taken place yet
1364                         }
1365                         else
1366                         {
1367                                 // a winner!
1368                                 ClearWinners(); SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1369                                 dprint("Have a winner, ending game.\n");
1370                                 return WINNING_YES;
1371                         }
1372                 }
1373         }
1374         else
1375         {
1376                 // nobody is playing at all...
1377                 if(l)
1378                 {
1379                         // wait for players...
1380                 }
1381                 else
1382                 {
1383                         // SNAFU (maybe a draw game?)
1384                         ClearWinners();
1385                         dprint("No players, ending game.\n");
1386                         return WINNING_YES;
1387                 }
1388         }
1389
1390         // When we get here, we have at least two players who are actually LIVING,
1391         // or one player who is still waiting for a victim to join the server. Now
1392         // check if the top two players have equal score.
1393
1394         checkrules_leaderfrags = 0;
1395         checkrules_equality = FALSE;
1396         FOR_EACH_PLAYER(head)
1397         {
1398                 if(head.frags > checkrules_leaderfrags)
1399                 {
1400                         checkrules_leaderfrags = head.frags;
1401                         checkrules_equality = FALSE;
1402                 }
1403                 else if(head.frags > 0 && head.frags == checkrules_leaderfrags)
1404                         checkrules_equality = TRUE;
1405         }
1406
1407         SetWinners(frags, checkrules_leaderfrags);
1408
1409         // The top two players have the same amount of lives? No timelimit then,
1410         // enter overtime...
1411
1412         if(checkrules_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 // DM winning condition: game terminates if a player reached the fraglimit,
1420 // unless the first two players have the same score. The latter case also
1421 // breaks the time limit.
1422 float WinningCondition_MaxIndividualScore(float fraglimit)
1423 {
1424         float checkrules_oldleaderfrags;
1425         entity head;
1426
1427         checkrules_oldleaderfrags = checkrules_leaderfrags;
1428         checkrules_leaderfrags = 0;
1429         checkrules_equality = FALSE;
1430         FOR_EACH_PLAYER(head)
1431         {
1432                 if(head.frags > checkrules_leaderfrags)
1433                 {
1434                         checkrules_leaderfrags = head.frags;
1435                         checkrules_equality = FALSE;
1436                 }
1437                 else if(head.frags > 0 && head.frags == checkrules_leaderfrags)
1438                         checkrules_equality = TRUE;
1439         }
1440
1441         if(checkrules_leaderfrags > 0)
1442                 SetWinners(frags, checkrules_leaderfrags);
1443         else
1444                 ClearWinners();
1445
1446         if (!g_runematch)
1447                 if (checkrules_leaderfrags != checkrules_oldleaderfrags)
1448                 {
1449                         if (checkrules_leaderfrags == fraglimit - 1)
1450                                 sound(world, CHAN_AUTO, "announcer/robotic/1fragleft.wav", 1, ATTN_NONE);
1451                         else if (checkrules_leaderfrags == fraglimit - 2)
1452                                 sound(world, CHAN_AUTO, "announcer/robotic/2fragsleft.wav", 1, ATTN_NONE);
1453                         else if (checkrules_leaderfrags == fraglimit - 3)
1454                                 sound(world, CHAN_AUTO, "announcer/robotic/3fragsleft.wav", 1, ATTN_NONE);
1455                 }
1456
1457         return GetWinningCode(fraglimit && checkrules_leaderfrags >= fraglimit, checkrules_equality);
1458 }
1459
1460 float WinningConditionBase_Teamplay(float fraglimit)
1461 {
1462         tdm_old_score = tdm_max_score;
1463         tdm_max_score = max4(team1_score, team2_score, team3_score, team4_score);
1464
1465         checkrules_equality =
1466         (
1467                 (tdm_max_score > 0)
1468                 &&
1469                 (
1470                           (team1_score == tdm_max_score)
1471                         + (team2_score == tdm_max_score)
1472                         + (team3_score == tdm_max_score)
1473                         + (team4_score == tdm_max_score)
1474                         >= 2));
1475
1476         ClearWinners();
1477         if(tdm_max_score > 0)
1478         {
1479                 if(team1_score == tdm_max_score)
1480                         AddWinners(team, COLOR_TEAM1);
1481                 if(team2_score == tdm_max_score)
1482                         AddWinners(team, COLOR_TEAM2);
1483                 if(team3_score == tdm_max_score)
1484                         AddWinners(team, COLOR_TEAM3);
1485                 if(team4_score == tdm_max_score)
1486                         AddWinners(team, COLOR_TEAM4);
1487         }
1488
1489         if(!g_runematch && !g_domination && !g_ctf)
1490                 if(tdm_max_score != tdm_old_score)
1491                 {
1492                         if(tdm_max_score == fraglimit - 1)
1493                                 sound(world, CHAN_AUTO, "announcer/robotic/1fragleft.wav", 1, ATTN_NONE);
1494                         else if(tdm_max_score == fraglimit - 2)
1495                                 sound(world, CHAN_AUTO, "announcer/robotic/2fragsleft.wav", 1, ATTN_NONE);
1496                         else if(tdm_max_score == fraglimit - 3)
1497                                 sound(world, CHAN_AUTO, "announcer/robotic/3fragsleft.wav", 1, ATTN_NONE);
1498                 }
1499
1500         return GetWinningCode(fraglimit && tdm_max_score >= fraglimit, checkrules_equality);
1501 }
1502
1503 // TDM winning condition: game terminates if a team's score sum reached the
1504 // fraglimit, unless the first two teams have the same total score. The latter
1505 // case also breaks the time limit.
1506 float WinningCondition_MaxTeamSum(float fraglimit)
1507 {
1508         entity head;
1509
1510         team1_score = team2_score = team3_score = team4_score = 0;
1511
1512         FOR_EACH_PLAYER(head)
1513         {
1514                 if(head.team == COLOR_TEAM1)
1515                         team1_score += head.frags;
1516                 else if(head.team == COLOR_TEAM2)
1517                         team2_score += head.frags;
1518                 else if(head.team == COLOR_TEAM3)
1519                         team3_score += head.frags;
1520                 else if(head.team == COLOR_TEAM4)
1521                         team4_score += head.frags;
1522         }
1523
1524         return WinningConditionBase_Teamplay(fraglimit);
1525 }
1526
1527 // DOM/CTF winning condition: game terminates if the max of a team's players'
1528 // score reached the fraglimit, unless the first two teams have the same
1529 // maximum score. The latter case also breaks the time limit.
1530 float WinningCondition_MaxTeamMax(float fraglimit)
1531 {
1532         entity head;
1533
1534         team1_score = team2_score = team3_score = team4_score = 0;
1535
1536         FOR_EACH_PLAYER(head)
1537         {
1538                 if(head.team == COLOR_TEAM1)
1539                 {
1540                         if(head.frags > team1_score)
1541                                 team1_score = head.frags;
1542                 }
1543                 else if(head.team == COLOR_TEAM2)
1544                 {
1545                         if(head.frags > team2_score)
1546                                 team2_score = head.frags;
1547                 }
1548                 else if(head.team == COLOR_TEAM3)
1549                 {
1550                         if(head.frags > team3_score)
1551                                 team3_score = head.frags;
1552                 }
1553                 else if(head.team == COLOR_TEAM4)
1554                 {
1555                         if(head.frags > team4_score)
1556                                 team4_score = head.frags;
1557                 }
1558         }
1559
1560         return WinningConditionBase_Teamplay(fraglimit);
1561 }
1562
1563 float WinningCondition_CTF(float capturelimit, float fraglimit)
1564 {
1565         if(cvar("g_ctf_win_mode") == 2)
1566                 return WinningCondition_MaxTeamSum(fraglimit);
1567         
1568         team1_score = caps_team1;
1569         team2_score = caps_team2;
1570         team3_score = team4_score = 0;
1571
1572         if(team1_score == team2_score && cvar("g_ctf_win_mode"))
1573         {
1574                 return WinningCondition_MaxTeamSum(0);
1575         }
1576
1577         return WinningConditionBase_Teamplay(capturelimit);
1578 }
1579
1580 void print_to(entity e, string s)
1581 {
1582         if(e)
1583                 sprint(e, strcat(s, "\n"));
1584         else
1585                 ServerConsoleEcho(s, TRUE);
1586 }
1587
1588 void PrintScoreboardFor(entity e, string name, string colorcode, float whichteam)
1589 {
1590         entity head;
1591         float v;
1592         float teamvalue;
1593         float fragtotal;
1594         string s;
1595         float found;
1596         found = FALSE;
1597         teamvalue = 0;
1598         FOR_EACH_PLAYER(head)
1599         {
1600                 if(!whichteam || head.team == whichteam)
1601                 {
1602                         if(name != "")
1603                                 if(!found)
1604                                         print_to(e, strcat(" ", colorcode, name, ":"));
1605                         found = TRUE;
1606                         fragtotal = fragtotal + head.frags;
1607                         s = ftos(head.frags);
1608                         s = strcat(s, "/", ftos(head.deaths));
1609                         s = strcat(s, " @ ", ftos(head.ping));
1610                         if(clienttype(head) == CLIENTTYPE_BOT)
1611                                 s = strcat(s, "botms");
1612                         else
1613                                 s = strcat(s, "ms");
1614                         v = PlayerValue(head);
1615                         teamvalue += v;
1616                         s = strcat(s, " / ", ftos(v));
1617                         print_to(e, strcat("  ", colorcode, head.netname, colorcode, " (", s, ")"));
1618                 }
1619         }
1620         if(whichteam && found)
1621         {
1622                 s = ftos(fragtotal);
1623                 s = strcat(s, " / ", ftos(teamvalue));
1624                 print_to(e, strcat(colorcode, "  (total: ", s, ")"));
1625         }
1626 }
1627
1628 void PrintScoreboard(entity e)
1629 {
1630         print_to(e, strcat("Time:      ", ftos(time / 60)));
1631         print_to(e, strcat("Timelimit: ", ftos(cvar("timelimit"))));
1632         print_to(e, strcat("Fraglimit: ", ftos(cvar("fraglimit"))));
1633         print_to(e, "Scoreboard:");
1634         if(teams_matter)
1635         {
1636                 PrintScoreboardFor(e, "Red", "^1", COLOR_TEAM1);
1637                 PrintScoreboardFor(e, "Blue", "^4", COLOR_TEAM2);
1638                 PrintScoreboardFor(e, "Yellow", "^3", COLOR_TEAM3);
1639                 PrintScoreboardFor(e, "Pink", "^6", COLOR_TEAM4);
1640         }
1641         else
1642         {
1643                 PrintScoreboardFor(e, "", "^7", 0);
1644         }
1645         print_to(e, ".");
1646 }
1647
1648 void ShuffleMaplist()
1649 {
1650         string result;
1651         float start;
1652         float litems;
1653         float selected;
1654         float i;
1655
1656         result = cvar_string("g_maplist");
1657 #ifdef MAPINFO
1658         litems = tokenizebyseparator(result, " ");
1659 #else
1660         litems = tokenize(result);
1661 #endif
1662
1663         for(start = 0; start < litems - 1; ++start)
1664         {
1665                 result = "";
1666
1667                 // select a random item
1668                 selected = ceil(random() * (litems - start) + start) - 1;
1669
1670                 // shift this item to the place start
1671 #ifdef MAPINFO
1672                 for(i = 0; i < start; ++i)
1673                         result = strcat(result, " ", argv(i));
1674                 result = strcat(result, " ", argv(selected));
1675                 for(i = start; i < litems; ++i)
1676                         if(i != selected)
1677                                 result = strcat(result, " ", argv(i));
1678                 result = substring(result, 1, strlen(result) - 1);
1679
1680                 litems = tokenizebyseparator(result, " ");
1681 #else
1682                 for(i = 0; i < start; ++i)
1683                         result = strcat(result, "'", argv(i), "'");
1684                 result = strcat(result, "'", argv(selected), "'");
1685                 for(i = start; i < litems; ++i)
1686                         if(i != selected)
1687                                 result = strcat(result, "'", argv(i), "'");
1688
1689                 litems = tokenize(result);
1690 #endif
1691
1692                 //dprint(result, "\n");
1693         }
1694
1695         cvar_set("g_maplist", result);
1696 }
1697
1698 float WinningCondition_RanOutOfSpawns()
1699 {
1700         entity head;
1701
1702         if(!have_team_spawns)
1703                 return WINNING_NO;
1704
1705         if(!some_spawn_has_been_used)
1706                 return WINNING_NO;
1707
1708         team1_score = team2_score = team3_score = team4_score = 0;
1709
1710         FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
1711         {
1712                 if(head.team == COLOR_TEAM1)
1713                         team1_score = 1;
1714                 else if(head.team == COLOR_TEAM2)
1715                         team2_score = 1;
1716                 else if(head.team == COLOR_TEAM3)
1717                         team3_score = 1;
1718                 else if(head.team == COLOR_TEAM4)
1719                         team4_score = 1;
1720         }
1721
1722         for(head = world; (head = find(head, classname, "info_player_deathmatch")) != world; )
1723         {
1724                 if(head.team == COLOR_TEAM1)
1725                         team1_score = 1;
1726                 else if(head.team == COLOR_TEAM2)
1727                         team2_score = 1;
1728                 else if(head.team == COLOR_TEAM3)
1729                         team3_score = 1;
1730                 else if(head.team == COLOR_TEAM4)
1731                         team4_score = 1;
1732         }
1733
1734         ClearWinners();
1735         if(team1_score + team2_score + team3_score + team4_score == 0)
1736         {
1737                 checkrules_equality = TRUE;
1738                 return WINNING_YES;
1739         }
1740         else if(team1_score + team2_score + team3_score + team4_score == 1)
1741         {
1742                 if(team1_score)
1743                 {
1744                         AddWinners(team, COLOR_TEAM1);
1745                         ClearFragsForEveryoneBut(team, COLOR_TEAM1);
1746                 }
1747                 if(team2_score)
1748                 {
1749                         AddWinners(team, COLOR_TEAM2);
1750                         ClearFragsForEveryoneBut(team, COLOR_TEAM2);
1751                 }
1752                 if(team3_score)
1753                 {
1754                         AddWinners(team, COLOR_TEAM3);
1755                         ClearFragsForEveryoneBut(team, COLOR_TEAM3);
1756                 }
1757                 if(team4_score)
1758                 {
1759                         AddWinners(team, COLOR_TEAM4);
1760                         ClearFragsForEveryoneBut(team, COLOR_TEAM4);
1761                 }
1762                 return WINNING_YES;
1763         }
1764         else
1765                 return WINNING_NO;
1766 }
1767
1768 /*
1769 ============
1770 CheckRules_World
1771
1772 Exit deathmatch games upon conditions
1773 ============
1774 */
1775 void CheckRules_World()
1776 {
1777         local float status;
1778         local float timelimit;
1779         local float fraglimit;
1780         local float capturelimit;
1781
1782         VoteThink();
1783         MapVote_Think();
1784
1785         SetDefaultAlpha();
1786
1787         /*
1788         MapVote_Think should now do that part
1789         if (intermission_running)
1790                 if (time >= intermission_exittime + 60)
1791                 {
1792                         if(!DoNextMapOverride())
1793                                 GotoNextMap();
1794                         return;
1795                 }
1796         */
1797
1798         if (gameover)   // someone else quit the game already
1799         {
1800                 if(player_count == 0) // Nobody there? Then let's go to the next map
1801                         MapVote_Start();
1802                         // this will actually check the player count in the next frame
1803                         // again, but this shouldn't hurt
1804                 return;
1805         }
1806
1807         timelimit = cvar("timelimit") * 60;
1808         fraglimit = cvar("fraglimit");
1809         capturelimit = cvar("capturelimit");
1810
1811         if(checkrules_overtimeend)
1812         {
1813                 if(!checkrules_overtimewarning)
1814                 {
1815                         checkrules_overtimewarning = TRUE;
1816                         //sound(world, CHAN_AUTO, "announcer/robotic/1minuteremains.wav", 1, ATTN_NONE);
1817                         bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
1818                 }
1819         }
1820         else
1821         {
1822                 if (timelimit && time >= timelimit)
1823                         InitiateOvertime();
1824         }
1825
1826         if (checkrules_overtimeend && time >= checkrules_overtimeend)
1827         {
1828                 NextLevel();
1829                 return;
1830         }
1831
1832         if (!checkrules_oneminutewarning && timelimit > 0 && time > timelimit - 60)
1833         {
1834                 checkrules_oneminutewarning = TRUE;
1835                 sound(world, CHAN_AUTO, "announcer/robotic/1minuteremains.wav", 1, ATTN_NONE);
1836         }
1837
1838         status = WinningCondition_RanOutOfSpawns();
1839         if(status == WINNING_YES)
1840         {
1841                 bprint("Hey! Someone ran out of spawns!\n");
1842         }
1843         else if(g_assault)
1844         {
1845                 status = WinningCondition_Assault();
1846         }
1847         else if(g_lms)
1848         {
1849                 status = WinningCondition_LMS();
1850         }
1851         else if (g_onslaught)
1852         {
1853                 status = WinningCondition_Onslaught();
1854         }
1855         else if(g_ctf)
1856         {
1857                 status = WinningCondition_CTF(capturelimit, fraglimit);
1858         }
1859         else
1860         {
1861                 if(teams_matter)
1862                 {
1863                         if(g_tdm || g_runematch || g_ctf || g_domination || g_keyhunt)
1864                                 status = WinningCondition_MaxTeamSum(fraglimit);
1865                         //else if()
1866                         //      status = WinningCondition_MaxTeamMax(fraglimit);
1867                         else
1868                         {
1869                                 dprint("div0: How can this happen?\n");
1870                                 status = WinningCondition_MaxTeamMax(fraglimit);
1871                         }
1872                 }
1873                 else
1874                         status = WinningCondition_MaxIndividualScore(fraglimit);
1875         }
1876
1877         if(status == WINNING_STARTOVERTIME)
1878         {
1879                 status = WINNING_NEVER;
1880                 InitiateOvertime();
1881         }
1882
1883         if(status == WINNING_NEVER)
1884                 // equality cases! Nobody wins if the overtime ends in a draw.
1885                 ClearWinners();
1886
1887         if(checkrules_overtimeend)
1888                 if(status != WINNING_NEVER || time >= checkrules_overtimeend)
1889                         status = WINNING_YES;
1890
1891         if(status == WINNING_YES)
1892                 NextLevel();
1893 };
1894
1895 float randsel_value;
1896 float randsel_priority;
1897 float randsel_count;
1898 void RandSel_Init()
1899 {
1900         randsel_value = -1;
1901         randsel_priority = -1;
1902         randsel_count = -1;
1903 }
1904 void RandSel_Add(float priority, float value)
1905 {
1906         if(priority > randsel_priority)
1907         {
1908                 randsel_priority = priority;
1909                 randsel_value = value;
1910                 randsel_count = 1;
1911         }
1912         else if(priority == randsel_priority)
1913         {
1914                 randsel_count += 1;
1915                 if(ceil(random() * randsel_count) == 1)
1916                         randsel_value = value;
1917         }
1918 }
1919
1920 float mapvote_nextthink;
1921 float mapvote_initialized;
1922 float mapvote_keeptwotime;
1923 float mapvote_timeout;
1924 string mapvote_message;
1925
1926 float mapvote_count;
1927 float mapvote_count_real;
1928 string mapvote_maps[MAPVOTE_COUNT];
1929 float mapvote_maps_suggested[MAPVOTE_COUNT];
1930 string mapvote_suggestions[MAPVOTE_COUNT];
1931 float mapvote_suggestion_ptr;
1932 float mapvote_maxlen;
1933 float mapvote_voters;
1934 float mapvote_votes[MAPVOTE_COUNT];
1935 float mapvote_run;
1936 float mapvote_detail;
1937 float mapvote_abstain;
1938 float mapvote_dirty;
1939 .float mapvote;
1940
1941 void MapVote_ClearAllVotes()
1942 {
1943         FOR_EACH_CLIENT(other)
1944                 other.mapvote = 0;
1945 }
1946
1947 string MapVote_Suggest(string m)
1948 {
1949         float i;
1950         if(m == "")
1951                 return "That's not how to use this command.";
1952         if(!cvar("g_maplist_votable_suggestions"))
1953                 return "Suggestions are not accepted on this server.";
1954         if(mapvote_initialized)
1955                 return "Can't suggest - voting is already in progress!";
1956 #ifdef MAPINFO
1957         m = MapInfo_FixName(m);
1958         if(!m)
1959                 return "The map you suggested is not available on this server.";
1960 #else
1961         if(!cvar("g_maplist_votable_suggestions_change_gametype"))
1962                 if(!IsSameGametype(m))
1963                         return "This server does not allow changing the game type by map suggestions.";
1964 #endif
1965         if(!cvar("g_maplist_votable_override_mostrecent"))
1966                 if(Map_IsRecent(m))
1967                         return "This server does not allow for recent maps to be played again. Please be patient for some rounds.";
1968
1969 #ifdef MAPINFO
1970         if(!MapInfo_CheckMap(m))
1971                 return "The map you suggested does not support the current game mode.";
1972 #else
1973         if(!TryFile(strcat("maps/", m, ".mapcfg")))
1974                 return "The map you suggested is not available on this server.";
1975 #endif
1976         for(i = 0; i < mapvote_suggestion_ptr; ++i)
1977                 if(mapvote_suggestions[i] == m)
1978                         return "This map was already suggested.";
1979         if(mapvote_suggestion_ptr >= MAPVOTE_COUNT)
1980         {
1981                 i = ceil(random() * mapvote_suggestion_ptr) - 1;
1982         }
1983         else
1984         {
1985                 i = mapvote_suggestion_ptr;
1986                 mapvote_suggestion_ptr += 1;
1987         }
1988         if(mapvote_suggestions[i] != "")
1989                 strunzone(mapvote_suggestions[i]);
1990         mapvote_suggestions[i] = strzone(m);
1991         if(cvar("sv_eventlog"))
1992                 GameLogEcho(strcat(":vote:suggested:", m, ":", ftos(self.playerid)), TRUE);
1993         return strcat("Suggestion of ", m, " accepted.");
1994 }
1995
1996 void MapVote_AddVotable(string nextMap, float isSuggestion)
1997 {
1998         float j;
1999         if(nextMap == "")
2000                 return;
2001         for(j = 0; j < mapvote_count; ++j)
2002                 if(mapvote_maps[j] == nextMap)
2003                         return;
2004         if(strlen(nextMap) > mapvote_maxlen)
2005                 mapvote_maxlen = strlen(nextMap);
2006         mapvote_maps[mapvote_count] = strzone(nextMap);
2007         mapvote_maps_suggested[mapvote_count] = isSuggestion;
2008         mapvote_count += 1;
2009 }
2010
2011 void MapVote_SendData(float target);
2012 void MapVote_Init()
2013 {
2014         float i;
2015         float nmax, smax;
2016
2017         MapVote_ClearAllVotes();
2018
2019         mapvote_count = 0;
2020         mapvote_detail = !cvar("g_maplist_votable_nodetail");
2021         mapvote_abstain = cvar("g_maplist_votable_abstain");
2022
2023         if(mapvote_abstain)
2024                 nmax = min(MAPVOTE_COUNT - 1, cvar("g_maplist_votable"));
2025         else
2026                 nmax = min(MAPVOTE_COUNT, cvar("g_maplist_votable"));
2027         smax = min3(nmax, cvar("g_maplist_votable_suggestions"), mapvote_suggestion_ptr);
2028
2029         if(mapvote_suggestion_ptr)
2030                 for(i = 0; i < 100 && mapvote_count < smax; ++i)
2031                         MapVote_AddVotable(mapvote_suggestions[ceil(random() * mapvote_suggestion_ptr) - 1], TRUE);
2032
2033         for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2034                 MapVote_AddVotable(GetNextMap(), FALSE);
2035
2036         if(mapvote_count == 0)
2037         {
2038                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
2039 #ifdef MAPINFO
2040                 cvar_set("g_maplist", MapInfo_ListAllowedMaps());
2041                 localcmd("\nmenu_cmd sync\n");
2042 #else
2043                 cvar_set("g_maplist", cvar_string("g_maplist_defaultlist"));
2044 #endif
2045                 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2046                         MapVote_AddVotable(GetNextMap(), FALSE);
2047         }
2048
2049         mapvote_count_real = mapvote_count;
2050         if(mapvote_abstain)
2051                 MapVote_AddVotable("don't care", 0);
2052
2053         //dprint("mapvote count is ", ftos(mapvote_count), "\n");
2054
2055         mapvote_keeptwotime = time + cvar("g_maplist_votable_keeptwotime");
2056         mapvote_timeout = time + cvar("g_maplist_votable_timeout");
2057         if(mapvote_count_real < 3 || mapvote_keeptwotime <= time)
2058                 mapvote_keeptwotime = 0;
2059         mapvote_message = "Choose a map and press its key!";
2060
2061         if(!cvar("g_maplist_textonly"))
2062                 MapVote_SendData(MSG_BROADCAST);
2063 }
2064
2065 void MapVote_SendPicture(float id)
2066 {
2067         msg_entity = self;
2068         WriteByte(MSG_ONE, SVC_TEMPENTITY);
2069         WriteByte(MSG_ONE, TE_CSQC_MAPVOTE);
2070         WriteByte(MSG_ONE, MAPVOTE_NET_PIC);
2071         WriteByte(MSG_ONE, id);
2072         WritePicture(MSG_ONE, strcat("maps/", mapvote_maps[id]), 1024);
2073 }
2074
2075 float GameCommand_MapVote(string cmd)
2076 {
2077         if(!intermission_running)
2078                 return FALSE;
2079         if(!cvar("g_maplist_textonly"))
2080         {
2081                 if(cmd == "mv_getpic")
2082                 {
2083                         MapVote_SendPicture(stof(argv(1)));
2084                         return TRUE;
2085                 }
2086         }
2087
2088         return FALSE;
2089 }
2090
2091 float MapVote_GetMapMask()
2092 {
2093         float mask, i, power;
2094         mask = 0;
2095         for(i = 0, power = 1; i < mapvote_count; ++i, power *= 2)
2096                 if(mapvote_maps[i] != "")
2097                         mask |= power;
2098         return mask;
2099 }
2100
2101 void MapVote_SendData(float targ)
2102 {
2103         string mapfile;
2104         float i, o, c;
2105         WriteByte(targ, SVC_TEMPENTITY);
2106         WriteByte(targ, TE_CSQC_MAPVOTE);
2107         WriteByte(targ, MAPVOTE_NET_INIT);
2108
2109         WriteByte(targ, mapvote_count);
2110         WriteByte(targ, mapvote_abstain);
2111         WriteByte(targ, mapvote_detail);
2112         if(mapvote_count <= 8)
2113                 WriteByte(targ, MapVote_GetMapMask());
2114         else
2115                 WriteShort(targ, MapVote_GetMapMask());
2116         for(i = 0; i < mapvote_count; ++i)
2117                 if(mapvote_maps[i] != "")
2118                 {
2119                         WriteString(targ, mapvote_maps[i]);
2120                         mapfile = strcat("maps/", mapvote_maps[i], ".bsp");
2121                         mapfile = whichpack(mapfile);
2122                         for(o = strstr(mapfile, "/", 0)+1; o > 0; o = strstr(mapfile, "/", 0)+1)
2123                                 mapfile = substring(mapfile, o, 999);
2124                         WriteString(targ, mapfile);
2125                 }
2126 }
2127
2128 void MapVote_UpdateData(float targ)
2129 {
2130         float i;
2131         WriteByte(targ, SVC_TEMPENTITY);
2132         WriteByte(targ, TE_CSQC_MAPVOTE);
2133         WriteByte(targ, MAPVOTE_NET_UPDATE);
2134         if(mapvote_count <= 8)
2135                 WriteByte(targ, MapVote_GetMapMask());
2136         else
2137                 WriteShort(targ, MapVote_GetMapMask());
2138         if(mapvote_detail)
2139                 for(i = 0; i < mapvote_count; ++i)
2140                         if(mapvote_maps[i] != "")
2141                                 WriteByte(targ, mapvote_votes[i]);
2142 }
2143
2144 void MapVote_TellVote(float targ, float vote)
2145 {
2146         float i;
2147         WriteByte(targ, SVC_TEMPENTITY);
2148         WriteByte(targ, TE_CSQC_MAPVOTE);
2149         WriteByte(targ, MAPVOTE_NET_OWNVOTE);
2150         WriteByte(targ, vote);
2151 }
2152
2153 float MapVote_Finished(float mappos)
2154 {
2155         string result;
2156         float i;
2157         float didntvote;
2158
2159         if(cvar("sv_eventlog"))
2160         {
2161                 result = strcat(":vote:finished:", mapvote_maps[mappos]);
2162                 result = strcat(result, ":", ftos(mapvote_votes[mappos]), "::");
2163                 didntvote = mapvote_voters;
2164                 for(i = 0; i < mapvote_count; ++i)
2165                         if(mapvote_maps[i] != "")
2166                         {
2167                                 didntvote -= mapvote_votes[i];
2168                                 if(i != mappos)
2169                                 {
2170                                         result = strcat(result, ":", mapvote_maps[i]);
2171                                         result = strcat(result, ":", ftos(mapvote_votes[i]));
2172                                 }
2173                         }
2174                 result = strcat(result, ":didn't vote:", ftos(didntvote));
2175
2176                 GameLogEcho(result, FALSE);
2177                 if(mapvote_maps_suggested[mappos])
2178                         GameLogEcho(strcat(":vote:suggestion_accepted:", mapvote_maps[mappos]), FALSE);
2179         }
2180
2181         FOR_EACH_REALCLIENT(other)
2182                 FixClientCvars(other);
2183
2184         Map_Goto_SetStr(mapvote_maps[mappos]);
2185         Map_Goto();
2186         alreadychangedlevel = TRUE;
2187         return TRUE;
2188 }
2189 void MapVote_CheckRules_1()
2190 {
2191         float i;
2192
2193         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
2194         {
2195                 //dprint("Map ", ftos(i), ": "); dprint(mapvote_maps[i], "\n");
2196                 mapvote_votes[i] = 0;
2197         }
2198
2199         mapvote_voters = 0;
2200         FOR_EACH_REALCLIENT(other)
2201         {
2202                 ++mapvote_voters;
2203                 if(other.mapvote)
2204                 {
2205                         i = other.mapvote - 1;
2206                         //dprint("Player ", other.netname, " vote = ", ftos(other.mapvote - 1), "\n");
2207                         mapvote_votes[i] = mapvote_votes[i] + 1;
2208                 }
2209         }
2210 }
2211
2212 float MapVote_CheckRules_2()
2213 {
2214         float i;
2215         float firstPlace, secondPlace;
2216         float firstPlaceVotes, secondPlaceVotes;
2217         float mapvote_voters_real;
2218         string result;
2219
2220         mapvote_voters_real = mapvote_voters;
2221         if(mapvote_abstain)
2222                 mapvote_voters_real -= mapvote_votes[mapvote_count - 1];
2223
2224         RandSel_Init();
2225         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2226                 RandSel_Add(mapvote_votes[i], i);
2227         firstPlace = randsel_value;
2228         firstPlaceVotes = randsel_priority;
2229         //dprint("First place: ", ftos(firstPlace), "\n");
2230         //dprint("First place votes: ", ftos(firstPlaceVotes), "\n");
2231
2232         RandSel_Init();
2233         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2234                 if(i != firstPlace)
2235                         RandSel_Add(mapvote_votes[i], i);
2236         secondPlace = randsel_value;
2237         secondPlaceVotes = randsel_priority;
2238         //dprint("Second place: ", ftos(secondPlace), "\n");
2239         //dprint("Second place votes: ", ftos(secondPlaceVotes), "\n");
2240
2241         if(firstPlace == -1)
2242                 error("No first place in map vote... WTF?");
2243
2244         if(secondPlace == -1 || time > mapvote_timeout || (mapvote_voters_real - firstPlaceVotes) < firstPlaceVotes)
2245                 return MapVote_Finished(firstPlace);
2246
2247         if(mapvote_keeptwotime)
2248                 if(time > mapvote_keeptwotime || (mapvote_voters_real - firstPlaceVotes - secondPlaceVotes) < secondPlaceVotes)
2249                 {
2250                         float didntvote;
2251                         mapvote_dirty = TRUE;
2252                         mapvote_message = "Now decide between the TOP TWO!";
2253                         mapvote_keeptwotime = 0;
2254                         result = strcat(":vote:keeptwo:", mapvote_maps[firstPlace]);
2255                         result = strcat(result, ":", ftos(firstPlaceVotes));
2256                         result = strcat(result, ":", mapvote_maps[secondPlace]);
2257                         result = strcat(result, ":", ftos(secondPlaceVotes), "::");
2258                         didntvote = mapvote_voters;
2259                         for(i = 0; i < mapvote_count; ++i)
2260                                 if(mapvote_maps[i] != "")
2261                                 {
2262                                         didntvote -= mapvote_votes[i];
2263                                         if(i != firstPlace)
2264                                                 if(i != secondPlace)
2265                                                 {
2266                                                         result = strcat(result, ":", mapvote_maps[i]);
2267                                                         result = strcat(result, ":", ftos(mapvote_votes[i]));
2268                                                         if(i < mapvote_count_real)
2269                                                         {
2270                                                                 strunzone(mapvote_maps[i]);
2271                                                                 mapvote_maps[i] = "";
2272                                                         }
2273                                                 }
2274                                 }
2275                         result = strcat(result, ":didn't vote:", ftos(didntvote));
2276                         if(cvar("sv_eventlog"))
2277                                 GameLogEcho(result, FALSE);
2278                 }
2279
2280         return FALSE;
2281 }
2282 void MapVote_Tick()
2283 {
2284         string msgstr;
2285         string tmp;
2286         float i;
2287         float keeptwo;
2288         float totalvotes;
2289
2290         keeptwo = mapvote_keeptwotime;
2291         MapVote_CheckRules_1(); // count
2292         if(MapVote_CheckRules_2()) // decide
2293                 return;
2294
2295         totalvotes = 0;
2296         FOR_EACH_REALCLIENT(other)
2297         {
2298                 // hide scoreboard again
2299                 if(other.health != 2342)
2300                 {
2301                         other.health = 2342;
2302                         other.impulse = 0;
2303                         if(clienttype(other) == CLIENTTYPE_REAL)
2304                         {
2305                                 if(cvar("g_maplist_textonly"))
2306                                         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");
2307
2308                                 msg_entity = other;
2309                                 WriteByte(MSG_ONE, SVC_FINALE);
2310                                 WriteString(MSG_ONE, "");
2311                         }
2312                 }
2313
2314                 // notify about keep-two
2315                 if(keeptwo != 0 && mapvote_keeptwotime == 0)
2316                         play2(other, "misc/invshot.wav");
2317
2318                 // clear possibly invalid votes
2319                 if(mapvote_maps[other.mapvote - 1] == "")
2320                         other.mapvote = 0;
2321                 // use impulses as new vote
2322                 if(other.impulse >= 1 && other.impulse <= mapvote_count)
2323                         if(mapvote_maps[other.impulse - 1] != "")
2324                         {
2325                                 other.mapvote = other.impulse;
2326                                 if(mapvote_detail)
2327                                         mapvote_dirty = TRUE;
2328
2329                                 msg_entity = other;
2330                                 MapVote_TellVote(MSG_ONE, other.mapvote);
2331                         }
2332                 other.impulse = 0;
2333
2334                 if(other.mapvote)
2335                         ++totalvotes;
2336         }
2337
2338         MapVote_CheckRules_1(); // just count
2339
2340         if(!cvar("g_maplist_textonly"))
2341         if(mapvote_dirty) // 1 if "keeptwo" or "impulse" happened before
2342         {
2343                 MapVote_UpdateData(MSG_BROADCAST);
2344                 mapvote_dirty = FALSE;
2345         }
2346
2347         if(cvar("g_maplist_textonly"))
2348         {
2349                 FOR_EACH_REALCLIENT(other)
2350                 {
2351                         // display voting screen
2352                         msgstr = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
2353                         msgstr = substring(msgstr, 0, strlen(msgstr) - mapvote_count);
2354                         if(mapvote_abstain)
2355                                 msgstr = substring(msgstr, 1, strlen(msgstr) - 1);
2356                         msgstr = strcat(msgstr, mapvote_message);
2357                         msgstr = strcat(msgstr, "\n\n");
2358                         for(i = 0; i < mapvote_count; ++i)
2359                                 if(mapvote_maps[i] == "")
2360                                         msgstr = strcat(msgstr, "\n");
2361                                 else
2362                                 {
2363                                         tmp = mapvote_maps[i];
2364                                         tmp = strpad(mapvote_maxlen, tmp);
2365                                         tmp = strcat(ftos(mod(i + 1, 10)), ": ", tmp);
2366                                         if(mapvote_detail)
2367                                         {
2368                                                 tmp = strcat(tmp, " ^2(", ftos(mapvote_votes[i]), " vote");
2369                                                 if(mapvote_votes[i] != 1)
2370                                                         tmp = strcat(tmp, "s");
2371                                                 tmp = strcat(tmp, ")");
2372                                                 tmp = strpad(mapvote_maxlen + 15, tmp);
2373                                         }
2374                                         if(mapvote_abstain)
2375                                                 if(i == mapvote_count - 1)
2376                                                         msgstr = strcat(msgstr, "\n");
2377                                         if(other.mapvote == i + 1)
2378                                                 msgstr = strcat(msgstr, "^3> ", tmp, "\n");
2379                                         else
2380                                                 msgstr = strcat(msgstr, "^7  ", tmp, "\n");
2381                                 }
2382
2383                         msgstr = strcat(msgstr, "\n\n^2", ftos(totalvotes), " vote");
2384                         if(totalvotes != 1)
2385                                 msgstr = strcat(msgstr, "s");
2386                         msgstr = strcat(msgstr, " cast");
2387                         i = ceil(mapvote_timeout - time);
2388                         msgstr = strcat(msgstr, "\n", ftos(i), " second");
2389                         if(i != 1)
2390                                 msgstr = strcat(msgstr, "s");
2391                         msgstr = strcat(msgstr, " left");
2392
2393                         centerprint_atprio(other, CENTERPRIO_MAPVOTE, msgstr);
2394                 }
2395         }
2396 }
2397 void MapVote_Start()
2398 {
2399         if(mapvote_run)
2400                 return;
2401
2402 #ifdef MAPINFO
2403         MapInfo_Enumerate();
2404         if(MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 1))
2405 #endif
2406                 mapvote_run = TRUE;
2407 }
2408 void MapVote_Think()
2409 {
2410         if(!mapvote_run)
2411                 return;
2412
2413         if(alreadychangedlevel)
2414                 return;
2415
2416         if(time < mapvote_nextthink)
2417                 return;
2418         //dprint("tick\n");
2419
2420         mapvote_nextthink = time + 0.5;
2421
2422         if(!mapvote_initialized)
2423         {
2424                 mapvote_initialized = TRUE;
2425                 if(DoNextMapOverride())
2426                         return;
2427                 if(!cvar("g_maplist_votable") || player_count <= 0)
2428                 {
2429                         GotoNextMap();
2430                         return;
2431                 }
2432                 MapVote_Init();
2433         }
2434
2435         MapVote_Tick();
2436 };
2437
2438 string GotoMap(string m)
2439 {
2440 #ifdef MAPINFO
2441         if(!MapInfo_CheckMap(m))
2442 #else
2443         if(!TryFile(strcat("maps/", m, ".mapcfg")))
2444 #endif
2445                 return "The map you chose is not available on this server.";
2446         cvar_set("nextmap", m);
2447         cvar_set("timelimit", "-1");
2448         if(mapvote_initialized || alreadychangedlevel)
2449         {
2450                 if(DoNextMapOverride())
2451                         return "Map switch initiated.";
2452                 else
2453                         return "Hm... no. For some reason I like THIS map more.";
2454         }
2455         else
2456                 return "Map switch will happen after scoreboard.";
2457 }
2458
2459
2460 void EndFrame()
2461 {
2462         FOR_EACH_REALCLIENT(self)
2463         {
2464                 if(self.classname == "spectator")
2465                 {
2466                         if(self.enemy.hitsound)
2467                                 play2(self, "misc/hit.wav");
2468                 }
2469                 else
2470                 {
2471                         if(self.hitsound)
2472                                 play2(self, "misc/hit.wav");
2473                 }
2474         }
2475         FOR_EACH_CLIENT(self)
2476                 self.hitsound = FALSE;
2477 }
2478
2479
2480 /*
2481  * RedirectionThink:
2482  * returns TRUE if redirecting
2483  */
2484 float redirection_timeout;
2485 float redirection_nextthink;
2486 float RedirectionThink()
2487 {
2488         float clients_found;
2489
2490         if(redirection_target == "")
2491                 return FALSE;
2492
2493         if(!redirection_timeout)
2494         {
2495                 cvar_set("sv_public", "-2");
2496                 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2497                 if(redirection_target == "self")
2498                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2499                 else
2500                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2501         }
2502
2503         if(time < redirection_nextthink)
2504                 return TRUE;
2505
2506         redirection_nextthink = time + 1;
2507
2508         clients_found = 0;
2509         FOR_EACH_REALCLIENT(self)
2510         {
2511                 ServerConsoleEcho(strcat("Redirecting: sending connect command to ", self.netname), FALSE);
2512                 if(redirection_target == "self")
2513                         stuffcmd(self, "\ndisconnect; reconnect\n");
2514                 else
2515                         stuffcmd(self, strcat("\ndisconnect; connect ", redirection_target, "\n"));
2516                 ++clients_found;
2517         }
2518
2519         ServerConsoleEcho(strcat("Redirecting: ", ftos(clients_found), " clients left."), FALSE);
2520
2521         if(time > redirection_timeout || clients_found == 0)
2522                 localcmd("\nwait; wait; wait; quit\n");
2523
2524         return TRUE;
2525 }
2526
2527 void SV_Shutdown()
2528 {
2529         if(world_initialized)
2530         {
2531                 world_initialized = 0;
2532                 print("Saving persistent data...\n");
2533                 Ban_SaveBans();
2534                 if(!sv_cheats)
2535                         db_save(ServerProgsDB, "server.db");
2536                 db_close(ServerProgsDB);
2537                 print("done!\n");
2538                 // tell the bot system the game is ending now
2539                 bot_endgame();
2540
2541                 MapInfo_Shutdown();
2542         }
2543         else
2544         {
2545                 print("NOTE: crashed before even initializing the world, not saving persistent data\n");
2546         }
2547 }