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