beginning of "pure server" checking... the rule is simple: only settings in the offic...
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / g_world.qc
1 entity pingplreport;
2 void PingPLReport_Think()
3 {
4         float delta;
5         entity e;
6
7         delta = 3 / maxclients;
8         if(delta < sys_frametime)
9                 delta = 0;
10         self.nextthink = time + delta;
11
12         e = edict_num(self.cnt + 1);
13         if(clienttype(e) == CLIENTTYPE_REAL)
14         {
15                 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
16                 WriteByte(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
17                 WriteByte(MSG_BROADCAST, self.cnt);
18                 WriteShort(MSG_BROADCAST, max(1, e.ping));
19                 WriteByte(MSG_BROADCAST, ceil(e.ping_packetloss * 255));
20                 WriteByte(MSG_BROADCAST, ceil(e.ping_movementloss * 255));
21         }
22         else
23         {
24                 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
25                 WriteByte(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
26                 WriteByte(MSG_BROADCAST, self.cnt);
27                 WriteShort(MSG_BROADCAST, 0);
28                 WriteByte(MSG_BROADCAST, 0);
29                 WriteByte(MSG_BROADCAST, 0);
30         }
31         self.cnt = mod(self.cnt + 1, maxclients);
32 }
33 void PingPLReport_Spawn()
34 {
35         pingplreport = spawn();
36         pingplreport.classname = "pingplreport";
37         pingplreport.think = PingPLReport_Think;
38         pingplreport.nextthink = time;
39 }
40
41 float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
42 string redirection_target;
43 float world_initialized;
44
45 string GetMapname();
46 string GetGametype();
47 void GotoNextMap();
48 void ShuffleMaplist()
49 float() DoNextMapOverride;
50
51 void SetDefaultAlpha()
52 {
53         if(cvar("g_running_guns"))
54         {
55                 default_player_alpha = -1;
56                 default_weapon_alpha = +1;
57         }
58         else if(g_cloaked)
59         {
60                 default_player_alpha = cvar("g_balance_cloaked_alpha");
61                 default_weapon_alpha = default_player_alpha;
62         }
63         else
64         {
65                 default_player_alpha = cvar("g_player_alpha");
66                 if(default_player_alpha == 0)
67                         default_player_alpha = 1;
68                 default_weapon_alpha = default_player_alpha;
69         }
70 }
71
72 void fteqcc_testbugs()
73 {
74         float a, b;
75
76         if(!cvar("developer_fteqccbugs"))
77                 return;
78
79         dprint("*** fteqcc test: checking for bugs...\n");
80
81         a = 1;
82         b = 5;
83         if(sqrt(a) - sqrt(b - a) == 0)
84                 dprint("*** fteqcc test: found same-function-twice bug\n");
85         else
86                 dprint("*** fteqcc test: same-function-twice bug got FINALLY FIXED! HOORAY!\n");
87
88         world.cnt = -10;
89         world.enemy = world;
90         world.enemy.cnt += 10;
91         if(world.cnt > 0.2 || world.cnt < -0.2) // don't error out if it's just roundoff errors
92                 dprint("*** fteqcc test: found += bug\n");
93         else
94                 dprint("*** fteqcc test: += bug got FINALLY FIXED! HOORAY!\n");
95         world.cnt = 0;
96 }
97
98 /**
99  * Takes care of pausing and unpausing the game.
100  * Centerprints the information about an upcoming or active timeout to all active
101  * players. Also plays reminder sounds.
102  */
103 void timeoutHandler_Think() {
104         local string timeStr;
105         local entity plr;
106         if (timeoutStatus == 1) {
107                 if (remainingLeadTime > 0) {
108                         //centerprint the information to every player
109                         timeStr = getTimeoutText(0);
110                         FOR_EACH_REALCLIENT(plr) {
111                                 if(plr.classname == "player") {
112                                         centerprint_atprio(plr, CENTERPRIO_SPAM, timeStr);
113                                 }
114                         }
115                         remainingLeadTime -= 1;
116                         //think again in 1 second:
117                         self.nextthink = time + 1;
118                 }
119                 else {
120                         //now pause the game:
121                         timeoutStatus = 2;
122                         //reset all the flood variables
123                         FOR_EACH_CLIENT(plr) {
124                                 plr.nickspamcount = plr.nickspamtime = plr.floodcontrol_chat = plr.floodcontrol_chatteam = plr.floodcontrol_chattell = plr.floodcontrol_voice = plr.floodcontrol_voiceteam = 0;
125                         }
126                         cvar_set("slowmo", ftos(TIMEOUT_SLOWMO_VALUE));
127                         //copy .v_angle to .lastV_angle for every player in order to fix their view during pause (see PlayerPreThink)
128                         FOR_EACH_REALPLAYER(plr) {
129                                 plr.lastV_angle = plr.v_angle;
130                         }
131                         self.nextthink = time;
132                 }
133         }
134         else if (timeoutStatus == 2) {
135                 if (remainingTimeoutTime > 0) {
136                         timeStr = getTimeoutText(0);
137                         FOR_EACH_REALCLIENT(plr) {
138                                 if(plr.classname == "player") {
139                                         centerprint_atprio(plr, CENTERPRIO_SPAM, timeStr);
140                                 }
141                         }
142                         if(remainingTimeoutTime == cvar("sv_timeout_resumetime")) { //play a warning sound when only <sv_timeout_resumetime> seconds are left
143                                 Announce("prepareforbattle");
144                         }
145                         remainingTimeoutTime -= 1;
146                         self.nextthink = time + TIMEOUT_SLOWMO_VALUE;
147                 }
148                 else {
149                         //unpause the game again
150                         remainingTimeoutTime = timeoutStatus = 0;
151                         cvar_set("slowmo", ftos(orig_slowmo));
152                         //and unlock the fixed view again once there is no timeout active anymore
153                         FOR_EACH_REALPLAYER(plr) {
154                                 plr.fixangle = FALSE;
155                         }
156                         //get rid of the countdown message
157                         FOR_EACH_REALCLIENT(plr) {
158                                 if(plr.classname == "player") {
159                                         centerprint_atprio(plr, CENTERPRIO_SPAM, "");
160                                 }
161                         }
162                         remove(self);
163                         return;
164                 }
165
166         }
167         else if (timeoutStatus == 0) { //if a player called the resumegame command (which set timeoutStatus to 0 already)
168                 FOR_EACH_REALCLIENT(plr) {
169                         if(plr.classname == "player") {
170                                 centerprint_atprio(plr, CENTERPRIO_SPAM, "");
171                         }
172                 }
173                 remove(self);
174                 return;
175         }
176 }
177
178 void GotoFirstMap()
179 {
180         float n;
181         if(cvar("_sv_init"))
182         {
183                 // cvar_set("_sv_init", "0");
184                 // we do NOT set this to 0 any more, so someone "accidentally" changing
185                 // to this "init" map on a dedicated server will cause no permanent
186                 // harm
187                 if(cvar("g_maplist_shuffle"))
188                         ShuffleMaplist();
189                 n = tokenizebyseparator(cvar_string("g_maplist"), " ");
190                 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
191
192                 MapInfo_Enumerate();
193                 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
194
195                 if(!DoNextMapOverride())
196                         GotoNextMap();
197
198                 return;
199         }
200
201         if(time < 5)
202         {
203                 self.nextthink = time;
204         }
205         else
206         {
207                 self.nextthink = time + 1;
208                 print("Waiting for _sv_init being set to 1 by initialization scripts...\n");
209         }
210 }
211
212 void cvar_changes_init()
213 {
214         float h;
215         string k, v, d;
216         float n, i, adding, pureadding;
217
218         if(cvar_changes)
219                 strunzone(cvar_changes);
220         cvar_changes = string_null;
221         if(cvar_purechanges)
222                 strunzone(cvar_purechanges);
223         cvar_purechanges = string_null;
224         cvar_purechanges_count = 0;
225
226         h = buf_create();
227         buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
228         n = buf_getsize(h);
229
230         adding = TRUE;
231         pureadding = TRUE;
232
233         for(i = 0; i < n; ++i)
234         {
235                 k = bufstr_get(h, i);
236
237 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
238 #define BADCVAR(p) if(k == p) continue
239                 // internal
240                 BADPREFIX("csqc_");
241                 BADPREFIX("cvar_check_");
242                 BADCVAR("gamecfg");
243                 BADCVAR("g_configversion");
244                 BADCVAR("g_maplist_index");
245                 BADCVAR("halflifebsp");
246                 BADPREFIX("sv_world");
247
248                 // client
249                 BADPREFIX("cl_");
250                 BADPREFIX("con_");
251                 BADPREFIX("g_campaign");
252                 BADPREFIX("gl_");
253                 BADPREFIX("joy");
254                 BADPREFIX("menu_");
255                 BADPREFIX("net_slist_");
256                 BADPREFIX("r_");
257                 BADPREFIX("sbar_");
258                 BADPREFIX("scr_");
259                 BADPREFIX("userbind");
260                 BADPREFIX("v_");
261                 BADPREFIX("vid_");
262                 BADPREFIX("crosshair");
263                 BADCVAR("mod_q3bsp_lightmapmergepower");
264                 BADCVAR("mod_q3bsp_nolightmaps");
265
266                 // private
267                 BADCVAR("serverconfig");
268                 BADPREFIX("g_ban_");
269                 BADPREFIX("g_chat_flood_");
270                 BADPREFIX("g_voice_flood_");
271                 BADPREFIX("rcon_");
272                 BADPREFIX("settemp_");
273                 BADPREFIX("sv_allowdownloads_");
274                 BADPREFIX("sv_autodemo");
275                 BADPREFIX("sv_curl_");
276                 BADPREFIX("sv_eventlog");
277                 BADPREFIX("sv_logscores_");
278                 BADPREFIX("sv_master");
279                 BADCVAR("g_banned_list");
280                 BADCVAR("log_dest_udp");
281                 BADCVAR("log_file");
282                 BADCVAR("net_address");
283                 BADCVAR("port");
284                 BADCVAR("savedgamecfg");
285                 BADCVAR("sv_heartbeatperiod");
286                 BADCVAR("sv_vote_master_password");
287                 BADCVAR("sys_colortranslation");
288                 BADCVAR("sys_specialcharactertranslation");
289                 BADCVAR("timestamps");
290                 BADCVAR("net_address");
291                 BADCVAR("net_address_ipv6");
292                 BADPREFIX("sv_weaponstats_");
293
294                 // mapinfo
295                 BADCVAR("timelimit");
296                 BADCVAR("fraglimit");
297                 BADCVAR("g_arena");
298                 BADCVAR("g_ca");
299                 BADCVAR("g_assault");
300                 BADCVAR("g_ctf");
301                 BADCVAR("g_dm");
302                 BADCVAR("g_domination");
303                 BADCVAR("g_keyhunt");
304                 BADCVAR("g_keyhunt_teams");
305                 BADCVAR("g_onslaught");
306                 BADCVAR("g_race");
307                 BADCVAR("g_cts");
308                 BADCVAR("g_runematch");
309                 BADCVAR("g_tdm");
310                 BADCVAR("g_nexball");
311                 BADCVAR("teamplay");
312
313                 // long
314                 BADCVAR("hostname");
315                 BADCVAR("g_maplist");
316                 BADCVAR("g_maplist_mostrecent");
317                 BADCVAR("sv_motd");
318
319                 v = cvar_string(k);
320                 d = cvar_defstring(k);
321                 if(v == d)
322                         continue;
323
324                 if(adding)
325                 {
326                         cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
327                         if(strlen(cvar_changes) > 16384)
328                         {
329                                 cvar_changes = "// too many settings have been changed to show them here\n";
330                                 adding = 0;
331                         }
332                 }
333
334                 // now check if the changes are actually gameplay relevant
335
336                 // does nothing visible
337                 BADPREFIX("prvm_");
338                 BADCVAR("bot_prefix");
339                 BADCVAR("bot_suffix");
340
341                 // allowed changes to server admins (please sync this to server.cfg)
342                 // vi commands:
343                 //   :g!,^\/\/[^ /],d
344                 //   :%s,//\([^ ]*\).*,BADCVAR("\1");,
345                 //   :%!sort
346                 // yes, this does contain some redundant stuff, don't really care
347                 BADCVAR("bot_number");
348                 BADCVAR("bot_prefix");
349                 BADCVAR("bot_suffix");
350                 BADCVAR("capturelimit_override");
351                 BADCVAR("fraglimit_override");
352                 BADCVAR("gametype");
353                 BADCVAR("g_antilag");
354                 BADCVAR("g_balance_teams");
355                 BADCVAR("g_balance_teams_force");
356                 BADCVAR("g_ban_sync_trusted_servers");
357                 BADCVAR("g_ban_sync_uri");
358                 BADCVAR("g_cloaked");
359                 BADCVAR("g_ctf_capture_limit");
360                 BADCVAR("g_ctf_ignore_frags");
361                 BADCVAR("g_ctf_win_mode");
362                 BADCVAR("g_domination_point_limit");
363                 BADCVAR("g_footsteps");
364                 BADCVAR("g_fullbrightitems");
365                 BADCVAR("g_fullbrightplayers");
366                 BADCVAR("g_grappling_hook");
367                 BADCVAR("g_keyhunt_point_limit");
368                 BADCVAR("g_keyhunt_teams_override");
369                 BADCVAR("g_laserguided_missile");
370                 BADCVAR("g_lms_lives_override");
371                 BADCVAR("g_maplist");
372                 BADCVAR("g_maplist_check_waypoints");
373                 BADCVAR("g_maplist_mostrecent_count");
374                 BADCVAR("g_maplist_shuffle");
375                 BADCVAR("g_maplist_votable");
376                 BADCVAR("g_maplist_votable_abstain");
377                 BADCVAR("g_maplist_votable_nodetail");
378                 BADCVAR("g_maplist_votable_suggestions");
379                 BADCVAR("g_midair");
380                 BADCVAR("g_minstagib");
381                 BADCVAR("g_nexball_goallimit");
382                 BADCVAR("g_nixnex");
383                 BADCVAR("g_nixnex_with_laser");
384                 BADCVAR("g_runematch_point_limit");
385                 BADCVAR("g_vampire");
386                 BADCVAR("hostname");
387                 BADCVAR("log_file");
388                 BADCVAR("maxplayers");
389                 BADCVAR("minplayers");
390                 BADCVAR("net_address");
391                 BADCVAR("port");
392                 BADCVAR("rcon_password");
393                 BADCVAR("rcon_restricted_commands");
394                 BADCVAR("rcon_restricted_password");
395                 BADCVAR("skill");
396                 BADCVAR("sv_autoscreenshot");
397                 BADCVAR("sv_curl_defaulturl");
398                 BADCVAR("sv_defaultcharacter");
399                 BADCVAR("sv_defaultplayermodel");
400                 BADCVAR("sv_defaultplayerskin");
401                 BADCVAR("sv_gravity");
402                 BADCVAR("sv_maxrate");
403                 BADCVAR("sv_motd");
404                 BADCVAR("sv_public");
405                 BADCVAR("sv_ready_restart");
406                 BADCVAR("sv_status_privacy");
407                 BADCVAR("sv_vote_call");
408                 BADCVAR("sv_vote_commands");
409                 BADCVAR("sv_vote_majority_factor");
410                 BADCVAR("sv_vote_master");
411                 BADCVAR("sv_vote_master_commands");
412                 BADCVAR("sv_vote_master_password");
413                 BADCVAR("sv_vote_simple_majority_factor");
414                 BADCVAR("timelimit_override");
415 #undef BADPREFIX
416 #undef BADCVAR
417
418                 if(pureadding)
419                 {
420                         cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
421                         if(strlen(cvar_purechanges) > 16384)
422                         {
423                                 cvar_purechanges = "// too many settings have been changed to show them here\n";
424                                 pureadding = 0;
425                         }
426                 }
427                 ++cvar_purechanges_count;
428         }
429         buf_del(h);
430         if(cvar_changes == "")
431                 cvar_changes = "// this server runs at default server settings\n";
432         else
433                 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
434         cvar_changes = strzone(cvar_changes);
435         if(cvar_purechanges == "")
436                 cvar_purechanges = "// this server runs at default gameplay settings\n";
437         else
438                 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
439         cvar_purechanges = strzone(cvar_purechanges);
440 }
441
442 void detect_maptype()
443 {
444 #if 0
445         vector o, v;
446         float i;
447
448         for(;;)
449         {
450                 o = world.mins;
451                 o_x += random() * (world.maxs_x - world.mins_x);
452                 o_y += random() * (world.maxs_y - world.mins_y);
453                 o_z += random() * (world.maxs_z - world.mins_z);
454
455                 tracebox(o, PL_MIN, PL_MAX, o - '0 0 32768', MOVE_WORLDONLY, world);
456                 if(trace_fraction == 1)
457                         continue;
458
459                 v = trace_endpos;
460
461                 for(i = 0; i < 64; i += 4)
462                 {
463                         tracebox(o, '-1 -1 -1' * i, '1 1 1' * i, o - '0 0 32768', MOVE_WORLDONLY, world);
464         if(trace_fraction == 1)
465                 continue;
466                         print(ftos(i), " -> ", vtos(trace_endpos), "\n");
467                 }
468
469                 break;
470         }
471 #endif
472 }
473
474 entity randomseed;
475 float RandomSeed_Send(entity to, float sf)
476 {
477         WriteByte(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
478         WriteShort(MSG_ENTITY, self.cnt);
479         return TRUE;
480 }
481 void RandomSeed_Think()
482 {
483         self.cnt = bound(0, floor(random() * 65536), 65535);
484         self.nextthink = time + 5;
485
486         self.SendFlags |= 1;
487 }
488 void RandomSeed_Spawn()
489 {
490         randomseed = spawn();
491         randomseed.think = RandomSeed_Think;
492         Net_LinkEntity(randomseed, FALSE, 0, RandomSeed_Send);
493
494         entity oldself;
495         oldself = self;
496         self = randomseed;
497         self.think(); // sets random seed and nextthink
498         self = oldself;
499 }
500
501 void spawnfunc___init_dedicated_server(void)
502 {
503         // handler for _init/_init map (only for dedicated server initialization)
504
505         world_initialized = -1; // don't complain
506         cvar = cvar_normal;
507         cvar_string = cvar_string_normal;
508         cvar_set = cvar_set_normal;
509
510         remove = remove_unsafely;
511
512         entity e;
513         e = spawn();
514         e.think = GotoFirstMap;
515         e.nextthink = time; // this is usually 1 at this point
516
517         e = spawn();
518         e.classname = "info_player_deathmatch"; // safeguard against player joining
519
520         self.classname = "worldspawn"; // safeguard against various stuff ;)
521
522         MapInfo_Enumerate();
523         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
524 }
525
526 void Map_MarkAsRecent(string m);
527 float world_already_spawned;
528 void RegisterWeapons();
529 void Nagger_Init();
530 void ClientInit_Spawn();
531 void WeaponStats_Init();
532 void WeaponStats_Shutdown();
533 void spawnfunc_worldspawn (void)
534 {
535         float fd, l, i, j, n;
536         string s, col;
537
538         cvar = cvar_normal;
539         cvar_string = cvar_string_normal;
540         cvar_set = cvar_set_normal;
541
542         if(world_already_spawned)
543                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
544         world_already_spawned = TRUE;
545
546         remove = remove_safely; // during spawning, watch what you remove!
547
548         check_unacceptable_compiler_bugs();
549
550         cvar_changes_init(); // do this very early now so it REALLY matches the server config
551
552         compressShortVector_init();
553
554         allowed_to_spawn = TRUE;
555
556         local entity head;
557         head = nextent(world);
558         maxclients = 0;
559         while(head)
560         {
561                 ++maxclients;
562                 head = nextent(head);
563         }
564
565         // needs to be done so early as they would still spawn
566         RegisterWeapons();
567
568         ServerProgsDB = db_load("server.db");
569
570         TemporaryDB = db_create();
571
572         /*
573         TODO sound pack system
574         // initialize sound pack system
575         soundpack = cvar_string("g_soundpack");
576         if(soundpack != "")
577                 soundpack = strcat(soundpack, "/");
578         soundpack = strzone(soundpack);
579         */
580
581         // 0 normal
582         lightstyle(0, "m");
583
584         // 1 FLICKER (first variety)
585         lightstyle(1, "mmnmmommommnonmmonqnmmo");
586
587         // 2 SLOW STRONG PULSE
588         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
589
590         // 3 CANDLE (first variety)
591         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
592
593         // 4 FAST STROBE
594         lightstyle(4, "mamamamamama");
595
596         // 5 GENTLE PULSE 1
597         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
598
599         // 6 FLICKER (second variety)
600         lightstyle(6, "nmonqnmomnmomomno");
601
602         // 7 CANDLE (second variety)
603         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
604
605         // 8 CANDLE (third variety)
606         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
607
608         // 9 SLOW STROBE (fourth variety)
609         lightstyle(9, "aaaaaaaazzzzzzzz");
610
611         // 10 FLUORESCENT FLICKER
612         lightstyle(10, "mmamammmmammamamaaamammma");
613
614         // 11 SLOW PULSE NOT FADE TO BLACK
615         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
616
617         // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
618
619         // 63 testing
620         lightstyle(63, "a");
621
622         if(cvar("g_campaign"))
623                 CampaignPreInit();
624
625         Map_MarkAsRecent(mapname);
626
627         precache_model ("null"); // we need this one before InitGameplayMode
628         InitGameplayMode();
629         readlevelcvars();
630         GrappleHookInit();
631         ElectroInit();
632         LaserInit();
633
634         player_count = 0;
635         bot_waypoints_for_items = cvar("g_waypoints_for_items");
636         if(bot_waypoints_for_items == 1)
637                 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
638                         bot_waypoints_for_items = 0;
639
640         // for setting by mapinfo
641         q3acompat_machineshotgunswap = cvar("sv_q3acompat_machineshotgunswap");
642         cvar_set("sv_q3acompat_machineshotgunswap", "0");
643
644         precache();
645
646         WaypointSprite_Init();
647
648         //if (g_domination)
649         //      dom_init();
650
651         GameLogInit(); // prepare everything
652         if(cvar("sv_eventlog"))
653         {
654                 s = strcat(cvar_string("sv_eventlog_files_counter"), ".");
655                 s = strcat(s, ftos(random()));
656                 matchid = strzone(s);
657
658                 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
659                 s = ":gameinfo:mutators:LIST";
660
661                 ret_string = s;
662                 MUTATOR_CALLHOOK(BuildMutatorsString);
663                 s = ret_string;
664
665                 if(cvar("g_grappling_hook"))
666                         s = strcat(s, ":grappling_hook");
667                 if(!cvar("g_use_ammunition"))
668                         s = strcat(s, ":no_use_ammunition");
669                 if(!cvar("g_pickup_items"))
670                         s = strcat(s, ":no_pickup_items");
671                 if(cvar_string("g_weaponarena") != "0")
672                         s = strcat(s, ":", cvar_string("g_weaponarena"), " arena");
673                 if(cvar("g_vampire"))
674                         s = strcat(s, ":vampire");
675                 if(cvar("g_laserguided_missile"))
676                         s = strcat(s, ":laserguided_missile");
677                 if(cvar("g_norecoil"))
678                         s = strcat(s, ":norecoil");
679                 if(cvar("g_midair"))
680                         s = strcat(s, ":midair");
681                 if(cvar("g_minstagib"))
682                         s = strcat(s, ":minstagib");
683                 GameLogEcho(s);
684                 GameLogEcho(":gameinfo:end");
685         }
686         else
687                 matchid = strzone(ftos(random()));
688
689         cvar_set("nextmap", "");
690
691         SetDefaultAlpha();
692
693         if(cvar("g_campaign"))
694                 CampaignPostInit();
695
696         fteqcc_testbugs();
697
698         Ban_LoadBans();
699
700         MapInfo_Enumerate();
701         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
702
703         if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
704         {
705                 fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
706                 if(fd != -1)
707                 {
708                         while((s = fgets(fd)))
709                         {
710                                 l = tokenize_console(s);
711                                 if(l < 2)
712                                         continue;
713                                 if(argv(0) == "cd")
714                                 {
715                                         print("Found ^1DEPRECATED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
716                                         print("  cdtrack ", argv(2), "\n");
717                                 }
718                                 else if(argv(0) == "fog")
719                                 {
720                                         print("Found ^1DEPRECATED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
721                                         print("  \"fog\" \"", s, "\"\n");
722                                 }
723                                 else if(argv(0) == "set")
724                                 {
725                                         print("Found ^1DEPRECATED^7 set command in .cfg file; put this line in mapinfo instead:\n");
726                                         print("  clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
727                                 }
728                                 else if(argv(0) != "//")
729                                 {
730                                         print("Found ^1DEPRECATED^7 set command in .cfg file; put this line in mapinfo instead:\n");
731                                         print("  clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
732                                 }
733                         }
734                         fclose(fd);
735                 }
736         }
737
738         WeaponStats_Init();
739
740         addstat(STAT_WEAPONS, AS_INT, weapons);
741         addstat(STAT_SWITCHWEAPON, AS_INT, switchweapon);
742         addstat(STAT_GAMESTARTTIME, AS_FLOAT, stat_game_starttime);
743         addstat(STAT_ALLOW_OLDNEXBEAM, AS_INT, stat_allow_oldnexbeam);
744         Nagger_Init();
745
746         addstat(STAT_STRENGTH_FINISHED, AS_FLOAT, strength_finished);
747         addstat(STAT_INVINCIBLE_FINISHED, AS_FLOAT, invincible_finished);
748         addstat(STAT_PRESSED_KEYS, AS_FLOAT, pressedkeys);
749         addstat(STAT_FUEL, AS_INT, ammo_fuel);
750         addstat(STAT_DAMAGE_HITS, AS_INT, stat_hit);
751         addstat(STAT_DAMAGE_FIRED, AS_INT, stat_fired);
752         addstat(STAT_SHOTORG, AS_INT, stat_shotorg);
753         addstat(STAT_LEADLIMIT, AS_FLOAT, stat_leadlimit);
754         addstat(STAT_BULLETS_LOADED, AS_INT, campingrifle_bulletcounter);
755         addstat(STAT_LAST_PICKUP, AS_FLOAT, last_pickup);
756
757         addstat(STAT_NEX_CHARGE, AS_FLOAT, nex_charge);
758
759         if(g_ca)
760         {
761                 addstat(STAT_REDALIVE, AS_INT, redalive_stat);
762                 addstat(STAT_BLUEALIVE, AS_INT, bluealive_stat);
763         }
764         // g_movementspeed hack
765         addstat(STAT_MOVEVARS_AIRSPEEDLIMIT_NONQW, AS_FLOAT, stat_sv_airspeedlimit_nonqw);
766         addstat(STAT_MOVEVARS_AIRACCEL_QW, AS_FLOAT, stat_sv_airaccel_qw);
767         addstat(STAT_MOVEVARS_AIRSTRAFEACCEL_QW, AS_FLOAT, stat_sv_airstrafeaccel_qw);
768
769         next_pingtime = time + 5;
770
771         detect_maptype();
772
773         lsmaps_reply = "^7Maps available: ";
774         lsnewmaps_reply = "^7Maps without a record set: ";
775         for(i = 0, j = 0; i < MapInfo_count; ++i)
776         {
777                 if(MapInfo_Get_ByID(i))
778                         if not(MapInfo_Map_flags & (MAPINFO_FLAG_HIDDEN | MAPINFO_FLAG_FORBIDDEN))
779                         {
780                                 if(mod(i, 2))
781                                         col = "^2";
782                                 else
783                                         col = "^3";
784                                 ++j;
785                                 lsmaps_reply = strcat(lsmaps_reply, col, MapInfo_Map_bspname, " ");
786                                 if(g_race && !stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, RACE_RECORD, "time"))))
787                                         lsnewmaps_reply = strcat(lsnewmaps_reply, col, MapInfo_Map_bspname, " ");
788                                 else if(g_cts && !stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, CTS_RECORD, "time"))))
789                                         lsnewmaps_reply = strcat(lsnewmaps_reply, col, MapInfo_Map_bspname, " ");
790                         }
791         }
792         lsmaps_reply = strzone(strcat(lsmaps_reply, "\n"));
793         if (!g_race && !g_cts)
794                 lsnewmaps_reply = "Need to be playing race or CTS for lsnewmaps to work.";
795         lsnewmaps_reply = strzone(strcat(lsnewmaps_reply, "\n"));
796
797         maplist_reply = "^7Maps in list: ";
798         n = tokenize_console(cvar_string("g_maplist"));
799         for(i = 0, j = 0; i < n; ++i)
800         {
801                 if(MapInfo_CheckMap(argv(i)))
802                 {
803                         if(mod(j, 2))
804                                 col = "^2";
805                         else
806                                 col = "^3";
807                         maplist_reply = strcat(maplist_reply, col, argv(i), " ");
808                         ++j;
809                 }
810         }
811         maplist_reply = strzone(strcat(maplist_reply, "\n"));
812         MapInfo_ClearTemps();
813
814         for(i = 0; i < 10; ++i)
815         {
816                 records_reply[i] = strzone(getrecords(i));
817         }
818
819         rankings_reply = strzone(getrankings());
820
821         ClientInit_Spawn();
822         RandomSeed_Spawn();
823         PingPLReport_Spawn();
824
825         CheatInit();
826
827         localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
828
829         // fill sv_curl_serverpackages from .serverpackage files
830         if(cvar("sv_curl_serverpackages_auto"))
831         {
832                 fd = search_begin("*.serverpackage", TRUE, FALSE);
833                 s = "";
834                 if(fd >= 0)
835                 {
836                         j = search_getsize(fd);
837                         for(i = 0; i < j; ++i)
838                                 s = strcat(s, " ", search_getfilename(fd, i));
839                         search_end(fd);
840                 }
841                 cvar_set("sv_curl_serverpackages", substring(s, 1, -1));
842         }
843
844         world_initialized = 1;
845 }
846
847 void spawnfunc_light (void)
848 {
849         //makestatic (self); // Who the f___ did that?
850         remove(self);
851 }
852
853 float TryFile( string pFilename )
854 {
855         local float lHandle;
856         dprint("TryFile(\"", pFilename, "\")\n");
857         lHandle = fopen( pFilename, FILE_READ );
858         if( lHandle != -1 ) {
859                 fclose( lHandle );
860                 return TRUE;
861         } else {
862                 return FALSE;
863         }
864 };
865
866 string GetGametype()
867 {
868         return GametypeNameFromType(game);
869 }
870
871 string getmapname_stored;
872 string GetMapname()
873 {
874         return mapname;
875 }
876
877 float Map_Count, Map_Current;
878 string Map_Current_Name;
879
880 // NOTE: this now expects the map list to be already tokenize()d and the count in Map_Count
881 float GetMaplistPosition()
882 {
883         float pos, idx;
884         string map;
885
886         map = GetMapname();
887         idx = cvar("g_maplist_index");
888
889         if(idx >= 0)
890                 if(idx < Map_Count)
891                         if(map == argv(idx))
892                                 return idx;
893
894         for(pos = 0; pos < Map_Count; ++pos)
895                 if(map == argv(pos))
896                         return pos;
897
898         // resume normal maplist rotation if current map is not in g_maplist
899         return idx;
900 }
901
902 float MapHasRightSize(string map)
903 {
904         float fh;
905         if(currentbots || cvar("bot_number") || player_count < cvar("minplayers"))
906         if(cvar("g_maplist_check_waypoints"))
907         {
908                 dprint("checkwp "); dprint(map);
909                 fh = fopen(strcat("maps/", map, ".waypoints"), FILE_READ);
910                 if(fh < 0)
911                 {
912                         dprint(": no waypoints\n");
913                         return FALSE;
914                 }
915                 dprint(": has waypoints\n");
916                 fclose(fh);
917         }
918
919         // open map size restriction file
920         dprint("opensize "); dprint(map);
921         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
922         if(fh >= 0)
923         {
924                 float mapmin, mapmax;
925                 dprint(": ok, ");
926                 mapmin = stof(fgets(fh));
927                 mapmax = stof(fgets(fh));
928                 fclose(fh);
929                 if(player_count < mapmin)
930                 {
931                         dprint("not enough\n");
932                         return FALSE;
933                 }
934                 if(player_count > mapmax)
935                 {
936                         dprint("too many\n");
937                         return FALSE;
938                 }
939                 dprint("right size\n");
940                 return TRUE;
941         }
942         dprint(": not found\n");
943         return TRUE;
944 }
945
946 string Map_Filename(float position)
947 {
948         return strcat("maps/", argv(position), ".bsp");
949 }
950
951 string strwords(string s, float w)
952 {
953         float endpos;
954         for(endpos = 0; w && endpos >= 0; --w)
955                 endpos = strstrofs(s, " ", endpos + 1);
956         if(endpos < 0)
957                 return s;
958         else
959                 return substring(s, 0, endpos);
960 }
961
962 float strhasword(string s, string w)
963 {
964         return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
965 }
966
967 void Map_MarkAsRecent(string m)
968 {
969         cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", cvar_string("g_maplist_mostrecent")), max(0, cvar("g_maplist_mostrecent_count"))));
970 }
971
972 float Map_IsRecent(string m)
973 {
974         return strhasword(cvar_string("g_maplist_mostrecent"), m);
975 }
976
977 float Map_Check(float position, float pass)
978 {
979         string filename;
980         string map_next;
981         map_next = argv(position);
982         if(pass <= 1)
983         {
984                 if(Map_IsRecent(map_next))
985                         return 0;
986         }
987         filename = Map_Filename(position);
988         if(MapInfo_CheckMap(map_next))
989         {
990                 if(pass == 2)
991                         return 1;
992                 if(MapHasRightSize(map_next))
993                         return 1;
994                 return 0;
995         }
996         else
997                 dprint( "Couldn't select '", filename, "'..\n" );
998
999         return 0;
1000 }
1001
1002 void Map_Goto_SetStr(string nextmapname)
1003 {
1004         if(getmapname_stored != "")
1005                 strunzone(getmapname_stored);
1006         if(nextmapname == "")
1007                 getmapname_stored = "";
1008         else
1009                 getmapname_stored = strzone(nextmapname);
1010 }
1011
1012 void Map_Goto_SetFloat(float position)
1013 {
1014         cvar_set("g_maplist_index", ftos(position));
1015         Map_Goto_SetStr(argv(position));
1016 }
1017
1018 void GameResetCfg()
1019 {
1020         // settings persist, except...
1021         localcmd("\nsettemp_restore\n");
1022 };
1023
1024 void Map_Goto()
1025 {
1026         GameResetCfg();
1027         MapInfo_LoadMap(getmapname_stored);
1028 }
1029
1030 // return codes of map selectors:
1031 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
1032 //   -2 = permanent failure
1033 float() MaplistMethod_Iterate = // usual method
1034 {
1035         float pass, i;
1036
1037         for(pass = 1; pass <= 2; ++pass)
1038         {
1039                 for(i = 1; i < Map_Count; ++i)
1040                 {
1041                         float mapindex;
1042                         mapindex = mod(i + Map_Current, Map_Count);
1043                         if(Map_Check(mapindex, pass))
1044                                 return mapindex;
1045                 }
1046         }
1047         return -1;
1048 }
1049
1050 float() MaplistMethod_Repeat = // fallback method
1051 {
1052         if(Map_Check(Map_Current, 2))
1053                 return Map_Current;
1054         return -2;
1055 }
1056
1057 float() MaplistMethod_Random = // random map selection
1058 {
1059         float i, imax;
1060
1061         imax = 42;
1062
1063         for(i = 0; i <= imax; ++i)
1064         {
1065                 float mapindex;
1066                 mapindex = mod(Map_Current + floor(random() * (Map_Count - 1) + 1), Map_Count); // any OTHER map
1067                 if(Map_Check(mapindex, 1))
1068                         return mapindex;
1069         }
1070         return -1;
1071 }
1072
1073 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
1074 // the exponent sets a bias on the map selection:
1075 // the higher the exponent, the less likely "shortly repeated" same maps are
1076 {
1077         float i, j, imax, insertpos;
1078
1079         imax = 42;
1080
1081         for(i = 0; i <= imax; ++i)
1082         {
1083                 string newlist;
1084
1085                 // now reinsert this at another position
1086                 insertpos = pow(random(), 1 / exponent);       // ]0, 1]
1087                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
1088                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
1089                 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
1090
1091                 // insert the current map there
1092                 newlist = "";
1093                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
1094                         newlist = strcat(newlist, " ", argv(j));
1095                 newlist = strcat(newlist, " ", argv(0));       // now insert the just selected map
1096                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
1097                         newlist = strcat(newlist, " ", argv(j));
1098                 newlist = substring(newlist, 1, strlen(newlist) - 1);
1099                 cvar_set("g_maplist", newlist);
1100                 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
1101
1102                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
1103                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
1104                 if(Map_Check(Map_Current, 1))
1105                         return Map_Current;
1106         }
1107         return -1;
1108 }
1109
1110 void Maplist_Init()
1111 {
1112         Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
1113         if(Map_Count == 0)
1114         {
1115                 bprint( "Maplist is empty!  Resetting it to default map list.\n" );
1116                 cvar_set("g_maplist", MapInfo_ListAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
1117                 if(cvar("g_maplist_shuffle"))
1118                         ShuffleMaplist();
1119                 localcmd("\nmenu_cmd sync\n");
1120                 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
1121         }
1122         if(Map_Count == 0)
1123                 error("empty maplist, cannot select a new map");
1124         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
1125
1126         if(Map_Current_Name)
1127                 strunzone(Map_Current_Name);
1128         Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
1129         // this may or may not be correct, but who cares, in the worst case a map
1130         // isn't chosen in the first pass that should have been
1131 }
1132
1133 string GetNextMap()
1134 {
1135         float nextMap;
1136
1137         Maplist_Init();
1138         nextMap = -1;
1139
1140         if(nextMap == -1)
1141                 if(cvar("g_maplist_shuffle") > 0)
1142                         nextMap = MaplistMethod_Shuffle(cvar("g_maplist_shuffle") + 1);
1143
1144         if(nextMap == -1)
1145                 if(cvar("g_maplist_selectrandom"))
1146                         nextMap = MaplistMethod_Random();
1147
1148         if(nextMap == -1)
1149                 nextMap = MaplistMethod_Iterate();
1150
1151         if(nextMap == -1)
1152                 nextMap = MaplistMethod_Repeat();
1153
1154         if(nextMap >= 0)
1155         {
1156                 Map_Goto_SetFloat(nextMap);
1157                 return getmapname_stored;
1158         }
1159
1160         return "";
1161 };
1162
1163 float DoNextMapOverride()
1164 {
1165         if(cvar("g_campaign"))
1166         {
1167                 CampaignPostIntermission();
1168                 alreadychangedlevel = TRUE;
1169                 return TRUE;
1170         }
1171         if(cvar("quit_when_empty"))
1172         {
1173                 if(player_count <= currentbots)
1174                 {
1175                         localcmd("quit\n");
1176                         alreadychangedlevel = TRUE;
1177                         return TRUE;
1178                 }
1179         }
1180         if(cvar_string("quit_and_redirect") != "")
1181         {
1182                 redirection_target = strzone(cvar_string("quit_and_redirect"));
1183                 alreadychangedlevel = TRUE;
1184                 return TRUE;
1185         }
1186         if (cvar("samelevel")) // if samelevel is set, stay on same level
1187         {
1188                 // 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)
1189                 //localcmd(strcat("exec \"maps/", mapname, ".mapcfg\"\n"));
1190                 // so instead just restart the current map using the restart command (DOES NOT WORK PROPERLY WITH exit_cfg STUFF)
1191                 localcmd("restart\n");
1192                 //changelevel (mapname);
1193                 alreadychangedlevel = TRUE;
1194                 return TRUE;
1195         }
1196         if(cvar_string("nextmap") != "")
1197                 if(MapInfo_CheckMap(cvar_string("nextmap")))
1198                 {
1199                         Map_Goto_SetStr(cvar_string("nextmap"));
1200                         Map_Goto();
1201                         alreadychangedlevel = TRUE;
1202                         return TRUE;
1203                 }
1204         if(cvar("lastlevel"))
1205         {
1206                 GameResetCfg();
1207                 localcmd("set lastlevel 0\ntogglemenu\n");
1208                 alreadychangedlevel = TRUE;
1209                 return TRUE;
1210         }
1211         return FALSE;
1212 };
1213
1214 void GotoNextMap()
1215 {
1216         //local string nextmap;
1217         //local float n, nummaps;
1218         //local string s;
1219         if (alreadychangedlevel)
1220                 return;
1221         alreadychangedlevel = TRUE;
1222
1223         {
1224                 string nextMap;
1225                 float allowReset;
1226
1227                 for(allowReset = 1; allowReset >= 0; --allowReset)
1228                 {
1229                         nextMap = GetNextMap();
1230                         if(nextMap != "")
1231                                 break;
1232
1233                         if(allowReset)
1234                         {
1235                                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
1236                                 cvar_set("g_maplist", MapInfo_ListAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
1237                                 if(cvar("g_maplist_shuffle"))
1238                                         ShuffleMaplist();
1239                                 localcmd("\nmenu_cmd sync\n");
1240                         }
1241                         else
1242                         {
1243                                 error("Everything is broken - not even the default map list works. Please report this to the developers.");
1244                         }
1245                 }
1246                 Map_Goto();
1247         }
1248 };
1249
1250
1251 /*
1252 ============
1253 IntermissionThink
1254
1255 When the player presses attack or jump, change to the next level
1256 ============
1257 */
1258 .float autoscreenshot;
1259 void() MapVote_Start;
1260 void() MapVote_Think;
1261 float mapvote_initialized;
1262 void IntermissionThink()
1263 {
1264         FixIntermissionClient(self);
1265
1266         if(cvar("sv_autoscreenshot"))
1267         if(self.autoscreenshot > 0)
1268         if(time > self.autoscreenshot)
1269         {
1270                 self.autoscreenshot = -1;
1271                 if(clienttype(self) == CLIENTTYPE_REAL)
1272                         stuffcmd(self, "\nscreenshot\necho \"^5A screenshot has been taken at request of the server.\"\n");
1273                 return;
1274         }
1275
1276         if (time < intermission_exittime)
1277                 return;
1278
1279         if(!mapvote_initialized)
1280                 if (time < intermission_exittime + 10 && !self.BUTTON_ATCK && !self.BUTTON_JUMP && !self.BUTTON_ATCK2 && !self.BUTTON_HOOK && !self.BUTTON_USE)
1281                         return;
1282
1283         MapVote_Start();
1284 };
1285
1286 /*
1287 ============
1288 FindIntermission
1289
1290 Returns the entity to view from
1291 ============
1292 */
1293 /*
1294 entity FindIntermission()
1295 {
1296         local   entity spot;
1297         local   float cyc;
1298
1299 // look for info_intermission first
1300         spot = find (world, classname, "info_intermission");
1301         if (spot)
1302         {       // pick a random one
1303                 cyc = random() * 4;
1304                 while (cyc > 1)
1305                 {
1306                         spot = find (spot, classname, "info_intermission");
1307                         if (!spot)
1308                                 spot = find (spot, classname, "info_intermission");
1309                         cyc = cyc - 1;
1310                 }
1311                 return spot;
1312         }
1313
1314 // then look for the start position
1315         spot = find (world, classname, "info_player_start");
1316         if (spot)
1317                 return spot;
1318
1319 // testinfo_player_start is only found in regioned levels
1320         spot = find (world, classname, "testplayerstart");
1321         if (spot)
1322                 return spot;
1323
1324 // then look for the start position
1325         spot = find (world, classname, "info_player_deathmatch");
1326         if (spot)
1327                 return spot;
1328
1329         //objerror ("FindIntermission: no spot");
1330         return world;
1331 };
1332 */
1333
1334 /*
1335 ===============================================================================
1336
1337 RULES
1338
1339 ===============================================================================
1340 */
1341
1342 void DumpStats(float final)
1343 {
1344         local float file;
1345         local string s;
1346         local float to_console;
1347         local float to_eventlog;
1348         local float to_file;
1349         local float i;
1350
1351         to_console = cvar("sv_logscores_console");
1352         to_eventlog = cvar("sv_eventlog");
1353         to_file = cvar("sv_logscores_file");
1354
1355         if(!final)
1356         {
1357                 to_console = TRUE; // always print printstats replies
1358                 to_eventlog = FALSE; // but never print them to the event log
1359         }
1360
1361         if(to_eventlog)
1362                 if(cvar("sv_eventlog_console"))
1363                         to_console = FALSE; // otherwise we get the output twice
1364
1365         if(final)
1366                 s = ":scores:";
1367         else
1368                 s = ":status:";
1369         s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1370
1371         if(to_console)
1372                 print(s, "\n");
1373         if(to_eventlog)
1374                 GameLogEcho(s);
1375         if(to_file)
1376         {
1377                 file = fopen(cvar_string("sv_logscores_filename"), FILE_APPEND);
1378                 if(file == -1)
1379                         to_file = FALSE;
1380                 else
1381                         fputs(file, strcat(s, "\n"));
1382         }
1383
1384         s = strcat(":labels:player:", GetPlayerScoreString(world, 0));
1385         if(to_console)
1386                 print(s, "\n");
1387         if(to_eventlog)
1388                 GameLogEcho(s);
1389         if(to_file)
1390                 fputs(file, strcat(s, "\n"));
1391
1392         FOR_EACH_CLIENT(other)
1393         {
1394                 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && cvar("sv_logscores_bots")))
1395                 {
1396                         s = strcat(":player:see-labels:", GetPlayerScoreString(other, 0), ":");
1397                         s = strcat(s, ftos(rint(time - other.jointime)), ":");
1398                         if(other.classname == "player" || g_arena || g_ca || g_lms)
1399                                 s = strcat(s, ftos(other.team), ":");
1400                         else
1401                                 s = strcat(s, "spectator:");
1402
1403                         if(to_console)
1404                                 print(s, other.netname, "\n");
1405                         if(to_eventlog)
1406                                 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname));
1407                         if(to_file)
1408                                 fputs(file, strcat(s, other.netname, "\n"));
1409                 }
1410         }
1411
1412         if(teams_matter)
1413         {
1414                 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1415                 if(to_console)
1416                         print(s, "\n");
1417                 if(to_eventlog)
1418                         GameLogEcho(s);
1419                 if(to_file)
1420                         fputs(file, strcat(s, "\n"));
1421
1422                 for(i = 1; i < 16; ++i)
1423                 {
1424                         s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1425                         s = strcat(s, ":", ftos(i));
1426                         if(to_console)
1427                                 print(s, "\n");
1428                         if(to_eventlog)
1429                                 GameLogEcho(s);
1430                         if(to_file)
1431                                 fputs(file, strcat(s, "\n"));
1432                 }
1433         }
1434
1435         if(to_console)
1436                 print(":end\n");
1437         if(to_eventlog)
1438                 GameLogEcho(":end");
1439         if(to_file)
1440         {
1441                 fputs(file, ":end\n");
1442                 fclose(file);
1443         }
1444 }
1445
1446 void FixIntermissionClient(entity e)
1447 {
1448         string s;
1449         if(!e.autoscreenshot) // initial call
1450         {
1451                 e.angles = e.v_angle;
1452                 e.angles_x = -e.angles_x;
1453                 e.autoscreenshot = time + 0.8;  // used for autoscreenshot
1454                 e.health = -2342;
1455                 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1456                 e.solid = SOLID_NOT;
1457                 e.movetype = MOVETYPE_NONE;
1458                 e.takedamage = DAMAGE_NO;
1459                 if(e.weaponentity)
1460                 {
1461                         e.weaponentity.effects = EF_NODRAW;
1462                         if (e.weaponentity.weaponentity)
1463                                 e.weaponentity.weaponentity.effects = EF_NODRAW;
1464                 }
1465                 if(clienttype(e) == CLIENTTYPE_REAL)
1466                 {
1467                         stuffcmd(e, "\nscr_printspeed 1000000\n");
1468                         s = cvar_string("sv_intermission_cdtrack");
1469                         if(s != "")
1470                                 stuffcmd(e, strcat("\ncd loop ", s, "\n"));
1471                         msg_entity = e;
1472                         WriteByte(MSG_ONE, SVC_INTERMISSION);
1473                 }
1474         }
1475
1476         //e.velocity = '0 0 0';
1477         //e.fixangle = TRUE;
1478
1479         // TODO halt weapon animation
1480 }
1481
1482
1483 /*
1484 go to the next level for deathmatch
1485 only called if a time or frag limit has expired
1486 */
1487 void NextLevel()
1488 {
1489         float i;
1490
1491         gameover = TRUE;
1492
1493         intermission_running = 1;
1494
1495 // enforce a wait time before allowing changelevel
1496         if(player_count > 0)
1497                 intermission_exittime = time + cvar("sv_mapchange_delay");
1498         else
1499                 intermission_exittime = -1;
1500
1501         /*
1502         WriteByte (MSG_ALL, SVC_CDTRACK);
1503         WriteByte (MSG_ALL, 3);
1504         WriteByte (MSG_ALL, 3);
1505         // done in FixIntermission
1506         */
1507
1508         //pos = FindIntermission ();
1509
1510         VoteReset();
1511
1512         DumpStats(TRUE);
1513
1514         if(cvar("sv_eventlog"))
1515                 GameLogEcho(":gameover");
1516
1517         GameLogClose();
1518
1519 // TO DO
1520
1521 // save the stats to a text file on the client
1522 // stuffcmd(other, log_stats "stats/file_name");
1523 // bprint stats
1524 // stuffcmd(other, log_stats "");
1525 // use a filename similar to the demo name
1526         // string file_name;
1527         // file_name = strcat("\nlog_file \"stats/", strftime(TRUE, "%Y-%m-%d_%H-%M"), "_", mapname, ".txt\"");  // open the log file
1528
1529 // write a stats parser for the menu
1530
1531         if(cvar("sv_accuracy_data_send")) {
1532                 string stats_to_send;
1533
1534                 FOR_EACH_CLIENT(other) {  // make the string to send
1535                         FixIntermissionClient(other);
1536
1537                         if(other.cvar_cl_accuracy_data_share) {
1538                                 stats_to_send = strcat(stats_to_send, ":hits:", other.netname);
1539
1540                                 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
1541                                         stats_to_send = strcat(stats_to_send, ":", ftos(other.stats_hit[i-1]));
1542
1543                                 stats_to_send = strcat(stats_to_send, "\n:fired:", other.netname);
1544
1545                                 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
1546                                         stats_to_send = strcat(stats_to_send, ":", ftos(other.stats_fired[i-1]));
1547
1548                                 stats_to_send = strcat(stats_to_send, "\n");
1549                         }
1550                 }
1551
1552                 FOR_EACH_REALCLIENT(other) {  // only spam humans
1553                         Score_NicePrint(other);  // print the score
1554
1555                         if(other.cvar_cl_accuracy_data_receive)  // send the stats string to all the willing clients
1556                                 bprint(stats_to_send);
1557                 }
1558         } else { // ye olde message
1559                 FOR_EACH_PLAYER(other) {
1560                         FixIntermissionClient(other);
1561
1562                         if(other.winning)
1563                                 bprint(other.netname, " ^7wins.\n");
1564                 }
1565         }
1566
1567         if(cvar("g_campaign"))
1568                 CampaignPreIntermission();
1569
1570         localcmd("\nsv_hook_gameend\n");
1571 }
1572
1573 /*
1574 ============
1575 CheckRules_Player
1576
1577 Exit deathmatch games upon conditions
1578 ============
1579 */
1580 void CheckRules_Player()
1581 {
1582         if (gameover)   // someone else quit the game already
1583                 return;
1584
1585         if(self.deadflag == DEAD_NO)
1586                 self.play_time += frametime;
1587
1588         // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1589         //   (div0: and that in CheckRules_World please)
1590 };
1591
1592 float checkrules_equality;
1593 float checkrules_suddendeathwarning;
1594 float checkrules_suddendeathend;
1595 float checkrules_overtimesadded; //how many overtimes have been already added
1596
1597 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1598 float WINNING_YES = 1; // winner found
1599 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1600 float WINNING_STARTSUDDENDEATHOVERTIME = 3; // no winner, enter suddendeath overtime NOW
1601
1602 float InitiateSuddenDeath()
1603 {
1604         // Check first whether normal overtimes could be added before initiating suddendeath mode
1605         // - for this timelimit_overtime needs to be >0 of course
1606         // - also check the winning condition calculated in the previous frame and only add normal overtime
1607         //   again, if at the point at which timelimit would be extended again, still no winner was found
1608         if ((checkrules_overtimesadded >= 0) && (checkrules_overtimesadded < cvar("timelimit_overtimes")) && cvar("timelimit_overtime") && !(g_race && !g_race_qualifying))
1609         {
1610                 return 1; // need to call InitiateOvertime later
1611         }
1612         else
1613         {
1614                 if(!checkrules_suddendeathend)
1615                 {
1616                         checkrules_suddendeathend = time + 60 * cvar("timelimit_suddendeath");
1617                         if(g_race && !g_race_qualifying)
1618                                 race_StartCompleting();
1619                 }
1620                 return 0;
1621         }
1622 }
1623
1624 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1625 {
1626         ++checkrules_overtimesadded;
1627         //add one more overtime by simply extending the timelimit
1628         float tl;
1629         tl = cvar("timelimit");
1630         tl += cvar("timelimit_overtime");
1631         cvar_set("timelimit", ftos(tl));
1632         string minutesPlural;
1633         if (cvar("timelimit_overtime") == 1)
1634                 minutesPlural = " ^3minute";
1635         else
1636                 minutesPlural = " ^3minutes";
1637
1638         bcenterprint(
1639                 strcat(
1640                         "^3Now playing ^1OVERTIME^3!\n\n^3Added ^1",
1641                         ftos(cvar("timelimit_overtime")),
1642                         minutesPlural,
1643                         " to the game!"
1644                 )
1645         );
1646 }
1647
1648 float GetWinningCode(float fraglimitreached, float equality)
1649 {
1650         if(cvar("g_campaign") == 1)
1651                 if(fraglimitreached)
1652                         return WINNING_YES;
1653                 else
1654                         return WINNING_NO;
1655
1656         else
1657                 if(equality)
1658                         if(fraglimitreached)
1659                                 return WINNING_STARTSUDDENDEATHOVERTIME;
1660                         else
1661                                 return WINNING_NEVER;
1662                 else
1663                         if(fraglimitreached)
1664                                 return WINNING_YES;
1665                         else
1666                                 return WINNING_NO;
1667 }
1668
1669 // set the .winning flag for exactly those players with a given field value
1670 void SetWinners(.float field, float value)
1671 {
1672         entity head;
1673         FOR_EACH_PLAYER(head)
1674                 head.winning = (head.field == value);
1675 }
1676
1677 // set the .winning flag for those players with a given field value
1678 void AddWinners(.float field, float value)
1679 {
1680         entity head;
1681         FOR_EACH_PLAYER(head)
1682                 if(head.field == value)
1683                         head.winning = 1;
1684 }
1685
1686 // clear the .winning flags
1687 void ClearWinners(void)
1688 {
1689         entity head;
1690         FOR_EACH_PLAYER(head)
1691                 head.winning = 0;
1692 }
1693
1694 // Onslaught winning condition:
1695 // game terminates if only one team has a working generator (or none)
1696 float WinningCondition_Onslaught()
1697 {
1698         entity head;
1699         local float t1, t2, t3, t4;
1700
1701         WinningConditionHelper(); // set worldstatus
1702
1703         if(inWarmupStage)
1704                 return WINNING_NO;
1705
1706         // first check if the game has ended
1707         t1 = t2 = t3 = t4 = 0;
1708         head = find(world, classname, "onslaught_generator");
1709         while (head)
1710         {
1711                 if (head.health > 0)
1712                 {
1713                         if (head.team == COLOR_TEAM1) t1 = 1;
1714                         if (head.team == COLOR_TEAM2) t2 = 1;
1715                         if (head.team == COLOR_TEAM3) t3 = 1;
1716                         if (head.team == COLOR_TEAM4) t4 = 1;
1717                 }
1718                 head = find(head, classname, "onslaught_generator");
1719         }
1720         if (t1 + t2 + t3 + t4 < 2)
1721         {
1722                 // game over, only one team remains (or none)
1723                 ClearWinners();
1724                 if (t1) SetWinners(team, COLOR_TEAM1);
1725                 if (t2) SetWinners(team, COLOR_TEAM2);
1726                 if (t3) SetWinners(team, COLOR_TEAM3);
1727                 if (t4) SetWinners(team, COLOR_TEAM4);
1728                 dprint("Have a winner, ending game.\n");
1729                 return WINNING_YES;
1730         }
1731
1732         // Two or more teams remain
1733         return WINNING_NO;
1734 }
1735
1736 float LMS_NewPlayerLives()
1737 {
1738         float fl;
1739         fl = cvar("fraglimit");
1740         if(fl == 0)
1741                 fl = 999;
1742
1743         // first player has left the game for dying too much? Nobody else can get in.
1744         if(lms_lowest_lives < 1)
1745                 return 0;
1746
1747         if(!cvar("g_lms_join_anytime"))
1748                 if(lms_lowest_lives < fl - cvar("g_lms_last_join"))
1749                         return 0;
1750
1751         return bound(1, lms_lowest_lives, fl);
1752 }
1753
1754 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1755 // they win. Otherwise the defending team wins once the timelimit passes.
1756 void assault_new_round();
1757 float WinningCondition_Assault()
1758 {
1759         local float status;
1760
1761         WinningConditionHelper(); // set worldstatus
1762
1763         status = WINNING_NO;
1764         // as the timelimit has not yet passed just assume the defending team will win
1765         if(assault_attacker_team == COLOR_TEAM1)
1766         {
1767                 SetWinners(team, COLOR_TEAM2);
1768         }
1769         else
1770         {
1771                 SetWinners(team, COLOR_TEAM1);
1772         }
1773
1774         local entity ent;
1775         ent = find(world, classname, "target_assault_roundend");
1776         if(ent)
1777         {
1778                 if(ent.winning) // round end has been triggered by attacking team
1779                 {
1780                         bprint("ASSAULT: round completed...\n");
1781                         SetWinners(team, assault_attacker_team);
1782
1783                         TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 666 - TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 0));
1784
1785                         if(ent.cnt == 1 || cvar("g_campaign")) // this was the second round
1786                         {
1787                                 status = WINNING_YES;
1788                         }
1789                         else
1790                         {
1791                                 local entity oldself;
1792                                 oldself = self;
1793                                 self = ent;
1794                                 assault_new_round();
1795                                 self = oldself;
1796                         }
1797                 }
1798         }
1799
1800         return status;
1801 }
1802
1803 // LMS winning condition: game terminates if and only if there's at most one
1804 // one player who's living lives. Top two scores being equal cancels the time
1805 // limit.
1806 float WinningCondition_LMS()
1807 {
1808         entity head, head2;
1809         float have_player;
1810         float have_players;
1811         float l;
1812
1813         have_player = FALSE;
1814         have_players = FALSE;
1815         l = LMS_NewPlayerLives();
1816
1817         head = find(world, classname, "player");
1818         if(head)
1819                 have_player = TRUE;
1820         head2 = find(head, classname, "player");
1821         if(head2)
1822                 have_players = TRUE;
1823
1824         if(have_player)
1825         {
1826                 // we have at least one player
1827                 if(have_players)
1828                 {
1829                         // two or more active players - continue with the game
1830                 }
1831                 else
1832                 {
1833                         // exactly one player?
1834
1835                         ClearWinners();
1836                         SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1837
1838                         if(l)
1839                         {
1840                                 // game still running (that is, nobody got removed from the game by a frag yet)? then continue
1841                                 return WINNING_NO;
1842                         }
1843                         else
1844                         {
1845                                 // a winner!
1846                                 // and assign him his first place
1847                                 PlayerScore_Add(head, SP_LMS_RANK, 1);
1848                                 return WINNING_YES;
1849                         }
1850                 }
1851         }
1852         else
1853         {
1854                 // nobody is playing at all...
1855                 if(l)
1856                 {
1857                         // wait for players...
1858                 }
1859                 else
1860                 {
1861                         // SNAFU (maybe a draw game?)
1862                         ClearWinners();
1863                         dprint("No players, ending game.\n");
1864                         return WINNING_YES;
1865                 }
1866         }
1867
1868         // When we get here, we have at least two players who are actually LIVING,
1869         // now check if the top two players have equal score.
1870         WinningConditionHelper();
1871
1872         ClearWinners();
1873         if(WinningConditionHelper_winner)
1874                 WinningConditionHelper_winner.winning = TRUE;
1875         if(WinningConditionHelper_topscore == WinningConditionHelper_secondscore)
1876                 return WINNING_NEVER;
1877
1878         // Top two have different scores? Way to go for our beloved TIMELIMIT!
1879         return WINNING_NO;
1880 }
1881
1882 void ShuffleMaplist()
1883 {
1884         cvar_set("g_maplist", shufflewords(cvar_string("g_maplist")));
1885 }
1886
1887 float leaderfrags;
1888 float WinningCondition_Scores(float limit, float leadlimit)
1889 {
1890         float limitreached;
1891
1892         // TODO make everything use THIS winning condition (except LMS)
1893         WinningConditionHelper();
1894
1895         if(teams_matter)
1896         {
1897                 team1_score = TeamScore_GetCompareValue(COLOR_TEAM1);
1898                 team2_score = TeamScore_GetCompareValue(COLOR_TEAM2);
1899                 team3_score = TeamScore_GetCompareValue(COLOR_TEAM3);
1900                 team4_score = TeamScore_GetCompareValue(COLOR_TEAM4);
1901         }
1902
1903         ClearWinners();
1904         if(WinningConditionHelper_winner)
1905                 WinningConditionHelper_winner.winning = 1;
1906         if(WinningConditionHelper_winnerteam >= 0)
1907                 SetWinners(team, WinningConditionHelper_winnerteam);
1908
1909         if(WinningConditionHelper_lowerisbetter)
1910         {
1911                 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1912                 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1913                 limit = -limit;
1914         }
1915
1916         if(WinningConditionHelper_zeroisworst)
1917                 leadlimit = 0; // not supported in this mode
1918
1919         if(g_dm || g_tdm || g_arena || g_ca || (g_race && !g_race_qualifying) || g_nexball)
1920         // these modes always score in increments of 1, thus this makes sense
1921         {
1922                 if(leaderfrags != WinningConditionHelper_topscore)
1923                 {
1924                         leaderfrags = WinningConditionHelper_topscore;
1925
1926                         if (limit)
1927                         if (leaderfrags == limit - 1)
1928                                 Announce("1fragleft");
1929                         else if (leaderfrags == limit - 2)
1930                                 Announce("2fragsleft");
1931                         else if (leaderfrags == limit - 3)
1932                                 Announce("3fragsleft");
1933                 }
1934         }
1935
1936         limitreached = FALSE;
1937         if(limit)
1938                 if(WinningConditionHelper_topscore >= limit)
1939                         limitreached = TRUE;
1940         if(leadlimit)
1941         {
1942                 float leadlimitreached;
1943                 leadlimitreached = (WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1944                 if(cvar("leadlimit_and_fraglimit"))
1945                         limitreached = (limitreached && leadlimitreached);
1946                 else
1947                         limitreached = (limitreached || leadlimitreached);
1948         }
1949
1950         return GetWinningCode(
1951                 WinningConditionHelper_topscore && limitreached,
1952                 WinningConditionHelper_equality
1953         );
1954 }
1955
1956 float WinningCondition_Race(float fraglimit)
1957 {
1958         float wc;
1959         entity p;
1960         float n, c;
1961
1962         n = 0;
1963         c = 0;
1964         FOR_EACH_PLAYER(p)
1965         {
1966                 ++n;
1967                 if(p.race_completed)
1968                         ++c;
1969         }
1970         if(n && (n == c))
1971                 return WINNING_YES;
1972         wc = WinningCondition_Scores(fraglimit, 0);
1973
1974         // ALWAYS initiate overtime, unless EVERYONE has finished the race!
1975         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1976         // do NOT support equality when the laps are all raced!
1977                 return WINNING_STARTSUDDENDEATHOVERTIME;
1978         else
1979                 return WINNING_NEVER;
1980         return wc;
1981 }
1982
1983 void ReadyRestart();
1984 float WinningCondition_QualifyingThenRace(float limit)
1985 {
1986         float wc;
1987         wc = WinningCondition_Scores(limit, 0);
1988
1989         // NEVER initiate overtime
1990         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1991         {
1992                 return WINNING_YES;
1993         }
1994
1995         return wc;
1996 }
1997
1998 float WinningCondition_RanOutOfSpawns()
1999 {
2000         entity head;
2001
2002         if(have_team_spawns <= 0)
2003                 return WINNING_NO;
2004
2005         if(!some_spawn_has_been_used)
2006                 return WINNING_NO;
2007
2008         team1_score = team2_score = team3_score = team4_score = 0;
2009
2010         FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
2011         {
2012                 if(head.team == COLOR_TEAM1)
2013                         team1_score = 1;
2014                 else if(head.team == COLOR_TEAM2)
2015                         team2_score = 1;
2016                 else if(head.team == COLOR_TEAM3)
2017                         team3_score = 1;
2018                 else if(head.team == COLOR_TEAM4)
2019                         team4_score = 1;
2020         }
2021
2022         for(head = world; (head = find(head, classname, "info_player_deathmatch")) != world; )
2023         {
2024                 if(head.team == COLOR_TEAM1)
2025                         team1_score = 1;
2026                 else if(head.team == COLOR_TEAM2)
2027                         team2_score = 1;
2028                 else if(head.team == COLOR_TEAM3)
2029                         team3_score = 1;
2030                 else if(head.team == COLOR_TEAM4)
2031                         team4_score = 1;
2032         }
2033
2034         ClearWinners();
2035         if(team1_score + team2_score + team3_score + team4_score == 0)
2036         {
2037                 checkrules_equality = TRUE;
2038                 return WINNING_YES;
2039         }
2040         else if(team1_score + team2_score + team3_score + team4_score == 1)
2041         {
2042                 float t, i;
2043                 if(team1_score) t = COLOR_TEAM1;
2044                 if(team2_score) t = COLOR_TEAM2;
2045                 if(team3_score) t = COLOR_TEAM3;
2046                 if(team4_score) t = COLOR_TEAM4;
2047                 CheckAllowedTeams(world);
2048                 for(i = 0; i < MAX_TEAMSCORE; ++i)
2049                 {
2050                         if(t != COLOR_TEAM1) if(c1 >= 0) TeamScore_AddToTeam(COLOR_TEAM1, i, -1000);
2051                         if(t != COLOR_TEAM2) if(c2 >= 0) TeamScore_AddToTeam(COLOR_TEAM2, i, -1000);
2052                         if(t != COLOR_TEAM3) if(c3 >= 0) TeamScore_AddToTeam(COLOR_TEAM3, i, -1000);
2053                         if(t != COLOR_TEAM4) if(c4 >= 0) TeamScore_AddToTeam(COLOR_TEAM4, i, -1000);
2054                 }
2055
2056                 AddWinners(team, t);
2057                 return WINNING_YES;
2058         }
2059         else
2060                 return WINNING_NO;
2061 }
2062
2063 /*
2064 ============
2065 CheckRules_World
2066
2067 Exit deathmatch games upon conditions
2068 ============
2069 */
2070 void CheckRules_World()
2071 {
2072         float timelimit;
2073         float fraglimit;
2074         float leadlimit;
2075
2076         VoteThink();
2077         MapVote_Think();
2078
2079         SetDefaultAlpha();
2080
2081         /*
2082         MapVote_Think should now do that part
2083         if (intermission_running)
2084                 if (time >= intermission_exittime + 60)
2085                 {
2086                         if(!DoNextMapOverride())
2087                                 GotoNextMap();
2088                         return;
2089                 }
2090         */
2091
2092         if (gameover)   // someone else quit the game already
2093         {
2094                 if(player_count == 0) // Nobody there? Then let's go to the next map
2095                         MapVote_Start();
2096                         // this will actually check the player count in the next frame
2097                         // again, but this shouldn't hurt
2098                 return;
2099         }
2100
2101         timelimit = cvar("timelimit") * 60;
2102         fraglimit = cvar("fraglimit");
2103         leadlimit = cvar("leadlimit");
2104
2105         if(inWarmupStage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
2106         {
2107                 if(timelimit > 0)
2108                         timelimit = 0; // timelimit is not made for warmup
2109                 if(fraglimit > 0)
2110                         fraglimit = 0; // no fraglimit for now
2111                 leadlimit = 0; // no leadlimit for now
2112         }
2113
2114         if(g_onslaught)
2115                 timelimit = 0; // ONS has its own overtime rule
2116
2117         if(timelimit > 0)
2118         {
2119                 timelimit += game_starttime;
2120         }
2121         else if (timelimit < 0)
2122         {
2123                 // endmatch
2124                 NextLevel();
2125                 return;
2126         }
2127
2128         float wantovertime;
2129         wantovertime = 0;
2130
2131         if(checkrules_suddendeathend)
2132         {
2133                 if(!checkrules_suddendeathwarning)
2134                 {
2135                         checkrules_suddendeathwarning = TRUE;
2136                         if(g_race && !g_race_qualifying)
2137                                 bcenterprint("^3Everyone, finish your lap! The race is over!");
2138                         else
2139                                 bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
2140                 }
2141         }
2142         else
2143         {
2144                 if (timelimit && time >= timelimit)
2145                 {
2146                         if(g_race && (g_race_qualifying == 2) && timelimit > 0)
2147                         {
2148                                 float totalplayers;
2149                                 float playerswithlaps;
2150                                 float readyplayers;
2151                                 entity head;
2152                                 totalplayers = playerswithlaps = readyplayers = 0;
2153                                 FOR_EACH_PLAYER(head)
2154                                 {
2155                                         ++totalplayers;
2156                                         if(PlayerScore_Add(head, SP_RACE_FASTEST, 0))
2157                                                 ++playerswithlaps;
2158                                         if(head.ready)
2159                                                 ++readyplayers;
2160                                 }
2161
2162                                 // at least 2 of the players have completed a lap: start the RACE
2163                                 // otherwise, the players should end the qualifying on their own
2164                                 if(readyplayers || playerswithlaps >= 2)
2165                                 {
2166                                         checkrules_suddendeathend = 0;
2167                                         ReadyRestart(); // go to race
2168                                         return;
2169                                 }
2170                                 else
2171                                         wantovertime |= InitiateSuddenDeath();
2172                         }
2173                         else
2174                                 wantovertime |= InitiateSuddenDeath();
2175                 }
2176         }
2177
2178         if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
2179         {
2180                 NextLevel();
2181                 return;
2182         }
2183
2184         float checkrules_status;
2185         checkrules_status = WinningCondition_RanOutOfSpawns();
2186         if(checkrules_status == WINNING_YES)
2187         {
2188                 bprint("Hey! Someone ran out of spawns!\n");
2189         }
2190         else if(g_race && !g_race_qualifying && timelimit >= 0)
2191         {
2192                 checkrules_status = WinningCondition_Race(fraglimit);
2193                 //print("WC_RACE yields ", ftos(checkrules_status), "\n");
2194         }
2195         else if(g_race && g_race_qualifying == 2 && timelimit >= 0)
2196         {
2197                 checkrules_status = WinningCondition_QualifyingThenRace(fraglimit);
2198                 //print("WC_QUALIFYING_THEN_RACE yields ", ftos(checkrules_status), "\n");
2199         }
2200         else if(g_assault)
2201         {
2202                 checkrules_status = WinningCondition_Assault(); // TODO remove this?
2203         }
2204         else if(g_lms)
2205         {
2206                 checkrules_status = WinningCondition_LMS();
2207         }
2208         else if (g_onslaught)
2209         {
2210                 checkrules_status = WinningCondition_Onslaught(); // TODO remove this?
2211         }
2212         else
2213         {
2214                 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
2215                 //print("WC_SCORES yields ", ftos(checkrules_status), "\n");
2216         }
2217
2218         if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
2219         {
2220                 checkrules_status = WINNING_NEVER;
2221                 checkrules_overtimesadded = -1;
2222                 wantovertime |= InitiateSuddenDeath();
2223         }
2224
2225         if(checkrules_status == WINNING_NEVER)
2226                 // equality cases! Nobody wins if the overtime ends in a draw.
2227                 ClearWinners();
2228
2229         if(wantovertime)
2230         {
2231                 if(checkrules_status == WINNING_NEVER)
2232                         InitiateOvertime();
2233                 else
2234                         checkrules_status = WINNING_YES;
2235         }
2236
2237         if(checkrules_suddendeathend)
2238                 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
2239                         checkrules_status = WINNING_YES;
2240
2241         if(checkrules_status == WINNING_YES)
2242         {
2243                 //print("WINNING\n");
2244                 NextLevel();
2245         }
2246 };
2247
2248 float mapvote_nextthink;
2249 float mapvote_initialized;
2250 float mapvote_keeptwotime;
2251 float mapvote_timeout;
2252 string mapvote_message;
2253 #define MAPVOTE_SCREENSHOT_DIRS_COUNT 4
2254 string mapvote_screenshot_dirs[MAPVOTE_SCREENSHOT_DIRS_COUNT];
2255 float mapvote_screenshot_dirs_count;
2256
2257 float mapvote_count;
2258 float mapvote_count_real;
2259 string mapvote_maps[MAPVOTE_COUNT];
2260 float mapvote_maps_screenshot_dir[MAPVOTE_COUNT];
2261 string mapvote_maps_pakfile[MAPVOTE_COUNT];
2262 float mapvote_maps_suggested[MAPVOTE_COUNT];
2263 string mapvote_suggestions[MAPVOTE_COUNT];
2264 float mapvote_suggestion_ptr;
2265 float mapvote_maxlen;
2266 float mapvote_voters;
2267 float mapvote_votes[MAPVOTE_COUNT];
2268 float mapvote_run;
2269 float mapvote_detail;
2270 float mapvote_abstain;
2271 .float mapvote;
2272
2273 void MapVote_ClearAllVotes()
2274 {
2275         FOR_EACH_CLIENT(other)
2276                 other.mapvote = 0;
2277 }
2278
2279 string MapVote_Suggest(string m)
2280 {
2281         float i;
2282         if(m == "")
2283                 return "That's not how to use this command.";
2284         if(!cvar("g_maplist_votable_suggestions"))
2285                 return "Suggestions are not accepted on this server.";
2286         if(mapvote_initialized)
2287                 return "Can't suggest - voting is already in progress!";
2288         m = MapInfo_FixName(m);
2289         if(!m)
2290                 return "The map you suggested is not available on this server.";
2291         if(!cvar("g_maplist_votable_suggestions_override_mostrecent"))
2292                 if(Map_IsRecent(m))
2293                         return "This server does not allow for recent maps to be played again. Please be patient for some rounds.";
2294
2295         if(!MapInfo_CheckMap(m))
2296                 return "The map you suggested does not support the current game mode.";
2297         for(i = 0; i < mapvote_suggestion_ptr; ++i)
2298                 if(mapvote_suggestions[i] == m)
2299                         return "This map was already suggested.";
2300         if(mapvote_suggestion_ptr >= MAPVOTE_COUNT)
2301         {
2302                 i = floor(random() * mapvote_suggestion_ptr);
2303         }
2304         else
2305         {
2306                 i = mapvote_suggestion_ptr;
2307                 mapvote_suggestion_ptr += 1;
2308         }
2309         if(mapvote_suggestions[i] != "")
2310                 strunzone(mapvote_suggestions[i]);
2311         mapvote_suggestions[i] = strzone(m);
2312         if(cvar("sv_eventlog"))
2313                 GameLogEcho(strcat(":vote:suggested:", m, ":", ftos(self.playerid)));
2314         return strcat("Suggestion of ", m, " accepted.");
2315 }
2316
2317 void MapVote_AddVotable(string nextMap, float isSuggestion)
2318 {
2319         float j, i, o;
2320         string pakfile, mapfile;
2321
2322         if(nextMap == "")
2323                 return;
2324         for(j = 0; j < mapvote_count; ++j)
2325                 if(mapvote_maps[j] == nextMap)
2326                         return;
2327         if(strlen(nextMap) > mapvote_maxlen)
2328                 mapvote_maxlen = strlen(nextMap);
2329         mapvote_maps[mapvote_count] = strzone(nextMap);
2330         mapvote_maps_suggested[mapvote_count] = isSuggestion;
2331
2332         for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2333         {
2334                 mapfile = strcat(mapvote_screenshot_dirs[i], "/", mapvote_maps[i]);
2335                 pakfile = whichpack(strcat(mapfile, ".tga"));
2336                 if(pakfile == "")
2337                         pakfile = whichpack(strcat(mapfile, ".jpg"));
2338                 if(pakfile == "")
2339                         pakfile = whichpack(strcat(mapfile, ".png"));
2340                 if(pakfile != "")
2341                         break;
2342         }
2343         if(i >= mapvote_screenshot_dirs_count)
2344                 i = 0; // FIXME maybe network this error case, as that means there is no mapshot on the server?
2345         for(o = strstr(pakfile, "/", 0)+1; o > 0; o = strstr(pakfile, "/", 0)+1)
2346                 pakfile = substring(pakfile, o, -1);
2347
2348         mapvote_maps_screenshot_dir[mapvote_count] = i;
2349         mapvote_maps_pakfile[mapvote_count] = strzone(pakfile);
2350
2351         mapvote_count += 1;
2352 }
2353
2354 void MapVote_Spawn();
2355 void MapVote_Init()
2356 {
2357         float i;
2358         float nmax, smax;
2359
2360         MapVote_ClearAllVotes();
2361
2362         mapvote_count = 0;
2363         mapvote_detail = !cvar("g_maplist_votable_nodetail");
2364         mapvote_abstain = cvar("g_maplist_votable_abstain");
2365
2366         if(mapvote_abstain)
2367                 nmax = min(MAPVOTE_COUNT - 1, cvar("g_maplist_votable"));
2368         else
2369                 nmax = min(MAPVOTE_COUNT, cvar("g_maplist_votable"));
2370         smax = min3(nmax, cvar("g_maplist_votable_suggestions"), mapvote_suggestion_ptr);
2371
2372         // we need this for AddVotable, as that cycles through the screenshot dirs
2373         mapvote_screenshot_dirs_count = tokenize_console(cvar_string("g_maplist_votable_screenshot_dir"));
2374         if(mapvote_screenshot_dirs_count == 0)
2375                 mapvote_screenshot_dirs_count = tokenize_console("maps levelshots");
2376         mapvote_screenshot_dirs_count = min(mapvote_screenshot_dirs_count, MAPVOTE_SCREENSHOT_DIRS_COUNT);
2377         for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2378                 mapvote_screenshot_dirs[i] = strzone(argv(i));
2379
2380         if(mapvote_suggestion_ptr)
2381                 for(i = 0; i < 100 && mapvote_count < smax; ++i)
2382                         MapVote_AddVotable(mapvote_suggestions[floor(random() * mapvote_suggestion_ptr)], TRUE);
2383
2384         for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2385                 MapVote_AddVotable(GetNextMap(), FALSE);
2386
2387         if(mapvote_count == 0)
2388         {
2389                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
2390                 cvar_set("g_maplist", MapInfo_ListAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
2391                 if(cvar("g_maplist_shuffle"))
2392                         ShuffleMaplist();
2393                 localcmd("\nmenu_cmd sync\n");
2394                 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2395                         MapVote_AddVotable(GetNextMap(), FALSE);
2396         }
2397
2398         mapvote_count_real = mapvote_count;
2399         if(mapvote_abstain)
2400                 MapVote_AddVotable("don't care", 0);
2401
2402         //dprint("mapvote count is ", ftos(mapvote_count), "\n");
2403
2404         mapvote_keeptwotime = time + cvar("g_maplist_votable_keeptwotime");
2405         mapvote_timeout = time + cvar("g_maplist_votable_timeout");
2406         if(mapvote_count_real < 3 || mapvote_keeptwotime <= time)
2407                 mapvote_keeptwotime = 0;
2408         mapvote_message = "Choose a map and press its key!";
2409
2410         MapVote_Spawn();
2411 }
2412
2413 void MapVote_SendPicture(float id)
2414 {
2415         msg_entity = self;
2416         WriteByte(MSG_ONE, SVC_TEMPENTITY);
2417         WriteByte(MSG_ONE, TE_CSQC_PICTURE);
2418         WriteByte(MSG_ONE, id);
2419         WritePicture(MSG_ONE, strcat(mapvote_screenshot_dirs[mapvote_maps_screenshot_dir[id]], "/", mapvote_maps[id]), 3072);
2420 }
2421
2422 float GameCommand_MapVote(string cmd)
2423 {
2424         if(!intermission_running)
2425                 return FALSE;
2426
2427         if(cmd == "mv_getpic")
2428         {
2429                 MapVote_SendPicture(stof(argv(1)));
2430                 return TRUE;
2431         }
2432
2433         return FALSE;
2434 }
2435
2436 float MapVote_GetMapMask()
2437 {
2438         float mask, i, power;
2439         mask = 0;
2440         for(i = 0, power = 1; i < mapvote_count; ++i, power *= 2)
2441                 if(mapvote_maps[i] != "")
2442                         mask |= power;
2443         return mask;
2444 }
2445
2446 entity mapvote_ent;
2447 float MapVote_SendEntity(entity to, float sf)
2448 {
2449         float i;
2450
2451         if(sf & 1)
2452                 sf &~= 2; // if we send 1, we don't need to also send 2
2453
2454         WriteByte(MSG_ENTITY, ENT_CLIENT_MAPVOTE);
2455         WriteByte(MSG_ENTITY, sf);
2456
2457         if(sf & 1)
2458         {
2459                 // flag 1 == initialization
2460                 for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2461                         WriteString(MSG_ENTITY, mapvote_screenshot_dirs[i]);
2462                 WriteString(MSG_ENTITY, "");
2463                 WriteByte(MSG_ENTITY, mapvote_count);
2464                 WriteByte(MSG_ENTITY, mapvote_abstain);
2465                 WriteByte(MSG_ENTITY, mapvote_detail);
2466                 WriteCoord(MSG_ENTITY, mapvote_timeout);
2467                 if(mapvote_count <= 8)
2468                         WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2469                 else
2470                         WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2471                 for(i = 0; i < mapvote_count; ++i)
2472                         if(mapvote_maps[i] != "")
2473                         {
2474                                 if(mapvote_abstain && i == mapvote_count - 1)
2475                                 {
2476                                         WriteString(MSG_ENTITY, ""); // abstain needs no text
2477                                         WriteString(MSG_ENTITY, ""); // abstain needs no pack
2478                                         WriteByte(MSG_ENTITY, 0); // abstain needs no screenshot dir
2479                                 }
2480                                 else
2481                                 {
2482                                         WriteString(MSG_ENTITY, mapvote_maps[i]);
2483                                         WriteString(MSG_ENTITY, mapvote_maps_pakfile[i]);
2484                                         WriteByte(MSG_ENTITY, mapvote_maps_screenshot_dir[i]);
2485                                 }
2486                         }
2487         }
2488
2489         if(sf & 2)
2490         {
2491                 // flag 2 == update of mask
2492                 if(mapvote_count <= 8)
2493                         WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2494                 else
2495                         WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2496         }
2497
2498         if(sf & 4)
2499         {
2500                 if(mapvote_detail)
2501                         for(i = 0; i < mapvote_count; ++i)
2502                                 if(mapvote_maps[i] != "")
2503                                         WriteByte(MSG_ENTITY, mapvote_votes[i]);
2504
2505                 WriteByte(MSG_ENTITY, to.mapvote);
2506         }
2507
2508         return TRUE;
2509 }
2510
2511 void MapVote_Spawn()
2512 {
2513         Net_LinkEntity(mapvote_ent = spawn(), FALSE, 0, MapVote_SendEntity);
2514 }
2515
2516 void MapVote_TouchMask()
2517 {
2518         mapvote_ent.SendFlags |= 2;
2519 }
2520
2521 void MapVote_TouchVotes(entity voter)
2522 {
2523         mapvote_ent.SendFlags |= 4;
2524 }
2525
2526 float MapVote_Finished(float mappos)
2527 {
2528         string result;
2529         float i;
2530         float didntvote;
2531
2532         if(cvar("sv_eventlog"))
2533         {
2534                 result = strcat(":vote:finished:", mapvote_maps[mappos]);
2535                 result = strcat(result, ":", ftos(mapvote_votes[mappos]), "::");
2536                 didntvote = mapvote_voters;
2537                 for(i = 0; i < mapvote_count; ++i)
2538                         if(mapvote_maps[i] != "")
2539                         {
2540                                 didntvote -= mapvote_votes[i];
2541                                 if(i != mappos)
2542                                 {
2543                                         result = strcat(result, ":", mapvote_maps[i]);
2544                                         result = strcat(result, ":", ftos(mapvote_votes[i]));
2545                                 }
2546                         }
2547                 result = strcat(result, ":didn't vote:", ftos(didntvote));
2548
2549                 GameLogEcho(result);
2550                 if(mapvote_maps_suggested[mappos])
2551                         GameLogEcho(strcat(":vote:suggestion_accepted:", mapvote_maps[mappos]));
2552         }
2553
2554         FOR_EACH_REALCLIENT(other)
2555                 FixClientCvars(other);
2556
2557         Map_Goto_SetStr(mapvote_maps[mappos]);
2558         Map_Goto();
2559         alreadychangedlevel = TRUE;
2560         return TRUE;
2561 }
2562 void MapVote_CheckRules_1()
2563 {
2564         float i;
2565
2566         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
2567         {
2568                 //dprint("Map ", ftos(i), ": "); dprint(mapvote_maps[i], "\n");
2569                 mapvote_votes[i] = 0;
2570         }
2571
2572         mapvote_voters = 0;
2573         FOR_EACH_REALCLIENT(other)
2574         {
2575                 ++mapvote_voters;
2576                 if(other.mapvote)
2577                 {
2578                         i = other.mapvote - 1;
2579                         //dprint("Player ", other.netname, " vote = ", ftos(other.mapvote - 1), "\n");
2580                         mapvote_votes[i] = mapvote_votes[i] + 1;
2581                 }
2582         }
2583 }
2584
2585 float MapVote_CheckRules_2()
2586 {
2587         float i;
2588         float firstPlace, secondPlace;
2589         float firstPlaceVotes, secondPlaceVotes;
2590         float mapvote_voters_real;
2591         string result;
2592
2593         if(mapvote_count_real == 1)
2594                 return MapVote_Finished(0);
2595
2596         mapvote_voters_real = mapvote_voters;
2597         if(mapvote_abstain)
2598                 mapvote_voters_real -= mapvote_votes[mapvote_count - 1];
2599
2600         RandomSelection_Init();
2601         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2602                 RandomSelection_Add(world, i, string_null, 1, mapvote_votes[i]);
2603         firstPlace = RandomSelection_chosen_float;
2604         firstPlaceVotes = RandomSelection_best_priority;
2605         //dprint("First place: ", ftos(firstPlace), "\n");
2606         //dprint("First place votes: ", ftos(firstPlaceVotes), "\n");
2607
2608         RandomSelection_Init();
2609         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2610                 if(i != firstPlace)
2611                         RandomSelection_Add(world, i, string_null, 1, mapvote_votes[i]);
2612         secondPlace = RandomSelection_chosen_float;
2613         secondPlaceVotes = RandomSelection_best_priority;
2614         //dprint("Second place: ", ftos(secondPlace), "\n");
2615         //dprint("Second place votes: ", ftos(secondPlaceVotes), "\n");
2616
2617         if(firstPlace == -1)
2618                 error("No first place in map vote... WTF?");
2619
2620         if(secondPlace == -1 || time > mapvote_timeout || (mapvote_voters_real - firstPlaceVotes) < firstPlaceVotes)
2621                 return MapVote_Finished(firstPlace);
2622
2623         if(mapvote_keeptwotime)
2624                 if(time > mapvote_keeptwotime || (mapvote_voters_real - firstPlaceVotes - secondPlaceVotes) < secondPlaceVotes)
2625                 {
2626                         float didntvote;
2627                         MapVote_TouchMask();
2628                         mapvote_message = "Now decide between the TOP TWO!";
2629                         mapvote_keeptwotime = 0;
2630                         result = strcat(":vote:keeptwo:", mapvote_maps[firstPlace]);
2631                         result = strcat(result, ":", ftos(firstPlaceVotes));
2632                         result = strcat(result, ":", mapvote_maps[secondPlace]);
2633                         result = strcat(result, ":", ftos(secondPlaceVotes), "::");
2634                         didntvote = mapvote_voters;
2635                         for(i = 0; i < mapvote_count; ++i)
2636                                 if(mapvote_maps[i] != "")
2637                                 {
2638                                         didntvote -= mapvote_votes[i];
2639                                         if(i != firstPlace)
2640                                                 if(i != secondPlace)
2641                                                 {
2642                                                         result = strcat(result, ":", mapvote_maps[i]);
2643                                                         result = strcat(result, ":", ftos(mapvote_votes[i]));
2644                                                         if(i < mapvote_count_real)
2645                                                         {
2646                                                                 strunzone(mapvote_maps[i]);
2647                                                                 mapvote_maps[i] = "";
2648                                                                 strunzone(mapvote_maps_pakfile[i]);
2649                                                                 mapvote_maps_pakfile[i] = "";
2650                                                         }
2651                                                 }
2652                                 }
2653                         result = strcat(result, ":didn't vote:", ftos(didntvote));
2654                         if(cvar("sv_eventlog"))
2655                                 GameLogEcho(result);
2656                 }
2657
2658         return FALSE;
2659 }
2660 void MapVote_Tick()
2661 {
2662         float keeptwo;
2663         float totalvotes;
2664
2665         keeptwo = mapvote_keeptwotime;
2666         MapVote_CheckRules_1(); // count
2667         if(MapVote_CheckRules_2()) // decide
2668                 return;
2669
2670         totalvotes = 0;
2671         FOR_EACH_REALCLIENT(other)
2672         {
2673                 // hide scoreboard again
2674                 if(other.health != 2342)
2675                 {
2676                         other.health = 2342;
2677                         other.impulse = 0;
2678                         if(clienttype(other) == CLIENTTYPE_REAL)
2679                         {
2680                                 msg_entity = other;
2681                                 WriteByte(MSG_ONE, SVC_FINALE);
2682                                 WriteString(MSG_ONE, "");
2683                         }
2684                 }
2685
2686                 // clear possibly invalid votes
2687                 if(mapvote_maps[other.mapvote - 1] == "")
2688                         other.mapvote = 0;
2689                 // use impulses as new vote
2690                 if(other.impulse >= 1 && other.impulse <= mapvote_count)
2691                         if(mapvote_maps[other.impulse - 1] != "")
2692                         {
2693                                 other.mapvote = other.impulse;
2694                                 MapVote_TouchVotes(other);
2695                         }
2696                 other.impulse = 0;
2697
2698                 if(other.mapvote)
2699                         ++totalvotes;
2700         }
2701
2702         MapVote_CheckRules_1(); // just count
2703 }
2704 void MapVote_Start()
2705 {
2706         if(mapvote_run)
2707                 return;
2708
2709         MapInfo_Enumerate();
2710         if(MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1))
2711                 mapvote_run = TRUE;
2712 }
2713 void MapVote_Think()
2714 {
2715         if(!mapvote_run)
2716                 return;
2717
2718         if(alreadychangedlevel)
2719                 return;
2720
2721         if(time < mapvote_nextthink)
2722                 return;
2723         //dprint("tick\n");
2724
2725         mapvote_nextthink = time + 0.5;
2726
2727         if(!mapvote_initialized)
2728         {
2729                 if(cvar("rescan_pending") == 1)
2730                 {
2731                         cvar_set("rescan_pending", "2");
2732                         localcmd("fs_rescan\nrescan_pending 3\n");
2733                         return;
2734                 }
2735                 else if(cvar("rescan_pending") == 2)
2736                 {
2737                         return;
2738                 }
2739                 else if(cvar("rescan_pending") == 3)
2740                 {
2741                         // now build missing mapinfo files
2742                         if(!MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1))
2743                                 return;
2744
2745                         // we're done, start the timer
2746                         cvar_set("rescan_pending", "0");
2747                 }
2748
2749                 mapvote_initialized = TRUE;
2750                 if(DoNextMapOverride())
2751                         return;
2752                 if(!cvar("g_maplist_votable") || player_count <= 0)
2753                 {
2754                         GotoNextMap();
2755                         return;
2756                 }
2757                 MapVote_Init();
2758         }
2759
2760         MapVote_Tick();
2761 };
2762
2763 string GotoMap(string m)
2764 {
2765         if(!MapInfo_CheckMap(m))
2766                 return "The map you chose is not available on this server.";
2767         cvar_set("nextmap", m);
2768         cvar_set("timelimit", "-1");
2769         if(mapvote_initialized || alreadychangedlevel)
2770         {
2771                 if(DoNextMapOverride())
2772                         return "Map switch initiated.";
2773                 else
2774                         return "Hm... no. For some reason I like THIS map more.";
2775         }
2776         else
2777                 return "Map switch will happen after scoreboard.";
2778 }
2779
2780
2781 void EndFrame()
2782 {
2783         float altime;
2784         FOR_EACH_REALCLIENT(self)
2785         {
2786                 if(self.classname == "spectator")
2787                 {
2788                         if(self.enemy.typehitsound)
2789                                 play2(self, "misc/typehit.wav");
2790                         else if(self.enemy.hitsound && self.cvar_cl_hitsound)
2791                                 play2(self, "misc/hit.wav");
2792                 }
2793                 else
2794                 {
2795                         if(self.typehitsound)
2796                                 play2(self, "misc/typehit.wav");
2797                         else if(self.hitsound && self.cvar_cl_hitsound)
2798                                 play2(self, "misc/hit.wav");
2799                 }
2800         }
2801         altime = time + frametime * (1 + cvar("g_antilag_nudge"));
2802         // add 1 frametime because after this, engine SV_Physics
2803         // increases time by a frametime and then networks the frame
2804         // add another frametime because client shows everything with
2805         // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2806         // needed!
2807         FOR_EACH_CLIENT(self)
2808         {
2809                 self.hitsound = FALSE;
2810                 self.typehitsound = FALSE;
2811                 antilag_record(self, altime);
2812         }
2813 }
2814
2815
2816 /*
2817  * RedirectionThink:
2818  * returns TRUE if redirecting
2819  */
2820 float redirection_timeout;
2821 float redirection_nextthink;
2822 float RedirectionThink()
2823 {
2824         float clients_found;
2825
2826         if(redirection_target == "")
2827                 return FALSE;
2828
2829         if(!redirection_timeout)
2830         {
2831                 cvar_set("sv_public", "-2");
2832                 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2833                 if(redirection_target == "self")
2834                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2835                 else
2836                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2837         }
2838
2839         if(time < redirection_nextthink)
2840                 return TRUE;
2841
2842         redirection_nextthink = time + 1;
2843
2844         clients_found = 0;
2845         FOR_EACH_REALCLIENT(self)
2846         {
2847                 print("Redirecting: sending connect command to ", self.netname, "\n");
2848                 if(redirection_target == "self")
2849                         stuffcmd(self, "\ndisconnect; reconnect\n");
2850                 else
2851                         stuffcmd(self, strcat("\ndisconnect; connect ", redirection_target, "\n"));
2852                 ++clients_found;
2853         }
2854
2855         print("Redirecting: ", ftos(clients_found), " clients left.\n");
2856
2857         if(time > redirection_timeout || clients_found == 0)
2858                 localcmd("\nwait; wait; wait; quit\n");
2859
2860         return TRUE;
2861 }
2862
2863 void TargetMusic_RestoreGame();
2864 void RestoreGame()
2865 {
2866         // Loaded from a save game
2867         // some things then break, so let's work around them...
2868
2869         // Progs DB (capture records)
2870         ServerProgsDB = db_load("server.db");
2871
2872         // Mapinfo
2873         MapInfo_Shutdown();
2874         MapInfo_Enumerate();
2875         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2876         WeaponStats_Init();
2877
2878         TargetMusic_RestoreGame();
2879 }
2880
2881 void SV_Shutdown()
2882 {
2883         if(gameover > 1) // shutting down already?
2884                 return;
2885
2886         gameover = 2; // 2 = server shutting down
2887
2888         if(world_initialized > 0)
2889         {
2890                 world_initialized = 0;
2891                 print("Saving persistent data...\n");
2892                 Ban_SaveBans();
2893                 if(!cheatcount_total)
2894                 {
2895                         if(cvar("sv_db_saveasdump"))
2896                                 db_dump(ServerProgsDB, "server.db");
2897                         else
2898                                 db_save(ServerProgsDB, "server.db");
2899                 }
2900                 if(cvar("developer"))
2901                 {
2902                         if(cvar("sv_db_saveasdump"))
2903                                 db_dump(TemporaryDB, "server-temp.db");
2904                         else
2905                                 db_save(TemporaryDB, "server-temp.db");
2906                 }
2907                 CheatShutdown(); // must be after cheatcount check
2908                 db_close(ServerProgsDB);
2909                 db_close(TemporaryDB);
2910                 print("done!\n");
2911                 // tell the bot system the game is ending now
2912                 bot_endgame();
2913
2914                 WeaponStats_Shutdown();
2915                 MapInfo_Shutdown();
2916         }
2917         else if(world_initialized == 0)
2918         {
2919                 print("NOTE: crashed before even initializing the world, not saving persistent data\n");
2920         }
2921 }