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