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