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