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