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