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