]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/g_world.qc
Remove CheckRules_Player (empty function, the only incremented field in it was unused...
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / g_world.qc
1 #include "g_world.qh"
2
3 #include "anticheat.qh"
4 #include "antilag.qh"
5 #include "bot/api.qh"
6 #include "campaign.qh"
7 #include "cheats.qh"
8 #include "client.qh"
9 #include "command/common.qh"
10 #include "command/getreplies.qh"
11 #include "command/sv_cmd.qh"
12 #include "command/vote.qh"
13 #include "g_hook.qh"
14 #include "ipban.qh"
15 #include "mapvoting.qh"
16 #include "mutators/_mod.qh"
17 #include "race.qh"
18 #include "scores.qh"
19 #include "teamplay.qh"
20 #include "weapons/weaponstats.qh"
21 #include "../common/constants.qh"
22 #include <common/net_linked.qh>
23 #include "../common/deathtypes/all.qh"
24 #include "../common/mapinfo.qh"
25 #include "../common/monsters/_mod.qh"
26 #include "../common/monsters/sv_monsters.qh"
27 #include "../common/vehicles/all.qh"
28 #include "../common/notifications/all.qh"
29 #include "../common/physics/player.qh"
30 #include "../common/playerstats.qh"
31 #include "../common/stats.qh"
32 #include "../common/teams.qh"
33 #include "../common/triggers/trigger/secret.qh"
34 #include "../common/triggers/target/music.qh"
35 #include "../common/util.qh"
36 #include "../common/items/_mod.qh"
37 #include <common/weapons/_all.qh>
38 #include "../common/state.qh"
39
40 const float LATENCY_THINKRATE = 10;
41 .float latency_sum;
42 .float latency_cnt;
43 .float latency_time;
44 entity pingplreport;
45 void PingPLReport_Think(entity this)
46 {
47         float delta;
48         entity e;
49
50         delta = 3 / maxclients;
51         if(delta < sys_frametime)
52                 delta = 0;
53         this.nextthink = time + delta;
54
55         e = edict_num(this.cnt + 1);
56         if(IS_REAL_CLIENT(e))
57         {
58                 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
59                 WriteByte(MSG_BROADCAST, this.cnt);
60                 WriteShort(MSG_BROADCAST, bound(1, CS(e).ping, 65535));
61                 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_packetloss * 255), 255));
62                 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_movementloss * 255), 255));
63
64                 // record latency times for clients throughout the match so we can report it to playerstats
65                 if(time > (e.latency_time + LATENCY_THINKRATE))
66                 {
67                         e.latency_sum += CS(e).ping;
68                         e.latency_cnt += 1;
69                         e.latency_time = time;
70                         //print("sum: ", ftos(e.latency_sum), ", cnt: ", ftos(e.latency_cnt), ", avg: ", ftos(e.latency_sum / e.latency_cnt), ".\n");
71                 }
72         }
73         else
74         {
75                 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
76                 WriteByte(MSG_BROADCAST, this.cnt);
77                 WriteShort(MSG_BROADCAST, 0);
78                 WriteByte(MSG_BROADCAST, 0);
79                 WriteByte(MSG_BROADCAST, 0);
80         }
81         this.cnt = (this.cnt + 1) % maxclients;
82 }
83 void PingPLReport_Spawn()
84 {
85         pingplreport = new_pure(pingplreport);
86         setthink(pingplreport, PingPLReport_Think);
87         pingplreport.nextthink = time;
88 }
89
90 const float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
91 string redirection_target;
92 float world_initialized;
93
94 string GetGametype();
95 void ShuffleMaplist();
96
97 void SetDefaultAlpha()
98 {
99         if (!MUTATOR_CALLHOOK(SetDefaultAlpha))
100         {
101                 default_player_alpha = autocvar_g_player_alpha;
102                 if(default_player_alpha == 0)
103                         default_player_alpha = 1;
104                 default_weapon_alpha = default_player_alpha;
105         }
106 }
107
108 void GotoFirstMap(entity this)
109 {
110         float n;
111         if(autocvar__sv_init)
112         {
113                 // cvar_set("_sv_init", "0");
114                 // we do NOT set this to 0 any more, so someone "accidentally" changing
115                 // to this "init" map on a dedicated server will cause no permanent
116                 // harm
117                 if(autocvar_g_maplist_shuffle)
118                         ShuffleMaplist();
119                 n = tokenizebyseparator(autocvar_g_maplist, " ");
120                 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
121
122                 MapInfo_Enumerate();
123                 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
124
125                 if(!DoNextMapOverride(1))
126                         GotoNextMap(1);
127
128                 return;
129         }
130
131         if(time < 5)
132         {
133                 this.nextthink = time;
134         }
135         else
136         {
137                 this.nextthink = time + 1;
138                 LOG_INFO("Waiting for _sv_init being set to 1 by initialization scripts...\n");
139         }
140 }
141
142 void cvar_changes_init()
143 {
144         float h;
145         string k, v, d;
146         float n, i, adding, pureadding;
147
148         if(cvar_changes)
149                 strunzone(cvar_changes);
150         cvar_changes = string_null;
151         if(cvar_purechanges)
152                 strunzone(cvar_purechanges);
153         cvar_purechanges = string_null;
154         cvar_purechanges_count = 0;
155
156         h = buf_create();
157         buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
158         n = buf_getsize(h);
159
160         adding = true;
161         pureadding = true;
162
163         for(i = 0; i < n; ++i)
164         {
165                 k = bufstr_get(h, i);
166
167 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
168 #define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
169 #define BADCVAR(p) if(k == p) continue
170
171                 // general excludes and namespaces for server admin used cvars
172                 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
173
174                 // internal
175                 BADPREFIX("csqc_");
176                 BADPREFIX("cvar_check_");
177                 BADCVAR("gamecfg");
178                 BADCVAR("g_configversion");
179                 BADCVAR("halflifebsp");
180                 BADCVAR("sv_mapformat_is_quake2");
181                 BADCVAR("sv_mapformat_is_quake3");
182                 BADPREFIX("sv_world");
183
184                 // client
185                 BADPREFIX("chase_");
186                 BADPREFIX("cl_");
187                 BADPREFIX("con_");
188                 BADPREFIX("scoreboard_");
189                 BADPREFIX("g_campaign");
190                 BADPREFIX("g_waypointsprite_");
191                 BADPREFIX("gl_");
192                 BADPREFIX("joy");
193                 BADPREFIX("hud_");
194                 BADPREFIX("m_");
195                 BADPREFIX("menu_");
196                 BADPREFIX("net_slist_");
197                 BADPREFIX("r_");
198                 BADPREFIX("sbar_");
199                 BADPREFIX("scr_");
200                 BADPREFIX("snd_");
201                 BADPREFIX("show");
202                 BADPREFIX("sensitivity");
203                 BADPREFIX("userbind");
204                 BADPREFIX("v_");
205                 BADPREFIX("vid_");
206                 BADPREFIX("crosshair");
207                 BADCVAR("mod_q3bsp_lightmapmergepower");
208                 BADCVAR("mod_q3bsp_nolightmaps");
209                 BADCVAR("fov");
210                 BADCVAR("mastervolume");
211                 BADCVAR("volume");
212                 BADCVAR("bgmvolume");
213                 BADCVAR("in_pitch_min");
214                 BADCVAR("in_pitch_max");
215
216                 // private
217                 BADCVAR("developer");
218                 BADCVAR("log_dest_udp");
219                 BADCVAR("net_address");
220                 BADCVAR("net_address_ipv6");
221                 BADCVAR("port");
222                 BADCVAR("savedgamecfg");
223                 BADCVAR("serverconfig");
224                 BADCVAR("sv_autoscreenshot");
225                 BADCVAR("sv_heartbeatperiod");
226                 BADCVAR("sv_vote_master_password");
227                 BADCVAR("sys_colortranslation");
228                 BADCVAR("sys_specialcharactertranslation");
229                 BADCVAR("timeformat");
230                 BADCVAR("timestamps");
231                 BADCVAR("g_require_stats");
232                 BADPREFIX("developer_");
233                 BADPREFIX("g_ban_");
234                 BADPREFIX("g_banned_list");
235                 BADPREFIX("g_require_stats_");
236                 BADPREFIX("g_chat_flood_");
237                 BADPREFIX("g_ghost_items");
238                 BADPREFIX("g_playerstats_");
239                 BADPREFIX("g_voice_flood_");
240                 BADPREFIX("log_file");
241                 BADPREFIX("quit_");
242                 BADPREFIX("rcon_");
243                 BADPREFIX("sv_allowdownloads");
244                 BADPREFIX("sv_autodemo");
245                 BADPREFIX("sv_curl_");
246                 BADPREFIX("sv_eventlog");
247                 BADPREFIX("sv_logscores_");
248                 BADPREFIX("sv_master");
249                 BADPREFIX("sv_weaponstats_");
250                 BADPREFIX("sv_waypointsprite_");
251                 BADCVAR("rescan_pending");
252
253                 // these can contain player IDs, so better hide
254                 BADPREFIX("g_forced_team_");
255                 BADCVAR("sv_muteban_list");
256
257                 // mapinfo
258                 BADCVAR("fraglimit");
259                 BADCVAR("g_arena");
260                 BADCVAR("g_assault");
261                 BADCVAR("g_ca");
262                 BADCVAR("g_ca_teams");
263                 BADCVAR("g_conquest");
264                 BADCVAR("g_ctf");
265                 BADCVAR("g_cts");
266                 BADCVAR("g_dotc");
267                 BADCVAR("g_dm");
268                 BADCVAR("g_domination");
269                 BADCVAR("g_domination_default_teams");
270                 BADCVAR("g_freezetag");
271                 BADCVAR("g_freezetag_teams");
272                 BADCVAR("g_invasion_teams");
273                 BADCVAR("g_jailbreak");
274                 BADCVAR("g_jailbreak_teams");
275                 BADCVAR("g_keepaway");
276                 BADCVAR("g_keyhunt");
277                 BADCVAR("g_keyhunt_teams");
278                 BADCVAR("g_lms");
279                 BADCVAR("g_nexball");
280                 BADCVAR("g_onslaught");
281                 BADCVAR("g_race");
282                 BADCVAR("g_race_laps_limit");
283                 BADCVAR("g_race_qualifying_timelimit");
284                 BADCVAR("g_race_qualifying_timelimit_override");
285                 BADCVAR("g_runematch");
286                 BADCVAR("g_snafu");
287                 BADCVAR("g_tdm");
288                 BADCVAR("g_tdm_teams");
289                 BADCVAR("g_vip");
290                 BADCVAR("leadlimit");
291                 BADCVAR("nextmap");
292                 BADCVAR("teamplay");
293                 BADCVAR("timelimit");
294                 BADCVAR("g_mapinfo_ignore_warnings");
295
296                 // long
297                 BADCVAR("hostname");
298                 BADCVAR("g_maplist");
299                 BADCVAR("g_maplist_mostrecent");
300                 BADCVAR("sv_motd");
301
302                 v = cvar_string(k);
303                 d = cvar_defstring(k);
304                 if(v == d)
305                         continue;
306
307                 if(adding)
308                 {
309                         cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
310                         if(strlen(cvar_changes) > 16384)
311                         {
312                                 cvar_changes = "// too many settings have been changed to show them here\n";
313                                 adding = 0;
314                         }
315                 }
316
317                 // now check if the changes are actually gameplay relevant
318
319                 // does nothing gameplay relevant
320                 BADCVAR("captureleadlimit_override");
321                 BADCVAR("condump_stripcolors");
322                 BADCVAR("gameversion");
323                 BADCVAR("g_allow_oldvortexbeam");
324                 BADCVAR("g_balance_kill_delay");
325                 BADCVAR("g_buffs_pickup_anyway");
326                 BADCVAR("g_buffs_randomize");
327                 BADCVAR("g_campcheck_distance");
328                 BADCVAR("g_ca_point_leadlimit");
329                 BADCVAR("g_ca_point_limit");
330                 BADCVAR("g_ctf_captimerecord_always");
331                 BADCVAR("g_ctf_flag_glowtrails");
332                 BADCVAR("g_ctf_flag_pickup_verbosename");
333                 BADCVAR("g_domination_point_leadlimit");
334                 BADCVAR("g_forced_respawn");
335                 BADCVAR("g_freezetag_point_leadlimit");
336                 BADCVAR("g_freezetag_point_limit");
337                 BADCVAR("g_hats");
338                 BADCVAR("g_invasion_point_limit");
339                 BADCVAR("g_jump_grunt");
340                 BADCVAR("g_keyhunt_point_leadlimit");
341                 BADCVAR("g_nexball_goalleadlimit");
342                 BADCVAR("g_new_toys_use_pickupsound");
343                 BADCVAR("g_physics_predictall");
344                 BADCVAR("g_piggyback");
345                 BADCVAR("g_playerclip_collisions");
346                 BADCVAR("g_tdm_point_leadlimit");
347                 BADCVAR("g_tdm_point_limit");
348                 BADCVAR("leadlimit_and_fraglimit");
349                 BADCVAR("leadlimit_override");
350                 BADCVAR("pausable");
351                 BADCVAR("sv_checkforpacketsduringsleep");
352                 BADCVAR("sv_damagetext");
353                 BADCVAR("sv_db_saveasdump");
354                 BADCVAR("sv_intermission_cdtrack");
355                 BADCVAR("sv_minigames");
356                 BADCVAR("sv_namechangetimer");
357                 BADCVAR("sv_precacheplayermodels");
358                 BADCVAR("sv_stepheight");
359                 BADCVAR("sv_timeout");
360                 BADCVAR("sv_weapons_modeloverride");
361                 BADPREFIX("crypto_");
362                 BADPREFIX("gameversion_");
363                 BADPREFIX("g_chat_");
364                 BADPREFIX("g_ctf_captimerecord_");
365                 BADPREFIX("g_maplist_");
366                 BADPREFIX("g_mod_");
367                 BADPREFIX("g_respawn_");
368                 BADPREFIX("net_");
369                 BADPREFIX("notification_");
370                 BADPREFIX("prvm_");
371                 BADPREFIX("skill_");
372                 BADPREFIX("sv_allow_");
373                 BADPREFIX("sv_cullentities_");
374                 BADPREFIX("sv_maxidle_");
375                 BADPREFIX("sv_minigames_");
376                 BADPREFIX("sv_radio_");
377                 BADPREFIX("sv_timeout_");
378                 BADPREFIX("sv_vote_");
379                 BADPREFIX("timelimit_");
380
381                 // allowed changes to server admins (please sync this to server.cfg)
382                 // vi commands:
383                 //   :/"impure"/,$d
384                 //   :g!,^\/\/[^ /],d
385                 //   :%s,//\([^ ]*\).*,BADCVAR("\1");,
386                 //   :%!sort
387                 // yes, this does contain some redundant stuff, don't really care
388                 BADCVAR("bot_config_file");
389                 BADCVAR("bot_number");
390                 BADCVAR("bot_prefix");
391                 BADCVAR("bot_suffix");
392                 BADCVAR("capturelimit_override");
393                 BADCVAR("fraglimit_override");
394                 BADCVAR("gametype");
395                 BADCVAR("g_antilag");
396                 BADCVAR("g_balance_teams");
397                 BADCVAR("g_balance_teams_prevent_imbalance");
398                 BADCVAR("g_balance_teams_scorefactor");
399                 BADCVAR("g_ban_sync_trusted_servers");
400                 BADCVAR("g_ban_sync_uri");
401                 BADCVAR("g_buffs");
402                 BADCVAR("g_ca_teams_override");
403                 BADCVAR("g_ctf_ignore_frags");
404                 BADCVAR("g_ctf_leaderboard");
405                 BADCVAR("g_domination_point_limit");
406                 BADCVAR("g_domination_teams_override");
407                 BADCVAR("g_freezetag_teams_override");
408                 BADCVAR("g_friendlyfire");
409                 BADCVAR("g_fullbrightitems");
410                 BADCVAR("g_fullbrightplayers");
411                 BADCVAR("g_keyhunt_point_limit");
412                 BADCVAR("g_keyhunt_teams_override");
413                 BADCVAR("g_lms_lives_override");
414                 BADCVAR("g_maplist");
415                 BADCVAR("g_maxplayers");
416                 BADCVAR("g_mirrordamage");
417                 BADCVAR("g_nexball_goallimit");
418                 BADCVAR("g_norecoil");
419                 BADCVAR("g_physics_clientselect");
420                 BADCVAR("g_pinata");
421                 BADCVAR("g_powerups");
422                 BADCVAR("g_spawnshieldtime");
423                 BADCVAR("g_start_delay");
424                 BADCVAR("g_superspectate");
425                 BADCVAR("g_tdm_teams_override");
426                 BADCVAR("g_warmup");
427                 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
428                 BADCVAR("hostname");
429                 BADCVAR("log_file");
430                 BADCVAR("maxplayers");
431                 BADCVAR("minplayers");
432                 BADCVAR("net_address");
433                 BADCVAR("port");
434                 BADCVAR("rcon_password");
435                 BADCVAR("rcon_restricted_commands");
436                 BADCVAR("rcon_restricted_password");
437                 BADCVAR("skill");
438                 BADCVAR("sv_adminnick");
439                 BADCVAR("sv_autoscreenshot");
440                 BADCVAR("sv_autotaunt");
441                 BADCVAR("sv_curl_defaulturl");
442                 BADCVAR("sv_defaultcharacter");
443                 BADCVAR("sv_defaultcharacterskin");
444                 BADCVAR("sv_defaultplayercolors");
445                 BADCVAR("sv_defaultplayermodel");
446                 BADCVAR("sv_defaultplayerskin");
447                 BADCVAR("sv_maxidle");
448                 BADCVAR("sv_maxrate");
449                 BADCVAR("sv_motd");
450                 BADCVAR("sv_public");
451                 BADCVAR("sv_ready_restart");
452                 BADCVAR("sv_status_privacy");
453                 BADCVAR("sv_taunt");
454                 BADCVAR("sv_vote_call");
455                 BADCVAR("sv_vote_commands");
456                 BADCVAR("sv_vote_majority_factor");
457                 BADCVAR("sv_vote_master");
458                 BADCVAR("sv_vote_master_commands");
459                 BADCVAR("sv_vote_master_password");
460                 BADCVAR("sv_vote_simple_majority_factor");
461                 BADCVAR("teamplay_mode");
462                 BADCVAR("timelimit_override");
463                 BADPREFIX("g_warmup_");
464                 BADPREFIX("sv_info_");
465                 BADPREFIX("sv_ready_restart_");
466
467                 // mutators that announce themselves properly to the server browser
468                 BADCVAR("g_instagib");
469                 BADCVAR("g_new_toys");
470                 BADCVAR("g_nix");
471                 BADCVAR("g_grappling_hook");
472                 BADCVAR("g_jetpack");
473
474 #undef BADPRESUFFIX
475 #undef BADPREFIX
476 #undef BADCVAR
477
478                 if(pureadding)
479                 {
480                         cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
481                         if(strlen(cvar_purechanges) > 16384)
482                         {
483                                 cvar_purechanges = "// too many settings have been changed to show them here\n";
484                                 pureadding = 0;
485                         }
486                 }
487                 ++cvar_purechanges_count;
488                 // WARNING: this variable is used for the server list
489                 // NEVER dare to skip this code!
490                 // Hacks to intentionally appearing as "pure server" even though you DO have
491                 // modified settings may be punished by removal from the server list.
492                 // You can do to the variables cvar_changes and cvar_purechanges all you want,
493                 // though.
494         }
495         buf_del(h);
496         if(cvar_changes == "")
497                 cvar_changes = "// this server runs at default server settings\n";
498         else
499                 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
500         cvar_changes = strzone(cvar_changes);
501         if(cvar_purechanges == "")
502                 cvar_purechanges = "// this server runs at default gameplay settings\n";
503         else
504                 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
505         cvar_purechanges = strzone(cvar_purechanges);
506 }
507
508 void detect_maptype()
509 {
510 #if 0
511         vector o, v;
512         float i;
513
514         for (;;)
515         {
516                 o = world.mins;
517                 o.x += random() * (world.maxs.x - world.mins.x);
518                 o.y += random() * (world.maxs.y - world.mins.y);
519                 o.z += random() * (world.maxs.z - world.mins.z);
520
521                 tracebox(o, STAT(PL_MIN, NULL), STAT(PL_MAX, NULL), o - '0 0 32768', MOVE_WORLDONLY, NULL);
522                 if(trace_fraction == 1)
523                         continue;
524
525                 v = trace_endpos;
526
527                 for(i = 0; i < 64; i += 4)
528                 {
529                         tracebox(o, '-1 -1 -1' * i, '1 1 1' * i, o - '0 0 32768', MOVE_WORLDONLY, NULL);
530         if(trace_fraction == 1)
531                 continue;
532                         LOG_INFO(ftos(i), " -> ", vtos(trace_endpos), "\n");
533                 }
534
535                 break;
536         }
537 #endif
538 }
539
540 entity randomseed;
541 bool RandomSeed_Send(entity this, entity to, int sf)
542 {
543         WriteHeader(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
544         WriteShort(MSG_ENTITY, this.cnt);
545         return true;
546 }
547 void RandomSeed_Think(entity this)
548 {
549         this.cnt = bound(0, floor(random() * 65536), 65535);
550         this.nextthink = time + 5;
551
552         this.SendFlags |= 1;
553 }
554 void RandomSeed_Spawn()
555 {
556         randomseed = new_pure(randomseed);
557         setthink(randomseed, RandomSeed_Think);
558         Net_LinkEntity(randomseed, false, 0, RandomSeed_Send);
559
560         getthink(randomseed)(randomseed); // sets random seed and nextthink
561 }
562
563 spawnfunc(__init_dedicated_server)
564 {
565         // handler for _init/_init map (only for dedicated server initialization)
566
567         world_initialized = -1; // don't complain
568         cvar = cvar_normal;
569         cvar_string = cvar_string_normal;
570         cvar_set = cvar_set_normal;
571
572         delete_fn = remove_unsafely;
573
574         entity e = spawn();
575         setthink(e, GotoFirstMap);
576         e.nextthink = time; // this is usually 1 at this point
577
578         e = new(info_player_deathmatch);  // safeguard against player joining
579
580         this.classname = "worldspawn"; // safeguard against various stuff ;)
581
582         // needs to be done so early because of the constants they create
583         static_init();
584         static_init_late();
585         static_init_precache();
586
587         IL_PUSH(g_spawnpoints, e); // just incase
588
589         MapInfo_Enumerate();
590         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
591 }
592
593 void __init_dedicated_server_shutdown() {
594         MapInfo_Shutdown();
595 }
596
597 void SetLimits(int fraglimit_override, int leadlimit_override, float timelimit_override, float qualifying_override)
598 {
599         if(!autocvar_g_campaign)
600         {
601                 if(fraglimit_override >= 0) cvar_set("fraglimit", ftos(fraglimit_override));
602                 if(timelimit_override >= 0) cvar_set("timelimit", ftos(timelimit_override));
603                 if(leadlimit_override >= 0) cvar_set("leadlimit", ftos(leadlimit_override));
604                 if(qualifying_override >= 0) cvar_set("g_race_qualifying_timelimit", ftos(qualifying_override));
605         }
606         limits_are_set = true;
607 }
608
609 void Map_MarkAsRecent(string m);
610 float world_already_spawned;
611 void Nagger_Init();
612 void ClientInit_Spawn();
613 void WeaponStats_Init();
614 void WeaponStats_Shutdown();
615 spawnfunc(worldspawn)
616 {
617         server_is_dedicated = boolean(stof(cvar_defstring("is_dedicated")));
618
619     bool wantrestart = false;
620         {
621                 if (!server_is_dedicated)
622                 {
623                         // force unloading of server pk3 files when starting a listen server
624                         // localcmd("\nfs_rescan\n"); // FIXME: does more harm than good, has unintended side effects. What we really want is to unload temporary pk3s only
625                         // restore csqc_progname too
626                         string expect = "csprogs.dat";
627                         wantrestart = cvar_string_normal("csqc_progname") != expect;
628                         cvar_set_normal("csqc_progname", expect);
629                 }
630                 else
631                 {
632                         // Try to use versioned csprogs from pk3
633                         // Only ever use versioned csprogs.dat files on dedicated servers;
634                         // we need to reset csqc_progname on clients ourselves, and it's easier if the client's release name is constant
635                         string pk3csprogs = "csprogs-" WATERMARK ".dat";
636                         // This always works; fall back to it if a versioned csprogs.dat is suddenly missing
637                         string select = "csprogs.dat";
638                         if (fexists(pk3csprogs)) select = pk3csprogs;
639                         if (cvar_string_normal("csqc_progname") != select)
640                         {
641                                 cvar_set_normal("csqc_progname", select);
642                                 wantrestart = true;
643                         }
644                         // Check for updates on startup
645                         // We do it this way for atomicity so that connecting clients still match the server progs and don't disconnect
646                         int sentinel = fopen("progs.txt", FILE_READ);
647                         if (sentinel >= 0)
648                         {
649                                 string switchversion = fgets(sentinel);
650                                 fclose(sentinel);
651                                 if (switchversion != "" && switchversion != WATERMARK)
652                                 {
653                                         LOG_INFOF("Switching progs: " WATERMARK " -> %s\n", switchversion);
654                                         // if it doesn't exist, assume either:
655                                         //   a) the current program was overwritten
656                                         //   b) this is a client only update
657                                         string newprogs = sprintf("progs-%s.dat", switchversion);
658                                         if (fexists(newprogs))
659                                         {
660                                                 cvar_set_normal("sv_progs", newprogs);
661                                                 wantrestart = true;
662                                         }
663                                         string newcsprogs = sprintf("csprogs-%s.dat", switchversion);
664                                         if (fexists(newcsprogs))
665                                         {
666                                                 cvar_set_normal("csqc_progname", newcsprogs);
667                                                 wantrestart = true;
668                                         }
669                                 }
670                         }
671                 }
672                 if (wantrestart)
673                 {
674                         LOG_INFOF("Restart requested\n");
675                         changelevel(mapname);
676                         // let initialization continue, shutdown depends on it
677                 }
678         }
679
680         cvar = cvar_normal;
681         cvar_string = cvar_string_normal;
682         cvar_set = cvar_set_normal;
683
684         if(world_already_spawned)
685                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
686         world_already_spawned = true;
687
688         delete_fn = remove_safely; // during spawning, watch what you remove!
689
690         cvar_changes_init(); // do this very early now so it REALLY matches the server config
691
692         maxclients = 0;
693         for (entity head = nextent(NULL); head; head = nextent(head))
694         {
695                 ++maxclients;
696         }
697
698         // needs to be done so early because of the constants they create
699         static_init();
700
701         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
702
703         TemporaryDB = db_create();
704
705         // 0 normal
706         lightstyle(0, "m");
707
708         // 1 FLICKER (first variety)
709         lightstyle(1, "mmnmmommommnonmmonqnmmo");
710
711         // 2 SLOW STRONG PULSE
712         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
713
714         // 3 CANDLE (first variety)
715         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
716
717         // 4 FAST STROBE
718         lightstyle(4, "mamamamamama");
719
720         // 5 GENTLE PULSE 1
721         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
722
723         // 6 FLICKER (second variety)
724         lightstyle(6, "nmonqnmomnmomomno");
725
726         // 7 CANDLE (second variety)
727         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
728
729         // 8 CANDLE (third variety)
730         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
731
732         // 9 SLOW STROBE (fourth variety)
733         lightstyle(9, "aaaaaaaazzzzzzzz");
734
735         // 10 FLUORESCENT FLICKER
736         lightstyle(10, "mmamammmmammamamaaamammma");
737
738         // 11 SLOW PULSE NOT FADE TO BLACK
739         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
740
741         // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
742
743         // 63 testing
744         lightstyle(63, "a");
745
746         if(autocvar_g_campaign)
747                 CampaignPreInit();
748
749         Map_MarkAsRecent(mapname);
750
751         PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
752
753         InitGameplayMode();
754         static_init_late();
755         static_init_precache();
756         readlevelcvars();
757         GrappleHookInit();
758
759         if(!limits_are_set)
760                 SetLimits(autocvar_fraglimit_override, autocvar_leadlimit_override, autocvar_timelimit_override, -1);
761
762         if(warmup_limit == 0)
763                 warmup_limit = (autocvar_timelimit > 0) ? autocvar_timelimit * 60 : autocvar_timelimit;
764
765         player_count = 0;
766         bot_waypoints_for_items = autocvar_g_waypoints_for_items;
767         if(bot_waypoints_for_items == 1)
768                 if(this.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
769                         bot_waypoints_for_items = 0;
770
771         precache();
772
773         WaypointSprite_Init();
774
775         GameLogInit(); // prepare everything
776         // NOTE for matchid:
777         // changing the logic generating it is okay. But:
778         // it HAS to stay <= 64 chars
779         // character set: ASCII 33-126 without the following characters: : ; ' " \ $
780         if(autocvar_sv_eventlog)
781         {
782                 string s = sprintf("%d.%s.%06d", itos(autocvar_sv_eventlog_files_counter), strftime(false, "%s"), floor(random() * 1000000));
783                 matchid = strzone(s);
784
785                 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
786                 s = ":gameinfo:mutators:LIST";
787
788                 MUTATOR_CALLHOOK(BuildMutatorsString, s);
789                 s = M_ARGV(0, string);
790
791                 // initialiation stuff, not good in the mutator system
792                 if(!autocvar_g_use_ammunition)
793                         s = strcat(s, ":no_use_ammunition");
794
795                 // initialiation stuff, not good in the mutator system
796                 if(autocvar_g_pickup_items == 0)
797                         s = strcat(s, ":no_pickup_items");
798                 if(autocvar_g_pickup_items > 0)
799                         s = strcat(s, ":pickup_items");
800
801                 // initialiation stuff, not good in the mutator system
802                 if(autocvar_g_weaponarena != "0")
803                         s = strcat(s, ":", autocvar_g_weaponarena, " arena");
804
805                 // TODO to mutator system
806                 if(autocvar_g_norecoil)
807                         s = strcat(s, ":norecoil");
808
809                 // TODO to mutator system
810                 if(autocvar_g_powerups == 0)
811                         s = strcat(s, ":no_powerups");
812                 if(autocvar_g_powerups > 0)
813                         s = strcat(s, ":powerups");
814
815                 GameLogEcho(s);
816                 GameLogEcho(":gameinfo:end");
817         }
818         else
819                 matchid = strzone(ftos(random()));
820
821         cvar_set("nextmap", "");
822
823         SetDefaultAlpha();
824
825         if(autocvar_g_campaign)
826                 CampaignPostInit();
827
828         Ban_LoadBans();
829
830         MapInfo_Enumerate();
831         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
832
833         if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
834         {
835                 int fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
836                 if(fd != -1)
837                 {
838                         string s;
839                         while((s = fgets(fd)))
840                         {
841                                 int l = tokenize_console(s);
842                                 if(l < 2)
843                                         continue;
844                                 if(argv(0) == "cd")
845                                 {
846                                         LOG_INFO("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
847                                         LOG_INFO("  cdtrack ", argv(2), "\n");
848                                 }
849                                 else if(argv(0) == "fog")
850                                 {
851                                         LOG_INFO("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
852                                         LOG_INFO("  \"fog\" \"", s, "\"\n");
853                                 }
854                                 else if(argv(0) == "set")
855                                 {
856                                         LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
857                                         LOG_INFO("  clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
858                                 }
859                                 else if(argv(0) != "//")
860                                 {
861                                         LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
862                                         LOG_INFO("  clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
863                                 }
864                         }
865                         fclose(fd);
866                 }
867         }
868
869         WeaponStats_Init();
870
871         Nagger_Init();
872
873         next_pingtime = time + 5;
874
875         detect_maptype();
876
877         // set up information replies for clients and server to use
878         maplist_reply = strzone(getmaplist());
879         lsmaps_reply = strzone(getlsmaps());
880         monsterlist_reply = strzone(getmonsterlist());
881         for(int i = 0; i < 10; ++i)
882         {
883                 string s = getrecords(i);
884                 if (s)
885                         records_reply[i] = strzone(s);
886         }
887         ladder_reply = strzone(getladder());
888         rankings_reply = strzone(getrankings());
889
890         // begin other init
891         ClientInit_Spawn();
892         RandomSeed_Spawn();
893         PingPLReport_Spawn();
894
895         CheatInit();
896
897         if (!wantrestart) localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
898
899         // fill sv_curl_serverpackages from .serverpackage files
900         if (autocvar_sv_curl_serverpackages_auto)
901         {
902                 string s = "csprogs-" WATERMARK ".txt";
903                 // remove automatically managed files from the list to prevent duplicates
904                 for (int i = 0, n = tokenize_console(cvar_string("sv_curl_serverpackages")); i < n; ++i)
905                 {
906                         string pkg = argv(i);
907                         if (startsWith(pkg, "csprogs-")) continue;
908                         if (endsWith(pkg, "-serverpackage.txt")) continue;
909                         if (endsWith(pkg, ".serverpackage")) continue;  // OLD legacy
910                         s = cons(s, pkg);
911                 }
912                 // add automatically managed files to the list
913                 #define X(match) MACRO_BEGIN { \
914                         int fd = search_begin(match, true, false); \
915                         if (fd >= 0) \
916                         { \
917                                 for (int i = 0, j = search_getsize(fd); i < j; ++i) \
918                                 { \
919                                         s = cons(s, search_getfilename(fd, i)); \
920                                 } \
921                                 search_end(fd); \
922                         } \
923                 } MACRO_END
924                 X("*-serverpackage.txt");
925                 X("*.serverpackage");
926                 #undef X
927                 cvar_set("sv_curl_serverpackages", s);
928         }
929
930         // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
931         modname = "Xonotic";
932         // physics/balance/config changes that count as mod
933         if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
934                 modname = cvar_string("g_mod_physics");
935         if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance"))
936                 modname = cvar_string("g_mod_balance");
937         if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
938                 modname = cvar_string("g_mod_config");
939         // extra mutators that deserve to count as mod
940         MUTATOR_CALLHOOK(SetModname, modname);
941         modname = M_ARGV(0, string);
942
943         // save it for later
944         modname = strzone(modname);
945
946         WinningConditionHelper(this); // set worldstatus
947
948         world_initialized = 1;
949 }
950
951 spawnfunc(light)
952 {
953         //makestatic (this); // Who the f___ did that?
954         delete(this);
955 }
956
957 string GetGametype()
958 {
959         return MapInfo_Type_ToString(MapInfo_LoadedGametype);
960 }
961
962 string GetMapname()
963 {
964         return mapname;
965 }
966
967 float Map_Count, Map_Current;
968 string Map_Current_Name;
969
970 // NOTE: this now expects the map list to be already tokenized and the count in Map_Count
971 float GetMaplistPosition()
972 {
973         float pos, idx;
974         string map;
975
976         map = GetMapname();
977         idx = autocvar_g_maplist_index;
978
979         if(idx >= 0)
980                 if(idx < Map_Count)
981                         if(map == argv(idx))
982                                 return idx;
983
984         for(pos = 0; pos < Map_Count; ++pos)
985                 if(map == argv(pos))
986                         return pos;
987
988         // resume normal maplist rotation if current map is not in g_maplist
989         return idx;
990 }
991
992 float MapHasRightSize(string map)
993 {
994         float fh;
995         if(currentbots || autocvar_bot_number || player_count < autocvar_minplayers)
996         if(autocvar_g_maplist_check_waypoints)
997         {
998                 LOG_TRACE("checkwp "); LOG_TRACE(map);
999                 if(!fexists(strcat("maps/", map, ".waypoints")))
1000                 {
1001                         LOG_TRACE(": no waypoints");
1002                         return false;
1003                 }
1004                 LOG_TRACE(": has waypoints");
1005         }
1006
1007         // open map size restriction file
1008         LOG_TRACE("opensize "); LOG_TRACE(map);
1009         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
1010         if(fh >= 0)
1011         {
1012                 float mapmin, mapmax;
1013                 LOG_TRACE(": ok, ");
1014                 mapmin = stof(fgets(fh));
1015                 mapmax = stof(fgets(fh));
1016                 fclose(fh);
1017                 if(player_count < mapmin)
1018                 {
1019                         LOG_TRACE("not enough");
1020                         return false;
1021                 }
1022                 if(player_count > mapmax)
1023                 {
1024                         LOG_TRACE("too many");
1025                         return false;
1026                 }
1027                 LOG_TRACE("right size");
1028                 return true;
1029         }
1030         LOG_TRACE(": not found");
1031         return true;
1032 }
1033
1034 string Map_Filename(float position)
1035 {
1036         return strcat("maps/", argv(position), ".bsp");
1037 }
1038
1039 void Map_MarkAsRecent(string m)
1040 {
1041         cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", autocvar_g_maplist_mostrecent), max(0, autocvar_g_maplist_mostrecent_count)));
1042 }
1043
1044 float Map_IsRecent(string m)
1045 {
1046         return strhasword(autocvar_g_maplist_mostrecent, m);
1047 }
1048
1049 float Map_Check(float position, float pass)
1050 {
1051         string filename;
1052         string map_next;
1053         map_next = argv(position);
1054         if(pass <= 1)
1055         {
1056                 if(Map_IsRecent(map_next))
1057                         return 0;
1058         }
1059         filename = Map_Filename(position);
1060         if(MapInfo_CheckMap(map_next))
1061         {
1062                 if(pass == 2)
1063                         return 1;
1064                 if(MapHasRightSize(map_next))
1065                         return 1;
1066                 return 0;
1067         }
1068         else
1069                 LOG_DEBUG( "Couldn't select '", filename, "'..." );
1070
1071         return 0;
1072 }
1073
1074 void Map_Goto_SetStr(string nextmapname)
1075 {
1076         if(getmapname_stored != "")
1077                 strunzone(getmapname_stored);
1078         if(nextmapname == "")
1079                 getmapname_stored = "";
1080         else
1081                 getmapname_stored = strzone(nextmapname);
1082 }
1083
1084 void Map_Goto_SetFloat(float position)
1085 {
1086         cvar_set("g_maplist_index", ftos(position));
1087         Map_Goto_SetStr(argv(position));
1088 }
1089
1090 void Map_Goto(float reinit)
1091 {
1092         MapInfo_LoadMap(getmapname_stored, reinit);
1093 }
1094
1095 // return codes of map selectors:
1096 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
1097 //   -2 = permanent failure
1098 float() MaplistMethod_Iterate = // usual method
1099 {
1100         float pass, i;
1101
1102         LOG_TRACE("Trying MaplistMethod_Iterate");
1103
1104         for(pass = 1; pass <= 2; ++pass)
1105         {
1106                 for(i = 1; i < Map_Count; ++i)
1107                 {
1108                         float mapindex;
1109                         mapindex = (i + Map_Current) % Map_Count;
1110                         if(Map_Check(mapindex, pass))
1111                                 return mapindex;
1112                 }
1113         }
1114         return -1;
1115 }
1116
1117 float() MaplistMethod_Repeat = // fallback method
1118 {
1119         LOG_TRACE("Trying MaplistMethod_Repeat");
1120
1121         if(Map_Check(Map_Current, 2))
1122                 return Map_Current;
1123         return -2;
1124 }
1125
1126 float() MaplistMethod_Random = // random map selection
1127 {
1128         float i, imax;
1129
1130         LOG_TRACE("Trying MaplistMethod_Random");
1131
1132         imax = 42;
1133
1134         for(i = 0; i <= imax; ++i)
1135         {
1136                 float mapindex;
1137                 mapindex = (Map_Current + floor(random() * (Map_Count - 1) + 1)) % Map_Count; // any OTHER map
1138                 if(Map_Check(mapindex, 1))
1139                         return mapindex;
1140         }
1141         return -1;
1142 }
1143
1144 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
1145 // the exponent sets a bias on the map selection:
1146 // the higher the exponent, the less likely "shortly repeated" same maps are
1147 {
1148         float i, j, imax, insertpos;
1149
1150         LOG_TRACE("Trying MaplistMethod_Shuffle");
1151
1152         imax = 42;
1153
1154         for(i = 0; i <= imax; ++i)
1155         {
1156                 string newlist;
1157
1158                 // now reinsert this at another position
1159                 insertpos = (random() ** (1 / exponent));       // ]0, 1]
1160                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
1161                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
1162                 LOG_TRACE("SHUFFLE: insert pos = ", ftos(insertpos));
1163
1164                 // insert the current map there
1165                 newlist = "";
1166                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
1167                         newlist = strcat(newlist, " ", argv(j));
1168                 newlist = strcat(newlist, " ", argv(0));       // now insert the just selected map
1169                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
1170                         newlist = strcat(newlist, " ", argv(j));
1171                 newlist = substring(newlist, 1, strlen(newlist) - 1);
1172                 cvar_set("g_maplist", newlist);
1173                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1174
1175                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
1176                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
1177                 if(Map_Check(Map_Current, 1))
1178                         return Map_Current;
1179         }
1180         return -1;
1181 }
1182
1183 void Maplist_Init()
1184 {
1185         Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1186         float i;
1187         for (i = 0; i < Map_Count; ++i)
1188                 if (Map_Check(i, 2))
1189                         break;
1190         if (i == Map_Count)
1191         {
1192                 bprint( "Maplist contains no usable maps!  Resetting it to default map list.\n" );
1193                 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags() | MAPINFO_FLAG_NOAUTOMAPLIST));
1194                 if(autocvar_g_maplist_shuffle)
1195                         ShuffleMaplist();
1196                 localcmd("\nmenu_cmd sync\n");
1197                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1198         }
1199         if(Map_Count == 0)
1200                 error("empty maplist, cannot select a new map");
1201         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
1202
1203         if(Map_Current_Name)
1204                 strunzone(Map_Current_Name);
1205         Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
1206         // this may or may not be correct, but who cares, in the worst case a map
1207         // isn't chosen in the first pass that should have been
1208 }
1209
1210 string GetNextMap()
1211 {
1212         float nextMap;
1213
1214         Maplist_Init();
1215         nextMap = -1;
1216
1217         if(nextMap == -1)
1218                 if(autocvar_g_maplist_shuffle > 0)
1219                         nextMap = MaplistMethod_Shuffle(autocvar_g_maplist_shuffle + 1);
1220
1221         if(nextMap == -1)
1222                 if(autocvar_g_maplist_selectrandom)
1223                         nextMap = MaplistMethod_Random();
1224
1225         if(nextMap == -1)
1226                 nextMap = MaplistMethod_Iterate();
1227
1228         if(nextMap == -1)
1229                 nextMap = MaplistMethod_Repeat();
1230
1231         if(nextMap >= 0)
1232         {
1233                 Map_Goto_SetFloat(nextMap);
1234                 return getmapname_stored;
1235         }
1236
1237         return "";
1238 }
1239
1240 float DoNextMapOverride(float reinit)
1241 {
1242         if(autocvar_g_campaign)
1243         {
1244                 CampaignPostIntermission();
1245                 alreadychangedlevel = true;
1246                 return true;
1247         }
1248         if(autocvar_quit_when_empty)
1249         {
1250                 if(player_count <= currentbots)
1251                 {
1252                         localcmd("quit\n");
1253                         alreadychangedlevel = true;
1254                         return true;
1255                 }
1256         }
1257         if(autocvar_quit_and_redirect != "")
1258         {
1259                 redirection_target = strzone(autocvar_quit_and_redirect);
1260                 alreadychangedlevel = true;
1261                 return true;
1262         }
1263         if (!reinit && autocvar_samelevel) // if samelevel is set, stay on same level
1264         {
1265                 localcmd("restart\n");
1266                 alreadychangedlevel = true;
1267                 return true;
1268         }
1269         if(autocvar_nextmap != "")
1270         {
1271                 string m;
1272                 m = GameTypeVote_MapInfo_FixName(autocvar_nextmap);
1273                 cvar_set("nextmap",m);
1274
1275                 if(!m || gametypevote)
1276                         return false;
1277                 if(autocvar_sv_vote_gametype)
1278                 {
1279                         Map_Goto_SetStr(m);
1280                         return false;
1281                 }
1282
1283                 if(MapInfo_CheckMap(m))
1284                 {
1285                         Map_Goto_SetStr(m);
1286                         Map_Goto(reinit);
1287                         alreadychangedlevel = true;
1288                         return true;
1289                 }
1290         }
1291         if(!reinit && autocvar_lastlevel)
1292         {
1293                 cvar_settemp_restore();
1294                 localcmd("set lastlevel 0\ntogglemenu 1\n");
1295                 alreadychangedlevel = true;
1296                 return true;
1297         }
1298         return false;
1299 }
1300
1301 void GotoNextMap(float reinit)
1302 {
1303         //string nextmap;
1304         //float n, nummaps;
1305         //string s;
1306         if (alreadychangedlevel)
1307                 return;
1308         alreadychangedlevel = true;
1309
1310         string nextMap;
1311
1312         nextMap = GetNextMap();
1313         if(nextMap == "")
1314                 error("Everything is broken - cannot find a next map. Please report this to the developers.");
1315         Map_Goto(reinit);
1316 }
1317
1318
1319 /*
1320 ============
1321 IntermissionThink
1322
1323 When the player presses attack or jump, change to the next level
1324 ============
1325 */
1326 .float autoscreenshot;
1327 void IntermissionThink(entity this)
1328 {
1329         FixIntermissionClient(this);
1330
1331         float server_screenshot = (autocvar_sv_autoscreenshot && this.cvar_cl_autoscreenshot);
1332         float client_screenshot = (this.cvar_cl_autoscreenshot == 2);
1333
1334         if( (server_screenshot || client_screenshot)
1335                 && ((this.autoscreenshot > 0) && (time > this.autoscreenshot)) )
1336         {
1337                 this.autoscreenshot = -1;
1338                 if(IS_REAL_CLIENT(this)) { stuffcmd(this, sprintf("\nscreenshot screenshots/autoscreenshot/%s-%s.jpg; echo \"^5A screenshot has been taken at request of the server.\"\n", GetMapname(), strftime(false, "%s"))); }
1339                 return;
1340         }
1341
1342         if (time < intermission_exittime)
1343                 return;
1344
1345         if(!mapvote_initialized)
1346                 if (time < intermission_exittime + 10 && !(PHYS_INPUT_BUTTON_ATCK(this) || PHYS_INPUT_BUTTON_JUMP(this) || PHYS_INPUT_BUTTON_ATCK2(this) || PHYS_INPUT_BUTTON_HOOK(this) || PHYS_INPUT_BUTTON_USE(this)))
1347                         return;
1348
1349         MapVote_Start();
1350 }
1351
1352 /*
1353 ============
1354 FindIntermission
1355
1356 Returns the entity to view from
1357 ============
1358 */
1359 /*
1360 entity FindIntermission()
1361 {
1362         local   entity spot;
1363         local   float cyc;
1364
1365 // look for info_intermission first
1366         spot = find(NULL, classname, "info_intermission");
1367         if (spot)
1368         {       // pick a random one
1369                 cyc = random() * 4;
1370                 while (cyc > 1)
1371                 {
1372                         spot = find(spot, classname, "info_intermission");
1373                         if (!spot)
1374                                 spot = find(spot, classname, "info_intermission");
1375                         cyc = cyc - 1;
1376                 }
1377                 return spot;
1378         }
1379
1380 // then look for the start position
1381         spot = find(NULL, classname, "info_player_start");
1382         if (spot)
1383                 return spot;
1384
1385 // testinfo_player_start is only found in regioned levels
1386         spot = find(NULL, classname, "testplayerstart");
1387         if (spot)
1388                 return spot;
1389
1390 // then look for the start position
1391         spot = find(NULL, classname, "info_player_deathmatch");
1392         if (spot)
1393                 return spot;
1394
1395         //objerror ("FindIntermission: no spot");
1396         return NULL;
1397 }
1398 */
1399
1400 /*
1401 ===============================================================================
1402
1403 RULES
1404
1405 ===============================================================================
1406 */
1407
1408 void DumpStats(float final)
1409 {
1410         float file;
1411         string s;
1412         float to_console;
1413         float to_eventlog;
1414         float to_file;
1415         float i;
1416
1417         to_console = autocvar_sv_logscores_console;
1418         to_eventlog = autocvar_sv_eventlog;
1419         to_file = autocvar_sv_logscores_file;
1420
1421         if(!final)
1422         {
1423                 to_console = true; // always print printstats replies
1424                 to_eventlog = false; // but never print them to the event log
1425         }
1426
1427         if(to_eventlog)
1428                 if(autocvar_sv_eventlog_console)
1429                         to_console = false; // otherwise we get the output twice
1430
1431         if(final)
1432                 s = ":scores:";
1433         else
1434                 s = ":status:";
1435         s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1436
1437         if(to_console)
1438                 LOG_INFO(s, "\n");
1439         if(to_eventlog)
1440                 GameLogEcho(s);
1441
1442         file = -1;
1443         if(to_file)
1444         {
1445                 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1446                 if(file == -1)
1447                         to_file = false;
1448                 else
1449                         fputs(file, strcat(s, "\n"));
1450         }
1451
1452         s = strcat(":labels:player:", GetPlayerScoreString(NULL, 0));
1453         if(to_console)
1454                 LOG_INFO(s, "\n");
1455         if(to_eventlog)
1456                 GameLogEcho(s);
1457         if(to_file)
1458                 fputs(file, strcat(s, "\n"));
1459
1460         FOREACH_CLIENT(IS_REAL_CLIENT(it) || (IS_BOT_CLIENT(it) && autocvar_sv_logscores_bots), LAMBDA(
1461                 s = strcat(":player:see-labels:", GetPlayerScoreString(it, 0), ":");
1462                 s = strcat(s, ftos(rint(time - CS(it).jointime)), ":");
1463                 if(IS_PLAYER(it) || MUTATOR_CALLHOOK(GetPlayerStatus, it))
1464                         s = strcat(s, ftos(it.team), ":");
1465                 else
1466                         s = strcat(s, "spectator:");
1467
1468                 if(to_console)
1469                         LOG_INFO(s, playername(it, false), "\n");
1470                 if(to_eventlog)
1471                         GameLogEcho(strcat(s, ftos(it.playerid), ":", playername(it, false)));
1472                 if(to_file)
1473                         fputs(file, strcat(s, playername(it, false), "\n"));
1474         ));
1475
1476         if(teamplay)
1477         {
1478                 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1479                 if(to_console)
1480                         LOG_INFO(s, "\n");
1481                 if(to_eventlog)
1482                         GameLogEcho(s);
1483                 if(to_file)
1484                         fputs(file, strcat(s, "\n"));
1485
1486                 for(i = 1; i < 16; ++i)
1487                 {
1488                         s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1489                         s = strcat(s, ":", ftos(i));
1490                         if(to_console)
1491                                 LOG_INFO(s, "\n");
1492                         if(to_eventlog)
1493                                 GameLogEcho(s);
1494                         if(to_file)
1495                                 fputs(file, strcat(s, "\n"));
1496                 }
1497         }
1498
1499         if(to_console)
1500                 LOG_INFO(":end\n");
1501         if(to_eventlog)
1502                 GameLogEcho(":end");
1503         if(to_file)
1504         {
1505                 fputs(file, ":end\n");
1506                 fclose(file);
1507         }
1508 }
1509
1510 void FixIntermissionClient(entity e)
1511 {
1512         if(!e.autoscreenshot) // initial call
1513         {
1514                 e.autoscreenshot = time + 0.8;  // used for autoscreenshot
1515                 e.health = -2342;
1516                 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1517                 for (int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1518                 {
1519                     .entity weaponentity = weaponentities[slot];
1520                         if(e.(weaponentity))
1521                         {
1522                                 e.(weaponentity).effects = EF_NODRAW;
1523                                 if (e.(weaponentity).weaponchild)
1524                                         e.(weaponentity).weaponchild.effects = EF_NODRAW;
1525                         }
1526                 }
1527                 if(IS_REAL_CLIENT(e))
1528                 {
1529                         stuffcmd(e, "\nscr_printspeed 1000000\n");
1530                         RandomSelection_Init();
1531                         FOREACH_WORD(autocvar_sv_intermission_cdtrack, true, LAMBDA(
1532                                 RandomSelection_AddString(it, 1, 1);
1533                         ));
1534                         if (RandomSelection_chosen_string != "")
1535                         {
1536                                 stuffcmd(e, sprintf("\ncd loop %s\n", RandomSelection_chosen_string));
1537                         }
1538                         msg_entity = e;
1539                         WriteByte(MSG_ONE, SVC_INTERMISSION);
1540                 }
1541         }
1542 }
1543
1544 /*
1545 go to the next level for deathmatch
1546 only called if a time or frag limit has expired
1547 */
1548 void NextLevel()
1549 {
1550         game_stopped = true;
1551         intermission_running = 1; // game over
1552
1553         // enforce a wait time before allowing changelevel
1554         if(player_count > 0)
1555                 intermission_exittime = time + autocvar_sv_mapchange_delay;
1556         else
1557                 intermission_exittime = -1;
1558
1559         /*
1560         WriteByte (MSG_ALL, SVC_CDTRACK);
1561         WriteByte (MSG_ALL, 3);
1562         WriteByte (MSG_ALL, 3);
1563         // done in FixIntermission
1564         */
1565
1566         //pos = FindIntermission ();
1567
1568         VoteReset();
1569
1570         DumpStats(true);
1571
1572         // send statistics
1573         PlayerStats_GameReport(true);
1574         WeaponStats_Shutdown();
1575
1576         Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_Null); // kill all centerprints now
1577
1578         if(autocvar_sv_eventlog)
1579                 GameLogEcho(":gameover");
1580
1581         GameLogClose();
1582
1583         FOREACH_CLIENT(IS_PLAYER(it), LAMBDA(
1584                 FixIntermissionClient(it);
1585                 if(it.winning)
1586                         bprint(playername(it, false), " ^7wins.\n");
1587         ));
1588
1589         target_music_kill();
1590
1591         if(autocvar_g_campaign)
1592                 CampaignPreIntermission();
1593
1594         MUTATOR_CALLHOOK(MatchEnd);
1595
1596         localcmd("\nsv_hook_gameend\n");
1597 }
1598
1599
1600 float InitiateSuddenDeath()
1601 {
1602         // Check first whether normal overtimes could be added before initiating suddendeath mode
1603         // - for this timelimit_overtime needs to be >0 of course
1604         // - also check the winning condition calculated in the previous frame and only add normal overtime
1605         //   again, if at the point at which timelimit would be extended again, still no winner was found
1606         if (!autocvar_g_campaign && (checkrules_overtimesadded >= 0) && (checkrules_overtimesadded < autocvar_timelimit_overtimes || autocvar_timelimit_overtimes < 0) && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1607         {
1608                 return 1; // need to call InitiateOvertime later
1609         }
1610         else
1611         {
1612                 if(!checkrules_suddendeathend)
1613                 {
1614                         if(autocvar_g_campaign)
1615                                 checkrules_suddendeathend = time; // no suddendeath in campaign
1616                         else
1617                                 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1618                         if(g_race && !g_race_qualifying)
1619                                 race_StartCompleting();
1620                 }
1621                 return 0;
1622         }
1623 }
1624
1625 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1626 {
1627         ++checkrules_overtimesadded;
1628         //add one more overtime by simply extending the timelimit
1629         float tl;
1630         tl = autocvar_timelimit;
1631         tl += autocvar_timelimit_overtime;
1632         cvar_set("timelimit", ftos(tl));
1633
1634         Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime * 60);
1635 }
1636
1637 float GetWinningCode(float fraglimitreached, float equality)
1638 {
1639         if(autocvar_g_campaign == 1)
1640                 if(fraglimitreached)
1641                         return WINNING_YES;
1642                 else
1643                         return WINNING_NO;
1644
1645         else
1646                 if(equality)
1647                         if(fraglimitreached)
1648                                 return WINNING_STARTSUDDENDEATHOVERTIME;
1649                         else
1650                                 return WINNING_NEVER;
1651                 else
1652                         if(fraglimitreached)
1653                                 return WINNING_YES;
1654                         else
1655                                 return WINNING_NO;
1656 }
1657
1658 // set the .winning flag for exactly those players with a given field value
1659 void SetWinners(.float field, float value)
1660 {
1661         FOREACH_CLIENT(IS_PLAYER(it), LAMBDA(it.winning = (it.(field) == value)));
1662 }
1663
1664 // set the .winning flag for those players with a given field value
1665 void AddWinners(.float field, float value)
1666 {
1667         FOREACH_CLIENT(IS_PLAYER(it), LAMBDA(
1668                 if(it.(field) == value)
1669                         it.winning = 1;
1670         ));
1671 }
1672
1673 // clear the .winning flags
1674 void ClearWinners()
1675 {
1676         FOREACH_CLIENT(IS_PLAYER(it), LAMBDA(it.winning = 0));
1677 }
1678
1679 void ShuffleMaplist()
1680 {
1681         cvar_set("g_maplist", shufflewords(autocvar_g_maplist));
1682 }
1683
1684 float leaderfrags;
1685 float WinningCondition_Scores(float limit, float leadlimit)
1686 {
1687         float limitreached;
1688
1689         // TODO make everything use THIS winning condition (except LMS)
1690         WinningConditionHelper(NULL);
1691
1692         if(teamplay)
1693         {
1694                 team1_score = TeamScore_GetCompareValue(NUM_TEAM_1);
1695                 team2_score = TeamScore_GetCompareValue(NUM_TEAM_2);
1696                 team3_score = TeamScore_GetCompareValue(NUM_TEAM_3);
1697                 team4_score = TeamScore_GetCompareValue(NUM_TEAM_4);
1698         }
1699
1700         ClearWinners();
1701         if(WinningConditionHelper_winner)
1702                 WinningConditionHelper_winner.winning = 1;
1703         if(WinningConditionHelper_winnerteam >= 0)
1704                 SetWinners(team, WinningConditionHelper_winnerteam);
1705
1706         if(WinningConditionHelper_lowerisbetter)
1707         {
1708                 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1709                 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1710                 limit = -limit;
1711         }
1712
1713         if(WinningConditionHelper_zeroisworst)
1714                 leadlimit = 0; // not supported in this mode
1715
1716         if(MUTATOR_CALLHOOK(Scores_CountFragsRemaining))
1717         // these modes always score in increments of 1, thus this makes sense
1718         {
1719                 if(leaderfrags != WinningConditionHelper_topscore)
1720                 {
1721                         leaderfrags = WinningConditionHelper_topscore;
1722
1723                         if (limit)
1724                         if (leaderfrags == limit - 1)
1725                                 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_1);
1726                         else if (leaderfrags == limit - 2)
1727                                 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_2);
1728                         else if (leaderfrags == limit - 3)
1729                                 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_3);
1730                 }
1731         }
1732
1733         limitreached = false;
1734         if(limit)
1735                 if(WinningConditionHelper_topscore >= limit)
1736                         limitreached = true;
1737         if(leadlimit)
1738         {
1739                 float leadlimitreached;
1740                 leadlimitreached = (WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1741                 if(autocvar_leadlimit_and_fraglimit)
1742                         limitreached = (limitreached && leadlimitreached);
1743                 else
1744                         limitreached = (limitreached || leadlimitreached);
1745         }
1746
1747         if(limit)
1748                 game_completion_ratio = max(game_completion_ratio, bound(0, WinningConditionHelper_topscore / limit, 1));
1749
1750         return GetWinningCode(
1751                 WinningConditionHelper_topscore && limitreached,
1752                 WinningConditionHelper_equality
1753         );
1754 }
1755
1756 float WinningCondition_RanOutOfSpawns()
1757 {
1758         if(have_team_spawns <= 0)
1759                 return WINNING_NO;
1760
1761         if(!autocvar_g_spawn_useallspawns)
1762                 return WINNING_NO;
1763
1764         if(!some_spawn_has_been_used)
1765                 return WINNING_NO;
1766
1767         team1_score = team2_score = team3_score = team4_score = 0;
1768
1769         FOREACH_CLIENT(IS_PLAYER(it) && !IS_DEAD(it), LAMBDA(
1770                 switch(it.team)
1771                 {
1772                         case NUM_TEAM_1: team1_score = 1; break;
1773                         case NUM_TEAM_2: team2_score = 1; break;
1774                         case NUM_TEAM_3: team3_score = 1; break;
1775                         case NUM_TEAM_4: team4_score = 1; break;
1776                 }
1777         ));
1778
1779         IL_EACH(g_spawnpoints, true,
1780         {
1781                 switch(it.team)
1782                 {
1783                         case NUM_TEAM_1: team1_score = 1; break;
1784                         case NUM_TEAM_2: team2_score = 1; break;
1785                         case NUM_TEAM_3: team3_score = 1; break;
1786                         case NUM_TEAM_4: team4_score = 1; break;
1787                 }
1788         });
1789
1790         ClearWinners();
1791         if(team1_score + team2_score + team3_score + team4_score == 0)
1792         {
1793                 checkrules_equality = true;
1794                 return WINNING_YES;
1795         }
1796         else if(team1_score + team2_score + team3_score + team4_score == 1)
1797         {
1798                 float t, i;
1799                 if(team1_score)
1800                         t = NUM_TEAM_1;
1801                 else if(team2_score)
1802                         t = NUM_TEAM_2;
1803                 else if(team3_score)
1804                         t = NUM_TEAM_3;
1805                 else // if(team4_score)
1806                         t = NUM_TEAM_4;
1807                 CheckAllowedTeams(NULL);
1808                 for(i = 0; i < MAX_TEAMSCORE; ++i)
1809                 {
1810                         if(t != NUM_TEAM_1) if(c1 >= 0) TeamScore_AddToTeam(NUM_TEAM_1, i, -1000);
1811                         if(t != NUM_TEAM_2) if(c2 >= 0) TeamScore_AddToTeam(NUM_TEAM_2, i, -1000);
1812                         if(t != NUM_TEAM_3) if(c3 >= 0) TeamScore_AddToTeam(NUM_TEAM_3, i, -1000);
1813                         if(t != NUM_TEAM_4) if(c4 >= 0) TeamScore_AddToTeam(NUM_TEAM_4, i, -1000);
1814                 }
1815
1816                 AddWinners(team, t);
1817                 return WINNING_YES;
1818         }
1819         else
1820                 return WINNING_NO;
1821 }
1822
1823 /*
1824 ============
1825 CheckRules_World
1826
1827 Exit deathmatch games upon conditions
1828 ============
1829 */
1830 void CheckRules_World()
1831 {
1832         float timelimit;
1833         float fraglimit;
1834         float leadlimit;
1835
1836         VoteThink();
1837         MapVote_Think();
1838
1839         SetDefaultAlpha();
1840
1841         if (intermission_running) // someone else quit the game already
1842         {
1843                 if(player_count == 0) // Nobody there? Then let's go to the next map
1844                         MapVote_Start();
1845                         // this will actually check the player count in the next frame
1846                         // again, but this shouldn't hurt
1847                 return;
1848         }
1849
1850         timelimit = autocvar_timelimit * 60;
1851         fraglimit = autocvar_fraglimit;
1852         leadlimit = autocvar_leadlimit;
1853
1854         if(warmup_stage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1855         {
1856                 if(timelimit > 0)
1857                         timelimit = 0; // timelimit is not made for warmup
1858                 if(fraglimit > 0)
1859                         fraglimit = 0; // no fraglimit for now
1860                 leadlimit = 0; // no leadlimit for now
1861         }
1862
1863         if(timelimit > 0)
1864         {
1865                 timelimit += game_starttime;
1866         }
1867         else if (timelimit < 0)
1868         {
1869                 // endmatch
1870                 NextLevel();
1871                 return;
1872         }
1873
1874         float wantovertime;
1875         wantovertime = 0;
1876
1877         if(timelimit > game_starttime)
1878                 game_completion_ratio = (time - game_starttime) / (timelimit - game_starttime);
1879         else
1880                 game_completion_ratio = 0;
1881
1882         if(checkrules_suddendeathend)
1883         {
1884                 if(!checkrules_suddendeathwarning)
1885                 {
1886                         checkrules_suddendeathwarning = true;
1887                         if(g_race && !g_race_qualifying)
1888                                 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_RACE_FINISHLAP);
1889                         else
1890                                 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_FRAG);
1891                 }
1892         }
1893         else
1894         {
1895                 if (timelimit && time >= timelimit)
1896                 {
1897                         if(g_race && (g_race_qualifying == 2) && timelimit > 0)
1898                         {
1899                                 float totalplayers;
1900                                 float playerswithlaps;
1901                                 float readyplayers;
1902                                 totalplayers = playerswithlaps = readyplayers = 0;
1903                                 FOREACH_CLIENT(IS_PLAYER(it), LAMBDA(
1904                                         ++totalplayers;
1905                                         if(PlayerScore_Add(it, SP_RACE_FASTEST, 0))
1906                                                 ++playerswithlaps;
1907                                         if(it.ready)
1908                                                 ++readyplayers;
1909                                 ));
1910
1911                                 // at least 2 of the players have completed a lap: start the RACE
1912                                 // otherwise, the players should end the qualifying on their own
1913                                 if(readyplayers || playerswithlaps >= 2)
1914                                 {
1915                                         checkrules_suddendeathend = 0;
1916                                         ReadyRestart(); // go to race
1917                                         return;
1918                                 }
1919                                 else
1920                                         wantovertime |= InitiateSuddenDeath();
1921                         }
1922                         else
1923                                 wantovertime |= InitiateSuddenDeath();
1924                 }
1925         }
1926
1927         if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1928         {
1929                 NextLevel();
1930                 return;
1931         }
1932
1933         int checkrules_status = WinningCondition_RanOutOfSpawns();
1934         if(checkrules_status == WINNING_YES)
1935                 bprint("Hey! Someone ran out of spawns!\n");
1936         else if(MUTATOR_CALLHOOK(CheckRules_World, checkrules_status, timelimit, fraglimit))
1937                 checkrules_status = M_ARGV(0, float);
1938         else
1939                 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
1940
1941         if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
1942         {
1943                 checkrules_status = WINNING_NEVER;
1944                 checkrules_overtimesadded = -1;
1945                 wantovertime |= InitiateSuddenDeath();
1946         }
1947
1948         if(checkrules_status == WINNING_NEVER)
1949                 // equality cases! Nobody wins if the overtime ends in a draw.
1950                 ClearWinners();
1951
1952         if(wantovertime)
1953         {
1954                 if(checkrules_status == WINNING_NEVER)
1955                         InitiateOvertime();
1956                 else
1957                         checkrules_status = WINNING_YES;
1958         }
1959
1960         if(checkrules_suddendeathend)
1961                 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
1962                         checkrules_status = WINNING_YES;
1963
1964         if(checkrules_status == WINNING_YES)
1965         {
1966                 //print("WINNING\n");
1967                 NextLevel();
1968         }
1969 }
1970
1971 string GotoMap(string m)
1972 {
1973         m = GameTypeVote_MapInfo_FixName(m);
1974         if (!m)
1975                 return "The map you suggested is not available on this server.";
1976         if (!autocvar_sv_vote_gametype)
1977         if(!MapInfo_CheckMap(m))
1978                 return "The map you suggested does not support the current game mode.";
1979         cvar_set("nextmap", m);
1980         cvar_set("timelimit", "-1");
1981         if(mapvote_initialized || alreadychangedlevel)
1982         {
1983                 if(DoNextMapOverride(0))
1984                         return "Map switch initiated.";
1985                 else
1986                         return "Hm... no. For some reason I like THIS map more.";
1987         }
1988         else
1989                 return "Map switch will happen after scoreboard.";
1990 }
1991
1992 bool autocvar_sv_gameplayfix_multiplethinksperframe;
1993 void RunThink(entity this)
1994 {
1995         // don't let things stay in the past.
1996         // it is possible to start that way by a trigger with a local time.
1997         if(this.nextthink <= 0 || this.nextthink > time + frametime)
1998                 return;
1999
2000         float oldtime = time; // do we need to save this?
2001
2002         for (int iterations = 0; iterations < 128 && !wasfreed(this); iterations++)
2003         {
2004                 time = max(oldtime, this.nextthink);
2005                 this.nextthink = 0;
2006
2007                 if(getthink(this))
2008                         getthink(this)(this);
2009                 // mods often set nextthink to time to cause a think every frame,
2010                 // we don't want to loop in that case, so exit if the new nextthink is
2011                 // <= the time the qc was told, also exit if it is past the end of the
2012                 // frame
2013                 if(this.nextthink <= time || this.nextthink > oldtime + frametime || !autocvar_sv_gameplayfix_multiplethinksperframe)
2014                         break;
2015         }
2016
2017         time = oldtime;
2018 }
2019
2020 bool autocvar_sv_freezenonclients;
2021 bool autocvar_sv_gameplayfix_delayprojectiles;
2022 void Physics_Frame()
2023 {
2024         if(autocvar_sv_freezenonclients)
2025                 return;
2026
2027         FOREACH_ENTITY_FLOAT(pure_data, false,
2028         {
2029                 if(IS_CLIENT(it) || it.classname == "" || it.move_movetype == MOVETYPE_PUSH || it.move_movetype == MOVETYPE_FAKEPUSH || it.move_movetype == MOVETYPE_PHYSICS)
2030                         continue;
2031
2032                 //set_movetype(it, it.move_movetype);
2033                 // inline the set_movetype function, since this is called a lot
2034                 it.movetype = (it.move_qcphysics) ? MOVETYPE_NONE : it.move_movetype;
2035
2036                 if(it.move_movetype == MOVETYPE_NONE)
2037                         continue;
2038
2039                 if(it.move_qcphysics)
2040                         Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2041
2042                 if(it.movetype >= MOVETYPE_USER_FIRST && it.movetype <= MOVETYPE_USER_LAST) // these cases have no think handling
2043                 {
2044                         // handle thinking here
2045                         if (getthink(it) && it.nextthink > 0 && it.nextthink <= time + frametime)
2046                                 RunThink(it);
2047                 }
2048         });
2049
2050         if(autocvar_sv_gameplayfix_delayprojectiles >= 0)
2051                 return;
2052
2053         FOREACH_ENTITY_FLOAT(move_qcphysics, true,
2054         {
2055                 if(IS_CLIENT(it) || is_pure(it) || it.classname == "" || it.move_movetype == MOVETYPE_NONE)
2056                         continue;
2057                 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2058         });
2059 }
2060
2061 void systems_update();
2062 void EndFrame()
2063 {
2064         anticheat_endframe();
2065
2066         Physics_Frame();
2067
2068         FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2069                 entity e = IS_SPEC(it) ? it.enemy : it;
2070                 if (e.typehitsound) {
2071                         it.typehit_time = time;
2072                 } else if (e.killsound) {
2073                         it.kill_time = time;
2074                 } else if (e.damage_dealt) {
2075                         it.hit_time = time;
2076                         it.damage_dealt_total += ceil(e.damage_dealt);
2077                 }
2078         });
2079         // add 1 frametime because after this, engine SV_Physics
2080         // increases time by a frametime and then networks the frame
2081         // add another frametime because client shows everything with
2082         // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2083         // needed!
2084         float altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2085         FOREACH_CLIENT(true, {
2086                 it.typehitsound = false;
2087                 it.damage_dealt = 0;
2088                 it.killsound = false;
2089                 antilag_record(it, CS(it), altime);
2090         });
2091         IL_EACH(g_monsters, true,
2092         {
2093                 antilag_record(it, it, altime);
2094         });
2095         systems_update();
2096         IL_ENDFRAME();
2097 }
2098
2099
2100 /*
2101  * RedirectionThink:
2102  * returns true if redirecting
2103  */
2104 float redirection_timeout;
2105 float redirection_nextthink;
2106 float RedirectionThink()
2107 {
2108         float clients_found;
2109
2110         if(redirection_target == "")
2111                 return false;
2112
2113         if(!redirection_timeout)
2114         {
2115                 cvar_set("sv_public", "-2");
2116                 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2117                 if(redirection_target == "self")
2118                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2119                 else
2120                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2121         }
2122
2123         if(time < redirection_nextthink)
2124                 return true;
2125
2126         redirection_nextthink = time + 1;
2127
2128         clients_found = 0;
2129         FOREACH_CLIENT(IS_REAL_CLIENT(it), LAMBDA(
2130                 // TODO add timer
2131                 LOG_INFO("Redirecting: sending connect command to ", it.netname, "\n");
2132                 if(redirection_target == "self")
2133                         stuffcmd(it, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2134                 else
2135                         stuffcmd(it, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2136                 ++clients_found;
2137         ));
2138
2139         LOG_INFO("Redirecting: ", ftos(clients_found), " clients left.\n");
2140
2141         if(time > redirection_timeout || clients_found == 0)
2142                 localcmd("\nwait; wait; wait; quit\n");
2143
2144         return true;
2145 }
2146
2147 void TargetMusic_RestoreGame();
2148 void RestoreGame()
2149 {
2150         // Loaded from a save game
2151         // some things then break, so let's work around them...
2152
2153         // Progs DB (capture records)
2154         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2155
2156         // Mapinfo
2157         MapInfo_Shutdown();
2158         MapInfo_Enumerate();
2159         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2160         WeaponStats_Init();
2161
2162         TargetMusic_RestoreGame();
2163 }
2164
2165 void Shutdown()
2166 {
2167         game_stopped = 2;
2168
2169         if(world_initialized > 0)
2170         {
2171                 world_initialized = 0;
2172                 LOG_TRACE("Saving persistent data...");
2173                 Ban_SaveBans();
2174
2175                 // playerstats with unfinished match
2176                 PlayerStats_GameReport(false);
2177
2178                 if(!cheatcount_total)
2179                 {
2180                         if(autocvar_sv_db_saveasdump)
2181                                 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2182                         else
2183                                 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2184                 }
2185                 if(autocvar_developer)
2186                 {
2187                         if(autocvar_sv_db_saveasdump)
2188                                 db_dump(TemporaryDB, "server-temp.db");
2189                         else
2190                                 db_save(TemporaryDB, "server-temp.db");
2191                 }
2192                 CheatShutdown(); // must be after cheatcount check
2193                 db_close(ServerProgsDB);
2194                 db_close(TemporaryDB);
2195                 LOG_TRACE("Saving persistent data... done!");
2196                 // tell the bot system the game is ending now
2197                 bot_endgame();
2198
2199                 WeaponStats_Shutdown();
2200                 MapInfo_Shutdown();
2201         }
2202         else if(world_initialized == 0)
2203         {
2204                 LOG_INFO("NOTE: crashed before even initializing the world, not saving persistent data\n");
2205         }
2206         else
2207         {
2208                 __init_dedicated_server_shutdown();
2209         }
2210 }