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 <lib/warpzone/common.qh>
26 #include <server/anticheat.qh>
27 #include <server/antilag.qh>
28 #include <server/bot/api.qh>
29 #include <server/campaign.qh>
30 #include <server/cheats.qh>
31 #include <server/client.qh>
32 #include <server/command/common.qh>
33 #include <server/command/getreplies.qh>
34 #include <server/command/sv_cmd.qh>
35 #include <server/command/vote.qh>
36 #include <server/damage.qh>
37 #include <server/gamelog.qh>
38 #include <server/hook.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/weaponstats.qh>
51 const float LATENCY_THINKRATE = 10;
56 void PingPLReport_Think(entity this)
61 delta = 3 / maxclients;
62 if(delta < sys_frametime)
64 this.nextthink = time + delta;
66 e = edict_num(this.cnt + 1);
67 if(IS_CLIENT(e) && IS_REAL_CLIENT(e))
69 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
70 WriteByte(MSG_BROADCAST, this.cnt);
71 WriteShort(MSG_BROADCAST, bound(1, rint(CS(e).ping), 32767));
72 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_packetloss * 255), 255));
73 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_movementloss * 255), 255));
75 // record latency times for clients throughout the match so we can report it to playerstats
76 if(time > (CS(e).latency_time + LATENCY_THINKRATE))
78 CS(e).latency_sum += CS(e).ping;
79 CS(e).latency_cnt += 1;
80 CS(e).latency_time = time;
81 //print("sum: ", ftos(CS(e).latency_sum), ", cnt: ", ftos(CS(e).latency_cnt), ", avg: ", ftos(CS(e).latency_sum / CS(e).latency_cnt), ".\n");
86 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
87 WriteByte(MSG_BROADCAST, this.cnt);
88 WriteShort(MSG_BROADCAST, 0);
89 WriteByte(MSG_BROADCAST, 0);
90 WriteByte(MSG_BROADCAST, 0);
92 this.cnt = (this.cnt + 1) % maxclients;
94 void PingPLReport_Spawn()
96 pingplreport = new_pure(pingplreport);
97 setthink(pingplreport, PingPLReport_Think);
98 pingplreport.nextthink = time;
101 const float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
103 void SetDefaultAlpha()
105 if (!MUTATOR_CALLHOOK(SetDefaultAlpha))
107 default_player_alpha = autocvar_g_player_alpha;
108 if(default_player_alpha == 0)
109 default_player_alpha = 1;
110 default_weapon_alpha = default_player_alpha;
114 void GotoFirstMap(entity this)
117 if(autocvar__sv_init)
119 // cvar_set("_sv_init", "0");
120 // we do NOT set this to 0 any more, so someone "accidentally" changing
121 // to this "init" map on a dedicated server will cause no permanent
123 if(autocvar_g_maplist_shuffle)
125 n = tokenizebyseparator(autocvar_g_maplist, " ");
126 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
129 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
131 if(!DoNextMapOverride(1))
139 this.nextthink = time;
143 this.nextthink = time + 1;
144 LOG_INFO("Waiting for _sv_init being set to 1 by initialization scripts...");
148 void cvar_changes_init()
152 float n, i, adding, pureadding;
154 strfree(cvar_changes);
155 strfree(cvar_purechanges);
156 cvar_purechanges_count = 0;
159 buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
165 for(i = 0; i < n; ++i)
167 k = bufstr_get(h, i);
169 #define BADPREFIX_COND(p) (substring(k, 0, strlen(p)) == p)
170 #define BADSUFFIX_COND(s) (substring(k, -strlen(s), -1) == s)
172 #define BADPREFIX(p) if(BADPREFIX_COND(p)) continue
173 #define BADPRESUFFIX(p, s) if(BADPREFIX_COND(p) && BADSUFFIX_COND(s)) continue
174 #define BADCVAR(p) if(k == p) continue
175 #define BADVALUE(p, val) if (k == p && v == val) continue
176 #define BADPRESUFFIXVALUE(p, s, val) if(BADPREFIX_COND(p) && BADSUFFIX_COND(s) && v == val) continue
178 // general excludes and namespaces for server admin used cvars
179 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
183 BADPREFIX("cvar_check_");
185 BADCVAR("g_configversion");
186 BADCVAR("halflifebsp");
187 BADCVAR("sv_mapformat_is_quake2");
188 BADCVAR("sv_mapformat_is_quake3");
189 BADPREFIX("sv_world");
195 BADPREFIX("scoreboard_");
196 BADPREFIX("g_campaign");
197 BADPREFIX("g_waypointsprite_");
203 BADPREFIX("net_slist_");
209 BADPREFIX("sensitivity");
210 BADPREFIX("userbind");
213 BADPREFIX("crosshair");
214 BADCVAR("mod_q3bsp_lightmapmergepower");
215 BADCVAR("mod_q3bsp_nolightmaps");
217 BADCVAR("mastervolume");
219 BADCVAR("bgmvolume");
220 BADCVAR("in_pitch_min");
221 BADCVAR("in_pitch_max");
224 BADCVAR("developer");
225 BADCVAR("log_dest_udp");
226 BADCVAR("net_address");
227 BADCVAR("net_address_ipv6");
229 BADCVAR("savedgamecfg");
230 BADCVAR("serverconfig");
231 BADCVAR("sv_autoscreenshot");
232 BADCVAR("sv_heartbeatperiod");
233 BADCVAR("sv_vote_master_password");
234 BADCVAR("sys_colortranslation");
235 BADCVAR("sys_specialcharactertranslation");
236 BADCVAR("timeformat");
237 BADCVAR("timestamps");
238 BADCVAR("g_require_stats");
239 BADCVAR("g_chatban_list");
240 BADCVAR("g_playban_list");
241 BADCVAR("g_playban_minigames");
242 BADCVAR("g_voteban_list");
243 BADPREFIX("developer_");
245 BADPREFIX("g_banned_list");
246 BADPREFIX("g_require_stats_");
247 BADPREFIX("g_chat_flood_");
248 BADPREFIX("g_ghost_items");
249 BADPREFIX("g_playerstats_");
250 BADPREFIX("g_voice_flood_");
251 BADPREFIX("log_file");
254 BADPREFIX("sv_allowdownloads");
255 BADPREFIX("sv_autodemo");
256 BADPREFIX("sv_curl_");
257 BADPREFIX("sv_eventlog");
258 BADPREFIX("sv_logscores_");
259 BADPREFIX("sv_master");
260 BADPREFIX("sv_weaponstats_");
261 BADPREFIX("sv_waypointsprite_");
262 BADCVAR("rescan_pending");
264 // these can contain player IDs, so better hide
265 BADPREFIX("g_forced_team_");
266 BADCVAR("sv_allow_customplayermodels_idlist");
267 BADCVAR("sv_allow_customplayermodels_speciallist");
270 BADCVAR("fraglimit");
272 BADCVAR("g_assault");
274 BADCVAR("g_ca_teams");
275 BADCVAR("g_conquest");
276 BADCVAR("g_conquest_teams");
281 BADCVAR("g_domination");
282 BADCVAR("g_domination_default_teams");
284 BADCVAR("g_duel_not_dm_maps");
285 BADCVAR("g_freezetag");
286 BADCVAR("g_freezetag_teams");
287 BADCVAR("g_invasion_type");
288 BADCVAR("g_jailbreak");
289 BADCVAR("g_jailbreak_teams");
290 BADCVAR("g_keepaway");
291 BADCVAR("g_keyhunt");
292 BADCVAR("g_keyhunt_teams");
295 BADCVAR("g_nexball");
296 BADCVAR("g_onslaught");
298 BADCVAR("g_race_laps_limit");
299 BADCVAR("g_race_qualifying_timelimit");
300 BADCVAR("g_race_qualifying_timelimit_override");
301 BADCVAR("g_runematch");
302 BADCVAR("g_shootfromeye");
304 BADCVAR("g_survival");
305 BADCVAR("g_survival_not_dm_maps");
307 BADCVAR("g_tdm_on_dm_maps");
308 BADCVAR("g_tdm_teams");
310 BADCVAR("g_tka_on_ka_maps");
311 BADCVAR("g_tka_on_tdm_maps");
312 BADCVAR("g_tka_teams");
313 BADCVAR("g_tmayhem");
314 BADCVAR("g_tmayhem_teams");
316 BADCVAR("leadlimit");
319 BADCVAR("timelimit");
320 BADCVAR("g_mapinfo_q3compat");
321 BADCVAR("g_mapinfo_settemp_acl");
322 BADCVAR("g_mapinfo_ignore_warnings");
323 BADCVAR("g_maplist_ignore_sizes");
324 BADCVAR("g_maplist_sizes_count_bots");
328 BADCVAR("g_maplist");
329 BADCVAR("g_maplist_mostrecent");
331 BADCVAR("sv_termsofservice_url");
334 d = cvar_defstring(k);
340 cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
341 if(strlen(cvar_changes) > 16384)
343 cvar_changes = "// too many settings have been changed to show them here\n";
348 // now check if the changes are actually gameplay relevant
350 // does nothing gameplay relevant
351 BADCVAR("captureleadlimit_override");
352 BADCVAR("condump_stripcolors");
353 BADCVAR("fs_gamedir");
354 BADCVAR("g_allow_oldvortexbeam");
355 BADCVAR("g_balance_kill_delay");
356 BADCVAR("g_buffs_pickup_anyway");
357 BADCVAR("g_buffs_randomize");
358 BADCVAR("g_buffs_randomize_teamplay");
359 BADCVAR("g_campcheck_distance");
360 BADCVAR("g_chatsounds");
361 BADCVAR("g_ca_point_leadlimit");
362 BADCVAR("g_ca_point_limit");
363 BADCVAR("g_ca_spectate_enemies");
364 BADCVAR("g_ctf_captimerecord_always");
365 BADCVAR("g_ctf_flag_glowtrails");
366 BADCVAR("g_ctf_dynamiclights");
367 BADCVAR("g_ctf_flag_pickup_verbosename");
368 BADCVAR("g_ctf_flagcarrier_auto_helpme_damage");
369 BADPRESUFFIX("g_ctf_flag_", "_model");
370 BADPRESUFFIX("g_ctf_flag_", "_skin");
371 BADCVAR("g_domination_point_leadlimit");
372 BADCVAR("g_forced_respawn");
373 BADCVAR("g_freezetag_point_leadlimit");
374 BADCVAR("g_freezetag_point_limit");
375 BADCVAR("g_glowtrails");
377 BADCVAR("g_casings");
378 BADCVAR("g_invasion_point_limit");
379 BADCVAR("g_jump_grunt");
380 BADCVAR("g_keepaway_ballcarrier_effects");
381 BADCVAR("g_keepawayball_effects");
382 BADCVAR("g_keyhunt_point_leadlimit");
383 BADCVAR("g_nexball_goalleadlimit");
384 BADCVAR("g_new_toys_autoreplace");
385 BADCVAR("g_new_toys_use_pickupsound");
386 BADCVAR("g_physics_predictall");
387 BADCVAR("g_piggyback");
388 BADCVAR("g_playerclip_collisions");
389 BADCVAR("g_spawn_alloweffects");
390 BADCVAR("g_tdm_point_leadlimit");
391 BADCVAR("g_tdm_point_limit");
392 BADCVAR("g_mayhem_point_limit");
393 BADCVAR("g_mayhem_point_leadlimit");
394 BADCVAR("g_tmayhem_point_limit");
395 BADCVAR("g_tmayhem_point_leadlimit");
396 BADCVAR("leadlimit_and_fraglimit");
397 BADCVAR("leadlimit_override");
399 BADCVAR("sv_announcer");
400 BADCVAR("sv_autopause");
401 BADCVAR("sv_checkforpacketsduringsleep");
402 BADCVAR("sv_damagetext");
403 BADCVAR("sv_db_saveasdump");
404 BADCVAR("sv_intermission_cdtrack");
405 BADCVAR("sv_mapchange_delay");
406 BADCVAR("sv_minigames");
407 BADCVAR("sv_namechangetimer");
408 BADCVAR("sv_precacheplayermodels");
409 BADCVAR("sv_qcphysics");
411 BADCVAR("sv_stepheight");
412 BADCVAR("sv_timeout");
413 BADCVAR("sv_weapons_modeloverride");
414 BADCVAR("w_prop_interval");
416 BADPREFIX("crypto_");
417 BADPREFIX("g_chat_");
418 BADPREFIX("g_ctf_captimerecord_");
419 BADPREFIX("g_hats_");
420 BADPREFIX("g_maplist_");
422 BADPREFIX("g_respawn_");
424 BADPREFIX("notification_");
427 BADPREFIX("sv_allow_");
428 BADPREFIX("sv_cullentities_");
429 BADPREFIX("sv_maxidle");
430 BADPREFIX("sv_minigames_");
431 BADPREFIX("sv_radio_");
432 BADPREFIX("sv_timeout_");
433 BADPREFIX("sv_vote_");
434 BADPREFIX("timelimit_");
435 BADPRESUFFIX("g_", "_round_timelimit");
437 // allowed changes to server admins (please sync this to server.cfg)
441 // :%s,//\([^ ]*\).*,BADCVAR("\1");,
443 // yes, this does contain some redundant stuff, don't really care
444 BADPREFIX("bot_ai_");
445 BADCVAR("bot_config_file");
446 BADCVAR("bot_number");
447 BADCVAR("bot_prefix");
448 BADCVAR("bot_suffix");
449 BADCVAR("capturelimit_override");
450 BADCVAR("fraglimit_override");
452 BADCVAR("g_antilag");
453 BADCVAR("g_balance_teams");
454 BADCVAR("g_balance_teams_prevent_imbalance");
455 BADCVAR("g_balance_teams_scorefactor");
456 BADCVAR("g_ban_sync_trusted_servers");
457 BADCVAR("g_ban_sync_uri");
459 BADCVAR("g_ca_teams_override");
460 BADCVAR("g_ca_prevent_stalemate");
461 BADCVAR("g_ctf_fullbrightflags");
462 BADCVAR("g_ctf_ignore_frags");
463 BADCVAR("g_ctf_leaderboard");
464 BADCVAR("g_domination_point_limit");
465 BADCVAR("g_domination_teams_override");
466 BADCVAR("g_freezetag_revive_spawnshield");
467 BADCVAR("g_freezetag_teams_override");
468 BADCVAR("g_friendlyfire");
469 BADCVAR("g_fullbrightitems");
470 BADCVAR("g_fullbrightplayers");
471 BADCVAR("g_keyhunt_point_limit");
472 BADCVAR("g_keyhunt_teams_override");
473 BADCVAR("g_lms_lives_override");
474 BADCVAR("g_mayhem_powerups");
475 BADCVAR("g_maplist");
476 BADCVAR("g_maxplayers");
477 BADCVAR("g_mirrordamage");
478 BADCVAR("g_nexball_goallimit");
479 BADCVAR("g_norecoil");
480 BADCVAR("g_physics_clientselect");
482 BADCVAR("g_powerups");
483 BADCVAR("g_powerups_drop_ondeath");
484 BADCVAR("g_player_brightness");
485 BADCVAR("g_rocket_flying");
486 BADCVAR("g_rocket_flying_disabledelays");
487 BADPREFIX("g_spawnshield");
488 BADCVAR("g_start_delay");
489 BADCVAR("g_superspectate");
490 BADCVAR("g_tdm_teams_override");
491 BADCVAR("g_tmayhem_teams_override");
492 BADCVAR("g_tmayhem_powerups");
493 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
496 BADCVAR("maxplayers");
497 BADCVAR("minplayers");
498 BADCVAR("minplayers_per_team");
499 BADCVAR("net_address");
501 BADCVAR("rcon_password");
502 BADCVAR("rcon_restricted_commands");
503 BADCVAR("rcon_restricted_password");
505 BADCVAR("sv_adminnick");
506 BADCVAR("sv_autoscreenshot");
507 BADCVAR("sv_autotaunt");
508 BADCVAR("sv_curl_defaulturl");
509 BADCVAR("sv_defaultcharacter");
510 BADCVAR("sv_defaultcharacterskin");
511 BADCVAR("sv_defaultplayercolors");
512 BADCVAR("sv_defaultplayermodel");
513 BADCVAR("sv_defaultplayerskin");
514 BADCVAR("sv_maxrate");
516 BADCVAR("sv_public");
517 BADCVAR("sv_showfps");
518 BADCVAR("sv_showspectators");
519 BADCVAR("sv_status_privacy");
521 BADCVAR("sv_vote_call");
522 BADCVAR("sv_vote_commands");
523 BADCVAR("sv_vote_majority_factor");
524 BADCVAR("sv_vote_master");
525 BADCVAR("sv_vote_master_commands");
526 BADCVAR("sv_vote_master_password");
527 BADCVAR("sv_vote_simple_majority_factor");
528 BADVALUE("sys_ticrate", "0.0166667");
529 BADVALUE("sys_ticrate", "0.0333333");
530 BADCVAR("teamplay_mode");
531 BADCVAR("timelimit_override");
532 BADPREFIX("g_warmup");
533 BADPREFIX("sv_info_");
534 BADPREFIX("sv_ready_restart_");
536 BADPRESUFFIXVALUE("g_", "_weaponarena", "most");
537 BADPRESUFFIXVALUE("g_", "_weaponarena", "most_available");
539 // mutators that announce themselves properly to the server browser
540 BADCVAR("g_instagib");
541 BADCVAR("g_new_toys");
543 BADCVAR("g_grappling_hook");
544 BADCVAR("g_jetpack");
550 #undef BADPRESUFFIXVALUE
554 cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
555 if(strlen(cvar_purechanges) > 16384)
557 cvar_purechanges = "// too many settings have been changed to show them here\n";
561 ++cvar_purechanges_count;
562 // WARNING: this variable is used for the server list
563 // NEVER dare to skip this code!
564 // Hacks to intentionally appearing as "pure server" even though you DO have
565 // modified settings may be punished by removal from the server list.
566 // You can do to the variables cvar_changes and cvar_purechanges all you want,
570 if(cvar_changes == "")
571 cvar_changes = "// this server runs at default server settings\n";
573 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
574 cvar_changes = strzone(cvar_changes);
575 if(cvar_purechanges == "")
576 cvar_purechanges = "// this server runs at default gameplay settings\n";
578 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
579 cvar_purechanges = strzone(cvar_purechanges);
583 bool RandomSeed_Send(entity this, entity to, int sf)
585 WriteHeader(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
586 WriteShort(MSG_ENTITY, this.cnt);
589 void RandomSeed_Think(entity this)
591 this.cnt = bound(0, floor(random() * 65536), 65535);
592 this.nextthink = time + 5;
596 void RandomSeed_Spawn()
598 randomseed = new_pure(randomseed);
599 setthink(randomseed, RandomSeed_Think);
600 Net_LinkEntity(randomseed, false, 0, RandomSeed_Send);
602 getthink(randomseed)(randomseed); // sets random seed and nextthink
605 spawnfunc(__init_dedicated_server)
607 // handler for _init/_init map (only for dedicated server initialization)
609 world_initialized = -1; // don't complain
611 delete_fn = remove_unsafely;
613 entity e = new(GotoFirstMap);
614 setthink(e, GotoFirstMap);
615 e.nextthink = time; // this is usually 1 at this point
617 e = new(info_player_deathmatch); // safeguard against player joining
619 // assign reflectively to avoid "assignment to world" warning
620 for (int i = 0, n = numentityfields(); i < n; ++i)
622 string k = entityfieldname(i);
623 if (k == "classname")
625 // safeguard against various stuff ;)
626 putentityfieldstring(i, this, "worldspawn");
631 // needs to be done so early because of the constants they create
634 static_init_precache();
636 IL_PUSH(g_spawnpoints, e); // just incase
639 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
642 void __init_dedicated_server_shutdown() {
646 STATIC_INIT_EARLY(maxclients)
649 for (entity head = nextent(NULL); head; head = nextent(head)) {
654 void GameplayMode_DelayedInit(entity this)
656 // at this stage team entities are spawned, teamplay contains the number of them
658 if(!scores_initialized)
659 ScoreRules_generic();
661 if (warmup_stage >= 0 && autocvar_g_maxplayers >= 0)
664 MapReadSizes(mapname);
666 if (autocvar_g_maxplayers < 0 && teamplay)
668 // automatic maxplayers should be a multiple of team count
669 if (map_maxplayers == 0 || map_maxplayers > maxclients)
670 map_maxplayers = maxclients; // unlimited, but may need rounding
671 int d = map_maxplayers % AVAILABLE_TEAMS;
672 int u = AVAILABLE_TEAMS - d;
673 map_maxplayers += (u <= d && u + map_maxplayers <= maxclients) ? u : -d;
676 if (warmup_stage < 0)
678 int m = GetPlayerLimit();
679 if (m <= 0) m = maxclients;
680 map_minplayers = bound(max(2, AVAILABLE_TEAMS * 2), map_minplayers, m);
683 // automatic minplayers should be a multiple of team count
684 int d = map_minplayers % AVAILABLE_TEAMS;
685 int u = AVAILABLE_TEAMS - d;
686 map_minplayers += (u < d && u + map_minplayers <= m) ? u : -d;
690 map_minplayers = 0; // don't display a minimum if it's not used (g_maxplayers < 0 && g_warmup >= 0)
693 void InitGameplayMode()
697 // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
699 // assign reflectively to avoid "assignment to world" warning
700 for (int i = 0, done = 0, n = numentityfields(); i < n; ++i)
702 string k = entityfieldname(i);
703 vector v = (k == "mins") ? mi_min : (k == "maxs") ? mi_max : '0 0 0';
706 putentityfieldstring(i, world, sprintf("%v", v));
707 if (++done == 2) break;
710 // currently, NetRadiant's limit is 131072 qu for each side
711 // distance from one corner of a 131072qu cube to the opposite corner is approx. 227023 qu
712 // set the distance according to map size but don't go over the limit to avoid issues with float precision
713 // in case somebody makes extremely large maps
714 max_shot_distance = min(230000, vlen(world.maxs - world.mins));
716 MapInfo_LoadMapSettings(mapname);
717 GameRules_teams(false);
719 if (!cvar_value_issafe(world.fog))
721 LOG_INFO("The current map contains a potentially harmful fog setting, ignored");
722 world.fog = string_null;
724 if(MapInfo_Map_fog != "")
726 if(MapInfo_Map_fog == "none")
727 world.fog = string_null;
729 world.fog = strzone(MapInfo_Map_fog);
731 clientstuff = strzone(MapInfo_Map_clientstuff);
733 MapInfo_ClearTemps();
735 gamemode_name = MapInfo_Type_ToText(MapInfo_LoadedGametype);
737 cache_mutatormsg = strzone("");
738 cache_lastmutatormsg = strzone("");
740 InitializeEntity(NULL, GameplayMode_DelayedInit, INITPRIO_GAMETYPE_FALLBACK);
743 bool world_already_spawned;
744 spawnfunc(worldspawn)
746 cvar_set("_endmatch", "0");
747 server_is_dedicated = boolean(stof(cvar_defstring("is_dedicated")));
749 if (autocvar_sv_termsofservice_url && autocvar_sv_termsofservice_url != "")
751 strcpy(sv_termsofservice_url_escaped, strreplace(":", "|", autocvar_sv_termsofservice_url));
755 strcpy(sv_termsofservice_url_escaped, "INVALID");
758 bool wantrestart = false;
760 if (!server_is_dedicated)
762 // DP unloads dlcache pk3s before starting a listen server since https://gitlab.com/xonotic/darkplaces/-/merge_requests/134
763 // restore csqc_progname too
764 string expect = "csprogs.dat";
765 wantrestart = cvar_string("csqc_progname") != expect;
766 cvar_set("csqc_progname", expect);
770 // Try to use versioned csprogs from pk3
771 // Only ever use versioned csprogs.dat files on dedicated servers;
772 // we need to reset csqc_progname on clients ourselves, and it's easier if the client's release name is constant
773 string pk3csprogs = "csprogs-" WATERMARK ".dat";
774 // This always works; fall back to it if a versioned csprogs.dat is suddenly missing
775 string select = "csprogs.dat";
776 if (fexists(pk3csprogs)) select = pk3csprogs;
777 if (cvar_string("csqc_progname") != select)
779 cvar_set("csqc_progname", select);
782 // Check for updates on startup
783 // We do it this way for atomicity so that connecting clients still match the server progs and don't disconnect
784 int sentinel = fopen("progs.txt", FILE_READ);
787 string switchversion = fgets(sentinel);
789 if (switchversion != "" && switchversion != WATERMARK)
791 LOG_INFOF("Switching progs: " WATERMARK " -> %s", switchversion);
792 // if it doesn't exist, assume either:
793 // a) the current program was overwritten
794 // b) this is a client only update
795 string newprogs = sprintf("progs-%s.dat", switchversion);
796 if (fexists(newprogs))
798 cvar_set("sv_progs", newprogs);
801 string newcsprogs = sprintf("csprogs-%s.dat", switchversion);
802 if (fexists(newcsprogs))
804 cvar_set("csqc_progname", newcsprogs);
812 LOG_INFO("Restart requested");
813 changelevel(mapname);
814 // let initialization continue, shutdown depends on it
818 if(world_already_spawned)
819 error("world already spawned - you may have EXACTLY ONE worldspawn!");
820 world_already_spawned = true;
822 delete_fn = remove_safely; // during spawning, watch what you remove!
824 cvar_changes_init(); // do this very early now so it REALLY matches the server config
826 // default to RACE_RECORD, can be overwritten by gamemodes
827 record_type = RACE_RECORD;
829 // needs to be done so early because of the constants they create
832 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
834 TemporaryDB = db_create();
839 // 1 FLICKER (first variety)
840 lightstyle(1, "mmnmmommommnonmmonqnmmo");
842 // 2 SLOW STRONG PULSE
843 lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
845 // 3 CANDLE (first variety)
846 lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
849 lightstyle(4, "mamamamamama");
852 lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
854 // 6 FLICKER (second variety)
855 lightstyle(6, "nmonqnmomnmomomno");
857 // 7 CANDLE (second variety)
858 lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
860 // 8 CANDLE (third variety)
861 lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
863 // 9 SLOW STROBE (fourth variety)
864 lightstyle(9, "aaaaaaaazzzzzzzz");
866 // 10 FLUORESCENT FLICKER
867 lightstyle(10, "mmamammmmammamamaaamammma");
869 // 11 SLOW PULSE NOT FADE TO BLACK
870 lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
872 // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
877 if(autocvar_g_campaign)
880 PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
882 Map_MarkAsRecent(mapname);
886 static_init_precache();
889 GameRules_limit_fallbacks();
892 bot_waypoints_for_items = autocvar_g_waypoints_for_items;
893 if(bot_waypoints_for_items == 1)
894 if(this.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
895 bot_waypoints_for_items = 0;
897 WaypointSprite_Init();
900 // changing the logic generating it is okay. But:
901 // it HAS to stay <= 64 chars
902 // character set: ASCII 33-126 without the following characters: : ; ' " \ $
903 // strftime(false, "%s") isn't reliable, see strftime_s description
904 matchid = strzone(sprintf("%d.%s.%06d", autocvar_sv_eventlog_files_counter, strftime_s(), random() * 1000000));
906 if(autocvar_sv_eventlog)
907 GameLogInit(); // requires matchid to be set
909 cvar_set("nextmap", "");
913 if(autocvar_g_campaign)
919 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
921 q3compat = BITSET(q3compat, Q3COMPAT_ARENA, _MapInfo_FindArenaFile(mapname, ".arena") != "");
922 q3compat = BITSET(q3compat, Q3COMPAT_DEFI, _MapInfo_FindArenaFile(mapname, ".defi") != "");
924 // quake 3 music support
925 if(world.music || world.noise)
927 // prefer .music over .noise
930 chosen_music = world.music;
932 chosen_music = world.noise;
934 string newstuff = strcat(clientstuff, "cd loop \"", chosen_music, "\"\n");
935 strcpy(clientstuff, newstuff);
938 if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
940 int fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
944 while((s = fgets(fd)))
946 int l = tokenize_console(s);
951 string trackname = argv(2);
952 LOG_INFO("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:");
953 LOG_INFO(" cdtrack ", trackname);
954 if (cvar_value_issafe(trackname))
956 string newstuff = strcat(clientstuff, "cd loop \"", trackname, "\"\n");
957 strcpy(clientstuff, newstuff);
960 else if(argv(0) == "fog")
962 LOG_INFO("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:");
963 LOG_INFO(" \"fog\" \"", s, "\"");
965 else if(argv(0) == "set")
967 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
968 LOG_INFO(" clientsettemp_for_type all ", argv(1), " ", argv(2));
970 else if(argv(0) != "//")
972 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
973 LOG_INFO(" clientsettemp_for_type all ", argv(0), " ", argv(1));
984 // set up information replies for clients and server to use
985 maplist_reply = strzone(getmaplist());
986 lsmaps_reply = strzone(getlsmaps());
987 monsterlist_reply = strzone(getmonsterlist());
988 bool records_available = false;
989 for(int i = 0; i < 10; ++i)
991 string s = getrecords(i);
994 records_reply[i] = strzone(s);
995 records_available = true;
998 if (!records_available)
999 records_reply[0] = "No records available for the current game mode.\n";
1000 ladder_reply = strzone(getladder());
1001 rankings_reply = strzone(getrankings());
1006 PingPLReport_Spawn();
1010 if (!wantrestart) localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
1012 // fill sv_curl_serverpackages from .serverpackage files
1013 if (autocvar_sv_curl_serverpackages_auto)
1015 string s = "csprogs-" WATERMARK ".dat";
1016 // remove automatically managed files from the list to prevent duplicates
1017 for (int i = 0, n = tokenize_console(cvar_string("sv_curl_serverpackages")); i < n; ++i)
1019 string pkg = argv(i);
1020 if (startsWith(pkg, "csprogs-")) continue;
1021 if (endsWith(pkg, "-serverpackage.txt")) continue;
1022 if (endsWith(pkg, ".serverpackage")) continue; // OLD legacy
1025 // add automatically managed files to the list
1026 #define X(match) MACRO_BEGIN \
1027 int fd = search_begin(match, true, false); \
1030 for (int i = 0, j = search_getsize(fd); i < j; ++i) \
1032 s = cons(s, search_getfilename(fd, i)); \
1037 X("*-serverpackage.txt");
1038 X("*.serverpackage");
1040 cvar_set("sv_curl_serverpackages", s);
1043 // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
1044 modname = "Xonotic";
1045 // physics/balance/config changes that count as mod
1046 if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
1047 modname = cvar_string("g_mod_physics");
1048 if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance") && cvar_string("g_mod_balance") != "Testing")
1049 modname = cvar_string("g_mod_balance");
1050 if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
1051 modname = cvar_string("g_mod_config");
1052 // extra mutators that deserve to count as mod
1053 MUTATOR_CALLHOOK(SetModname, modname);
1054 modname = M_ARGV(0, string);
1056 // save it for later
1057 modname = strzone(modname);
1059 WinningConditionHelper(this); // set worldstatus
1061 if (autocvar_sv_autopause && server_is_dedicated && !wantrestart)
1062 // INITPRIO_LAST is to soon: bots either didn't join yet or didn't leave yet, see: bot_fixcount()
1063 defer(this, 5, Pause_TryPause_Dedicated);
1065 world_initialized = 1;
1066 __spawnfunc_spawn_all();
1071 //makestatic (this); // Who the f___ did that?
1075 bool MoveToRandomLocationWithinBounds(entity e, vector boundmin, vector boundmax, float goodcontents, float badcontents, float badsurfaceflags, int attempts, float maxaboveground, float minviewdistance, bool frompos)
1077 float m = e.dphitcontentsmask;
1078 e.dphitcontentsmask = goodcontents | badcontents;
1080 vector org = boundmin;
1081 vector delta = boundmax - boundmin;
1085 int j; // used after the loop
1086 for(j = 0; j < attempts; ++j)
1088 start.x = org.x + random() * delta.x;
1089 start.y = org.y + random() * delta.y;
1090 start.z = org.z + random() * delta.z;
1092 // rule 1: start inside world bounds, and outside
1093 // solid, and don't start from somewhere where you can
1094 // fall down to evil
1095 tracebox(start, e.mins, e.maxs, start - '0 0 1' * delta.z, MOVE_NORMAL, e);
1096 if (trace_fraction >= 1)
1098 if (trace_startsolid)
1100 if (trace_dphitcontents & badcontents)
1102 if (trace_dphitq3surfaceflags & badsurfaceflags)
1105 // rule 2: if we are too high, lower the point
1106 if (trace_fraction * delta.z > maxaboveground)
1107 start = trace_endpos + '0 0 1' * maxaboveground;
1108 vector enddown = trace_endpos;
1110 // rule 3: make sure we aren't outside the map. This only works
1111 // for somewhat well formed maps. A good rule of thumb is that
1112 // the map should have a convex outside hull.
1113 // these can be traceLINES as we already verified the starting box
1114 vector mstart = start + 0.5 * (e.mins + e.maxs);
1115 traceline(mstart, mstart + '1 0 0' * delta.x, MOVE_NORMAL, e);
1116 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1118 traceline(mstart, mstart - '1 0 0' * delta.x, MOVE_NORMAL, e);
1119 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1121 traceline(mstart, mstart + '0 1 0' * delta.y, MOVE_NORMAL, e);
1122 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1124 traceline(mstart, mstart - '0 1 0' * delta.y, MOVE_NORMAL, e);
1125 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1127 traceline(mstart, mstart + '0 0 1' * delta.z, MOVE_NORMAL, e);
1128 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1131 // rule 4: we must "see" some spawnpoint or item
1135 if((traceline(mstart, e.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1140 IL_EACH(g_spawnpoints, checkpvs(mstart, it),
1142 if((traceline(mstart, it.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1151 int items_checked = 0;
1152 IL_EACH(g_items, checkpvs(mstart, it),
1154 if((traceline(mstart, it.origin + (it.mins + it.maxs) * 0.5, MOVE_NORMAL, e), trace_fraction) >= 1)
1161 if(items_checked >= attempts)
1169 // find a random vector to "look at"
1170 end.x = org.x + random() * delta.x;
1171 end.y = org.y + random() * delta.y;
1172 end.z = org.z + random() * delta.z;
1173 end = start + normalize(end - start) * vlen(delta);
1175 // rule 4: start TO end must not be too short
1176 tracebox(start, e.mins, e.maxs, end, MOVE_NORMAL, e);
1177 if(trace_startsolid)
1179 if(trace_fraction < minviewdistance / vlen(delta))
1182 // rule 5: don't want to look at sky
1183 if(trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
1186 // rule 6: we must not end up in trigger_hurt
1187 if(tracebox_hits_trigger_hurt(start, e.mins, e.maxs, enddown))
1193 e.dphitcontentsmask = m;
1197 setorigin(e, start);
1198 e.angles = vectoangles(end - start);
1199 LOG_DEBUG("Needed ", ftos(j + 1), " attempts");
1205 float MoveToRandomMapLocation(entity e, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1207 return MoveToRandomLocationWithinBounds(e, world.mins, world.maxs, goodcontents, badcontents, badsurfaceflags, attempts, maxaboveground, minviewdistance, false);
1211 ===============================================================================
1215 ===============================================================================
1218 void DumpStats(float final)
1227 to_console = autocvar_sv_logscores_console;
1228 to_eventlog = autocvar_sv_eventlog;
1229 to_file = autocvar_sv_logscores_file;
1233 to_console = true; // always print printstats replies
1234 to_eventlog = false; // but never print them to the event log
1238 if(autocvar_sv_eventlog_console)
1239 to_console = false; // otherwise we get the output twice
1245 s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1255 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1259 fputs(file, strcat(s, "\n"));
1262 s = strcat(":labels:player:", GetPlayerScoreString(NULL, 0));
1268 fputs(file, strcat(s, "\n"));
1270 FOREACH_CLIENT(IS_REAL_CLIENT(it) || (IS_BOT_CLIENT(it) && autocvar_sv_logscores_bots), {
1271 s = strcat(":player:see-labels:", GetPlayerScoreString(it, 0), ":");
1272 s = strcat(s, ftos(rint(time - CS(it).jointime)), ":");
1273 if(IS_PLAYER(it) || INGAME_JOINED(it))
1274 s = strcat(s, ftos(it.team), ":");
1276 s = strcat(s, "spectator:");
1279 LOG_HELP(s, playername(it.netname, it.team, false));
1281 GameLogEcho(strcat(s, ftos(it.playerid), ":", playername(it.netname, it.team, false)));
1283 fputs(file, strcat(s, playername(it.netname, it.team, false), "\n"));
1288 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1294 fputs(file, strcat(s, "\n"));
1296 for(i = 1; i < 16; ++i)
1298 s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1299 s = strcat(s, ":", ftos(i));
1305 fputs(file, strcat(s, "\n"));
1312 GameLogEcho(":end");
1315 fputs(file, ":end\n");
1321 go to the next level for deathmatch
1322 only called if a time or frag limit has expired
1326 cvar_set("_endmatch", "0");
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 ();
1350 PlayerStats_GameReport(true);
1351 WeaponStats_Shutdown();
1353 Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_Null); // kill all centerprints now
1355 if(autocvar_sv_eventlog)
1356 GameLogEcho(":gameover");
1360 int winner_team = 0;
1361 FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), {
1362 FixIntermissionClient(it);
1365 if (teamplay && !winner_team)
1367 winner_team = it.team;
1368 bprint(Team_ColorCode(winner_team), Team_ColorName_Upper(winner_team), "^7 team wins the match\n");
1370 bprint(playername(it.netname, it.team, false), " ^7wins\n");
1374 target_music_kill();
1376 if(autocvar_g_campaign)
1377 CampaignPreIntermission();
1379 MUTATOR_CALLHOOK(MatchEnd);
1381 localcmd("\nsv_hook_gameend\n");
1385 int InitiateSuddenDeath()
1387 // Check first whether normal overtimes could be added before initiating suddendeath mode
1388 // - for this timelimit_overtime needs to be >0 of course
1389 // - also check the winning condition calculated in the previous frame and only add normal overtime
1390 // again, if at the point at which timelimit would be extended again, still no winner was found
1391 if (!autocvar_g_campaign && checkrules_overtimesadded >= 0
1392 && (checkrules_overtimesadded < autocvar_timelimit_overtimes || autocvar_timelimit_overtimes < 0)
1393 && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1395 return 1; // need to call InitiateOvertime later
1399 if(!checkrules_suddendeathend)
1401 if(autocvar_g_campaign)
1403 checkrules_suddendeathend = time; // no suddendeath in campaign
1407 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1410 if(g_race && !g_race_qualifying)
1411 race_StartCompleting();
1417 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1419 ++checkrules_overtimesadded;
1420 overtimes = checkrules_overtimesadded;
1421 //add one more overtime by simply extending the timelimit
1422 cvar_set("timelimit", ftos(autocvar_timelimit + autocvar_timelimit_overtime));
1423 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime * 60);
1426 float GetWinningCode(float fraglimitreached, float equality)
1428 if(autocvar_g_campaign == 1)
1430 if(fraglimitreached)
1439 if(fraglimitreached)
1440 return WINNING_STARTSUDDENDEATHOVERTIME;
1442 return WINNING_NEVER;
1446 if(fraglimitreached)
1454 // set the .winning flag for exactly those players with a given field value
1455 void SetWinners(.float field, float value)
1457 FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), { it.winning = (it.(field) == value); });
1460 // set the .winning flag for those players with a given field value
1461 void AddWinners(.float field, float value)
1463 FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), {
1464 if(it.(field) == value)
1469 // clear the .winning flags
1472 FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), { it.winning = 0; });
1476 float WinningCondition_Scores(float limit, float leadlimit)
1478 // TODO make everything use THIS winning condition (except LMS)
1479 WinningConditionHelper(NULL);
1483 for (int i = 1; i < 5; ++i)
1485 Team_SetTeamScore(Team_GetTeamFromIndex(i),
1486 TeamScore_GetCompareValue(Team_IndexToTeam(i)));
1491 if(WinningConditionHelper_winner)
1492 WinningConditionHelper_winner.winning = 1;
1493 if(WinningConditionHelper_winnerteam >= 0)
1494 SetWinners(team, WinningConditionHelper_winnerteam);
1496 if(WinningConditionHelper_lowerisbetter)
1498 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1499 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1503 if(WinningConditionHelper_zeroisworst)
1504 leadlimit = 0; // not supported in this mode
1506 if(MUTATOR_CALLHOOK(Scores_CountFragsRemaining))
1509 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1515 fragsleft = FLOAT_MAX;
1516 float leadingfragsleft = FLOAT_MAX;
1518 fragsleft = limit - WinningConditionHelper_topscore;
1520 leadingfragsleft = WinningConditionHelper_secondscore + leadlimit - WinningConditionHelper_topscore;
1522 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1523 fragsleft = max(fragsleft, leadingfragsleft);
1525 fragsleft = min(fragsleft, leadingfragsleft);
1528 if (fragsleft_last != fragsleft) // do not announce same remaining frags multiple times
1531 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_1);
1532 else if (fragsleft == 2)
1533 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_2);
1534 else if (fragsleft == 3)
1535 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_3);
1537 fragsleft_last = fragsleft;
1541 bool fraglimit_reached = (limit && WinningConditionHelper_topscore >= limit);
1542 bool leadlimit_reached = (leadlimit && WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1545 // only respect leadlimit_and_fraglimit when both limits are set or the game will never end
1546 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1547 limit_reached = (fraglimit_reached && leadlimit_reached);
1549 limit_reached = (fraglimit_reached || leadlimit_reached);
1551 return GetWinningCode(
1552 WinningConditionHelper_topscore && limit_reached,
1553 WinningConditionHelper_equality
1557 float WinningCondition_RanOutOfSpawns()
1559 if(have_team_spawns <= 0)
1562 if(!autocvar_g_spawn_useallspawns)
1565 if(!some_spawn_has_been_used)
1568 for (int i = 1; i < 5; ++i)
1570 Team_SetTeamScore(Team_GetTeamFromIndex(i), 0);
1573 FOREACH_CLIENT(IS_PLAYER(it) && !IS_DEAD(it),
1575 if (Team_IsValidTeam(it.team))
1577 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1581 IL_EACH(g_spawnpoints, true,
1583 if (Team_IsValidTeam(it.team))
1585 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1590 float team1_score = Team_GetTeamScore(Team_GetTeamFromIndex(1));
1591 float team2_score = Team_GetTeamScore(Team_GetTeamFromIndex(2));
1592 float team3_score = Team_GetTeamScore(Team_GetTeamFromIndex(3));
1593 float team4_score = Team_GetTeamScore(Team_GetTeamFromIndex(4));
1594 if(team1_score + team2_score + team3_score + team4_score == 0)
1596 checkrules_equality = true;
1599 else if(team1_score + team2_score + team3_score + team4_score == 1)
1604 else if(team2_score)
1606 else if(team3_score)
1608 else // if(team4_score)
1610 entity balance = TeamBalance_CheckAllowedTeams(NULL);
1611 for(i = 0; i < MAX_TEAMSCORE; ++i)
1613 for (int j = 1; j <= NUM_TEAMS; ++j)
1619 if (!TeamBalance_IsTeamAllowed(balance, j))
1623 TeamScore_AddToTeam(Team_IndexToTeam(j), i, -1000);
1627 AddWinners(team, t);
1638 Exit deathmatch games upon conditions
1641 void CheckRules_World()
1648 if (intermission_running) // someone else quit the game already
1650 if(player_count == 0) // Nobody there? Then let's go to the next map
1652 // this will actually check the player count in the next frame
1653 // again, but this shouldn't hurt
1657 float timelimit = autocvar_timelimit * 60;
1658 float fraglimit = autocvar_fraglimit;
1659 float leadlimit = autocvar_leadlimit;
1660 if (leadlimit < 0) leadlimit = 0;
1662 if(warmup_stage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1665 timelimit = 0; // timelimit is not made for warmup
1667 fraglimit = 0; // no fraglimit for now
1668 leadlimit = 0; // no leadlimit for now
1671 if (autocvar__endmatch || timelimit < 0)
1679 timelimit += game_starttime;
1681 int overtimes_prev = overtimes;
1682 int wantovertime = 0;
1684 if(checkrules_suddendeathend)
1686 if(!checkrules_suddendeathwarning)
1688 checkrules_suddendeathwarning = true;
1689 if(g_race && !g_race_qualifying)
1690 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_RACE_FINISHLAP);
1692 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_FRAG);
1697 if (timelimit && time >= timelimit)
1699 if(g_race && (g_race_qualifying == 2) && timelimit > 0)
1702 float playerswithlaps;
1704 totalplayers = playerswithlaps = readyplayers = 0;
1705 FOREACH_CLIENT(IS_PLAYER(it), {
1707 if(GameRules_scoring_add(it, RACE_FASTEST, 0))
1713 // at least 2 of the players have completed a lap: start the RACE
1714 // otherwise, the players should end the qualifying on their own
1715 if(readyplayers || playerswithlaps >= 2)
1717 checkrules_suddendeathend = 0;
1718 ReadyRestart(true); // go to race
1722 wantovertime |= InitiateSuddenDeath();
1725 wantovertime |= InitiateSuddenDeath();
1729 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1735 int checkrules_status = WinningCondition_RanOutOfSpawns();
1736 if(checkrules_status == WINNING_YES)
1737 bprint("Hey! Someone ran out of spawns!\n");
1738 else if(MUTATOR_CALLHOOK(CheckRules_World, checkrules_status, timelimit, fraglimit))
1739 checkrules_status = M_ARGV(0, float);
1741 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
1743 if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
1745 checkrules_status = WINNING_NEVER;
1746 checkrules_overtimesadded = -1;
1747 wantovertime |= InitiateSuddenDeath();
1750 if(checkrules_status == WINNING_NEVER)
1751 // equality cases! Nobody wins if the overtime ends in a draw.
1756 if(checkrules_status == WINNING_NEVER)
1759 checkrules_status = WINNING_YES;
1762 if(checkrules_suddendeathend)
1763 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
1764 checkrules_status = WINNING_YES;
1766 if(checkrules_status == WINNING_YES)
1768 if (overtimes == -1 && overtimes != overtimes_prev)
1770 // if suddendeathend overtime has just begun, revert it
1771 checkrules_suddendeathend = 0;
1772 overtimes = overtimes_prev;
1774 //print("WINNING\n");
1779 float want_weapon(entity weaponinfo, float allguns)
1782 bool allow_mutatorblocked = false;
1784 if(!weaponinfo.m_id)
1787 bool mutator_returnvalue = MUTATOR_CALLHOOK(WantWeapon, weaponinfo, d, allguns, allow_mutatorblocked);
1788 d = M_ARGV(1, float);
1789 allguns = M_ARGV(2, bool);
1790 allow_mutatorblocked = M_ARGV(3, bool);
1793 d = boolean((weaponinfo.spawnflags & WEP_FLAG_NORMAL) && !(weaponinfo.spawnflags & (WEP_FLAG_HIDDEN | WEP_FLAG_SPECIALATTACK)));
1794 else if(!mutator_returnvalue)
1795 d = !(!weaponinfo.weaponstart);
1797 if(!allow_mutatorblocked && (weaponinfo.spawnflags & WEP_FLAG_MUTATORBLOCKED)) // never default mutator blocked guns
1800 float t = weaponinfo.weaponstartoverride;
1802 //LOG_INFOF("want_weapon: %s - d: %d t: %d\n", weaponinfo.netname, d, t);
1807 // 4: is set by default?
1816 /// Weapons the player normally starts with outside weapon arena.
1817 WepSet weapons_start()
1819 WepSet ret = '0 0 0';
1820 FOREACH(Weapons, it != WEP_Null, {
1821 int w = want_weapon(it, false);
1828 WepSet weapons_all()
1830 WepSet ret = '0 0 0';
1831 FOREACH(Weapons, it != WEP_Null, {
1832 if (!(it.spawnflags & (WEP_FLAG_MUTATORBLOCKED | WEP_FLAG_SPECIALATTACK)))
1838 WepSet weapons_devall()
1840 WepSet ret = '0 0 0';
1841 FOREACH(Weapons, it != WEP_Null,
1848 WepSet weapons_most()
1850 WepSet ret = '0 0 0';
1851 FOREACH(Weapons, it != WEP_Null, {
1852 if ((it.spawnflags & WEP_FLAG_NORMAL) && !(it.spawnflags & (WEP_FLAG_MUTATORBLOCKED | WEP_FLAG_HIDDEN | WEP_FLAG_SPECIALATTACK)))
1858 void weaponarena_available_all_update(entity this)
1860 if (weaponsInMapAll)
1862 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | (weaponsInMapAll & weapons_all());
1866 // if no weapons are available on the map, just fall back to all weapons arena
1867 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_all();
1871 void weaponarena_available_devall_update(entity this)
1873 if (weaponsInMapAll)
1875 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | weaponsInMapAll;
1879 // if no weapons are available on the map, just fall back to devall weapons arena
1880 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_devall();
1884 void weaponarena_available_most_update(entity this)
1886 if (weaponsInMapAll)
1888 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | (weaponsInMapAll & weapons_most());
1892 // if no weapons are available on the map, just fall back to most weapons arena
1893 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_most();
1897 void readplayerstartcvars()
1899 // initialize starting values for players
1900 start_weapons = '0 0 0';
1901 start_weapons_default = '0 0 0';
1902 start_weapons_defaultmask = '0 0 0';
1904 start_ammo_shells = 0;
1905 start_ammo_nails = 0;
1906 start_ammo_rockets = 0;
1907 start_ammo_cells = 0;
1908 start_ammo_plasma = 0;
1909 if (random_start_ammo == NULL)
1911 random_start_ammo = new_pure(random_start_ammo);
1913 start_health = cvar("g_balance_health_start");
1914 start_armorvalue = cvar("g_balance_armor_start");
1917 g_weaponarena_weapons = '0 0 0';
1919 string s = cvar_string("g_weaponarena");
1921 MUTATOR_CALLHOOK(SetWeaponArena, s);
1922 s = M_ARGV(0, string);
1924 if (s == "0" || s == "")
1928 else if (s == "off")
1930 // forcibly turn off weaponarena
1932 else if (s == "all" || s == "1")
1935 g_weaponarena_list = "All Weapons Arena";
1936 g_weaponarena_weapons = weapons_all();
1938 else if (s == "devall")
1941 g_weaponarena_list = "Dev All Weapons Arena";
1942 g_weaponarena_weapons = weapons_devall();
1944 else if (s == "most")
1947 g_weaponarena_list = "Most Weapons Arena";
1948 g_weaponarena_weapons = weapons_most();
1950 else if (s == "all_available")
1953 g_weaponarena_list = "All Available Weapons Arena";
1955 // this needs to run after weaponsInMapAll is initialized
1956 InitializeEntity(NULL, weaponarena_available_all_update, INITPRIO_FINDTARGET);
1958 else if (s == "devall_available")
1961 g_weaponarena_list = "Dev All Available Weapons Arena";
1963 // this needs to run after weaponsInMapAll is initialized
1964 InitializeEntity(NULL, weaponarena_available_devall_update, INITPRIO_FINDTARGET);
1966 else if (s == "most_available")
1969 g_weaponarena_list = "Most Available Weapons Arena";
1971 // this needs to run after weaponsInMapAll is initialized
1972 InitializeEntity(NULL, weaponarena_available_most_update, INITPRIO_FINDTARGET);
1974 else if (s == "none")
1977 g_weaponarena_list = "No Weapons Arena";
1982 float t = tokenize_console(s);
1983 g_weaponarena_list = "";
1984 for (int j = 0; j < t; ++j)
1987 Weapon wep = Weapon_from_name(s);
1990 g_weaponarena_weapons |= (wep.m_wepset);
1991 g_weaponarena_list = strcat(g_weaponarena_list, wep.netname, " & ");
1994 if (g_weaponarena_list != "") // remove trailing " & "
1995 g_weaponarena_list = substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3);
1996 else // no valid weapon found
1997 g_weaponarena_list = "No Weapons Arena";
2002 g_weapon_stay = 0; // incompatible
2003 start_weapons = g_weaponarena_weapons;
2004 start_items |= IT_UNLIMITED_AMMO | IT_UNLIMITED_SUPERWEAPONS;
2005 g_weaponarena_list = strzone(g_weaponarena_list);
2009 FOREACH(Weapons, it != WEP_Null, {
2010 int w = want_weapon(it, false);
2011 WepSet s = it.m_wepset;
2015 start_weapons_default |= s;
2017 start_weapons_defaultmask |= s;
2021 if(cvar("g_balance_superweapons_time") < 0)
2022 start_items |= IT_UNLIMITED_SUPERWEAPONS;
2024 if(!cvar("g_use_ammunition"))
2025 start_items |= IT_UNLIMITED_AMMO;
2027 if(start_items & IT_UNLIMITED_AMMO)
2029 start_ammo_shells = 999;
2030 start_ammo_nails = 999;
2031 start_ammo_rockets = 999;
2032 start_ammo_cells = 999;
2033 start_ammo_plasma = 999;
2034 start_ammo_fuel = 999;
2038 start_ammo_shells = cvar("g_start_ammo_shells");
2039 start_ammo_nails = cvar("g_start_ammo_nails");
2040 start_ammo_rockets = cvar("g_start_ammo_rockets");
2041 start_ammo_cells = cvar("g_start_ammo_cells");
2042 start_ammo_plasma = cvar("g_start_ammo_plasma");
2043 start_ammo_fuel = cvar("g_start_ammo_fuel");
2044 random_start_weapons_count = cvar("g_random_start_weapons_count");
2045 SetResource(random_start_ammo, RES_SHELLS, cvar("g_random_start_shells"));
2046 SetResource(random_start_ammo, RES_BULLETS, cvar("g_random_start_bullets"));
2047 SetResource(random_start_ammo, RES_ROCKETS, cvar("g_random_start_rockets"));
2048 SetResource(random_start_ammo, RES_CELLS, cvar("g_random_start_cells"));
2049 SetResource(random_start_ammo, RES_PLASMA, cvar("g_random_start_plasma"));
2052 warmup_start_ammo_shells = start_ammo_shells;
2053 warmup_start_ammo_nails = start_ammo_nails;
2054 warmup_start_ammo_rockets = start_ammo_rockets;
2055 warmup_start_ammo_cells = start_ammo_cells;
2056 warmup_start_ammo_plasma = start_ammo_plasma;
2057 warmup_start_ammo_fuel = start_ammo_fuel;
2058 warmup_start_health = start_health;
2059 warmup_start_armorvalue = start_armorvalue;
2060 warmup_start_weapons = start_weapons;
2061 warmup_start_weapons_default = start_weapons_default;
2062 warmup_start_weapons_defaultmask = start_weapons_defaultmask;
2066 warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
2067 warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
2068 warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
2069 warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
2070 warmup_start_ammo_plasma = cvar("g_warmup_start_ammo_plasma");
2071 warmup_start_ammo_fuel = cvar("g_warmup_start_ammo_fuel");
2072 warmup_start_health = cvar("g_warmup_start_health");
2073 warmup_start_armorvalue = cvar("g_warmup_start_armor");
2074 warmup_start_weapons = '0 0 0';
2075 warmup_start_weapons_default = '0 0 0';
2076 warmup_start_weapons_defaultmask = '0 0 0';
2077 FOREACH(Weapons, it != WEP_Null, {
2078 int w = want_weapon(it, autocvar_g_warmup_allguns);
2079 WepSet s = it.m_wepset;
2081 warmup_start_weapons |= s;
2083 warmup_start_weapons_default |= s;
2085 warmup_start_weapons_defaultmask |= s;
2089 if (autocvar_g_jetpack)
2090 start_items |= ITEM_Jetpack.m_itemid;
2092 MUTATOR_CALLHOOK(SetStartItems);
2094 if (start_items & ITEM_Jetpack.m_itemid)
2096 start_items |= ITEM_JetpackRegen.m_itemid;
2097 start_ammo_fuel = max(start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
2098 warmup_start_ammo_fuel = max(warmup_start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
2101 start_ammo_shells = max(0, start_ammo_shells);
2102 start_ammo_nails = max(0, start_ammo_nails);
2103 start_ammo_rockets = max(0, start_ammo_rockets);
2104 start_ammo_cells = max(0, start_ammo_cells);
2105 start_ammo_plasma = max(0, start_ammo_plasma);
2106 start_ammo_fuel = max(0, start_ammo_fuel);
2107 SetResource(random_start_ammo, RES_SHELLS, max(0, GetResource(random_start_ammo, RES_SHELLS)));
2108 SetResource(random_start_ammo, RES_BULLETS, max(0, GetResource(random_start_ammo, RES_BULLETS)));
2109 SetResource(random_start_ammo, RES_ROCKETS, max(0, GetResource(random_start_ammo, RES_ROCKETS)));
2110 SetResource(random_start_ammo, RES_CELLS, max(0, GetResource(random_start_ammo, RES_CELLS)));
2111 SetResource(random_start_ammo, RES_PLASMA, max(0, GetResource(random_start_ammo, RES_PLASMA)));
2113 warmup_start_ammo_shells = max(0, warmup_start_ammo_shells);
2114 warmup_start_ammo_nails = max(0, warmup_start_ammo_nails);
2115 warmup_start_ammo_rockets = max(0, warmup_start_ammo_rockets);
2116 warmup_start_ammo_cells = max(0, warmup_start_ammo_cells);
2117 warmup_start_ammo_plasma = max(0, warmup_start_ammo_plasma);
2118 warmup_start_ammo_fuel = max(0, warmup_start_ammo_fuel);
2121 void readlevelcvars()
2123 serverflags &= ~SERVERFLAG_ALLOW_FULLBRIGHT;
2124 if(cvar("sv_allow_fullbright"))
2125 serverflags |= SERVERFLAG_ALLOW_FULLBRIGHT;
2127 serverflags &= ~SERVERFLAG_FORBID_PICKUPTIMER;
2128 if(cvar("sv_forbid_pickuptimer"))
2129 serverflags |= SERVERFLAG_FORBID_PICKUPTIMER;
2131 sv_ready_restart_after_countdown = cvar("sv_ready_restart_after_countdown");
2133 if(cvar("g_campaign"))
2134 warmup_stage = 0; // no warmup during campaign
2137 warmup_stage = autocvar_g_warmup;
2138 if (warmup_stage < 0 || warmup_stage > 1)
2139 warmup_limit = -1; // don't start until there's enough players
2140 else if (warmup_stage == 1)
2142 // this code is duplicated in ReadyCount()
2143 warmup_limit = cvar("g_warmup_limit");
2144 if(warmup_limit == 0)
2145 warmup_limit = autocvar_timelimit * 60;
2149 g_pickup_respawntime_weapon = cvar("g_pickup_respawntime_weapon");
2150 g_pickup_respawntime_superweapon = cvar("g_pickup_respawntime_superweapon");
2151 g_pickup_respawntime_ammo = cvar("g_pickup_respawntime_ammo");
2152 g_pickup_respawntime_short = cvar("g_pickup_respawntime_short");
2153 g_pickup_respawntime_medium = cvar("g_pickup_respawntime_medium");
2154 g_pickup_respawntime_long = cvar("g_pickup_respawntime_long");
2155 g_pickup_respawntime_powerup = cvar("g_pickup_respawntime_powerup");
2156 g_pickup_respawntimejitter_weapon = cvar("g_pickup_respawntimejitter_weapon");
2157 g_pickup_respawntimejitter_superweapon = cvar("g_pickup_respawntimejitter_superweapon");
2158 g_pickup_respawntimejitter_ammo = cvar("g_pickup_respawntimejitter_ammo");
2159 g_pickup_respawntimejitter_short = cvar("g_pickup_respawntimejitter_short");
2160 g_pickup_respawntimejitter_medium = cvar("g_pickup_respawntimejitter_medium");
2161 g_pickup_respawntimejitter_long = cvar("g_pickup_respawntimejitter_long");
2162 g_pickup_respawntimejitter_powerup = cvar("g_pickup_respawntimejitter_powerup");
2164 g_pickup_shells = cvar("g_pickup_shells");
2165 g_pickup_shells_max = cvar("g_pickup_shells_max");
2166 g_pickup_nails = cvar("g_pickup_nails");
2167 g_pickup_nails_max = cvar("g_pickup_nails_max");
2168 g_pickup_rockets = cvar("g_pickup_rockets");
2169 g_pickup_rockets_max = cvar("g_pickup_rockets_max");
2170 g_pickup_cells = cvar("g_pickup_cells");
2171 g_pickup_cells_max = cvar("g_pickup_cells_max");
2172 g_pickup_plasma = cvar("g_pickup_plasma");
2173 g_pickup_plasma_max = cvar("g_pickup_plasma_max");
2174 g_pickup_fuel = cvar("g_pickup_fuel");
2175 g_pickup_fuel_jetpack = cvar("g_pickup_fuel_jetpack");
2176 g_pickup_fuel_max = cvar("g_pickup_fuel_max");
2177 g_pickup_armorsmall = cvar("g_pickup_armorsmall");
2178 g_pickup_armorsmall_max = cvar("g_pickup_armorsmall_max");
2179 g_pickup_armorsmall_anyway = cvar("g_pickup_armorsmall_anyway");
2180 g_pickup_armormedium = cvar("g_pickup_armormedium");
2181 g_pickup_armormedium_max = cvar("g_pickup_armormedium_max");
2182 g_pickup_armormedium_anyway = cvar("g_pickup_armormedium_anyway");
2183 g_pickup_armorbig = cvar("g_pickup_armorbig");
2184 g_pickup_armorbig_max = cvar("g_pickup_armorbig_max");
2185 g_pickup_armorbig_anyway = cvar("g_pickup_armorbig_anyway");
2186 g_pickup_armormega = cvar("g_pickup_armormega");
2187 g_pickup_armormega_max = cvar("g_pickup_armormega_max");
2188 g_pickup_armormega_anyway = cvar("g_pickup_armormega_anyway");
2189 g_pickup_healthsmall = cvar("g_pickup_healthsmall");
2190 g_pickup_healthsmall_max = cvar("g_pickup_healthsmall_max");
2191 g_pickup_healthsmall_anyway = cvar("g_pickup_healthsmall_anyway");
2192 g_pickup_healthmedium = cvar("g_pickup_healthmedium");
2193 g_pickup_healthmedium_max = cvar("g_pickup_healthmedium_max");
2194 g_pickup_healthmedium_anyway = cvar("g_pickup_healthmedium_anyway");
2195 g_pickup_healthbig = cvar("g_pickup_healthbig");
2196 g_pickup_healthbig_max = cvar("g_pickup_healthbig_max");
2197 g_pickup_healthbig_anyway = cvar("g_pickup_healthbig_anyway");
2198 g_pickup_healthmega = cvar("g_pickup_healthmega");
2199 g_pickup_healthmega_max = cvar("g_pickup_healthmega_max");
2200 g_pickup_healthmega_anyway = cvar("g_pickup_healthmega_anyway");
2202 g_pickup_ammo_anyway = cvar("g_pickup_ammo_anyway");
2203 g_pickup_weapons_anyway = cvar("g_pickup_weapons_anyway");
2205 g_weapon_stay = cvar(strcat("g_", GetGametype(), "_weapon_stay"));
2207 g_weapon_stay = cvar("g_weapon_stay");
2209 MUTATOR_CALLHOOK(ReadLevelCvars);
2211 if (!warmup_stage && !autocvar_g_campaign)
2212 game_starttime = time + cvar("g_start_delay");
2214 FOREACH(Weapons, it != WEP_Null, { it.wr_init(it); });
2216 readplayerstartcvars();
2219 void InitializeEntity(entity e, void(entity this) func, int order)
2223 if (!e || e.initialize_entity)
2225 // make a proxy initializer entity
2227 e = new(initialize_entity);
2231 e.initialize_entity = func;
2232 e.initialize_entity_order = order;
2234 cur = initialize_entity_first;
2238 if (!cur || cur.initialize_entity_order > order)
2240 // insert between prev and cur
2242 prev.initialize_entity_next = e;
2244 initialize_entity_first = e;
2245 e.initialize_entity_next = cur;
2249 cur = cur.initialize_entity_next;
2252 void InitializeEntitiesRun()
2254 entity startoflist = initialize_entity_first;
2255 initialize_entity_first = NULL;
2256 delete_fn = remove_except_protected;
2257 for (entity e = startoflist; e; e = e.initialize_entity_next)
2259 e.remove_except_protected_forbidden = 1;
2261 for (entity e = startoflist; e; )
2263 e.remove_except_protected_forbidden = 0;
2264 e.initialize_entity_order = 0;
2265 entity next = e.initialize_entity_next;
2266 e.initialize_entity_next = NULL;
2267 var void(entity this) func = e.initialize_entity;
2268 e.initialize_entity = func_null;
2269 if (e.classname == "initialize_entity")
2271 entity wrappee = e.enemy;
2275 //dprint("Delayed initialization: ", e.classname, "\n");
2283 backtrace(strcat("Null function in: ", e.classname, "\n"));
2287 delete_fn = remove_unsafely;
2290 // deferred dropping
2291 // ported from VM_SV_droptofloor TODO: make a common function for the client-side?
2292 void DropToFloor_Handler(entity this)
2294 if(!this || wasfreed(this))
2296 // no modifying free entities
2300 vector end = this.origin;
2301 if (autocvar_sv_mapformat_is_quake3)
2303 else if (autocvar_sv_mapformat_is_quake2)
2306 end.z -= 256; // Quake, QuakeWorld
2308 // NOTE: SV_NudgeOutOfSolid is used in the engine here
2309 if(autocvar_sv_gameplayfix_droptofloorstartsolid_nudgetocorrect)
2311 _Movetype_UnstickEntity(this);
2312 move_out_of_solid(this);
2315 tracebox(this.origin, this.mins, this.maxs, end, MOVE_NORMAL, this);
2317 if(trace_startsolid && autocvar_sv_gameplayfix_droptofloorstartsolid)
2320 offset = 0.5 * (this.mins + this.maxs);
2321 offset.z = this.mins.z;
2322 org = this.origin + offset;
2323 traceline(org, end, MOVE_NORMAL, this);
2324 trace_endpos = trace_endpos - offset;
2325 if(trace_startsolid)
2327 LOG_DEBUGF("DropToFloor_Handler: %v could not fix badly placed entity", this.origin);
2328 _Movetype_LinkEdict(this, false);
2330 this.groundentity = NULL;
2332 else if(trace_fraction < 1)
2334 LOG_DEBUGF("DropToFloor_Handler: %v fixed badly placed entity", this.origin);
2335 setorigin(this, trace_endpos);
2336 if(autocvar_sv_gameplayfix_droptofloorstartsolid_nudgetocorrect)
2338 _Movetype_UnstickEntity(this);
2339 move_out_of_solid(this);
2342 this.groundentity = trace_ent;
2343 // if support is destroyed, keep suspended (gross hack for floating items in various maps)
2344 this.move_suspendedinair = true;
2349 if(!trace_allsolid && trace_fraction < 1)
2351 setorigin(this, trace_endpos);
2353 this.groundentity = trace_ent;
2354 // if support is destroyed, keep suspended (gross hack for floating items in various maps)
2355 this.move_suspendedinair = true;
2359 // if we can't get the entity out of solid, mark it as on ground so physics doesn't attempt to drop it
2360 // hacky workaround for #2774
2364 this.dropped_origin = this.origin;
2367 void droptofloor(entity this)
2369 InitializeEntity(this, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
2372 bool autocvar_sv_gameplayfix_multiplethinksperframe = true;
2373 void RunThink(entity this, float dt)
2375 // don't let things stay in the past.
2376 // it is possible to start that way by a trigger with a local time.
2377 if(this.nextthink <= 0 || this.nextthink > time + dt)
2380 float oldtime = time; // do we need to save this?
2382 for (int iterations = 0; iterations < 128 && !wasfreed(this); iterations++)
2384 time = max(oldtime, this.nextthink);
2388 getthink(this)(this);
2389 // mods often set nextthink to time to cause a think every frame,
2390 // we don't want to loop in that case, so exit if the new nextthink is
2391 // <= the time the qc was told, also exit if it is past the end of the
2393 if(this.nextthink <= time || this.nextthink > oldtime + dt || !autocvar_sv_gameplayfix_multiplethinksperframe)
2400 bool autocvar_sv_freezenonclients;
2401 void Physics_Frame()
2403 if(autocvar_sv_freezenonclients)
2406 IL_EACH(g_moveables, true,
2408 if(IS_CLIENT(it) || it.move_movetype == MOVETYPE_PHYSICS)
2411 //set_movetype(it, it.move_movetype);
2412 // inline the set_movetype function, since this is called a lot
2413 it.movetype = (it.move_qcphysics) ? MOVETYPE_QCENTITY : it.move_movetype;
2415 if(it.move_qcphysics && it.move_movetype != MOVETYPE_NONE)
2416 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2418 if(it.movetype >= MOVETYPE_USER_FIRST && it.movetype <= MOVETYPE_USER_LAST) // these cases have no think handling
2420 if(it.move_movetype == MOVETYPE_PUSH || it.move_movetype == MOVETYPE_FAKEPUSH)
2421 continue; // these movetypes have no regular think function
2422 // handle thinking here
2423 if (getthink(it) && it.nextthink > 0 && it.nextthink <= time + PHYS_INPUT_TIMELENGTH)
2424 RunThink(it, PHYS_INPUT_TIMELENGTH);
2428 if(autocvar_sv_gameplayfix_delayprojectiles >= 0)
2431 // make a second pass to see if any ents spawned this frame and make
2432 // sure they run their move/think. this is verified by checking .move_time, which will never be 0 if the entity has moved
2433 // MOVETYPE_NONE is also checked as .move_time WILL be 0 with that movetype
2434 IL_EACH(g_moveables, it.move_qcphysics,
2436 if(IS_CLIENT(it) || it.move_time || it.move_movetype == MOVETYPE_NONE || it.move_movetype == MOVETYPE_PHYSICS)
2438 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2442 void systems_update();
2445 anticheat_endframe();
2449 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2450 entity e = IS_SPEC(it) ? it.enemy : it;
2451 if (e.typehitsound) {
2452 STAT(TYPEHIT_TIME, it) = time;
2453 } else if (e.killsound) {
2454 STAT(KILL_TIME, it) = time;
2455 } else if (e.hitsound_damage_dealt) {
2456 STAT(HIT_TIME, it) = time;
2457 // NOTE: this is not accurate as client code doesn't need so much accuracy for its purposes
2458 STAT(HITSOUND_DAMAGE_DEALT_TOTAL, it) += ceil(e.hitsound_damage_dealt);
2461 // add 1 frametime because after this, engine SV_Physics
2462 // increases time by a frametime and then networks the frame
2463 // add another frametime because client shows everything with
2464 // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2466 float altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2467 FOREACH_CLIENT(true, {
2468 it.typehitsound = false;
2469 it.hitsound_damage_dealt = 0;
2470 it.killsound = false;
2471 antilag_record(it, CS(it), altime);
2473 IL_EACH(g_monsters, true,
2475 antilag_record(it, it, altime);
2477 IL_EACH(g_projectiles, it.classname == "nade",
2479 antilag_record(it, it, altime);
2488 * returns true if redirecting
2490 float redirection_timeout;
2491 float redirection_nextthink;
2492 float RedirectionThink()
2494 float clients_found;
2496 if(redirection_target == "")
2499 if(!redirection_timeout)
2501 cvar_set("sv_public", "-2");
2502 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2503 if(redirection_target == "self")
2504 bprint("^3SERVER NOTICE:^7 restarting the server\n");
2506 bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2509 if(time < redirection_nextthink)
2512 redirection_nextthink = time + 1;
2515 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2517 LOG_INFO("Redirecting: sending connect command to ", it.netname);
2518 if(redirection_target == "self")
2519 stuffcmd(it, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2521 stuffcmd(it, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2525 LOG_INFO("Redirecting: ", ftos(clients_found), " clients left.");
2527 if(time > redirection_timeout || clients_found == 0)
2528 localcmd("\nwait; wait; wait; quit\n");
2535 // Loaded from a save game
2536 // some things then break, so let's work around them...
2538 // Progs DB (capture records)
2539 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2543 MapInfo_Enumerate();
2544 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2547 TargetMusic_RestoreGame();
2554 if(world_initialized > 0)
2556 world_initialized = 0;
2558 // if a timeout is active, reset the slowmo value to normal
2559 if(timeout_status == TIMEOUT_ACTIVE)
2560 cvar_set("slowmo", ftos(orig_slowmo));
2562 LOG_TRACE("Saving persistent data...");
2565 // playerstats with unfinished match
2566 PlayerStats_GameReport(false);
2568 if(!cheatcount_total)
2570 if(autocvar_sv_db_saveasdump)
2571 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2573 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2575 if(autocvar_developer > 0)
2577 if(autocvar_sv_db_saveasdump)
2578 db_dump(TemporaryDB, "server-temp.db");
2580 db_save(TemporaryDB, "server-temp.db");
2582 CheatShutdown(); // must be after cheatcount check
2583 db_close(ServerProgsDB);
2584 db_close(TemporaryDB);
2585 LOG_TRACE("Saving persistent data... done!");
2586 // tell the bot system the game is ending now
2589 WeaponStats_Shutdown();
2592 strfree(sv_termsofservice_url_escaped);
2594 else if(world_initialized == 0)
2596 LOG_INFO("NOTE: crashed before even initializing the world, not saving persistent data");
2600 __init_dedicated_server_shutdown();