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