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