]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/world.qc
124ca5afe85f32bf06e9f925a1372b2e8d56e8f8
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / world.qc
1 #include "world.qh"
2
3 #include <common/constants.qh>
4 #include <common/deathtypes/all.qh>
5 #include <common/gamemodes/_mod.qh>
6 #include <common/gamemodes/sv_rules.qh>
7 #include <common/items/_mod.qh>
8 #include <common/mapinfo.qh>
9 #include <common/mapobjects/target/music.qh>
10 #include <common/mapobjects/trigger/hurt.qh>
11 #include <common/mapobjects/trigger/secret.qh>
12 #include <common/mapobjects/triggers.qh>
13 #include <common/monsters/_mod.qh>
14 #include <common/monsters/sv_monsters.qh>
15 #include <common/net_linked.qh>
16 #include <common/notifications/all.qh>
17 #include <common/physics/player.qh>
18 #include <common/playerstats.qh>
19 #include <common/state.qh>
20 #include <common/stats.qh>
21 #include <common/teams.qh>
22 #include <common/util.qh>
23 #include <common/vehicles/all.qh>
24 #include <common/weapons/_all.qh>
25 #include <lib/warpzone/common.qh>
26 #include <server/anticheat.qh>
27 #include <server/antilag.qh>
28 #include <server/bot/api.qh>
29 #include <server/campaign.qh>
30 #include <server/cheats.qh>
31 #include <server/client.qh>
32 #include <server/command/common.qh>
33 #include <server/command/getreplies.qh>
34 #include <server/command/sv_cmd.qh>
35 #include <server/command/vote.qh>
36 #include <server/damage.qh>
37 #include <server/gamelog.qh>
38 #include <server/hook.qh>
39 #include <server/ipban.qh>
40 #include <server/items/items.qh>
41 #include <server/main.qh>
42 #include <server/mapvoting.qh>
43 #include <server/mutators/_mod.qh>
44 #include <server/race.qh>
45 #include <server/scores.qh>
46 #include <server/scores_rules.qh>
47 #include <server/spawnpoints.qh>
48 #include <server/teamplay.qh>
49 #include <server/weapons/weaponstats.qh>
50
51 const float LATENCY_THINKRATE = 10;
52 .float latency_sum;
53 .float latency_cnt;
54 .float latency_time;
55 entity pingplreport;
56 void PingPLReport_Think(entity this)
57 {
58         float delta;
59         entity e;
60
61         delta = 3 / maxclients;
62         if(delta < sys_frametime)
63                 delta = 0;
64         this.nextthink = time + delta;
65
66         e = edict_num(this.cnt + 1);
67         if(IS_CLIENT(e) && IS_REAL_CLIENT(e))
68         {
69                 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
70                 WriteByte(MSG_BROADCAST, this.cnt);
71                 WriteShort(MSG_BROADCAST, bound(1, rint(CS(e).ping), 32767));
72                 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_packetloss * 255), 255));
73                 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_movementloss * 255), 255));
74
75                 // record latency times for clients throughout the match so we can report it to playerstats
76                 if(time > (CS(e).latency_time + LATENCY_THINKRATE))
77                 {
78                         CS(e).latency_sum += CS(e).ping;
79                         CS(e).latency_cnt += 1;
80                         CS(e).latency_time = time;
81                         //print("sum: ", ftos(CS(e).latency_sum), ", cnt: ", ftos(CS(e).latency_cnt), ", avg: ", ftos(CS(e).latency_sum / CS(e).latency_cnt), ".\n");
82                 }
83         }
84         else
85         {
86                 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
87                 WriteByte(MSG_BROADCAST, this.cnt);
88                 WriteShort(MSG_BROADCAST, 0);
89                 WriteByte(MSG_BROADCAST, 0);
90                 WriteByte(MSG_BROADCAST, 0);
91         }
92         this.cnt = (this.cnt + 1) % maxclients;
93 }
94 void PingPLReport_Spawn()
95 {
96         pingplreport = new_pure(pingplreport);
97         setthink(pingplreport, PingPLReport_Think);
98         pingplreport.nextthink = time;
99 }
100
101 const float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
102
103 void SetDefaultAlpha()
104 {
105         if (!MUTATOR_CALLHOOK(SetDefaultAlpha))
106         {
107                 default_player_alpha = autocvar_g_player_alpha;
108                 if(default_player_alpha == 0)
109                         default_player_alpha = 1;
110                 default_weapon_alpha = default_player_alpha;
111         }
112 }
113
114 void GotoFirstMap(entity this)
115 {
116         float n;
117         if(autocvar__sv_init)
118         {
119                 // cvar_set("_sv_init", "0");
120                 // we do NOT set this to 0 any more, so someone "accidentally" changing
121                 // to this "init" map on a dedicated server will cause no permanent
122                 // harm
123                 if(autocvar_g_maplist_shuffle)
124                         ShuffleMaplist();
125                 n = tokenizebyseparator(autocvar_g_maplist, " ");
126                 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
127
128                 MapInfo_Enumerate();
129                 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
130
131                 if(!DoNextMapOverride(1))
132                         GotoNextMap(1);
133
134                 return;
135         }
136
137         if(time < 5)
138         {
139                 this.nextthink = time;
140         }
141         else
142         {
143                 this.nextthink = time + 1;
144                 LOG_INFO("Waiting for _sv_init being set to 1 by initialization scripts...");
145         }
146 }
147
148 void cvar_changes_init()
149 {
150         float h;
151         string k, v, d;
152         float n, i, adding, pureadding;
153
154         strfree(cvar_changes);
155         strfree(cvar_purechanges);
156         cvar_purechanges_count = 0;
157
158         h = buf_create();
159         buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
160         n = buf_getsize(h);
161
162         adding = true;
163         pureadding = true;
164
165         for(i = 0; i < n; ++i)
166         {
167                 k = bufstr_get(h, i);
168
169 #define BADPREFIX_COND(p) (substring(k, 0, strlen(p)) == p)
170 #define BADSUFFIX_COND(s) (substring(k, -strlen(s), -1) == s)
171
172 #define BADPREFIX(p) if(BADPREFIX_COND(p)) continue
173 #define BADPRESUFFIX(p, s) if(BADPREFIX_COND(p) && BADSUFFIX_COND(s)) continue
174 #define BADCVAR(p) if(k == p) continue
175 #define BADVALUE(p, val) if (k == p && v == val) continue
176 #define BADPRESUFFIXVALUE(p, s, val) if(BADPREFIX_COND(p) && BADSUFFIX_COND(s) && v == val) continue
177
178                 // general excludes and namespaces for server admin used cvars
179                 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
180
181                 // internal
182                 BADPREFIX("csqc_");
183                 BADPREFIX("cvar_check_");
184                 BADCVAR("gamecfg");
185                 BADCVAR("g_configversion");
186                 BADCVAR("halflifebsp");
187                 BADCVAR("sv_mapformat_is_quake2");
188                 BADCVAR("sv_mapformat_is_quake3");
189                 BADPREFIX("sv_world");
190
191                 // client
192                 BADPREFIX("chase_");
193                 BADPREFIX("cl_");
194                 BADPREFIX("con_");
195                 BADPREFIX("scoreboard_");
196                 BADPREFIX("g_campaign");
197                 BADPREFIX("g_waypointsprite_");
198                 BADPREFIX("gl_");
199                 BADPREFIX("joy");
200                 BADPREFIX("hud_");
201                 BADPREFIX("m_");
202                 BADPREFIX("menu_");
203                 BADPREFIX("net_slist_");
204                 BADPREFIX("r_");
205                 BADPREFIX("sbar_");
206                 BADPREFIX("scr_");
207                 BADPREFIX("snd_");
208                 BADPREFIX("show");
209                 BADPREFIX("sensitivity");
210                 BADPREFIX("userbind");
211                 BADPREFIX("v_");
212                 BADPREFIX("vid_");
213                 BADPREFIX("crosshair");
214                 BADCVAR("mod_q3bsp_lightmapmergepower");
215                 BADCVAR("mod_q3bsp_nolightmaps");
216                 BADCVAR("fov");
217                 BADCVAR("mastervolume");
218                 BADCVAR("volume");
219                 BADCVAR("bgmvolume");
220                 BADCVAR("in_pitch_min");
221                 BADCVAR("in_pitch_max");
222
223                 // private
224                 BADCVAR("developer");
225                 BADCVAR("log_dest_udp");
226                 BADCVAR("net_address");
227                 BADCVAR("net_address_ipv6");
228                 BADCVAR("port");
229                 BADCVAR("savedgamecfg");
230                 BADCVAR("serverconfig");
231                 BADCVAR("sv_autoscreenshot");
232                 BADCVAR("sv_heartbeatperiod");
233                 BADCVAR("sv_vote_master_password");
234                 BADCVAR("sys_colortranslation");
235                 BADCVAR("sys_specialcharactertranslation");
236                 BADCVAR("timeformat");
237                 BADCVAR("timestamps");
238                 BADCVAR("g_require_stats");
239                 BADPREFIX("developer_");
240                 BADPREFIX("g_ban_");
241                 BADPREFIX("g_banned_list");
242                 BADPREFIX("g_require_stats_");
243                 BADPREFIX("g_chat_flood_");
244                 BADPREFIX("g_ghost_items");
245                 BADPREFIX("g_playerstats_");
246                 BADPREFIX("g_voice_flood_");
247                 BADPREFIX("log_file");
248                 BADPREFIX("quit_");
249                 BADPREFIX("rcon_");
250                 BADPREFIX("sv_allowdownloads");
251                 BADPREFIX("sv_autodemo");
252                 BADPREFIX("sv_curl_");
253                 BADPREFIX("sv_eventlog");
254                 BADPREFIX("sv_logscores_");
255                 BADPREFIX("sv_master");
256                 BADPREFIX("sv_weaponstats_");
257                 BADPREFIX("sv_waypointsprite_");
258                 BADCVAR("rescan_pending");
259
260                 // these can contain player IDs, so better hide
261                 BADPREFIX("g_forced_team_");
262                 BADCVAR("sv_muteban_list");
263                 BADCVAR("sv_voteban_list");
264                 BADCVAR("sv_allow_customplayermodels_idlist");
265                 BADCVAR("sv_allow_customplayermodels_speciallist");
266
267                 // mapinfo
268                 BADCVAR("fraglimit");
269                 BADCVAR("g_arena");
270                 BADCVAR("g_assault");
271                 BADCVAR("g_ca");
272                 BADCVAR("g_ca_teams");
273                 BADCVAR("g_conquest");
274                 BADCVAR("g_conquest_teams");
275                 BADCVAR("g_ctf");
276                 BADCVAR("g_cts");
277                 BADCVAR("g_dotc");
278                 BADCVAR("g_dm");
279                 BADCVAR("g_domination");
280                 BADCVAR("g_domination_default_teams");
281                 BADCVAR("g_duel");
282                 BADCVAR("g_duel_not_dm_maps");
283                 BADCVAR("g_freezetag");
284                 BADCVAR("g_freezetag_teams");
285                 BADCVAR("g_invasion_type");
286                 BADCVAR("g_jailbreak");
287                 BADCVAR("g_jailbreak_teams");
288                 BADCVAR("g_keepaway");
289                 BADCVAR("g_keyhunt");
290                 BADCVAR("g_keyhunt_teams");
291                 BADCVAR("g_lms");
292                 BADCVAR("g_mayhem");
293                 BADCVAR("g_nexball");
294                 BADCVAR("g_onslaught");
295                 BADCVAR("g_race");
296                 BADCVAR("g_race_laps_limit");
297                 BADCVAR("g_race_qualifying_timelimit");
298                 BADCVAR("g_race_qualifying_timelimit_override");
299                 BADCVAR("g_runematch");
300                 BADCVAR("g_shootfromeye");
301                 BADCVAR("g_snafu");
302                 BADCVAR("g_survival");
303                 BADCVAR("g_survival_not_dm_maps");
304                 BADCVAR("g_tdm");
305                 BADCVAR("g_tdm_on_dm_maps");
306                 BADCVAR("g_tdm_teams");
307                 BADCVAR("g_tmayhem");
308                 BADCVAR("g_tmayhem_teams");
309                 BADCVAR("g_vip");
310                 BADCVAR("leadlimit");
311                 BADCVAR("nextmap");
312                 BADCVAR("teamplay");
313                 BADCVAR("timelimit");
314                 BADCVAR("g_mapinfo_q3compat");
315                 BADCVAR("g_mapinfo_settemp_acl");
316                 BADCVAR("g_mapinfo_ignore_warnings");
317                 BADCVAR("g_maplist_ignore_sizes");
318                 BADCVAR("g_maplist_sizes_count_bots");
319
320                 // long
321                 BADCVAR("hostname");
322                 BADCVAR("g_maplist");
323                 BADCVAR("g_maplist_mostrecent");
324                 BADCVAR("sv_motd");
325                 BADCVAR("sv_termsofservice_url");
326
327                 v = cvar_string(k);
328                 d = cvar_defstring(k);
329                 if(v == d)
330                         continue;
331
332                 if(adding)
333                 {
334                         cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
335                         if(strlen(cvar_changes) > 16384)
336                         {
337                                 cvar_changes = "// too many settings have been changed to show them here\n";
338                                 adding = 0;
339                         }
340                 }
341
342                 // now check if the changes are actually gameplay relevant
343
344                 // does nothing gameplay relevant
345                 BADCVAR("captureleadlimit_override");
346                 BADCVAR("condump_stripcolors");
347                 BADCVAR("fs_gamedir");
348                 BADCVAR("g_allow_oldvortexbeam");
349                 BADCVAR("g_balance_kill_delay");
350                 BADCVAR("g_buffs_pickup_anyway");
351                 BADCVAR("g_buffs_randomize");
352                 BADCVAR("g_buffs_randomize_teamplay");
353                 BADCVAR("g_campcheck_distance");
354                 BADCVAR("g_chatsounds");
355                 BADCVAR("g_ca_point_leadlimit");
356                 BADCVAR("g_ca_point_limit");
357                 BADCVAR("g_ca_spectate_enemies");
358                 BADCVAR("g_ctf_captimerecord_always");
359                 BADCVAR("g_ctf_flag_glowtrails");
360                 BADCVAR("g_ctf_dynamiclights");
361                 BADCVAR("g_ctf_flag_pickup_verbosename");
362                 BADCVAR("g_ctf_flagcarrier_auto_helpme_damage");
363                 BADPRESUFFIX("g_ctf_flag_", "_model");
364                 BADPRESUFFIX("g_ctf_flag_", "_skin");
365                 BADCVAR("g_domination_point_leadlimit");
366                 BADCVAR("g_forced_respawn");
367                 BADCVAR("g_freezetag_point_leadlimit");
368                 BADCVAR("g_freezetag_point_limit");
369                 BADCVAR("g_glowtrails");
370                 BADCVAR("g_hats");
371                 BADCVAR("g_casings");
372                 BADCVAR("g_invasion_point_limit");
373                 BADCVAR("g_jump_grunt");
374                 BADCVAR("g_keepaway_ballcarrier_effects");
375                 BADCVAR("g_keepawayball_effects");
376                 BADCVAR("g_keyhunt_point_leadlimit");
377                 BADCVAR("g_nexball_goalleadlimit");
378                 BADCVAR("g_new_toys_autoreplace");
379                 BADCVAR("g_new_toys_use_pickupsound");
380                 BADCVAR("g_physics_predictall");
381                 BADCVAR("g_piggyback");
382                 BADCVAR("g_playerclip_collisions");
383                 BADCVAR("g_spawn_alloweffects");
384                 BADCVAR("g_tdm_point_leadlimit");
385                 BADCVAR("g_tdm_point_limit");
386                 BADCVAR("g_mayhem_point_limit");
387                 BADCVAR("g_mayhem_point_leadlimit");
388                 BADCVAR("g_tmayhem_point_limit");
389                 BADCVAR("g_tmayhem_point_leadlimit");
390                 BADCVAR("leadlimit_and_fraglimit");
391                 BADCVAR("leadlimit_override");
392                 BADCVAR("pausable");
393                 BADCVAR("sv_announcer");
394                 BADCVAR("sv_autopause");
395                 BADCVAR("sv_checkforpacketsduringsleep");
396                 BADCVAR("sv_damagetext");
397                 BADCVAR("sv_db_saveasdump");
398                 BADCVAR("sv_intermission_cdtrack");
399                 BADCVAR("sv_mapchange_delay");
400                 BADCVAR("sv_minigames");
401                 BADCVAR("sv_namechangetimer");
402                 BADCVAR("sv_precacheplayermodels");
403                 BADCVAR("sv_qcphysics");
404                 BADCVAR("sv_radio");
405                 BADCVAR("sv_stepheight");
406                 BADCVAR("sv_timeout");
407                 BADCVAR("sv_weapons_modeloverride");
408                 BADCVAR("w_prop_interval");
409                 BADPREFIX("chat_");
410                 BADPREFIX("crypto_");
411                 BADPREFIX("gameversion");
412                 BADPREFIX("g_chat_");
413                 BADPREFIX("g_ctf_captimerecord_");
414                 BADPREFIX("g_hats_");
415                 BADPREFIX("g_maplist_");
416                 BADPREFIX("g_mod_");
417                 BADPREFIX("g_respawn_");
418                 BADPREFIX("net_");
419                 BADPREFIX("notification_");
420                 BADPREFIX("prvm_");
421                 BADPREFIX("skill_");
422                 BADPREFIX("sv_allow_");
423                 BADPREFIX("sv_cullentities_");
424                 BADPREFIX("sv_maxidle");
425                 BADPREFIX("sv_minigames_");
426                 BADPREFIX("sv_radio_");
427                 BADPREFIX("sv_timeout_");
428                 BADPREFIX("sv_vote_");
429                 BADPREFIX("timelimit_");
430                 BADPRESUFFIX("g_", "_round_timelimit");
431
432                 // allowed changes to server admins (please sync this to server.cfg)
433                 // vi commands:
434                 //   :/"impure"/,$d
435                 //   :g!,^\/\/[^ /],d
436                 //   :%s,//\([^ ]*\).*,BADCVAR("\1");,
437                 //   :%!sort
438                 // yes, this does contain some redundant stuff, don't really care
439                 BADPREFIX("bot_ai_");
440                 BADCVAR("bot_config_file");
441                 BADCVAR("bot_number");
442                 BADCVAR("bot_prefix");
443                 BADCVAR("bot_suffix");
444                 BADCVAR("capturelimit_override");
445                 BADCVAR("fraglimit_override");
446                 BADCVAR("gametype");
447                 BADCVAR("g_antilag");
448                 BADCVAR("g_balance_teams");
449                 BADCVAR("g_balance_teams_prevent_imbalance");
450                 BADCVAR("g_balance_teams_scorefactor");
451                 BADCVAR("g_ban_sync_trusted_servers");
452                 BADCVAR("g_ban_sync_uri");
453                 BADCVAR("g_buffs");
454                 BADCVAR("g_ca_teams_override");
455                 BADCVAR("g_ctf_fullbrightflags");
456                 BADCVAR("g_ctf_ignore_frags");
457                 BADCVAR("g_ctf_leaderboard");
458                 BADCVAR("g_domination_point_limit");
459                 BADCVAR("g_domination_teams_override");
460                 BADCVAR("g_freezetag_revive_spawnshield");
461                 BADCVAR("g_freezetag_teams_override");
462                 BADCVAR("g_friendlyfire");
463                 BADCVAR("g_fullbrightitems");
464                 BADCVAR("g_fullbrightplayers");
465                 BADCVAR("g_keyhunt_point_limit");
466                 BADCVAR("g_keyhunt_teams_override");
467                 BADCVAR("g_lms_lives_override");
468                 BADCVAR("g_mayhem_powerups");
469                 BADCVAR("g_maplist");
470                 BADCVAR("g_maxplayers");
471                 BADCVAR("g_mirrordamage");
472                 BADCVAR("g_nexball_goallimit");
473                 BADCVAR("g_norecoil");
474                 BADCVAR("g_physics_clientselect");
475                 BADCVAR("g_pinata");
476                 BADCVAR("g_powerups");
477                 BADCVAR("g_powerups_drop_ondeath");
478                 BADCVAR("g_player_brightness");
479                 BADCVAR("g_rocket_flying");
480                 BADCVAR("g_rocket_flying_disabledelays");
481                 BADPREFIX("g_spawnshield");
482                 BADCVAR("g_start_delay");
483                 BADCVAR("g_superspectate");
484                 BADCVAR("g_tdm_teams_override");
485                 BADCVAR("g_tmayhem_teams_override");
486                 BADCVAR("g_tmayhem_powerups");
487                 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
488                 BADCVAR("hostname");
489                 BADCVAR("log_file");
490                 BADCVAR("maxplayers");
491                 BADCVAR("minplayers");
492                 BADCVAR("minplayers_per_team");
493                 BADCVAR("net_address");
494                 BADCVAR("port");
495                 BADCVAR("rcon_password");
496                 BADCVAR("rcon_restricted_commands");
497                 BADCVAR("rcon_restricted_password");
498                 BADCVAR("skill");
499                 BADCVAR("sv_adminnick");
500                 BADCVAR("sv_autoscreenshot");
501                 BADCVAR("sv_autotaunt");
502                 BADCVAR("sv_curl_defaulturl");
503                 BADCVAR("sv_defaultcharacter");
504                 BADCVAR("sv_defaultcharacterskin");
505                 BADCVAR("sv_defaultplayercolors");
506                 BADCVAR("sv_defaultplayermodel");
507                 BADCVAR("sv_defaultplayerskin");
508                 BADCVAR("sv_maxrate");
509                 BADCVAR("sv_motd");
510                 BADCVAR("sv_public");
511                 BADCVAR("sv_showfps");
512                 BADCVAR("sv_showspectators");
513                 BADCVAR("sv_status_privacy");
514                 BADCVAR("sv_taunt");
515                 BADCVAR("sv_vote_call");
516                 BADCVAR("sv_vote_commands");
517                 BADCVAR("sv_vote_majority_factor");
518                 BADCVAR("sv_vote_master");
519                 BADCVAR("sv_vote_master_commands");
520                 BADCVAR("sv_vote_master_password");
521                 BADCVAR("sv_vote_simple_majority_factor");
522                 BADVALUE("sys_ticrate", "0.0166667");
523                 BADVALUE("sys_ticrate", "0.0333333");
524                 BADCVAR("teamplay_mode");
525                 BADCVAR("timelimit_override");
526                 BADPREFIX("g_warmup");
527                 BADPREFIX("sv_info_");
528                 BADPREFIX("sv_ready_restart_");
529
530                 BADPRESUFFIXVALUE("g_", "_weaponarena", "most");
531                 BADPRESUFFIXVALUE("g_", "_weaponarena", "most_available");
532
533                 // mutators that announce themselves properly to the server browser
534                 BADCVAR("g_instagib");
535                 BADCVAR("g_new_toys");
536                 BADCVAR("g_nix");
537                 BADCVAR("g_grappling_hook");
538                 BADCVAR("g_jetpack");
539
540 #undef BADPRESUFFIX
541 #undef BADPREFIX
542 #undef BADCVAR
543 #undef BADVALUE
544 #undef BADPRESUFFIXVALUE
545
546                 if(pureadding)
547                 {
548                         cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
549                         if(strlen(cvar_purechanges) > 16384)
550                         {
551                                 cvar_purechanges = "// too many settings have been changed to show them here\n";
552                                 pureadding = 0;
553                         }
554                 }
555                 ++cvar_purechanges_count;
556                 // WARNING: this variable is used for the server list
557                 // NEVER dare to skip this code!
558                 // Hacks to intentionally appearing as "pure server" even though you DO have
559                 // modified settings may be punished by removal from the server list.
560                 // You can do to the variables cvar_changes and cvar_purechanges all you want,
561                 // though.
562         }
563         buf_del(h);
564         if(cvar_changes == "")
565                 cvar_changes = "// this server runs at default server settings\n";
566         else
567                 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
568         cvar_changes = strzone(cvar_changes);
569         if(cvar_purechanges == "")
570                 cvar_purechanges = "// this server runs at default gameplay settings\n";
571         else
572                 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
573         cvar_purechanges = strzone(cvar_purechanges);
574 }
575
576 entity randomseed;
577 bool RandomSeed_Send(entity this, entity to, int sf)
578 {
579         WriteHeader(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
580         WriteShort(MSG_ENTITY, this.cnt);
581         return true;
582 }
583 void RandomSeed_Think(entity this)
584 {
585         this.cnt = bound(0, floor(random() * 65536), 65535);
586         this.nextthink = time + 5;
587
588         this.SendFlags |= 1;
589 }
590 void RandomSeed_Spawn()
591 {
592         randomseed = new_pure(randomseed);
593         setthink(randomseed, RandomSeed_Think);
594         Net_LinkEntity(randomseed, false, 0, RandomSeed_Send);
595
596         getthink(randomseed)(randomseed); // sets random seed and nextthink
597 }
598
599 spawnfunc(__init_dedicated_server)
600 {
601         // handler for _init/_init map (only for dedicated server initialization)
602
603         world_initialized = -1; // don't complain
604
605         delete_fn = remove_unsafely;
606
607         entity e = new(GotoFirstMap);
608         setthink(e, GotoFirstMap);
609         e.nextthink = time; // this is usually 1 at this point
610
611         e = new(info_player_deathmatch);  // safeguard against player joining
612
613         // assign reflectively to avoid "assignment to world" warning
614         for (int i = 0, n = numentityfields(); i < n; ++i)
615         {
616                 string k = entityfieldname(i);
617                 if (k == "classname")
618                 {
619                         // safeguard against various stuff ;)
620                         putentityfieldstring(i, this, "worldspawn");
621                         break;
622                 }
623         }
624
625         // needs to be done so early because of the constants they create
626         static_init();
627         static_init_late();
628         static_init_precache();
629
630         IL_PUSH(g_spawnpoints, e); // just incase
631
632         MapInfo_Enumerate();
633         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
634 }
635
636 void __init_dedicated_server_shutdown() {
637         MapInfo_Shutdown();
638 }
639
640 STATIC_INIT_EARLY(maxclients)
641 {
642         maxclients = 0;
643         for (entity head = nextent(NULL); head; head = nextent(head)) {
644                 ++maxclients;
645         }
646 }
647
648 void GameplayMode_DelayedInit(entity this)
649 {
650         // at this stage team entities are spawned, teamplay contains the number of them
651
652         if(!scores_initialized)
653                 ScoreRules_generic();
654
655         if (warmup_stage >= 0 && autocvar_g_maxplayers >= 0)
656                 return;
657         if (!g_duel)
658                 MapReadSizes(mapname);
659
660         if (autocvar_g_maxplayers < 0 && teamplay)
661         {
662                 // automatic maxplayers should be a multiple of team count
663                 if (map_maxplayers == 0 || map_maxplayers > maxclients)
664                         map_maxplayers = maxclients; // unlimited, but may need rounding
665                 int d = map_maxplayers % AVAILABLE_TEAMS;
666                 int u = AVAILABLE_TEAMS - d;
667                 map_maxplayers += (u <= d && u + map_maxplayers <= maxclients) ? u : -d;
668         }
669
670         if (warmup_stage < 0)
671         {
672                 int m = GetPlayerLimit();
673                 if (m <= 0) m = maxclients;
674                 map_minplayers = bound(max(2, AVAILABLE_TEAMS * 2), map_minplayers, m);
675                 if (teamplay)
676                 {
677                         // automatic minplayers should be a multiple of team count
678                         int d = map_minplayers % AVAILABLE_TEAMS;
679                         int u = AVAILABLE_TEAMS - d;
680                         map_minplayers += (u < d && u + map_minplayers <= m) ? u : -d;
681                 }
682         }
683         else
684                 map_minplayers = 0; // don't display a minimum if it's not used (g_maxplayers < 0 && g_warmup >= 0)
685 }
686
687 void InitGameplayMode()
688 {
689         VoteReset();
690
691         // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
692         get_mi_min_max(1);
693         // assign reflectively to avoid "assignment to world" warning
694         for (int i = 0, done = 0, n = numentityfields(); i < n; ++i)
695         {
696                 string k = entityfieldname(i);
697                 vector v = (k == "mins") ? mi_min : (k == "maxs") ? mi_max : '0 0 0';
698                 if (v)
699                 {
700                         putentityfieldstring(i, world, sprintf("%v", v));
701                         if (++done == 2) break;
702                 }
703         }
704         // currently, NetRadiant's limit is 131072 qu for each side
705         // distance from one corner of a 131072qu cube to the opposite corner is approx. 227023 qu
706         // set the distance according to map size but don't go over the limit to avoid issues with float precision
707         // in case somebody makes extremely large maps
708         max_shot_distance = min(230000, vlen(world.maxs - world.mins));
709
710         MapInfo_LoadMapSettings(mapname);
711         GameRules_teams(false);
712
713         if (!cvar_value_issafe(world.fog))
714         {
715                 LOG_INFO("The current map contains a potentially harmful fog setting, ignored");
716                 world.fog = string_null;
717         }
718         if(MapInfo_Map_fog != "")
719         {
720                 if(MapInfo_Map_fog == "none")
721                         world.fog = string_null;
722                 else
723                         world.fog = strzone(MapInfo_Map_fog);
724         }
725         clientstuff = strzone(MapInfo_Map_clientstuff);
726
727         MapInfo_ClearTemps();
728
729         gamemode_name = MapInfo_Type_ToText(MapInfo_LoadedGametype);
730
731         cache_mutatormsg = strzone("");
732         cache_lastmutatormsg = strzone("");
733
734         InitializeEntity(NULL, GameplayMode_DelayedInit, INITPRIO_GAMETYPE_FALLBACK);
735 }
736
737 bool world_already_spawned;
738 spawnfunc(worldspawn)
739 {
740         cvar_set("_endmatch", "0");
741         server_is_dedicated = boolean(stof(cvar_defstring("is_dedicated")));
742
743         if (autocvar_sv_termsofservice_url && autocvar_sv_termsofservice_url != "")
744         {
745                 strcpy(sv_termsofservice_url_escaped, strreplace(":", "|", autocvar_sv_termsofservice_url));
746         }
747         else
748         {
749                 strcpy(sv_termsofservice_url_escaped, "INVALID");
750         }
751
752         bool wantrestart = false;
753         {
754                 if (!server_is_dedicated)
755                 {
756                         // DP unloads dlcache pk3s before starting a listen server since https://gitlab.com/xonotic/darkplaces/-/merge_requests/134
757                         // restore csqc_progname too
758                         string expect = "csprogs.dat";
759                         wantrestart = cvar_string("csqc_progname") != expect;
760                         cvar_set("csqc_progname", expect);
761                 }
762                 else
763                 {
764                         // Try to use versioned csprogs from pk3
765                         // Only ever use versioned csprogs.dat files on dedicated servers;
766                         // we need to reset csqc_progname on clients ourselves, and it's easier if the client's release name is constant
767                         string pk3csprogs = "csprogs-" WATERMARK ".dat";
768                         // This always works; fall back to it if a versioned csprogs.dat is suddenly missing
769                         string select = "csprogs.dat";
770                         if (fexists(pk3csprogs)) select = pk3csprogs;
771                         if (cvar_string("csqc_progname") != select)
772                         {
773                                 cvar_set("csqc_progname", select);
774                                 wantrestart = true;
775                         }
776                         // Check for updates on startup
777                         // We do it this way for atomicity so that connecting clients still match the server progs and don't disconnect
778                         int sentinel = fopen("progs.txt", FILE_READ);
779                         if (sentinel >= 0)
780                         {
781                                 string switchversion = fgets(sentinel);
782                                 fclose(sentinel);
783                                 if (switchversion != "" && switchversion != WATERMARK)
784                                 {
785                                         LOG_INFOF("Switching progs: " WATERMARK " -> %s", switchversion);
786                                         // if it doesn't exist, assume either:
787                                         //   a) the current program was overwritten
788                                         //   b) this is a client only update
789                                         string newprogs = sprintf("progs-%s.dat", switchversion);
790                                         if (fexists(newprogs))
791                                         {
792                                                 cvar_set("sv_progs", newprogs);
793                                                 wantrestart = true;
794                                         }
795                                         string newcsprogs = sprintf("csprogs-%s.dat", switchversion);
796                                         if (fexists(newcsprogs))
797                                         {
798                                                 cvar_set("csqc_progname", newcsprogs);
799                                                 wantrestart = true;
800                                         }
801                                 }
802                         }
803                 }
804                 if (wantrestart)
805                 {
806                         LOG_INFO("Restart requested");
807                         changelevel(mapname);
808                         // let initialization continue, shutdown depends on it
809                 }
810         }
811
812         if(world_already_spawned)
813                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
814         world_already_spawned = true;
815
816         delete_fn = remove_safely; // during spawning, watch what you remove!
817
818         cvar_changes_init(); // do this very early now so it REALLY matches the server config
819
820         // default to RACE_RECORD, can be overwritten by gamemodes
821         record_type = RACE_RECORD;
822
823         // needs to be done so early because of the constants they create
824         static_init();
825
826         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
827
828         TemporaryDB = db_create();
829
830         // 0 normal
831         lightstyle(0, "m");
832
833         // 1 FLICKER (first variety)
834         lightstyle(1, "mmnmmommommnonmmonqnmmo");
835
836         // 2 SLOW STRONG PULSE
837         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
838
839         // 3 CANDLE (first variety)
840         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
841
842         // 4 FAST STROBE
843         lightstyle(4, "mamamamamama");
844
845         // 5 GENTLE PULSE 1
846         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
847
848         // 6 FLICKER (second variety)
849         lightstyle(6, "nmonqnmomnmomomno");
850
851         // 7 CANDLE (second variety)
852         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
853
854         // 8 CANDLE (third variety)
855         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
856
857         // 9 SLOW STROBE (fourth variety)
858         lightstyle(9, "aaaaaaaazzzzzzzz");
859
860         // 10 FLUORESCENT FLICKER
861         lightstyle(10, "mmamammmmammamamaaamammma");
862
863         // 11 SLOW PULSE NOT FADE TO BLACK
864         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
865
866         // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
867
868         // 63 testing
869         lightstyle(63, "a");
870
871         if(autocvar_g_campaign)
872                 CampaignPreInit();
873         else
874                 PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
875
876         Map_MarkAsRecent(mapname);
877
878         InitGameplayMode();
879         static_init_late();
880         static_init_precache();
881         readlevelcvars();
882
883         GameRules_limit_fallbacks();
884
885         player_count = 0;
886         bot_waypoints_for_items = autocvar_g_waypoints_for_items;
887         if(bot_waypoints_for_items == 1)
888                 if(this.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
889                         bot_waypoints_for_items = 0;
890
891         WaypointSprite_Init();
892
893         // NOTE for matchid:
894         // changing the logic generating it is okay. But:
895         // it HAS to stay <= 64 chars
896         // character set: ASCII 33-126 without the following characters: : ; ' " \ $
897         // strftime(false, "%s") isn't reliable, see strftime_s description
898         matchid = strzone(sprintf("%d.%s.%06d", autocvar_sv_eventlog_files_counter, strftime_s(), random() * 1000000));
899
900         if(autocvar_sv_eventlog)
901                 GameLogInit(); // requires matchid to be set
902
903         cvar_set("nextmap", "");
904
905         SetDefaultAlpha();
906
907         if(autocvar_g_campaign)
908                 CampaignPostInit();
909
910         Ban_LoadBans();
911
912         MapInfo_Enumerate();
913         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
914
915         q3compat = BITSET(q3compat, Q3COMPAT_ARENA, _MapInfo_FindArenaFile(mapname, ".arena") != "");
916         q3compat = BITSET(q3compat, Q3COMPAT_DEFI, _MapInfo_FindArenaFile(mapname, ".defi") != "");
917
918         // quake 3 music support
919         if(world.music || world.noise)
920         {
921                 // prefer .music over .noise
922                 string chosen_music;
923                 if(world.music)
924                         chosen_music = world.music;
925                 else
926                         chosen_music = world.noise;
927
928                 string newstuff = strcat(clientstuff, "cd loop \"", chosen_music, "\"\n");
929                 strcpy(clientstuff, newstuff);
930         }
931
932         if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
933         {
934                 int fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
935                 if(fd != -1)
936                 {
937                         string s;
938                         while((s = fgets(fd)))
939                         {
940                                 int l = tokenize_console(s);
941                                 if(l < 2)
942                                         continue;
943                                 if(argv(0) == "cd")
944                                 {
945                                         string trackname = argv(2);
946                                         LOG_INFO("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:");
947                                         LOG_INFO("  cdtrack ", trackname);
948                                         if (cvar_value_issafe(trackname))
949                                         {
950                                                 string newstuff = strcat(clientstuff, "cd loop \"", trackname, "\"\n");
951                                                 strcpy(clientstuff, newstuff);
952                                         }
953                                 }
954                                 else if(argv(0) == "fog")
955                                 {
956                                         LOG_INFO("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:");
957                                         LOG_INFO("  \"fog\" \"", s, "\"");
958                                 }
959                                 else if(argv(0) == "set")
960                                 {
961                                         LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
962                                         LOG_INFO("  clientsettemp_for_type all ", argv(1), " ", argv(2));
963                                 }
964                                 else if(argv(0) != "//")
965                                 {
966                                         LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
967                                         LOG_INFO("  clientsettemp_for_type all ", argv(0), " ", argv(1));
968                                 }
969                         }
970                         fclose(fd);
971                 }
972         }
973
974         WeaponStats_Init();
975
976         Nagger_Init();
977
978         // set up information replies for clients and server to use
979         maplist_reply = strzone(getmaplist());
980         lsmaps_reply = strzone(getlsmaps());
981         monsterlist_reply = strzone(getmonsterlist());
982         bool records_available = false;
983         for(int i = 0; i < 10; ++i)
984         {
985                 string s = getrecords(i);
986                 if (s != "")
987                 {
988                         records_reply[i] = strzone(s);
989                         records_available = true;
990                 }
991         }
992         if (!records_available)
993                 records_reply[0] = "No records available for the current game mode.\n";
994         ladder_reply = strzone(getladder());
995         rankings_reply = strzone(getrankings());
996
997         // begin other init
998         ClientInit_Spawn();
999         RandomSeed_Spawn();
1000         PingPLReport_Spawn();
1001
1002         CheatInit();
1003
1004         if (!wantrestart) localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
1005
1006         // fill sv_curl_serverpackages from .serverpackage files
1007         if (autocvar_sv_curl_serverpackages_auto)
1008         {
1009                 string s = "csprogs-" WATERMARK ".dat";
1010                 // remove automatically managed files from the list to prevent duplicates
1011                 for (int i = 0, n = tokenize_console(cvar_string("sv_curl_serverpackages")); i < n; ++i)
1012                 {
1013                         string pkg = argv(i);
1014                         if (startsWith(pkg, "csprogs-")) continue;
1015                         if (endsWith(pkg, "-serverpackage.txt")) continue;
1016                         if (endsWith(pkg, ".serverpackage")) continue;  // OLD legacy
1017                         s = cons(s, pkg);
1018                 }
1019                 // add automatically managed files to the list
1020                 #define X(match) MACRO_BEGIN \
1021                         int fd = search_begin(match, true, false); \
1022                         if (fd >= 0) \
1023                         { \
1024                                 for (int i = 0, j = search_getsize(fd); i < j; ++i) \
1025                                 { \
1026                                         s = cons(s, search_getfilename(fd, i)); \
1027                                 } \
1028                                 search_end(fd); \
1029                         } \
1030                 MACRO_END
1031                 X("*-serverpackage.txt");
1032                 X("*.serverpackage");
1033                 #undef X
1034                 cvar_set("sv_curl_serverpackages", s);
1035         }
1036
1037         // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
1038         modname = "Xonotic";
1039         // physics/balance/config changes that count as mod
1040         if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
1041                 modname = cvar_string("g_mod_physics");
1042         if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance") && cvar_string("g_mod_balance") != "Testing")
1043                 modname = cvar_string("g_mod_balance");
1044         if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
1045                 modname = cvar_string("g_mod_config");
1046         // extra mutators that deserve to count as mod
1047         MUTATOR_CALLHOOK(SetModname, modname);
1048         modname = M_ARGV(0, string);
1049
1050         // save it for later
1051         modname = strzone(modname);
1052
1053         WinningConditionHelper(this); // set worldstatus
1054
1055         if (autocvar_sv_autopause && server_is_dedicated && !wantrestart)
1056                 // INITPRIO_LAST is to soon: bots either didn't join yet or didn't leave yet, see: bot_fixcount()
1057                 defer(this, 5, Pause_TryPause_Dedicated);
1058
1059         world_initialized = 1;
1060         __spawnfunc_spawn_all();
1061 }
1062
1063 spawnfunc(light)
1064 {
1065         //makestatic (this); // Who the f___ did that?
1066         delete(this);
1067 }
1068
1069 bool MoveToRandomLocationWithinBounds(entity e, vector boundmin, vector boundmax, float goodcontents, float badcontents, float badsurfaceflags, int attempts, float maxaboveground, float minviewdistance, bool frompos)
1070 {
1071         float m = e.dphitcontentsmask;
1072         e.dphitcontentsmask = goodcontents | badcontents;
1073
1074         vector org = boundmin;
1075         vector delta = boundmax - boundmin;
1076
1077         vector start, end;
1078         start = end = org;
1079         int j; // used after the loop
1080         for(j = 0; j < attempts; ++j)
1081         {
1082                 start.x = org.x + random() * delta.x;
1083                 start.y = org.y + random() * delta.y;
1084                 start.z = org.z + random() * delta.z;
1085
1086                 // rule 1: start inside world bounds, and outside
1087                 // solid, and don't start from somewhere where you can
1088                 // fall down to evil
1089                 tracebox(start, e.mins, e.maxs, start - '0 0 1' * delta.z, MOVE_NORMAL, e);
1090                 if (trace_fraction >= 1)
1091                         continue;
1092                 if (trace_startsolid)
1093                         continue;
1094                 if (trace_dphitcontents & badcontents)
1095                         continue;
1096                 if (trace_dphitq3surfaceflags & badsurfaceflags)
1097                         continue;
1098
1099                 // rule 2: if we are too high, lower the point
1100                 if (trace_fraction * delta.z > maxaboveground)
1101                         start = trace_endpos + '0 0 1' * maxaboveground;
1102                 vector enddown = trace_endpos;
1103
1104                 // rule 3: make sure we aren't outside the map. This only works
1105                 // for somewhat well formed maps. A good rule of thumb is that
1106                 // the map should have a convex outside hull.
1107                 // these can be traceLINES as we already verified the starting box
1108                 vector mstart = start + 0.5 * (e.mins + e.maxs);
1109                 traceline(mstart, mstart + '1 0 0' * delta.x, MOVE_NORMAL, e);
1110                 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1111                         continue;
1112                 traceline(mstart, mstart - '1 0 0' * delta.x, MOVE_NORMAL, e);
1113                 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1114                         continue;
1115                 traceline(mstart, mstart + '0 1 0' * delta.y, MOVE_NORMAL, e);
1116                 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1117                         continue;
1118                 traceline(mstart, mstart - '0 1 0' * delta.y, MOVE_NORMAL, e);
1119                 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1120                         continue;
1121                 traceline(mstart, mstart + '0 0 1' * delta.z, MOVE_NORMAL, e);
1122                 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1123                         continue;
1124
1125                 // rule 4: we must "see" some spawnpoint or item
1126                 entity sp = NULL;
1127                 if(frompos)
1128                 {
1129                         if((traceline(mstart, e.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1130                                 sp = e;
1131                 }
1132                 if(!sp)
1133                 {
1134                         IL_EACH(g_spawnpoints, checkpvs(mstart, it),
1135                         {
1136                                 if((traceline(mstart, it.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1137                                 {
1138                                         sp = it;
1139                                         break;
1140                                 }
1141                         });
1142                 }
1143                 if(!sp)
1144                 {
1145                         int items_checked = 0;
1146                         IL_EACH(g_items, checkpvs(mstart, it),
1147                         {
1148                                 if((traceline(mstart, it.origin + (it.mins + it.maxs) * 0.5, MOVE_NORMAL, e), trace_fraction) >= 1)
1149                                 {
1150                                         sp = it;
1151                                         break;
1152                                 }
1153
1154                                 ++items_checked;
1155                                 if(items_checked >= attempts)
1156                                         break; // sanity
1157                         });
1158
1159                         if(!sp)
1160                                 continue;
1161                 }
1162
1163                 // find a random vector to "look at"
1164                 end.x = org.x + random() * delta.x;
1165                 end.y = org.y + random() * delta.y;
1166                 end.z = org.z + random() * delta.z;
1167                 end = start + normalize(end - start) * vlen(delta);
1168
1169                 // rule 4: start TO end must not be too short
1170                 tracebox(start, e.mins, e.maxs, end, MOVE_NORMAL, e);
1171                 if(trace_startsolid)
1172                         continue;
1173                 if(trace_fraction < minviewdistance / vlen(delta))
1174                         continue;
1175
1176                 // rule 5: don't want to look at sky
1177                 if(trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
1178                         continue;
1179
1180                 // rule 6: we must not end up in trigger_hurt
1181                 if(tracebox_hits_trigger_hurt(start, e.mins, e.maxs, enddown))
1182                         continue;
1183
1184                 break;
1185         }
1186
1187         e.dphitcontentsmask = m;
1188
1189         if(j < attempts)
1190         {
1191                 setorigin(e, start);
1192                 e.angles = vectoangles(end - start);
1193                 LOG_DEBUG("Needed ", ftos(j + 1), " attempts");
1194                 return true;
1195         }
1196         return false;
1197 }
1198
1199 float MoveToRandomMapLocation(entity e, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1200 {
1201         return MoveToRandomLocationWithinBounds(e, world.mins, world.maxs, goodcontents, badcontents, badsurfaceflags, attempts, maxaboveground, minviewdistance, false);
1202 }
1203
1204 /*
1205 ===============================================================================
1206
1207 RULES
1208
1209 ===============================================================================
1210 */
1211
1212 void DumpStats(float final)
1213 {
1214         float file;
1215         string s;
1216         float to_console;
1217         float to_eventlog;
1218         float to_file;
1219         float i;
1220
1221         to_console = autocvar_sv_logscores_console;
1222         to_eventlog = autocvar_sv_eventlog;
1223         to_file = autocvar_sv_logscores_file;
1224
1225         if(!final)
1226         {
1227                 to_console = true; // always print printstats replies
1228                 to_eventlog = false; // but never print them to the event log
1229         }
1230
1231         if(to_eventlog)
1232                 if(autocvar_sv_eventlog_console)
1233                         to_console = false; // otherwise we get the output twice
1234
1235         if(final)
1236                 s = ":scores:";
1237         else
1238                 s = ":status:";
1239         s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1240
1241         if(to_console)
1242                 LOG_HELP(s);
1243         if(to_eventlog)
1244                 GameLogEcho(s);
1245
1246         file = -1;
1247         if(to_file)
1248         {
1249                 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1250                 if(file == -1)
1251                         to_file = false;
1252                 else
1253                         fputs(file, strcat(s, "\n"));
1254         }
1255
1256         s = strcat(":labels:player:", GetPlayerScoreString(NULL, 0));
1257         if(to_console)
1258                 LOG_HELP(s);
1259         if(to_eventlog)
1260                 GameLogEcho(s);
1261         if(to_file)
1262                 fputs(file, strcat(s, "\n"));
1263
1264         FOREACH_CLIENT(IS_REAL_CLIENT(it) || (IS_BOT_CLIENT(it) && autocvar_sv_logscores_bots), {
1265                 s = strcat(":player:see-labels:", GetPlayerScoreString(it, 0), ":");
1266                 s = strcat(s, ftos(rint(time - CS(it).jointime)), ":");
1267                 if(IS_PLAYER(it) || INGAME_JOINED(it))
1268                         s = strcat(s, ftos(it.team), ":");
1269                 else
1270                         s = strcat(s, "spectator:");
1271
1272                 if(to_console)
1273                         LOG_HELP(s, playername(it.netname, it.team, false));
1274                 if(to_eventlog)
1275                         GameLogEcho(strcat(s, ftos(it.playerid), ":", playername(it.netname, it.team, false)));
1276                 if(to_file)
1277                         fputs(file, strcat(s, playername(it.netname, it.team, false), "\n"));
1278         });
1279
1280         if(teamplay)
1281         {
1282                 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1283                 if(to_console)
1284                         LOG_HELP(s);
1285                 if(to_eventlog)
1286                         GameLogEcho(s);
1287                 if(to_file)
1288                         fputs(file, strcat(s, "\n"));
1289
1290                 for(i = 1; i < 16; ++i)
1291                 {
1292                         s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1293                         s = strcat(s, ":", ftos(i));
1294                         if(to_console)
1295                                 LOG_HELP(s);
1296                         if(to_eventlog)
1297                                 GameLogEcho(s);
1298                         if(to_file)
1299                                 fputs(file, strcat(s, "\n"));
1300                 }
1301         }
1302
1303         if(to_console)
1304                 LOG_HELP(":end");
1305         if(to_eventlog)
1306                 GameLogEcho(":end");
1307         if(to_file)
1308         {
1309                 fputs(file, ":end\n");
1310                 fclose(file);
1311         }
1312 }
1313
1314 /*
1315 go to the next level for deathmatch
1316 only called if a time or frag limit has expired
1317 */
1318 void NextLevel()
1319 {
1320         cvar_set("_endmatch", "0");
1321         game_stopped = true;
1322         intermission_running = true; // game over
1323
1324         // enforce a wait time before allowing changelevel
1325         if(player_count > 0)
1326                 intermission_exittime = time + autocvar_sv_mapchange_delay;
1327         else
1328                 intermission_exittime = -1;
1329
1330         /*
1331         WriteByte (MSG_ALL, SVC_CDTRACK);
1332         WriteByte (MSG_ALL, 3);
1333         WriteByte (MSG_ALL, 3);
1334         // done in FixIntermission
1335         */
1336
1337         //pos = FindIntermission ();
1338
1339         VoteReset();
1340
1341         DumpStats(true);
1342
1343         // send statistics
1344         PlayerStats_GameReport(true);
1345         WeaponStats_Shutdown();
1346
1347         Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_Null); // kill all centerprints now
1348
1349         if(autocvar_sv_eventlog)
1350                 GameLogEcho(":gameover");
1351
1352         GameLogClose();
1353
1354         int winner_team = 0;
1355         FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), {
1356                 FixIntermissionClient(it);
1357                 if(it.winning)
1358                 {
1359                         if (teamplay && !winner_team)
1360                         {
1361                                 winner_team = it.team;
1362                                 bprint(Team_ColorCode(winner_team), Team_ColorName_Upper(winner_team), "^7 team wins the match\n");
1363                         }
1364                         bprint(playername(it.netname, it.team, false), " ^7wins\n");
1365                 }
1366         });
1367
1368         target_music_kill();
1369
1370         if(autocvar_g_campaign)
1371                 CampaignPreIntermission();
1372
1373         MUTATOR_CALLHOOK(MatchEnd);
1374
1375         localcmd("\nsv_hook_gameend\n");
1376 }
1377
1378
1379 int InitiateSuddenDeath()
1380 {
1381         // Check first whether normal overtimes could be added before initiating suddendeath mode
1382         // - for this timelimit_overtime needs to be >0 of course
1383         // - also check the winning condition calculated in the previous frame and only add normal overtime
1384         //   again, if at the point at which timelimit would be extended again, still no winner was found
1385         if (!autocvar_g_campaign && checkrules_overtimesadded >= 0
1386                 && (checkrules_overtimesadded < autocvar_timelimit_overtimes || autocvar_timelimit_overtimes < 0)
1387                 && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1388         {
1389                 return 1; // need to call InitiateOvertime later
1390         }
1391         else
1392         {
1393                 if(!checkrules_suddendeathend)
1394                 {
1395                         if(autocvar_g_campaign)
1396                         {
1397                                 checkrules_suddendeathend = time; // no suddendeath in campaign
1398                         }
1399                         else
1400                         {
1401                                 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1402                                 overtimes = -1;
1403                         }
1404                         if(g_race && !g_race_qualifying)
1405                                 race_StartCompleting();
1406                 }
1407                 return 0;
1408         }
1409 }
1410
1411 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1412 {
1413         ++checkrules_overtimesadded;
1414         overtimes = checkrules_overtimesadded;
1415         //add one more overtime by simply extending the timelimit
1416         cvar_set("timelimit", ftos(autocvar_timelimit + autocvar_timelimit_overtime));
1417         Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime * 60);
1418 }
1419
1420 float GetWinningCode(float fraglimitreached, float equality)
1421 {
1422         if(autocvar_g_campaign == 1)
1423         {
1424                 if(fraglimitreached)
1425                         return WINNING_YES;
1426                 else
1427                         return WINNING_NO;
1428         }
1429         else
1430         {
1431                 if(equality)
1432                 {
1433                         if(fraglimitreached)
1434                                 return WINNING_STARTSUDDENDEATHOVERTIME;
1435                         else
1436                                 return WINNING_NEVER;
1437                 }
1438                 else
1439                 {
1440                         if(fraglimitreached)
1441                                 return WINNING_YES;
1442                         else
1443                                 return WINNING_NO;
1444                 }
1445         }
1446 }
1447
1448 // set the .winning flag for exactly those players with a given field value
1449 void SetWinners(.float field, float value)
1450 {
1451         FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), { it.winning = (it.(field) == value); });
1452 }
1453
1454 // set the .winning flag for those players with a given field value
1455 void AddWinners(.float field, float value)
1456 {
1457         FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), {
1458                 if(it.(field) == value)
1459                         it.winning = 1;
1460         });
1461 }
1462
1463 // clear the .winning flags
1464 void ClearWinners()
1465 {
1466         FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), { it.winning = 0; });
1467 }
1468
1469 int fragsleft_last;
1470 float WinningCondition_Scores(float limit, float leadlimit)
1471 {
1472         // TODO make everything use THIS winning condition (except LMS)
1473         WinningConditionHelper(NULL);
1474
1475         if(teamplay)
1476         {
1477                 for (int i = 1; i < 5; ++i)
1478                 {
1479                         Team_SetTeamScore(Team_GetTeamFromIndex(i),
1480                                 TeamScore_GetCompareValue(Team_IndexToTeam(i)));
1481                 }
1482         }
1483
1484         ClearWinners();
1485         if(WinningConditionHelper_winner)
1486                 WinningConditionHelper_winner.winning = 1;
1487         if(WinningConditionHelper_winnerteam >= 0)
1488                 SetWinners(team, WinningConditionHelper_winnerteam);
1489
1490         if(WinningConditionHelper_lowerisbetter)
1491         {
1492                 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1493                 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1494                 limit = -limit;
1495         }
1496
1497         if(WinningConditionHelper_zeroisworst)
1498                 leadlimit = 0; // not supported in this mode
1499
1500         if(MUTATOR_CALLHOOK(Scores_CountFragsRemaining))
1501         {
1502                 float fragsleft;
1503                 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1504                 {
1505                         fragsleft = 1;
1506                 }
1507                 else
1508                 {
1509                         fragsleft = FLOAT_MAX;
1510                         float leadingfragsleft = FLOAT_MAX;
1511                         if (limit)
1512                                 fragsleft = limit - WinningConditionHelper_topscore;
1513                         if (leadlimit)
1514                                 leadingfragsleft = WinningConditionHelper_secondscore + leadlimit - WinningConditionHelper_topscore;
1515
1516                         if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1517                                 fragsleft = max(fragsleft, leadingfragsleft);
1518                         else
1519                                 fragsleft = min(fragsleft, leadingfragsleft);
1520                 }
1521
1522                 if (fragsleft_last != fragsleft) // do not announce same remaining frags multiple times
1523                 {
1524                         if (fragsleft == 1)
1525                                 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_1);
1526                         else if (fragsleft == 2)
1527                                 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_2);
1528                         else if (fragsleft == 3)
1529                                 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_3);
1530
1531                         fragsleft_last = fragsleft;
1532                 }
1533         }
1534
1535         bool fraglimit_reached = (limit && WinningConditionHelper_topscore >= limit);
1536         bool leadlimit_reached = (leadlimit && WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1537
1538         bool limit_reached;
1539         // only respect leadlimit_and_fraglimit when both limits are set or the game will never end
1540         if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1541                 limit_reached = (fraglimit_reached && leadlimit_reached);
1542         else
1543                 limit_reached = (fraglimit_reached || leadlimit_reached);
1544
1545         return GetWinningCode(
1546                 WinningConditionHelper_topscore && limit_reached,
1547                 WinningConditionHelper_equality
1548         );
1549 }
1550
1551 float WinningCondition_RanOutOfSpawns()
1552 {
1553         if(have_team_spawns <= 0)
1554                 return WINNING_NO;
1555
1556         if(!autocvar_g_spawn_useallspawns)
1557                 return WINNING_NO;
1558
1559         if(!some_spawn_has_been_used)
1560                 return WINNING_NO;
1561
1562         for (int i = 1; i < 5; ++i)
1563         {
1564                 Team_SetTeamScore(Team_GetTeamFromIndex(i), 0);
1565         }
1566
1567         FOREACH_CLIENT(IS_PLAYER(it) && !IS_DEAD(it),
1568         {
1569                 if (Team_IsValidTeam(it.team))
1570                 {
1571                         Team_SetTeamScore(Team_GetTeam(it.team), 1);
1572                 }
1573         });
1574
1575         IL_EACH(g_spawnpoints, true,
1576         {
1577                 if (Team_IsValidTeam(it.team))
1578                 {
1579                         Team_SetTeamScore(Team_GetTeam(it.team), 1);
1580                 }
1581         });
1582
1583         ClearWinners();
1584         float team1_score = Team_GetTeamScore(Team_GetTeamFromIndex(1));
1585         float team2_score = Team_GetTeamScore(Team_GetTeamFromIndex(2));
1586         float team3_score = Team_GetTeamScore(Team_GetTeamFromIndex(3));
1587         float team4_score = Team_GetTeamScore(Team_GetTeamFromIndex(4));
1588         if(team1_score + team2_score + team3_score + team4_score == 0)
1589         {
1590                 checkrules_equality = true;
1591                 return WINNING_YES;
1592         }
1593         else if(team1_score + team2_score + team3_score + team4_score == 1)
1594         {
1595                 float t, i;
1596                 if(team1_score)
1597                         t = 1;
1598                 else if(team2_score)
1599                         t = 2;
1600                 else if(team3_score)
1601                         t = 3;
1602                 else // if(team4_score)
1603                         t = 4;
1604                 entity balance = TeamBalance_CheckAllowedTeams(NULL);
1605                 for(i = 0; i < MAX_TEAMSCORE; ++i)
1606                 {
1607                         for (int j = 1; j <= NUM_TEAMS; ++j)
1608                         {
1609                                 if (t == j)
1610                                 {
1611                                         continue;
1612                                 }
1613                                 if (!TeamBalance_IsTeamAllowed(balance, j))
1614                                 {
1615                                         continue;
1616                                 }
1617                                 TeamScore_AddToTeam(Team_IndexToTeam(j), i, -1000);
1618                         }
1619                 }
1620
1621                 AddWinners(team, t);
1622                 return WINNING_YES;
1623         }
1624         else
1625                 return WINNING_NO;
1626 }
1627
1628 /*
1629 ============
1630 CheckRules_World
1631
1632 Exit deathmatch games upon conditions
1633 ============
1634 */
1635 void CheckRules_World()
1636 {
1637         VoteThink();
1638         MapVote_Think();
1639
1640         SetDefaultAlpha();
1641
1642         if (intermission_running) // someone else quit the game already
1643         {
1644                 if(player_count == 0) // Nobody there? Then let's go to the next map
1645                         MapVote_Start();
1646                         // this will actually check the player count in the next frame
1647                         // again, but this shouldn't hurt
1648                 return;
1649         }
1650
1651         float timelimit = autocvar_timelimit * 60;
1652         float fraglimit = autocvar_fraglimit;
1653         float leadlimit = autocvar_leadlimit;
1654         if (leadlimit < 0) leadlimit = 0;
1655
1656         if(warmup_stage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1657         {
1658                 if(timelimit > 0)
1659                         timelimit = 0; // timelimit is not made for warmup
1660                 if(fraglimit > 0)
1661                         fraglimit = 0; // no fraglimit for now
1662                 leadlimit = 0; // no leadlimit for now
1663         }
1664
1665         if (autocvar__endmatch || timelimit < 0)
1666         {
1667                 // endmatch
1668                 NextLevel();
1669                 return;
1670         }
1671
1672         if(timelimit > 0)
1673                 timelimit += game_starttime;
1674
1675         int overtimes_prev = overtimes;
1676         int wantovertime = 0;
1677
1678         if(checkrules_suddendeathend)
1679         {
1680                 if(!checkrules_suddendeathwarning)
1681                 {
1682                         checkrules_suddendeathwarning = true;
1683                         if(g_race && !g_race_qualifying)
1684                                 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_RACE_FINISHLAP);
1685                         else
1686                                 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_FRAG);
1687                 }
1688         }
1689         else
1690         {
1691                 if (timelimit && time >= timelimit)
1692                 {
1693                         if(g_race && (g_race_qualifying == 2) && timelimit > 0)
1694                         {
1695                                 float totalplayers;
1696                                 float playerswithlaps;
1697                                 float readyplayers;
1698                                 totalplayers = playerswithlaps = readyplayers = 0;
1699                                 FOREACH_CLIENT(IS_PLAYER(it), {
1700                                         ++totalplayers;
1701                                         if(GameRules_scoring_add(it, RACE_FASTEST, 0))
1702                                                 ++playerswithlaps;
1703                                         if(it.ready)
1704                                                 ++readyplayers;
1705                                 });
1706
1707                                 // at least 2 of the players have completed a lap: start the RACE
1708                                 // otherwise, the players should end the qualifying on their own
1709                                 if(readyplayers || playerswithlaps >= 2)
1710                                 {
1711                                         checkrules_suddendeathend = 0;
1712                                         ReadyRestart(true); // go to race
1713                                         return;
1714                                 }
1715                                 else
1716                                         wantovertime |= InitiateSuddenDeath();
1717                         }
1718                         else
1719                                 wantovertime |= InitiateSuddenDeath();
1720                 }
1721         }
1722
1723         if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1724         {
1725                 NextLevel();
1726                 return;
1727         }
1728
1729         int checkrules_status = WinningCondition_RanOutOfSpawns();
1730         if(checkrules_status == WINNING_YES)
1731                 bprint("Hey! Someone ran out of spawns!\n");
1732         else if(MUTATOR_CALLHOOK(CheckRules_World, checkrules_status, timelimit, fraglimit))
1733                 checkrules_status = M_ARGV(0, float);
1734         else
1735                 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
1736
1737         if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
1738         {
1739                 checkrules_status = WINNING_NEVER;
1740                 checkrules_overtimesadded = -1;
1741                 wantovertime |= InitiateSuddenDeath();
1742         }
1743
1744         if(checkrules_status == WINNING_NEVER)
1745                 // equality cases! Nobody wins if the overtime ends in a draw.
1746                 ClearWinners();
1747
1748         if(wantovertime)
1749         {
1750                 if(checkrules_status == WINNING_NEVER)
1751                         InitiateOvertime();
1752                 else
1753                         checkrules_status = WINNING_YES;
1754         }
1755
1756         if(checkrules_suddendeathend)
1757                 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
1758                         checkrules_status = WINNING_YES;
1759
1760         if(checkrules_status == WINNING_YES)
1761         {
1762                 if (overtimes == -1 && overtimes != overtimes_prev)
1763                 {
1764                         // if suddendeathend overtime has just begun, revert it
1765                         checkrules_suddendeathend = 0;
1766                         overtimes = overtimes_prev;
1767                 }
1768                 //print("WINNING\n");
1769                 NextLevel();
1770         }
1771 }
1772
1773 float want_weapon(entity weaponinfo, float allguns)
1774 {
1775         int d = 0;
1776         bool allow_mutatorblocked = false;
1777
1778         if(!weaponinfo.m_id)
1779                 return 0;
1780
1781         bool mutator_returnvalue = MUTATOR_CALLHOOK(WantWeapon, weaponinfo, d, allguns, allow_mutatorblocked);
1782         d = M_ARGV(1, float);
1783         allguns = M_ARGV(2, bool);
1784         allow_mutatorblocked = M_ARGV(3, bool);
1785
1786         if(allguns)
1787                 d = boolean((weaponinfo.spawnflags & WEP_FLAG_NORMAL) && !(weaponinfo.spawnflags & (WEP_FLAG_HIDDEN | WEP_FLAG_SPECIALATTACK)));
1788         else if(!mutator_returnvalue)
1789                 d = !(!weaponinfo.weaponstart);
1790
1791         if(!allow_mutatorblocked && (weaponinfo.spawnflags & WEP_FLAG_MUTATORBLOCKED)) // never default mutator blocked guns
1792                 d = 0;
1793
1794         float t = weaponinfo.weaponstartoverride;
1795
1796         //LOG_INFOF("want_weapon: %s - d: %d t: %d\n", weaponinfo.netname, d, t);
1797
1798         // bit order in t:
1799         // 1: want or not
1800         // 2: is default?
1801         // 4: is set by default?
1802         if(t < 0)
1803                 t = 4 | (3 * d);
1804         else
1805                 t |= (2 * d);
1806
1807         return t;
1808 }
1809
1810 /// Weapons the player normally starts with outside weapon arena.
1811 WepSet weapons_start()
1812 {
1813         WepSet ret = '0 0 0';
1814         FOREACH(Weapons, it != WEP_Null, {
1815                 int w = want_weapon(it, false);
1816                 if (w & 1)
1817                         ret |= it.m_wepset;
1818         });
1819         return ret;
1820 }
1821
1822 WepSet weapons_all()
1823 {
1824         WepSet ret = '0 0 0';
1825         FOREACH(Weapons, it != WEP_Null, {
1826                 if (!(it.spawnflags & (WEP_FLAG_MUTATORBLOCKED | WEP_FLAG_SPECIALATTACK)))
1827                         ret |= it.m_wepset;
1828         });
1829         return ret;
1830 }
1831
1832 WepSet weapons_devall()
1833 {
1834         WepSet ret = '0 0 0';
1835         FOREACH(Weapons, it != WEP_Null,
1836         {
1837                 ret |= it.m_wepset;
1838         });
1839         return ret;
1840 }
1841
1842 WepSet weapons_most()
1843 {
1844         WepSet ret = '0 0 0';
1845         FOREACH(Weapons, it != WEP_Null, {
1846                 if ((it.spawnflags & WEP_FLAG_NORMAL) && !(it.spawnflags & (WEP_FLAG_MUTATORBLOCKED | WEP_FLAG_HIDDEN | WEP_FLAG_SPECIALATTACK)))
1847                         ret |= it.m_wepset;
1848         });
1849         return ret;
1850 }
1851
1852 void weaponarena_available_all_update(entity this)
1853 {
1854         if (weaponsInMapAll)
1855         {
1856                 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | (weaponsInMapAll & weapons_all());
1857         }
1858         else
1859         {
1860                 // if no weapons are available on the map, just fall back to all weapons arena
1861                 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_all();
1862         }
1863 }
1864
1865 void weaponarena_available_devall_update(entity this)
1866 {
1867         if (weaponsInMapAll)
1868         {
1869                 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | weaponsInMapAll;
1870         }
1871         else
1872         {
1873                 // if no weapons are available on the map, just fall back to devall weapons arena
1874                 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_devall();
1875         }
1876 }
1877
1878 void weaponarena_available_most_update(entity this)
1879 {
1880         if (weaponsInMapAll)
1881         {
1882                 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | (weaponsInMapAll & weapons_most());
1883         }
1884         else
1885         {
1886                 // if no weapons are available on the map, just fall back to most weapons arena
1887                 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_most();
1888         }
1889 }
1890
1891 void readplayerstartcvars()
1892 {
1893         // initialize starting values for players
1894         start_weapons = '0 0 0';
1895         start_weapons_default = '0 0 0';
1896         start_weapons_defaultmask = '0 0 0';
1897         start_items = 0;
1898         start_ammo_shells = 0;
1899         start_ammo_nails = 0;
1900         start_ammo_rockets = 0;
1901         start_ammo_cells = 0;
1902         start_ammo_plasma = 0;
1903         if (random_start_ammo == NULL)
1904         {
1905                 random_start_ammo = new_pure(random_start_ammo);
1906         }
1907         start_health = cvar("g_balance_health_start");
1908         start_armorvalue = cvar("g_balance_armor_start");
1909
1910         g_weaponarena = 0;
1911         g_weaponarena_weapons = '0 0 0';
1912
1913         string s = cvar_string("g_weaponarena");
1914
1915         MUTATOR_CALLHOOK(SetWeaponArena, s);
1916         s = M_ARGV(0, string);
1917
1918         if (s == "0" || s == "")
1919         {
1920                 // no arena
1921         }
1922         else if (s == "off")
1923         {
1924                 // forcibly turn off weaponarena
1925         }
1926         else if (s == "all" || s == "1")
1927         {
1928                 g_weaponarena = 1;
1929                 g_weaponarena_list = "All Weapons Arena";
1930                 g_weaponarena_weapons = weapons_all();
1931         }
1932         else if (s == "devall")
1933         {
1934                 g_weaponarena = 1;
1935                 g_weaponarena_list = "Dev All Weapons Arena";
1936                 g_weaponarena_weapons = weapons_devall();
1937         }
1938         else if (s == "most")
1939         {
1940                 g_weaponarena = 1;
1941                 g_weaponarena_list = "Most Weapons Arena";
1942                 g_weaponarena_weapons = weapons_most();
1943         }
1944         else if (s == "all_available")
1945         {
1946                 g_weaponarena = 1;
1947                 g_weaponarena_list = "All Available Weapons Arena";
1948
1949                 // this needs to run after weaponsInMapAll is initialized
1950                 InitializeEntity(NULL, weaponarena_available_all_update, INITPRIO_FINDTARGET);
1951         }
1952         else if (s == "devall_available")
1953         {
1954                 g_weaponarena = 1;
1955                 g_weaponarena_list = "Dev All Available Weapons Arena";
1956
1957                 // this needs to run after weaponsInMapAll is initialized
1958                 InitializeEntity(NULL, weaponarena_available_devall_update, INITPRIO_FINDTARGET);
1959         }
1960         else if (s == "most_available")
1961         {
1962                 g_weaponarena = 1;
1963                 g_weaponarena_list = "Most Available Weapons Arena";
1964
1965                 // this needs to run after weaponsInMapAll is initialized
1966                 InitializeEntity(NULL, weaponarena_available_most_update, INITPRIO_FINDTARGET);
1967         }
1968         else if (s == "none")
1969         {
1970                 g_weaponarena = 1;
1971                 g_weaponarena_list = "No Weapons Arena";
1972         }
1973         else
1974         {
1975                 g_weaponarena = 1;
1976                 float t = tokenize_console(s);
1977                 g_weaponarena_list = "";
1978                 for (int j = 0; j < t; ++j)
1979                 {
1980                         s = argv(j);
1981                         Weapon wep = Weapon_from_name(s);
1982                         if(wep != WEP_Null)
1983                         {
1984                                 g_weaponarena_weapons |= (wep.m_wepset);
1985                                 g_weaponarena_list = strcat(g_weaponarena_list, wep.netname, " & ");
1986                         }
1987                 }
1988                 if (g_weaponarena_list != "") // remove trailing " & "
1989                         g_weaponarena_list = substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3);
1990                 else // no valid weapon found
1991                         g_weaponarena_list = "No Weapons Arena";
1992         }
1993
1994         if (g_weaponarena)
1995         {
1996                 g_weapon_stay = 0; // incompatible
1997                 start_weapons = g_weaponarena_weapons;
1998                 start_items |= IT_UNLIMITED_AMMO | IT_UNLIMITED_SUPERWEAPONS;
1999                 g_weaponarena_list = strzone(g_weaponarena_list);
2000         }
2001         else
2002         {
2003                 FOREACH(Weapons, it != WEP_Null, {
2004                         int w = want_weapon(it, false);
2005                         WepSet s = it.m_wepset;
2006                         if(w & 1)
2007                                 start_weapons |= s;
2008                         if(w & 2)
2009                                 start_weapons_default |= s;
2010                         if(w & 4)
2011                                 start_weapons_defaultmask |= s;
2012                 });
2013         }
2014
2015         if(cvar("g_balance_superweapons_time") < 0)
2016                 start_items |= IT_UNLIMITED_SUPERWEAPONS;
2017
2018         if(!cvar("g_use_ammunition"))
2019                 start_items |= IT_UNLIMITED_AMMO;
2020
2021         if(start_items & IT_UNLIMITED_AMMO)
2022         {
2023                 start_ammo_shells = 999;
2024                 start_ammo_nails = 999;
2025                 start_ammo_rockets = 999;
2026                 start_ammo_cells = 999;
2027                 start_ammo_plasma = 999;
2028                 start_ammo_fuel = 999;
2029         }
2030         else
2031         {
2032                 start_ammo_shells = cvar("g_start_ammo_shells");
2033                 start_ammo_nails = cvar("g_start_ammo_nails");
2034                 start_ammo_rockets = cvar("g_start_ammo_rockets");
2035                 start_ammo_cells = cvar("g_start_ammo_cells");
2036                 start_ammo_plasma = cvar("g_start_ammo_plasma");
2037                 start_ammo_fuel = cvar("g_start_ammo_fuel");
2038                 random_start_weapons_count = cvar("g_random_start_weapons_count");
2039                 SetResource(random_start_ammo, RES_SHELLS, cvar("g_random_start_shells"));
2040                 SetResource(random_start_ammo, RES_BULLETS, cvar("g_random_start_bullets"));
2041                 SetResource(random_start_ammo, RES_ROCKETS, cvar("g_random_start_rockets"));
2042                 SetResource(random_start_ammo, RES_CELLS, cvar("g_random_start_cells"));
2043                 SetResource(random_start_ammo, RES_PLASMA, cvar("g_random_start_plasma"));
2044         }
2045
2046         warmup_start_ammo_shells = start_ammo_shells;
2047         warmup_start_ammo_nails = start_ammo_nails;
2048         warmup_start_ammo_rockets = start_ammo_rockets;
2049         warmup_start_ammo_cells = start_ammo_cells;
2050         warmup_start_ammo_plasma = start_ammo_plasma;
2051         warmup_start_ammo_fuel = start_ammo_fuel;
2052         warmup_start_health = start_health;
2053         warmup_start_armorvalue = start_armorvalue;
2054         warmup_start_weapons = start_weapons;
2055         warmup_start_weapons_default = start_weapons_default;
2056         warmup_start_weapons_defaultmask = start_weapons_defaultmask;
2057
2058         if (!g_weaponarena)
2059         {
2060                 warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
2061                 warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
2062                 warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
2063                 warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
2064                 warmup_start_ammo_plasma = cvar("g_warmup_start_ammo_plasma");
2065                 warmup_start_ammo_fuel = cvar("g_warmup_start_ammo_fuel");
2066                 warmup_start_health = cvar("g_warmup_start_health");
2067                 warmup_start_armorvalue = cvar("g_warmup_start_armor");
2068                 warmup_start_weapons = '0 0 0';
2069                 warmup_start_weapons_default = '0 0 0';
2070                 warmup_start_weapons_defaultmask = '0 0 0';
2071                 FOREACH(Weapons, it != WEP_Null, {
2072                         int w = want_weapon(it, autocvar_g_warmup_allguns);
2073                         WepSet s = it.m_wepset;
2074                         if(w & 1)
2075                                 warmup_start_weapons |= s;
2076                         if(w & 2)
2077                                 warmup_start_weapons_default |= s;
2078                         if(w & 4)
2079                                 warmup_start_weapons_defaultmask |= s;
2080                 });
2081         }
2082
2083         if (autocvar_g_jetpack)
2084                 start_items |= ITEM_Jetpack.m_itemid;
2085
2086         MUTATOR_CALLHOOK(SetStartItems);
2087
2088         if (start_items & ITEM_Jetpack.m_itemid)
2089         {
2090                 start_items |= ITEM_JetpackRegen.m_itemid;
2091                 start_ammo_fuel = max(start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
2092                 warmup_start_ammo_fuel = max(warmup_start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
2093         }
2094
2095         start_ammo_shells = max(0, start_ammo_shells);
2096         start_ammo_nails = max(0, start_ammo_nails);
2097         start_ammo_rockets = max(0, start_ammo_rockets);
2098         start_ammo_cells = max(0, start_ammo_cells);
2099         start_ammo_plasma = max(0, start_ammo_plasma);
2100         start_ammo_fuel = max(0, start_ammo_fuel);
2101         SetResource(random_start_ammo, RES_SHELLS, max(0, GetResource(random_start_ammo, RES_SHELLS)));
2102         SetResource(random_start_ammo, RES_BULLETS, max(0, GetResource(random_start_ammo, RES_BULLETS)));
2103         SetResource(random_start_ammo, RES_ROCKETS, max(0, GetResource(random_start_ammo, RES_ROCKETS)));
2104         SetResource(random_start_ammo, RES_CELLS, max(0, GetResource(random_start_ammo, RES_CELLS)));
2105         SetResource(random_start_ammo, RES_PLASMA, max(0, GetResource(random_start_ammo, RES_PLASMA)));
2106
2107         warmup_start_ammo_shells = max(0, warmup_start_ammo_shells);
2108         warmup_start_ammo_nails = max(0, warmup_start_ammo_nails);
2109         warmup_start_ammo_rockets = max(0, warmup_start_ammo_rockets);
2110         warmup_start_ammo_cells = max(0, warmup_start_ammo_cells);
2111         warmup_start_ammo_plasma = max(0, warmup_start_ammo_plasma);
2112         warmup_start_ammo_fuel = max(0, warmup_start_ammo_fuel);
2113 }
2114
2115 void readlevelcvars()
2116 {
2117         serverflags &= ~SERVERFLAG_ALLOW_FULLBRIGHT;
2118         if(cvar("sv_allow_fullbright"))
2119                 serverflags |= SERVERFLAG_ALLOW_FULLBRIGHT;
2120
2121         serverflags &= ~SERVERFLAG_FORBID_PICKUPTIMER;
2122         if(cvar("sv_forbid_pickuptimer"))
2123                 serverflags |= SERVERFLAG_FORBID_PICKUPTIMER;
2124
2125         sv_ready_restart_after_countdown = cvar("sv_ready_restart_after_countdown");
2126
2127         if(cvar("g_campaign"))
2128                 warmup_stage = 0; // no warmup during campaign
2129         else
2130         {
2131                 warmup_stage = autocvar_g_warmup;
2132                 if (warmup_stage < 0 || warmup_stage > 1)
2133                         warmup_limit = -1; // don't start until there's enough players
2134                 else if (warmup_stage == 1)
2135                 {
2136                         // this code is duplicated in ReadyCount()
2137                         warmup_limit = cvar("g_warmup_limit");
2138                         if(warmup_limit == 0)
2139                                 warmup_limit = autocvar_timelimit * 60;
2140                 }
2141         }
2142
2143         g_pickup_respawntime_weapon = cvar("g_pickup_respawntime_weapon");
2144         g_pickup_respawntime_superweapon = cvar("g_pickup_respawntime_superweapon");
2145         g_pickup_respawntime_ammo = cvar("g_pickup_respawntime_ammo");
2146         g_pickup_respawntime_short = cvar("g_pickup_respawntime_short");
2147         g_pickup_respawntime_medium = cvar("g_pickup_respawntime_medium");
2148         g_pickup_respawntime_long = cvar("g_pickup_respawntime_long");
2149         g_pickup_respawntime_powerup = cvar("g_pickup_respawntime_powerup");
2150         g_pickup_respawntimejitter_weapon = cvar("g_pickup_respawntimejitter_weapon");
2151         g_pickup_respawntimejitter_superweapon = cvar("g_pickup_respawntimejitter_superweapon");
2152         g_pickup_respawntimejitter_ammo = cvar("g_pickup_respawntimejitter_ammo");
2153         g_pickup_respawntimejitter_short = cvar("g_pickup_respawntimejitter_short");
2154         g_pickup_respawntimejitter_medium = cvar("g_pickup_respawntimejitter_medium");
2155         g_pickup_respawntimejitter_long = cvar("g_pickup_respawntimejitter_long");
2156         g_pickup_respawntimejitter_powerup = cvar("g_pickup_respawntimejitter_powerup");
2157
2158         g_pickup_shells = cvar("g_pickup_shells");
2159         g_pickup_shells_max = cvar("g_pickup_shells_max");
2160         g_pickup_nails = cvar("g_pickup_nails");
2161         g_pickup_nails_max = cvar("g_pickup_nails_max");
2162         g_pickup_rockets = cvar("g_pickup_rockets");
2163         g_pickup_rockets_max = cvar("g_pickup_rockets_max");
2164         g_pickup_cells = cvar("g_pickup_cells");
2165         g_pickup_cells_max = cvar("g_pickup_cells_max");
2166         g_pickup_plasma = cvar("g_pickup_plasma");
2167         g_pickup_plasma_max = cvar("g_pickup_plasma_max");
2168         g_pickup_fuel = cvar("g_pickup_fuel");
2169         g_pickup_fuel_jetpack = cvar("g_pickup_fuel_jetpack");
2170         g_pickup_fuel_max = cvar("g_pickup_fuel_max");
2171         g_pickup_armorsmall = cvar("g_pickup_armorsmall");
2172         g_pickup_armorsmall_max = cvar("g_pickup_armorsmall_max");
2173         g_pickup_armorsmall_anyway = cvar("g_pickup_armorsmall_anyway");
2174         g_pickup_armormedium = cvar("g_pickup_armormedium");
2175         g_pickup_armormedium_max = cvar("g_pickup_armormedium_max");
2176         g_pickup_armormedium_anyway = cvar("g_pickup_armormedium_anyway");
2177         g_pickup_armorbig = cvar("g_pickup_armorbig");
2178         g_pickup_armorbig_max = cvar("g_pickup_armorbig_max");
2179         g_pickup_armorbig_anyway = cvar("g_pickup_armorbig_anyway");
2180         g_pickup_armormega = cvar("g_pickup_armormega");
2181         g_pickup_armormega_max = cvar("g_pickup_armormega_max");
2182         g_pickup_armormega_anyway = cvar("g_pickup_armormega_anyway");
2183         g_pickup_healthsmall = cvar("g_pickup_healthsmall");
2184         g_pickup_healthsmall_max = cvar("g_pickup_healthsmall_max");
2185         g_pickup_healthsmall_anyway = cvar("g_pickup_healthsmall_anyway");
2186         g_pickup_healthmedium = cvar("g_pickup_healthmedium");
2187         g_pickup_healthmedium_max = cvar("g_pickup_healthmedium_max");
2188         g_pickup_healthmedium_anyway = cvar("g_pickup_healthmedium_anyway");
2189         g_pickup_healthbig = cvar("g_pickup_healthbig");
2190         g_pickup_healthbig_max = cvar("g_pickup_healthbig_max");
2191         g_pickup_healthbig_anyway = cvar("g_pickup_healthbig_anyway");
2192         g_pickup_healthmega = cvar("g_pickup_healthmega");
2193         g_pickup_healthmega_max = cvar("g_pickup_healthmega_max");
2194         g_pickup_healthmega_anyway = cvar("g_pickup_healthmega_anyway");
2195
2196         g_pickup_ammo_anyway = cvar("g_pickup_ammo_anyway");
2197         g_pickup_weapons_anyway = cvar("g_pickup_weapons_anyway");
2198
2199         g_weapon_stay = cvar(strcat("g_", GetGametype(), "_weapon_stay"));
2200         if(!g_weapon_stay)
2201                 g_weapon_stay = cvar("g_weapon_stay");
2202
2203         MUTATOR_CALLHOOK(ReadLevelCvars);
2204
2205         if (!warmup_stage && !autocvar_g_campaign)
2206                 game_starttime = time + cvar("g_start_delay");
2207
2208         FOREACH(Weapons, it != WEP_Null, { it.wr_init(it); });
2209
2210         readplayerstartcvars();
2211 }
2212
2213 void InitializeEntity(entity e, void(entity this) func, int order)
2214 {
2215         entity prev, cur;
2216
2217         if (!e || e.initialize_entity)
2218         {
2219                 // make a proxy initializer entity
2220                 entity e_old = e;
2221                 e = new(initialize_entity);
2222                 e.enemy = e_old;
2223         }
2224
2225         e.initialize_entity = func;
2226         e.initialize_entity_order = order;
2227
2228         cur = initialize_entity_first;
2229         prev = NULL;
2230         for (;;)
2231         {
2232                 if (!cur || cur.initialize_entity_order > order)
2233                 {
2234                         // insert between prev and cur
2235                         if (prev)
2236                                 prev.initialize_entity_next = e;
2237                         else
2238                                 initialize_entity_first = e;
2239                         e.initialize_entity_next = cur;
2240                         return;
2241                 }
2242                 prev = cur;
2243                 cur = cur.initialize_entity_next;
2244         }
2245 }
2246 void InitializeEntitiesRun()
2247 {
2248         entity startoflist = initialize_entity_first;
2249         initialize_entity_first = NULL;
2250         delete_fn = remove_except_protected;
2251         for (entity e = startoflist; e; e = e.initialize_entity_next)
2252         {
2253                 e.remove_except_protected_forbidden = 1;
2254         }
2255         for (entity e = startoflist; e; )
2256         {
2257                 e.remove_except_protected_forbidden = 0;
2258                 e.initialize_entity_order = 0;
2259                 entity next = e.initialize_entity_next;
2260                 e.initialize_entity_next = NULL;
2261                 var void(entity this) func = e.initialize_entity;
2262                 e.initialize_entity = func_null;
2263                 if (e.classname == "initialize_entity")
2264                 {
2265                         entity wrappee = e.enemy;
2266                         builtin_remove(e);
2267                         e = wrappee;
2268                 }
2269                 //dprint("Delayed initialization: ", e.classname, "\n");
2270                 if (func)
2271                 {
2272                         func(e);
2273                 }
2274                 else
2275                 {
2276                         eprint(e);
2277                         backtrace(strcat("Null function in: ", e.classname, "\n"));
2278                 }
2279                 e = next;
2280         }
2281         delete_fn = remove_unsafely;
2282 }
2283
2284 // deferred dropping
2285 // ported from VM_SV_droptofloor TODO: make a common function for the client-side?
2286 void DropToFloor_Handler(entity this)
2287 {
2288         if(!this || wasfreed(this))
2289         {
2290                 // no modifying free entities
2291                 return;
2292         }
2293
2294         vector end = this.origin;
2295         if (autocvar_sv_mapformat_is_quake3)
2296                 end.z -= 4096;
2297         else if (autocvar_sv_mapformat_is_quake2)
2298                 end.z -= 128;
2299         else
2300                 end.z -= 256; // Quake, QuakeWorld
2301
2302         // NOTE: SV_NudgeOutOfSolid is used in the engine here
2303         if(autocvar_sv_gameplayfix_droptofloorstartsolid_nudgetocorrect)
2304         {
2305                 _Movetype_UnstickEntity(this);
2306                 move_out_of_solid(this);
2307         }
2308
2309         tracebox(this.origin, this.mins, this.maxs, end, MOVE_NORMAL, this);
2310
2311         if(trace_startsolid && autocvar_sv_gameplayfix_droptofloorstartsolid)
2312         {
2313                 vector offset, org;
2314                 offset = 0.5 * (this.mins + this.maxs);
2315                 offset.z = this.mins.z;
2316                 org = this.origin + offset;
2317                 traceline(org, end, MOVE_NORMAL, this);
2318                 trace_endpos = trace_endpos - offset;
2319                 if(trace_startsolid)
2320                 {
2321                         LOG_DEBUGF("DropToFloor_Handler: %v could not fix badly placed entity", this.origin);
2322                         _Movetype_LinkEdict(this, false);
2323                         SET_ONGROUND(this);
2324                         this.groundentity = NULL;
2325                 }
2326                 else if(trace_fraction < 1)
2327                 {
2328                         LOG_DEBUGF("DropToFloor_Handler: %v fixed badly placed entity", this.origin);
2329                         setorigin(this, trace_endpos);
2330                         if(autocvar_sv_gameplayfix_droptofloorstartsolid_nudgetocorrect)
2331                         {
2332                                 _Movetype_UnstickEntity(this);
2333                                 move_out_of_solid(this);
2334                         }
2335                         SET_ONGROUND(this);
2336                         this.groundentity = trace_ent;
2337                         // if support is destroyed, keep suspended (gross hack for floating items in various maps)
2338                         this.move_suspendedinair = true;
2339                 }
2340         }
2341         else
2342         {
2343                 if(!trace_allsolid && trace_fraction < 1)
2344                 {
2345                         setorigin(this, trace_endpos);
2346                         SET_ONGROUND(this);
2347                         this.groundentity = trace_ent;
2348                         // if support is destroyed, keep suspended (gross hack for floating items in various maps)
2349                         this.move_suspendedinair = true;
2350                 }
2351                 else
2352                 {
2353                         // if we can't get the entity out of solid, mark it as on ground so physics doesn't attempt to drop it
2354                         // hacky workaround for #2774
2355                         SET_ONGROUND(this);
2356                 }
2357         }
2358         this.dropped_origin = this.origin;
2359 }
2360
2361 void droptofloor(entity this)
2362 {
2363         InitializeEntity(this, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
2364 }
2365
2366 bool autocvar_sv_gameplayfix_multiplethinksperframe = true;
2367 void RunThink(entity this, float dt)
2368 {
2369         // don't let things stay in the past.
2370         // it is possible to start that way by a trigger with a local time.
2371         if(this.nextthink <= 0 || this.nextthink > time + dt)
2372                 return;
2373
2374         float oldtime = time; // do we need to save this?
2375
2376         for (int iterations = 0; iterations < 128 && !wasfreed(this); iterations++)
2377         {
2378                 time = max(oldtime, this.nextthink);
2379                 this.nextthink = 0;
2380
2381                 if(getthink(this))
2382                         getthink(this)(this);
2383                 // mods often set nextthink to time to cause a think every frame,
2384                 // we don't want to loop in that case, so exit if the new nextthink is
2385                 // <= the time the qc was told, also exit if it is past the end of the
2386                 // frame
2387                 if(this.nextthink <= time || this.nextthink > oldtime + dt || !autocvar_sv_gameplayfix_multiplethinksperframe)
2388                         break;
2389         }
2390
2391         time = oldtime;
2392 }
2393
2394 bool autocvar_sv_freezenonclients;
2395 void Physics_Frame()
2396 {
2397         if(autocvar_sv_freezenonclients)
2398                 return;
2399
2400         IL_EACH(g_moveables, true,
2401         {
2402                 if(IS_CLIENT(it) || it.move_movetype == MOVETYPE_PHYSICS)
2403                         continue;
2404
2405                 //set_movetype(it, it.move_movetype);
2406                 // inline the set_movetype function, since this is called a lot
2407                 it.movetype = (it.move_qcphysics) ? MOVETYPE_QCENTITY : it.move_movetype;
2408
2409                 if(it.move_qcphysics && it.move_movetype != MOVETYPE_NONE)
2410                         Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2411
2412                 if(it.movetype >= MOVETYPE_USER_FIRST && it.movetype <= MOVETYPE_USER_LAST) // these cases have no think handling
2413                 {
2414                         if(it.move_movetype == MOVETYPE_PUSH || it.move_movetype == MOVETYPE_FAKEPUSH)
2415                                 continue; // these movetypes have no regular think function
2416                         // handle thinking here
2417                         if (getthink(it) && it.nextthink > 0 && it.nextthink <= time + PHYS_INPUT_TIMELENGTH)
2418                                 RunThink(it, PHYS_INPUT_TIMELENGTH);
2419                 }
2420         });
2421
2422         if(autocvar_sv_gameplayfix_delayprojectiles >= 0)
2423                 return;
2424
2425         // make a second pass to see if any ents spawned this frame and make
2426         // sure they run their move/think. this is verified by checking .move_time, which will never be 0 if the entity has moved
2427         // MOVETYPE_NONE is also checked as .move_time WILL be 0 with that movetype
2428         IL_EACH(g_moveables, it.move_qcphysics,
2429         {
2430                 if(IS_CLIENT(it) || it.move_time || it.move_movetype == MOVETYPE_NONE || it.move_movetype == MOVETYPE_PHYSICS)
2431                         continue;
2432                 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2433         });
2434 }
2435
2436 void systems_update();
2437 void EndFrame()
2438 {
2439         anticheat_endframe();
2440
2441         Physics_Frame();
2442
2443         FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2444                 entity e = IS_SPEC(it) ? it.enemy : it;
2445                 if (e.typehitsound) {
2446                         STAT(TYPEHIT_TIME, it) = time;
2447                 } else if (e.killsound) {
2448                         STAT(KILL_TIME, it) = time;
2449                 } else if (e.hitsound_damage_dealt) {
2450                         STAT(HIT_TIME, it) = time;
2451                         // NOTE: this is not accurate as client code doesn't need so much accuracy for its purposes
2452                         STAT(HITSOUND_DAMAGE_DEALT_TOTAL, it) += ceil(e.hitsound_damage_dealt);
2453                 }
2454         });
2455         // add 1 frametime because after this, engine SV_Physics
2456         // increases time by a frametime and then networks the frame
2457         // add another frametime because client shows everything with
2458         // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2459         // needed!
2460         float altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2461         FOREACH_CLIENT(true, {
2462                 it.typehitsound = false;
2463                 it.hitsound_damage_dealt = 0;
2464                 it.killsound = false;
2465                 antilag_record(it, CS(it), altime);
2466         });
2467         IL_EACH(g_monsters, true,
2468         {
2469                 antilag_record(it, it, altime);
2470         });
2471         IL_EACH(g_projectiles, it.classname == "nade",
2472         {
2473                 antilag_record(it, it, altime);
2474         });
2475         systems_update();
2476         IL_ENDFRAME();
2477 }
2478
2479
2480 /*
2481  * RedirectionThink:
2482  * returns true if redirecting
2483  */
2484 float redirection_timeout;
2485 float redirection_nextthink;
2486 float RedirectionThink()
2487 {
2488         float clients_found;
2489
2490         if(redirection_target == "")
2491                 return false;
2492
2493         if(!redirection_timeout)
2494         {
2495                 cvar_set("sv_public", "-2");
2496                 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2497                 if(redirection_target == "self")
2498                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2499                 else
2500                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2501         }
2502
2503         if(time < redirection_nextthink)
2504                 return true;
2505
2506         redirection_nextthink = time + 1;
2507
2508         clients_found = 0;
2509         FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2510                 // TODO add timer
2511                 LOG_INFO("Redirecting: sending connect command to ", it.netname);
2512                 if(redirection_target == "self")
2513                         stuffcmd(it, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2514                 else
2515                         stuffcmd(it, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2516                 ++clients_found;
2517         });
2518
2519         LOG_INFO("Redirecting: ", ftos(clients_found), " clients left.");
2520
2521         if(time > redirection_timeout || clients_found == 0)
2522                 localcmd("\nwait; wait; wait; quit\n");
2523
2524         return true;
2525 }
2526
2527 void RestoreGame()
2528 {
2529         // Loaded from a save game
2530         // some things then break, so let's work around them...
2531
2532         // Progs DB (capture records)
2533         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2534
2535         // Mapinfo
2536         MapInfo_Shutdown();
2537         MapInfo_Enumerate();
2538         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2539         WeaponStats_Init();
2540
2541         TargetMusic_RestoreGame();
2542 }
2543
2544 void Shutdown()
2545 {
2546         game_stopped = 2;
2547
2548         if(world_initialized > 0)
2549         {
2550                 world_initialized = 0;
2551
2552                 // if a timeout is active, reset the slowmo value to normal
2553                 if(timeout_status == TIMEOUT_ACTIVE)
2554                         cvar_set("slowmo", ftos(orig_slowmo));
2555
2556                 LOG_TRACE("Saving persistent data...");
2557                 Ban_SaveBans();
2558
2559                 // playerstats with unfinished match
2560                 PlayerStats_GameReport(false);
2561
2562                 if(!cheatcount_total)
2563                 {
2564                         if(autocvar_sv_db_saveasdump)
2565                                 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2566                         else
2567                                 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2568                 }
2569                 if(autocvar_developer > 0)
2570                 {
2571                         if(autocvar_sv_db_saveasdump)
2572                                 db_dump(TemporaryDB, "server-temp.db");
2573                         else
2574                                 db_save(TemporaryDB, "server-temp.db");
2575                 }
2576                 CheatShutdown(); // must be after cheatcount check
2577                 db_close(ServerProgsDB);
2578                 db_close(TemporaryDB);
2579                 LOG_TRACE("Saving persistent data... done!");
2580                 // tell the bot system the game is ending now
2581                 bot_endgame();
2582
2583                 WeaponStats_Shutdown();
2584                 MapInfo_Shutdown();
2585
2586                 strfree(sv_termsofservice_url_escaped);
2587         }
2588         else if(world_initialized == 0)
2589         {
2590                 LOG_INFO("NOTE: crashed before even initializing the world, not saving persistent data");
2591         }
2592         else
2593         {
2594                 __init_dedicated_server_shutdown();
2595         }
2596 }