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