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