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