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/sv_rules.qh"
27 #include "../common/mapinfo.qh"
28 #include "../common/monsters/_mod.qh"
29 #include "../common/monsters/sv_monsters.qh"
30 #include "../common/vehicles/all.qh"
31 #include "../common/notifications/all.qh"
32 #include "../common/physics/player.qh"
33 #include "../common/playerstats.qh"
34 #include "../common/stats.qh"
35 #include "../common/teams.qh"
36 #include "../common/mapobjects/trigger/secret.qh"
37 #include "../common/mapobjects/target/music.qh"
38 #include "../common/util.qh"
39 #include "../common/items/_mod.qh"
40 #include <common/weapons/_all.qh>
41 #include "../common/state.qh"
43 const float LATENCY_THINKRATE = 10;
48 void PingPLReport_Think(entity this)
53 delta = 3 / maxclients;
54 if(delta < sys_frametime)
56 this.nextthink = time + delta;
58 e = edict_num(this.cnt + 1);
59 if(IS_CLIENT(e) && IS_REAL_CLIENT(e))
61 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
62 WriteByte(MSG_BROADCAST, this.cnt);
63 WriteShort(MSG_BROADCAST, bound(1, CS(e).ping, 65535));
64 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_packetloss * 255), 255));
65 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_movementloss * 255), 255));
67 // record latency times for clients throughout the match so we can report it to playerstats
68 if(time > (CS(e).latency_time + LATENCY_THINKRATE))
70 CS(e).latency_sum += CS(e).ping;
71 CS(e).latency_cnt += 1;
72 CS(e).latency_time = time;
73 //print("sum: ", ftos(CS(e).latency_sum), ", cnt: ", ftos(CS(e).latency_cnt), ", avg: ", ftos(CS(e).latency_sum / CS(e).latency_cnt), ".\n");
78 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
79 WriteByte(MSG_BROADCAST, this.cnt);
80 WriteShort(MSG_BROADCAST, 0);
81 WriteByte(MSG_BROADCAST, 0);
82 WriteByte(MSG_BROADCAST, 0);
84 this.cnt = (this.cnt + 1) % maxclients;
86 void PingPLReport_Spawn()
88 pingplreport = new_pure(pingplreport);
89 setthink(pingplreport, PingPLReport_Think);
90 pingplreport.nextthink = time;
93 const float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
94 string redirection_target;
95 float world_initialized;
97 void SetDefaultAlpha()
99 if (!MUTATOR_CALLHOOK(SetDefaultAlpha))
101 default_player_alpha = autocvar_g_player_alpha;
102 if(default_player_alpha == 0)
103 default_player_alpha = 1;
104 default_weapon_alpha = default_player_alpha;
108 void GotoFirstMap(entity this)
111 if(autocvar__sv_init)
113 // cvar_set("_sv_init", "0");
114 // we do NOT set this to 0 any more, so someone "accidentally" changing
115 // to this "init" map on a dedicated server will cause no permanent
117 if(autocvar_g_maplist_shuffle)
119 n = tokenizebyseparator(autocvar_g_maplist, " ");
120 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
123 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
125 if(!DoNextMapOverride(1))
133 this.nextthink = time;
137 this.nextthink = time + 1;
138 LOG_INFO("Waiting for _sv_init being set to 1 by initialization scripts...");
142 void cvar_changes_init()
146 float n, i, adding, pureadding;
148 strfree(cvar_changes);
149 strfree(cvar_purechanges);
150 cvar_purechanges_count = 0;
153 buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
159 for(i = 0; i < n; ++i)
161 k = bufstr_get(h, i);
163 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
164 #define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
165 #define BADCVAR(p) if(k == p) continue
167 // general excludes and namespaces for server admin used cvars
168 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
172 BADPREFIX("cvar_check_");
174 BADCVAR("g_configversion");
175 BADCVAR("halflifebsp");
176 BADCVAR("sv_mapformat_is_quake2");
177 BADCVAR("sv_mapformat_is_quake3");
178 BADPREFIX("sv_world");
184 BADPREFIX("scoreboard_");
185 BADPREFIX("g_campaign");
186 BADPREFIX("g_waypointsprite_");
192 BADPREFIX("net_slist_");
198 BADPREFIX("sensitivity");
199 BADPREFIX("userbind");
202 BADPREFIX("crosshair");
203 BADCVAR("mod_q3bsp_lightmapmergepower");
204 BADCVAR("mod_q3bsp_nolightmaps");
206 BADCVAR("mastervolume");
208 BADCVAR("bgmvolume");
209 BADCVAR("in_pitch_min");
210 BADCVAR("in_pitch_max");
213 BADCVAR("developer");
214 BADCVAR("log_dest_udp");
215 BADCVAR("net_address");
216 BADCVAR("net_address_ipv6");
218 BADCVAR("savedgamecfg");
219 BADCVAR("serverconfig");
220 BADCVAR("sv_autoscreenshot");
221 BADCVAR("sv_heartbeatperiod");
222 BADCVAR("sv_vote_master_password");
223 BADCVAR("sys_colortranslation");
224 BADCVAR("sys_specialcharactertranslation");
225 BADCVAR("timeformat");
226 BADCVAR("timestamps");
227 BADCVAR("g_require_stats");
228 BADPREFIX("developer_");
230 BADPREFIX("g_banned_list");
231 BADPREFIX("g_require_stats_");
232 BADPREFIX("g_chat_flood_");
233 BADPREFIX("g_ghost_items");
234 BADPREFIX("g_playerstats_");
235 BADPREFIX("g_voice_flood_");
236 BADPREFIX("log_file");
239 BADPREFIX("sv_allowdownloads");
240 BADPREFIX("sv_autodemo");
241 BADPREFIX("sv_curl_");
242 BADPREFIX("sv_eventlog");
243 BADPREFIX("sv_logscores_");
244 BADPREFIX("sv_master");
245 BADPREFIX("sv_weaponstats_");
246 BADPREFIX("sv_waypointsprite_");
247 BADCVAR("rescan_pending");
249 // these can contain player IDs, so better hide
250 BADPREFIX("g_forced_team_");
251 BADCVAR("sv_muteban_list");
252 BADCVAR("sv_voteban_list");
253 BADCVAR("sv_allow_customplayermodels_idlist");
254 BADCVAR("sv_allow_customplayermodels_speciallist");
257 BADCVAR("fraglimit");
259 BADCVAR("g_assault");
261 BADCVAR("g_ca_teams");
262 BADCVAR("g_conquest");
267 BADCVAR("g_domination");
268 BADCVAR("g_domination_default_teams");
270 BADCVAR("g_duel_not_dm_maps");
271 BADCVAR("g_freezetag");
272 BADCVAR("g_freezetag_teams");
273 BADCVAR("g_invasion_teams");
274 BADCVAR("g_invasion_type");
275 BADCVAR("g_jailbreak");
276 BADCVAR("g_jailbreak_teams");
277 BADCVAR("g_keepaway");
278 BADCVAR("g_keyhunt");
279 BADCVAR("g_keyhunt_teams");
281 BADCVAR("g_nexball");
282 BADCVAR("g_onslaught");
284 BADCVAR("g_race_laps_limit");
285 BADCVAR("g_race_qualifying_timelimit");
286 BADCVAR("g_race_qualifying_timelimit_override");
287 BADCVAR("g_runematch");
288 BADCVAR("g_shootfromeye");
291 BADCVAR("g_tdm_on_dm_maps");
292 BADCVAR("g_tdm_teams");
294 BADCVAR("leadlimit");
297 BADCVAR("timelimit");
298 BADCVAR("g_mapinfo_settemp_acl");
299 BADCVAR("g_mapinfo_ignore_warnings");
300 BADCVAR("g_maplist_ignore_sizes");
301 BADCVAR("g_maplist_sizes_count_bots");
305 BADCVAR("g_maplist");
306 BADCVAR("g_maplist_mostrecent");
310 d = cvar_defstring(k);
316 cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
317 if(strlen(cvar_changes) > 16384)
319 cvar_changes = "// too many settings have been changed to show them here\n";
324 // now check if the changes are actually gameplay relevant
326 // does nothing gameplay relevant
327 BADCVAR("captureleadlimit_override");
328 BADCVAR("condump_stripcolors");
329 BADCVAR("gameversion");
330 BADCVAR("fs_gamedir");
331 BADCVAR("g_allow_oldvortexbeam");
332 BADCVAR("g_balance_kill_delay");
333 BADCVAR("g_buffs_pickup_anyway");
334 BADCVAR("g_buffs_randomize");
335 BADCVAR("g_buffs_randomize_teamplay");
336 BADCVAR("g_campcheck_distance");
337 BADCVAR("g_chatsounds");
338 BADCVAR("g_ca_point_leadlimit");
339 BADCVAR("g_ca_point_limit");
340 BADCVAR("g_ctf_captimerecord_always");
341 BADCVAR("g_ctf_flag_glowtrails");
342 BADCVAR("g_ctf_dynamiclights");
343 BADCVAR("g_ctf_flag_pickup_verbosename");
344 BADPRESUFFIX("g_ctf_flag_", "_model");
345 BADPRESUFFIX("g_ctf_flag_", "_skin");
346 BADCVAR("g_domination_point_leadlimit");
347 BADCVAR("g_forced_respawn");
348 BADCVAR("g_freezetag_point_leadlimit");
349 BADCVAR("g_freezetag_point_limit");
350 BADCVAR("g_glowtrails");
352 BADCVAR("g_casings");
353 BADCVAR("g_invasion_point_limit");
354 BADCVAR("g_jump_grunt");
355 BADCVAR("g_keepaway_ballcarrier_effects");
356 BADCVAR("g_keepawayball_effects");
357 BADCVAR("g_keyhunt_point_leadlimit");
358 BADCVAR("g_nexball_goalleadlimit");
359 BADCVAR("g_new_toys_autoreplace");
360 BADCVAR("g_new_toys_use_pickupsound");
361 BADCVAR("g_physics_predictall");
362 BADCVAR("g_piggyback");
363 BADCVAR("g_playerclip_collisions");
364 BADCVAR("g_spawn_alloweffects");
365 BADCVAR("g_tdm_point_leadlimit");
366 BADCVAR("g_tdm_point_limit");
367 BADCVAR("leadlimit_and_fraglimit");
368 BADCVAR("leadlimit_override");
370 BADCVAR("sv_announcer");
371 BADCVAR("sv_checkforpacketsduringsleep");
372 BADCVAR("sv_damagetext");
373 BADCVAR("sv_db_saveasdump");
374 BADCVAR("sv_intermission_cdtrack");
375 BADCVAR("sv_mapchange_delay");
376 BADCVAR("sv_minigames");
377 BADCVAR("sv_namechangetimer");
378 BADCVAR("sv_precacheplayermodels");
380 BADCVAR("sv_stepheight");
381 BADCVAR("sv_timeout");
382 BADCVAR("sv_weapons_modeloverride");
383 BADCVAR("w_prop_interval");
385 BADPREFIX("crypto_");
386 BADPREFIX("gameversion_");
387 BADPREFIX("g_chat_");
388 BADPREFIX("g_ctf_captimerecord_");
389 BADPREFIX("g_hats_");
390 BADPREFIX("g_maplist_");
392 BADPREFIX("g_respawn_");
394 BADPREFIX("notification_");
397 BADPREFIX("sv_allow_");
398 BADPREFIX("sv_cullentities_");
399 BADPREFIX("sv_maxidle_");
400 BADPREFIX("sv_minigames_");
401 BADPREFIX("sv_radio_");
402 BADPREFIX("sv_timeout_");
403 BADPREFIX("sv_vote_");
404 BADPREFIX("timelimit_");
406 // allowed changes to server admins (please sync this to server.cfg)
410 // :%s,//\([^ ]*\).*,BADCVAR("\1");,
412 // yes, this does contain some redundant stuff, don't really care
413 BADPREFIX("bot_ai_");
414 BADCVAR("bot_config_file");
415 BADCVAR("bot_number");
416 BADCVAR("bot_prefix");
417 BADCVAR("bot_suffix");
418 BADCVAR("capturelimit_override");
419 BADCVAR("fraglimit_override");
421 BADCVAR("g_antilag");
422 BADCVAR("g_balance_teams");
423 BADCVAR("g_balance_teams_prevent_imbalance");
424 BADCVAR("g_balance_teams_scorefactor");
425 BADCVAR("g_ban_sync_trusted_servers");
426 BADCVAR("g_ban_sync_uri");
428 BADCVAR("g_ca_teams_override");
429 BADCVAR("g_ctf_fullbrightflags");
430 BADCVAR("g_ctf_ignore_frags");
431 BADCVAR("g_ctf_leaderboard");
432 BADCVAR("g_domination_point_limit");
433 BADCVAR("g_domination_teams_override");
434 BADCVAR("g_freezetag_teams_override");
435 BADCVAR("g_friendlyfire");
436 BADCVAR("g_fullbrightitems");
437 BADCVAR("g_fullbrightplayers");
438 BADCVAR("g_keyhunt_point_limit");
439 BADCVAR("g_keyhunt_teams_override");
440 BADCVAR("g_lms_lives_override");
441 BADCVAR("g_maplist");
442 BADCVAR("g_maxplayers");
443 BADCVAR("g_mirrordamage");
444 BADCVAR("g_nexball_goallimit");
445 BADCVAR("g_norecoil");
446 BADCVAR("g_physics_clientselect");
448 BADCVAR("g_powerups");
449 BADCVAR("g_player_brightness");
450 BADCVAR("g_rocket_flying");
451 BADCVAR("g_rocket_flying_disabledelays");
452 BADCVAR("g_spawnshieldtime");
453 BADCVAR("g_start_delay");
454 BADCVAR("g_superspectate");
455 BADCVAR("g_tdm_teams_override");
457 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
460 BADCVAR("maxplayers");
461 BADCVAR("minplayers");
462 BADCVAR("minplayers_per_team");
463 BADCVAR("net_address");
465 BADCVAR("rcon_password");
466 BADCVAR("rcon_restricted_commands");
467 BADCVAR("rcon_restricted_password");
469 BADCVAR("sv_adminnick");
470 BADCVAR("sv_autoscreenshot");
471 BADCVAR("sv_autotaunt");
472 BADCVAR("sv_curl_defaulturl");
473 BADCVAR("sv_defaultcharacter");
474 BADCVAR("sv_defaultcharacterskin");
475 BADCVAR("sv_defaultplayercolors");
476 BADCVAR("sv_defaultplayermodel");
477 BADCVAR("sv_defaultplayerskin");
478 BADCVAR("sv_maxidle");
479 BADCVAR("sv_maxrate");
481 BADCVAR("sv_public");
482 BADCVAR("sv_ready_restart");
483 BADCVAR("sv_status_privacy");
485 BADCVAR("sv_vote_call");
486 BADCVAR("sv_vote_commands");
487 BADCVAR("sv_vote_majority_factor");
488 BADCVAR("sv_vote_master");
489 BADCVAR("sv_vote_master_commands");
490 BADCVAR("sv_vote_master_password");
491 BADCVAR("sv_vote_simple_majority_factor");
492 BADCVAR("teamplay_mode");
493 BADCVAR("timelimit_override");
494 BADPREFIX("g_warmup_");
495 BADPREFIX("sv_info_");
496 BADPREFIX("sv_ready_restart_");
498 // mutators that announce themselves properly to the server browser
499 BADCVAR("g_instagib");
500 BADCVAR("g_new_toys");
502 BADCVAR("g_grappling_hook");
503 BADCVAR("g_jetpack");
505 // temporary for testing
506 // TODO remove before 0.8.3 release
507 BADCVAR("g_ca_weaponarena");
508 BADCVAR("g_freezetag_weaponarena");
509 BADCVAR("g_lms_weaponarena");
510 BADCVAR("g_ctf_stalemate_time");
512 if(cvar_string("g_mod_balance") == "Testing")
514 // (temporary) while using the Testing balance, any weapon balance cvars are allowed to be changed
515 BADPREFIX("g_balance_");
524 cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
525 if(strlen(cvar_purechanges) > 16384)
527 cvar_purechanges = "// too many settings have been changed to show them here\n";
531 ++cvar_purechanges_count;
532 // WARNING: this variable is used for the server list
533 // NEVER dare to skip this code!
534 // Hacks to intentionally appearing as "pure server" even though you DO have
535 // modified settings may be punished by removal from the server list.
536 // You can do to the variables cvar_changes and cvar_purechanges all you want,
540 if(cvar_changes == "")
541 cvar_changes = "// this server runs at default server settings\n";
543 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
544 cvar_changes = strzone(cvar_changes);
545 if(cvar_purechanges == "")
546 cvar_purechanges = "// this server runs at default gameplay settings\n";
548 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
549 cvar_purechanges = strzone(cvar_purechanges);
553 bool RandomSeed_Send(entity this, entity to, int sf)
555 WriteHeader(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
556 WriteShort(MSG_ENTITY, this.cnt);
559 void RandomSeed_Think(entity this)
561 this.cnt = bound(0, floor(random() * 65536), 65535);
562 this.nextthink = time + 5;
566 void RandomSeed_Spawn()
568 randomseed = new_pure(randomseed);
569 setthink(randomseed, RandomSeed_Think);
570 Net_LinkEntity(randomseed, false, 0, RandomSeed_Send);
572 getthink(randomseed)(randomseed); // sets random seed and nextthink
575 spawnfunc(__init_dedicated_server)
577 // handler for _init/_init map (only for dedicated server initialization)
579 world_initialized = -1; // don't complain
581 delete_fn = remove_unsafely;
584 setthink(e, GotoFirstMap);
585 e.nextthink = time; // this is usually 1 at this point
587 e = new(info_player_deathmatch); // safeguard against player joining
589 // assign reflectively to avoid "assignment to world" warning
590 for (int i = 0, n = numentityfields(); i < n; ++i) {
591 string k = entityfieldname(i);
592 if (k == "classname") {
593 // safeguard against various stuff ;)
594 putentityfieldstring(i, this, "worldspawn");
599 // needs to be done so early because of the constants they create
602 static_init_precache();
604 IL_PUSH(g_spawnpoints, e); // just incase
607 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
610 void __init_dedicated_server_shutdown() {
614 STATIC_INIT_EARLY(maxclients)
617 for (entity head = nextent(NULL); head; head = nextent(head)) {
622 void default_delayedinit(entity this)
624 if(!scores_initialized)
625 ScoreRules_generic();
628 void InitGameplayMode()
632 // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
634 // assign reflectively to avoid "assignment to world" warning
635 int done = 0; for (int i = 0, n = numentityfields(); i < n; ++i) {
636 string k = entityfieldname(i); vector v = (k == "mins") ? mi_min : (k == "maxs") ? mi_max : '0 0 0';
638 putentityfieldstring(i, world, sprintf("%v", v));
639 if (++done == 2) break;
642 // currently, NetRadiant's limit is 131072 qu for each side
643 // distance from one corner of a 131072qu cube to the opposite corner is approx. 227023 qu
644 // set the distance according to map size but don't go over the limit to avoid issues with float precision
645 // in case somebody makes extremely large maps
646 max_shot_distance = min(230000, vlen(world.maxs - world.mins));
648 MapInfo_LoadMapSettings(mapname);
649 GameRules_teams(false);
651 if (!cvar_value_issafe(world.fog))
653 LOG_INFO("The current map contains a potentially harmful fog setting, ignored");
654 world.fog = string_null;
656 if(MapInfo_Map_fog != "")
658 if(MapInfo_Map_fog == "none")
659 world.fog = string_null;
661 world.fog = strzone(MapInfo_Map_fog);
663 clientstuff = strzone(MapInfo_Map_clientstuff);
665 MapInfo_ClearTemps();
667 gamemode_name = MapInfo_Type_ToText(MapInfo_LoadedGametype);
669 cache_mutatormsg = strzone("");
670 cache_lastmutatormsg = strzone("");
672 InitializeEntity(NULL, default_delayedinit, INITPRIO_GAMETYPE_FALLBACK);
675 void Map_MarkAsRecent(string m);
676 float world_already_spawned;
677 spawnfunc(worldspawn)
679 server_is_dedicated = boolean(stof(cvar_defstring("is_dedicated")));
681 bool wantrestart = false;
683 if (!server_is_dedicated)
685 // force unloading of server pk3 files when starting a listen server
686 // localcmd("\nfs_rescan\n"); // FIXME: does more harm than good, has unintended side effects. What we really want is to unload temporary pk3s only
687 // restore csqc_progname too
688 string expect = "csprogs.dat";
689 wantrestart = cvar_string("csqc_progname") != expect;
690 cvar_set("csqc_progname", expect);
694 // Try to use versioned csprogs from pk3
695 // Only ever use versioned csprogs.dat files on dedicated servers;
696 // we need to reset csqc_progname on clients ourselves, and it's easier if the client's release name is constant
697 string pk3csprogs = "csprogs-" WATERMARK ".dat";
698 // This always works; fall back to it if a versioned csprogs.dat is suddenly missing
699 string select = "csprogs.dat";
700 if (fexists(pk3csprogs)) select = pk3csprogs;
701 if (cvar_string("csqc_progname") != select)
703 cvar_set("csqc_progname", select);
706 // Check for updates on startup
707 // We do it this way for atomicity so that connecting clients still match the server progs and don't disconnect
708 int sentinel = fopen("progs.txt", FILE_READ);
711 string switchversion = fgets(sentinel);
713 if (switchversion != "" && switchversion != WATERMARK)
715 LOG_INFOF("Switching progs: " WATERMARK " -> %s", switchversion);
716 // if it doesn't exist, assume either:
717 // a) the current program was overwritten
718 // b) this is a client only update
719 string newprogs = sprintf("progs-%s.dat", switchversion);
720 if (fexists(newprogs))
722 cvar_set("sv_progs", newprogs);
725 string newcsprogs = sprintf("csprogs-%s.dat", switchversion);
726 if (fexists(newcsprogs))
728 cvar_set("csqc_progname", newcsprogs);
736 LOG_INFO("Restart requested");
737 changelevel(mapname);
738 // let initialization continue, shutdown depends on it
742 if(world_already_spawned)
743 error("world already spawned - you may have EXACTLY ONE worldspawn!");
744 world_already_spawned = true;
746 delete_fn = remove_safely; // during spawning, watch what you remove!
748 cvar_changes_init(); // do this very early now so it REALLY matches the server config
750 // needs to be done so early because of the constants they create
753 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
755 TemporaryDB = db_create();
760 // 1 FLICKER (first variety)
761 lightstyle(1, "mmnmmommommnonmmonqnmmo");
763 // 2 SLOW STRONG PULSE
764 lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
766 // 3 CANDLE (first variety)
767 lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
770 lightstyle(4, "mamamamamama");
773 lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
775 // 6 FLICKER (second variety)
776 lightstyle(6, "nmonqnmomnmomomno");
778 // 7 CANDLE (second variety)
779 lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
781 // 8 CANDLE (third variety)
782 lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
784 // 9 SLOW STROBE (fourth variety)
785 lightstyle(9, "aaaaaaaazzzzzzzz");
787 // 10 FLUORESCENT FLICKER
788 lightstyle(10, "mmamammmmammamamaaamammma");
790 // 11 SLOW PULSE NOT FADE TO BLACK
791 lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
793 // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
798 if(autocvar_g_campaign)
801 Map_MarkAsRecent(mapname);
803 PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
807 static_init_precache();
811 GameRules_limit_fallbacks();
813 if(warmup_limit == 0)
814 warmup_limit = (autocvar_timelimit > 0) ? autocvar_timelimit * 60 : autocvar_timelimit;
817 bot_waypoints_for_items = autocvar_g_waypoints_for_items;
818 if(bot_waypoints_for_items == 1)
819 if(this.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
820 bot_waypoints_for_items = 0;
822 WaypointSprite_Init();
824 GameLogInit(); // prepare everything
826 // changing the logic generating it is okay. But:
827 // it HAS to stay <= 64 chars
828 // character set: ASCII 33-126 without the following characters: : ; ' " \ $
829 if(autocvar_sv_eventlog)
831 string s = sprintf("%s.%s.%06d", itos(autocvar_sv_eventlog_files_counter), strftime(false, "%s"), floor(random() * 1000000));
832 matchid = strzone(s);
834 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
835 s = ":gameinfo:mutators:LIST";
837 MUTATOR_CALLHOOK(BuildMutatorsString, s);
838 s = M_ARGV(0, string);
840 // initialiation stuff, not good in the mutator system
841 if(!autocvar_g_use_ammunition)
842 s = strcat(s, ":no_use_ammunition");
844 // initialiation stuff, not good in the mutator system
845 if(autocvar_g_pickup_items == 0)
846 s = strcat(s, ":no_pickup_items");
847 if(autocvar_g_pickup_items > 0)
848 s = strcat(s, ":pickup_items");
850 // initialiation stuff, not good in the mutator system
851 if(autocvar_g_weaponarena != "0")
852 s = strcat(s, ":", autocvar_g_weaponarena, " arena");
854 // TODO to mutator system
855 if(autocvar_g_norecoil)
856 s = strcat(s, ":norecoil");
858 // TODO to mutator system
859 if(autocvar_g_powerups == 0)
860 s = strcat(s, ":no_powerups");
861 if(autocvar_g_powerups > 0)
862 s = strcat(s, ":powerups");
865 GameLogEcho(":gameinfo:end");
868 matchid = strzone(ftos(random()));
870 cvar_set("nextmap", "");
874 if(autocvar_g_campaign)
880 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
882 if(fexists(strcat("scripts/", mapname, ".arena")))
883 cvar_settemp("sv_q3acompat_machineshotgunswap", "1");
885 if(fexists(strcat("scripts/", mapname, ".defi")))
886 cvar_settemp("sv_q3defragcompat", "1");
888 if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
890 int fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
894 while((s = fgets(fd)))
896 int l = tokenize_console(s);
901 string trackname = argv(2);
902 LOG_INFO("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:");
903 LOG_INFO(" cdtrack ", trackname);
904 if (cvar_value_issafe(trackname))
906 string newstuff = strcat(clientstuff, "cd loop \"", trackname, "\"\n");
907 strcpy(clientstuff, newstuff);
910 else if(argv(0) == "fog")
912 LOG_INFO("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:");
913 LOG_INFO(" \"fog\" \"", s, "\"");
915 else if(argv(0) == "set")
917 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
918 LOG_INFO(" clientsettemp_for_type all ", argv(1), " ", argv(2));
920 else if(argv(0) != "//")
922 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
923 LOG_INFO(" clientsettemp_for_type all ", argv(0), " ", argv(1));
934 next_pingtime = time + 5;
936 // set up information replies for clients and server to use
937 maplist_reply = strzone(getmaplist());
938 lsmaps_reply = strzone(getlsmaps());
939 monsterlist_reply = strzone(getmonsterlist());
940 for(int i = 0; i < 10; ++i)
942 string s = getrecords(i);
944 records_reply[i] = strzone(s);
946 ladder_reply = strzone(getladder());
947 rankings_reply = strzone(getrankings());
952 PingPLReport_Spawn();
956 if (!wantrestart) localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
958 // fill sv_curl_serverpackages from .serverpackage files
959 if (autocvar_sv_curl_serverpackages_auto)
961 string s = "csprogs-" WATERMARK ".txt";
962 // remove automatically managed files from the list to prevent duplicates
963 for (int i = 0, n = tokenize_console(cvar_string("sv_curl_serverpackages")); i < n; ++i)
965 string pkg = argv(i);
966 if (startsWith(pkg, "csprogs-")) continue;
967 if (endsWith(pkg, "-serverpackage.txt")) continue;
968 if (endsWith(pkg, ".serverpackage")) continue; // OLD legacy
971 // add automatically managed files to the list
972 #define X(match) MACRO_BEGIN \
973 int fd = search_begin(match, true, false); \
976 for (int i = 0, j = search_getsize(fd); i < j; ++i) \
978 s = cons(s, search_getfilename(fd, i)); \
983 X("*-serverpackage.txt");
984 X("*.serverpackage");
986 cvar_set("sv_curl_serverpackages", s);
989 // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
991 // physics/balance/config changes that count as mod
992 if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
993 modname = cvar_string("g_mod_physics");
994 if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance") && cvar_string("g_mod_balance") != "Testing")
995 modname = cvar_string("g_mod_balance");
996 if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
997 modname = cvar_string("g_mod_config");
998 // extra mutators that deserve to count as mod
999 MUTATOR_CALLHOOK(SetModname, modname);
1000 modname = M_ARGV(0, string);
1002 // save it for later
1003 modname = strzone(modname);
1005 WinningConditionHelper(this); // set worldstatus
1007 world_initialized = 1;
1008 __spawnfunc_spawn_all();
1013 //makestatic (this); // Who the f___ did that?
1017 string GetGametype()
1019 return MapInfo_Type_ToString(MapInfo_LoadedGametype);
1027 float Map_Count, Map_Current;
1028 string Map_Current_Name;
1030 // NOTE: this now expects the map list to be already tokenized and the count in Map_Count
1031 int GetMaplistPosition()
1033 string map = GetMapname();
1034 int idx = autocvar_g_maplist_index;
1040 if(map == argv(idx))
1047 for(int pos = 0; pos < Map_Count; ++pos)
1049 if(map == argv(pos))
1053 // resume normal maplist rotation if current map is not in g_maplist
1057 bool MapHasRightSize(string map)
1059 int minplayers = max(0, floor(autocvar_minplayers));
1061 minplayers = max(0, floor(autocvar_minplayers_per_team) * AvailableTeams());
1062 if (autocvar_g_maplist_check_waypoints
1063 && (currentbots || autocvar_bot_number || player_count < minplayers))
1065 string checkwp_msg = strcat("checkwp ", map);
1066 if(!fexists(strcat("maps/", map, ".waypoints")))
1068 LOG_TRACE(checkwp_msg, ": no waypoints");
1071 LOG_TRACE(checkwp_msg, ": has waypoints");
1074 if(autocvar_g_maplist_ignore_sizes)
1077 // open map size restriction file
1078 string opensize_msg = strcat("opensize ", map);
1079 float fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
1080 int player_limit = ((autocvar_g_maplist_sizes_count_maxplayers) ? GetPlayerLimit() : 0);
1081 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
1082 if(!autocvar_g_maplist_sizes_count_bots)
1083 pcount -= currentbots;
1086 opensize_msg = strcat(opensize_msg, ": ok, ");
1087 int mapmin = stoi(fgets(fh));
1088 int mapmax = stoi(fgets(fh));
1092 LOG_TRACE(opensize_msg, "not enough");
1095 if(mapmax && pcount > mapmax)
1097 LOG_TRACE(opensize_msg, "too many");
1100 LOG_TRACE(opensize_msg, "right size");
1103 LOG_TRACE(opensize_msg, ": not found");
1107 string Map_Filename(float position)
1109 return strcat("maps/", argv(position), ".bsp");
1112 void Map_MarkAsRecent(string m)
1114 cvar_set("g_maplist_mostrecent", strwords(cons(m, autocvar_g_maplist_mostrecent), max(0, autocvar_g_maplist_mostrecent_count)));
1117 float Map_IsRecent(string m)
1119 return strhasword(autocvar_g_maplist_mostrecent, m);
1122 float Map_Check(float position, float pass)
1126 map_next = argv(position);
1129 if(Map_IsRecent(map_next))
1132 filename = Map_Filename(position);
1133 if(MapInfo_CheckMap(map_next))
1137 if(MapHasRightSize(map_next))
1142 LOG_DEBUG( "Couldn't select '", filename, "'..." );
1147 void Map_Goto_SetStr(string nextmapname)
1149 if(getmapname_stored != "")
1150 strunzone(getmapname_stored);
1151 if(nextmapname == "")
1152 getmapname_stored = "";
1154 getmapname_stored = strzone(nextmapname);
1157 void Map_Goto_SetFloat(float position)
1159 cvar_set("g_maplist_index", ftos(position));
1160 Map_Goto_SetStr(argv(position));
1163 void Map_Goto(float reinit)
1165 MapInfo_LoadMap(getmapname_stored, reinit);
1168 // return codes of map selectors:
1169 // -1 = temporary failure (that is, try some method that is guaranteed to succeed)
1170 // -2 = permanent failure
1171 float MaplistMethod_Iterate() // usual method
1175 LOG_TRACE("Trying MaplistMethod_Iterate");
1177 for(pass = 1; pass <= 2; ++pass)
1179 for(i = 1; i < Map_Count; ++i)
1182 mapindex = (i + Map_Current) % Map_Count;
1183 if(Map_Check(mapindex, pass))
1190 float MaplistMethod_Repeat() // fallback method
1192 LOG_TRACE("Trying MaplistMethod_Repeat");
1194 if(Map_Check(Map_Current, 2))
1199 float MaplistMethod_Random() // random map selection
1203 LOG_TRACE("Trying MaplistMethod_Random");
1207 for(i = 0; i <= imax; ++i)
1210 mapindex = (Map_Current + floor(random() * (Map_Count - 1) + 1)) % Map_Count; // any OTHER map
1211 if(Map_Check(mapindex, 1))
1217 float MaplistMethod_Shuffle(float exponent) // more clever shuffling
1218 // the exponent sets a bias on the map selection:
1219 // the higher the exponent, the less likely "shortly repeated" same maps are
1221 float i, j, imax, insertpos;
1223 LOG_TRACE("Trying MaplistMethod_Shuffle");
1227 for(i = 0; i <= imax; ++i)
1231 // now reinsert this at another position
1232 insertpos = (random() ** (1 / exponent)); // ]0, 1]
1233 insertpos = insertpos * (Map_Count - 1); // ]0, Map_Count - 1]
1234 insertpos = ceil(insertpos) + 1; // {2, 3, 4, ..., Map_Count}
1235 LOG_TRACE("SHUFFLE: insert pos = ", ftos(insertpos));
1237 // insert the current map there
1239 for(j = 1; j < insertpos; ++j) // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
1240 newlist = strcat(newlist, " ", argv(j));
1241 newlist = strcat(newlist, " ", argv(0)); // now insert the just selected map
1242 for(j = insertpos; j < Map_Count; ++j) // i == Map_Count: no loop, has just been inserted as last
1243 newlist = strcat(newlist, " ", argv(j));
1244 newlist = substring(newlist, 1, strlen(newlist) - 1);
1245 cvar_set("g_maplist", newlist);
1246 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1248 // NOTE: the selected map has just been inserted at (insertpos-1)th position
1249 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
1250 if(Map_Check(Map_Current, 1))
1258 float i = Map_Count = 0;
1259 if(autocvar_g_maplist != "")
1261 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1262 for (i = 0; i < Map_Count; ++i)
1264 if (Map_Check(i, 2))
1271 bprint( "Maplist contains no usable maps! Resetting it to default map list.\n" );
1272 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags() | MAPINFO_FLAG_NOAUTOMAPLIST));
1273 if(autocvar_g_maplist_shuffle)
1275 if(!server_is_dedicated)
1276 localcmd("\nmenu_cmd sync\n");
1277 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1280 error("empty maplist, cannot select a new map");
1281 Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
1283 strcpy(Map_Current_Name, argv(Map_Current)); // will be automatically freed on exit thanks to DP
1284 // this may or may not be correct, but who cares, in the worst case a map
1285 // isn't chosen in the first pass that should have been
1294 if(autocvar_g_maplist_shuffle > 0)
1295 nextMap = MaplistMethod_Shuffle(autocvar_g_maplist_shuffle + 1);
1298 if(autocvar_g_maplist_selectrandom)
1299 nextMap = MaplistMethod_Random();
1302 nextMap = MaplistMethod_Iterate();
1305 nextMap = MaplistMethod_Repeat();
1309 Map_Goto_SetFloat(nextMap);
1310 return getmapname_stored;
1316 float DoNextMapOverride(float reinit)
1318 if(autocvar_g_campaign)
1320 CampaignPostIntermission();
1321 alreadychangedlevel = true;
1324 if(autocvar_quit_when_empty)
1326 if(player_count <= currentbots)
1329 alreadychangedlevel = true;
1333 if(autocvar_quit_and_redirect != "")
1335 redirection_target = strzone(autocvar_quit_and_redirect);
1336 alreadychangedlevel = true;
1339 if (!reinit && autocvar_samelevel) // if samelevel is set, stay on same level
1341 localcmd("restart\n");
1342 alreadychangedlevel = true;
1345 if(autocvar_nextmap != "")
1348 m = GameTypeVote_MapInfo_FixName(autocvar_nextmap);
1349 cvar_set("nextmap",m);
1351 if(!m || gametypevote)
1353 if(autocvar_sv_vote_gametype)
1359 if(MapInfo_CheckMap(m))
1363 alreadychangedlevel = true;
1367 if(!reinit && autocvar_lastlevel)
1369 cvar_settemp_restore();
1370 localcmd("set lastlevel 0\ntogglemenu 1\n");
1371 alreadychangedlevel = true;
1377 void GotoNextMap(float reinit)
1382 if (alreadychangedlevel)
1384 alreadychangedlevel = true;
1386 string nextMap = GetNextMap();
1388 error("Everything is broken - cannot find a next map. Please report this to the developers.");
1397 When the player presses attack or jump, change to the next level
1400 .float autoscreenshot;
1401 void IntermissionThink(entity this)
1403 FixIntermissionClient(this);
1405 float server_screenshot = (autocvar_sv_autoscreenshot && CS(this).cvar_cl_autoscreenshot);
1406 float client_screenshot = (CS(this).cvar_cl_autoscreenshot == 2);
1408 if( (server_screenshot || client_screenshot)
1409 && ((this.autoscreenshot > 0) && (time > this.autoscreenshot)) )
1411 this.autoscreenshot = -1;
1412 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"))); }
1416 if (time < intermission_exittime)
1419 if(!mapvote_initialized)
1420 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)))
1427 ===============================================================================
1431 ===============================================================================
1434 void DumpStats(float final)
1443 to_console = autocvar_sv_logscores_console;
1444 to_eventlog = autocvar_sv_eventlog;
1445 to_file = autocvar_sv_logscores_file;
1449 to_console = true; // always print printstats replies
1450 to_eventlog = false; // but never print them to the event log
1454 if(autocvar_sv_eventlog_console)
1455 to_console = false; // otherwise we get the output twice
1461 s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1471 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1475 fputs(file, strcat(s, "\n"));
1478 s = strcat(":labels:player:", GetPlayerScoreString(NULL, 0));
1484 fputs(file, strcat(s, "\n"));
1486 FOREACH_CLIENT(IS_REAL_CLIENT(it) || (IS_BOT_CLIENT(it) && autocvar_sv_logscores_bots), {
1487 s = strcat(":player:see-labels:", GetPlayerScoreString(it, 0), ":");
1488 s = strcat(s, ftos(rint(time - CS(it).jointime)), ":");
1489 if(IS_PLAYER(it) || MUTATOR_CALLHOOK(GetPlayerStatus, it))
1490 s = strcat(s, ftos(it.team), ":");
1492 s = strcat(s, "spectator:");
1495 LOG_INFO(s, playername(it, false));
1497 GameLogEcho(strcat(s, ftos(it.playerid), ":", playername(it, false)));
1499 fputs(file, strcat(s, playername(it, false), "\n"));
1504 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1510 fputs(file, strcat(s, "\n"));
1512 for(i = 1; i < 16; ++i)
1514 s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1515 s = strcat(s, ":", ftos(i));
1521 fputs(file, strcat(s, "\n"));
1528 GameLogEcho(":end");
1531 fputs(file, ":end\n");
1536 void FixIntermissionClient(entity e)
1538 if(!e.autoscreenshot) // initial call
1540 e.autoscreenshot = time + 0.8; // used for autoscreenshot
1541 SetResourceExplicit(e, RES_HEALTH, -2342);
1542 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1543 for (int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1545 .entity weaponentity = weaponentities[slot];
1546 if(e.(weaponentity))
1548 e.(weaponentity).effects = EF_NODRAW;
1549 if (e.(weaponentity).weaponchild)
1550 e.(weaponentity).weaponchild.effects = EF_NODRAW;
1553 if(IS_REAL_CLIENT(e))
1555 stuffcmd(e, "\nscr_printspeed 1000000\n");
1556 RandomSelection_Init();
1557 FOREACH_WORD(autocvar_sv_intermission_cdtrack, true, {
1558 RandomSelection_AddString(it, 1, 1);
1560 if (RandomSelection_chosen_string != "")
1562 stuffcmd(e, sprintf("\ncd loop %s\n", RandomSelection_chosen_string));
1565 WriteByte(MSG_ONE, SVC_INTERMISSION);
1571 go to the next level for deathmatch
1572 only called if a time or frag limit has expired
1576 game_stopped = true;
1577 intermission_running = 1; // game over
1579 // enforce a wait time before allowing changelevel
1580 if(player_count > 0)
1581 intermission_exittime = time + autocvar_sv_mapchange_delay;
1583 intermission_exittime = -1;
1586 WriteByte (MSG_ALL, SVC_CDTRACK);
1587 WriteByte (MSG_ALL, 3);
1588 WriteByte (MSG_ALL, 3);
1589 // done in FixIntermission
1592 //pos = FindIntermission ();
1599 PlayerStats_GameReport(true);
1600 WeaponStats_Shutdown();
1602 Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_Null); // kill all centerprints now
1604 if(autocvar_sv_eventlog)
1605 GameLogEcho(":gameover");
1609 FOREACH_CLIENT(IS_PLAYER(it), {
1610 FixIntermissionClient(it);
1612 bprint(playername(it, false), " ^7wins.\n");
1615 target_music_kill();
1617 if(autocvar_g_campaign)
1618 CampaignPreIntermission();
1620 MUTATOR_CALLHOOK(MatchEnd);
1622 localcmd("\nsv_hook_gameend\n");
1626 float InitiateSuddenDeath()
1628 // Check first whether normal overtimes could be added before initiating suddendeath mode
1629 // - for this timelimit_overtime needs to be >0 of course
1630 // - also check the winning condition calculated in the previous frame and only add normal overtime
1631 // again, if at the point at which timelimit would be extended again, still no winner was found
1632 if (!autocvar_g_campaign && checkrules_overtimesadded >= 0
1633 && (checkrules_overtimesadded < autocvar_timelimit_overtimes || autocvar_timelimit_overtimes < 0)
1634 && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1636 return 1; // need to call InitiateOvertime later
1640 if(!checkrules_suddendeathend)
1642 if(autocvar_g_campaign)
1643 checkrules_suddendeathend = time; // no suddendeath in campaign
1645 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1646 if(g_race && !g_race_qualifying)
1647 race_StartCompleting();
1653 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1655 ++checkrules_overtimesadded;
1656 //add one more overtime by simply extending the timelimit
1657 cvar_set("timelimit", ftos(autocvar_timelimit + autocvar_timelimit_overtime));
1658 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime * 60);
1661 float GetWinningCode(float fraglimitreached, float equality)
1663 if(autocvar_g_campaign == 1)
1665 if(fraglimitreached)
1674 if(fraglimitreached)
1675 return WINNING_STARTSUDDENDEATHOVERTIME;
1677 return WINNING_NEVER;
1681 if(fraglimitreached)
1689 // set the .winning flag for exactly those players with a given field value
1690 void SetWinners(.float field, float value)
1692 FOREACH_CLIENT(IS_PLAYER(it), { it.winning = (it.(field) == value); });
1695 // set the .winning flag for those players with a given field value
1696 void AddWinners(.float field, float value)
1698 FOREACH_CLIENT(IS_PLAYER(it), {
1699 if(it.(field) == value)
1704 // clear the .winning flags
1707 FOREACH_CLIENT(IS_PLAYER(it), { it.winning = 0; });
1710 void ShuffleMaplist()
1712 cvar_set("g_maplist", shufflewords(autocvar_g_maplist));
1716 float WinningCondition_Scores(float limit, float leadlimit)
1718 // TODO make everything use THIS winning condition (except LMS)
1719 WinningConditionHelper(NULL);
1723 for (int i = 1; i < 5; ++i)
1725 Team_SetTeamScore(Team_GetTeamFromIndex(i),
1726 TeamScore_GetCompareValue(Team_IndexToTeam(i)));
1731 if(WinningConditionHelper_winner)
1732 WinningConditionHelper_winner.winning = 1;
1733 if(WinningConditionHelper_winnerteam >= 0)
1734 SetWinners(team, WinningConditionHelper_winnerteam);
1736 if(WinningConditionHelper_lowerisbetter)
1738 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1739 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1743 if(WinningConditionHelper_zeroisworst)
1744 leadlimit = 0; // not supported in this mode
1746 if(MUTATOR_CALLHOOK(Scores_CountFragsRemaining))
1749 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1755 fragsleft = FLOAT_MAX;
1756 float leadingfragsleft = FLOAT_MAX;
1758 fragsleft = limit - WinningConditionHelper_topscore;
1760 leadingfragsleft = WinningConditionHelper_secondscore + leadlimit - WinningConditionHelper_topscore;
1762 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1763 fragsleft = max(fragsleft, leadingfragsleft);
1765 fragsleft = min(fragsleft, leadingfragsleft);
1768 if (fragsleft_last != fragsleft) // do not announce same remaining frags multiple times
1771 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_1);
1772 else if (fragsleft == 2)
1773 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_2);
1774 else if (fragsleft == 3)
1775 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_3);
1777 fragsleft_last = fragsleft;
1781 bool fraglimit_reached = (limit && WinningConditionHelper_topscore >= limit);
1782 bool leadlimit_reached = (leadlimit && WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1785 // only respect leadlimit_and_fraglimit when both limits are set or the game will never end
1786 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1787 limit_reached = (fraglimit_reached && leadlimit_reached);
1789 limit_reached = (fraglimit_reached || leadlimit_reached);
1791 return GetWinningCode(
1792 WinningConditionHelper_topscore && limit_reached,
1793 WinningConditionHelper_equality
1797 float WinningCondition_RanOutOfSpawns()
1799 if(have_team_spawns <= 0)
1802 if(!autocvar_g_spawn_useallspawns)
1805 if(!some_spawn_has_been_used)
1808 for (int i = 1; i < 5; ++i)
1810 Team_SetTeamScore(Team_GetTeamFromIndex(i), 0);
1813 FOREACH_CLIENT(IS_PLAYER(it) && !IS_DEAD(it),
1815 if (Team_IsValidTeam(it.team))
1817 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1821 IL_EACH(g_spawnpoints, true,
1823 if (Team_IsValidTeam(it.team))
1825 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1830 float team1_score = Team_GetTeamScore(Team_GetTeamFromIndex(1));
1831 float team2_score = Team_GetTeamScore(Team_GetTeamFromIndex(2));
1832 float team3_score = Team_GetTeamScore(Team_GetTeamFromIndex(3));
1833 float team4_score = Team_GetTeamScore(Team_GetTeamFromIndex(4));
1834 if(team1_score + team2_score + team3_score + team4_score == 0)
1836 checkrules_equality = true;
1839 else if(team1_score + team2_score + team3_score + team4_score == 1)
1844 else if(team2_score)
1846 else if(team3_score)
1848 else // if(team4_score)
1850 entity balance = TeamBalance_CheckAllowedTeams(NULL);
1851 for(i = 0; i < MAX_TEAMSCORE; ++i)
1853 for (int j = 1; j <= NUM_TEAMS; ++j)
1859 if (!TeamBalance_IsTeamAllowed(balance, j))
1863 TeamScore_AddToTeam(Team_IndexToTeam(j), i, -1000);
1867 AddWinners(team, t);
1878 Exit deathmatch games upon conditions
1881 void CheckRules_World()
1888 if (intermission_running) // someone else quit the game already
1890 if(player_count == 0) // Nobody there? Then let's go to the next map
1892 // this will actually check the player count in the next frame
1893 // again, but this shouldn't hurt
1897 float timelimit = autocvar_timelimit * 60;
1898 float fraglimit = autocvar_fraglimit;
1899 float leadlimit = autocvar_leadlimit;
1900 if (leadlimit < 0) leadlimit = 0;
1902 if(warmup_stage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1905 timelimit = 0; // timelimit is not made for warmup
1907 fraglimit = 0; // no fraglimit for now
1908 leadlimit = 0; // no leadlimit for now
1913 timelimit += game_starttime;
1915 else if (timelimit < 0)
1925 if(checkrules_suddendeathend)
1927 if(!checkrules_suddendeathwarning)
1929 checkrules_suddendeathwarning = true;
1930 if(g_race && !g_race_qualifying)
1931 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_RACE_FINISHLAP);
1933 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_FRAG);
1938 if (timelimit && time >= timelimit)
1940 if(g_race && (g_race_qualifying == 2) && timelimit > 0)
1943 float playerswithlaps;
1945 totalplayers = playerswithlaps = readyplayers = 0;
1946 FOREACH_CLIENT(IS_PLAYER(it), {
1948 if(GameRules_scoring_add(it, RACE_FASTEST, 0))
1954 // at least 2 of the players have completed a lap: start the RACE
1955 // otherwise, the players should end the qualifying on their own
1956 if(readyplayers || playerswithlaps >= 2)
1958 checkrules_suddendeathend = 0;
1959 ReadyRestart(); // go to race
1963 wantovertime |= InitiateSuddenDeath();
1966 wantovertime |= InitiateSuddenDeath();
1970 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1976 int checkrules_status = WinningCondition_RanOutOfSpawns();
1977 if(checkrules_status == WINNING_YES)
1978 bprint("Hey! Someone ran out of spawns!\n");
1979 else if(MUTATOR_CALLHOOK(CheckRules_World, checkrules_status, timelimit, fraglimit))
1980 checkrules_status = M_ARGV(0, float);
1982 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
1984 if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
1986 checkrules_status = WINNING_NEVER;
1987 checkrules_overtimesadded = -1;
1988 wantovertime |= InitiateSuddenDeath();
1991 if(checkrules_status == WINNING_NEVER)
1992 // equality cases! Nobody wins if the overtime ends in a draw.
1997 if(checkrules_status == WINNING_NEVER)
2000 checkrules_status = WINNING_YES;
2003 if(checkrules_suddendeathend)
2004 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
2005 checkrules_status = WINNING_YES;
2007 if(checkrules_status == WINNING_YES)
2009 //print("WINNING\n");
2014 string GotoMap(string m)
2016 m = GameTypeVote_MapInfo_FixName(m);
2018 return "The map you suggested is not available on this server.";
2019 if (!autocvar_sv_vote_gametype)
2020 if(!MapInfo_CheckMap(m))
2021 return "The map you suggested does not support the current game mode.";
2022 cvar_set("nextmap", m);
2023 cvar_set("timelimit", "-1");
2024 if(mapvote_initialized || alreadychangedlevel)
2026 if(DoNextMapOverride(0))
2027 return "Map switch initiated.";
2029 return "Hm... no. For some reason I like THIS map more.";
2032 return "Map switch will happen after scoreboard.";
2035 bool autocvar_sv_gameplayfix_multiplethinksperframe = true;
2036 void RunThink(entity this)
2038 // don't let things stay in the past.
2039 // it is possible to start that way by a trigger with a local time.
2040 if(this.nextthink <= 0 || this.nextthink > time + frametime)
2043 float oldtime = time; // do we need to save this?
2045 for (int iterations = 0; iterations < 128 && !wasfreed(this); iterations++)
2047 time = max(oldtime, this.nextthink);
2051 getthink(this)(this);
2052 // mods often set nextthink to time to cause a think every frame,
2053 // we don't want to loop in that case, so exit if the new nextthink is
2054 // <= the time the qc was told, also exit if it is past the end of the
2056 if(this.nextthink <= time || this.nextthink > oldtime + frametime || !autocvar_sv_gameplayfix_multiplethinksperframe)
2063 bool autocvar_sv_freezenonclients;
2064 bool autocvar_sv_gameplayfix_delayprojectiles = false;
2065 void Physics_Frame()
2067 if(autocvar_sv_freezenonclients)
2070 IL_EACH(g_moveables, true,
2072 if(IS_CLIENT(it) || it.classname == "" || it.move_movetype == MOVETYPE_PHYSICS)
2075 //set_movetype(it, it.move_movetype);
2076 // inline the set_movetype function, since this is called a lot
2077 it.movetype = (it.move_qcphysics) ? MOVETYPE_QCENTITY : it.move_movetype;
2079 if(it.move_qcphysics && it.move_movetype != MOVETYPE_NONE)
2080 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2082 if(it.movetype >= MOVETYPE_USER_FIRST && it.movetype <= MOVETYPE_USER_LAST) // these cases have no think handling
2084 if(it.move_movetype == MOVETYPE_PUSH || it.move_movetype == MOVETYPE_FAKEPUSH)
2085 continue; // these movetypes have no regular think function
2086 // handle thinking here
2087 if (getthink(it) && it.nextthink > 0 && it.nextthink <= time + frametime)
2092 if(autocvar_sv_gameplayfix_delayprojectiles >= 0)
2095 IL_EACH(g_moveables, it.move_qcphysics,
2097 if(IS_CLIENT(it) || it.classname == "" || it.move_movetype == MOVETYPE_NONE)
2099 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2103 void systems_update();
2106 anticheat_endframe();
2110 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2111 entity e = IS_SPEC(it) ? it.enemy : it;
2112 if (e.typehitsound) {
2113 STAT(TYPEHIT_TIME, it) = time;
2114 } else if (e.killsound) {
2115 STAT(KILL_TIME, it) = time;
2116 } else if (e.damage_dealt) {
2117 STAT(HIT_TIME, it) = time;
2118 STAT(DAMAGE_DEALT_TOTAL, it) += ceil(e.damage_dealt);
2121 // add 1 frametime because after this, engine SV_Physics
2122 // increases time by a frametime and then networks the frame
2123 // add another frametime because client shows everything with
2124 // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2126 float altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2127 FOREACH_CLIENT(true, {
2128 it.typehitsound = false;
2129 it.damage_dealt = 0;
2130 it.killsound = false;
2131 antilag_record(it, CS(it), altime);
2133 IL_EACH(g_monsters, true,
2135 antilag_record(it, it, altime);
2137 IL_EACH(g_projectiles, it.classname == "nade",
2139 antilag_record(it, it, altime);
2148 * returns true if redirecting
2150 float redirection_timeout;
2151 float redirection_nextthink;
2152 float RedirectionThink()
2154 float clients_found;
2156 if(redirection_target == "")
2159 if(!redirection_timeout)
2161 cvar_set("sv_public", "-2");
2162 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2163 if(redirection_target == "self")
2164 bprint("^3SERVER NOTICE:^7 restarting the server\n");
2166 bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2169 if(time < redirection_nextthink)
2172 redirection_nextthink = time + 1;
2175 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2177 LOG_INFO("Redirecting: sending connect command to ", it.netname);
2178 if(redirection_target == "self")
2179 stuffcmd(it, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2181 stuffcmd(it, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2185 LOG_INFO("Redirecting: ", ftos(clients_found), " clients left.");
2187 if(time > redirection_timeout || clients_found == 0)
2188 localcmd("\nwait; wait; wait; quit\n");
2195 // Loaded from a save game
2196 // some things then break, so let's work around them...
2198 // Progs DB (capture records)
2199 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2203 MapInfo_Enumerate();
2204 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2207 TargetMusic_RestoreGame();
2214 if(world_initialized > 0)
2216 world_initialized = 0;
2218 // if a timeout is active, reset the slowmo value to normal
2219 if(timeout_status == TIMEOUT_ACTIVE)
2220 cvar_set("slowmo", ftos(orig_slowmo));
2222 LOG_TRACE("Saving persistent data...");
2225 // playerstats with unfinished match
2226 PlayerStats_GameReport(false);
2228 if(!cheatcount_total)
2230 if(autocvar_sv_db_saveasdump)
2231 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2233 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2235 if(autocvar_developer > 0)
2237 if(autocvar_sv_db_saveasdump)
2238 db_dump(TemporaryDB, "server-temp.db");
2240 db_save(TemporaryDB, "server-temp.db");
2242 CheatShutdown(); // must be after cheatcount check
2243 db_close(ServerProgsDB);
2244 db_close(TemporaryDB);
2245 LOG_TRACE("Saving persistent data... done!");
2246 // tell the bot system the game is ending now
2249 WeaponStats_Shutdown();
2252 else if(world_initialized == 0)
2254 LOG_INFO("NOTE: crashed before even initializing the world, not saving persistent data");
2258 __init_dedicated_server_shutdown();