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