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