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/ipban.qh>
39 #include <server/items/items.qh>
40 #include <server/main.qh>
41 #include <server/mapvoting.qh>
42 #include <server/mutators/_mod.qh>
43 #include <server/race.qh>
44 #include <server/scores.qh>
45 #include <server/scores_rules.qh>
46 #include <server/spawnpoints.qh>
47 #include <server/teamplay.qh>
48 #include <server/weapons/weaponstats.qh>
50 const float LATENCY_THINKRATE = 10;
55 void PingPLReport_Think(entity this)
60 delta = 3 / maxclients;
61 if(delta < sys_frametime)
63 this.nextthink = time + delta;
65 e = edict_num(this.cnt + 1);
66 if(IS_CLIENT(e) && IS_REAL_CLIENT(e))
68 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
69 WriteByte(MSG_BROADCAST, this.cnt);
70 WriteShort(MSG_BROADCAST, bound(1, rint(CS(e).ping), 32767));
71 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_packetloss * 255), 255));
72 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_movementloss * 255), 255));
74 // record latency times for clients throughout the match so we can report it to playerstats
75 if(time > (CS(e).latency_time + LATENCY_THINKRATE))
77 CS(e).latency_sum += CS(e).ping;
78 CS(e).latency_cnt += 1;
79 CS(e).latency_time = time;
80 //print("sum: ", ftos(CS(e).latency_sum), ", cnt: ", ftos(CS(e).latency_cnt), ", avg: ", ftos(CS(e).latency_sum / CS(e).latency_cnt), ".\n");
85 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
86 WriteByte(MSG_BROADCAST, this.cnt);
87 WriteShort(MSG_BROADCAST, 0);
88 WriteByte(MSG_BROADCAST, 0);
89 WriteByte(MSG_BROADCAST, 0);
91 this.cnt = (this.cnt + 1) % maxclients;
93 void PingPLReport_Spawn()
95 pingplreport = new_pure(pingplreport);
96 setthink(pingplreport, PingPLReport_Think);
97 pingplreport.nextthink = time;
100 const float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
102 void send_TotalShards(entity to) {
104 // Send total number of picked up shards
105 if(!autocvar_rjz_count_shards) return;
106 if(!IS_REAL_CLIENT(to)) return;
109 WriteHeader(MSG_ONE, TE_CSQC_TOTALSHARDS);
110 WriteInt24_t(MSG_ONE, total_shards);
113 void send_TotalShardsAll() {
115 // Send total number of picked up shards
116 if(!autocvar_rjz_count_shards) return;
118 FOREACH_CLIENT(IS_REAL_CLIENT(it) && (IS_SPEC(it) || IS_OBSERVER(it)), {
119 send_TotalShards(it);
123 void SetDefaultAlpha()
125 if (!MUTATOR_CALLHOOK(SetDefaultAlpha))
127 default_player_alpha = autocvar_g_player_alpha;
128 if(default_player_alpha == 0)
129 default_player_alpha = 1;
130 default_weapon_alpha = default_player_alpha;
134 void GotoFirstMap(entity this)
137 if(autocvar__sv_init)
139 // cvar_set("_sv_init", "0");
140 // we do NOT set this to 0 any more, so someone "accidentally" changing
141 // to this "init" map on a dedicated server will cause no permanent
143 if(autocvar_g_maplist_shuffle)
145 n = tokenizebyseparator(autocvar_g_maplist, " ");
146 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
149 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
151 if(!DoNextMapOverride(1))
159 this.nextthink = time;
163 this.nextthink = time + 1;
164 LOG_INFO("Waiting for _sv_init being set to 1 by initialization scripts...");
168 void cvar_changes_init()
172 float n, i, adding, pureadding;
174 strfree(cvar_changes);
175 strfree(cvar_purechanges);
176 cvar_purechanges_count = 0;
179 buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
185 for(i = 0; i < n; ++i)
187 k = bufstr_get(h, i);
189 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
190 #define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
191 #define BADCVAR(p) if(k == p) continue
192 #define BADVALUE(p, val) if (k == p && v == val) continue
194 // general excludes and namespaces for server admin used cvars
195 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
199 BADPREFIX("cvar_check_");
201 BADCVAR("g_configversion");
202 BADCVAR("halflifebsp");
203 BADCVAR("sv_mapformat_is_quake2");
204 BADCVAR("sv_mapformat_is_quake3");
205 BADPREFIX("sv_world");
211 BADPREFIX("scoreboard_");
212 BADPREFIX("g_campaign");
213 BADPREFIX("g_waypointsprite_");
219 BADPREFIX("net_slist_");
225 BADPREFIX("sensitivity");
226 BADPREFIX("userbind");
229 BADPREFIX("crosshair");
230 BADCVAR("mod_q3bsp_lightmapmergepower");
231 BADCVAR("mod_q3bsp_nolightmaps");
233 BADCVAR("mastervolume");
235 BADCVAR("bgmvolume");
236 BADCVAR("in_pitch_min");
237 BADCVAR("in_pitch_max");
240 BADCVAR("developer");
241 BADCVAR("log_dest_udp");
242 BADCVAR("net_address");
243 BADCVAR("net_address_ipv6");
245 BADCVAR("savedgamecfg");
246 BADCVAR("serverconfig");
247 BADCVAR("sv_autoscreenshot");
248 BADCVAR("sv_heartbeatperiod");
249 BADCVAR("sv_vote_master_password");
250 BADCVAR("sys_colortranslation");
251 BADCVAR("sys_specialcharactertranslation");
252 BADCVAR("timeformat");
253 BADCVAR("timestamps");
254 BADCVAR("g_require_stats");
255 BADPREFIX("developer_");
257 BADPREFIX("g_banned_list");
258 BADPREFIX("g_require_stats_");
259 BADPREFIX("g_chat_flood_");
260 BADPREFIX("g_ghost_items");
261 BADPREFIX("g_playerstats_");
262 BADPREFIX("g_voice_flood_");
263 BADPREFIX("log_file");
266 BADPREFIX("sv_allowdownloads");
267 BADPREFIX("sv_autodemo");
268 BADPREFIX("sv_curl_");
269 BADPREFIX("sv_eventlog");
270 BADPREFIX("sv_logscores_");
271 BADPREFIX("sv_master");
272 BADPREFIX("sv_weaponstats_");
273 BADPREFIX("sv_waypointsprite_");
274 BADCVAR("rescan_pending");
276 // these can contain player IDs, so better hide
277 BADPREFIX("g_forced_team_");
278 BADCVAR("sv_muteban_list");
279 BADCVAR("sv_voteban_list");
280 BADCVAR("sv_allow_customplayermodels_idlist");
281 BADCVAR("sv_allow_customplayermodels_speciallist");
284 BADCVAR("fraglimit");
286 BADCVAR("g_assault");
288 BADCVAR("g_ca_teams");
289 BADCVAR("g_conquest");
290 BADCVAR("g_conquest_teams");
295 BADCVAR("g_domination");
296 BADCVAR("g_domination_default_teams");
298 BADCVAR("g_duel_not_dm_maps");
299 BADCVAR("g_freezetag");
300 BADCVAR("g_freezetag_teams");
301 BADCVAR("g_invasion_type");
302 BADCVAR("g_jailbreak");
303 BADCVAR("g_jailbreak_teams");
304 BADCVAR("g_keepaway");
305 BADCVAR("g_keyhunt");
306 BADCVAR("g_keyhunt_teams");
309 BADCVAR("g_nexball");
310 BADCVAR("g_onslaught");
312 BADCVAR("g_race_laps_limit");
313 BADCVAR("g_race_qualifying_timelimit");
314 BADCVAR("g_race_qualifying_timelimit_override");
315 BADCVAR("g_runematch");
316 BADCVAR("g_shootfromeye");
318 BADCVAR("g_survival");
319 BADCVAR("g_survival_not_dm_maps");
321 BADCVAR("g_tdm_on_dm_maps");
322 BADCVAR("g_tdm_teams");
323 BADCVAR("g_tmayhem");
324 BADCVAR("g_tmayhem_teams");
326 BADCVAR("leadlimit");
329 BADCVAR("timelimit");
330 BADCVAR("g_mapinfo_q3compat");
331 BADCVAR("g_mapinfo_settemp_acl");
332 BADCVAR("g_mapinfo_ignore_warnings");
333 BADCVAR("g_maplist_ignore_sizes");
334 BADCVAR("g_maplist_sizes_count_bots");
337 BADCVAR("hostname_full");
338 BADCVAR("g_maplist");
339 BADCVAR("g_maplist_mostrecent");
341 BADCVAR("sv_motd_permanent");
343 BADPREFIX("g_teamnames_");
344 BADCVAR("sv_termsofservice_url");
347 d = cvar_defstring(k);
353 cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
354 if(strlen(cvar_changes) > 16384)
356 cvar_changes = "// too many settings have been changed to show them here\n";
361 // now check if the changes are actually gameplay relevant
363 // does nothing gameplay relevant
364 BADCVAR("captureleadlimit_override");
365 BADCVAR("condump_stripcolors");
366 BADCVAR("fs_gamedir");
367 BADCVAR("g_allow_oldvortexbeam");
368 BADCVAR("g_balance_kill_delay");
369 BADCVAR("g_buffs_pickup_anyway");
370 BADCVAR("g_buffs_randomize");
371 BADCVAR("g_buffs_randomize_teamplay");
372 BADCVAR("g_campcheck_distance");
373 BADCVAR("g_chatsounds");
374 BADCVAR("g_ca_point_leadlimit");
375 BADCVAR("g_ca_point_limit");
376 BADCVAR("g_ca_spectate_enemies");
377 BADCVAR("g_ctf_captimerecord_always");
378 BADCVAR("g_ctf_flag_glowtrails");
379 BADCVAR("g_ctf_dynamiclights");
380 BADCVAR("g_ctf_flag_pickup_verbosename");
381 BADCVAR("g_ctf_flagcarrier_auto_helpme_damage");
382 BADPRESUFFIX("g_ctf_flag_", "_model");
383 BADPRESUFFIX("g_ctf_flag_", "_skin");
384 BADCVAR("g_domination_point_leadlimit");
385 BADCVAR("g_forced_respawn");
386 BADCVAR("g_freezetag_point_leadlimit");
387 BADCVAR("g_freezetag_point_limit");
388 BADCVAR("g_freezetag_revive_respawn");
389 BADCVAR("g_freezetag_round_stop");
390 BADCVAR("g_freezetag_round_respawn");
391 BADCVAR("g_glowtrails");
393 BADCVAR("g_casings");
394 BADCVAR("g_invasion_point_limit");
395 BADCVAR("g_jump_grunt");
396 BADCVAR("g_keepaway_ballcarrier_effects");
397 BADCVAR("g_keepawayball_effects");
398 BADCVAR("g_keyhunt_point_leadlimit");
399 BADCVAR("g_nexball_goalleadlimit");
400 BADCVAR("g_new_toys_autoreplace");
401 BADCVAR("g_new_toys_use_pickupsound");
402 BADCVAR("g_physics_predictall");
403 BADCVAR("g_piggyback");
404 BADCVAR("g_playerclip_collisions");
405 BADCVAR("g_spawn_alloweffects");
406 BADCVAR("g_tdm_point_leadlimit");
407 BADCVAR("g_tdm_point_limit");
408 BADCVAR("g_mayhem_fraglimit");
409 BADCVAR("g_tmayhem_fraglimit");
410 BADCVAR("g_mayhem_visual_score_limit");
411 BADCVAR("g_tmayhem_visual_score_limit");
412 BADCVAR("g_tmayhem_score_leadlimit");
413 BADCVAR("leadlimit_and_fraglimit");
414 BADCVAR("leadlimit_override");
415 BADCVAR("g_mayhem_scoringmethod");
416 BADCVAR("g_mayhem_scoringmethod_damage_weight");
417 BADCVAR("g_mayhem_scoringmethod_frag_weight");
418 BADCVAR("g_tmayhem_scoringmethod");
419 BADCVAR("g_tmayhem_scoringmethod_damage_weight");
420 BADCVAR("g_tmayhem_scoringmethod_frag_weight");
422 BADCVAR("sv_announcer");
423 BADCVAR("sv_checkforpacketsduringsleep");
424 BADCVAR("sv_damagetext");
425 BADCVAR("sv_db_saveasdump");
426 BADCVAR("sv_intermission_cdtrack");
427 BADCVAR("sv_mapchange_delay");
428 BADCVAR("sv_minigames");
429 BADCVAR("sv_namechangetimer");
430 BADCVAR("sv_precacheplayermodels");
431 BADCVAR("sv_qcphysics");
433 BADCVAR("sv_stepheight");
434 BADCVAR("sv_timeout");
435 BADCVAR("sv_weapons_modeloverride");
436 BADCVAR("w_prop_interval");
438 BADPREFIX("crypto_");
439 BADPREFIX("gameversion");
440 BADPREFIX("g_chat_");
441 BADPREFIX("g_ctf_captimerecord_");
442 BADPREFIX("g_hats_");
443 BADPREFIX("g_maplist_");
445 BADPREFIX("g_respawn_");
447 BADPREFIX("notification_");
450 BADPREFIX("sv_allow_");
451 BADPREFIX("sv_cullentities_");
452 BADPREFIX("sv_maxidle");
453 BADPREFIX("sv_minigames_");
454 BADPREFIX("sv_radio_");
455 BADPREFIX("sv_timeout_");
456 BADPREFIX("sv_vote_");
457 BADPREFIX("timelimit_");
458 BADPREFIX("sv_chat_");
459 BADPREFIX("sv_jingle_");
460 BADPRESUFFIX("g_", "_round_timelimit");
462 // allowed changes to server admins (please sync this to server.cfg)
466 // :%s,//\([^ ]*\).*,BADCVAR("\1");,
468 // yes, this does contain some redundant stuff, don't really care
469 BADPREFIX("bot_ai_");
470 BADCVAR("bot_config_file");
471 BADCVAR("bot_number");
472 BADCVAR("bot_prefix");
473 BADCVAR("bot_suffix");
474 BADCVAR("capturelimit_override");
475 BADCVAR("fraglimit_override");
477 BADCVAR("g_antilag");
478 BADCVAR("g_balance_teams");
479 BADCVAR("g_balance_teams_prevent_imbalance");
480 BADCVAR("g_balance_teams_scorefactor");
481 BADCVAR("g_ban_sync_trusted_servers");
482 BADCVAR("g_ban_sync_uri");
484 BADCVAR("g_ca_teams_override");
485 BADCVAR("g_ctf_fullbrightflags");
486 BADCVAR("g_ctf_ignore_frags");
487 BADCVAR("g_ctf_leaderboard");
488 BADCVAR("g_domination_point_limit");
489 BADCVAR("g_domination_teams_override");
490 BADCVAR("g_freezetag_revive_spawnshield");
491 BADCVAR("g_freezetag_teams_override");
492 BADCVAR("g_friendlyfire");
493 BADCVAR("g_fullbrightitems");
494 BADCVAR("g_fullbrightplayers");
495 BADCVAR("g_keyhunt_point_limit");
496 BADCVAR("g_keyhunt_teams_override");
497 BADCVAR("g_lms_lives_override");
498 BADCVAR("g_mayhem_powerups");
499 BADCVAR("g_maplist");
500 BADCVAR("g_maxplayers");
501 BADCVAR("g_mirrordamage");
502 BADCVAR("g_nexball_goallimit");
503 BADCVAR("g_norecoil");
504 BADCVAR("g_physics_clientselect");
506 BADCVAR("g_powerups");
507 BADCVAR("g_powerups_drop_ondeath");
508 BADCVAR("g_player_brightness");
509 BADCVAR("g_rocket_flying");
510 BADCVAR("g_rocket_flying_disabledelays");
511 BADPREFIX("g_spawnshield");
512 BADCVAR("g_start_delay");
513 BADCVAR("g_superspectate");
514 BADCVAR("g_tdm_teams_override");
515 BADCVAR("g_tmayhem_teams_override");
516 BADCVAR("g_tmayhem_powerups");
517 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
520 BADCVAR("maxplayers");
521 BADCVAR("minplayers");
522 BADCVAR("minplayers_per_team");
523 BADCVAR("net_address");
525 BADCVAR("rcon_password");
526 BADCVAR("rcon_restricted_commands");
527 BADCVAR("rcon_restricted_password");
529 BADCVAR("sv_adminnick");
530 BADCVAR("sv_autoscreenshot");
531 BADCVAR("sv_autotaunt");
532 BADCVAR("sv_curl_defaulturl");
533 BADCVAR("sv_defaultcharacter");
534 BADCVAR("sv_defaultcharacterskin");
535 BADCVAR("sv_defaultplayercolors");
536 BADCVAR("sv_defaultplayermodel");
537 BADCVAR("sv_defaultplayerskin");
538 BADCVAR("sv_maxrate");
540 BADCVAR("sv_public");
541 BADCVAR("sv_showfps");
542 BADCVAR("sv_showspectators");
543 BADCVAR("sv_status_privacy");
545 BADCVAR("sv_vote_call");
546 BADCVAR("sv_vote_commands");
547 BADCVAR("sv_vote_majority_factor");
548 BADCVAR("sv_vote_master");
549 BADCVAR("sv_vote_master_commands");
550 BADCVAR("sv_vote_master_password");
551 BADCVAR("sv_vote_simple_majority_factor");
552 BADVALUE("sys_ticrate", "0.0166667");
553 BADVALUE("sys_ticrate", "0.0333333");
554 BADCVAR("teamplay_mode");
555 BADCVAR("timelimit_override");
556 BADPREFIX("g_warmup");
557 BADPREFIX("sv_info_");
558 BADPREFIX("sv_ready_restart_");
560 // mutators that announce themselves properly to the server browser
561 BADCVAR("g_instagib");
562 BADCVAR("g_new_toys");
564 BADCVAR("g_grappling_hook");
565 BADCVAR("g_jetpack");
567 // temporary for testing
568 // TODO remove before 0.8.3 release
569 BADCVAR("g_ca_weaponarena");
570 BADCVAR("g_freezetag_weaponarena");
571 BADCVAR("g_lms_weaponarena");
572 BADCVAR("g_mayhem_weaponarena");
573 BADCVAR("g_tmayhem_weaponarena");
574 BADCVAR("g_ctf_stalemate_time");
583 cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
584 if(strlen(cvar_purechanges) > 16384)
586 cvar_purechanges = "// too many settings have been changed to show them here\n";
590 ++cvar_purechanges_count;
591 // WARNING: this variable is used for the server list
592 // NEVER dare to skip this code!
593 // Hacks to intentionally appearing as "pure server" even though you DO have
594 // modified settings may be punished by removal from the server list.
595 // You can do to the variables cvar_changes and cvar_purechanges all you want,
599 if(cvar_changes == "")
600 cvar_changes = "// this server runs at default server settings\n";
602 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
603 cvar_changes = strzone(cvar_changes);
604 if(cvar_purechanges == "")
605 cvar_purechanges = "// this server runs at default gameplay settings\n";
607 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
608 cvar_purechanges = strzone(cvar_purechanges);
612 bool RandomSeed_Send(entity this, entity to, int sf)
614 WriteHeader(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
615 WriteShort(MSG_ENTITY, this.cnt);
618 void RandomSeed_Think(entity this)
620 this.cnt = bound(0, floor(random() * 65536), 65535);
621 this.nextthink = time + 5;
625 void RandomSeed_Spawn()
627 randomseed = new_pure(randomseed);
628 setthink(randomseed, RandomSeed_Think);
629 Net_LinkEntity(randomseed, false, 0, RandomSeed_Send);
631 getthink(randomseed)(randomseed); // sets random seed and nextthink
634 spawnfunc(__init_dedicated_server)
636 // handler for _init/_init map (only for dedicated server initialization)
638 world_initialized = -1; // don't complain
640 delete_fn = remove_unsafely;
642 entity e = new(GotoFirstMap);
643 setthink(e, GotoFirstMap);
644 e.nextthink = time; // this is usually 1 at this point
646 e = new(info_player_deathmatch); // safeguard against player joining
648 // assign reflectively to avoid "assignment to world" warning
649 for (int i = 0, n = numentityfields(); i < n; ++i)
651 string k = entityfieldname(i);
652 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 // at this stage team entities are spawned, teamplay contains the number of them
687 if(!scores_initialized)
688 ScoreRules_generic();
690 if (warmup_stage >= 0 && autocvar_g_maxplayers >= 0)
693 MapReadSizes(mapname);
695 if (autocvar_g_maxplayers < 0 && teamplay)
697 // automatic maxplayers should be a multiple of team count
698 if (map_maxplayers == 0 || map_maxplayers > maxclients)
699 map_maxplayers = maxclients; // unlimited, but may need rounding
700 int d = map_maxplayers % AVAILABLE_TEAMS;
701 int u = AVAILABLE_TEAMS - d;
702 map_maxplayers += (u <= d && u + map_maxplayers <= maxclients) ? u : -d;
705 if (warmup_stage < 0)
707 int m = GetPlayerLimit();
708 if (m <= 0) m = maxclients;
709 map_minplayers = bound(max(2, AVAILABLE_TEAMS * 2), map_minplayers, m);
712 // automatic minplayers should be a multiple of team count
713 int d = map_minplayers % AVAILABLE_TEAMS;
714 int u = AVAILABLE_TEAMS - d;
715 map_minplayers += (u < d && u + map_minplayers <= m) ? u : -d;
720 map_minplayers = 0; // don't display a minimum if it's not used
723 void InitGameplayMode()
727 // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
729 // assign reflectively to avoid "assignment to world" warning
730 for (int i = 0, done = 0, n = numentityfields(); i < n; ++i)
732 string k = entityfieldname(i);
733 vector v = (k == "mins") ? mi_min : (k == "maxs") ? mi_max : '0 0 0';
736 putentityfieldstring(i, world, sprintf("%v", v));
737 if (++done == 2) break;
740 // currently, NetRadiant's limit is 131072 qu for each side
741 // distance from one corner of a 131072qu cube to the opposite corner is approx. 227023 qu
742 // set the distance according to map size but don't go over the limit to avoid issues with float precision
743 // in case somebody makes extremely large maps
744 max_shot_distance = min(230000, vlen(world.maxs - world.mins));
746 MapInfo_LoadMapSettings(mapname);
747 GameRules_teams(false);
749 if (!cvar_value_issafe(world.fog))
751 LOG_INFO("The current map contains a potentially harmful fog setting, ignored");
752 world.fog = string_null;
754 if(MapInfo_Map_fog != "")
756 if(MapInfo_Map_fog == "none")
757 world.fog = string_null;
759 world.fog = strzone(MapInfo_Map_fog);
761 clientstuff = strzone(MapInfo_Map_clientstuff);
763 MapInfo_ClearTemps();
765 gamemode_name = MapInfo_Type_ToText(MapInfo_LoadedGametype);
767 cache_mutatormsg = strzone("");
768 cache_lastmutatormsg = strzone("");
770 InitializeEntity(NULL, GameplayMode_DelayedInit, INITPRIO_GAMETYPE_FALLBACK);
773 bool world_already_spawned;
774 spawnfunc(worldspawn)
776 cvar_set("_endmatch", "0");
777 server_is_dedicated = boolean(stof(cvar_defstring("is_dedicated")));
779 if (autocvar_sv_termsofservice_url && autocvar_sv_termsofservice_url != "")
781 strcpy(sv_termsofservice_url_escaped, strreplace(":", "|", autocvar_sv_termsofservice_url));
785 strcpy(sv_termsofservice_url_escaped, "INVALID");
788 bool wantrestart = false;
790 if (!server_is_dedicated)
792 // force unloading of server pk3 files when starting a listen server
793 // localcmd("\nfs_rescan\n"); // FIXME: does more harm than good, has unintended side effects. What we really want is to unload temporary pk3s only
794 // restore csqc_progname too
795 string expect = "csprogs.dat";
796 wantrestart = cvar_string("csqc_progname") != expect;
797 cvar_set("csqc_progname", expect);
801 // Try to use versioned csprogs from pk3
802 // Only ever use versioned csprogs.dat files on dedicated servers;
803 // we need to reset csqc_progname on clients ourselves, and it's easier if the client's release name is constant
804 string pk3csprogs = "csprogs-" WATERMARK ".dat";
805 // This always works; fall back to it if a versioned csprogs.dat is suddenly missing
806 string select = "csprogs.dat";
807 if (fexists(pk3csprogs)) select = pk3csprogs;
808 if (cvar_string("csqc_progname") != select)
810 cvar_set("csqc_progname", select);
813 // Check for updates on startup
814 // We do it this way for atomicity so that connecting clients still match the server progs and don't disconnect
815 int sentinel = fopen("progs.txt", FILE_READ);
818 string switchversion = fgets(sentinel);
820 if (switchversion != "" && switchversion != WATERMARK)
822 LOG_INFOF("Switching progs: " WATERMARK " -> %s", switchversion);
823 // if it doesn't exist, assume either:
824 // a) the current program was overwritten
825 // b) this is a client only update
826 string newprogs = sprintf("progs-%s.dat", switchversion);
827 if (fexists(newprogs))
829 cvar_set("sv_progs", newprogs);
832 string newcsprogs = sprintf("csprogs-%s.dat", switchversion);
833 if (fexists(newcsprogs))
835 cvar_set("csqc_progname", newcsprogs);
843 LOG_INFO("Restart requested");
844 changelevel(mapname);
845 // let initialization continue, shutdown depends on it
849 if(world_already_spawned)
850 error("world already spawned - you may have EXACTLY ONE worldspawn!");
851 world_already_spawned = true;
853 delete_fn = remove_safely; // during spawning, watch what you remove!
855 cvar_changes_init(); // do this very early now so it REALLY matches the server config
857 // default to RACE_RECORD, can be overwritten by gamemodes
858 record_type = RACE_RECORD;
860 // needs to be done so early because of the constants they create
863 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
865 TemporaryDB = db_create();
870 // 1 FLICKER (first variety)
871 lightstyle(1, "mmnmmommommnonmmonqnmmo");
873 // 2 SLOW STRONG PULSE
874 lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
876 // 3 CANDLE (first variety)
877 lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
880 lightstyle(4, "mamamamamama");
883 lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
885 // 6 FLICKER (second variety)
886 lightstyle(6, "nmonqnmomnmomomno");
888 // 7 CANDLE (second variety)
889 lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
891 // 8 CANDLE (third variety)
892 lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
894 // 9 SLOW STROBE (fourth variety)
895 lightstyle(9, "aaaaaaaazzzzzzzz");
897 // 10 FLUORESCENT FLICKER
898 lightstyle(10, "mmamammmmammamamaaamammma");
900 // 11 SLOW PULSE NOT FADE TO BLACK
901 lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
903 // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
908 if(autocvar_g_campaign)
911 PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
913 Map_MarkAsRecent(mapname);
917 static_init_precache();
920 GameRules_limit_fallbacks();
922 if(warmup_limit == 0)
923 warmup_limit = autocvar_timelimit * 60;
926 bot_waypoints_for_items = autocvar_g_waypoints_for_items;
927 if(bot_waypoints_for_items == 1)
928 if(this.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
929 bot_waypoints_for_items = 0;
931 WaypointSprite_Init();
934 // changing the logic generating it is okay. But:
935 // it HAS to stay <= 64 chars
936 // character set: ASCII 33-126 without the following characters: : ; ' " \ $
937 // strftime(false, "%s") isn't reliable, see strftime_s description
938 matchid = strzone(sprintf("%d.%s.%06d", autocvar_sv_eventlog_files_counter, strftime_s(), random() * 1000000));
940 if(autocvar_sv_eventlog)
941 GameLogInit(); // requires matchid to be set
943 cvar_set("nextmap", "");
947 if(autocvar_g_campaign)
953 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
955 q3compat = BITSET(q3compat, Q3COMPAT_ARENA, _MapInfo_FindArenaFile(mapname, ".arena") != "");
956 q3compat = BITSET(q3compat, Q3COMPAT_DEFI, _MapInfo_FindArenaFile(mapname, ".defi") != "");
958 // quake 3 music support
959 if(world.music || world.noise)
961 // prefer .music over .noise
964 chosen_music = world.music;
966 chosen_music = world.noise;
968 string newstuff = strcat(clientstuff, "cd loop \"", chosen_music, "\"\n");
969 strcpy(clientstuff, newstuff);
972 if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
974 int fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
978 while((s = fgets(fd)))
980 int l = tokenize_console(s);
985 string trackname = argv(2);
986 LOG_INFO("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:");
987 LOG_INFO(" cdtrack ", trackname);
988 if (cvar_value_issafe(trackname))
990 string newstuff = strcat(clientstuff, "cd loop \"", trackname, "\"\n");
991 strcpy(clientstuff, newstuff);
994 else if(argv(0) == "fog")
996 LOG_INFO("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:");
997 LOG_INFO(" \"fog\" \"", s, "\"");
999 else if(argv(0) == "set")
1001 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
1002 LOG_INFO(" clientsettemp_for_type all ", argv(1), " ", argv(2));
1004 else if(argv(0) != "//")
1006 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
1007 LOG_INFO(" clientsettemp_for_type all ", argv(0), " ", argv(1));
1018 // set up information replies for clients and server to use
1019 maplist_reply = strzone(getmaplist());
1020 lsmaps_reply = strzone(getlsmaps());
1021 monsterlist_reply = strzone(getmonsterlist());
1022 bool records_available = false;
1023 for(int i = 0; i < 10; ++i)
1025 string s = getrecords(i);
1028 records_reply[i] = strzone(s);
1029 records_available = true;
1032 if (!records_available)
1033 records_reply[0] = "No records available for the current game mode.\n";
1034 ladder_reply = strzone(getladder());
1035 rankings_reply = strzone(getrankings());
1040 PingPLReport_Spawn();
1044 if (!wantrestart) localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
1046 // fill sv_curl_serverpackages from .serverpackage files
1047 if (autocvar_sv_curl_serverpackages_auto)
1049 string s = "csprogs-" WATERMARK ".dat";
1050 // remove automatically managed files from the list to prevent duplicates
1051 for (int i = 0, n = tokenize_console(cvar_string("sv_curl_serverpackages")); i < n; ++i)
1053 string pkg = argv(i);
1054 if (startsWith(pkg, "csprogs-")) continue;
1055 if (endsWith(pkg, "-serverpackage.txt")) continue;
1056 if (endsWith(pkg, ".serverpackage")) continue; // OLD legacy
1059 // add automatically managed files to the list
1060 #define X(match) MACRO_BEGIN \
1061 int fd = search_begin(match, true, false); \
1064 for (int i = 0, j = search_getsize(fd); i < j; ++i) \
1066 s = cons(s, search_getfilename(fd, i)); \
1071 X("*-serverpackage.txt");
1072 X("*.serverpackage");
1074 cvar_set("sv_curl_serverpackages", s);
1077 // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
1078 modname = "Xonotic";
1079 // physics/balance/config changes that count as mod
1080 if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
1081 modname = cvar_string("g_mod_physics");
1082 if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance") && cvar_string("g_mod_balance") != "Testing")
1083 modname = cvar_string("g_mod_balance");
1084 if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
1085 modname = cvar_string("g_mod_config");
1086 // extra mutators that deserve to count as mod
1087 MUTATOR_CALLHOOK(SetModname, modname);
1088 modname = M_ARGV(0, string);
1090 // save it for later
1091 modname = strzone(modname);
1093 WinningConditionHelper(this); // set worldstatus
1095 round_handler_Activate(!warmup_stage);
1098 if (autocvar_rjz_count_shards && warmup_stage) {
1100 send_TotalShardsAll();
1103 world_initialized = 1;
1104 __spawnfunc_spawn_all();
1109 //makestatic (this); // Who the f___ did that?
1113 bool MoveToRandomLocationWithinBounds(entity e, vector boundmin, vector boundmax, float goodcontents, float badcontents, float badsurfaceflags, int attempts, float maxaboveground, float minviewdistance, bool frompos)
1115 float m = e.dphitcontentsmask;
1116 e.dphitcontentsmask = goodcontents | badcontents;
1118 vector org = boundmin;
1119 vector delta = boundmax - boundmin;
1123 int j; // used after the loop
1124 for(j = 0; j < attempts; ++j)
1126 start.x = org.x + random() * delta.x;
1127 start.y = org.y + random() * delta.y;
1128 start.z = org.z + random() * delta.z;
1130 // rule 1: start inside world bounds, and outside
1131 // solid, and don't start from somewhere where you can
1132 // fall down to evil
1133 tracebox(start, e.mins, e.maxs, start - '0 0 1' * delta.z, MOVE_NORMAL, e);
1134 if (trace_fraction >= 1)
1136 if (trace_startsolid)
1138 if (trace_dphitcontents & badcontents)
1140 if (trace_dphitq3surfaceflags & badsurfaceflags)
1143 // rule 2: if we are too high, lower the point
1144 if (trace_fraction * delta.z > maxaboveground)
1145 start = trace_endpos + '0 0 1' * maxaboveground;
1146 vector enddown = trace_endpos;
1148 // rule 3: make sure we aren't outside the map. This only works
1149 // for somewhat well formed maps. A good rule of thumb is that
1150 // the map should have a convex outside hull.
1151 // these can be traceLINES as we already verified the starting box
1152 vector mstart = start + 0.5 * (e.mins + e.maxs);
1153 traceline(mstart, mstart + '1 0 0' * delta.x, MOVE_NORMAL, e);
1154 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1156 traceline(mstart, mstart - '1 0 0' * delta.x, MOVE_NORMAL, e);
1157 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1159 traceline(mstart, mstart + '0 1 0' * delta.y, MOVE_NORMAL, e);
1160 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1162 traceline(mstart, mstart - '0 1 0' * delta.y, MOVE_NORMAL, e);
1163 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1165 traceline(mstart, mstart + '0 0 1' * delta.z, MOVE_NORMAL, e);
1166 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1169 // rule 4: we must "see" some spawnpoint or item
1173 if((traceline(mstart, e.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1178 IL_EACH(g_spawnpoints, checkpvs(mstart, it),
1180 if((traceline(mstart, it.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1189 int items_checked = 0;
1190 IL_EACH(g_items, checkpvs(mstart, it),
1192 if((traceline(mstart, it.origin + (it.mins + it.maxs) * 0.5, MOVE_NORMAL, e), trace_fraction) >= 1)
1199 if(items_checked >= attempts)
1207 // find a random vector to "look at"
1208 end.x = org.x + random() * delta.x;
1209 end.y = org.y + random() * delta.y;
1210 end.z = org.z + random() * delta.z;
1211 end = start + normalize(end - start) * vlen(delta);
1213 // rule 4: start TO end must not be too short
1214 tracebox(start, e.mins, e.maxs, end, MOVE_NORMAL, e);
1215 if(trace_startsolid)
1217 if(trace_fraction < minviewdistance / vlen(delta))
1220 // rule 5: don't want to look at sky
1221 if(trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
1224 // rule 6: we must not end up in trigger_hurt
1225 if(tracebox_hits_trigger_hurt(start, e.mins, e.maxs, enddown))
1231 e.dphitcontentsmask = m;
1235 setorigin(e, start);
1236 e.angles = vectoangles(end - start);
1237 LOG_DEBUG("Needed ", ftos(j + 1), " attempts");
1243 float MoveToRandomMapLocation(entity e, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1245 return MoveToRandomLocationWithinBounds(e, world.mins, world.maxs, goodcontents, badcontents, badsurfaceflags, attempts, maxaboveground, minviewdistance, false);
1249 ===============================================================================
1253 ===============================================================================
1256 void DumpStats(float final)
1265 to_console = autocvar_sv_logscores_console;
1266 to_eventlog = autocvar_sv_eventlog;
1267 to_file = autocvar_sv_logscores_file;
1271 to_console = true; // always print printstats replies
1272 to_eventlog = false; // but never print them to the event log
1276 if(autocvar_sv_eventlog_console)
1277 to_console = false; // otherwise we get the output twice
1283 s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1293 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1297 fputs(file, strcat(s, "\n"));
1300 s = strcat(":labels:player:", GetPlayerScoreString(NULL, 0));
1306 fputs(file, strcat(s, "\n"));
1308 FOREACH_CLIENT(IS_REAL_CLIENT(it) || (IS_BOT_CLIENT(it) && autocvar_sv_logscores_bots), {
1309 s = strcat(":player:see-labels:", GetPlayerScoreString(it, 0), ":");
1310 s = strcat(s, ftos(rint(time - CS(it).jointime)), ":");
1311 if(IS_PLAYER(it) || INGAME_JOINED(it))
1312 s = strcat(s, ftos(it.team), ":");
1314 s = strcat(s, "spectator:");
1317 LOG_HELP(s, playername(it.netname, it.team, false));
1319 GameLogEcho(strcat(s, ftos(it.playerid), ":", playername(it.netname, it.team, false)));
1321 fputs(file, strcat(s, playername(it.netname, it.team, false), "\n"));
1326 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1332 fputs(file, strcat(s, "\n"));
1334 for(i = 1; i < 16; ++i)
1336 s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1337 s = strcat(s, ":", ftos(i));
1343 fputs(file, strcat(s, "\n"));
1350 GameLogEcho(":end");
1353 fputs(file, ":end\n");
1359 go to the next level for deathmatch
1360 only called if a time or frag limit has expired
1364 cvar_set("_endmatch", "0");
1365 game_stopped = true;
1366 intermission_running = true; // game over
1368 // enforce a wait time before allowing changelevel
1369 if(player_count > 0)
1370 intermission_exittime = time + autocvar_sv_mapchange_delay;
1372 intermission_exittime = -1;
1375 WriteByte (MSG_ALL, SVC_CDTRACK);
1376 WriteByte (MSG_ALL, 3);
1377 WriteByte (MSG_ALL, 3);
1378 // done in FixIntermission
1381 //pos = FindIntermission ();
1383 sound(NULL, CH_INFO, SND_ENDMATCH, VOL_BASE, ATTN_NONE);
1390 PlayerStats_GameReport(true);
1391 WeaponStats_Shutdown();
1393 Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_Null); // kill all centerprints now
1395 // send winner notification
1397 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, APP_TEAM_NUM(WinningConditionHelper_winnerteam, ANNCE_TEAM_WINS));
1400 if(autocvar_sv_eventlog)
1401 GameLogEcho(":gameover");
1405 int winner_team = 0;
1406 FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), {
1407 FixIntermissionClient(it);
1410 if (teamplay && !winner_team)
1412 winner_team = it.team;
1413 bprint(Team_ColorCode(winner_team), Team_ColorName_Upper(winner_team), "^7 team wins the match\n");
1415 bprint(playername(it.netname, it.team, false), " ^7wins\n");
1419 target_music_kill();
1422 if(autocvar_sv_jingle_end) {
1423 int jingles_len = 0;
1427 FOREACH_WORD(autocvar_sv_jingle_end_list, it,
1429 jingles[jingles_len] = it;
1434 int song_to_play = rint(random() * (jingles_len - 1));
1436 FOREACH_CLIENT(IS_REAL_CLIENT(it),
1438 stuffcmd(it, "cd stop\n");
1439 _sound(it, CH_INFO, strcat("jingle/", jingles[song_to_play], ".ogg"), VOL_BASE * autocvar_sv_jingle_end_volume, ATTEN_NORM);
1444 if(autocvar_g_campaign)
1445 CampaignPreIntermission();
1447 MUTATOR_CALLHOOK(MatchEnd);
1449 localcmd("\nsv_hook_gameend\n");
1453 int InitiateSuddenDeath()
1455 // Check first whether normal overtimes could be added before initiating suddendeath mode
1456 // - for this timelimit_overtime needs to be >0 of course
1457 // - also check the winning condition calculated in the previous frame and only add normal overtime
1458 // again, if at the point at which timelimit would be extended again, still no winner was found
1459 if (!autocvar_g_campaign && checkrules_overtimesadded >= 0
1460 && (checkrules_overtimesadded < autocvar_timelimit_overtimes || autocvar_timelimit_overtimes < 0)
1461 && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1463 return 1; // need to call InitiateOvertime later
1467 if(!checkrules_suddendeathend)
1469 if(autocvar_g_campaign)
1471 checkrules_suddendeathend = time; // no suddendeath in campaign
1475 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1478 if(g_race && !g_race_qualifying)
1479 race_StartCompleting();
1485 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1487 ++checkrules_overtimesadded;
1488 overtimes = checkrules_overtimesadded;
1489 //add one more overtime by simply extending the timelimit
1490 cvar_set("timelimit", ftos(autocvar_timelimit + autocvar_timelimit_overtime));
1491 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime * 60);
1493 sound(NULL, CH_INFO, SND_OVERTIME, VOL_BASE, ATTN_NONE);
1494 if(checkrules_overtimesadded == 1) {
1495 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_OVERTIME);
1496 overtime_starttime = time;
1500 float GetWinningCode(float fraglimitreached, float equality)
1502 if(autocvar_g_campaign == 1)
1504 if(fraglimitreached)
1513 if(fraglimitreached)
1514 return WINNING_STARTSUDDENDEATHOVERTIME;
1516 return WINNING_NEVER;
1520 if(fraglimitreached)
1528 // set the .winning flag for exactly those players with a given field value
1529 void SetWinners(.float field, float value)
1531 FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), { it.winning = (it.(field) == value); });
1534 // set the .winning flag for those players with a given field value
1535 void AddWinners(.float field, float value)
1537 FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), {
1538 if(it.(field) == value)
1543 // clear the .winning flags
1546 FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), { it.winning = 0; });
1549 void AnnounceNewLeader()
1551 // Don't announce if in warmup or just started
1552 if(warmup_stage || time - game_starttime < 1) return;
1555 if (WinningConditionHelper_equality)
1556 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_TEAM_LEADS_TIED);
1558 FOREACH_CLIENT(IS_PLAYER(it), {
1559 if(it.team == WinningConditionHelper_winnerteam)
1560 Send_Notification(NOTIF_ONE_ONLY, it, MSG_ANNCE, ANNCE_TEAM_LEADS_TEAM);
1562 Send_Notification(NOTIF_ONE_ONLY, it, MSG_ANNCE, ANNCE_TEAM_LEADS_ENEMY);
1564 Send_Notification(NOTIF_ALL_SPEC, NULL, MSG_ANNCE, APP_TEAM_NUM(WinningConditionHelper_winnerteam, ANNCE_TEAM_LEADS));
1566 if (WinningConditionHelper_equality)
1568 Send_Notification(NOTIF_ONE, WinningConditionHelper_equality_one, MSG_ANNCE, ANNCE_LEAD_TIED);
1569 Send_Notification(NOTIF_ONE, WinningConditionHelper_equality_two, MSG_ANNCE, ANNCE_LEAD_TIED);
1573 Send_Notification(NOTIF_ONE, WinningConditionHelper_winner, MSG_ANNCE, ANNCE_LEAD_GAINED);
1574 Send_Notification(NOTIF_ONE, WinningConditionHelper_second, MSG_ANNCE, ANNCE_LEAD_LOST);
1579 void AnnounceScores(float tm)
1581 WinningConditionHelper(NULL);
1582 if (Score_NewLeader()) {
1583 AnnounceNewLeader();
1585 FOREACH_CLIENT(IS_PLAYER(it), {
1587 Send_Notification(NOTIF_ONE_ONLY, it, MSG_ANNCE, ANNCE_TEAM_SCORES_TEAM);
1589 Send_Notification(NOTIF_ONE_ONLY, it, MSG_ANNCE, ANNCE_TEAM_SCORES_ENEMY);
1591 Send_Notification(NOTIF_ALL_SPEC, NULL, MSG_ANNCE, APP_TEAM_NUM(tm, ANNCE_TEAM_SCORES));
1595 float WinningCondition_Scores(float limit, float leadlimit)
1597 // TODO make everything use THIS winning condition (except LMS)
1598 WinningConditionHelper(NULL);
1602 for (int i = 1; i < 5; ++i)
1604 Team_SetTeamScore(Team_GetTeamFromIndex(i),
1605 TeamScore_GetCompareValue(Team_IndexToTeam(i)));
1610 if(WinningConditionHelper_winner)
1611 WinningConditionHelper_winner.winning = 1;
1612 if(WinningConditionHelper_winnerteam >= 0)
1613 SetWinners(team, WinningConditionHelper_winnerteam);
1615 if(WinningConditionHelper_lowerisbetter)
1617 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1618 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1622 if(WinningConditionHelper_zeroisworst)
1623 leadlimit = 0; // not supported in this mode
1625 if(MUTATOR_CALLHOOK(Scores_CountFragsRemaining))
1627 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1633 fragsleft = FLOAT_MAX;
1634 float leadingfragsleft = FLOAT_MAX;
1636 fragsleft = limit - WinningConditionHelper_topscore;
1638 leadingfragsleft = WinningConditionHelper_secondscore + leadlimit - WinningConditionHelper_topscore;
1640 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1641 fragsleft = max(fragsleft, leadingfragsleft);
1643 fragsleft = min(fragsleft, leadingfragsleft);
1646 if (fragsleft_last != fragsleft) // do not announce same remaining frags multiple times
1649 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_1);
1650 else if (fragsleft == 2)
1651 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_2);
1652 else if (fragsleft == 3)
1653 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_3);
1655 fragsleft_last = fragsleft;
1659 // z411 - lead announcer
1660 if(MUTATOR_CALLHOOK(Scores_AnnounceLeads)) {
1661 if (Score_NewLeader())
1662 AnnounceNewLeader();
1665 bool fraglimit_reached = (limit && WinningConditionHelper_topscore >= limit);
1666 bool leadlimit_reached = (leadlimit && WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1669 // only respect leadlimit_and_fraglimit when both limits are set or the game will never end
1670 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1671 limit_reached = (fraglimit_reached && leadlimit_reached);
1673 limit_reached = (fraglimit_reached || leadlimit_reached);
1675 return GetWinningCode(
1676 WinningConditionHelper_topscore && limit_reached,
1677 WinningConditionHelper_equality
1681 float WinningCondition_RanOutOfSpawns()
1683 if(have_team_spawns <= 0)
1686 if(!autocvar_g_spawn_useallspawns)
1689 if(!some_spawn_has_been_used)
1692 for (int i = 1; i < 5; ++i)
1694 Team_SetTeamScore(Team_GetTeamFromIndex(i), 0);
1697 FOREACH_CLIENT(IS_PLAYER(it) && !IS_DEAD(it),
1699 if (Team_IsValidTeam(it.team))
1701 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1705 IL_EACH(g_spawnpoints, true,
1707 if (Team_IsValidTeam(it.team))
1709 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1714 float team1_score = Team_GetTeamScore(Team_GetTeamFromIndex(1));
1715 float team2_score = Team_GetTeamScore(Team_GetTeamFromIndex(2));
1716 float team3_score = Team_GetTeamScore(Team_GetTeamFromIndex(3));
1717 float team4_score = Team_GetTeamScore(Team_GetTeamFromIndex(4));
1718 if(team1_score + team2_score + team3_score + team4_score == 0)
1720 checkrules_equality = true;
1723 else if(team1_score + team2_score + team3_score + team4_score == 1)
1728 else if(team2_score)
1730 else if(team3_score)
1732 else // if(team4_score)
1734 entity balance = TeamBalance_CheckAllowedTeams(NULL);
1735 for(i = 0; i < MAX_TEAMSCORE; ++i)
1737 for (int j = 1; j <= NUM_TEAMS; ++j)
1743 if (!TeamBalance_IsTeamAllowed(balance, j))
1747 TeamScore_AddToTeam(Team_IndexToTeam(j), i, -1000);
1751 AddWinners(team, t);
1762 Exit deathmatch games upon conditions
1765 void CheckRules_World()
1772 if (intermission_running) // someone else quit the game already
1774 if(player_count == 0) // Nobody there? Then let's go to the next map
1776 // this will actually check the player count in the next frame
1777 // again, but this shouldn't hurt
1781 // z411 don't check rules if we're in a timeout
1782 if (game_timeout) return;
1784 float timelimit = autocvar_timelimit * 60;
1785 float fraglimit = autocvar_fraglimit;
1786 float leadlimit = autocvar_leadlimit;
1787 if (leadlimit < 0) leadlimit = 0;
1789 if(warmup_stage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1792 timelimit = 0; // timelimit is not made for warmup
1794 fraglimit = 0; // no fraglimit for now
1795 leadlimit = 0; // no leadlimit for now
1798 if (autocvar__endmatch || timelimit < 0)
1806 timelimit += game_starttime;
1808 int overtimes_prev = overtimes;
1809 int wantovertime = 0;
1811 if(checkrules_suddendeathend)
1813 if(!checkrules_suddendeathwarning)
1815 checkrules_suddendeathwarning = true;
1816 if(g_race && !g_race_qualifying)
1817 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_RACE_FINISHLAP);
1819 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_FRAG);
1820 checkrules_overtimesadded = 1;
1821 sound(NULL, CH_INFO, SND_OVERTIME, VOL_BASE, ATTN_NONE);
1822 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_OVERTIME);
1827 if (timelimit && time >= timelimit)
1829 if(g_race && (g_race_qualifying == 2) && timelimit > 0)
1832 float playerswithlaps;
1834 totalplayers = playerswithlaps = readyplayers = 0;
1835 FOREACH_CLIENT(IS_PLAYER(it), {
1837 if(GameRules_scoring_add(it, RACE_FASTEST, 0))
1843 // at least 2 of the players have completed a lap: start the RACE
1844 // otherwise, the players should end the qualifying on their own
1845 if(readyplayers || playerswithlaps >= 2)
1847 checkrules_suddendeathend = 0;
1848 ReadyRestart(true); // go to race
1852 wantovertime |= InitiateSuddenDeath();
1855 wantovertime |= InitiateSuddenDeath();
1859 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1865 int checkrules_status = WinningCondition_RanOutOfSpawns();
1866 if(checkrules_status == WINNING_YES)
1867 bprint("Hey! Someone ran out of spawns!\n");
1868 else if(MUTATOR_CALLHOOK(CheckRules_World, checkrules_status, timelimit, fraglimit))
1869 checkrules_status = M_ARGV(0, float);
1871 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
1873 if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
1875 checkrules_status = WINNING_NEVER;
1876 checkrules_overtimesadded = -1;
1877 wantovertime |= InitiateSuddenDeath();
1880 if(checkrules_status == WINNING_NEVER)
1881 // equality cases! Nobody wins if the overtime ends in a draw.
1886 if(checkrules_status == WINNING_NEVER)
1889 checkrules_status = WINNING_YES;
1892 if(checkrules_suddendeathend)
1893 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
1894 checkrules_status = WINNING_YES;
1896 if(checkrules_status == WINNING_YES)
1898 if (overtimes == -1 && overtimes != overtimes_prev)
1900 // if suddendeathend overtime has just begun, revert it
1901 checkrules_suddendeathend = 0;
1902 overtimes = overtimes_prev;
1904 //print("WINNING\n");
1909 float want_weapon(entity weaponinfo, float allguns)
1912 bool allow_mutatorblocked = false;
1914 if(!weaponinfo.m_id)
1917 bool mutator_returnvalue = MUTATOR_CALLHOOK(WantWeapon, weaponinfo, d, allguns, allow_mutatorblocked);
1918 d = M_ARGV(1, float);
1919 allguns = M_ARGV(2, bool);
1920 allow_mutatorblocked = M_ARGV(3, bool);
1923 d = boolean((weaponinfo.spawnflags & WEP_FLAG_NORMAL) && !(weaponinfo.spawnflags & (WEP_FLAG_HIDDEN | WEP_FLAG_SPECIALATTACK)));
1924 else if(!mutator_returnvalue)
1925 d = !(!weaponinfo.weaponstart);
1927 if(!allow_mutatorblocked && (weaponinfo.spawnflags & WEP_FLAG_MUTATORBLOCKED)) // never default mutator blocked guns
1930 float t = weaponinfo.weaponstartoverride;
1932 //LOG_INFOF("want_weapon: %s - d: %d t: %d\n", weaponinfo.netname, d, t);
1937 // 4: is set by default?
1946 /// Weapons the player normally starts with outside weapon arena.
1947 WepSet weapons_start()
1949 WepSet ret = '0 0 0';
1950 FOREACH(Weapons, it != WEP_Null, {
1951 int w = want_weapon(it, false);
1958 WepSet weapons_all()
1960 WepSet ret = '0 0 0';
1961 FOREACH(Weapons, it != WEP_Null, {
1962 if (!(it.spawnflags & (WEP_FLAG_MUTATORBLOCKED | WEP_FLAG_SPECIALATTACK)))
1968 WepSet weapons_devall()
1970 WepSet ret = '0 0 0';
1971 FOREACH(Weapons, it != WEP_Null,
1978 WepSet weapons_most()
1980 WepSet ret = '0 0 0';
1981 FOREACH(Weapons, it != WEP_Null, {
1982 if ((it.spawnflags & WEP_FLAG_NORMAL) && !(it.spawnflags & (WEP_FLAG_MUTATORBLOCKED | WEP_FLAG_HIDDEN | WEP_FLAG_SPECIALATTACK)))
1988 void weaponarena_available_all_update(entity this)
1990 if (weaponsInMapAll)
1992 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | (weaponsInMapAll & weapons_all());
1996 // if no weapons are available on the map, just fall back to all weapons arena
1997 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_all();
2001 void weaponarena_available_devall_update(entity this)
2003 if (weaponsInMapAll)
2005 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | weaponsInMapAll;
2009 // if no weapons are available on the map, just fall back to devall weapons arena
2010 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_devall();
2014 void weaponarena_available_most_update(entity this)
2016 if (weaponsInMapAll)
2018 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | (weaponsInMapAll & weapons_most());
2022 // if no weapons are available on the map, just fall back to most weapons arena
2023 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_most();
2027 void readplayerstartcvars()
2029 // initialize starting values for players
2030 start_weapons = '0 0 0';
2031 start_weapons_default = '0 0 0';
2032 start_weapons_defaultmask = '0 0 0';
2034 start_ammo_shells = 0;
2035 start_ammo_nails = 0;
2036 start_ammo_rockets = 0;
2037 start_ammo_cells = 0;
2038 start_ammo_plasma = 0;
2039 if (random_start_ammo == NULL)
2041 random_start_ammo = new_pure(random_start_ammo);
2043 start_health = cvar("g_balance_health_start");
2044 start_armorvalue = cvar("g_balance_armor_start");
2047 g_weaponarena_weapons = '0 0 0';
2049 string s = cvar_string("g_weaponarena");
2051 MUTATOR_CALLHOOK(SetWeaponArena, s);
2052 s = M_ARGV(0, string);
2054 if (s == "0" || s == "")
2058 else if (s == "off")
2060 // forcibly turn off weaponarena
2062 else if (s == "all" || s == "1")
2065 g_weaponarena_list = "All Weapons Arena";
2066 g_weaponarena_weapons = weapons_all();
2068 else if (s == "devall")
2071 g_weaponarena_list = "Dev All Weapons Arena";
2072 g_weaponarena_weapons = weapons_devall();
2074 else if (s == "most")
2077 g_weaponarena_list = "Most Weapons Arena";
2078 g_weaponarena_weapons = weapons_most();
2080 else if (s == "all_available")
2083 g_weaponarena_list = "All Available Weapons Arena";
2085 // this needs to run after weaponsInMapAll is initialized
2086 InitializeEntity(NULL, weaponarena_available_all_update, INITPRIO_FINDTARGET);
2088 else if (s == "devall_available")
2091 g_weaponarena_list = "Dev All Available Weapons Arena";
2093 // this needs to run after weaponsInMapAll is initialized
2094 InitializeEntity(NULL, weaponarena_available_devall_update, INITPRIO_FINDTARGET);
2096 else if (s == "most_available")
2099 g_weaponarena_list = "Most Available Weapons Arena";
2101 // this needs to run after weaponsInMapAll is initialized
2102 InitializeEntity(NULL, weaponarena_available_most_update, INITPRIO_FINDTARGET);
2104 else if (s == "none")
2107 g_weaponarena_list = "No Weapons Arena";
2112 float t = tokenize_console(s);
2113 g_weaponarena_list = "";
2114 for (int j = 0; j < t; ++j)
2117 Weapon wep = Weapon_from_name(s);
2120 g_weaponarena_weapons |= (wep.m_wepset);
2121 g_weaponarena_list = strcat(g_weaponarena_list, wep.netname, " & ");
2124 if (g_weaponarena_list != "") // remove trailing " & "
2125 g_weaponarena_list = substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3);
2126 else // no valid weapon found
2127 g_weaponarena_list = "No Weapons Arena";
2132 g_weapon_stay = 0; // incompatible
2133 start_weapons = g_weaponarena_weapons;
2134 start_items |= IT_UNLIMITED_AMMO | IT_UNLIMITED_SUPERWEAPONS;
2135 g_weaponarena_list = strzone(g_weaponarena_list);
2139 FOREACH(Weapons, it != WEP_Null, {
2140 int w = want_weapon(it, false);
2141 WepSet s = it.m_wepset;
2145 start_weapons_default |= s;
2147 start_weapons_defaultmask |= s;
2151 if(cvar("g_balance_superweapons_time") < 0)
2152 start_items |= IT_UNLIMITED_SUPERWEAPONS;
2154 if(!cvar("g_use_ammunition"))
2155 start_items |= IT_UNLIMITED_AMMO;
2157 if(start_items & IT_UNLIMITED_AMMO)
2159 start_ammo_shells = 999;
2160 start_ammo_nails = 999;
2161 start_ammo_rockets = 999;
2162 start_ammo_cells = 999;
2163 start_ammo_plasma = 999;
2164 start_ammo_fuel = 999;
2168 start_ammo_shells = cvar("g_start_ammo_shells");
2169 start_ammo_nails = cvar("g_start_ammo_nails");
2170 start_ammo_rockets = cvar("g_start_ammo_rockets");
2171 start_ammo_cells = cvar("g_start_ammo_cells");
2172 start_ammo_plasma = cvar("g_start_ammo_plasma");
2173 start_ammo_fuel = cvar("g_start_ammo_fuel");
2174 random_start_weapons_count = cvar("g_random_start_weapons_count");
2175 SetResource(random_start_ammo, RES_SHELLS, cvar("g_random_start_shells"));
2176 SetResource(random_start_ammo, RES_BULLETS, cvar("g_random_start_bullets"));
2177 SetResource(random_start_ammo, RES_ROCKETS, cvar("g_random_start_rockets"));
2178 SetResource(random_start_ammo, RES_CELLS, cvar("g_random_start_cells"));
2179 SetResource(random_start_ammo, RES_PLASMA, cvar("g_random_start_plasma"));
2182 warmup_start_ammo_shells = start_ammo_shells;
2183 warmup_start_ammo_nails = start_ammo_nails;
2184 warmup_start_ammo_rockets = start_ammo_rockets;
2185 warmup_start_ammo_cells = start_ammo_cells;
2186 warmup_start_ammo_plasma = start_ammo_plasma;
2187 warmup_start_ammo_fuel = start_ammo_fuel;
2188 warmup_start_health = start_health;
2189 warmup_start_armorvalue = start_armorvalue;
2190 warmup_start_weapons = start_weapons;
2191 warmup_start_weapons_default = start_weapons_default;
2192 warmup_start_weapons_defaultmask = start_weapons_defaultmask;
2196 warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
2197 warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
2198 warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
2199 warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
2200 warmup_start_ammo_plasma = cvar("g_warmup_start_ammo_plasma");
2201 warmup_start_ammo_fuel = cvar("g_warmup_start_ammo_fuel");
2202 warmup_start_health = cvar("g_warmup_start_health");
2203 warmup_start_armorvalue = cvar("g_warmup_start_armor");
2204 warmup_start_weapons = '0 0 0';
2205 warmup_start_weapons_default = '0 0 0';
2206 warmup_start_weapons_defaultmask = '0 0 0';
2207 FOREACH(Weapons, it != WEP_Null, {
2208 int w = want_weapon(it, autocvar_g_warmup_allguns);
2209 WepSet s = it.m_wepset;
2211 warmup_start_weapons |= s;
2213 warmup_start_weapons_default |= s;
2215 warmup_start_weapons_defaultmask |= s;
2219 if (autocvar_g_jetpack)
2220 start_items |= ITEM_Jetpack.m_itemid;
2222 MUTATOR_CALLHOOK(SetStartItems);
2224 if (start_items & ITEM_Jetpack.m_itemid)
2226 start_items |= ITEM_JetpackRegen.m_itemid;
2227 start_ammo_fuel = max(start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
2228 warmup_start_ammo_fuel = max(warmup_start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
2231 start_ammo_shells = max(0, start_ammo_shells);
2232 start_ammo_nails = max(0, start_ammo_nails);
2233 start_ammo_rockets = max(0, start_ammo_rockets);
2234 start_ammo_cells = max(0, start_ammo_cells);
2235 start_ammo_plasma = max(0, start_ammo_plasma);
2236 start_ammo_fuel = max(0, start_ammo_fuel);
2237 SetResource(random_start_ammo, RES_SHELLS, max(0, GetResource(random_start_ammo, RES_SHELLS)));
2238 SetResource(random_start_ammo, RES_BULLETS, max(0, GetResource(random_start_ammo, RES_BULLETS)));
2239 SetResource(random_start_ammo, RES_ROCKETS, max(0, GetResource(random_start_ammo, RES_ROCKETS)));
2240 SetResource(random_start_ammo, RES_CELLS, max(0, GetResource(random_start_ammo, RES_CELLS)));
2241 SetResource(random_start_ammo, RES_PLASMA, max(0, GetResource(random_start_ammo, RES_PLASMA)));
2243 warmup_start_ammo_shells = max(0, warmup_start_ammo_shells);
2244 warmup_start_ammo_nails = max(0, warmup_start_ammo_nails);
2245 warmup_start_ammo_rockets = max(0, warmup_start_ammo_rockets);
2246 warmup_start_ammo_cells = max(0, warmup_start_ammo_cells);
2247 warmup_start_ammo_plasma = max(0, warmup_start_ammo_plasma);
2248 warmup_start_ammo_fuel = max(0, warmup_start_ammo_fuel);
2251 void readlevelcvars()
2253 serverflags &= ~SERVERFLAG_ALLOW_FULLBRIGHT;
2254 if(cvar("sv_allow_fullbright"))
2255 serverflags |= SERVERFLAG_ALLOW_FULLBRIGHT;
2256 if(cvar("sv_forbid_pickuptimer"))
2257 serverflags |= SERVERFLAG_FORBID_PICKUPTIMER;
2259 sv_ready_restart_after_countdown = cvar("sv_ready_restart_after_countdown");
2261 warmup_stage = cvar("g_warmup");
2262 warmup_limit = cvar("g_warmup_limit");
2264 if(cvar("g_campaign"))
2265 warmup_stage = 0; // no warmup during campaign
2267 g_pickup_respawntime_weapon = cvar("g_pickup_respawntime_weapon");
2268 g_pickup_respawntime_superweapon = cvar("g_pickup_respawntime_superweapon");
2269 g_pickup_respawntime_ammo = cvar("g_pickup_respawntime_ammo");
2270 g_pickup_respawntime_short = cvar("g_pickup_respawntime_short");
2271 g_pickup_respawntime_medium = cvar("g_pickup_respawntime_medium");
2272 g_pickup_respawntime_long = cvar("g_pickup_respawntime_long");
2273 g_pickup_respawntime_powerup = cvar("g_pickup_respawntime_powerup");
2274 g_pickup_respawntimejitter_weapon = cvar("g_pickup_respawntimejitter_weapon");
2275 g_pickup_respawntimejitter_superweapon = cvar("g_pickup_respawntimejitter_superweapon");
2276 g_pickup_respawntimejitter_ammo = cvar("g_pickup_respawntimejitter_ammo");
2277 g_pickup_respawntimejitter_short = cvar("g_pickup_respawntimejitter_short");
2278 g_pickup_respawntimejitter_medium = cvar("g_pickup_respawntimejitter_medium");
2279 g_pickup_respawntimejitter_long = cvar("g_pickup_respawntimejitter_long");
2280 g_pickup_respawntimejitter_powerup = cvar("g_pickup_respawntimejitter_powerup");
2282 g_pickup_shells = cvar("g_pickup_shells");
2283 g_pickup_shells_max = cvar("g_pickup_shells_max");
2284 g_pickup_nails = cvar("g_pickup_nails");
2285 g_pickup_nails_max = cvar("g_pickup_nails_max");
2286 g_pickup_rockets = cvar("g_pickup_rockets");
2287 g_pickup_rockets_max = cvar("g_pickup_rockets_max");
2288 g_pickup_cells = cvar("g_pickup_cells");
2289 g_pickup_cells_max = cvar("g_pickup_cells_max");
2290 g_pickup_plasma = cvar("g_pickup_plasma");
2291 g_pickup_plasma_max = cvar("g_pickup_plasma_max");
2292 g_pickup_fuel = cvar("g_pickup_fuel");
2293 g_pickup_fuel_jetpack = cvar("g_pickup_fuel_jetpack");
2294 g_pickup_fuel_max = cvar("g_pickup_fuel_max");
2295 g_pickup_armorsmall = cvar("g_pickup_armorsmall");
2296 g_pickup_armorsmall_max = cvar("g_pickup_armorsmall_max");
2297 g_pickup_armorsmall_anyway = cvar("g_pickup_armorsmall_anyway");
2298 g_pickup_armormedium = cvar("g_pickup_armormedium");
2299 g_pickup_armormedium_max = cvar("g_pickup_armormedium_max");
2300 g_pickup_armormedium_anyway = cvar("g_pickup_armormedium_anyway");
2301 g_pickup_armorbig = cvar("g_pickup_armorbig");
2302 g_pickup_armorbig_max = cvar("g_pickup_armorbig_max");
2303 g_pickup_armorbig_anyway = cvar("g_pickup_armorbig_anyway");
2304 g_pickup_armormega = cvar("g_pickup_armormega");
2305 g_pickup_armormega_max = cvar("g_pickup_armormega_max");
2306 g_pickup_armormega_anyway = cvar("g_pickup_armormega_anyway");
2307 g_pickup_healthsmall = cvar("g_pickup_healthsmall");
2308 g_pickup_healthsmall_max = cvar("g_pickup_healthsmall_max");
2309 g_pickup_healthsmall_anyway = cvar("g_pickup_healthsmall_anyway");
2310 g_pickup_healthmedium = cvar("g_pickup_healthmedium");
2311 g_pickup_healthmedium_max = cvar("g_pickup_healthmedium_max");
2312 g_pickup_healthmedium_anyway = cvar("g_pickup_healthmedium_anyway");
2313 g_pickup_healthbig = cvar("g_pickup_healthbig");
2314 g_pickup_healthbig_max = cvar("g_pickup_healthbig_max");
2315 g_pickup_healthbig_anyway = cvar("g_pickup_healthbig_anyway");
2316 g_pickup_healthmega = cvar("g_pickup_healthmega");
2317 g_pickup_healthmega_max = cvar("g_pickup_healthmega_max");
2318 g_pickup_healthmega_anyway = cvar("g_pickup_healthmega_anyway");
2320 g_pickup_ammo_anyway = cvar("g_pickup_ammo_anyway");
2321 g_pickup_weapons_anyway = cvar("g_pickup_weapons_anyway");
2323 g_weapon_stay = cvar(strcat("g_", GetGametype(), "_weapon_stay"));
2325 g_weapon_stay = cvar("g_weapon_stay");
2327 MUTATOR_CALLHOOK(ReadLevelCvars);
2329 if (!warmup_stage && !autocvar_g_campaign)
2330 game_starttime = time + cvar("g_start_delay");
2332 FOREACH(Weapons, it != WEP_Null, { it.wr_init(it); });
2334 readplayerstartcvars();
2337 void InitializeEntity(entity e, void(entity this) func, int order)
2341 if (!e || e.initialize_entity)
2343 // make a proxy initializer entity
2345 e = new(initialize_entity);
2349 e.initialize_entity = func;
2350 e.initialize_entity_order = order;
2352 cur = initialize_entity_first;
2356 if (!cur || cur.initialize_entity_order > order)
2358 // insert between prev and cur
2360 prev.initialize_entity_next = e;
2362 initialize_entity_first = e;
2363 e.initialize_entity_next = cur;
2367 cur = cur.initialize_entity_next;
2370 void InitializeEntitiesRun()
2372 entity startoflist = initialize_entity_first;
2373 initialize_entity_first = NULL;
2374 delete_fn = remove_except_protected;
2375 for (entity e = startoflist; e; e = e.initialize_entity_next)
2377 e.remove_except_protected_forbidden = 1;
2379 for (entity e = startoflist; e; )
2381 e.remove_except_protected_forbidden = 0;
2382 e.initialize_entity_order = 0;
2383 entity next = e.initialize_entity_next;
2384 e.initialize_entity_next = NULL;
2385 var void(entity this) func = e.initialize_entity;
2386 e.initialize_entity = func_null;
2387 if (e.classname == "initialize_entity")
2389 entity wrappee = e.enemy;
2393 //dprint("Delayed initialization: ", e.classname, "\n");
2401 backtrace(strcat("Null function in: ", e.classname, "\n"));
2405 delete_fn = remove_unsafely;
2408 // deferred dropping
2409 // ported from VM_SV_droptofloor TODO: make a common function for the client-side?
2410 void DropToFloor_Handler(entity this)
2412 if(!this || wasfreed(this))
2414 // no modifying free entities
2418 vector end = this.origin - '0 0 256';
2420 // NOTE: NudgeOutOfSolid support is not added as Xonotic's physics do not use it!
2421 //if(autocvar_sv_gameplayfix_droptofloorstartsolid_nudgetocorrect)
2422 //SV_NudgeOutOfSolid(this);
2424 tracebox(this.origin, this.mins, this.maxs, end, MOVE_NORMAL, this);
2426 if(trace_startsolid && autocvar_sv_gameplayfix_droptofloorstartsolid)
2429 offset = 0.5 * (this.mins + this.maxs);
2430 offset.z = this.mins.z;
2431 org = this.origin + offset;
2432 traceline(org, end, MOVE_NORMAL, this);
2433 trace_endpos = trace_endpos - offset;
2434 if(trace_startsolid)
2436 LOG_DEBUGF("DropToFloor_Handler: %v could not fix badly placed entity", this.origin);
2437 _Movetype_LinkEdict(this, false);
2439 this.groundentity = NULL;
2441 else if(trace_fraction < 1)
2443 LOG_DEBUGF("DropToFloor_Handler: %v fixed badly placed entity", this.origin);
2444 //if(autocvar_sv_gameplayfix_droptofloorstartsolid_nudgetocorrect)
2445 //SV_NudgeOutOfSolid(this);
2446 setorigin(this, trace_endpos);
2448 this.groundentity = trace_ent;
2449 // if support is destroyed, keep suspended (gross hack for floating items in various maps)
2450 this.move_suspendedinair = true;
2455 if(!trace_allsolid && trace_fraction < 1)
2457 setorigin(this, trace_endpos);
2459 this.groundentity = trace_ent;
2460 // if support is destroyed, keep suspended (gross hack for floating items in various maps)
2461 this.move_suspendedinair = true;
2464 this.dropped_origin = this.origin;
2467 void droptofloor(entity this)
2469 InitializeEntity(this, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
2472 bool autocvar_sv_gameplayfix_multiplethinksperframe = true;
2473 void RunThink(entity this, float dt)
2475 // don't let things stay in the past.
2476 // it is possible to start that way by a trigger with a local time.
2477 if(this.nextthink <= 0 || this.nextthink > time + dt)
2480 float oldtime = time; // do we need to save this?
2482 for (int iterations = 0; iterations < 128 && !wasfreed(this); iterations++)
2484 time = max(oldtime, this.nextthink);
2488 getthink(this)(this);
2489 // mods often set nextthink to time to cause a think every frame,
2490 // we don't want to loop in that case, so exit if the new nextthink is
2491 // <= the time the qc was told, also exit if it is past the end of the
2493 if(this.nextthink <= time || this.nextthink > oldtime + dt || !autocvar_sv_gameplayfix_multiplethinksperframe)
2500 bool autocvar_sv_freezenonclients;
2501 void Physics_Frame()
2503 if(autocvar_sv_freezenonclients || game_timeout)
2506 IL_EACH(g_moveables, true,
2508 if(IS_CLIENT(it) || it.move_movetype == MOVETYPE_PHYSICS)
2511 //set_movetype(it, it.move_movetype);
2512 // inline the set_movetype function, since this is called a lot
2513 it.movetype = (it.move_qcphysics) ? MOVETYPE_QCENTITY : it.move_movetype;
2515 if(it.move_qcphysics && it.move_movetype != MOVETYPE_NONE)
2516 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2518 if(it.movetype >= MOVETYPE_USER_FIRST && it.movetype <= MOVETYPE_USER_LAST) // these cases have no think handling
2520 if(it.move_movetype == MOVETYPE_PUSH || it.move_movetype == MOVETYPE_FAKEPUSH)
2521 continue; // these movetypes have no regular think function
2522 // handle thinking here
2523 if (getthink(it) && it.nextthink > 0 && it.nextthink <= time + PHYS_INPUT_TIMELENGTH)
2524 RunThink(it, PHYS_INPUT_TIMELENGTH);
2528 if(autocvar_sv_gameplayfix_delayprojectiles >= 0)
2531 // make a second pass to see if any ents spawned this frame and make
2532 // sure they run their move/think. this is verified by checking .move_time, which will never be 0 if the entity has moved
2533 // MOVETYPE_NONE is also checked as .move_time WILL be 0 with that movetype
2534 IL_EACH(g_moveables, it.move_qcphysics,
2536 if(IS_CLIENT(it) || it.move_time || it.move_movetype == MOVETYPE_NONE || it.move_movetype == MOVETYPE_PHYSICS)
2538 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2542 void systems_update();
2545 anticheat_endframe();
2549 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2550 entity e = IS_SPEC(it) ? it.enemy : it;
2551 if (e.typehitsound) {
2552 STAT(TYPEHIT_TIME, it) = time;
2553 } else if (e.killsound) {
2554 STAT(KILL_TIME, it) = time;
2555 } else if (e.hitsound_damage_dealt) {
2556 STAT(HIT_TIME, it) = time;
2557 // NOTE: this is not accurate as client code doesn't need so much accuracy for its purposes
2558 STAT(HITSOUND_DAMAGE_DEALT_TOTAL, it) += ceil(e.hitsound_damage_dealt);
2561 // add 1 frametime because after this, engine SV_Physics
2562 // increases time by a frametime and then networks the frame
2563 // add another frametime because client shows everything with
2564 // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2566 float altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2567 FOREACH_CLIENT(true, {
2568 it.typehitsound = false;
2569 it.hitsound_damage_dealt = 0;
2570 it.killsound = false;
2571 antilag_record(it, CS(it), altime);
2573 IL_EACH(g_monsters, true,
2575 antilag_record(it, it, altime);
2577 IL_EACH(g_projectiles, it.classname == "nade",
2579 antilag_record(it, it, altime);
2588 * returns true if redirecting
2590 float redirection_timeout;
2591 float redirection_nextthink;
2592 float RedirectionThink()
2594 float clients_found;
2596 if(redirection_target == "")
2599 if(!redirection_timeout)
2601 cvar_set("sv_public", "-2");
2602 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2603 if(redirection_target == "self")
2604 bprint("^3SERVER NOTICE:^7 restarting the server\n");
2606 bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2609 if(time < redirection_nextthink)
2612 redirection_nextthink = time + 1;
2615 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2617 LOG_INFO("Redirecting: sending connect command to ", it.netname);
2618 if(redirection_target == "self")
2619 stuffcmd(it, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2621 stuffcmd(it, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2625 LOG_INFO("Redirecting: ", ftos(clients_found), " clients left.");
2627 if(time > redirection_timeout || clients_found == 0)
2628 localcmd("\nwait; wait; wait; quit\n");
2635 // Loaded from a save game
2636 // some things then break, so let's work around them...
2638 // Progs DB (capture records)
2639 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2643 MapInfo_Enumerate();
2644 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2647 TargetMusic_RestoreGame();
2654 if(world_initialized > 0)
2656 world_initialized = 0;
2658 // if a timeout is active, reset the slowmo value to normal
2659 if(timeout_status == TIMEOUT_ACTIVE)
2660 cvar_set("slowmo", ftos(orig_slowmo));
2662 LOG_TRACE("Saving persistent data...");
2665 // playerstats with unfinished match
2666 PlayerStats_GameReport(false);
2668 if(!cheatcount_total)
2670 if(autocvar_sv_db_saveasdump)
2671 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2673 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2675 if(autocvar_developer > 0)
2677 if(autocvar_sv_db_saveasdump)
2678 db_dump(TemporaryDB, "server-temp.db");
2680 db_save(TemporaryDB, "server-temp.db");
2682 CheatShutdown(); // must be after cheatcount check
2683 db_close(ServerProgsDB);
2684 db_close(TemporaryDB);
2685 LOG_TRACE("Saving persistent data... done!");
2686 // tell the bot system the game is ending now
2689 WeaponStats_Shutdown();
2692 strfree(sv_termsofservice_url_escaped);
2694 else if(world_initialized == 0)
2696 LOG_INFO("NOTE: crashed before even initializing the world, not saving persistent data");
2700 __init_dedicated_server_shutdown();