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