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>
16 #include "mapvoting.qh"
17 #include <server/mutators/_mod.qh>
20 #include "scores_rules.qh"
21 #include "teamplay.qh"
22 #include "weapons/weaponstats.qh"
23 #include "../common/constants.qh"
24 #include <common/net_linked.qh>
25 #include "../common/deathtypes/all.qh"
26 #include <common/gamemodes/_mod.qh>
27 #include "../common/gamemodes/sv_rules.qh"
28 #include "../common/mapinfo.qh"
29 #include "../common/monsters/_mod.qh"
30 #include "../common/monsters/sv_monsters.qh"
31 #include "../common/vehicles/all.qh"
32 #include "../common/notifications/all.qh"
33 #include "../common/physics/player.qh"
34 #include "../common/playerstats.qh"
35 #include "../common/stats.qh"
36 #include "../common/teams.qh"
37 #include "../common/mapobjects/trigger/secret.qh"
38 #include "../common/mapobjects/target/music.qh"
39 #include "../common/util.qh"
40 #include "../common/items/_mod.qh"
41 #include <common/weapons/_all.qh>
42 #include "../common/state.qh"
44 const float LATENCY_THINKRATE = 10;
49 void PingPLReport_Think(entity this)
54 delta = 3 / maxclients;
55 if(delta < sys_frametime)
57 this.nextthink = time + delta;
59 e = edict_num(this.cnt + 1);
60 if(IS_CLIENT(e) && IS_REAL_CLIENT(e))
62 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
63 WriteByte(MSG_BROADCAST, this.cnt);
64 WriteShort(MSG_BROADCAST, bound(1, CS(e).ping, 65535));
65 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_packetloss * 255), 255));
66 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_movementloss * 255), 255));
68 // record latency times for clients throughout the match so we can report it to playerstats
69 if(time > (CS(e).latency_time + LATENCY_THINKRATE))
71 CS(e).latency_sum += CS(e).ping;
72 CS(e).latency_cnt += 1;
73 CS(e).latency_time = time;
74 //print("sum: ", ftos(CS(e).latency_sum), ", cnt: ", ftos(CS(e).latency_cnt), ", avg: ", ftos(CS(e).latency_sum / CS(e).latency_cnt), ".\n");
79 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
80 WriteByte(MSG_BROADCAST, this.cnt);
81 WriteShort(MSG_BROADCAST, 0);
82 WriteByte(MSG_BROADCAST, 0);
83 WriteByte(MSG_BROADCAST, 0);
85 this.cnt = (this.cnt + 1) % maxclients;
87 void PingPLReport_Spawn()
89 pingplreport = new_pure(pingplreport);
90 setthink(pingplreport, PingPLReport_Think);
91 pingplreport.nextthink = time;
94 const float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
95 string redirection_target;
96 float world_initialized;
98 void SetDefaultAlpha()
100 if (!MUTATOR_CALLHOOK(SetDefaultAlpha))
102 default_player_alpha = autocvar_g_player_alpha;
103 if(default_player_alpha == 0)
104 default_player_alpha = 1;
105 default_weapon_alpha = default_player_alpha;
109 void GotoFirstMap(entity this)
112 if(autocvar__sv_init)
114 // cvar_set("_sv_init", "0");
115 // we do NOT set this to 0 any more, so someone "accidentally" changing
116 // to this "init" map on a dedicated server will cause no permanent
118 if(autocvar_g_maplist_shuffle)
120 n = tokenizebyseparator(autocvar_g_maplist, " ");
121 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
124 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
126 if(!DoNextMapOverride(1))
134 this.nextthink = time;
138 this.nextthink = time + 1;
139 LOG_INFO("Waiting for _sv_init being set to 1 by initialization scripts...");
143 void cvar_changes_init()
147 float n, i, adding, pureadding;
149 strfree(cvar_changes);
150 strfree(cvar_purechanges);
151 cvar_purechanges_count = 0;
154 buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
160 for(i = 0; i < n; ++i)
162 k = bufstr_get(h, i);
164 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
165 #define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
166 #define BADCVAR(p) if(k == p) continue
168 // general excludes and namespaces for server admin used cvars
169 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
173 BADPREFIX("cvar_check_");
175 BADCVAR("g_configversion");
176 BADCVAR("halflifebsp");
177 BADCVAR("sv_mapformat_is_quake2");
178 BADCVAR("sv_mapformat_is_quake3");
179 BADPREFIX("sv_world");
185 BADPREFIX("scoreboard_");
186 BADPREFIX("g_campaign");
187 BADPREFIX("g_waypointsprite_");
193 BADPREFIX("net_slist_");
199 BADPREFIX("sensitivity");
200 BADPREFIX("userbind");
203 BADPREFIX("crosshair");
204 BADCVAR("mod_q3bsp_lightmapmergepower");
205 BADCVAR("mod_q3bsp_nolightmaps");
207 BADCVAR("mastervolume");
209 BADCVAR("bgmvolume");
210 BADCVAR("in_pitch_min");
211 BADCVAR("in_pitch_max");
214 BADCVAR("developer");
215 BADCVAR("log_dest_udp");
216 BADCVAR("net_address");
217 BADCVAR("net_address_ipv6");
219 BADCVAR("savedgamecfg");
220 BADCVAR("serverconfig");
221 BADCVAR("sv_autoscreenshot");
222 BADCVAR("sv_heartbeatperiod");
223 BADCVAR("sv_vote_master_password");
224 BADCVAR("sys_colortranslation");
225 BADCVAR("sys_specialcharactertranslation");
226 BADCVAR("timeformat");
227 BADCVAR("timestamps");
228 BADCVAR("g_require_stats");
229 BADPREFIX("developer_");
231 BADPREFIX("g_banned_list");
232 BADPREFIX("g_require_stats_");
233 BADPREFIX("g_chat_flood_");
234 BADPREFIX("g_ghost_items");
235 BADPREFIX("g_playerstats_");
236 BADPREFIX("g_voice_flood_");
237 BADPREFIX("log_file");
240 BADPREFIX("sv_allowdownloads");
241 BADPREFIX("sv_autodemo");
242 BADPREFIX("sv_curl_");
243 BADPREFIX("sv_eventlog");
244 BADPREFIX("sv_logscores_");
245 BADPREFIX("sv_master");
246 BADPREFIX("sv_weaponstats_");
247 BADPREFIX("sv_waypointsprite_");
248 BADCVAR("rescan_pending");
250 // these can contain player IDs, so better hide
251 BADPREFIX("g_forced_team_");
252 BADCVAR("sv_muteban_list");
253 BADCVAR("sv_voteban_list");
254 BADCVAR("sv_allow_customplayermodels_idlist");
255 BADCVAR("sv_allow_customplayermodels_speciallist");
258 BADCVAR("fraglimit");
260 BADCVAR("g_assault");
262 BADCVAR("g_ca_teams");
263 BADCVAR("g_conquest");
264 BADCVAR("g_conquest_teams");
269 BADCVAR("g_domination");
270 BADCVAR("g_domination_default_teams");
272 BADCVAR("g_duel_not_dm_maps");
273 BADCVAR("g_freezetag");
274 BADCVAR("g_freezetag_teams");
275 BADCVAR("g_invasion_teams");
276 BADCVAR("g_invasion_type");
277 BADCVAR("g_jailbreak");
278 BADCVAR("g_jailbreak_teams");
279 BADCVAR("g_keepaway");
280 BADCVAR("g_keyhunt");
281 BADCVAR("g_keyhunt_teams");
283 BADCVAR("g_nexball");
284 BADCVAR("g_onslaught");
286 BADCVAR("g_race_laps_limit");
287 BADCVAR("g_race_qualifying_timelimit");
288 BADCVAR("g_race_qualifying_timelimit_override");
289 BADCVAR("g_runematch");
290 BADCVAR("g_shootfromeye");
292 BADCVAR("g_survival");
293 BADCVAR("g_survival_not_dm_maps");
295 BADCVAR("g_tdm_on_dm_maps");
296 BADCVAR("g_tdm_teams");
298 BADCVAR("leadlimit");
301 BADCVAR("timelimit");
302 BADCVAR("g_mapinfo_settemp_acl");
303 BADCVAR("g_mapinfo_ignore_warnings");
304 BADCVAR("g_maplist_ignore_sizes");
305 BADCVAR("g_maplist_sizes_count_bots");
309 BADCVAR("g_maplist");
310 BADCVAR("g_maplist_mostrecent");
314 d = cvar_defstring(k);
320 cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
321 if(strlen(cvar_changes) > 16384)
323 cvar_changes = "// too many settings have been changed to show them here\n";
328 // now check if the changes are actually gameplay relevant
330 // does nothing gameplay relevant
331 BADCVAR("captureleadlimit_override");
332 BADCVAR("condump_stripcolors");
333 BADCVAR("gameversion");
334 BADCVAR("fs_gamedir");
335 BADCVAR("g_allow_oldvortexbeam");
336 BADCVAR("g_balance_kill_delay");
337 BADCVAR("g_buffs_pickup_anyway");
338 BADCVAR("g_buffs_randomize");
339 BADCVAR("g_buffs_randomize_teamplay");
340 BADCVAR("g_campcheck_distance");
341 BADCVAR("g_chatsounds");
342 BADCVAR("g_ca_point_leadlimit");
343 BADCVAR("g_ca_point_limit");
344 BADCVAR("g_ctf_captimerecord_always");
345 BADCVAR("g_ctf_flag_glowtrails");
346 BADCVAR("g_ctf_dynamiclights");
347 BADCVAR("g_ctf_flag_pickup_verbosename");
348 BADPRESUFFIX("g_ctf_flag_", "_model");
349 BADPRESUFFIX("g_ctf_flag_", "_skin");
350 BADCVAR("g_domination_point_leadlimit");
351 BADCVAR("g_forced_respawn");
352 BADCVAR("g_freezetag_point_leadlimit");
353 BADCVAR("g_freezetag_point_limit");
354 BADCVAR("g_glowtrails");
356 BADCVAR("g_casings");
357 BADCVAR("g_invasion_point_limit");
358 BADCVAR("g_jump_grunt");
359 BADCVAR("g_keepaway_ballcarrier_effects");
360 BADCVAR("g_keepawayball_effects");
361 BADCVAR("g_keyhunt_point_leadlimit");
362 BADCVAR("g_nexball_goalleadlimit");
363 BADCVAR("g_new_toys_autoreplace");
364 BADCVAR("g_new_toys_use_pickupsound");
365 BADCVAR("g_physics_predictall");
366 BADCVAR("g_piggyback");
367 BADCVAR("g_playerclip_collisions");
368 BADCVAR("g_spawn_alloweffects");
369 BADCVAR("g_tdm_point_leadlimit");
370 BADCVAR("g_tdm_point_limit");
371 BADCVAR("leadlimit_and_fraglimit");
372 BADCVAR("leadlimit_override");
374 BADCVAR("sv_announcer");
375 BADCVAR("sv_checkforpacketsduringsleep");
376 BADCVAR("sv_damagetext");
377 BADCVAR("sv_db_saveasdump");
378 BADCVAR("sv_intermission_cdtrack");
379 BADCVAR("sv_mapchange_delay");
380 BADCVAR("sv_minigames");
381 BADCVAR("sv_namechangetimer");
382 BADCVAR("sv_precacheplayermodels");
384 BADCVAR("sv_stepheight");
385 BADCVAR("sv_timeout");
386 BADCVAR("sv_weapons_modeloverride");
387 BADCVAR("w_prop_interval");
389 BADPREFIX("crypto_");
390 BADPREFIX("gameversion_");
391 BADPREFIX("g_chat_");
392 BADPREFIX("g_ctf_captimerecord_");
393 BADPREFIX("g_hats_");
394 BADPREFIX("g_maplist_");
396 BADPREFIX("g_respawn_");
398 BADPREFIX("notification_");
401 BADPREFIX("sv_allow_");
402 BADPREFIX("sv_cullentities_");
403 BADPREFIX("sv_maxidle_");
404 BADPREFIX("sv_minigames_");
405 BADPREFIX("sv_radio_");
406 BADPREFIX("sv_timeout_");
407 BADPREFIX("sv_vote_");
408 BADPREFIX("timelimit_");
410 // allowed changes to server admins (please sync this to server.cfg)
414 // :%s,//\([^ ]*\).*,BADCVAR("\1");,
416 // yes, this does contain some redundant stuff, don't really care
417 BADPREFIX("bot_ai_");
418 BADCVAR("bot_config_file");
419 BADCVAR("bot_number");
420 BADCVAR("bot_prefix");
421 BADCVAR("bot_suffix");
422 BADCVAR("capturelimit_override");
423 BADCVAR("fraglimit_override");
425 BADCVAR("g_antilag");
426 BADCVAR("g_balance_teams");
427 BADCVAR("g_balance_teams_prevent_imbalance");
428 BADCVAR("g_balance_teams_scorefactor");
429 BADCVAR("g_ban_sync_trusted_servers");
430 BADCVAR("g_ban_sync_uri");
432 BADCVAR("g_ca_teams_override");
433 BADCVAR("g_ctf_fullbrightflags");
434 BADCVAR("g_ctf_ignore_frags");
435 BADCVAR("g_ctf_leaderboard");
436 BADCVAR("g_domination_point_limit");
437 BADCVAR("g_domination_teams_override");
438 BADCVAR("g_freezetag_teams_override");
439 BADCVAR("g_friendlyfire");
440 BADCVAR("g_fullbrightitems");
441 BADCVAR("g_fullbrightplayers");
442 BADCVAR("g_keyhunt_point_limit");
443 BADCVAR("g_keyhunt_teams_override");
444 BADCVAR("g_lms_lives_override");
445 BADCVAR("g_maplist");
446 BADCVAR("g_maxplayers");
447 BADCVAR("g_mirrordamage");
448 BADCVAR("g_nexball_goallimit");
449 BADCVAR("g_norecoil");
450 BADCVAR("g_physics_clientselect");
452 BADCVAR("g_powerups");
453 BADCVAR("g_player_brightness");
454 BADCVAR("g_rocket_flying");
455 BADCVAR("g_rocket_flying_disabledelays");
456 BADCVAR("g_spawnshieldtime");
457 BADCVAR("g_start_delay");
458 BADCVAR("g_superspectate");
459 BADCVAR("g_tdm_teams_override");
461 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
464 BADCVAR("maxplayers");
465 BADCVAR("minplayers");
466 BADCVAR("minplayers_per_team");
467 BADCVAR("net_address");
469 BADCVAR("rcon_password");
470 BADCVAR("rcon_restricted_commands");
471 BADCVAR("rcon_restricted_password");
473 BADCVAR("sv_adminnick");
474 BADCVAR("sv_autoscreenshot");
475 BADCVAR("sv_autotaunt");
476 BADCVAR("sv_curl_defaulturl");
477 BADCVAR("sv_defaultcharacter");
478 BADCVAR("sv_defaultcharacterskin");
479 BADCVAR("sv_defaultplayercolors");
480 BADCVAR("sv_defaultplayermodel");
481 BADCVAR("sv_defaultplayerskin");
482 BADCVAR("sv_maxidle");
483 BADCVAR("sv_maxrate");
485 BADCVAR("sv_public");
486 BADCVAR("sv_ready_restart");
487 BADCVAR("sv_status_privacy");
489 BADCVAR("sv_vote_call");
490 BADCVAR("sv_vote_commands");
491 BADCVAR("sv_vote_majority_factor");
492 BADCVAR("sv_vote_master");
493 BADCVAR("sv_vote_master_commands");
494 BADCVAR("sv_vote_master_password");
495 BADCVAR("sv_vote_simple_majority_factor");
496 BADCVAR("teamplay_mode");
497 BADCVAR("timelimit_override");
498 BADPREFIX("g_warmup_");
499 BADPREFIX("sv_info_");
500 BADPREFIX("sv_ready_restart_");
502 // mutators that announce themselves properly to the server browser
503 BADCVAR("g_instagib");
504 BADCVAR("g_new_toys");
506 BADCVAR("g_grappling_hook");
507 BADCVAR("g_jetpack");
509 // temporary for testing
510 // TODO remove before 0.8.3 release
511 BADCVAR("g_ca_weaponarena");
512 BADCVAR("g_freezetag_weaponarena");
513 BADCVAR("g_lms_weaponarena");
514 BADCVAR("g_ctf_stalemate_time");
516 if(cvar_string("g_mod_balance") == "Testing")
518 // (temporary) while using the Testing balance, any weapon balance cvars are allowed to be changed
519 BADPREFIX("g_balance_");
528 cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
529 if(strlen(cvar_purechanges) > 16384)
531 cvar_purechanges = "// too many settings have been changed to show them here\n";
535 ++cvar_purechanges_count;
536 // WARNING: this variable is used for the server list
537 // NEVER dare to skip this code!
538 // Hacks to intentionally appearing as "pure server" even though you DO have
539 // modified settings may be punished by removal from the server list.
540 // You can do to the variables cvar_changes and cvar_purechanges all you want,
544 if(cvar_changes == "")
545 cvar_changes = "// this server runs at default server settings\n";
547 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
548 cvar_changes = strzone(cvar_changes);
549 if(cvar_purechanges == "")
550 cvar_purechanges = "// this server runs at default gameplay settings\n";
552 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
553 cvar_purechanges = strzone(cvar_purechanges);
557 bool RandomSeed_Send(entity this, entity to, int sf)
559 WriteHeader(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
560 WriteShort(MSG_ENTITY, this.cnt);
563 void RandomSeed_Think(entity this)
565 this.cnt = bound(0, floor(random() * 65536), 65535);
566 this.nextthink = time + 5;
570 void RandomSeed_Spawn()
572 randomseed = new_pure(randomseed);
573 setthink(randomseed, RandomSeed_Think);
574 Net_LinkEntity(randomseed, false, 0, RandomSeed_Send);
576 getthink(randomseed)(randomseed); // sets random seed and nextthink
579 spawnfunc(__init_dedicated_server)
581 // handler for _init/_init map (only for dedicated server initialization)
583 world_initialized = -1; // don't complain
585 delete_fn = remove_unsafely;
588 setthink(e, GotoFirstMap);
589 e.nextthink = time; // this is usually 1 at this point
591 e = new(info_player_deathmatch); // safeguard against player joining
593 // assign reflectively to avoid "assignment to world" warning
594 for (int i = 0, n = numentityfields(); i < n; ++i) {
595 string k = entityfieldname(i);
596 if (k == "classname") {
597 // safeguard against various stuff ;)
598 putentityfieldstring(i, this, "worldspawn");
603 // needs to be done so early because of the constants they create
606 static_init_precache();
608 IL_PUSH(g_spawnpoints, e); // just incase
611 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
614 void __init_dedicated_server_shutdown() {
618 STATIC_INIT_EARLY(maxclients)
621 for (entity head = nextent(NULL); head; head = nextent(head)) {
626 void default_delayedinit(entity this)
628 if(!scores_initialized)
629 ScoreRules_generic();
632 void InitGameplayMode()
636 // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
638 // assign reflectively to avoid "assignment to world" warning
639 int done = 0; for (int i = 0, n = numentityfields(); i < n; ++i) {
640 string k = entityfieldname(i); vector v = (k == "mins") ? mi_min : (k == "maxs") ? mi_max : '0 0 0';
642 putentityfieldstring(i, world, sprintf("%v", v));
643 if (++done == 2) break;
646 // currently, NetRadiant's limit is 131072 qu for each side
647 // distance from one corner of a 131072qu cube to the opposite corner is approx. 227023 qu
648 // set the distance according to map size but don't go over the limit to avoid issues with float precision
649 // in case somebody makes extremely large maps
650 max_shot_distance = min(230000, vlen(world.maxs - world.mins));
652 MapInfo_LoadMapSettings(mapname);
653 GameRules_teams(false);
655 if (!cvar_value_issafe(world.fog))
657 LOG_INFO("The current map contains a potentially harmful fog setting, ignored");
658 world.fog = string_null;
660 if(MapInfo_Map_fog != "")
662 if(MapInfo_Map_fog == "none")
663 world.fog = string_null;
665 world.fog = strzone(MapInfo_Map_fog);
667 clientstuff = strzone(MapInfo_Map_clientstuff);
669 MapInfo_ClearTemps();
671 gamemode_name = MapInfo_Type_ToText(MapInfo_LoadedGametype);
673 cache_mutatormsg = strzone("");
674 cache_lastmutatormsg = strzone("");
676 InitializeEntity(NULL, default_delayedinit, INITPRIO_GAMETYPE_FALLBACK);
679 void Map_MarkAsRecent(string m);
680 float world_already_spawned;
681 spawnfunc(worldspawn)
683 server_is_dedicated = boolean(stof(cvar_defstring("is_dedicated")));
685 bool wantrestart = false;
687 if (!server_is_dedicated)
689 // force unloading of server pk3 files when starting a listen server
690 // localcmd("\nfs_rescan\n"); // FIXME: does more harm than good, has unintended side effects. What we really want is to unload temporary pk3s only
691 // restore csqc_progname too
692 string expect = "csprogs.dat";
693 wantrestart = cvar_string("csqc_progname") != expect;
694 cvar_set("csqc_progname", expect);
698 // Try to use versioned csprogs from pk3
699 // Only ever use versioned csprogs.dat files on dedicated servers;
700 // we need to reset csqc_progname on clients ourselves, and it's easier if the client's release name is constant
701 string pk3csprogs = "csprogs-" WATERMARK ".dat";
702 // This always works; fall back to it if a versioned csprogs.dat is suddenly missing
703 string select = "csprogs.dat";
704 if (fexists(pk3csprogs)) select = pk3csprogs;
705 if (cvar_string("csqc_progname") != select)
707 cvar_set("csqc_progname", select);
710 // Check for updates on startup
711 // We do it this way for atomicity so that connecting clients still match the server progs and don't disconnect
712 int sentinel = fopen("progs.txt", FILE_READ);
715 string switchversion = fgets(sentinel);
717 if (switchversion != "" && switchversion != WATERMARK)
719 LOG_INFOF("Switching progs: " WATERMARK " -> %s", switchversion);
720 // if it doesn't exist, assume either:
721 // a) the current program was overwritten
722 // b) this is a client only update
723 string newprogs = sprintf("progs-%s.dat", switchversion);
724 if (fexists(newprogs))
726 cvar_set("sv_progs", newprogs);
729 string newcsprogs = sprintf("csprogs-%s.dat", switchversion);
730 if (fexists(newcsprogs))
732 cvar_set("csqc_progname", newcsprogs);
740 LOG_INFO("Restart requested");
741 changelevel(mapname);
742 // let initialization continue, shutdown depends on it
746 if(world_already_spawned)
747 error("world already spawned - you may have EXACTLY ONE worldspawn!");
748 world_already_spawned = true;
750 delete_fn = remove_safely; // during spawning, watch what you remove!
752 cvar_changes_init(); // do this very early now so it REALLY matches the server config
754 // needs to be done so early because of the constants they create
757 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
759 TemporaryDB = db_create();
764 // 1 FLICKER (first variety)
765 lightstyle(1, "mmnmmommommnonmmonqnmmo");
767 // 2 SLOW STRONG PULSE
768 lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
770 // 3 CANDLE (first variety)
771 lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
774 lightstyle(4, "mamamamamama");
777 lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
779 // 6 FLICKER (second variety)
780 lightstyle(6, "nmonqnmomnmomomno");
782 // 7 CANDLE (second variety)
783 lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
785 // 8 CANDLE (third variety)
786 lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
788 // 9 SLOW STROBE (fourth variety)
789 lightstyle(9, "aaaaaaaazzzzzzzz");
791 // 10 FLUORESCENT FLICKER
792 lightstyle(10, "mmamammmmammamamaaamammma");
794 // 11 SLOW PULSE NOT FADE TO BLACK
795 lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
797 // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
802 if(autocvar_g_campaign)
805 Map_MarkAsRecent(mapname);
807 PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
811 static_init_precache();
815 GameRules_limit_fallbacks();
817 if(warmup_limit == 0)
818 warmup_limit = (autocvar_timelimit > 0) ? autocvar_timelimit * 60 : autocvar_timelimit;
821 bot_waypoints_for_items = autocvar_g_waypoints_for_items;
822 if(bot_waypoints_for_items == 1)
823 if(this.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
824 bot_waypoints_for_items = 0;
826 WaypointSprite_Init();
828 GameLogInit(); // prepare everything
830 // changing the logic generating it is okay. But:
831 // it HAS to stay <= 64 chars
832 // character set: ASCII 33-126 without the following characters: : ; ' " \ $
833 if(autocvar_sv_eventlog)
835 string s = sprintf("%s.%s.%06d", itos(autocvar_sv_eventlog_files_counter), strftime(false, "%s"), floor(random() * 1000000));
836 matchid = strzone(s);
838 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
839 s = ":gameinfo:mutators:LIST";
841 MUTATOR_CALLHOOK(BuildMutatorsString, s);
842 s = M_ARGV(0, string);
844 // initialiation stuff, not good in the mutator system
845 if(!autocvar_g_use_ammunition)
846 s = strcat(s, ":no_use_ammunition");
848 // initialiation stuff, not good in the mutator system
849 if(autocvar_g_pickup_items == 0)
850 s = strcat(s, ":no_pickup_items");
851 if(autocvar_g_pickup_items > 0)
852 s = strcat(s, ":pickup_items");
854 // initialiation stuff, not good in the mutator system
855 if(autocvar_g_weaponarena != "0")
856 s = strcat(s, ":", autocvar_g_weaponarena, " arena");
858 // TODO to mutator system
859 if(autocvar_g_norecoil)
860 s = strcat(s, ":norecoil");
862 // TODO to mutator system
863 if(autocvar_g_powerups == 0)
864 s = strcat(s, ":no_powerups");
865 if(autocvar_g_powerups > 0)
866 s = strcat(s, ":powerups");
869 GameLogEcho(":gameinfo:end");
872 matchid = strzone(ftos(random()));
874 cvar_set("nextmap", "");
878 if(autocvar_g_campaign)
884 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
886 if(fexists(strcat("scripts/", mapname, ".arena")))
887 cvar_settemp("sv_q3acompat_machineshotgunswap", "1");
889 if(fexists(strcat("scripts/", mapname, ".defi")))
890 cvar_settemp("sv_q3defragcompat", "1");
892 if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
894 int fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
898 while((s = fgets(fd)))
900 int l = tokenize_console(s);
905 string trackname = argv(2);
906 LOG_INFO("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:");
907 LOG_INFO(" cdtrack ", trackname);
908 if (cvar_value_issafe(trackname))
910 string newstuff = strcat(clientstuff, "cd loop \"", trackname, "\"\n");
911 strcpy(clientstuff, newstuff);
914 else if(argv(0) == "fog")
916 LOG_INFO("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:");
917 LOG_INFO(" \"fog\" \"", s, "\"");
919 else if(argv(0) == "set")
921 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
922 LOG_INFO(" clientsettemp_for_type all ", argv(1), " ", argv(2));
924 else if(argv(0) != "//")
926 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
927 LOG_INFO(" clientsettemp_for_type all ", argv(0), " ", argv(1));
938 // set up information replies for clients and server to use
939 maplist_reply = strzone(getmaplist());
940 lsmaps_reply = strzone(getlsmaps());
941 monsterlist_reply = strzone(getmonsterlist());
942 for(int i = 0; i < 10; ++i)
944 string s = getrecords(i);
946 records_reply[i] = strzone(s);
948 ladder_reply = strzone(getladder());
949 rankings_reply = strzone(getrankings());
954 PingPLReport_Spawn();
958 if (!wantrestart) localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
960 // fill sv_curl_serverpackages from .serverpackage files
961 if (autocvar_sv_curl_serverpackages_auto)
963 string s = "csprogs-" WATERMARK ".txt";
964 // remove automatically managed files from the list to prevent duplicates
965 for (int i = 0, n = tokenize_console(cvar_string("sv_curl_serverpackages")); i < n; ++i)
967 string pkg = argv(i);
968 if (startsWith(pkg, "csprogs-")) continue;
969 if (endsWith(pkg, "-serverpackage.txt")) continue;
970 if (endsWith(pkg, ".serverpackage")) continue; // OLD legacy
973 // add automatically managed files to the list
974 #define X(match) MACRO_BEGIN \
975 int fd = search_begin(match, true, false); \
978 for (int i = 0, j = search_getsize(fd); i < j; ++i) \
980 s = cons(s, search_getfilename(fd, i)); \
985 X("*-serverpackage.txt");
986 X("*.serverpackage");
988 cvar_set("sv_curl_serverpackages", s);
991 // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
993 // physics/balance/config changes that count as mod
994 if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
995 modname = cvar_string("g_mod_physics");
996 if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance") && cvar_string("g_mod_balance") != "Testing")
997 modname = cvar_string("g_mod_balance");
998 if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
999 modname = cvar_string("g_mod_config");
1000 // extra mutators that deserve to count as mod
1001 MUTATOR_CALLHOOK(SetModname, modname);
1002 modname = M_ARGV(0, string);
1004 // save it for later
1005 modname = strzone(modname);
1007 WinningConditionHelper(this); // set worldstatus
1009 world_initialized = 1;
1010 __spawnfunc_spawn_all();
1015 //makestatic (this); // Who the f___ did that?
1019 string GetGametype()
1021 return MapInfo_Type_ToString(MapInfo_LoadedGametype);
1029 float Map_Count, Map_Current;
1030 string Map_Current_Name;
1032 // NOTE: this now expects the map list to be already tokenized and the count in Map_Count
1033 int GetMaplistPosition()
1035 string map = GetMapname();
1036 int idx = autocvar_g_maplist_index;
1042 if(map == argv(idx))
1049 for(int pos = 0; pos < Map_Count; ++pos)
1051 if(map == argv(pos))
1055 // resume normal maplist rotation if current map is not in g_maplist
1059 bool MapHasRightSize(string map)
1061 int minplayers = max(0, floor(autocvar_minplayers));
1063 minplayers = max(0, floor(autocvar_minplayers_per_team) * AvailableTeams());
1064 if (autocvar_g_maplist_check_waypoints
1065 && (currentbots || autocvar_bot_number || player_count < minplayers))
1067 string checkwp_msg = strcat("checkwp ", map);
1068 if(!fexists(strcat("maps/", map, ".waypoints")))
1070 LOG_TRACE(checkwp_msg, ": no waypoints");
1073 LOG_TRACE(checkwp_msg, ": has waypoints");
1076 if(autocvar_g_maplist_ignore_sizes)
1079 // open map size restriction file
1080 string opensize_msg = strcat("opensize ", map);
1081 float fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
1082 int player_limit = ((autocvar_g_maplist_sizes_count_maxplayers) ? GetPlayerLimit() : 0);
1083 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
1084 if(!autocvar_g_maplist_sizes_count_bots)
1085 pcount -= currentbots;
1088 opensize_msg = strcat(opensize_msg, ": ok, ");
1089 int mapmin = stoi(fgets(fh));
1090 int mapmax = stoi(fgets(fh));
1094 LOG_TRACE(opensize_msg, "not enough");
1097 if(mapmax && pcount > mapmax)
1099 LOG_TRACE(opensize_msg, "too many");
1102 LOG_TRACE(opensize_msg, "right size");
1105 LOG_TRACE(opensize_msg, ": not found");
1109 string Map_Filename(float position)
1111 return strcat("maps/", argv(position), ".bsp");
1114 void Map_MarkAsRecent(string m)
1116 cvar_set("g_maplist_mostrecent", strwords(cons(m, autocvar_g_maplist_mostrecent), max(0, autocvar_g_maplist_mostrecent_count)));
1119 float Map_IsRecent(string m)
1121 return strhasword(autocvar_g_maplist_mostrecent, m);
1124 float Map_Check(float position, float pass)
1128 map_next = argv(position);
1131 if(Map_IsRecent(map_next))
1134 filename = Map_Filename(position);
1135 if(MapInfo_CheckMap(map_next))
1139 if(MapHasRightSize(map_next))
1144 LOG_DEBUG( "Couldn't select '", filename, "'..." );
1149 void Map_Goto_SetStr(string nextmapname)
1151 if(getmapname_stored != "")
1152 strunzone(getmapname_stored);
1153 if(nextmapname == "")
1154 getmapname_stored = "";
1156 getmapname_stored = strzone(nextmapname);
1159 void Map_Goto_SetFloat(float position)
1161 cvar_set("g_maplist_index", ftos(position));
1162 Map_Goto_SetStr(argv(position));
1165 void Map_Goto(float reinit)
1167 MapInfo_LoadMap(getmapname_stored, reinit);
1170 // return codes of map selectors:
1171 // -1 = temporary failure (that is, try some method that is guaranteed to succeed)
1172 // -2 = permanent failure
1173 float MaplistMethod_Iterate() // usual method
1177 LOG_TRACE("Trying MaplistMethod_Iterate");
1179 for(pass = 1; pass <= 2; ++pass)
1181 for(i = 1; i < Map_Count; ++i)
1184 mapindex = (i + Map_Current) % Map_Count;
1185 if(Map_Check(mapindex, pass))
1192 float MaplistMethod_Repeat() // fallback method
1194 LOG_TRACE("Trying MaplistMethod_Repeat");
1196 if(Map_Check(Map_Current, 2))
1201 float MaplistMethod_Random() // random map selection
1205 LOG_TRACE("Trying MaplistMethod_Random");
1209 for(i = 0; i <= imax; ++i)
1212 mapindex = (Map_Current + floor(random() * (Map_Count - 1) + 1)) % Map_Count; // any OTHER map
1213 if(Map_Check(mapindex, 1))
1219 float MaplistMethod_Shuffle(float exponent) // more clever shuffling
1220 // the exponent sets a bias on the map selection:
1221 // the higher the exponent, the less likely "shortly repeated" same maps are
1223 float i, j, imax, insertpos;
1225 LOG_TRACE("Trying MaplistMethod_Shuffle");
1229 for(i = 0; i <= imax; ++i)
1233 // now reinsert this at another position
1234 insertpos = (random() ** (1 / exponent)); // ]0, 1]
1235 insertpos = insertpos * (Map_Count - 1); // ]0, Map_Count - 1]
1236 insertpos = ceil(insertpos) + 1; // {2, 3, 4, ..., Map_Count}
1237 LOG_TRACE("SHUFFLE: insert pos = ", ftos(insertpos));
1239 // insert the current map there
1241 for(j = 1; j < insertpos; ++j) // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
1242 newlist = strcat(newlist, " ", argv(j));
1243 newlist = strcat(newlist, " ", argv(0)); // now insert the just selected map
1244 for(j = insertpos; j < Map_Count; ++j) // i == Map_Count: no loop, has just been inserted as last
1245 newlist = strcat(newlist, " ", argv(j));
1246 newlist = substring(newlist, 1, strlen(newlist) - 1);
1247 cvar_set("g_maplist", newlist);
1248 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1250 // NOTE: the selected map has just been inserted at (insertpos-1)th position
1251 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
1252 if(Map_Check(Map_Current, 1))
1260 float i = Map_Count = 0;
1261 if(autocvar_g_maplist != "")
1263 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1264 for (i = 0; i < Map_Count; ++i)
1266 if (Map_Check(i, 2))
1273 bprint( "Maplist contains no usable maps! Resetting it to default map list.\n" );
1274 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags() | MAPINFO_FLAG_NOAUTOMAPLIST));
1275 if(autocvar_g_maplist_shuffle)
1277 if(!server_is_dedicated)
1278 localcmd("\nmenu_cmd sync\n");
1279 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1282 error("empty maplist, cannot select a new map");
1283 Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
1285 strcpy(Map_Current_Name, argv(Map_Current)); // will be automatically freed on exit thanks to DP
1286 // this may or may not be correct, but who cares, in the worst case a map
1287 // isn't chosen in the first pass that should have been
1296 if(autocvar_g_maplist_shuffle > 0)
1297 nextMap = MaplistMethod_Shuffle(autocvar_g_maplist_shuffle + 1);
1300 if(autocvar_g_maplist_selectrandom)
1301 nextMap = MaplistMethod_Random();
1304 nextMap = MaplistMethod_Iterate();
1307 nextMap = MaplistMethod_Repeat();
1311 Map_Goto_SetFloat(nextMap);
1312 return getmapname_stored;
1318 float DoNextMapOverride(float reinit)
1320 if(autocvar_g_campaign)
1322 CampaignPostIntermission();
1323 alreadychangedlevel = true;
1326 if(autocvar_quit_when_empty)
1328 if(player_count <= currentbots)
1331 alreadychangedlevel = true;
1335 if(autocvar_quit_and_redirect != "")
1337 redirection_target = strzone(autocvar_quit_and_redirect);
1338 alreadychangedlevel = true;
1341 if (!reinit && autocvar_samelevel) // if samelevel is set, stay on same level
1343 localcmd("restart\n");
1344 alreadychangedlevel = true;
1347 if(autocvar_nextmap != "")
1350 m = GameTypeVote_MapInfo_FixName(autocvar_nextmap);
1351 cvar_set("nextmap",m);
1353 if(!m || gametypevote)
1355 if(autocvar_sv_vote_gametype)
1361 if(MapInfo_CheckMap(m))
1365 alreadychangedlevel = true;
1369 if(!reinit && autocvar_lastlevel)
1371 cvar_settemp_restore();
1372 localcmd("set lastlevel 0\ntogglemenu 1\n");
1373 alreadychangedlevel = true;
1379 void GotoNextMap(float reinit)
1384 if (alreadychangedlevel)
1386 alreadychangedlevel = true;
1388 string nextMap = GetNextMap();
1390 error("Everything is broken - cannot find a next map. Please report this to the developers.");
1399 When the player presses attack or jump, change to the next level
1402 .float autoscreenshot;
1403 void IntermissionThink(entity this)
1405 FixIntermissionClient(this);
1407 float server_screenshot = (autocvar_sv_autoscreenshot && CS(this).cvar_cl_autoscreenshot);
1408 float client_screenshot = (CS(this).cvar_cl_autoscreenshot == 2);
1410 if( (server_screenshot || client_screenshot)
1411 && ((this.autoscreenshot > 0) && (time > this.autoscreenshot)) )
1413 this.autoscreenshot = -1;
1414 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"))); }
1418 if (time < intermission_exittime)
1421 if(!mapvote_initialized)
1422 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)))
1429 ===============================================================================
1433 ===============================================================================
1436 void DumpStats(float final)
1445 to_console = autocvar_sv_logscores_console;
1446 to_eventlog = autocvar_sv_eventlog;
1447 to_file = autocvar_sv_logscores_file;
1451 to_console = true; // always print printstats replies
1452 to_eventlog = false; // but never print them to the event log
1456 if(autocvar_sv_eventlog_console)
1457 to_console = false; // otherwise we get the output twice
1463 s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1473 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1477 fputs(file, strcat(s, "\n"));
1480 s = strcat(":labels:player:", GetPlayerScoreString(NULL, 0));
1486 fputs(file, strcat(s, "\n"));
1488 FOREACH_CLIENT(IS_REAL_CLIENT(it) || (IS_BOT_CLIENT(it) && autocvar_sv_logscores_bots), {
1489 s = strcat(":player:see-labels:", GetPlayerScoreString(it, 0), ":");
1490 s = strcat(s, ftos(rint(time - CS(it).jointime)), ":");
1491 if(IS_PLAYER(it) || MUTATOR_CALLHOOK(GetPlayerStatus, it))
1492 s = strcat(s, ftos(it.team), ":");
1494 s = strcat(s, "spectator:");
1497 LOG_INFO(s, playername(it, false));
1499 GameLogEcho(strcat(s, ftos(it.playerid), ":", playername(it, false)));
1501 fputs(file, strcat(s, playername(it, false), "\n"));
1506 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1512 fputs(file, strcat(s, "\n"));
1514 for(i = 1; i < 16; ++i)
1516 s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1517 s = strcat(s, ":", ftos(i));
1523 fputs(file, strcat(s, "\n"));
1530 GameLogEcho(":end");
1533 fputs(file, ":end\n");
1538 void FixIntermissionClient(entity e)
1540 if(!e.autoscreenshot) // initial call
1542 e.autoscreenshot = time + 0.8; // used for autoscreenshot
1543 SetResourceExplicit(e, RES_HEALTH, -2342);
1544 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1545 for (int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1547 .entity weaponentity = weaponentities[slot];
1548 if(e.(weaponentity))
1550 e.(weaponentity).effects = EF_NODRAW;
1551 if (e.(weaponentity).weaponchild)
1552 e.(weaponentity).weaponchild.effects = EF_NODRAW;
1555 if(IS_REAL_CLIENT(e))
1557 stuffcmd(e, "\nscr_printspeed 1000000\n");
1558 RandomSelection_Init();
1559 FOREACH_WORD(autocvar_sv_intermission_cdtrack, true, {
1560 RandomSelection_AddString(it, 1, 1);
1562 if (RandomSelection_chosen_string != "")
1564 stuffcmd(e, sprintf("\ncd loop %s\n", RandomSelection_chosen_string));
1567 WriteByte(MSG_ONE, SVC_INTERMISSION);
1573 go to the next level for deathmatch
1574 only called if a time or frag limit has expired
1578 game_stopped = true;
1579 intermission_running = 1; // game over
1581 // enforce a wait time before allowing changelevel
1582 if(player_count > 0)
1583 intermission_exittime = time + autocvar_sv_mapchange_delay;
1585 intermission_exittime = -1;
1588 WriteByte (MSG_ALL, SVC_CDTRACK);
1589 WriteByte (MSG_ALL, 3);
1590 WriteByte (MSG_ALL, 3);
1591 // done in FixIntermission
1594 //pos = FindIntermission ();
1601 PlayerStats_GameReport(true);
1602 WeaponStats_Shutdown();
1604 Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_Null); // kill all centerprints now
1606 if(autocvar_sv_eventlog)
1607 GameLogEcho(":gameover");
1611 FOREACH_CLIENT(IS_PLAYER(it), {
1612 FixIntermissionClient(it);
1614 bprint(playername(it, false), " ^7wins.\n");
1617 target_music_kill();
1619 if(autocvar_g_campaign)
1620 CampaignPreIntermission();
1622 MUTATOR_CALLHOOK(MatchEnd);
1624 localcmd("\nsv_hook_gameend\n");
1628 float InitiateSuddenDeath()
1630 // Check first whether normal overtimes could be added before initiating suddendeath mode
1631 // - for this timelimit_overtime needs to be >0 of course
1632 // - also check the winning condition calculated in the previous frame and only add normal overtime
1633 // again, if at the point at which timelimit would be extended again, still no winner was found
1634 if (!autocvar_g_campaign && checkrules_overtimesadded >= 0
1635 && (checkrules_overtimesadded < autocvar_timelimit_overtimes || autocvar_timelimit_overtimes < 0)
1636 && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1638 return 1; // need to call InitiateOvertime later
1642 if(!checkrules_suddendeathend)
1644 if(autocvar_g_campaign)
1645 checkrules_suddendeathend = time; // no suddendeath in campaign
1647 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1648 if(g_race && !g_race_qualifying)
1649 race_StartCompleting();
1655 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1657 ++checkrules_overtimesadded;
1658 //add one more overtime by simply extending the timelimit
1659 cvar_set("timelimit", ftos(autocvar_timelimit + autocvar_timelimit_overtime));
1660 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime * 60);
1663 float GetWinningCode(float fraglimitreached, float equality)
1665 if(autocvar_g_campaign == 1)
1667 if(fraglimitreached)
1676 if(fraglimitreached)
1677 return WINNING_STARTSUDDENDEATHOVERTIME;
1679 return WINNING_NEVER;
1683 if(fraglimitreached)
1691 // set the .winning flag for exactly those players with a given field value
1692 void SetWinners(.float field, float value)
1694 FOREACH_CLIENT(IS_PLAYER(it), { it.winning = (it.(field) == value); });
1697 // set the .winning flag for those players with a given field value
1698 void AddWinners(.float field, float value)
1700 FOREACH_CLIENT(IS_PLAYER(it), {
1701 if(it.(field) == value)
1706 // clear the .winning flags
1709 FOREACH_CLIENT(IS_PLAYER(it), { it.winning = 0; });
1712 void ShuffleMaplist()
1714 cvar_set("g_maplist", shufflewords(autocvar_g_maplist));
1718 float WinningCondition_Scores(float limit, float leadlimit)
1720 // TODO make everything use THIS winning condition (except LMS)
1721 WinningConditionHelper(NULL);
1725 for (int i = 1; i < 5; ++i)
1727 Team_SetTeamScore(Team_GetTeamFromIndex(i),
1728 TeamScore_GetCompareValue(Team_IndexToTeam(i)));
1733 if(WinningConditionHelper_winner)
1734 WinningConditionHelper_winner.winning = 1;
1735 if(WinningConditionHelper_winnerteam >= 0)
1736 SetWinners(team, WinningConditionHelper_winnerteam);
1738 if(WinningConditionHelper_lowerisbetter)
1740 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1741 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1745 if(WinningConditionHelper_zeroisworst)
1746 leadlimit = 0; // not supported in this mode
1748 if(MUTATOR_CALLHOOK(Scores_CountFragsRemaining))
1751 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1757 fragsleft = FLOAT_MAX;
1758 float leadingfragsleft = FLOAT_MAX;
1760 fragsleft = limit - WinningConditionHelper_topscore;
1762 leadingfragsleft = WinningConditionHelper_secondscore + leadlimit - WinningConditionHelper_topscore;
1764 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1765 fragsleft = max(fragsleft, leadingfragsleft);
1767 fragsleft = min(fragsleft, leadingfragsleft);
1770 if (fragsleft_last != fragsleft) // do not announce same remaining frags multiple times
1773 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_1);
1774 else if (fragsleft == 2)
1775 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_2);
1776 else if (fragsleft == 3)
1777 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_3);
1779 fragsleft_last = fragsleft;
1783 bool fraglimit_reached = (limit && WinningConditionHelper_topscore >= limit);
1784 bool leadlimit_reached = (leadlimit && WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1787 // only respect leadlimit_and_fraglimit when both limits are set or the game will never end
1788 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1789 limit_reached = (fraglimit_reached && leadlimit_reached);
1791 limit_reached = (fraglimit_reached || leadlimit_reached);
1793 return GetWinningCode(
1794 WinningConditionHelper_topscore && limit_reached,
1795 WinningConditionHelper_equality
1799 float WinningCondition_RanOutOfSpawns()
1801 if(have_team_spawns <= 0)
1804 if(!autocvar_g_spawn_useallspawns)
1807 if(!some_spawn_has_been_used)
1810 for (int i = 1; i < 5; ++i)
1812 Team_SetTeamScore(Team_GetTeamFromIndex(i), 0);
1815 FOREACH_CLIENT(IS_PLAYER(it) && !IS_DEAD(it),
1817 if (Team_IsValidTeam(it.team))
1819 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1823 IL_EACH(g_spawnpoints, true,
1825 if (Team_IsValidTeam(it.team))
1827 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1832 float team1_score = Team_GetTeamScore(Team_GetTeamFromIndex(1));
1833 float team2_score = Team_GetTeamScore(Team_GetTeamFromIndex(2));
1834 float team3_score = Team_GetTeamScore(Team_GetTeamFromIndex(3));
1835 float team4_score = Team_GetTeamScore(Team_GetTeamFromIndex(4));
1836 if(team1_score + team2_score + team3_score + team4_score == 0)
1838 checkrules_equality = true;
1841 else if(team1_score + team2_score + team3_score + team4_score == 1)
1846 else if(team2_score)
1848 else if(team3_score)
1850 else // if(team4_score)
1852 entity balance = TeamBalance_CheckAllowedTeams(NULL);
1853 for(i = 0; i < MAX_TEAMSCORE; ++i)
1855 for (int j = 1; j <= NUM_TEAMS; ++j)
1861 if (!TeamBalance_IsTeamAllowed(balance, j))
1865 TeamScore_AddToTeam(Team_IndexToTeam(j), i, -1000);
1869 AddWinners(team, t);
1880 Exit deathmatch games upon conditions
1883 void CheckRules_World()
1890 if (intermission_running) // someone else quit the game already
1892 if(player_count == 0) // Nobody there? Then let's go to the next map
1894 // this will actually check the player count in the next frame
1895 // again, but this shouldn't hurt
1899 float timelimit = autocvar_timelimit * 60;
1900 float fraglimit = autocvar_fraglimit;
1901 float leadlimit = autocvar_leadlimit;
1902 if (leadlimit < 0) leadlimit = 0;
1904 if(warmup_stage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1907 timelimit = 0; // timelimit is not made for warmup
1909 fraglimit = 0; // no fraglimit for now
1910 leadlimit = 0; // no leadlimit for now
1915 timelimit += game_starttime;
1917 else if (timelimit < 0)
1927 if(checkrules_suddendeathend)
1929 if(!checkrules_suddendeathwarning)
1931 checkrules_suddendeathwarning = true;
1932 if(g_race && !g_race_qualifying)
1933 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_RACE_FINISHLAP);
1935 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_FRAG);
1940 if (timelimit && time >= timelimit)
1942 if(g_race && (g_race_qualifying == 2) && timelimit > 0)
1945 float playerswithlaps;
1947 totalplayers = playerswithlaps = readyplayers = 0;
1948 FOREACH_CLIENT(IS_PLAYER(it), {
1950 if(GameRules_scoring_add(it, RACE_FASTEST, 0))
1956 // at least 2 of the players have completed a lap: start the RACE
1957 // otherwise, the players should end the qualifying on their own
1958 if(readyplayers || playerswithlaps >= 2)
1960 checkrules_suddendeathend = 0;
1961 ReadyRestart(); // go to race
1965 wantovertime |= InitiateSuddenDeath();
1968 wantovertime |= InitiateSuddenDeath();
1972 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1978 int checkrules_status = WinningCondition_RanOutOfSpawns();
1979 if(checkrules_status == WINNING_YES)
1980 bprint("Hey! Someone ran out of spawns!\n");
1981 else if(MUTATOR_CALLHOOK(CheckRules_World, checkrules_status, timelimit, fraglimit))
1982 checkrules_status = M_ARGV(0, float);
1984 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
1986 if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
1988 checkrules_status = WINNING_NEVER;
1989 checkrules_overtimesadded = -1;
1990 wantovertime |= InitiateSuddenDeath();
1993 if(checkrules_status == WINNING_NEVER)
1994 // equality cases! Nobody wins if the overtime ends in a draw.
1999 if(checkrules_status == WINNING_NEVER)
2002 checkrules_status = WINNING_YES;
2005 if(checkrules_suddendeathend)
2006 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
2007 checkrules_status = WINNING_YES;
2009 if(checkrules_status == WINNING_YES)
2011 //print("WINNING\n");
2016 string GotoMap(string m)
2018 m = GameTypeVote_MapInfo_FixName(m);
2020 return "The map you suggested is not available on this server.";
2021 if (!autocvar_sv_vote_gametype)
2022 if(!MapInfo_CheckMap(m))
2023 return "The map you suggested does not support the current game mode.";
2024 cvar_set("nextmap", m);
2025 cvar_set("timelimit", "-1");
2026 if(mapvote_initialized || alreadychangedlevel)
2028 if(DoNextMapOverride(0))
2029 return "Map switch initiated.";
2031 return "Hm... no. For some reason I like THIS map more.";
2034 return "Map switch will happen after scoreboard.";
2037 bool autocvar_sv_gameplayfix_multiplethinksperframe = true;
2038 void RunThink(entity this)
2040 // don't let things stay in the past.
2041 // it is possible to start that way by a trigger with a local time.
2042 if(this.nextthink <= 0 || this.nextthink > time + frametime)
2045 float oldtime = time; // do we need to save this?
2047 for (int iterations = 0; iterations < 128 && !wasfreed(this); iterations++)
2049 time = max(oldtime, this.nextthink);
2053 getthink(this)(this);
2054 // mods often set nextthink to time to cause a think every frame,
2055 // we don't want to loop in that case, so exit if the new nextthink is
2056 // <= the time the qc was told, also exit if it is past the end of the
2058 if(this.nextthink <= time || this.nextthink > oldtime + frametime || !autocvar_sv_gameplayfix_multiplethinksperframe)
2065 bool autocvar_sv_freezenonclients;
2066 bool autocvar_sv_gameplayfix_delayprojectiles = false;
2067 void Physics_Frame()
2069 if(autocvar_sv_freezenonclients)
2072 IL_EACH(g_moveables, true,
2074 if(IS_CLIENT(it) || it.classname == "" || it.move_movetype == MOVETYPE_PHYSICS)
2077 //set_movetype(it, it.move_movetype);
2078 // inline the set_movetype function, since this is called a lot
2079 it.movetype = (it.move_qcphysics) ? MOVETYPE_QCENTITY : it.move_movetype;
2081 if(it.move_qcphysics && it.move_movetype != MOVETYPE_NONE)
2082 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2084 if(it.movetype >= MOVETYPE_USER_FIRST && it.movetype <= MOVETYPE_USER_LAST) // these cases have no think handling
2086 if(it.move_movetype == MOVETYPE_PUSH || it.move_movetype == MOVETYPE_FAKEPUSH)
2087 continue; // these movetypes have no regular think function
2088 // handle thinking here
2089 if (getthink(it) && it.nextthink > 0 && it.nextthink <= time + frametime)
2094 if(autocvar_sv_gameplayfix_delayprojectiles >= 0)
2097 IL_EACH(g_moveables, it.move_qcphysics,
2099 if(IS_CLIENT(it) || it.classname == "" || it.move_movetype == MOVETYPE_NONE)
2101 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2105 void systems_update();
2108 anticheat_endframe();
2112 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2113 entity e = IS_SPEC(it) ? it.enemy : it;
2114 if (e.typehitsound) {
2115 STAT(TYPEHIT_TIME, it) = time;
2116 } else if (e.killsound) {
2117 STAT(KILL_TIME, it) = time;
2118 } else if (e.damage_dealt) {
2119 STAT(HIT_TIME, it) = time;
2120 STAT(DAMAGE_DEALT_TOTAL, it) += ceil(e.damage_dealt);
2123 // add 1 frametime because after this, engine SV_Physics
2124 // increases time by a frametime and then networks the frame
2125 // add another frametime because client shows everything with
2126 // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2128 float altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2129 FOREACH_CLIENT(true, {
2130 it.typehitsound = false;
2131 it.damage_dealt = 0;
2132 it.killsound = false;
2133 antilag_record(it, CS(it), altime);
2135 IL_EACH(g_monsters, true,
2137 antilag_record(it, it, altime);
2139 IL_EACH(g_projectiles, it.classname == "nade",
2141 antilag_record(it, it, altime);
2150 * returns true if redirecting
2152 float redirection_timeout;
2153 float redirection_nextthink;
2154 float RedirectionThink()
2156 float clients_found;
2158 if(redirection_target == "")
2161 if(!redirection_timeout)
2163 cvar_set("sv_public", "-2");
2164 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2165 if(redirection_target == "self")
2166 bprint("^3SERVER NOTICE:^7 restarting the server\n");
2168 bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2171 if(time < redirection_nextthink)
2174 redirection_nextthink = time + 1;
2177 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2179 LOG_INFO("Redirecting: sending connect command to ", it.netname);
2180 if(redirection_target == "self")
2181 stuffcmd(it, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2183 stuffcmd(it, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2187 LOG_INFO("Redirecting: ", ftos(clients_found), " clients left.");
2189 if(time > redirection_timeout || clients_found == 0)
2190 localcmd("\nwait; wait; wait; quit\n");
2197 // Loaded from a save game
2198 // some things then break, so let's work around them...
2200 // Progs DB (capture records)
2201 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2205 MapInfo_Enumerate();
2206 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2209 TargetMusic_RestoreGame();
2216 if(world_initialized > 0)
2218 world_initialized = 0;
2220 // if a timeout is active, reset the slowmo value to normal
2221 if(timeout_status == TIMEOUT_ACTIVE)
2222 cvar_set("slowmo", ftos(orig_slowmo));
2224 LOG_TRACE("Saving persistent data...");
2227 // playerstats with unfinished match
2228 PlayerStats_GameReport(false);
2230 if(!cheatcount_total)
2232 if(autocvar_sv_db_saveasdump)
2233 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2235 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2237 if(autocvar_developer > 0)
2239 if(autocvar_sv_db_saveasdump)
2240 db_dump(TemporaryDB, "server-temp.db");
2242 db_save(TemporaryDB, "server-temp.db");
2244 CheatShutdown(); // must be after cheatcount check
2245 db_close(ServerProgsDB);
2246 db_close(TemporaryDB);
2247 LOG_TRACE("Saving persistent data... done!");
2248 // tell the bot system the game is ending now
2251 WeaponStats_Shutdown();
2254 else if(world_initialized == 0)
2256 LOG_INFO("NOTE: crashed before even initializing the world, not saving persistent data");
2260 __init_dedicated_server_shutdown();