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