3 #include "anticheat.qh"
9 #include "command/common.qh"
10 #include "command/getreplies.qh"
11 #include "command/sv_cmd.qh"
12 #include "command/vote.qh"
14 #include <server/gamelog.qh>
15 #include <server/damage.qh>
17 #include "mapvoting.qh"
18 #include <server/mutators/_mod.qh>
21 #include "scores_rules.qh"
22 #include "spawnpoints.qh"
23 #include "teamplay.qh"
24 #include "weapons/weaponstats.qh"
25 #include <server/weapons/common.qh>
26 #include "../common/constants.qh"
27 #include <common/net_linked.qh>
28 #include "../common/deathtypes/all.qh"
29 #include <common/gamemodes/_mod.qh>
30 #include "../common/gamemodes/sv_rules.qh"
31 #include "../common/mapinfo.qh"
32 #include "../common/monsters/_mod.qh"
33 #include "../common/monsters/sv_monsters.qh"
34 #include "../common/vehicles/all.qh"
35 #include "../common/notifications/all.qh"
36 #include "../common/physics/player.qh"
37 #include "../common/playerstats.qh"
38 #include "../common/stats.qh"
39 #include "../common/teams.qh"
40 #include <common/mapobjects/triggers.qh>
41 #include "../common/mapobjects/trigger/secret.qh"
42 #include "../common/mapobjects/target/music.qh"
43 #include "../common/util.qh"
44 #include "../common/items/_mod.qh"
45 #include <common/weapons/_all.qh>
46 #include "../common/state.qh"
48 const float LATENCY_THINKRATE = 10;
53 void PingPLReport_Think(entity this)
58 delta = 3 / maxclients;
59 if(delta < sys_frametime)
61 this.nextthink = time + delta;
63 e = edict_num(this.cnt + 1);
64 if(IS_CLIENT(e) && IS_REAL_CLIENT(e))
66 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
67 WriteByte(MSG_BROADCAST, this.cnt);
68 WriteShort(MSG_BROADCAST, bound(1, CS(e).ping, 65535));
69 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_packetloss * 255), 255));
70 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_movementloss * 255), 255));
72 // record latency times for clients throughout the match so we can report it to playerstats
73 if(time > (CS(e).latency_time + LATENCY_THINKRATE))
75 CS(e).latency_sum += CS(e).ping;
76 CS(e).latency_cnt += 1;
77 CS(e).latency_time = time;
78 //print("sum: ", ftos(CS(e).latency_sum), ", cnt: ", ftos(CS(e).latency_cnt), ", avg: ", ftos(CS(e).latency_sum / CS(e).latency_cnt), ".\n");
83 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
84 WriteByte(MSG_BROADCAST, this.cnt);
85 WriteShort(MSG_BROADCAST, 0);
86 WriteByte(MSG_BROADCAST, 0);
87 WriteByte(MSG_BROADCAST, 0);
89 this.cnt = (this.cnt + 1) % maxclients;
91 void PingPLReport_Spawn()
93 pingplreport = new_pure(pingplreport);
94 setthink(pingplreport, PingPLReport_Think);
95 pingplreport.nextthink = time;
98 const float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
99 string redirection_target;
100 float world_initialized;
102 void SetDefaultAlpha()
104 if (!MUTATOR_CALLHOOK(SetDefaultAlpha))
106 default_player_alpha = autocvar_g_player_alpha;
107 if(default_player_alpha == 0)
108 default_player_alpha = 1;
109 default_weapon_alpha = default_player_alpha;
113 void GotoFirstMap(entity this)
116 if(autocvar__sv_init)
118 // cvar_set("_sv_init", "0");
119 // we do NOT set this to 0 any more, so someone "accidentally" changing
120 // to this "init" map on a dedicated server will cause no permanent
122 if(autocvar_g_maplist_shuffle)
124 n = tokenizebyseparator(autocvar_g_maplist, " ");
125 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
128 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
130 if(!DoNextMapOverride(1))
138 this.nextthink = time;
142 this.nextthink = time + 1;
143 LOG_INFO("Waiting for _sv_init being set to 1 by initialization scripts...");
147 void cvar_changes_init()
151 float n, i, adding, pureadding;
153 strfree(cvar_changes);
154 strfree(cvar_purechanges);
155 cvar_purechanges_count = 0;
158 buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
164 for(i = 0; i < n; ++i)
166 k = bufstr_get(h, i);
168 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
169 #define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
170 #define BADCVAR(p) if(k == p) continue
172 // general excludes and namespaces for server admin used cvars
173 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
177 BADPREFIX("cvar_check_");
179 BADCVAR("g_configversion");
180 BADCVAR("halflifebsp");
181 BADCVAR("sv_mapformat_is_quake2");
182 BADCVAR("sv_mapformat_is_quake3");
183 BADPREFIX("sv_world");
189 BADPREFIX("scoreboard_");
190 BADPREFIX("g_campaign");
191 BADPREFIX("g_waypointsprite_");
197 BADPREFIX("net_slist_");
203 BADPREFIX("sensitivity");
204 BADPREFIX("userbind");
207 BADPREFIX("crosshair");
208 BADCVAR("mod_q3bsp_lightmapmergepower");
209 BADCVAR("mod_q3bsp_nolightmaps");
211 BADCVAR("mastervolume");
213 BADCVAR("bgmvolume");
214 BADCVAR("in_pitch_min");
215 BADCVAR("in_pitch_max");
218 BADCVAR("developer");
219 BADCVAR("log_dest_udp");
220 BADCVAR("net_address");
221 BADCVAR("net_address_ipv6");
223 BADCVAR("savedgamecfg");
224 BADCVAR("serverconfig");
225 BADCVAR("sv_autoscreenshot");
226 BADCVAR("sv_heartbeatperiod");
227 BADCVAR("sv_vote_master_password");
228 BADCVAR("sys_colortranslation");
229 BADCVAR("sys_specialcharactertranslation");
230 BADCVAR("timeformat");
231 BADCVAR("timestamps");
232 BADCVAR("g_require_stats");
233 BADPREFIX("developer_");
235 BADPREFIX("g_banned_list");
236 BADPREFIX("g_require_stats_");
237 BADPREFIX("g_chat_flood_");
238 BADPREFIX("g_ghost_items");
239 BADPREFIX("g_playerstats_");
240 BADPREFIX("g_voice_flood_");
241 BADPREFIX("log_file");
244 BADPREFIX("sv_allowdownloads");
245 BADPREFIX("sv_autodemo");
246 BADPREFIX("sv_curl_");
247 BADPREFIX("sv_eventlog");
248 BADPREFIX("sv_logscores_");
249 BADPREFIX("sv_master");
250 BADPREFIX("sv_weaponstats_");
251 BADPREFIX("sv_waypointsprite_");
252 BADCVAR("rescan_pending");
254 // these can contain player IDs, so better hide
255 BADPREFIX("g_forced_team_");
256 BADCVAR("sv_muteban_list");
257 BADCVAR("sv_voteban_list");
258 BADCVAR("sv_allow_customplayermodels_idlist");
259 BADCVAR("sv_allow_customplayermodels_speciallist");
262 BADCVAR("fraglimit");
264 BADCVAR("g_assault");
266 BADCVAR("g_ca_teams");
267 BADCVAR("g_conquest");
268 BADCVAR("g_conquest_teams");
273 BADCVAR("g_domination");
274 BADCVAR("g_domination_default_teams");
276 BADCVAR("g_duel_not_dm_maps");
277 BADCVAR("g_freezetag");
278 BADCVAR("g_freezetag_teams");
279 BADCVAR("g_invasion_teams");
280 BADCVAR("g_invasion_type");
281 BADCVAR("g_jailbreak");
282 BADCVAR("g_jailbreak_teams");
283 BADCVAR("g_keepaway");
284 BADCVAR("g_keyhunt");
285 BADCVAR("g_keyhunt_teams");
287 BADCVAR("g_nexball");
288 BADCVAR("g_onslaught");
290 BADCVAR("g_race_laps_limit");
291 BADCVAR("g_race_qualifying_timelimit");
292 BADCVAR("g_race_qualifying_timelimit_override");
293 BADCVAR("g_runematch");
294 BADCVAR("g_shootfromeye");
296 BADCVAR("g_survival");
297 BADCVAR("g_survival_not_dm_maps");
299 BADCVAR("g_tdm_on_dm_maps");
300 BADCVAR("g_tdm_teams");
302 BADCVAR("leadlimit");
305 BADCVAR("timelimit");
306 BADCVAR("g_mapinfo_settemp_acl");
307 BADCVAR("g_mapinfo_ignore_warnings");
308 BADCVAR("g_maplist_ignore_sizes");
309 BADCVAR("g_maplist_sizes_count_bots");
313 BADCVAR("g_maplist");
314 BADCVAR("g_maplist_mostrecent");
318 d = cvar_defstring(k);
324 cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
325 if(strlen(cvar_changes) > 16384)
327 cvar_changes = "// too many settings have been changed to show them here\n";
332 // now check if the changes are actually gameplay relevant
334 // does nothing gameplay relevant
335 BADCVAR("captureleadlimit_override");
336 BADCVAR("condump_stripcolors");
337 BADCVAR("gameversion");
338 BADCVAR("fs_gamedir");
339 BADCVAR("g_allow_oldvortexbeam");
340 BADCVAR("g_balance_kill_delay");
341 BADCVAR("g_buffs_pickup_anyway");
342 BADCVAR("g_buffs_randomize");
343 BADCVAR("g_buffs_randomize_teamplay");
344 BADCVAR("g_campcheck_distance");
345 BADCVAR("g_chatsounds");
346 BADCVAR("g_ca_point_leadlimit");
347 BADCVAR("g_ca_point_limit");
348 BADCVAR("g_ctf_captimerecord_always");
349 BADCVAR("g_ctf_flag_glowtrails");
350 BADCVAR("g_ctf_dynamiclights");
351 BADCVAR("g_ctf_flag_pickup_verbosename");
352 BADPRESUFFIX("g_ctf_flag_", "_model");
353 BADPRESUFFIX("g_ctf_flag_", "_skin");
354 BADCVAR("g_domination_point_leadlimit");
355 BADCVAR("g_forced_respawn");
356 BADCVAR("g_freezetag_point_leadlimit");
357 BADCVAR("g_freezetag_point_limit");
358 BADCVAR("g_glowtrails");
360 BADCVAR("g_casings");
361 BADCVAR("g_invasion_point_limit");
362 BADCVAR("g_jump_grunt");
363 BADCVAR("g_keepaway_ballcarrier_effects");
364 BADCVAR("g_keepawayball_effects");
365 BADCVAR("g_keyhunt_point_leadlimit");
366 BADCVAR("g_nexball_goalleadlimit");
367 BADCVAR("g_new_toys_autoreplace");
368 BADCVAR("g_new_toys_use_pickupsound");
369 BADCVAR("g_physics_predictall");
370 BADCVAR("g_piggyback");
371 BADCVAR("g_playerclip_collisions");
372 BADCVAR("g_spawn_alloweffects");
373 BADCVAR("g_tdm_point_leadlimit");
374 BADCVAR("g_tdm_point_limit");
375 BADCVAR("leadlimit_and_fraglimit");
376 BADCVAR("leadlimit_override");
378 BADCVAR("sv_announcer");
379 BADCVAR("sv_checkforpacketsduringsleep");
380 BADCVAR("sv_damagetext");
381 BADCVAR("sv_db_saveasdump");
382 BADCVAR("sv_intermission_cdtrack");
383 BADCVAR("sv_mapchange_delay");
384 BADCVAR("sv_minigames");
385 BADCVAR("sv_namechangetimer");
386 BADCVAR("sv_precacheplayermodels");
388 BADCVAR("sv_stepheight");
389 BADCVAR("sv_timeout");
390 BADCVAR("sv_weapons_modeloverride");
391 BADCVAR("w_prop_interval");
393 BADPREFIX("crypto_");
394 BADPREFIX("gameversion_");
395 BADPREFIX("g_chat_");
396 BADPREFIX("g_ctf_captimerecord_");
397 BADPREFIX("g_hats_");
398 BADPREFIX("g_maplist_");
400 BADPREFIX("g_respawn_");
402 BADPREFIX("notification_");
405 BADPREFIX("sv_allow_");
406 BADPREFIX("sv_cullentities_");
407 BADPREFIX("sv_maxidle_");
408 BADPREFIX("sv_minigames_");
409 BADPREFIX("sv_radio_");
410 BADPREFIX("sv_timeout_");
411 BADPREFIX("sv_vote_");
412 BADPREFIX("timelimit_");
414 // allowed changes to server admins (please sync this to server.cfg)
418 // :%s,//\([^ ]*\).*,BADCVAR("\1");,
420 // yes, this does contain some redundant stuff, don't really care
421 BADPREFIX("bot_ai_");
422 BADCVAR("bot_config_file");
423 BADCVAR("bot_number");
424 BADCVAR("bot_prefix");
425 BADCVAR("bot_suffix");
426 BADCVAR("capturelimit_override");
427 BADCVAR("fraglimit_override");
429 BADCVAR("g_antilag");
430 BADCVAR("g_balance_teams");
431 BADCVAR("g_balance_teams_prevent_imbalance");
432 BADCVAR("g_balance_teams_scorefactor");
433 BADCVAR("g_ban_sync_trusted_servers");
434 BADCVAR("g_ban_sync_uri");
436 BADCVAR("g_ca_teams_override");
437 BADCVAR("g_ctf_fullbrightflags");
438 BADCVAR("g_ctf_ignore_frags");
439 BADCVAR("g_ctf_leaderboard");
440 BADCVAR("g_domination_point_limit");
441 BADCVAR("g_domination_teams_override");
442 BADCVAR("g_freezetag_teams_override");
443 BADCVAR("g_friendlyfire");
444 BADCVAR("g_fullbrightitems");
445 BADCVAR("g_fullbrightplayers");
446 BADCVAR("g_keyhunt_point_limit");
447 BADCVAR("g_keyhunt_teams_override");
448 BADCVAR("g_lms_lives_override");
449 BADCVAR("g_maplist");
450 BADCVAR("g_maxplayers");
451 BADCVAR("g_mirrordamage");
452 BADCVAR("g_nexball_goallimit");
453 BADCVAR("g_norecoil");
454 BADCVAR("g_physics_clientselect");
456 BADCVAR("g_powerups");
457 BADCVAR("g_player_brightness");
458 BADCVAR("g_rocket_flying");
459 BADCVAR("g_rocket_flying_disabledelays");
460 BADCVAR("g_spawnshieldtime");
461 BADCVAR("g_start_delay");
462 BADCVAR("g_superspectate");
463 BADCVAR("g_tdm_teams_override");
465 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
468 BADCVAR("maxplayers");
469 BADCVAR("minplayers");
470 BADCVAR("minplayers_per_team");
471 BADCVAR("net_address");
473 BADCVAR("rcon_password");
474 BADCVAR("rcon_restricted_commands");
475 BADCVAR("rcon_restricted_password");
477 BADCVAR("sv_adminnick");
478 BADCVAR("sv_autoscreenshot");
479 BADCVAR("sv_autotaunt");
480 BADCVAR("sv_curl_defaulturl");
481 BADCVAR("sv_defaultcharacter");
482 BADCVAR("sv_defaultcharacterskin");
483 BADCVAR("sv_defaultplayercolors");
484 BADCVAR("sv_defaultplayermodel");
485 BADCVAR("sv_defaultplayerskin");
486 BADCVAR("sv_maxidle");
487 BADCVAR("sv_maxrate");
489 BADCVAR("sv_public");
490 BADCVAR("sv_ready_restart");
491 BADCVAR("sv_status_privacy");
493 BADCVAR("sv_vote_call");
494 BADCVAR("sv_vote_commands");
495 BADCVAR("sv_vote_majority_factor");
496 BADCVAR("sv_vote_master");
497 BADCVAR("sv_vote_master_commands");
498 BADCVAR("sv_vote_master_password");
499 BADCVAR("sv_vote_simple_majority_factor");
500 BADCVAR("teamplay_mode");
501 BADCVAR("timelimit_override");
502 BADPREFIX("g_warmup_");
503 BADPREFIX("sv_info_");
504 BADPREFIX("sv_ready_restart_");
506 // mutators that announce themselves properly to the server browser
507 BADCVAR("g_instagib");
508 BADCVAR("g_new_toys");
510 BADCVAR("g_grappling_hook");
511 BADCVAR("g_jetpack");
513 // temporary for testing
514 // TODO remove before 0.8.3 release
515 BADCVAR("g_ca_weaponarena");
516 BADCVAR("g_freezetag_weaponarena");
517 BADCVAR("g_lms_weaponarena");
518 BADCVAR("g_ctf_stalemate_time");
520 if(cvar_string("g_mod_balance") == "Testing")
522 // (temporary) while using the Testing balance, any weapon balance cvars are allowed to be changed
523 BADPREFIX("g_balance_");
532 cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
533 if(strlen(cvar_purechanges) > 16384)
535 cvar_purechanges = "// too many settings have been changed to show them here\n";
539 ++cvar_purechanges_count;
540 // WARNING: this variable is used for the server list
541 // NEVER dare to skip this code!
542 // Hacks to intentionally appearing as "pure server" even though you DO have
543 // modified settings may be punished by removal from the server list.
544 // You can do to the variables cvar_changes and cvar_purechanges all you want,
548 if(cvar_changes == "")
549 cvar_changes = "// this server runs at default server settings\n";
551 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
552 cvar_changes = strzone(cvar_changes);
553 if(cvar_purechanges == "")
554 cvar_purechanges = "// this server runs at default gameplay settings\n";
556 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
557 cvar_purechanges = strzone(cvar_purechanges);
561 bool RandomSeed_Send(entity this, entity to, int sf)
563 WriteHeader(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
564 WriteShort(MSG_ENTITY, this.cnt);
567 void RandomSeed_Think(entity this)
569 this.cnt = bound(0, floor(random() * 65536), 65535);
570 this.nextthink = time + 5;
574 void RandomSeed_Spawn()
576 randomseed = new_pure(randomseed);
577 setthink(randomseed, RandomSeed_Think);
578 Net_LinkEntity(randomseed, false, 0, RandomSeed_Send);
580 getthink(randomseed)(randomseed); // sets random seed and nextthink
583 spawnfunc(__init_dedicated_server)
585 // handler for _init/_init map (only for dedicated server initialization)
587 world_initialized = -1; // don't complain
589 delete_fn = remove_unsafely;
592 setthink(e, GotoFirstMap);
593 e.nextthink = time; // this is usually 1 at this point
595 e = new(info_player_deathmatch); // safeguard against player joining
597 // assign reflectively to avoid "assignment to world" warning
598 for (int i = 0, n = numentityfields(); i < n; ++i) {
599 string k = entityfieldname(i);
600 if (k == "classname") {
601 // safeguard against various stuff ;)
602 putentityfieldstring(i, this, "worldspawn");
607 // needs to be done so early because of the constants they create
610 static_init_precache();
612 IL_PUSH(g_spawnpoints, e); // just incase
615 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
618 void __init_dedicated_server_shutdown() {
622 STATIC_INIT_EARLY(maxclients)
625 for (entity head = nextent(NULL); head; head = nextent(head)) {
630 void default_delayedinit(entity this)
632 if(!scores_initialized)
633 ScoreRules_generic();
636 void InitGameplayMode()
640 // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
642 // assign reflectively to avoid "assignment to world" warning
643 int done = 0; for (int i = 0, n = numentityfields(); i < n; ++i) {
644 string k = entityfieldname(i); vector v = (k == "mins") ? mi_min : (k == "maxs") ? mi_max : '0 0 0';
646 putentityfieldstring(i, world, sprintf("%v", v));
647 if (++done == 2) break;
650 // currently, NetRadiant's limit is 131072 qu for each side
651 // distance from one corner of a 131072qu cube to the opposite corner is approx. 227023 qu
652 // set the distance according to map size but don't go over the limit to avoid issues with float precision
653 // in case somebody makes extremely large maps
654 max_shot_distance = min(230000, vlen(world.maxs - world.mins));
656 MapInfo_LoadMapSettings(mapname);
657 GameRules_teams(false);
659 if (!cvar_value_issafe(world.fog))
661 LOG_INFO("The current map contains a potentially harmful fog setting, ignored");
662 world.fog = string_null;
664 if(MapInfo_Map_fog != "")
666 if(MapInfo_Map_fog == "none")
667 world.fog = string_null;
669 world.fog = strzone(MapInfo_Map_fog);
671 clientstuff = strzone(MapInfo_Map_clientstuff);
673 MapInfo_ClearTemps();
675 gamemode_name = MapInfo_Type_ToText(MapInfo_LoadedGametype);
677 cache_mutatormsg = strzone("");
678 cache_lastmutatormsg = strzone("");
680 InitializeEntity(NULL, default_delayedinit, INITPRIO_GAMETYPE_FALLBACK);
683 void Map_MarkAsRecent(string m);
684 float world_already_spawned;
685 spawnfunc(worldspawn)
687 server_is_dedicated = boolean(stof(cvar_defstring("is_dedicated")));
689 bool wantrestart = false;
691 if (!server_is_dedicated)
693 // force unloading of server pk3 files when starting a listen server
694 // localcmd("\nfs_rescan\n"); // FIXME: does more harm than good, has unintended side effects. What we really want is to unload temporary pk3s only
695 // restore csqc_progname too
696 string expect = "csprogs.dat";
697 wantrestart = cvar_string("csqc_progname") != expect;
698 cvar_set("csqc_progname", expect);
702 // Try to use versioned csprogs from pk3
703 // Only ever use versioned csprogs.dat files on dedicated servers;
704 // we need to reset csqc_progname on clients ourselves, and it's easier if the client's release name is constant
705 string pk3csprogs = "csprogs-" WATERMARK ".dat";
706 // This always works; fall back to it if a versioned csprogs.dat is suddenly missing
707 string select = "csprogs.dat";
708 if (fexists(pk3csprogs)) select = pk3csprogs;
709 if (cvar_string("csqc_progname") != select)
711 cvar_set("csqc_progname", select);
714 // Check for updates on startup
715 // We do it this way for atomicity so that connecting clients still match the server progs and don't disconnect
716 int sentinel = fopen("progs.txt", FILE_READ);
719 string switchversion = fgets(sentinel);
721 if (switchversion != "" && switchversion != WATERMARK)
723 LOG_INFOF("Switching progs: " WATERMARK " -> %s", switchversion);
724 // if it doesn't exist, assume either:
725 // a) the current program was overwritten
726 // b) this is a client only update
727 string newprogs = sprintf("progs-%s.dat", switchversion);
728 if (fexists(newprogs))
730 cvar_set("sv_progs", newprogs);
733 string newcsprogs = sprintf("csprogs-%s.dat", switchversion);
734 if (fexists(newcsprogs))
736 cvar_set("csqc_progname", newcsprogs);
744 LOG_INFO("Restart requested");
745 changelevel(mapname);
746 // let initialization continue, shutdown depends on it
750 if(world_already_spawned)
751 error("world already spawned - you may have EXACTLY ONE worldspawn!");
752 world_already_spawned = true;
754 delete_fn = remove_safely; // during spawning, watch what you remove!
756 cvar_changes_init(); // do this very early now so it REALLY matches the server config
758 // needs to be done so early because of the constants they create
761 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
763 TemporaryDB = db_create();
768 // 1 FLICKER (first variety)
769 lightstyle(1, "mmnmmommommnonmmonqnmmo");
771 // 2 SLOW STRONG PULSE
772 lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
774 // 3 CANDLE (first variety)
775 lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
778 lightstyle(4, "mamamamamama");
781 lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
783 // 6 FLICKER (second variety)
784 lightstyle(6, "nmonqnmomnmomomno");
786 // 7 CANDLE (second variety)
787 lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
789 // 8 CANDLE (third variety)
790 lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
792 // 9 SLOW STROBE (fourth variety)
793 lightstyle(9, "aaaaaaaazzzzzzzz");
795 // 10 FLUORESCENT FLICKER
796 lightstyle(10, "mmamammmmammamamaaamammma");
798 // 11 SLOW PULSE NOT FADE TO BLACK
799 lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
801 // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
806 if(autocvar_g_campaign)
809 Map_MarkAsRecent(mapname);
811 PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
815 static_init_precache();
819 GameRules_limit_fallbacks();
821 if(warmup_limit == 0)
822 warmup_limit = (autocvar_timelimit > 0) ? autocvar_timelimit * 60 : autocvar_timelimit;
825 bot_waypoints_for_items = autocvar_g_waypoints_for_items;
826 if(bot_waypoints_for_items == 1)
827 if(this.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
828 bot_waypoints_for_items = 0;
830 WaypointSprite_Init();
832 GameLogInit(); // prepare everything
834 // changing the logic generating it is okay. But:
835 // it HAS to stay <= 64 chars
836 // character set: ASCII 33-126 without the following characters: : ; ' " \ $
837 if(autocvar_sv_eventlog)
839 string s = sprintf("%s.%s.%06d", itos(autocvar_sv_eventlog_files_counter), strftime(false, "%s"), floor(random() * 1000000));
840 matchid = strzone(s);
842 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
843 s = ":gameinfo:mutators:LIST";
845 MUTATOR_CALLHOOK(BuildMutatorsString, s);
846 s = M_ARGV(0, string);
848 // initialiation stuff, not good in the mutator system
849 if(!autocvar_g_use_ammunition)
850 s = strcat(s, ":no_use_ammunition");
852 // initialiation stuff, not good in the mutator system
853 if(autocvar_g_pickup_items == 0)
854 s = strcat(s, ":no_pickup_items");
855 if(autocvar_g_pickup_items > 0)
856 s = strcat(s, ":pickup_items");
858 // initialiation stuff, not good in the mutator system
859 if(autocvar_g_weaponarena != "0")
860 s = strcat(s, ":", autocvar_g_weaponarena, " arena");
862 // TODO to mutator system
863 if(autocvar_g_norecoil)
864 s = strcat(s, ":norecoil");
866 // TODO to mutator system
867 if(autocvar_g_powerups == 0)
868 s = strcat(s, ":no_powerups");
869 if(autocvar_g_powerups > 0)
870 s = strcat(s, ":powerups");
873 GameLogEcho(":gameinfo:end");
876 matchid = strzone(ftos(random()));
878 cvar_set("nextmap", "");
882 if(autocvar_g_campaign)
888 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
890 if(fexists(strcat("scripts/", mapname, ".arena")))
891 cvar_settemp("sv_q3acompat_machineshotgunswap", "1");
893 if(fexists(strcat("scripts/", mapname, ".defi")))
894 cvar_settemp("sv_q3defragcompat", "1");
896 if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
898 int fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
902 while((s = fgets(fd)))
904 int l = tokenize_console(s);
909 string trackname = argv(2);
910 LOG_INFO("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:");
911 LOG_INFO(" cdtrack ", trackname);
912 if (cvar_value_issafe(trackname))
914 string newstuff = strcat(clientstuff, "cd loop \"", trackname, "\"\n");
915 strcpy(clientstuff, newstuff);
918 else if(argv(0) == "fog")
920 LOG_INFO("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:");
921 LOG_INFO(" \"fog\" \"", s, "\"");
923 else if(argv(0) == "set")
925 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
926 LOG_INFO(" clientsettemp_for_type all ", argv(1), " ", argv(2));
928 else if(argv(0) != "//")
930 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
931 LOG_INFO(" clientsettemp_for_type all ", argv(0), " ", argv(1));
942 // set up information replies for clients and server to use
943 maplist_reply = strzone(getmaplist());
944 lsmaps_reply = strzone(getlsmaps());
945 monsterlist_reply = strzone(getmonsterlist());
946 for(int i = 0; i < 10; ++i)
948 string s = getrecords(i);
950 records_reply[i] = strzone(s);
952 ladder_reply = strzone(getladder());
953 rankings_reply = strzone(getrankings());
958 PingPLReport_Spawn();
962 if (!wantrestart) localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
964 // fill sv_curl_serverpackages from .serverpackage files
965 if (autocvar_sv_curl_serverpackages_auto)
967 string s = "csprogs-" WATERMARK ".txt";
968 // remove automatically managed files from the list to prevent duplicates
969 for (int i = 0, n = tokenize_console(cvar_string("sv_curl_serverpackages")); i < n; ++i)
971 string pkg = argv(i);
972 if (startsWith(pkg, "csprogs-")) continue;
973 if (endsWith(pkg, "-serverpackage.txt")) continue;
974 if (endsWith(pkg, ".serverpackage")) continue; // OLD legacy
977 // add automatically managed files to the list
978 #define X(match) MACRO_BEGIN \
979 int fd = search_begin(match, true, false); \
982 for (int i = 0, j = search_getsize(fd); i < j; ++i) \
984 s = cons(s, search_getfilename(fd, i)); \
989 X("*-serverpackage.txt");
990 X("*.serverpackage");
992 cvar_set("sv_curl_serverpackages", s);
995 // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
997 // physics/balance/config changes that count as mod
998 if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
999 modname = cvar_string("g_mod_physics");
1000 if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance") && cvar_string("g_mod_balance") != "Testing")
1001 modname = cvar_string("g_mod_balance");
1002 if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
1003 modname = cvar_string("g_mod_config");
1004 // extra mutators that deserve to count as mod
1005 MUTATOR_CALLHOOK(SetModname, modname);
1006 modname = M_ARGV(0, string);
1008 // save it for later
1009 modname = strzone(modname);
1011 WinningConditionHelper(this); // set worldstatus
1013 world_initialized = 1;
1014 __spawnfunc_spawn_all();
1019 //makestatic (this); // Who the f___ did that?
1023 string GetGametype()
1025 return MapInfo_Type_ToString(MapInfo_LoadedGametype);
1033 float Map_Count, Map_Current;
1034 string Map_Current_Name;
1036 // NOTE: this now expects the map list to be already tokenized and the count in Map_Count
1037 int GetMaplistPosition()
1039 string map = GetMapname();
1040 int idx = autocvar_g_maplist_index;
1046 if(map == argv(idx))
1053 for(int pos = 0; pos < Map_Count; ++pos)
1055 if(map == argv(pos))
1059 // resume normal maplist rotation if current map is not in g_maplist
1063 bool MapHasRightSize(string map)
1065 int minplayers = max(0, floor(autocvar_minplayers));
1067 minplayers = max(0, floor(autocvar_minplayers_per_team) * AvailableTeams());
1068 if (autocvar_g_maplist_check_waypoints
1069 && (currentbots || autocvar_bot_number || player_count < minplayers))
1071 string checkwp_msg = strcat("checkwp ", map);
1072 if(!fexists(strcat("maps/", map, ".waypoints")))
1074 LOG_TRACE(checkwp_msg, ": no waypoints");
1077 LOG_TRACE(checkwp_msg, ": has waypoints");
1080 if(autocvar_g_maplist_ignore_sizes)
1083 // open map size restriction file
1084 string opensize_msg = strcat("opensize ", map);
1085 float fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
1086 int player_limit = ((autocvar_g_maplist_sizes_count_maxplayers) ? GetPlayerLimit() : 0);
1087 int pcount = ((player_limit > 0) ? min(player_count, player_limit) : player_count); // bind it to the player limit so that forced spectators don't influence the limits
1088 if(!autocvar_g_maplist_sizes_count_bots)
1089 pcount -= currentbots;
1092 opensize_msg = strcat(opensize_msg, ": ok, ");
1093 int mapmin = stoi(fgets(fh));
1094 int mapmax = stoi(fgets(fh));
1098 LOG_TRACE(opensize_msg, "not enough");
1101 if(mapmax && pcount > mapmax)
1103 LOG_TRACE(opensize_msg, "too many");
1106 LOG_TRACE(opensize_msg, "right size");
1109 LOG_TRACE(opensize_msg, ": not found");
1113 string Map_Filename(float position)
1115 return strcat("maps/", argv(position), ".bsp");
1118 void Map_MarkAsRecent(string m)
1120 cvar_set("g_maplist_mostrecent", strwords(cons(m, autocvar_g_maplist_mostrecent), max(0, autocvar_g_maplist_mostrecent_count)));
1123 float Map_IsRecent(string m)
1125 return strhasword(autocvar_g_maplist_mostrecent, m);
1128 float Map_Check(float position, float pass)
1132 map_next = argv(position);
1135 if(Map_IsRecent(map_next))
1138 filename = Map_Filename(position);
1139 if(MapInfo_CheckMap(map_next))
1143 if(MapHasRightSize(map_next))
1148 LOG_DEBUG( "Couldn't select '", filename, "'..." );
1153 void Map_Goto_SetStr(string nextmapname)
1155 if(getmapname_stored != "")
1156 strunzone(getmapname_stored);
1157 if(nextmapname == "")
1158 getmapname_stored = "";
1160 getmapname_stored = strzone(nextmapname);
1163 void Map_Goto_SetFloat(float position)
1165 cvar_set("g_maplist_index", ftos(position));
1166 Map_Goto_SetStr(argv(position));
1169 void Map_Goto(float reinit)
1171 MapInfo_LoadMap(getmapname_stored, reinit);
1174 // return codes of map selectors:
1175 // -1 = temporary failure (that is, try some method that is guaranteed to succeed)
1176 // -2 = permanent failure
1177 float MaplistMethod_Iterate() // usual method
1181 LOG_TRACE("Trying MaplistMethod_Iterate");
1183 for(pass = 1; pass <= 2; ++pass)
1185 for(i = 1; i < Map_Count; ++i)
1188 mapindex = (i + Map_Current) % Map_Count;
1189 if(Map_Check(mapindex, pass))
1196 float MaplistMethod_Repeat() // fallback method
1198 LOG_TRACE("Trying MaplistMethod_Repeat");
1200 if(Map_Check(Map_Current, 2))
1205 float MaplistMethod_Random() // random map selection
1209 LOG_TRACE("Trying MaplistMethod_Random");
1213 for(i = 0; i <= imax; ++i)
1216 mapindex = (Map_Current + floor(random() * (Map_Count - 1) + 1)) % Map_Count; // any OTHER map
1217 if(Map_Check(mapindex, 1))
1223 float MaplistMethod_Shuffle(float exponent) // more clever shuffling
1224 // the exponent sets a bias on the map selection:
1225 // the higher the exponent, the less likely "shortly repeated" same maps are
1227 float i, j, imax, insertpos;
1229 LOG_TRACE("Trying MaplistMethod_Shuffle");
1233 for(i = 0; i <= imax; ++i)
1237 // now reinsert this at another position
1238 insertpos = (random() ** (1 / exponent)); // ]0, 1]
1239 insertpos = insertpos * (Map_Count - 1); // ]0, Map_Count - 1]
1240 insertpos = ceil(insertpos) + 1; // {2, 3, 4, ..., Map_Count}
1241 LOG_TRACE("SHUFFLE: insert pos = ", ftos(insertpos));
1243 // insert the current map there
1245 for(j = 1; j < insertpos; ++j) // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
1246 newlist = strcat(newlist, " ", argv(j));
1247 newlist = strcat(newlist, " ", argv(0)); // now insert the just selected map
1248 for(j = insertpos; j < Map_Count; ++j) // i == Map_Count: no loop, has just been inserted as last
1249 newlist = strcat(newlist, " ", argv(j));
1250 newlist = substring(newlist, 1, strlen(newlist) - 1);
1251 cvar_set("g_maplist", newlist);
1252 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1254 // NOTE: the selected map has just been inserted at (insertpos-1)th position
1255 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
1256 if(Map_Check(Map_Current, 1))
1264 float i = Map_Count = 0;
1265 if(autocvar_g_maplist != "")
1267 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1268 for (i = 0; i < Map_Count; ++i)
1270 if (Map_Check(i, 2))
1277 bprint( "Maplist contains no usable maps! Resetting it to default map list.\n" );
1278 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags() | MAPINFO_FLAG_NOAUTOMAPLIST));
1279 if(autocvar_g_maplist_shuffle)
1281 if(!server_is_dedicated)
1282 localcmd("\nmenu_cmd sync\n");
1283 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1286 error("empty maplist, cannot select a new map");
1287 Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
1289 strcpy(Map_Current_Name, argv(Map_Current)); // will be automatically freed on exit thanks to DP
1290 // this may or may not be correct, but who cares, in the worst case a map
1291 // isn't chosen in the first pass that should have been
1300 if(autocvar_g_maplist_shuffle > 0)
1301 nextMap = MaplistMethod_Shuffle(autocvar_g_maplist_shuffle + 1);
1304 if(autocvar_g_maplist_selectrandom)
1305 nextMap = MaplistMethod_Random();
1308 nextMap = MaplistMethod_Iterate();
1311 nextMap = MaplistMethod_Repeat();
1315 Map_Goto_SetFloat(nextMap);
1316 return getmapname_stored;
1322 float DoNextMapOverride(float reinit)
1324 if(autocvar_g_campaign)
1326 CampaignPostIntermission();
1327 alreadychangedlevel = true;
1330 if(autocvar_quit_when_empty)
1332 if(player_count <= currentbots)
1335 alreadychangedlevel = true;
1339 if(autocvar_quit_and_redirect != "")
1341 redirection_target = strzone(autocvar_quit_and_redirect);
1342 alreadychangedlevel = true;
1345 if (!reinit && autocvar_samelevel) // if samelevel is set, stay on same level
1347 localcmd("restart\n");
1348 alreadychangedlevel = true;
1351 if(autocvar_nextmap != "")
1354 m = GameTypeVote_MapInfo_FixName(autocvar_nextmap);
1355 cvar_set("nextmap",m);
1357 if(!m || gametypevote)
1359 if(autocvar_sv_vote_gametype)
1365 if(MapInfo_CheckMap(m))
1369 alreadychangedlevel = true;
1373 if(!reinit && autocvar_lastlevel)
1375 cvar_settemp_restore();
1376 localcmd("set lastlevel 0\ntogglemenu 1\n");
1377 alreadychangedlevel = true;
1383 void GotoNextMap(float reinit)
1388 if (alreadychangedlevel)
1390 alreadychangedlevel = true;
1392 string nextMap = GetNextMap();
1394 error("Everything is broken - cannot find a next map. Please report this to the developers.");
1403 When the player presses attack or jump, change to the next level
1406 .float autoscreenshot;
1407 void IntermissionThink(entity this)
1409 FixIntermissionClient(this);
1411 float server_screenshot = (autocvar_sv_autoscreenshot && CS(this).cvar_cl_autoscreenshot);
1412 float client_screenshot = (CS(this).cvar_cl_autoscreenshot == 2);
1414 if( (server_screenshot || client_screenshot)
1415 && ((this.autoscreenshot > 0) && (time > this.autoscreenshot)) )
1417 this.autoscreenshot = -1;
1418 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"))); }
1422 if (time < intermission_exittime)
1425 if(!mapvote_initialized)
1426 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)))
1433 ===============================================================================
1437 ===============================================================================
1440 void DumpStats(float final)
1449 to_console = autocvar_sv_logscores_console;
1450 to_eventlog = autocvar_sv_eventlog;
1451 to_file = autocvar_sv_logscores_file;
1455 to_console = true; // always print printstats replies
1456 to_eventlog = false; // but never print them to the event log
1460 if(autocvar_sv_eventlog_console)
1461 to_console = false; // otherwise we get the output twice
1467 s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1477 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1481 fputs(file, strcat(s, "\n"));
1484 s = strcat(":labels:player:", GetPlayerScoreString(NULL, 0));
1490 fputs(file, strcat(s, "\n"));
1492 FOREACH_CLIENT(IS_REAL_CLIENT(it) || (IS_BOT_CLIENT(it) && autocvar_sv_logscores_bots), {
1493 s = strcat(":player:see-labels:", GetPlayerScoreString(it, 0), ":");
1494 s = strcat(s, ftos(rint(time - CS(it).jointime)), ":");
1495 if(IS_PLAYER(it) || MUTATOR_CALLHOOK(GetPlayerStatus, it))
1496 s = strcat(s, ftos(it.team), ":");
1498 s = strcat(s, "spectator:");
1501 LOG_INFO(s, playername(it, false));
1503 GameLogEcho(strcat(s, ftos(it.playerid), ":", playername(it, false)));
1505 fputs(file, strcat(s, playername(it, false), "\n"));
1510 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1516 fputs(file, strcat(s, "\n"));
1518 for(i = 1; i < 16; ++i)
1520 s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1521 s = strcat(s, ":", ftos(i));
1527 fputs(file, strcat(s, "\n"));
1534 GameLogEcho(":end");
1537 fputs(file, ":end\n");
1542 void FixIntermissionClient(entity e)
1544 if(!e.autoscreenshot) // initial call
1546 e.autoscreenshot = time + 0.8; // used for autoscreenshot
1547 SetResourceExplicit(e, RES_HEALTH, -2342);
1548 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1549 for (int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1551 .entity weaponentity = weaponentities[slot];
1552 if(e.(weaponentity))
1554 e.(weaponentity).effects = EF_NODRAW;
1555 if (e.(weaponentity).weaponchild)
1556 e.(weaponentity).weaponchild.effects = EF_NODRAW;
1559 if(IS_REAL_CLIENT(e))
1561 stuffcmd(e, "\nscr_printspeed 1000000\n");
1562 RandomSelection_Init();
1563 FOREACH_WORD(autocvar_sv_intermission_cdtrack, true, {
1564 RandomSelection_AddString(it, 1, 1);
1566 if (RandomSelection_chosen_string != "")
1568 stuffcmd(e, sprintf("\ncd loop %s\n", RandomSelection_chosen_string));
1571 WriteByte(MSG_ONE, SVC_INTERMISSION);
1577 go to the next level for deathmatch
1578 only called if a time or frag limit has expired
1582 game_stopped = true;
1583 intermission_running = 1; // game over
1585 // enforce a wait time before allowing changelevel
1586 if(player_count > 0)
1587 intermission_exittime = time + autocvar_sv_mapchange_delay;
1589 intermission_exittime = -1;
1592 WriteByte (MSG_ALL, SVC_CDTRACK);
1593 WriteByte (MSG_ALL, 3);
1594 WriteByte (MSG_ALL, 3);
1595 // done in FixIntermission
1598 //pos = FindIntermission ();
1605 PlayerStats_GameReport(true);
1606 WeaponStats_Shutdown();
1608 Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_Null); // kill all centerprints now
1610 if(autocvar_sv_eventlog)
1611 GameLogEcho(":gameover");
1615 FOREACH_CLIENT(IS_PLAYER(it), {
1616 FixIntermissionClient(it);
1618 bprint(playername(it, false), " ^7wins.\n");
1621 target_music_kill();
1623 if(autocvar_g_campaign)
1624 CampaignPreIntermission();
1626 MUTATOR_CALLHOOK(MatchEnd);
1628 localcmd("\nsv_hook_gameend\n");
1632 float InitiateSuddenDeath()
1634 // Check first whether normal overtimes could be added before initiating suddendeath mode
1635 // - for this timelimit_overtime needs to be >0 of course
1636 // - also check the winning condition calculated in the previous frame and only add normal overtime
1637 // again, if at the point at which timelimit would be extended again, still no winner was found
1638 if (!autocvar_g_campaign && checkrules_overtimesadded >= 0
1639 && (checkrules_overtimesadded < autocvar_timelimit_overtimes || autocvar_timelimit_overtimes < 0)
1640 && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1642 return 1; // need to call InitiateOvertime later
1646 if(!checkrules_suddendeathend)
1648 if(autocvar_g_campaign)
1649 checkrules_suddendeathend = time; // no suddendeath in campaign
1651 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1652 if(g_race && !g_race_qualifying)
1653 race_StartCompleting();
1659 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1661 ++checkrules_overtimesadded;
1662 //add one more overtime by simply extending the timelimit
1663 cvar_set("timelimit", ftos(autocvar_timelimit + autocvar_timelimit_overtime));
1664 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime * 60);
1667 float GetWinningCode(float fraglimitreached, float equality)
1669 if(autocvar_g_campaign == 1)
1671 if(fraglimitreached)
1680 if(fraglimitreached)
1681 return WINNING_STARTSUDDENDEATHOVERTIME;
1683 return WINNING_NEVER;
1687 if(fraglimitreached)
1695 // set the .winning flag for exactly those players with a given field value
1696 void SetWinners(.float field, float value)
1698 FOREACH_CLIENT(IS_PLAYER(it), { it.winning = (it.(field) == value); });
1701 // set the .winning flag for those players with a given field value
1702 void AddWinners(.float field, float value)
1704 FOREACH_CLIENT(IS_PLAYER(it), {
1705 if(it.(field) == value)
1710 // clear the .winning flags
1713 FOREACH_CLIENT(IS_PLAYER(it), { it.winning = 0; });
1716 void ShuffleMaplist()
1718 cvar_set("g_maplist", shufflewords(autocvar_g_maplist));
1722 float WinningCondition_Scores(float limit, float leadlimit)
1724 // TODO make everything use THIS winning condition (except LMS)
1725 WinningConditionHelper(NULL);
1729 for (int i = 1; i < 5; ++i)
1731 Team_SetTeamScore(Team_GetTeamFromIndex(i),
1732 TeamScore_GetCompareValue(Team_IndexToTeam(i)));
1737 if(WinningConditionHelper_winner)
1738 WinningConditionHelper_winner.winning = 1;
1739 if(WinningConditionHelper_winnerteam >= 0)
1740 SetWinners(team, WinningConditionHelper_winnerteam);
1742 if(WinningConditionHelper_lowerisbetter)
1744 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1745 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1749 if(WinningConditionHelper_zeroisworst)
1750 leadlimit = 0; // not supported in this mode
1752 if(MUTATOR_CALLHOOK(Scores_CountFragsRemaining))
1755 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1761 fragsleft = FLOAT_MAX;
1762 float leadingfragsleft = FLOAT_MAX;
1764 fragsleft = limit - WinningConditionHelper_topscore;
1766 leadingfragsleft = WinningConditionHelper_secondscore + leadlimit - WinningConditionHelper_topscore;
1768 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1769 fragsleft = max(fragsleft, leadingfragsleft);
1771 fragsleft = min(fragsleft, leadingfragsleft);
1774 if (fragsleft_last != fragsleft) // do not announce same remaining frags multiple times
1777 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_1);
1778 else if (fragsleft == 2)
1779 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_2);
1780 else if (fragsleft == 3)
1781 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_3);
1783 fragsleft_last = fragsleft;
1787 bool fraglimit_reached = (limit && WinningConditionHelper_topscore >= limit);
1788 bool leadlimit_reached = (leadlimit && WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1791 // only respect leadlimit_and_fraglimit when both limits are set or the game will never end
1792 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1793 limit_reached = (fraglimit_reached && leadlimit_reached);
1795 limit_reached = (fraglimit_reached || leadlimit_reached);
1797 return GetWinningCode(
1798 WinningConditionHelper_topscore && limit_reached,
1799 WinningConditionHelper_equality
1803 float WinningCondition_RanOutOfSpawns()
1805 if(have_team_spawns <= 0)
1808 if(!autocvar_g_spawn_useallspawns)
1811 if(!some_spawn_has_been_used)
1814 for (int i = 1; i < 5; ++i)
1816 Team_SetTeamScore(Team_GetTeamFromIndex(i), 0);
1819 FOREACH_CLIENT(IS_PLAYER(it) && !IS_DEAD(it),
1821 if (Team_IsValidTeam(it.team))
1823 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1827 IL_EACH(g_spawnpoints, true,
1829 if (Team_IsValidTeam(it.team))
1831 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1836 float team1_score = Team_GetTeamScore(Team_GetTeamFromIndex(1));
1837 float team2_score = Team_GetTeamScore(Team_GetTeamFromIndex(2));
1838 float team3_score = Team_GetTeamScore(Team_GetTeamFromIndex(3));
1839 float team4_score = Team_GetTeamScore(Team_GetTeamFromIndex(4));
1840 if(team1_score + team2_score + team3_score + team4_score == 0)
1842 checkrules_equality = true;
1845 else if(team1_score + team2_score + team3_score + team4_score == 1)
1850 else if(team2_score)
1852 else if(team3_score)
1854 else // if(team4_score)
1856 entity balance = TeamBalance_CheckAllowedTeams(NULL);
1857 for(i = 0; i < MAX_TEAMSCORE; ++i)
1859 for (int j = 1; j <= NUM_TEAMS; ++j)
1865 if (!TeamBalance_IsTeamAllowed(balance, j))
1869 TeamScore_AddToTeam(Team_IndexToTeam(j), i, -1000);
1873 AddWinners(team, t);
1884 Exit deathmatch games upon conditions
1887 void CheckRules_World()
1894 if (intermission_running) // someone else quit the game already
1896 if(player_count == 0) // Nobody there? Then let's go to the next map
1898 // this will actually check the player count in the next frame
1899 // again, but this shouldn't hurt
1903 float timelimit = autocvar_timelimit * 60;
1904 float fraglimit = autocvar_fraglimit;
1905 float leadlimit = autocvar_leadlimit;
1906 if (leadlimit < 0) leadlimit = 0;
1908 if(warmup_stage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1911 timelimit = 0; // timelimit is not made for warmup
1913 fraglimit = 0; // no fraglimit for now
1914 leadlimit = 0; // no leadlimit for now
1919 timelimit += game_starttime;
1921 else if (timelimit < 0)
1931 if(checkrules_suddendeathend)
1933 if(!checkrules_suddendeathwarning)
1935 checkrules_suddendeathwarning = true;
1936 if(g_race && !g_race_qualifying)
1937 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_RACE_FINISHLAP);
1939 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_FRAG);
1944 if (timelimit && time >= timelimit)
1946 if(g_race && (g_race_qualifying == 2) && timelimit > 0)
1949 float playerswithlaps;
1951 totalplayers = playerswithlaps = readyplayers = 0;
1952 FOREACH_CLIENT(IS_PLAYER(it), {
1954 if(GameRules_scoring_add(it, RACE_FASTEST, 0))
1960 // at least 2 of the players have completed a lap: start the RACE
1961 // otherwise, the players should end the qualifying on their own
1962 if(readyplayers || playerswithlaps >= 2)
1964 checkrules_suddendeathend = 0;
1965 ReadyRestart(); // go to race
1969 wantovertime |= InitiateSuddenDeath();
1972 wantovertime |= InitiateSuddenDeath();
1976 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1982 int checkrules_status = WinningCondition_RanOutOfSpawns();
1983 if(checkrules_status == WINNING_YES)
1984 bprint("Hey! Someone ran out of spawns!\n");
1985 else if(MUTATOR_CALLHOOK(CheckRules_World, checkrules_status, timelimit, fraglimit))
1986 checkrules_status = M_ARGV(0, float);
1988 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
1990 if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
1992 checkrules_status = WINNING_NEVER;
1993 checkrules_overtimesadded = -1;
1994 wantovertime |= InitiateSuddenDeath();
1997 if(checkrules_status == WINNING_NEVER)
1998 // equality cases! Nobody wins if the overtime ends in a draw.
2003 if(checkrules_status == WINNING_NEVER)
2006 checkrules_status = WINNING_YES;
2009 if(checkrules_suddendeathend)
2010 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
2011 checkrules_status = WINNING_YES;
2013 if(checkrules_status == WINNING_YES)
2015 //print("WINNING\n");
2020 string GotoMap(string m)
2022 m = GameTypeVote_MapInfo_FixName(m);
2024 return "The map you suggested is not available on this server.";
2025 if (!autocvar_sv_vote_gametype)
2026 if(!MapInfo_CheckMap(m))
2027 return "The map you suggested does not support the current game mode.";
2028 cvar_set("nextmap", m);
2029 cvar_set("timelimit", "-1");
2030 if(mapvote_initialized || alreadychangedlevel)
2032 if(DoNextMapOverride(0))
2033 return "Map switch initiated.";
2035 return "Hm... no. For some reason I like THIS map more.";
2038 return "Map switch will happen after scoreboard.";
2041 bool autocvar_sv_gameplayfix_multiplethinksperframe = true;
2042 void RunThink(entity this)
2044 // don't let things stay in the past.
2045 // it is possible to start that way by a trigger with a local time.
2046 if(this.nextthink <= 0 || this.nextthink > time + frametime)
2049 float oldtime = time; // do we need to save this?
2051 for (int iterations = 0; iterations < 128 && !wasfreed(this); iterations++)
2053 time = max(oldtime, this.nextthink);
2057 getthink(this)(this);
2058 // mods often set nextthink to time to cause a think every frame,
2059 // we don't want to loop in that case, so exit if the new nextthink is
2060 // <= the time the qc was told, also exit if it is past the end of the
2062 if(this.nextthink <= time || this.nextthink > oldtime + frametime || !autocvar_sv_gameplayfix_multiplethinksperframe)
2069 bool autocvar_sv_freezenonclients;
2070 void Physics_Frame()
2072 if(autocvar_sv_freezenonclients)
2075 IL_EACH(g_moveables, true,
2077 if(IS_CLIENT(it) || it.move_movetype == MOVETYPE_PHYSICS)
2080 //set_movetype(it, it.move_movetype);
2081 // inline the set_movetype function, since this is called a lot
2082 it.movetype = (it.move_qcphysics) ? MOVETYPE_QCENTITY : it.move_movetype;
2084 if(it.move_qcphysics && it.move_movetype != MOVETYPE_NONE)
2085 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2087 if(it.movetype >= MOVETYPE_USER_FIRST && it.movetype <= MOVETYPE_USER_LAST) // these cases have no think handling
2089 if(it.move_movetype == MOVETYPE_PUSH || it.move_movetype == MOVETYPE_FAKEPUSH)
2090 continue; // these movetypes have no regular think function
2091 // handle thinking here
2092 if (getthink(it) && it.nextthink > 0 && it.nextthink <= time + frametime)
2097 if(autocvar_sv_gameplayfix_delayprojectiles >= 0)
2100 // make a second pass to see if any ents spawned this frame and make
2101 // sure they run their move/think. this is verified by checking .move_time, which will never be 0 if the entity has moved
2102 // MOVETYPE_NONE is also checked as .move_time WILL be 0 with that movetype
2103 IL_EACH(g_moveables, it.move_qcphysics,
2105 if(IS_CLIENT(it) || it.move_time || it.move_movetype == MOVETYPE_NONE || it.move_movetype == MOVETYPE_PHYSICS)
2107 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2111 void systems_update();
2114 anticheat_endframe();
2118 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2119 entity e = IS_SPEC(it) ? it.enemy : it;
2120 if (e.typehitsound) {
2121 STAT(TYPEHIT_TIME, it) = time;
2122 } else if (e.killsound) {
2123 STAT(KILL_TIME, it) = time;
2124 } else if (e.damage_dealt) {
2125 STAT(HIT_TIME, it) = time;
2126 STAT(DAMAGE_DEALT_TOTAL, it) += ceil(e.damage_dealt);
2129 // add 1 frametime because after this, engine SV_Physics
2130 // increases time by a frametime and then networks the frame
2131 // add another frametime because client shows everything with
2132 // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2134 float altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2135 FOREACH_CLIENT(true, {
2136 it.typehitsound = false;
2137 it.damage_dealt = 0;
2138 it.killsound = false;
2139 antilag_record(it, CS(it), altime);
2141 IL_EACH(g_monsters, true,
2143 antilag_record(it, it, altime);
2145 IL_EACH(g_projectiles, it.classname == "nade",
2147 antilag_record(it, it, altime);
2156 * returns true if redirecting
2158 float redirection_timeout;
2159 float redirection_nextthink;
2160 float RedirectionThink()
2162 float clients_found;
2164 if(redirection_target == "")
2167 if(!redirection_timeout)
2169 cvar_set("sv_public", "-2");
2170 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2171 if(redirection_target == "self")
2172 bprint("^3SERVER NOTICE:^7 restarting the server\n");
2174 bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2177 if(time < redirection_nextthink)
2180 redirection_nextthink = time + 1;
2183 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2185 LOG_INFO("Redirecting: sending connect command to ", it.netname);
2186 if(redirection_target == "self")
2187 stuffcmd(it, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2189 stuffcmd(it, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2193 LOG_INFO("Redirecting: ", ftos(clients_found), " clients left.");
2195 if(time > redirection_timeout || clients_found == 0)
2196 localcmd("\nwait; wait; wait; quit\n");
2203 // Loaded from a save game
2204 // some things then break, so let's work around them...
2206 // Progs DB (capture records)
2207 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2211 MapInfo_Enumerate();
2212 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2215 TargetMusic_RestoreGame();
2222 if(world_initialized > 0)
2224 world_initialized = 0;
2226 // if a timeout is active, reset the slowmo value to normal
2227 if(timeout_status == TIMEOUT_ACTIVE)
2228 cvar_set("slowmo", ftos(orig_slowmo));
2230 LOG_TRACE("Saving persistent data...");
2233 // playerstats with unfinished match
2234 PlayerStats_GameReport(false);
2236 if(!cheatcount_total)
2238 if(autocvar_sv_db_saveasdump)
2239 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2241 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2243 if(autocvar_developer > 0)
2245 if(autocvar_sv_db_saveasdump)
2246 db_dump(TemporaryDB, "server-temp.db");
2248 db_save(TemporaryDB, "server-temp.db");
2250 CheatShutdown(); // must be after cheatcount check
2251 db_close(ServerProgsDB);
2252 db_close(TemporaryDB);
2253 LOG_TRACE("Saving persistent data... done!");
2254 // tell the bot system the game is ending now
2257 WeaponStats_Shutdown();
2260 else if(world_initialized == 0)
2262 LOG_INFO("NOTE: crashed before even initializing the world, not saving persistent data");
2266 __init_dedicated_server_shutdown();