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