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