3 #include <common/constants.qh>
4 #include <common/deathtypes/all.qh>
5 #include <common/gamemodes/_mod.qh>
6 #include <common/gamemodes/sv_rules.qh>
7 #include <common/items/_mod.qh>
8 #include <common/mapinfo.qh>
9 #include <common/mapobjects/target/music.qh>
10 #include <common/mapobjects/trigger/hurt.qh>
11 #include <common/mapobjects/trigger/secret.qh>
12 #include <common/mapobjects/triggers.qh>
13 #include <common/monsters/_mod.qh>
14 #include <common/monsters/sv_monsters.qh>
15 #include <common/net_linked.qh>
16 #include <common/notifications/all.qh>
17 #include <common/physics/player.qh>
18 #include <common/playerstats.qh>
19 #include <common/state.qh>
20 #include <common/stats.qh>
21 #include <common/teams.qh>
22 #include <common/util.qh>
23 #include <common/vehicles/all.qh>
24 #include <common/weapons/_all.qh>
25 #include <server/anticheat.qh>
26 #include <server/antilag.qh>
27 #include <server/bot/api.qh>
28 #include <server/campaign.qh>
29 #include <server/cheats.qh>
30 #include <server/client.qh>
31 #include <server/command/common.qh>
32 #include <server/command/getreplies.qh>
33 #include <server/command/sv_cmd.qh>
34 #include <server/command/vote.qh>
35 #include <server/damage.qh>
36 #include <server/gamelog.qh>
37 #include <server/hook.qh>
38 #include <server/intermission.qh>
39 #include <server/ipban.qh>
40 #include <server/items/items.qh>
41 #include <server/main.qh>
42 #include <server/mapvoting.qh>
43 #include <server/mutators/_mod.qh>
44 #include <server/race.qh>
45 #include <server/scores.qh>
46 #include <server/scores_rules.qh>
47 #include <server/spawnpoints.qh>
48 #include <server/teamplay.qh>
49 #include <server/weapons/common.qh>
50 #include <server/weapons/weaponstats.qh>
52 const float LATENCY_THINKRATE = 10;
57 void PingPLReport_Think(entity this)
62 delta = 3 / maxclients;
63 if(delta < sys_frametime)
65 this.nextthink = time + delta;
67 e = edict_num(this.cnt + 1);
68 if(IS_CLIENT(e) && IS_REAL_CLIENT(e))
70 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
71 WriteByte(MSG_BROADCAST, this.cnt);
72 WriteShort(MSG_BROADCAST, bound(1, rint(CS(e).ping), 32767));
73 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_packetloss * 255), 255));
74 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_movementloss * 255), 255));
76 // record latency times for clients throughout the match so we can report it to playerstats
77 if(time > (CS(e).latency_time + LATENCY_THINKRATE))
79 CS(e).latency_sum += CS(e).ping;
80 CS(e).latency_cnt += 1;
81 CS(e).latency_time = time;
82 //print("sum: ", ftos(CS(e).latency_sum), ", cnt: ", ftos(CS(e).latency_cnt), ", avg: ", ftos(CS(e).latency_sum / CS(e).latency_cnt), ".\n");
87 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
88 WriteByte(MSG_BROADCAST, this.cnt);
89 WriteShort(MSG_BROADCAST, 0);
90 WriteByte(MSG_BROADCAST, 0);
91 WriteByte(MSG_BROADCAST, 0);
93 this.cnt = (this.cnt + 1) % maxclients;
95 void PingPLReport_Spawn()
97 pingplreport = new_pure(pingplreport);
98 setthink(pingplreport, PingPLReport_Think);
99 pingplreport.nextthink = time;
102 const float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
104 void send_TotalShards(entity to) {
106 // Send total number of picked up shards
107 if(!autocvar_g_count_shards) return;
108 if(!IS_REAL_CLIENT(to)) return;
111 WriteHeader(MSG_ONE, TE_CSQC_TOTALSHARDS);
112 WriteInt24_t(MSG_ONE, total_shards);
115 void send_TotalShardsAll() {
117 // Send total number of picked up shards
118 if(!autocvar_g_count_shards) return;
120 FOREACH_CLIENT(IS_REAL_CLIENT(it) && (IS_SPEC(it) || IS_OBSERVER(it)), {
121 send_TotalShards(it);
125 void SetDefaultAlpha()
127 if (!MUTATOR_CALLHOOK(SetDefaultAlpha))
129 default_player_alpha = autocvar_g_player_alpha;
130 if(default_player_alpha == 0)
131 default_player_alpha = 1;
132 default_weapon_alpha = default_player_alpha;
136 void GotoFirstMap(entity this)
139 if(autocvar__sv_init)
141 // cvar_set("_sv_init", "0");
142 // we do NOT set this to 0 any more, so someone "accidentally" changing
143 // to this "init" map on a dedicated server will cause no permanent
145 if(autocvar_g_maplist_shuffle)
147 n = tokenizebyseparator(autocvar_g_maplist, " ");
148 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
151 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
153 if(!DoNextMapOverride(1))
161 this.nextthink = time;
165 this.nextthink = time + 1;
166 LOG_INFO("Waiting for _sv_init being set to 1 by initialization scripts...");
170 void cvar_changes_init()
174 float n, i, adding, pureadding;
176 strfree(cvar_changes);
177 strfree(cvar_purechanges);
178 cvar_purechanges_count = 0;
181 buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
187 for(i = 0; i < n; ++i)
189 k = bufstr_get(h, i);
191 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
192 #define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
193 #define BADCVAR(p) if(k == p) continue
194 #define BADVALUE(p, val) if (k == p && v == val) continue
196 // general excludes and namespaces for server admin used cvars
197 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
201 BADPREFIX("cvar_check_");
203 BADCVAR("g_configversion");
204 BADCVAR("halflifebsp");
205 BADCVAR("sv_mapformat_is_quake2");
206 BADCVAR("sv_mapformat_is_quake3");
207 BADPREFIX("sv_world");
213 BADPREFIX("scoreboard_");
214 BADPREFIX("g_campaign");
215 BADPREFIX("g_waypointsprite_");
221 BADPREFIX("net_slist_");
227 BADPREFIX("sensitivity");
228 BADPREFIX("userbind");
231 BADPREFIX("crosshair");
232 BADCVAR("mod_q3bsp_lightmapmergepower");
233 BADCVAR("mod_q3bsp_nolightmaps");
235 BADCVAR("mastervolume");
237 BADCVAR("bgmvolume");
238 BADCVAR("in_pitch_min");
239 BADCVAR("in_pitch_max");
242 BADCVAR("developer");
243 BADCVAR("log_dest_udp");
244 BADCVAR("net_address");
245 BADCVAR("net_address_ipv6");
247 BADCVAR("savedgamecfg");
248 BADCVAR("serverconfig");
249 BADCVAR("sv_autoscreenshot");
250 BADCVAR("sv_heartbeatperiod");
251 BADCVAR("sv_vote_master_password");
252 BADCVAR("sys_colortranslation");
253 BADCVAR("sys_specialcharactertranslation");
254 BADCVAR("timeformat");
255 BADCVAR("timestamps");
256 BADCVAR("g_require_stats");
257 BADPREFIX("developer_");
259 BADPREFIX("g_banned_list");
260 BADPREFIX("g_require_stats_");
261 BADPREFIX("g_chat_flood_");
262 BADPREFIX("g_ghost_items");
263 BADPREFIX("g_playerstats_");
264 BADPREFIX("g_voice_flood_");
265 BADPREFIX("log_file");
268 BADPREFIX("sv_allowdownloads");
269 BADPREFIX("sv_autodemo");
270 BADPREFIX("sv_curl_");
271 BADPREFIX("sv_eventlog");
272 BADPREFIX("sv_logscores_");
273 BADPREFIX("sv_master");
274 BADPREFIX("sv_weaponstats_");
275 BADPREFIX("sv_waypointsprite_");
276 BADCVAR("rescan_pending");
278 // these can contain player IDs, so better hide
279 BADPREFIX("g_forced_team_");
280 BADCVAR("sv_muteban_list");
281 BADCVAR("sv_voteban_list");
282 BADCVAR("sv_allow_customplayermodels_idlist");
283 BADCVAR("sv_allow_customplayermodels_speciallist");
286 BADCVAR("fraglimit");
288 BADCVAR("g_assault");
290 BADCVAR("g_ca_teams");
291 BADCVAR("g_conquest");
292 BADCVAR("g_conquest_teams");
297 BADCVAR("g_domination");
298 BADCVAR("g_domination_default_teams");
300 BADCVAR("g_duel_not_dm_maps");
301 BADCVAR("g_freezetag");
302 BADCVAR("g_freezetag_teams");
303 BADCVAR("g_invasion_teams");
304 BADCVAR("g_invasion_type");
305 BADCVAR("g_jailbreak");
306 BADCVAR("g_jailbreak_teams");
307 BADCVAR("g_keepaway");
308 BADCVAR("g_keyhunt");
309 BADCVAR("g_keyhunt_teams");
312 BADCVAR("g_nexball");
313 BADCVAR("g_onslaught");
315 BADCVAR("g_race_laps_limit");
316 BADCVAR("g_race_qualifying_timelimit");
317 BADCVAR("g_race_qualifying_timelimit_override");
318 BADCVAR("g_runematch");
319 BADCVAR("g_shootfromeye");
321 BADCVAR("g_survival");
322 BADCVAR("g_survival_not_dm_maps");
324 BADCVAR("g_tdm_on_dm_maps");
325 BADCVAR("g_tdm_teams");
327 BADCVAR("g_mmm_not_dm_maps");
328 BADCVAR("g_tmayhem");
329 BADCVAR("g_tmayhem_teams");
331 BADCVAR("leadlimit");
334 BADCVAR("timelimit");
335 BADCVAR("g_mapinfo_settemp_acl");
336 BADCVAR("g_mapinfo_ignore_warnings");
337 BADCVAR("g_maplist_ignore_sizes");
338 BADCVAR("g_maplist_sizes_count_bots");
339 //LegendGuard adds BADCVAR(g_*) for MMM 20-02-2021
343 BADCVAR("hostname_full");
344 BADCVAR("g_maplist");
345 BADCVAR("g_maplist_mostrecent");
347 BADCVAR("sv_motd_permanent");
349 BADPREFIX("g_teamnames_");
352 d = cvar_defstring(k);
358 cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
359 if(strlen(cvar_changes) > 16384)
361 cvar_changes = "// too many settings have been changed to show them here\n";
366 // now check if the changes are actually gameplay relevant
368 // does nothing gameplay relevant
369 BADCVAR("captureleadlimit_override");
370 BADCVAR("condump_stripcolors");
371 BADCVAR("gameversion");
372 BADCVAR("fs_gamedir");
373 BADCVAR("g_allow_oldvortexbeam");
374 BADCVAR("g_balance_kill_delay");
375 BADCVAR("g_buffs_pickup_anyway");
376 BADCVAR("g_buffs_randomize");
377 BADCVAR("g_buffs_randomize_teamplay");
378 BADCVAR("g_campcheck_distance");
379 BADCVAR("g_chatsounds");
380 BADCVAR("g_ca_point_leadlimit");
381 BADCVAR("g_ca_point_limit");
382 BADCVAR("g_ca_spectate_enemies");
383 BADCVAR("g_ctf_captimerecord_always");
384 BADCVAR("g_ctf_flag_glowtrails");
385 BADCVAR("g_ctf_dynamiclights");
386 BADCVAR("g_ctf_flag_pickup_verbosename");
387 BADCVAR("g_ctf_flagcarrier_auto_helpme_damage");
388 BADPRESUFFIX("g_ctf_flag_", "_model");
389 BADPRESUFFIX("g_ctf_flag_", "_skin");
390 BADCVAR("g_domination_point_leadlimit");
391 BADCVAR("g_forced_respawn");
392 BADCVAR("g_freezetag_point_leadlimit");
393 BADCVAR("g_freezetag_point_limit");
394 BADCVAR("g_freezetag_revive_respawn");
395 BADCVAR("g_freezetag_round_stop");
396 BADCVAR("g_freezetag_round_respawn");
397 BADCVAR("g_glowtrails");
399 BADCVAR("g_casings");
400 BADCVAR("g_invasion_point_limit");
401 BADCVAR("g_jump_grunt");
402 BADCVAR("g_keepaway_ballcarrier_effects");
403 BADCVAR("g_keepawayball_effects");
404 BADCVAR("g_keyhunt_point_leadlimit");
405 BADCVAR("g_nexball_goalleadlimit");
406 BADCVAR("g_new_toys_autoreplace");
407 BADCVAR("g_new_toys_use_pickupsound");
408 BADCVAR("g_physics_predictall");
409 BADCVAR("g_piggyback");
410 BADCVAR("g_playerclip_collisions");
411 BADCVAR("g_spawn_alloweffects");
412 BADCVAR("g_tdm_point_leadlimit");
413 BADCVAR("g_tdm_point_limit");
414 BADCVAR("g_mayhem_fraglimit");
415 BADCVAR("g_tmayhem_fraglimit");
416 BADCVAR("g_mayhem_visual_score_limit");
417 BADCVAR("g_tmayhem_visual_score_limit");
418 BADCVAR("g_tmayhem_score_leadlimit");
419 BADCVAR("leadlimit_and_fraglimit");
420 BADCVAR("leadlimit_override");
421 BADCVAR("g_mayhem_scoringmethod");
422 BADCVAR("g_tmayhem_scoringmethod");
424 BADCVAR("sv_announcer");
425 BADCVAR("sv_checkforpacketsduringsleep");
426 BADCVAR("sv_damagetext");
427 BADCVAR("sv_db_saveasdump");
428 BADCVAR("sv_intermission_cdtrack");
429 BADCVAR("sv_mapchange_delay");
430 BADCVAR("sv_minigames");
431 BADCVAR("sv_namechangetimer");
432 BADCVAR("sv_precacheplayermodels");
433 BADCVAR("sv_qcphysics");
435 BADCVAR("sv_stepheight");
436 BADCVAR("sv_timeout");
437 BADCVAR("sv_weapons_modeloverride");
438 BADCVAR("w_prop_interval");
440 BADPREFIX("crypto_");
441 BADPREFIX("gameversion_");
442 BADPREFIX("g_chat_");
443 BADPREFIX("g_ctf_captimerecord_");
444 BADPREFIX("g_hats_");
445 BADPREFIX("g_maplist_");
447 BADPREFIX("g_respawn_");
449 BADPREFIX("notification_");
452 BADPREFIX("sv_allow_");
453 BADPREFIX("sv_cullentities_");
454 BADPREFIX("sv_maxidle");
455 BADPREFIX("sv_minigames_");
456 BADPREFIX("sv_radio_");
457 BADPREFIX("sv_timeout_");
458 BADPREFIX("sv_vote_");
459 BADPREFIX("timelimit_");
460 BADPREFIX("sv_chat_");
461 BADPREFIX("sv_jingle_");
463 // allowed changes to server admins (please sync this to server.cfg)
467 // :%s,//\([^ ]*\).*,BADCVAR("\1");,
469 // yes, this does contain some redundant stuff, don't really care
470 BADPREFIX("bot_ai_");
471 BADCVAR("bot_config_file");
472 BADCVAR("bot_number");
473 BADCVAR("bot_prefix");
474 BADCVAR("bot_suffix");
475 BADCVAR("capturelimit_override");
476 BADCVAR("fraglimit_override");
478 BADCVAR("g_antilag");
479 BADCVAR("g_balance_teams");
480 BADCVAR("g_balance_teams_prevent_imbalance");
481 BADCVAR("g_balance_teams_scorefactor");
482 BADCVAR("g_ban_sync_trusted_servers");
483 BADCVAR("g_ban_sync_uri");
485 BADCVAR("g_ca_teams_override");
486 BADCVAR("g_ctf_fullbrightflags");
487 BADCVAR("g_ctf_ignore_frags");
488 BADCVAR("g_ctf_leaderboard");
489 BADCVAR("g_domination_point_limit");
490 BADCVAR("g_domination_teams_override");
491 BADCVAR("g_freezetag_revive_spawnshield");
492 BADCVAR("g_freezetag_teams_override");
493 BADCVAR("g_friendlyfire");
494 BADCVAR("g_fullbrightitems");
495 BADCVAR("g_fullbrightplayers");
496 BADCVAR("g_keyhunt_point_limit");
497 BADCVAR("g_keyhunt_teams_override");
498 BADCVAR("g_lms_lives_override");
499 BADCVAR("g_mayhem_powerups");
500 BADCVAR("g_maplist");
501 BADCVAR("g_maxplayers");
502 BADCVAR("g_mirrordamage");
503 BADCVAR("g_nexball_goallimit");
504 BADCVAR("g_norecoil");
505 BADCVAR("g_physics_clientselect");
507 BADCVAR("g_powerups");
508 BADCVAR("g_powerups_drop_ondeath");
509 BADCVAR("g_player_brightness");
510 BADCVAR("g_rocket_flying");
511 BADCVAR("g_rocket_flying_disabledelays");
512 BADPREFIX("g_spawnshield");
513 BADCVAR("g_start_delay");
514 BADCVAR("g_superspectate");
515 BADCVAR("g_tdm_teams_override");
516 BADCVAR("g_tmayhem_teams_override");
517 BADCVAR("g_tmayhem_powerups");
519 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
522 BADCVAR("maxplayers");
523 BADCVAR("minplayers");
524 BADCVAR("minplayers_per_team");
525 BADCVAR("net_address");
527 BADCVAR("rcon_password");
528 BADCVAR("rcon_restricted_commands");
529 BADCVAR("rcon_restricted_password");
531 BADCVAR("sv_adminnick");
532 BADCVAR("sv_autoscreenshot");
533 BADCVAR("sv_autotaunt");
534 BADCVAR("sv_curl_defaulturl");
535 BADCVAR("sv_defaultcharacter");
536 BADCVAR("sv_defaultcharacterskin");
537 BADCVAR("sv_defaultplayercolors");
538 BADCVAR("sv_defaultplayermodel");
539 BADCVAR("sv_defaultplayerskin");
540 BADCVAR("sv_maxrate");
542 BADCVAR("sv_public");
543 BADCVAR("sv_ready_restart");
544 BADCVAR("sv_showfps");
545 BADCVAR("sv_status_privacy");
547 BADCVAR("sv_vote_call");
548 BADCVAR("sv_vote_commands");
549 BADCVAR("sv_vote_majority_factor");
550 BADCVAR("sv_vote_master");
551 BADCVAR("sv_vote_master_commands");
552 BADCVAR("sv_vote_master_password");
553 BADCVAR("sv_vote_simple_majority_factor");
554 BADVALUE("sys_ticrate", "0.0166667");
555 BADVALUE("sys_ticrate", "0.0333333");
556 BADCVAR("teamplay_mode");
557 BADCVAR("timelimit_override");
558 BADPREFIX("g_warmup_");
559 BADPREFIX("sv_info_");
560 BADPREFIX("sv_ready_restart_");
562 // mutators that announce themselves properly to the server browser
563 BADCVAR("g_instagib");
564 BADCVAR("g_new_toys");
566 BADCVAR("g_grappling_hook");
567 BADCVAR("g_jetpack");
569 // temporary for testing
570 // TODO remove before 0.8.3 release
571 BADCVAR("g_ca_weaponarena");
572 BADCVAR("g_freezetag_weaponarena");
573 BADCVAR("g_lms_weaponarena");
574 BADCVAR("g_mayhem_weaponarena");
575 BADCVAR("g_tmayhem_weaponarena");
576 BADCVAR("g_ctf_stalemate_time");
585 cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
586 if(strlen(cvar_purechanges) > 16384)
588 cvar_purechanges = "// too many settings have been changed to show them here\n";
592 ++cvar_purechanges_count;
593 // WARNING: this variable is used for the server list
594 // NEVER dare to skip this code!
595 // Hacks to intentionally appearing as "pure server" even though you DO have
596 // modified settings may be punished by removal from the server list.
597 // You can do to the variables cvar_changes and cvar_purechanges all you want,
601 if(cvar_changes == "")
602 cvar_changes = "// this server runs at default server settings\n";
604 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
605 cvar_changes = strzone(cvar_changes);
606 if(cvar_purechanges == "")
607 cvar_purechanges = "// this server runs at default gameplay settings\n";
609 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
610 cvar_purechanges = strzone(cvar_purechanges);
614 bool RandomSeed_Send(entity this, entity to, int sf)
616 WriteHeader(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
617 WriteShort(MSG_ENTITY, this.cnt);
620 void RandomSeed_Think(entity this)
622 this.cnt = bound(0, floor(random() * 65536), 65535);
623 this.nextthink = time + 5;
627 void RandomSeed_Spawn()
629 randomseed = new_pure(randomseed);
630 setthink(randomseed, RandomSeed_Think);
631 Net_LinkEntity(randomseed, false, 0, RandomSeed_Send);
633 getthink(randomseed)(randomseed); // sets random seed and nextthink
636 spawnfunc(__init_dedicated_server)
638 // handler for _init/_init map (only for dedicated server initialization)
640 world_initialized = -1; // don't complain
642 delete_fn = remove_unsafely;
644 entity e = new(GotoFirstMap);
645 setthink(e, GotoFirstMap);
646 e.nextthink = time; // this is usually 1 at this point
648 e = new(info_player_deathmatch); // safeguard against player joining
650 // assign reflectively to avoid "assignment to world" warning
651 for (int i = 0, n = numentityfields(); i < n; ++i) {
652 string k = entityfieldname(i);
653 if (k == "classname") {
654 // safeguard against various stuff ;)
655 putentityfieldstring(i, this, "worldspawn");
660 // needs to be done so early because of the constants they create
663 static_init_precache();
665 IL_PUSH(g_spawnpoints, e); // just incase
668 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
671 void __init_dedicated_server_shutdown() {
675 STATIC_INIT_EARLY(maxclients)
678 for (entity head = nextent(NULL); head; head = nextent(head)) {
683 void GameplayMode_DelayedInit(entity this)
685 if(!scores_initialized)
686 ScoreRules_generic();
689 void InitGameplayMode()
693 // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
695 // assign reflectively to avoid "assignment to world" warning
696 int done = 0; for (int i = 0, n = numentityfields(); i < n; ++i) {
697 string k = entityfieldname(i); vector v = (k == "mins") ? mi_min : (k == "maxs") ? mi_max : '0 0 0';
699 putentityfieldstring(i, world, sprintf("%v", v));
700 if (++done == 2) break;
703 // currently, NetRadiant's limit is 131072 qu for each side
704 // distance from one corner of a 131072qu cube to the opposite corner is approx. 227023 qu
705 // set the distance according to map size but don't go over the limit to avoid issues with float precision
706 // in case somebody makes extremely large maps
707 max_shot_distance = min(230000, vlen(world.maxs - world.mins));
709 MapInfo_LoadMapSettings(mapname);
710 GameRules_teams(false);
712 if (!cvar_value_issafe(world.fog))
714 LOG_INFO("The current map contains a potentially harmful fog setting, ignored");
715 world.fog = string_null;
717 if(MapInfo_Map_fog != "")
719 if(MapInfo_Map_fog == "none")
720 world.fog = string_null;
722 world.fog = strzone(MapInfo_Map_fog);
724 clientstuff = strzone(MapInfo_Map_clientstuff);
726 MapInfo_ClearTemps();
728 gamemode_name = MapInfo_Type_ToText(MapInfo_LoadedGametype);
730 cache_mutatormsg = strzone("");
731 cache_lastmutatormsg = strzone("");
733 InitializeEntity(NULL, GameplayMode_DelayedInit, INITPRIO_GAMETYPE_FALLBACK);
736 bool world_already_spawned;
737 spawnfunc(worldspawn)
739 server_is_dedicated = boolean(stof(cvar_defstring("is_dedicated")));
741 bool wantrestart = false;
743 if (!server_is_dedicated)
745 // force unloading of server pk3 files when starting a listen server
746 // localcmd("\nfs_rescan\n"); // FIXME: does more harm than good, has unintended side effects. What we really want is to unload temporary pk3s only
747 // restore csqc_progname too
748 string expect = "csprogs.dat";
749 wantrestart = cvar_string("csqc_progname") != expect;
750 cvar_set("csqc_progname", expect);
754 // Try to use versioned csprogs from pk3
755 // Only ever use versioned csprogs.dat files on dedicated servers;
756 // we need to reset csqc_progname on clients ourselves, and it's easier if the client's release name is constant
757 string pk3csprogs = "csprogs-" WATERMARK ".dat";
758 // This always works; fall back to it if a versioned csprogs.dat is suddenly missing
759 string select = "csprogs.dat";
760 if (fexists(pk3csprogs)) select = pk3csprogs;
761 if (cvar_string("csqc_progname") != select)
763 cvar_set("csqc_progname", select);
766 // Check for updates on startup
767 // We do it this way for atomicity so that connecting clients still match the server progs and don't disconnect
768 int sentinel = fopen("progs.txt", FILE_READ);
771 string switchversion = fgets(sentinel);
773 if (switchversion != "" && switchversion != WATERMARK)
775 LOG_INFOF("Switching progs: " WATERMARK " -> %s", switchversion);
776 // if it doesn't exist, assume either:
777 // a) the current program was overwritten
778 // b) this is a client only update
779 string newprogs = sprintf("progs-%s.dat", switchversion);
780 if (fexists(newprogs))
782 cvar_set("sv_progs", newprogs);
785 string newcsprogs = sprintf("csprogs-%s.dat", switchversion);
786 if (fexists(newcsprogs))
788 cvar_set("csqc_progname", newcsprogs);
796 LOG_INFO("Restart requested");
797 changelevel(mapname);
798 // let initialization continue, shutdown depends on it
802 if(world_already_spawned)
803 error("world already spawned - you may have EXACTLY ONE worldspawn!");
804 world_already_spawned = true;
806 delete_fn = remove_safely; // during spawning, watch what you remove!
808 cvar_changes_init(); // do this very early now so it REALLY matches the server config
810 // default to RACE_RECORD, can be overwritten by gamemodes
811 record_type = RACE_RECORD;
813 // needs to be done so early because of the constants they create
816 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
818 TemporaryDB = db_create();
823 // 1 FLICKER (first variety)
824 lightstyle(1, "mmnmmommommnonmmonqnmmo");
826 // 2 SLOW STRONG PULSE
827 lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
829 // 3 CANDLE (first variety)
830 lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
833 lightstyle(4, "mamamamamama");
836 lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
838 // 6 FLICKER (second variety)
839 lightstyle(6, "nmonqnmomnmomomno");
841 // 7 CANDLE (second variety)
842 lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
844 // 8 CANDLE (third variety)
845 lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
847 // 9 SLOW STROBE (fourth variety)
848 lightstyle(9, "aaaaaaaazzzzzzzz");
850 // 10 FLUORESCENT FLICKER
851 lightstyle(10, "mmamammmmammamamaaamammma");
853 // 11 SLOW PULSE NOT FADE TO BLACK
854 lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
856 // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
861 if(autocvar_g_campaign)
864 Map_MarkAsRecent(mapname);
866 PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
870 static_init_precache();
873 GameRules_limit_fallbacks();
875 if(warmup_limit == 0)
876 warmup_limit = (autocvar_timelimit > 0) ? autocvar_timelimit * 60 : autocvar_timelimit;
879 bot_waypoints_for_items = autocvar_g_waypoints_for_items;
880 if(bot_waypoints_for_items == 1)
881 if(this.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
882 bot_waypoints_for_items = 0;
884 WaypointSprite_Init();
886 GameLogInit(); // prepare everything
888 // changing the logic generating it is okay. But:
889 // it HAS to stay <= 64 chars
890 // character set: ASCII 33-126 without the following characters: : ; ' " \ $
891 if(autocvar_sv_eventlog)
893 string num = strftime_s(); // strftime(false, "%s") isn't reliable, see strftime_s description
894 string s = sprintf("%s.%s.%06d", itos(autocvar_sv_eventlog_files_counter), num, floor(random() * 1000000));
895 matchid = strzone(s);
897 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
898 s = ":gameinfo:mutators:LIST";
900 MUTATOR_CALLHOOK(BuildMutatorsString, s);
901 s = M_ARGV(0, string);
903 // initialiation stuff, not good in the mutator system
904 if(!autocvar_g_use_ammunition)
905 s = strcat(s, ":no_use_ammunition");
907 // initialiation stuff, not good in the mutator system
908 if(autocvar_g_pickup_items == 0)
909 s = strcat(s, ":no_pickup_items");
910 if(autocvar_g_pickup_items > 0)
911 s = strcat(s, ":pickup_items");
913 // initialiation stuff, not good in the mutator system
914 if(autocvar_g_weaponarena != "0")
915 s = strcat(s, ":", autocvar_g_weaponarena, " arena");
917 // TODO to mutator system
918 if(autocvar_g_norecoil)
919 s = strcat(s, ":norecoil");
922 GameLogEcho(":gameinfo:end");
925 matchid = strzone(ftos(random()));
927 cvar_set("nextmap", "");
931 if(autocvar_g_campaign)
937 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
939 q3compat = BITSET(q3compat, Q3COMPAT_ARENA, fexists(strcat("scripts/", mapname, ".arena")));
940 q3compat = BITSET(q3compat, Q3COMPAT_DEFI, fexists(strcat("scripts/", mapname, ".defi")));
942 if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
944 int fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
948 while((s = fgets(fd)))
950 int l = tokenize_console(s);
955 string trackname = argv(2);
956 LOG_INFO("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:");
957 LOG_INFO(" cdtrack ", trackname);
958 if (cvar_value_issafe(trackname))
960 string newstuff = strcat(clientstuff, "cd loop \"", trackname, "\"\n");
961 strcpy(clientstuff, newstuff);
964 else if(argv(0) == "fog")
966 LOG_INFO("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:");
967 LOG_INFO(" \"fog\" \"", s, "\"");
969 else if(argv(0) == "set")
971 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
972 LOG_INFO(" clientsettemp_for_type all ", argv(1), " ", argv(2));
974 else if(argv(0) != "//")
976 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
977 LOG_INFO(" clientsettemp_for_type all ", argv(0), " ", argv(1));
988 // set up information replies for clients and server to use
989 maplist_reply = strzone(getmaplist());
990 lsmaps_reply = strzone(getlsmaps());
991 monsterlist_reply = strzone(getmonsterlist());
992 bool records_available = false;
993 for(int i = 0; i < 10; ++i)
995 string s = getrecords(i);
998 records_reply[i] = strzone(s);
999 records_available = true;
1002 if (!records_available)
1003 records_reply[0] = "No records available for the current game mode.\n";
1004 ladder_reply = strzone(getladder());
1005 rankings_reply = strzone(getrankings());
1010 PingPLReport_Spawn();
1014 if (!wantrestart) localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
1016 // fill sv_curl_serverpackages from .serverpackage files
1017 if (autocvar_sv_curl_serverpackages_auto)
1019 string s = "csprogs-" WATERMARK ".dat";
1020 // remove automatically managed files from the list to prevent duplicates
1021 for (int i = 0, n = tokenize_console(cvar_string("sv_curl_serverpackages")); i < n; ++i)
1023 string pkg = argv(i);
1024 if (startsWith(pkg, "csprogs-")) continue;
1025 if (endsWith(pkg, "-serverpackage.txt")) continue;
1026 if (endsWith(pkg, ".serverpackage")) continue; // OLD legacy
1029 // add automatically managed files to the list
1030 #define X(match) MACRO_BEGIN \
1031 int fd = search_begin(match, true, false); \
1034 for (int i = 0, j = search_getsize(fd); i < j; ++i) \
1036 s = cons(s, search_getfilename(fd, i)); \
1041 X("*-serverpackage.txt");
1042 X("*.serverpackage");
1044 cvar_set("sv_curl_serverpackages", s);
1047 // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
1048 modname = "Xonotic";
1049 // physics/balance/config changes that count as mod
1050 if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
1051 modname = cvar_string("g_mod_physics");
1052 if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance") && cvar_string("g_mod_balance") != "Testing")
1053 modname = cvar_string("g_mod_balance");
1054 if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
1055 modname = cvar_string("g_mod_config");
1056 // extra mutators that deserve to count as mod
1057 MUTATOR_CALLHOOK(SetModname, modname);
1058 modname = M_ARGV(0, string);
1060 // save it for later
1061 modname = strzone(modname);
1063 WinningConditionHelper(this); // set worldstatus
1066 round_handler_Activate(true);
1069 if (autocvar_g_count_shards && warmup_stage) {
1071 send_TotalShardsAll();
1074 world_initialized = 1;
1075 __spawnfunc_spawn_all();
1080 //makestatic (this); // Who the f___ did that?
1084 bool MoveToRandomLocationWithinBounds(entity e, vector boundmin, vector boundmax, float goodcontents, float badcontents, float badsurfaceflags, int attempts, float maxaboveground, float minviewdistance)
1086 float m = e.dphitcontentsmask;
1087 e.dphitcontentsmask = goodcontents | badcontents;
1089 vector org = boundmin;
1090 vector delta = boundmax - boundmin;
1094 int j; // used after the loop
1095 for(j = 0; j < attempts; ++j)
1097 start.x = org.x + random() * delta.x;
1098 start.y = org.y + random() * delta.y;
1099 start.z = org.z + random() * delta.z;
1101 // rule 1: start inside world bounds, and outside
1102 // solid, and don't start from somewhere where you can
1103 // fall down to evil
1104 tracebox(start, e.mins, e.maxs, start - '0 0 1' * delta.z, MOVE_NORMAL, e);
1105 if (trace_fraction >= 1)
1107 if (trace_startsolid)
1109 if (trace_dphitcontents & badcontents)
1111 if (trace_dphitq3surfaceflags & badsurfaceflags)
1114 // rule 2: if we are too high, lower the point
1115 if (trace_fraction * delta.z > maxaboveground)
1116 start = trace_endpos + '0 0 1' * maxaboveground;
1117 vector enddown = trace_endpos;
1119 // rule 3: make sure we aren't outside the map. This only works
1120 // for somewhat well formed maps. A good rule of thumb is that
1121 // the map should have a convex outside hull.
1122 // these can be traceLINES as we already verified the starting box
1123 vector mstart = start + 0.5 * (e.mins + e.maxs);
1124 traceline(mstart, mstart + '1 0 0' * delta.x, MOVE_NORMAL, e);
1125 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1127 traceline(mstart, mstart - '1 0 0' * delta.x, MOVE_NORMAL, e);
1128 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1130 traceline(mstart, mstart + '0 1 0' * delta.y, MOVE_NORMAL, e);
1131 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1133 traceline(mstart, mstart - '0 1 0' * delta.y, MOVE_NORMAL, e);
1134 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1136 traceline(mstart, mstart + '0 0 1' * delta.z, MOVE_NORMAL, e);
1137 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1140 // rule 4: we must "see" some spawnpoint or item
1142 IL_EACH(g_spawnpoints, checkpvs(mstart, it),
1144 if((traceline(mstart, it.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1152 int items_checked = 0;
1153 IL_EACH(g_items, checkpvs(mstart, it),
1155 if((traceline(mstart, it.origin + (it.mins + it.maxs) * 0.5, MOVE_NORMAL, e), trace_fraction) >= 1)
1162 if(items_checked >= attempts)
1170 // find a random vector to "look at"
1171 end.x = org.x + random() * delta.x;
1172 end.y = org.y + random() * delta.y;
1173 end.z = org.z + random() * delta.z;
1174 end = start + normalize(end - start) * vlen(delta);
1176 // rule 4: start TO end must not be too short
1177 tracebox(start, e.mins, e.maxs, end, MOVE_NORMAL, e);
1178 if(trace_startsolid)
1180 if(trace_fraction < minviewdistance / vlen(delta))
1183 // rule 5: don't want to look at sky
1184 if(trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
1187 // rule 6: we must not end up in trigger_hurt
1188 if(tracebox_hits_trigger_hurt(start, e.mins, e.maxs, enddown))
1194 e.dphitcontentsmask = m;
1198 setorigin(e, start);
1199 e.angles = vectoangles(end - start);
1200 LOG_DEBUG("Needed ", ftos(j + 1), " attempts");
1206 float MoveToRandomMapLocation(entity e, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1208 return MoveToRandomLocationWithinBounds(e, world.mins, world.maxs, goodcontents, badcontents, badsurfaceflags, attempts, maxaboveground, minviewdistance);
1212 ===============================================================================
1216 ===============================================================================
1219 void DumpStats(float final)
1228 to_console = autocvar_sv_logscores_console;
1229 to_eventlog = autocvar_sv_eventlog;
1230 to_file = autocvar_sv_logscores_file;
1234 to_console = true; // always print printstats replies
1235 to_eventlog = false; // but never print them to the event log
1239 if(autocvar_sv_eventlog_console)
1240 to_console = false; // otherwise we get the output twice
1246 s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1256 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1260 fputs(file, strcat(s, "\n"));
1263 s = strcat(":labels:player:", GetPlayerScoreString(NULL, 0));
1269 fputs(file, strcat(s, "\n"));
1271 FOREACH_CLIENT(IS_REAL_CLIENT(it) || (IS_BOT_CLIENT(it) && autocvar_sv_logscores_bots), {
1272 s = strcat(":player:see-labels:", GetPlayerScoreString(it, 0), ":");
1273 s = strcat(s, ftos(rint(time - CS(it).jointime)), ":");
1274 if(IS_PLAYER(it) || MUTATOR_CALLHOOK(GetPlayerStatus, it))
1275 s = strcat(s, ftos(it.team), ":");
1277 s = strcat(s, "spectator:");
1280 LOG_HELP(s, playername(it.netname, it.team, false));
1282 GameLogEcho(strcat(s, ftos(it.playerid), ":", playername(it.netname, it.team, false)));
1284 fputs(file, strcat(s, playername(it.netname, it.team, false), "\n"));
1289 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1295 fputs(file, strcat(s, "\n"));
1297 for(i = 1; i < 16; ++i)
1299 s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1300 s = strcat(s, ":", ftos(i));
1306 fputs(file, strcat(s, "\n"));
1313 GameLogEcho(":end");
1316 fputs(file, ":end\n");
1322 go to the next level for deathmatch
1323 only called if a time or frag limit has expired
1327 game_stopped = true;
1328 intermission_running = true; // game over
1330 // enforce a wait time before allowing changelevel
1331 if(player_count > 0)
1332 intermission_exittime = time + autocvar_sv_mapchange_delay;
1334 intermission_exittime = -1;
1337 WriteByte (MSG_ALL, SVC_CDTRACK);
1338 WriteByte (MSG_ALL, 3);
1339 WriteByte (MSG_ALL, 3);
1340 // done in FixIntermission
1343 //pos = FindIntermission ();
1345 sound(NULL, CH_INFO, SND_ENDMATCH, VOL_BASE, ATTN_NONE);
1352 PlayerStats_GameReport(true);
1353 WeaponStats_Shutdown();
1355 Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_Null); // kill all centerprints now
1357 // send winner notification
1359 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, APP_TEAM_NUM(WinningConditionHelper_winnerteam, ANNCE_TEAM_WINS));
1362 if(autocvar_sv_eventlog)
1363 GameLogEcho(":gameover");
1367 FOREACH_CLIENT(IS_PLAYER(it), {
1368 FixIntermissionClient(it);
1370 bprint(playername(it.netname, it.team, false), " ^7wins.\n");
1373 target_music_kill();
1376 if(autocvar_sv_jingle_end) {
1377 int jingles_len = 0;
1381 FOREACH_WORD(autocvar_sv_jingle_end_list, it,
1383 jingles[jingles_len] = it;
1388 int song_to_play = rint(random() * (jingles_len - 1));
1390 FOREACH_CLIENT(IS_REAL_CLIENT(it),
1392 stuffcmd(it, "cd stop\n");
1393 _sound(it, CH_INFO, strcat("jingle/", jingles[song_to_play], ".ogg"), VOL_BASE * autocvar_sv_jingle_end_volume, ATTEN_NORM);
1398 if(autocvar_g_campaign)
1399 CampaignPreIntermission();
1401 MUTATOR_CALLHOOK(MatchEnd);
1403 localcmd("\nsv_hook_gameend\n");
1407 float InitiateSuddenDeath()
1409 // Check first whether normal overtimes could be added before initiating suddendeath mode
1410 // - for this timelimit_overtime needs to be >0 of course
1411 // - also check the winning condition calculated in the previous frame and only add normal overtime
1412 // again, if at the point at which timelimit would be extended again, still no winner was found
1413 if (!autocvar_g_campaign && checkrules_overtimesadded >= 0
1414 && (checkrules_overtimesadded < autocvar_timelimit_overtimes || autocvar_timelimit_overtimes < 0)
1415 && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1417 return 1; // need to call InitiateOvertime later
1421 if(!checkrules_suddendeathend)
1423 if(autocvar_g_campaign)
1424 checkrules_suddendeathend = time; // no suddendeath in campaign
1426 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1427 if(g_race && !g_race_qualifying)
1428 race_StartCompleting();
1434 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1436 ++checkrules_overtimesadded;
1437 //add one more overtime by simply extending the timelimit
1438 cvar_set("timelimit", ftos(autocvar_timelimit + autocvar_timelimit_overtime));
1439 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime * 60);
1441 sound(NULL, CH_INFO, SND_OVERTIME, VOL_BASE, ATTN_NONE);
1442 if(checkrules_overtimesadded == 1) {
1443 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_OVERTIME);
1444 overtime_starttime = time;
1448 float GetWinningCode(float fraglimitreached, float equality)
1450 if(autocvar_g_campaign == 1)
1452 if(fraglimitreached)
1461 if(fraglimitreached)
1462 return WINNING_STARTSUDDENDEATHOVERTIME;
1464 return WINNING_NEVER;
1468 if(fraglimitreached)
1476 // set the .winning flag for exactly those players with a given field value
1477 void SetWinners(.float field, float value)
1479 FOREACH_CLIENT(IS_PLAYER(it), { it.winning = (it.(field) == value); });
1482 // set the .winning flag for those players with a given field value
1483 void AddWinners(.float field, float value)
1485 FOREACH_CLIENT(IS_PLAYER(it), {
1486 if(it.(field) == value)
1491 // clear the .winning flags
1494 FOREACH_CLIENT(IS_PLAYER(it), { it.winning = 0; });
1497 void AnnounceNewLeader()
1500 if (WinningConditionHelper_equality)
1501 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_TEAM_LEADS_TIED);
1503 FOREACH_CLIENT(IS_PLAYER(it), {
1504 if(it.team == WinningConditionHelper_winnerteam)
1505 Send_Notification(NOTIF_ONE_ONLY, it, MSG_ANNCE, ANNCE_TEAM_LEADS_TEAM);
1507 Send_Notification(NOTIF_ONE_ONLY, it, MSG_ANNCE, ANNCE_TEAM_LEADS_ENEMY);
1509 Send_Notification(NOTIF_ALL_SPEC, NULL, MSG_ANNCE, APP_TEAM_NUM(WinningConditionHelper_winnerteam, ANNCE_TEAM_LEADS));
1511 if (WinningConditionHelper_equality)
1513 Send_Notification(NOTIF_ONE, WinningConditionHelper_equality_one, MSG_ANNCE, ANNCE_LEAD_TIED);
1514 Send_Notification(NOTIF_ONE, WinningConditionHelper_equality_two, MSG_ANNCE, ANNCE_LEAD_TIED);
1518 Send_Notification(NOTIF_ONE, WinningConditionHelper_winner, MSG_ANNCE, ANNCE_LEAD_GAINED);
1519 Send_Notification(NOTIF_ONE, WinningConditionHelper_second, MSG_ANNCE, ANNCE_LEAD_LOST);
1524 void AnnounceScores(float tm)
1526 WinningConditionHelper(NULL);
1527 if (Score_NewLeader()) {
1528 AnnounceNewLeader();
1530 FOREACH_CLIENT(IS_PLAYER(it), {
1532 Send_Notification(NOTIF_ONE_ONLY, it, MSG_ANNCE, ANNCE_TEAM_SCORES_TEAM);
1534 Send_Notification(NOTIF_ONE_ONLY, it, MSG_ANNCE, ANNCE_TEAM_SCORES_ENEMY);
1536 Send_Notification(NOTIF_ALL_SPEC, NULL, MSG_ANNCE, APP_TEAM_NUM(tm, ANNCE_TEAM_SCORES));
1540 float WinningCondition_Scores(float limit, float leadlimit)
1542 // TODO make everything use THIS winning condition (except LMS)
1543 WinningConditionHelper(NULL);
1547 for (int i = 1; i < 5; ++i)
1549 Team_SetTeamScore(Team_GetTeamFromIndex(i),
1550 TeamScore_GetCompareValue(Team_IndexToTeam(i)));
1555 if(WinningConditionHelper_winner)
1556 WinningConditionHelper_winner.winning = 1;
1557 if(WinningConditionHelper_winnerteam >= 0)
1558 SetWinners(team, WinningConditionHelper_winnerteam);
1560 if(WinningConditionHelper_lowerisbetter)
1562 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1563 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1567 if(WinningConditionHelper_zeroisworst)
1568 leadlimit = 0; // not supported in this mode
1570 if(MUTATOR_CALLHOOK(Scores_CountFragsRemaining))
1572 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1578 fragsleft = FLOAT_MAX;
1579 float leadingfragsleft = FLOAT_MAX;
1581 fragsleft = limit - WinningConditionHelper_topscore;
1583 leadingfragsleft = WinningConditionHelper_secondscore + leadlimit - WinningConditionHelper_topscore;
1585 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1586 fragsleft = max(fragsleft, leadingfragsleft);
1588 fragsleft = min(fragsleft, leadingfragsleft);
1591 if (fragsleft_last != fragsleft) // do not announce same remaining frags multiple times
1594 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_1);
1595 else if (fragsleft == 2)
1596 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_2);
1597 else if (fragsleft == 3)
1598 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_3);
1600 fragsleft_last = fragsleft;
1604 // z411 - lead announcer
1605 if(MUTATOR_CALLHOOK(Scores_AnnounceLeads)) {
1606 if (Score_NewLeader())
1607 AnnounceNewLeader();
1610 bool fraglimit_reached = (limit && WinningConditionHelper_topscore >= limit);
1611 bool leadlimit_reached = (leadlimit && WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1614 // only respect leadlimit_and_fraglimit when both limits are set or the game will never end
1615 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1616 limit_reached = (fraglimit_reached && leadlimit_reached);
1618 limit_reached = (fraglimit_reached || leadlimit_reached);
1620 return GetWinningCode(
1621 WinningConditionHelper_topscore && limit_reached,
1622 WinningConditionHelper_equality
1626 float WinningCondition_RanOutOfSpawns()
1628 if(have_team_spawns <= 0)
1631 if(!autocvar_g_spawn_useallspawns)
1634 if(!some_spawn_has_been_used)
1637 for (int i = 1; i < 5; ++i)
1639 Team_SetTeamScore(Team_GetTeamFromIndex(i), 0);
1642 FOREACH_CLIENT(IS_PLAYER(it) && !IS_DEAD(it),
1644 if (Team_IsValidTeam(it.team))
1646 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1650 IL_EACH(g_spawnpoints, true,
1652 if (Team_IsValidTeam(it.team))
1654 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1659 float team1_score = Team_GetTeamScore(Team_GetTeamFromIndex(1));
1660 float team2_score = Team_GetTeamScore(Team_GetTeamFromIndex(2));
1661 float team3_score = Team_GetTeamScore(Team_GetTeamFromIndex(3));
1662 float team4_score = Team_GetTeamScore(Team_GetTeamFromIndex(4));
1663 if(team1_score + team2_score + team3_score + team4_score == 0)
1665 checkrules_equality = true;
1668 else if(team1_score + team2_score + team3_score + team4_score == 1)
1673 else if(team2_score)
1675 else if(team3_score)
1677 else // if(team4_score)
1679 entity balance = TeamBalance_CheckAllowedTeams(NULL);
1680 for(i = 0; i < MAX_TEAMSCORE; ++i)
1682 for (int j = 1; j <= NUM_TEAMS; ++j)
1688 if (!TeamBalance_IsTeamAllowed(balance, j))
1692 TeamScore_AddToTeam(Team_IndexToTeam(j), i, -1000);
1696 AddWinners(team, t);
1707 Exit deathmatch games upon conditions
1710 void CheckRules_World()
1717 if (intermission_running) // someone else quit the game already
1719 if(player_count == 0) // Nobody there? Then let's go to the next map
1721 // this will actually check the player count in the next frame
1722 // again, but this shouldn't hurt
1726 // z411 don't check rules if we're in a timeout
1727 if (game_timeout) return;
1729 float timelimit = autocvar_timelimit * 60;
1730 float fraglimit = autocvar_fraglimit;
1731 float leadlimit = autocvar_leadlimit;
1732 if (leadlimit < 0) leadlimit = 0;
1734 if(warmup_stage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1737 timelimit = 0; // timelimit is not made for warmup
1739 fraglimit = 0; // no fraglimit for now
1740 leadlimit = 0; // no leadlimit for now
1745 timelimit += game_starttime;
1747 else if (timelimit < 0)
1757 if(checkrules_suddendeathend)
1759 if(!checkrules_suddendeathwarning)
1761 checkrules_suddendeathwarning = true;
1762 if(g_race && !g_race_qualifying)
1763 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_RACE_FINISHLAP);
1765 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_FRAG);
1766 checkrules_overtimesadded = 1;
1767 sound(NULL, CH_INFO, SND_OVERTIME, VOL_BASE, ATTN_NONE);
1768 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_OVERTIME);
1773 if (timelimit && time >= timelimit)
1775 if(g_race && (g_race_qualifying == 2) && timelimit > 0)
1778 float playerswithlaps;
1780 totalplayers = playerswithlaps = readyplayers = 0;
1781 FOREACH_CLIENT(IS_PLAYER(it), {
1783 if(GameRules_scoring_add(it, RACE_FASTEST, 0))
1789 // at least 2 of the players have completed a lap: start the RACE
1790 // otherwise, the players should end the qualifying on their own
1791 if(readyplayers || playerswithlaps >= 2)
1793 checkrules_suddendeathend = 0;
1794 ReadyRestart(); // go to race
1798 wantovertime |= InitiateSuddenDeath();
1801 wantovertime |= InitiateSuddenDeath();
1805 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1811 int checkrules_status = WinningCondition_RanOutOfSpawns();
1812 if(checkrules_status == WINNING_YES)
1813 bprint("Hey! Someone ran out of spawns!\n");
1814 else if(MUTATOR_CALLHOOK(CheckRules_World, checkrules_status, timelimit, fraglimit))
1815 checkrules_status = M_ARGV(0, float);
1817 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
1819 if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
1821 checkrules_status = WINNING_NEVER;
1822 checkrules_overtimesadded = -1;
1823 wantovertime |= InitiateSuddenDeath();
1826 if(checkrules_status == WINNING_NEVER)
1827 // equality cases! Nobody wins if the overtime ends in a draw.
1832 if(checkrules_status == WINNING_NEVER)
1835 checkrules_status = WINNING_YES;
1838 if(checkrules_suddendeathend)
1839 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
1840 checkrules_status = WINNING_YES;
1842 if(checkrules_status == WINNING_YES)
1844 //print("WINNING\n");
1849 float want_weapon(entity weaponinfo, float allguns)
1852 bool allow_mutatorblocked = false;
1854 if(!weaponinfo.m_id)
1857 bool mutator_returnvalue = MUTATOR_CALLHOOK(WantWeapon, weaponinfo, d, allguns, allow_mutatorblocked);
1858 d = M_ARGV(1, float);
1859 allguns = M_ARGV(2, bool);
1860 allow_mutatorblocked = M_ARGV(3, bool);
1863 d = boolean((weaponinfo.spawnflags & WEP_FLAG_NORMAL) && !(weaponinfo.spawnflags & (WEP_FLAG_HIDDEN | WEP_FLAG_SPECIALATTACK)));
1864 else if(!mutator_returnvalue)
1865 d = !(!weaponinfo.weaponstart);
1867 if(!allow_mutatorblocked && (weaponinfo.spawnflags & WEP_FLAG_MUTATORBLOCKED)) // never default mutator blocked guns
1870 float t = weaponinfo.weaponstartoverride;
1872 //LOG_INFOF("want_weapon: %s - d: %d t: %d\n", weaponinfo.netname, d, t);
1877 // 4: is set by default?
1886 /// Weapons the player normally starts with outside weapon arena.
1887 WepSet weapons_start()
1889 WepSet ret = '0 0 0';
1890 FOREACH(Weapons, it != WEP_Null, {
1891 int w = want_weapon(it, false);
1898 WepSet weapons_all()
1900 WepSet ret = '0 0 0';
1901 FOREACH(Weapons, it != WEP_Null, {
1902 if (!(it.spawnflags & (WEP_FLAG_MUTATORBLOCKED | WEP_FLAG_SPECIALATTACK)))
1908 WepSet weapons_devall()
1910 WepSet ret = '0 0 0';
1911 FOREACH(Weapons, it != WEP_Null,
1918 WepSet weapons_most()
1920 WepSet ret = '0 0 0';
1921 FOREACH(Weapons, it != WEP_Null, {
1922 if ((it.spawnflags & WEP_FLAG_NORMAL) && !(it.spawnflags & (WEP_FLAG_MUTATORBLOCKED | WEP_FLAG_HIDDEN | WEP_FLAG_SPECIALATTACK)))
1928 void weaponarena_available_all_update(entity this)
1930 if (weaponsInMapAll)
1932 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | (weaponsInMapAll & weapons_all());
1936 // if no weapons are available on the map, just fall back to all weapons arena
1937 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_all();
1941 void weaponarena_available_devall_update(entity this)
1943 if (weaponsInMapAll)
1945 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | weaponsInMapAll;
1949 // if no weapons are available on the map, just fall back to devall weapons arena
1950 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_devall();
1954 void weaponarena_available_most_update(entity this)
1956 if (weaponsInMapAll)
1958 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | (weaponsInMapAll & weapons_most());
1962 // if no weapons are available on the map, just fall back to most weapons arena
1963 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_most();
1967 void readplayerstartcvars()
1969 // initialize starting values for players
1970 start_weapons = '0 0 0';
1971 start_weapons_default = '0 0 0';
1972 start_weapons_defaultmask = '0 0 0';
1974 start_ammo_shells = 0;
1975 start_ammo_nails = 0;
1976 start_ammo_rockets = 0;
1977 start_ammo_cells = 0;
1978 start_ammo_plasma = 0;
1979 if (random_start_ammo == NULL)
1981 random_start_ammo = new_pure(random_start_ammo);
1983 start_health = cvar("g_balance_health_start");
1984 start_armorvalue = cvar("g_balance_armor_start");
1987 g_weaponarena_weapons = '0 0 0';
1989 string s = cvar_string("g_weaponarena");
1991 MUTATOR_CALLHOOK(SetWeaponArena, s);
1992 s = M_ARGV(0, string);
1994 if (s == "0" || s == "")
1998 else if (s == "off")
2000 // forcibly turn off weaponarena
2002 else if (s == "all" || s == "1")
2005 g_weaponarena_list = "All Weapons";
2006 g_weaponarena_weapons = weapons_all();
2008 else if (s == "devall")
2011 g_weaponarena_list = "Dev All Weapons";
2012 g_weaponarena_weapons = weapons_devall();
2014 else if (s == "most")
2017 g_weaponarena_list = "Most Weapons";
2018 g_weaponarena_weapons = weapons_most();
2020 else if (s == "all_available")
2023 g_weaponarena_list = "All Available Weapons";
2025 // this needs to run after weaponsInMapAll is initialized
2026 InitializeEntity(NULL, weaponarena_available_all_update, INITPRIO_FINDTARGET);
2028 else if (s == "devall_available")
2031 g_weaponarena_list = "Dev All Available Weapons";
2033 // this needs to run after weaponsInMapAll is initialized
2034 InitializeEntity(NULL, weaponarena_available_devall_update, INITPRIO_FINDTARGET);
2036 else if (s == "most_available")
2039 g_weaponarena_list = "Most Available Weapons";
2041 // this needs to run after weaponsInMapAll is initialized
2042 InitializeEntity(NULL, weaponarena_available_most_update, INITPRIO_FINDTARGET);
2044 else if (s == "none")
2047 g_weaponarena_list = "No Weapons";
2052 float t = tokenize_console(s);
2053 g_weaponarena_list = "";
2054 for (int j = 0; j < t; ++j)
2057 Weapon wep = Weapon_from_name(s);
2060 g_weaponarena_weapons |= (wep.m_wepset);
2061 g_weaponarena_list = strcat(g_weaponarena_list, wep.m_name, " & ");
2064 g_weaponarena_list = strzone(substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3));
2069 g_weapon_stay = 0; // incompatible
2070 start_weapons = g_weaponarena_weapons;
2071 start_items |= IT_UNLIMITED_AMMO | IT_UNLIMITED_SUPERWEAPONS;
2075 FOREACH(Weapons, it != WEP_Null, {
2076 int w = want_weapon(it, false);
2077 WepSet s = it.m_wepset;
2081 start_weapons_default |= s;
2083 start_weapons_defaultmask |= s;
2087 if(cvar("g_balance_superweapons_time") < 0)
2088 start_items |= IT_UNLIMITED_SUPERWEAPONS;
2090 if(!cvar("g_use_ammunition"))
2091 start_items |= IT_UNLIMITED_AMMO;
2093 if(start_items & IT_UNLIMITED_AMMO)
2095 start_ammo_shells = 999;
2096 start_ammo_nails = 999;
2097 start_ammo_rockets = 999;
2098 start_ammo_cells = 999;
2099 start_ammo_plasma = 999;
2100 start_ammo_fuel = 999;
2104 start_ammo_shells = cvar("g_start_ammo_shells");
2105 start_ammo_nails = cvar("g_start_ammo_nails");
2106 start_ammo_rockets = cvar("g_start_ammo_rockets");
2107 start_ammo_cells = cvar("g_start_ammo_cells");
2108 start_ammo_plasma = cvar("g_start_ammo_plasma");
2109 start_ammo_fuel = cvar("g_start_ammo_fuel");
2110 random_start_weapons_count = cvar("g_random_start_weapons_count");
2111 SetResource(random_start_ammo, RES_SHELLS, cvar("g_random_start_shells"));
2112 SetResource(random_start_ammo, RES_BULLETS, cvar("g_random_start_bullets"));
2113 SetResource(random_start_ammo, RES_ROCKETS, cvar("g_random_start_rockets"));
2114 SetResource(random_start_ammo, RES_CELLS, cvar("g_random_start_cells"));
2115 SetResource(random_start_ammo, RES_PLASMA, cvar("g_random_start_plasma"));
2118 warmup_start_ammo_shells = start_ammo_shells;
2119 warmup_start_ammo_nails = start_ammo_nails;
2120 warmup_start_ammo_rockets = start_ammo_rockets;
2121 warmup_start_ammo_cells = start_ammo_cells;
2122 warmup_start_ammo_plasma = start_ammo_plasma;
2123 warmup_start_ammo_fuel = start_ammo_fuel;
2124 warmup_start_health = start_health;
2125 warmup_start_armorvalue = start_armorvalue;
2126 warmup_start_weapons = start_weapons;
2127 warmup_start_weapons_default = start_weapons_default;
2128 warmup_start_weapons_defaultmask = start_weapons_defaultmask;
2132 warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
2133 warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
2134 warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
2135 warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
2136 warmup_start_ammo_plasma = cvar("g_warmup_start_ammo_plasma");
2137 warmup_start_ammo_fuel = cvar("g_warmup_start_ammo_fuel");
2138 warmup_start_health = cvar("g_warmup_start_health");
2139 warmup_start_armorvalue = cvar("g_warmup_start_armor");
2140 warmup_start_weapons = '0 0 0';
2141 warmup_start_weapons_default = '0 0 0';
2142 warmup_start_weapons_defaultmask = '0 0 0';
2143 FOREACH(Weapons, it != WEP_Null, {
2144 int w = want_weapon(it, autocvar_g_warmup_allguns);
2145 WepSet s = it.m_wepset;
2147 warmup_start_weapons |= s;
2149 warmup_start_weapons_default |= s;
2151 warmup_start_weapons_defaultmask |= s;
2155 if (autocvar_g_jetpack)
2156 start_items |= ITEM_Jetpack.m_itemid;
2158 MUTATOR_CALLHOOK(SetStartItems);
2160 if (start_items & ITEM_Jetpack.m_itemid)
2162 start_items |= ITEM_JetpackRegen.m_itemid;
2163 start_ammo_fuel = max(start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
2164 warmup_start_ammo_fuel = max(warmup_start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
2167 start_ammo_shells = max(0, start_ammo_shells);
2168 start_ammo_nails = max(0, start_ammo_nails);
2169 start_ammo_rockets = max(0, start_ammo_rockets);
2170 start_ammo_cells = max(0, start_ammo_cells);
2171 start_ammo_plasma = max(0, start_ammo_plasma);
2172 start_ammo_fuel = max(0, start_ammo_fuel);
2173 SetResource(random_start_ammo, RES_SHELLS, max(0, GetResource(random_start_ammo, RES_SHELLS)));
2174 SetResource(random_start_ammo, RES_BULLETS, max(0, GetResource(random_start_ammo, RES_BULLETS)));
2175 SetResource(random_start_ammo, RES_ROCKETS, max(0, GetResource(random_start_ammo, RES_ROCKETS)));
2176 SetResource(random_start_ammo, RES_CELLS, max(0, GetResource(random_start_ammo, RES_CELLS)));
2177 SetResource(random_start_ammo, RES_PLASMA, max(0, GetResource(random_start_ammo, RES_PLASMA)));
2179 warmup_start_ammo_shells = max(0, warmup_start_ammo_shells);
2180 warmup_start_ammo_nails = max(0, warmup_start_ammo_nails);
2181 warmup_start_ammo_rockets = max(0, warmup_start_ammo_rockets);
2182 warmup_start_ammo_cells = max(0, warmup_start_ammo_cells);
2183 warmup_start_ammo_plasma = max(0, warmup_start_ammo_plasma);
2184 warmup_start_ammo_fuel = max(0, warmup_start_ammo_fuel);
2187 void readlevelcvars()
2189 if(cvar("sv_allow_fullbright"))
2190 serverflags |= SERVERFLAG_ALLOW_FULLBRIGHT;
2191 if(cvar("sv_forbid_pickuptimer"))
2192 serverflags |= SERVERFLAG_FORBID_PICKUPTIMER;
2194 sv_ready_restart_after_countdown = cvar("sv_ready_restart_after_countdown");
2196 warmup_stage = cvar("g_warmup");
2197 warmup_limit = cvar("g_warmup_limit");
2199 if(cvar("g_campaign"))
2200 warmup_stage = 0; // no warmup during campaign
2202 g_pickup_respawntime_weapon = cvar("g_pickup_respawntime_weapon");
2203 g_pickup_respawntime_superweapon = cvar("g_pickup_respawntime_superweapon");
2204 g_pickup_respawntime_ammo = cvar("g_pickup_respawntime_ammo");
2205 g_pickup_respawntime_short = cvar("g_pickup_respawntime_short");
2206 g_pickup_respawntime_medium = cvar("g_pickup_respawntime_medium");
2207 g_pickup_respawntime_long = cvar("g_pickup_respawntime_long");
2208 g_pickup_respawntime_powerup = cvar("g_pickup_respawntime_powerup");
2209 g_pickup_respawntimejitter_weapon = cvar("g_pickup_respawntimejitter_weapon");
2210 g_pickup_respawntimejitter_superweapon = cvar("g_pickup_respawntimejitter_superweapon");
2211 g_pickup_respawntimejitter_ammo = cvar("g_pickup_respawntimejitter_ammo");
2212 g_pickup_respawntimejitter_short = cvar("g_pickup_respawntimejitter_short");
2213 g_pickup_respawntimejitter_medium = cvar("g_pickup_respawntimejitter_medium");
2214 g_pickup_respawntimejitter_long = cvar("g_pickup_respawntimejitter_long");
2215 g_pickup_respawntimejitter_powerup = cvar("g_pickup_respawntimejitter_powerup");
2217 g_pickup_shells = cvar("g_pickup_shells");
2218 g_pickup_shells_max = cvar("g_pickup_shells_max");
2219 g_pickup_nails = cvar("g_pickup_nails");
2220 g_pickup_nails_max = cvar("g_pickup_nails_max");
2221 g_pickup_rockets = cvar("g_pickup_rockets");
2222 g_pickup_rockets_max = cvar("g_pickup_rockets_max");
2223 g_pickup_cells = cvar("g_pickup_cells");
2224 g_pickup_cells_max = cvar("g_pickup_cells_max");
2225 g_pickup_plasma = cvar("g_pickup_plasma");
2226 g_pickup_plasma_max = cvar("g_pickup_plasma_max");
2227 g_pickup_fuel = cvar("g_pickup_fuel");
2228 g_pickup_fuel_jetpack = cvar("g_pickup_fuel_jetpack");
2229 g_pickup_fuel_max = cvar("g_pickup_fuel_max");
2230 g_pickup_armorsmall = cvar("g_pickup_armorsmall");
2231 g_pickup_armorsmall_max = cvar("g_pickup_armorsmall_max");
2232 g_pickup_armorsmall_anyway = cvar("g_pickup_armorsmall_anyway");
2233 g_pickup_armormedium = cvar("g_pickup_armormedium");
2234 g_pickup_armormedium_max = cvar("g_pickup_armormedium_max");
2235 g_pickup_armormedium_anyway = cvar("g_pickup_armormedium_anyway");
2236 g_pickup_armorbig = cvar("g_pickup_armorbig");
2237 g_pickup_armorbig_max = cvar("g_pickup_armorbig_max");
2238 g_pickup_armorbig_anyway = cvar("g_pickup_armorbig_anyway");
2239 g_pickup_armormega = cvar("g_pickup_armormega");
2240 g_pickup_armormega_max = cvar("g_pickup_armormega_max");
2241 g_pickup_armormega_anyway = cvar("g_pickup_armormega_anyway");
2242 g_pickup_healthsmall = cvar("g_pickup_healthsmall");
2243 g_pickup_healthsmall_max = cvar("g_pickup_healthsmall_max");
2244 g_pickup_healthsmall_anyway = cvar("g_pickup_healthsmall_anyway");
2245 g_pickup_healthmedium = cvar("g_pickup_healthmedium");
2246 g_pickup_healthmedium_max = cvar("g_pickup_healthmedium_max");
2247 g_pickup_healthmedium_anyway = cvar("g_pickup_healthmedium_anyway");
2248 g_pickup_healthbig = cvar("g_pickup_healthbig");
2249 g_pickup_healthbig_max = cvar("g_pickup_healthbig_max");
2250 g_pickup_healthbig_anyway = cvar("g_pickup_healthbig_anyway");
2251 g_pickup_healthmega = cvar("g_pickup_healthmega");
2252 g_pickup_healthmega_max = cvar("g_pickup_healthmega_max");
2253 g_pickup_healthmega_anyway = cvar("g_pickup_healthmega_anyway");
2255 g_pickup_ammo_anyway = cvar("g_pickup_ammo_anyway");
2256 g_pickup_weapons_anyway = cvar("g_pickup_weapons_anyway");
2258 g_weapon_stay = cvar(strcat("g_", GetGametype(), "_weapon_stay"));
2260 g_weapon_stay = cvar("g_weapon_stay");
2262 MUTATOR_CALLHOOK(ReadLevelCvars);
2265 game_starttime = time + cvar("g_start_delay");
2267 FOREACH(Weapons, it != WEP_Null, { it.wr_init(it); });
2269 readplayerstartcvars();
2272 void InitializeEntity(entity e, void(entity this) func, int order)
2276 if (!e || e.initialize_entity)
2278 // make a proxy initializer entity
2280 e = new(initialize_entity);
2284 e.initialize_entity = func;
2285 e.initialize_entity_order = order;
2287 cur = initialize_entity_first;
2291 if (!cur || cur.initialize_entity_order > order)
2293 // insert between prev and cur
2295 prev.initialize_entity_next = e;
2297 initialize_entity_first = e;
2298 e.initialize_entity_next = cur;
2302 cur = cur.initialize_entity_next;
2305 void InitializeEntitiesRun()
2307 entity startoflist = initialize_entity_first;
2308 initialize_entity_first = NULL;
2309 delete_fn = remove_except_protected;
2310 for (entity e = startoflist; e; e = e.initialize_entity_next)
2312 e.remove_except_protected_forbidden = 1;
2314 for (entity e = startoflist; e; )
2316 e.remove_except_protected_forbidden = 0;
2317 e.initialize_entity_order = 0;
2318 entity next = e.initialize_entity_next;
2319 e.initialize_entity_next = NULL;
2320 var void(entity this) func = e.initialize_entity;
2321 e.initialize_entity = func_null;
2322 if (e.classname == "initialize_entity")
2324 entity wrappee = e.enemy;
2328 //dprint("Delayed initialization: ", e.classname, "\n");
2336 backtrace(strcat("Null function in: ", e.classname, "\n"));
2340 delete_fn = remove_unsafely;
2343 // deferred dropping
2344 void DropToFloor_Handler(entity this)
2346 WITHSELF(this, builtin_droptofloor());
2347 this.dropped_origin = this.origin;
2350 void droptofloor(entity this)
2352 InitializeEntity(this, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
2355 bool autocvar_sv_gameplayfix_multiplethinksperframe = true;
2356 void RunThink(entity this, float dt)
2358 // don't let things stay in the past.
2359 // it is possible to start that way by a trigger with a local time.
2360 if(this.nextthink <= 0 || this.nextthink > time + dt)
2363 float oldtime = time; // do we need to save this?
2365 for (int iterations = 0; iterations < 128 && !wasfreed(this); iterations++)
2367 time = max(oldtime, this.nextthink);
2371 getthink(this)(this);
2372 // mods often set nextthink to time to cause a think every frame,
2373 // we don't want to loop in that case, so exit if the new nextthink is
2374 // <= the time the qc was told, also exit if it is past the end of the
2376 if(this.nextthink <= time || this.nextthink > oldtime + dt || !autocvar_sv_gameplayfix_multiplethinksperframe)
2383 bool autocvar_sv_freezenonclients;
2384 void Physics_Frame()
2386 if(autocvar_sv_freezenonclients || game_timeout)
2389 IL_EACH(g_moveables, true,
2391 if(IS_CLIENT(it) || it.move_movetype == MOVETYPE_PHYSICS)
2394 //set_movetype(it, it.move_movetype);
2395 // inline the set_movetype function, since this is called a lot
2396 it.movetype = (it.move_qcphysics) ? MOVETYPE_QCENTITY : it.move_movetype;
2398 if(it.move_qcphysics && it.move_movetype != MOVETYPE_NONE)
2399 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2401 if(it.movetype >= MOVETYPE_USER_FIRST && it.movetype <= MOVETYPE_USER_LAST) // these cases have no think handling
2403 if(it.move_movetype == MOVETYPE_PUSH || it.move_movetype == MOVETYPE_FAKEPUSH)
2404 continue; // these movetypes have no regular think function
2405 // handle thinking here
2406 if (getthink(it) && it.nextthink > 0 && it.nextthink <= time + PHYS_INPUT_TIMELENGTH)
2407 RunThink(it, PHYS_INPUT_TIMELENGTH);
2411 if(autocvar_sv_gameplayfix_delayprojectiles >= 0)
2414 // make a second pass to see if any ents spawned this frame and make
2415 // sure they run their move/think. this is verified by checking .move_time, which will never be 0 if the entity has moved
2416 // MOVETYPE_NONE is also checked as .move_time WILL be 0 with that movetype
2417 IL_EACH(g_moveables, it.move_qcphysics,
2419 if(IS_CLIENT(it) || it.move_time || it.move_movetype == MOVETYPE_NONE || it.move_movetype == MOVETYPE_PHYSICS)
2421 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2425 void systems_update();
2428 anticheat_endframe();
2432 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2433 entity e = IS_SPEC(it) ? it.enemy : it;
2434 if (e.typehitsound) {
2435 STAT(TYPEHIT_TIME, it) = time;
2436 } else if (e.killsound) {
2437 STAT(KILL_TIME, it) = time;
2438 } else if (e.damage_dealt) {
2439 STAT(HIT_TIME, it) = time;
2440 STAT(DAMAGE_DEALT_TOTAL, it) += ceil(e.damage_dealt);
2443 // add 1 frametime because after this, engine SV_Physics
2444 // increases time by a frametime and then networks the frame
2445 // add another frametime because client shows everything with
2446 // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2448 float altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2449 FOREACH_CLIENT(true, {
2450 it.typehitsound = false;
2451 it.damage_dealt = 0;
2452 it.killsound = false;
2453 antilag_record(it, CS(it), altime);
2455 IL_EACH(g_monsters, true,
2457 antilag_record(it, it, altime);
2459 IL_EACH(g_projectiles, it.classname == "nade",
2461 antilag_record(it, it, altime);
2470 * returns true if redirecting
2472 float redirection_timeout;
2473 float redirection_nextthink;
2474 float RedirectionThink()
2476 float clients_found;
2478 if(redirection_target == "")
2481 if(!redirection_timeout)
2483 cvar_set("sv_public", "-2");
2484 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2485 if(redirection_target == "self")
2486 bprint("^3SERVER NOTICE:^7 restarting the server\n");
2488 bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2491 if(time < redirection_nextthink)
2494 redirection_nextthink = time + 1;
2497 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2499 LOG_INFO("Redirecting: sending connect command to ", it.netname);
2500 if(redirection_target == "self")
2501 stuffcmd(it, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2503 stuffcmd(it, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2507 LOG_INFO("Redirecting: ", ftos(clients_found), " clients left.");
2509 if(time > redirection_timeout || clients_found == 0)
2510 localcmd("\nwait; wait; wait; quit\n");
2517 // Loaded from a save game
2518 // some things then break, so let's work around them...
2520 // Progs DB (capture records)
2521 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2525 MapInfo_Enumerate();
2526 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2529 TargetMusic_RestoreGame();
2536 if(world_initialized > 0)
2538 world_initialized = 0;
2540 // if a timeout is active, reset the slowmo value to normal
2541 if(timeout_status == TIMEOUT_ACTIVE)
2542 cvar_set("slowmo", ftos(orig_slowmo));
2544 LOG_TRACE("Saving persistent data...");
2547 // playerstats with unfinished match
2548 PlayerStats_GameReport(false);
2550 if(!cheatcount_total)
2552 if(autocvar_sv_db_saveasdump)
2553 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2555 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2557 if(autocvar_developer > 0)
2559 if(autocvar_sv_db_saveasdump)
2560 db_dump(TemporaryDB, "server-temp.db");
2562 db_save(TemporaryDB, "server-temp.db");
2564 CheatShutdown(); // must be after cheatcount check
2565 db_close(ServerProgsDB);
2566 db_close(TemporaryDB);
2567 LOG_TRACE("Saving persistent data... done!");
2568 // tell the bot system the game is ending now
2571 WeaponStats_Shutdown();
2574 else if(world_initialized == 0)
2576 LOG_INFO("NOTE: crashed before even initializing the world, not saving persistent data");
2580 __init_dedicated_server_shutdown();