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