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