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