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