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(p) if(substring(k, 0, strlen(p)) == p) continue
170 #define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
171 #define BADCVAR(p) if(k == p) continue
172 #define BADVALUE(p, val) if (k == p && v == val) continue
173 #define BADPRESUFFIXVALUE(p,s,val) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s && v == val) continue
175 // general excludes and namespaces for server admin used cvars
176 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
180 BADPREFIX("cvar_check_");
182 BADCVAR("g_configversion");
183 BADCVAR("halflifebsp");
184 BADCVAR("sv_mapformat_is_quake2");
185 BADCVAR("sv_mapformat_is_quake3");
186 BADPREFIX("sv_world");
192 BADPREFIX("scoreboard_");
193 BADPREFIX("g_campaign");
194 BADPREFIX("g_waypointsprite_");
200 BADPREFIX("net_slist_");
206 BADPREFIX("sensitivity");
207 BADPREFIX("userbind");
210 BADPREFIX("crosshair");
211 BADCVAR("mod_q3bsp_lightmapmergepower");
212 BADCVAR("mod_q3bsp_nolightmaps");
214 BADCVAR("mastervolume");
216 BADCVAR("bgmvolume");
217 BADCVAR("in_pitch_min");
218 BADCVAR("in_pitch_max");
221 BADCVAR("developer");
222 BADCVAR("log_dest_udp");
223 BADCVAR("net_address");
224 BADCVAR("net_address_ipv6");
226 BADCVAR("savedgamecfg");
227 BADCVAR("serverconfig");
228 BADCVAR("sv_autoscreenshot");
229 BADCVAR("sv_heartbeatperiod");
230 BADCVAR("sv_vote_master_password");
231 BADCVAR("sys_colortranslation");
232 BADCVAR("sys_specialcharactertranslation");
233 BADCVAR("timeformat");
234 BADCVAR("timestamps");
235 BADCVAR("g_require_stats");
236 BADPREFIX("developer_");
238 BADPREFIX("g_banned_list");
239 BADPREFIX("g_require_stats_");
240 BADPREFIX("g_chat_flood_");
241 BADPREFIX("g_ghost_items");
242 BADPREFIX("g_playerstats_");
243 BADPREFIX("g_voice_flood_");
244 BADPREFIX("log_file");
247 BADPREFIX("sv_allowdownloads");
248 BADPREFIX("sv_autodemo");
249 BADPREFIX("sv_curl_");
250 BADPREFIX("sv_eventlog");
251 BADPREFIX("sv_logscores_");
252 BADPREFIX("sv_master");
253 BADPREFIX("sv_weaponstats_");
254 BADPREFIX("sv_waypointsprite_");
255 BADCVAR("rescan_pending");
257 // these can contain player IDs, so better hide
258 BADPREFIX("g_forced_team_");
259 BADCVAR("sv_muteban_list");
260 BADCVAR("sv_voteban_list");
261 BADCVAR("sv_allow_customplayermodels_idlist");
262 BADCVAR("sv_allow_customplayermodels_speciallist");
265 BADCVAR("fraglimit");
267 BADCVAR("g_assault");
269 BADCVAR("g_ca_teams");
270 BADCVAR("g_conquest");
271 BADCVAR("g_conquest_teams");
276 BADCVAR("g_domination");
277 BADCVAR("g_domination_default_teams");
279 BADCVAR("g_duel_not_dm_maps");
280 BADCVAR("g_freezetag");
281 BADCVAR("g_freezetag_teams");
282 BADCVAR("g_invasion_type");
283 BADCVAR("g_jailbreak");
284 BADCVAR("g_jailbreak_teams");
285 BADCVAR("g_keepaway");
286 BADCVAR("g_keyhunt");
287 BADCVAR("g_keyhunt_teams");
290 BADCVAR("g_nexball");
291 BADCVAR("g_onslaught");
293 BADCVAR("g_race_laps_limit");
294 BADCVAR("g_race_qualifying_timelimit");
295 BADCVAR("g_race_qualifying_timelimit_override");
296 BADCVAR("g_runematch");
297 BADCVAR("g_shootfromeye");
299 BADCVAR("g_survival");
300 BADCVAR("g_survival_not_dm_maps");
302 BADCVAR("g_tdm_on_dm_maps");
303 BADCVAR("g_tdm_teams");
304 BADCVAR("g_tmayhem");
305 BADCVAR("g_tmayhem_teams");
307 BADCVAR("leadlimit");
310 BADCVAR("timelimit");
311 BADCVAR("g_mapinfo_q3compat");
312 BADCVAR("g_mapinfo_settemp_acl");
313 BADCVAR("g_mapinfo_ignore_warnings");
314 BADCVAR("g_maplist_ignore_sizes");
315 BADCVAR("g_maplist_sizes_count_bots");
319 BADCVAR("g_maplist");
320 BADCVAR("g_maplist_mostrecent");
322 BADCVAR("sv_termsofservice_url");
325 d = cvar_defstring(k);
331 cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
332 if(strlen(cvar_changes) > 16384)
334 cvar_changes = "// too many settings have been changed to show them here\n";
339 // now check if the changes are actually gameplay relevant
341 // does nothing gameplay relevant
342 BADCVAR("captureleadlimit_override");
343 BADCVAR("condump_stripcolors");
344 BADCVAR("fs_gamedir");
345 BADCVAR("g_allow_oldvortexbeam");
346 BADCVAR("g_balance_kill_delay");
347 BADCVAR("g_buffs_pickup_anyway");
348 BADCVAR("g_buffs_randomize");
349 BADCVAR("g_buffs_randomize_teamplay");
350 BADCVAR("g_campcheck_distance");
351 BADCVAR("g_chatsounds");
352 BADCVAR("g_ca_point_leadlimit");
353 BADCVAR("g_ca_point_limit");
354 BADCVAR("g_ca_spectate_enemies");
355 BADCVAR("g_ctf_captimerecord_always");
356 BADCVAR("g_ctf_flag_glowtrails");
357 BADCVAR("g_ctf_dynamiclights");
358 BADCVAR("g_ctf_flag_pickup_verbosename");
359 BADCVAR("g_ctf_flagcarrier_auto_helpme_damage");
360 BADPRESUFFIX("g_ctf_flag_", "_model");
361 BADPRESUFFIX("g_ctf_flag_", "_skin");
362 BADCVAR("g_domination_point_leadlimit");
363 BADCVAR("g_forced_respawn");
364 BADCVAR("g_freezetag_point_leadlimit");
365 BADCVAR("g_freezetag_point_limit");
366 BADCVAR("g_glowtrails");
368 BADCVAR("g_casings");
369 BADCVAR("g_invasion_point_limit");
370 BADCVAR("g_jump_grunt");
371 BADCVAR("g_keepaway_ballcarrier_effects");
372 BADCVAR("g_keepawayball_effects");
373 BADCVAR("g_keyhunt_point_leadlimit");
374 BADCVAR("g_nexball_goalleadlimit");
375 BADCVAR("g_new_toys_autoreplace");
376 BADCVAR("g_new_toys_use_pickupsound");
377 BADCVAR("g_physics_predictall");
378 BADCVAR("g_piggyback");
379 BADCVAR("g_playerclip_collisions");
380 BADCVAR("g_spawn_alloweffects");
381 BADCVAR("g_tdm_point_leadlimit");
382 BADCVAR("g_tdm_point_limit");
383 BADCVAR("g_mayhem_point_limit");
384 BADCVAR("g_mayhem_point_leadlimit");
385 BADCVAR("g_tmayhem_point_limit");
386 BADCVAR("g_tmayhem_point_leadlimit");
387 BADCVAR("leadlimit_and_fraglimit");
388 BADCVAR("leadlimit_override");
390 BADCVAR("sv_announcer");
391 BADCVAR("sv_autopause");
392 BADCVAR("sv_checkforpacketsduringsleep");
393 BADCVAR("sv_damagetext");
394 BADCVAR("sv_db_saveasdump");
395 BADCVAR("sv_intermission_cdtrack");
396 BADCVAR("sv_mapchange_delay");
397 BADCVAR("sv_minigames");
398 BADCVAR("sv_namechangetimer");
399 BADCVAR("sv_precacheplayermodels");
400 BADCVAR("sv_qcphysics");
402 BADCVAR("sv_stepheight");
403 BADCVAR("sv_timeout");
404 BADCVAR("sv_weapons_modeloverride");
405 BADCVAR("w_prop_interval");
407 BADPREFIX("crypto_");
408 BADPREFIX("gameversion");
409 BADPREFIX("g_chat_");
410 BADPREFIX("g_ctf_captimerecord_");
411 BADPREFIX("g_hats_");
412 BADPREFIX("g_maplist_");
414 BADPREFIX("g_respawn_");
416 BADPREFIX("notification_");
419 BADPREFIX("sv_allow_");
420 BADPREFIX("sv_cullentities_");
421 BADPREFIX("sv_maxidle");
422 BADPREFIX("sv_minigames_");
423 BADPREFIX("sv_radio_");
424 BADPREFIX("sv_timeout_");
425 BADPREFIX("sv_vote_");
426 BADPREFIX("timelimit_");
427 BADPRESUFFIX("g_", "_round_timelimit");
429 // allowed changes to server admins (please sync this to server.cfg)
433 // :%s,//\([^ ]*\).*,BADCVAR("\1");,
435 // yes, this does contain some redundant stuff, don't really care
436 BADPREFIX("bot_ai_");
437 BADCVAR("bot_config_file");
438 BADCVAR("bot_number");
439 BADCVAR("bot_prefix");
440 BADCVAR("bot_suffix");
441 BADCVAR("capturelimit_override");
442 BADCVAR("fraglimit_override");
444 BADCVAR("g_antilag");
445 BADCVAR("g_balance_teams");
446 BADCVAR("g_balance_teams_prevent_imbalance");
447 BADCVAR("g_balance_teams_scorefactor");
448 BADCVAR("g_ban_sync_trusted_servers");
449 BADCVAR("g_ban_sync_uri");
451 BADCVAR("g_ca_teams_override");
452 BADCVAR("g_ctf_fullbrightflags");
453 BADCVAR("g_ctf_ignore_frags");
454 BADCVAR("g_ctf_leaderboard");
455 BADCVAR("g_domination_point_limit");
456 BADCVAR("g_domination_teams_override");
457 BADCVAR("g_freezetag_revive_spawnshield");
458 BADCVAR("g_freezetag_teams_override");
459 BADCVAR("g_friendlyfire");
460 BADCVAR("g_fullbrightitems");
461 BADCVAR("g_fullbrightplayers");
462 BADCVAR("g_keyhunt_point_limit");
463 BADCVAR("g_keyhunt_teams_override");
464 BADCVAR("g_lms_lives_override");
465 BADCVAR("g_mayhem_powerups");
466 BADCVAR("g_maplist");
467 BADCVAR("g_maxplayers");
468 BADCVAR("g_mirrordamage");
469 BADCVAR("g_nexball_goallimit");
470 BADCVAR("g_norecoil");
471 BADCVAR("g_physics_clientselect");
473 BADCVAR("g_powerups");
474 BADCVAR("g_powerups_drop_ondeath");
475 BADCVAR("g_player_brightness");
476 BADCVAR("g_rocket_flying");
477 BADCVAR("g_rocket_flying_disabledelays");
478 BADPREFIX("g_spawnshield");
479 BADCVAR("g_start_delay");
480 BADCVAR("g_superspectate");
481 BADCVAR("g_tdm_teams_override");
482 BADCVAR("g_tmayhem_teams_override");
483 BADCVAR("g_tmayhem_powerups");
484 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
487 BADCVAR("maxplayers");
488 BADCVAR("minplayers");
489 BADCVAR("minplayers_per_team");
490 BADCVAR("net_address");
492 BADCVAR("rcon_password");
493 BADCVAR("rcon_restricted_commands");
494 BADCVAR("rcon_restricted_password");
496 BADCVAR("sv_adminnick");
497 BADCVAR("sv_autoscreenshot");
498 BADCVAR("sv_autotaunt");
499 BADCVAR("sv_curl_defaulturl");
500 BADCVAR("sv_defaultcharacter");
501 BADCVAR("sv_defaultcharacterskin");
502 BADCVAR("sv_defaultplayercolors");
503 BADCVAR("sv_defaultplayermodel");
504 BADCVAR("sv_defaultplayerskin");
505 BADCVAR("sv_maxrate");
507 BADCVAR("sv_public");
508 BADCVAR("sv_showfps");
509 BADCVAR("sv_showspectators");
510 BADCVAR("sv_status_privacy");
512 BADCVAR("sv_vote_call");
513 BADCVAR("sv_vote_commands");
514 BADCVAR("sv_vote_majority_factor");
515 BADCVAR("sv_vote_master");
516 BADCVAR("sv_vote_master_commands");
517 BADCVAR("sv_vote_master_password");
518 BADCVAR("sv_vote_simple_majority_factor");
519 BADVALUE("sys_ticrate", "0.0166667");
520 BADVALUE("sys_ticrate", "0.0333333");
521 BADCVAR("teamplay_mode");
522 BADCVAR("timelimit_override");
523 BADPREFIX("g_warmup");
524 BADPREFIX("sv_info_");
525 BADPREFIX("sv_ready_restart_");
527 BADPRESUFFIXVALUE("g_", "_weaponarena", "most");
528 BADPRESUFFIXVALUE("g_", "_weaponarena", "most_available");
530 // mutators that announce themselves properly to the server browser
531 BADCVAR("g_instagib");
532 BADCVAR("g_new_toys");
534 BADCVAR("g_grappling_hook");
535 BADCVAR("g_jetpack");
541 #undef BADPRESUFFIXVALUE
545 cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
546 if(strlen(cvar_purechanges) > 16384)
548 cvar_purechanges = "// too many settings have been changed to show them here\n";
552 ++cvar_purechanges_count;
553 // WARNING: this variable is used for the server list
554 // NEVER dare to skip this code!
555 // Hacks to intentionally appearing as "pure server" even though you DO have
556 // modified settings may be punished by removal from the server list.
557 // You can do to the variables cvar_changes and cvar_purechanges all you want,
561 if(cvar_changes == "")
562 cvar_changes = "// this server runs at default server settings\n";
564 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
565 cvar_changes = strzone(cvar_changes);
566 if(cvar_purechanges == "")
567 cvar_purechanges = "// this server runs at default gameplay settings\n";
569 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
570 cvar_purechanges = strzone(cvar_purechanges);
574 bool RandomSeed_Send(entity this, entity to, int sf)
576 WriteHeader(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
577 WriteShort(MSG_ENTITY, this.cnt);
580 void RandomSeed_Think(entity this)
582 this.cnt = bound(0, floor(random() * 65536), 65535);
583 this.nextthink = time + 5;
587 void RandomSeed_Spawn()
589 randomseed = new_pure(randomseed);
590 setthink(randomseed, RandomSeed_Think);
591 Net_LinkEntity(randomseed, false, 0, RandomSeed_Send);
593 getthink(randomseed)(randomseed); // sets random seed and nextthink
596 spawnfunc(__init_dedicated_server)
598 // handler for _init/_init map (only for dedicated server initialization)
600 world_initialized = -1; // don't complain
602 delete_fn = remove_unsafely;
604 entity e = new(GotoFirstMap);
605 setthink(e, GotoFirstMap);
606 e.nextthink = time; // this is usually 1 at this point
608 e = new(info_player_deathmatch); // safeguard against player joining
610 // assign reflectively to avoid "assignment to world" warning
611 for (int i = 0, n = numentityfields(); i < n; ++i)
613 string k = entityfieldname(i);
614 if (k == "classname")
616 // safeguard against various stuff ;)
617 putentityfieldstring(i, this, "worldspawn");
622 // needs to be done so early because of the constants they create
625 static_init_precache();
627 IL_PUSH(g_spawnpoints, e); // just incase
630 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
633 void __init_dedicated_server_shutdown() {
637 STATIC_INIT_EARLY(maxclients)
640 for (entity head = nextent(NULL); head; head = nextent(head)) {
645 void GameplayMode_DelayedInit(entity this)
647 // at this stage team entities are spawned, teamplay contains the number of them
649 if(!scores_initialized)
650 ScoreRules_generic();
652 if (warmup_stage >= 0 && autocvar_g_maxplayers >= 0)
655 MapReadSizes(mapname);
657 if (autocvar_g_maxplayers < 0 && teamplay)
659 // automatic maxplayers should be a multiple of team count
660 if (map_maxplayers == 0 || map_maxplayers > maxclients)
661 map_maxplayers = maxclients; // unlimited, but may need rounding
662 int d = map_maxplayers % AVAILABLE_TEAMS;
663 int u = AVAILABLE_TEAMS - d;
664 map_maxplayers += (u <= d && u + map_maxplayers <= maxclients) ? u : -d;
667 if (warmup_stage < 0)
669 int m = GetPlayerLimit();
670 if (m <= 0) m = maxclients;
671 map_minplayers = bound(max(2, AVAILABLE_TEAMS * 2), map_minplayers, m);
674 // automatic minplayers should be a multiple of team count
675 int d = map_minplayers % AVAILABLE_TEAMS;
676 int u = AVAILABLE_TEAMS - d;
677 map_minplayers += (u < d && u + map_minplayers <= m) ? u : -d;
681 map_minplayers = 0; // don't display a minimum if it's not used (g_maxplayers < 0 && g_warmup >= 0)
684 void InitGameplayMode()
688 // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
690 // assign reflectively to avoid "assignment to world" warning
691 for (int i = 0, done = 0, n = numentityfields(); i < n; ++i)
693 string k = entityfieldname(i);
694 vector v = (k == "mins") ? mi_min : (k == "maxs") ? mi_max : '0 0 0';
697 putentityfieldstring(i, world, sprintf("%v", v));
698 if (++done == 2) break;
701 // currently, NetRadiant's limit is 131072 qu for each side
702 // distance from one corner of a 131072qu cube to the opposite corner is approx. 227023 qu
703 // set the distance according to map size but don't go over the limit to avoid issues with float precision
704 // in case somebody makes extremely large maps
705 max_shot_distance = min(230000, vlen(world.maxs - world.mins));
707 MapInfo_LoadMapSettings(mapname);
708 GameRules_teams(false);
710 if (!cvar_value_issafe(world.fog))
712 LOG_INFO("The current map contains a potentially harmful fog setting, ignored");
713 world.fog = string_null;
715 if(MapInfo_Map_fog != "")
717 if(MapInfo_Map_fog == "none")
718 world.fog = string_null;
720 world.fog = strzone(MapInfo_Map_fog);
722 clientstuff = strzone(MapInfo_Map_clientstuff);
724 MapInfo_ClearTemps();
726 gamemode_name = MapInfo_Type_ToText(MapInfo_LoadedGametype);
728 cache_mutatormsg = strzone("");
729 cache_lastmutatormsg = strzone("");
731 InitializeEntity(NULL, GameplayMode_DelayedInit, INITPRIO_GAMETYPE_FALLBACK);
734 bool world_already_spawned;
735 spawnfunc(worldspawn)
737 cvar_set("_endmatch", "0");
738 server_is_dedicated = boolean(stof(cvar_defstring("is_dedicated")));
740 if (autocvar_sv_termsofservice_url && autocvar_sv_termsofservice_url != "")
742 strcpy(sv_termsofservice_url_escaped, strreplace(":", "|", autocvar_sv_termsofservice_url));
746 strcpy(sv_termsofservice_url_escaped, "INVALID");
749 bool wantrestart = false;
751 if (!server_is_dedicated)
753 // DP unloads dlcache pk3s before starting a listen server since https://gitlab.com/xonotic/darkplaces/-/merge_requests/134
754 // restore csqc_progname too
755 string expect = "csprogs.dat";
756 wantrestart = cvar_string("csqc_progname") != expect;
757 cvar_set("csqc_progname", expect);
761 // Try to use versioned csprogs from pk3
762 // Only ever use versioned csprogs.dat files on dedicated servers;
763 // we need to reset csqc_progname on clients ourselves, and it's easier if the client's release name is constant
764 string pk3csprogs = "csprogs-" WATERMARK ".dat";
765 // This always works; fall back to it if a versioned csprogs.dat is suddenly missing
766 string select = "csprogs.dat";
767 if (fexists(pk3csprogs)) select = pk3csprogs;
768 if (cvar_string("csqc_progname") != select)
770 cvar_set("csqc_progname", select);
773 // Check for updates on startup
774 // We do it this way for atomicity so that connecting clients still match the server progs and don't disconnect
775 int sentinel = fopen("progs.txt", FILE_READ);
778 string switchversion = fgets(sentinel);
780 if (switchversion != "" && switchversion != WATERMARK)
782 LOG_INFOF("Switching progs: " WATERMARK " -> %s", switchversion);
783 // if it doesn't exist, assume either:
784 // a) the current program was overwritten
785 // b) this is a client only update
786 string newprogs = sprintf("progs-%s.dat", switchversion);
787 if (fexists(newprogs))
789 cvar_set("sv_progs", newprogs);
792 string newcsprogs = sprintf("csprogs-%s.dat", switchversion);
793 if (fexists(newcsprogs))
795 cvar_set("csqc_progname", newcsprogs);
803 LOG_INFO("Restart requested");
804 changelevel(mapname);
805 // let initialization continue, shutdown depends on it
809 if(world_already_spawned)
810 error("world already spawned - you may have EXACTLY ONE worldspawn!");
811 world_already_spawned = true;
813 delete_fn = remove_safely; // during spawning, watch what you remove!
815 cvar_changes_init(); // do this very early now so it REALLY matches the server config
817 // default to RACE_RECORD, can be overwritten by gamemodes
818 record_type = RACE_RECORD;
820 // needs to be done so early because of the constants they create
823 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
825 TemporaryDB = db_create();
830 // 1 FLICKER (first variety)
831 lightstyle(1, "mmnmmommommnonmmonqnmmo");
833 // 2 SLOW STRONG PULSE
834 lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
836 // 3 CANDLE (first variety)
837 lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
840 lightstyle(4, "mamamamamama");
843 lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
845 // 6 FLICKER (second variety)
846 lightstyle(6, "nmonqnmomnmomomno");
848 // 7 CANDLE (second variety)
849 lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
851 // 8 CANDLE (third variety)
852 lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
854 // 9 SLOW STROBE (fourth variety)
855 lightstyle(9, "aaaaaaaazzzzzzzz");
857 // 10 FLUORESCENT FLICKER
858 lightstyle(10, "mmamammmmammamamaaamammma");
860 // 11 SLOW PULSE NOT FADE TO BLACK
861 lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
863 // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
868 if(autocvar_g_campaign)
871 PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
873 Map_MarkAsRecent(mapname);
877 static_init_precache();
880 GameRules_limit_fallbacks();
883 bot_waypoints_for_items = autocvar_g_waypoints_for_items;
884 if(bot_waypoints_for_items == 1)
885 if(this.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
886 bot_waypoints_for_items = 0;
888 WaypointSprite_Init();
891 // changing the logic generating it is okay. But:
892 // it HAS to stay <= 64 chars
893 // character set: ASCII 33-126 without the following characters: : ; ' " \ $
894 // strftime(false, "%s") isn't reliable, see strftime_s description
895 matchid = strzone(sprintf("%d.%s.%06d", autocvar_sv_eventlog_files_counter, strftime_s(), random() * 1000000));
897 if(autocvar_sv_eventlog)
898 GameLogInit(); // requires matchid to be set
900 cvar_set("nextmap", "");
904 if(autocvar_g_campaign)
910 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
912 q3compat = BITSET(q3compat, Q3COMPAT_ARENA, _MapInfo_FindArenaFile(mapname, ".arena") != "");
913 q3compat = BITSET(q3compat, Q3COMPAT_DEFI, _MapInfo_FindArenaFile(mapname, ".defi") != "");
915 // quake 3 music support
916 if(world.music || world.noise)
918 // prefer .music over .noise
921 chosen_music = world.music;
923 chosen_music = world.noise;
925 string newstuff = strcat(clientstuff, "cd loop \"", chosen_music, "\"\n");
926 strcpy(clientstuff, newstuff);
929 if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
931 int fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
935 while((s = fgets(fd)))
937 int l = tokenize_console(s);
942 string trackname = argv(2);
943 LOG_INFO("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:");
944 LOG_INFO(" cdtrack ", trackname);
945 if (cvar_value_issafe(trackname))
947 string newstuff = strcat(clientstuff, "cd loop \"", trackname, "\"\n");
948 strcpy(clientstuff, newstuff);
951 else if(argv(0) == "fog")
953 LOG_INFO("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:");
954 LOG_INFO(" \"fog\" \"", s, "\"");
956 else if(argv(0) == "set")
958 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
959 LOG_INFO(" clientsettemp_for_type all ", argv(1), " ", argv(2));
961 else if(argv(0) != "//")
963 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
964 LOG_INFO(" clientsettemp_for_type all ", argv(0), " ", argv(1));
975 // set up information replies for clients and server to use
976 maplist_reply = strzone(getmaplist());
977 lsmaps_reply = strzone(getlsmaps());
978 monsterlist_reply = strzone(getmonsterlist());
979 bool records_available = false;
980 for(int i = 0; i < 10; ++i)
982 string s = getrecords(i);
985 records_reply[i] = strzone(s);
986 records_available = true;
989 if (!records_available)
990 records_reply[0] = "No records available for the current game mode.\n";
991 ladder_reply = strzone(getladder());
992 rankings_reply = strzone(getrankings());
997 PingPLReport_Spawn();
1001 if (!wantrestart) localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
1003 // fill sv_curl_serverpackages from .serverpackage files
1004 if (autocvar_sv_curl_serverpackages_auto)
1006 string s = "csprogs-" WATERMARK ".dat";
1007 // remove automatically managed files from the list to prevent duplicates
1008 for (int i = 0, n = tokenize_console(cvar_string("sv_curl_serverpackages")); i < n; ++i)
1010 string pkg = argv(i);
1011 if (startsWith(pkg, "csprogs-")) continue;
1012 if (endsWith(pkg, "-serverpackage.txt")) continue;
1013 if (endsWith(pkg, ".serverpackage")) continue; // OLD legacy
1016 // add automatically managed files to the list
1017 #define X(match) MACRO_BEGIN \
1018 int fd = search_begin(match, true, false); \
1021 for (int i = 0, j = search_getsize(fd); i < j; ++i) \
1023 s = cons(s, search_getfilename(fd, i)); \
1028 X("*-serverpackage.txt");
1029 X("*.serverpackage");
1031 cvar_set("sv_curl_serverpackages", s);
1034 // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
1035 modname = "Xonotic";
1036 // physics/balance/config changes that count as mod
1037 if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
1038 modname = cvar_string("g_mod_physics");
1039 if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance") && cvar_string("g_mod_balance") != "Testing")
1040 modname = cvar_string("g_mod_balance");
1041 if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
1042 modname = cvar_string("g_mod_config");
1043 // extra mutators that deserve to count as mod
1044 MUTATOR_CALLHOOK(SetModname, modname);
1045 modname = M_ARGV(0, string);
1047 // save it for later
1048 modname = strzone(modname);
1050 WinningConditionHelper(this); // set worldstatus
1052 if (autocvar_sv_autopause && server_is_dedicated && !wantrestart)
1053 // INITPRIO_LAST is to soon: bots either didn't join yet or didn't leave yet, see: bot_fixcount()
1054 defer(this, 5, Pause_TryPause_Dedicated);
1056 world_initialized = 1;
1057 __spawnfunc_spawn_all();
1062 //makestatic (this); // Who the f___ did that?
1066 bool MoveToRandomLocationWithinBounds(entity e, vector boundmin, vector boundmax, float goodcontents, float badcontents, float badsurfaceflags, int attempts, float maxaboveground, float minviewdistance, bool frompos)
1068 float m = e.dphitcontentsmask;
1069 e.dphitcontentsmask = goodcontents | badcontents;
1071 vector org = boundmin;
1072 vector delta = boundmax - boundmin;
1076 int j; // used after the loop
1077 for(j = 0; j < attempts; ++j)
1079 start.x = org.x + random() * delta.x;
1080 start.y = org.y + random() * delta.y;
1081 start.z = org.z + random() * delta.z;
1083 // rule 1: start inside world bounds, and outside
1084 // solid, and don't start from somewhere where you can
1085 // fall down to evil
1086 tracebox(start, e.mins, e.maxs, start - '0 0 1' * delta.z, MOVE_NORMAL, e);
1087 if (trace_fraction >= 1)
1089 if (trace_startsolid)
1091 if (trace_dphitcontents & badcontents)
1093 if (trace_dphitq3surfaceflags & badsurfaceflags)
1096 // rule 2: if we are too high, lower the point
1097 if (trace_fraction * delta.z > maxaboveground)
1098 start = trace_endpos + '0 0 1' * maxaboveground;
1099 vector enddown = trace_endpos;
1101 // rule 3: make sure we aren't outside the map. This only works
1102 // for somewhat well formed maps. A good rule of thumb is that
1103 // the map should have a convex outside hull.
1104 // these can be traceLINES as we already verified the starting box
1105 vector mstart = start + 0.5 * (e.mins + e.maxs);
1106 traceline(mstart, mstart + '1 0 0' * delta.x, MOVE_NORMAL, e);
1107 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1109 traceline(mstart, mstart - '1 0 0' * delta.x, MOVE_NORMAL, e);
1110 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1112 traceline(mstart, mstart + '0 1 0' * delta.y, MOVE_NORMAL, e);
1113 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1115 traceline(mstart, mstart - '0 1 0' * delta.y, MOVE_NORMAL, e);
1116 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1118 traceline(mstart, mstart + '0 0 1' * delta.z, MOVE_NORMAL, e);
1119 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1122 // rule 4: we must "see" some spawnpoint or item
1126 if((traceline(mstart, e.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1131 IL_EACH(g_spawnpoints, checkpvs(mstart, it),
1133 if((traceline(mstart, it.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1142 int items_checked = 0;
1143 IL_EACH(g_items, checkpvs(mstart, it),
1145 if((traceline(mstart, it.origin + (it.mins + it.maxs) * 0.5, MOVE_NORMAL, e), trace_fraction) >= 1)
1152 if(items_checked >= attempts)
1160 // find a random vector to "look at"
1161 end.x = org.x + random() * delta.x;
1162 end.y = org.y + random() * delta.y;
1163 end.z = org.z + random() * delta.z;
1164 end = start + normalize(end - start) * vlen(delta);
1166 // rule 4: start TO end must not be too short
1167 tracebox(start, e.mins, e.maxs, end, MOVE_NORMAL, e);
1168 if(trace_startsolid)
1170 if(trace_fraction < minviewdistance / vlen(delta))
1173 // rule 5: don't want to look at sky
1174 if(trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
1177 // rule 6: we must not end up in trigger_hurt
1178 if(tracebox_hits_trigger_hurt(start, e.mins, e.maxs, enddown))
1184 e.dphitcontentsmask = m;
1188 setorigin(e, start);
1189 e.angles = vectoangles(end - start);
1190 LOG_DEBUG("Needed ", ftos(j + 1), " attempts");
1196 float MoveToRandomMapLocation(entity e, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1198 return MoveToRandomLocationWithinBounds(e, world.mins, world.maxs, goodcontents, badcontents, badsurfaceflags, attempts, maxaboveground, minviewdistance, false);
1202 ===============================================================================
1206 ===============================================================================
1209 void DumpStats(float final)
1218 to_console = autocvar_sv_logscores_console;
1219 to_eventlog = autocvar_sv_eventlog;
1220 to_file = autocvar_sv_logscores_file;
1224 to_console = true; // always print printstats replies
1225 to_eventlog = false; // but never print them to the event log
1229 if(autocvar_sv_eventlog_console)
1230 to_console = false; // otherwise we get the output twice
1236 s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1246 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1250 fputs(file, strcat(s, "\n"));
1253 s = strcat(":labels:player:", GetPlayerScoreString(NULL, 0));
1259 fputs(file, strcat(s, "\n"));
1261 FOREACH_CLIENT(IS_REAL_CLIENT(it) || (IS_BOT_CLIENT(it) && autocvar_sv_logscores_bots), {
1262 s = strcat(":player:see-labels:", GetPlayerScoreString(it, 0), ":");
1263 s = strcat(s, ftos(rint(time - CS(it).jointime)), ":");
1264 if(IS_PLAYER(it) || INGAME_JOINED(it))
1265 s = strcat(s, ftos(it.team), ":");
1267 s = strcat(s, "spectator:");
1270 LOG_HELP(s, playername(it.netname, it.team, false));
1272 GameLogEcho(strcat(s, ftos(it.playerid), ":", playername(it.netname, it.team, false)));
1274 fputs(file, strcat(s, playername(it.netname, it.team, false), "\n"));
1279 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1285 fputs(file, strcat(s, "\n"));
1287 for(i = 1; i < 16; ++i)
1289 s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1290 s = strcat(s, ":", ftos(i));
1296 fputs(file, strcat(s, "\n"));
1303 GameLogEcho(":end");
1306 fputs(file, ":end\n");
1312 go to the next level for deathmatch
1313 only called if a time or frag limit has expired
1317 cvar_set("_endmatch", "0");
1318 game_stopped = true;
1319 intermission_running = true; // game over
1321 // enforce a wait time before allowing changelevel
1322 if(player_count > 0)
1323 intermission_exittime = time + autocvar_sv_mapchange_delay;
1325 intermission_exittime = -1;
1328 WriteByte (MSG_ALL, SVC_CDTRACK);
1329 WriteByte (MSG_ALL, 3);
1330 WriteByte (MSG_ALL, 3);
1331 // done in FixIntermission
1334 //pos = FindIntermission ();
1341 PlayerStats_GameReport(true);
1342 WeaponStats_Shutdown();
1344 Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_Null); // kill all centerprints now
1346 if(autocvar_sv_eventlog)
1347 GameLogEcho(":gameover");
1351 int winner_team = 0;
1352 FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), {
1353 FixIntermissionClient(it);
1356 if (teamplay && !winner_team)
1358 winner_team = it.team;
1359 bprint(Team_ColorCode(winner_team), Team_ColorName_Upper(winner_team), "^7 team wins the match\n");
1361 bprint(playername(it.netname, it.team, false), " ^7wins\n");
1365 target_music_kill();
1367 if(autocvar_g_campaign)
1368 CampaignPreIntermission();
1370 MUTATOR_CALLHOOK(MatchEnd);
1372 localcmd("\nsv_hook_gameend\n");
1376 int InitiateSuddenDeath()
1378 // Check first whether normal overtimes could be added before initiating suddendeath mode
1379 // - for this timelimit_overtime needs to be >0 of course
1380 // - also check the winning condition calculated in the previous frame and only add normal overtime
1381 // again, if at the point at which timelimit would be extended again, still no winner was found
1382 if (!autocvar_g_campaign && checkrules_overtimesadded >= 0
1383 && (checkrules_overtimesadded < autocvar_timelimit_overtimes || autocvar_timelimit_overtimes < 0)
1384 && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1386 return 1; // need to call InitiateOvertime later
1390 if(!checkrules_suddendeathend)
1392 if(autocvar_g_campaign)
1394 checkrules_suddendeathend = time; // no suddendeath in campaign
1398 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1401 if(g_race && !g_race_qualifying)
1402 race_StartCompleting();
1408 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1410 ++checkrules_overtimesadded;
1411 overtimes = checkrules_overtimesadded;
1412 //add one more overtime by simply extending the timelimit
1413 cvar_set("timelimit", ftos(autocvar_timelimit + autocvar_timelimit_overtime));
1414 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime * 60);
1417 float GetWinningCode(float fraglimitreached, float equality)
1419 if(autocvar_g_campaign == 1)
1421 if(fraglimitreached)
1430 if(fraglimitreached)
1431 return WINNING_STARTSUDDENDEATHOVERTIME;
1433 return WINNING_NEVER;
1437 if(fraglimitreached)
1445 // set the .winning flag for exactly those players with a given field value
1446 void SetWinners(.float field, float value)
1448 FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), { it.winning = (it.(field) == value); });
1451 // set the .winning flag for those players with a given field value
1452 void AddWinners(.float field, float value)
1454 FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), {
1455 if(it.(field) == value)
1460 // clear the .winning flags
1463 FOREACH_CLIENT(IS_PLAYER(it) || INGAME(it), { it.winning = 0; });
1467 float WinningCondition_Scores(float limit, float leadlimit)
1469 // TODO make everything use THIS winning condition (except LMS)
1470 WinningConditionHelper(NULL);
1474 for (int i = 1; i < 5; ++i)
1476 Team_SetTeamScore(Team_GetTeamFromIndex(i),
1477 TeamScore_GetCompareValue(Team_IndexToTeam(i)));
1482 if(WinningConditionHelper_winner)
1483 WinningConditionHelper_winner.winning = 1;
1484 if(WinningConditionHelper_winnerteam >= 0)
1485 SetWinners(team, WinningConditionHelper_winnerteam);
1487 if(WinningConditionHelper_lowerisbetter)
1489 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1490 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1494 if(WinningConditionHelper_zeroisworst)
1495 leadlimit = 0; // not supported in this mode
1497 if(MUTATOR_CALLHOOK(Scores_CountFragsRemaining))
1500 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1506 fragsleft = FLOAT_MAX;
1507 float leadingfragsleft = FLOAT_MAX;
1509 fragsleft = limit - WinningConditionHelper_topscore;
1511 leadingfragsleft = WinningConditionHelper_secondscore + leadlimit - WinningConditionHelper_topscore;
1513 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1514 fragsleft = max(fragsleft, leadingfragsleft);
1516 fragsleft = min(fragsleft, leadingfragsleft);
1519 if (fragsleft_last != fragsleft) // do not announce same remaining frags multiple times
1522 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_1);
1523 else if (fragsleft == 2)
1524 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_2);
1525 else if (fragsleft == 3)
1526 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_3);
1528 fragsleft_last = fragsleft;
1532 bool fraglimit_reached = (limit && WinningConditionHelper_topscore >= limit);
1533 bool leadlimit_reached = (leadlimit && WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1536 // only respect leadlimit_and_fraglimit when both limits are set or the game will never end
1537 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1538 limit_reached = (fraglimit_reached && leadlimit_reached);
1540 limit_reached = (fraglimit_reached || leadlimit_reached);
1542 return GetWinningCode(
1543 WinningConditionHelper_topscore && limit_reached,
1544 WinningConditionHelper_equality
1548 float WinningCondition_RanOutOfSpawns()
1550 if(have_team_spawns <= 0)
1553 if(!autocvar_g_spawn_useallspawns)
1556 if(!some_spawn_has_been_used)
1559 for (int i = 1; i < 5; ++i)
1561 Team_SetTeamScore(Team_GetTeamFromIndex(i), 0);
1564 FOREACH_CLIENT(IS_PLAYER(it) && !IS_DEAD(it),
1566 if (Team_IsValidTeam(it.team))
1568 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1572 IL_EACH(g_spawnpoints, true,
1574 if (Team_IsValidTeam(it.team))
1576 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1581 float team1_score = Team_GetTeamScore(Team_GetTeamFromIndex(1));
1582 float team2_score = Team_GetTeamScore(Team_GetTeamFromIndex(2));
1583 float team3_score = Team_GetTeamScore(Team_GetTeamFromIndex(3));
1584 float team4_score = Team_GetTeamScore(Team_GetTeamFromIndex(4));
1585 if(team1_score + team2_score + team3_score + team4_score == 0)
1587 checkrules_equality = true;
1590 else if(team1_score + team2_score + team3_score + team4_score == 1)
1595 else if(team2_score)
1597 else if(team3_score)
1599 else // if(team4_score)
1601 entity balance = TeamBalance_CheckAllowedTeams(NULL);
1602 for(i = 0; i < MAX_TEAMSCORE; ++i)
1604 for (int j = 1; j <= NUM_TEAMS; ++j)
1610 if (!TeamBalance_IsTeamAllowed(balance, j))
1614 TeamScore_AddToTeam(Team_IndexToTeam(j), i, -1000);
1618 AddWinners(team, t);
1629 Exit deathmatch games upon conditions
1632 void CheckRules_World()
1639 if (intermission_running) // someone else quit the game already
1641 if(player_count == 0) // Nobody there? Then let's go to the next map
1643 // this will actually check the player count in the next frame
1644 // again, but this shouldn't hurt
1648 float timelimit = autocvar_timelimit * 60;
1649 float fraglimit = autocvar_fraglimit;
1650 float leadlimit = autocvar_leadlimit;
1651 if (leadlimit < 0) leadlimit = 0;
1653 if(warmup_stage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1656 timelimit = 0; // timelimit is not made for warmup
1658 fraglimit = 0; // no fraglimit for now
1659 leadlimit = 0; // no leadlimit for now
1662 if (autocvar__endmatch || timelimit < 0)
1670 timelimit += game_starttime;
1672 int overtimes_prev = overtimes;
1673 int wantovertime = 0;
1675 if(checkrules_suddendeathend)
1677 if(!checkrules_suddendeathwarning)
1679 checkrules_suddendeathwarning = true;
1680 if(g_race && !g_race_qualifying)
1681 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_RACE_FINISHLAP);
1683 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_FRAG);
1688 if (timelimit && time >= timelimit)
1690 if(g_race && (g_race_qualifying == 2) && timelimit > 0)
1693 float playerswithlaps;
1695 totalplayers = playerswithlaps = readyplayers = 0;
1696 FOREACH_CLIENT(IS_PLAYER(it), {
1698 if(GameRules_scoring_add(it, RACE_FASTEST, 0))
1704 // at least 2 of the players have completed a lap: start the RACE
1705 // otherwise, the players should end the qualifying on their own
1706 if(readyplayers || playerswithlaps >= 2)
1708 checkrules_suddendeathend = 0;
1709 ReadyRestart(true); // go to race
1713 wantovertime |= InitiateSuddenDeath();
1716 wantovertime |= InitiateSuddenDeath();
1720 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1726 int checkrules_status = WinningCondition_RanOutOfSpawns();
1727 if(checkrules_status == WINNING_YES)
1728 bprint("Hey! Someone ran out of spawns!\n");
1729 else if(MUTATOR_CALLHOOK(CheckRules_World, checkrules_status, timelimit, fraglimit))
1730 checkrules_status = M_ARGV(0, float);
1732 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
1734 if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
1736 checkrules_status = WINNING_NEVER;
1737 checkrules_overtimesadded = -1;
1738 wantovertime |= InitiateSuddenDeath();
1741 if(checkrules_status == WINNING_NEVER)
1742 // equality cases! Nobody wins if the overtime ends in a draw.
1747 if(checkrules_status == WINNING_NEVER)
1750 checkrules_status = WINNING_YES;
1753 if(checkrules_suddendeathend)
1754 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
1755 checkrules_status = WINNING_YES;
1757 if(checkrules_status == WINNING_YES)
1759 if (overtimes == -1 && overtimes != overtimes_prev)
1761 // if suddendeathend overtime has just begun, revert it
1762 checkrules_suddendeathend = 0;
1763 overtimes = overtimes_prev;
1765 //print("WINNING\n");
1770 float want_weapon(entity weaponinfo, float allguns)
1773 bool allow_mutatorblocked = false;
1775 if(!weaponinfo.m_id)
1778 bool mutator_returnvalue = MUTATOR_CALLHOOK(WantWeapon, weaponinfo, d, allguns, allow_mutatorblocked);
1779 d = M_ARGV(1, float);
1780 allguns = M_ARGV(2, bool);
1781 allow_mutatorblocked = M_ARGV(3, bool);
1784 d = boolean((weaponinfo.spawnflags & WEP_FLAG_NORMAL) && !(weaponinfo.spawnflags & (WEP_FLAG_HIDDEN | WEP_FLAG_SPECIALATTACK)));
1785 else if(!mutator_returnvalue)
1786 d = !(!weaponinfo.weaponstart);
1788 if(!allow_mutatorblocked && (weaponinfo.spawnflags & WEP_FLAG_MUTATORBLOCKED)) // never default mutator blocked guns
1791 float t = weaponinfo.weaponstartoverride;
1793 //LOG_INFOF("want_weapon: %s - d: %d t: %d\n", weaponinfo.netname, d, t);
1798 // 4: is set by default?
1807 /// Weapons the player normally starts with outside weapon arena.
1808 WepSet weapons_start()
1810 WepSet ret = '0 0 0';
1811 FOREACH(Weapons, it != WEP_Null, {
1812 int w = want_weapon(it, false);
1819 WepSet weapons_all()
1821 WepSet ret = '0 0 0';
1822 FOREACH(Weapons, it != WEP_Null, {
1823 if (!(it.spawnflags & (WEP_FLAG_MUTATORBLOCKED | WEP_FLAG_SPECIALATTACK)))
1829 WepSet weapons_devall()
1831 WepSet ret = '0 0 0';
1832 FOREACH(Weapons, it != WEP_Null,
1839 WepSet weapons_most()
1841 WepSet ret = '0 0 0';
1842 FOREACH(Weapons, it != WEP_Null, {
1843 if ((it.spawnflags & WEP_FLAG_NORMAL) && !(it.spawnflags & (WEP_FLAG_MUTATORBLOCKED | WEP_FLAG_HIDDEN | WEP_FLAG_SPECIALATTACK)))
1849 void weaponarena_available_all_update(entity this)
1851 if (weaponsInMapAll)
1853 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | (weaponsInMapAll & weapons_all());
1857 // if no weapons are available on the map, just fall back to all weapons arena
1858 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_all();
1862 void weaponarena_available_devall_update(entity this)
1864 if (weaponsInMapAll)
1866 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | weaponsInMapAll;
1870 // if no weapons are available on the map, just fall back to devall weapons arena
1871 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_devall();
1875 void weaponarena_available_most_update(entity this)
1877 if (weaponsInMapAll)
1879 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | (weaponsInMapAll & weapons_most());
1883 // if no weapons are available on the map, just fall back to most weapons arena
1884 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_most();
1888 void readplayerstartcvars()
1890 // initialize starting values for players
1891 start_weapons = '0 0 0';
1892 start_weapons_default = '0 0 0';
1893 start_weapons_defaultmask = '0 0 0';
1895 start_ammo_shells = 0;
1896 start_ammo_nails = 0;
1897 start_ammo_rockets = 0;
1898 start_ammo_cells = 0;
1899 start_ammo_plasma = 0;
1900 if (random_start_ammo == NULL)
1902 random_start_ammo = new_pure(random_start_ammo);
1904 start_health = cvar("g_balance_health_start");
1905 start_armorvalue = cvar("g_balance_armor_start");
1908 g_weaponarena_weapons = '0 0 0';
1910 string s = cvar_string("g_weaponarena");
1912 MUTATOR_CALLHOOK(SetWeaponArena, s);
1913 s = M_ARGV(0, string);
1915 if (s == "0" || s == "")
1919 else if (s == "off")
1921 // forcibly turn off weaponarena
1923 else if (s == "all" || s == "1")
1926 g_weaponarena_list = "All Weapons Arena";
1927 g_weaponarena_weapons = weapons_all();
1929 else if (s == "devall")
1932 g_weaponarena_list = "Dev All Weapons Arena";
1933 g_weaponarena_weapons = weapons_devall();
1935 else if (s == "most")
1938 g_weaponarena_list = "Most Weapons Arena";
1939 g_weaponarena_weapons = weapons_most();
1941 else if (s == "all_available")
1944 g_weaponarena_list = "All Available Weapons Arena";
1946 // this needs to run after weaponsInMapAll is initialized
1947 InitializeEntity(NULL, weaponarena_available_all_update, INITPRIO_FINDTARGET);
1949 else if (s == "devall_available")
1952 g_weaponarena_list = "Dev All Available Weapons Arena";
1954 // this needs to run after weaponsInMapAll is initialized
1955 InitializeEntity(NULL, weaponarena_available_devall_update, INITPRIO_FINDTARGET);
1957 else if (s == "most_available")
1960 g_weaponarena_list = "Most Available Weapons Arena";
1962 // this needs to run after weaponsInMapAll is initialized
1963 InitializeEntity(NULL, weaponarena_available_most_update, INITPRIO_FINDTARGET);
1965 else if (s == "none")
1968 g_weaponarena_list = "No Weapons Arena";
1973 float t = tokenize_console(s);
1974 g_weaponarena_list = "";
1975 for (int j = 0; j < t; ++j)
1978 Weapon wep = Weapon_from_name(s);
1981 g_weaponarena_weapons |= (wep.m_wepset);
1982 g_weaponarena_list = strcat(g_weaponarena_list, wep.netname, " & ");
1985 if (g_weaponarena_list != "") // remove trailing " & "
1986 g_weaponarena_list = substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3);
1987 else // no valid weapon found
1988 g_weaponarena_list = "No Weapons Arena";
1993 g_weapon_stay = 0; // incompatible
1994 start_weapons = g_weaponarena_weapons;
1995 start_items |= IT_UNLIMITED_AMMO | IT_UNLIMITED_SUPERWEAPONS;
1996 g_weaponarena_list = strzone(g_weaponarena_list);
2000 FOREACH(Weapons, it != WEP_Null, {
2001 int w = want_weapon(it, false);
2002 WepSet s = it.m_wepset;
2006 start_weapons_default |= s;
2008 start_weapons_defaultmask |= s;
2012 if(cvar("g_balance_superweapons_time") < 0)
2013 start_items |= IT_UNLIMITED_SUPERWEAPONS;
2015 if(!cvar("g_use_ammunition"))
2016 start_items |= IT_UNLIMITED_AMMO;
2018 if(start_items & IT_UNLIMITED_AMMO)
2020 start_ammo_shells = 999;
2021 start_ammo_nails = 999;
2022 start_ammo_rockets = 999;
2023 start_ammo_cells = 999;
2024 start_ammo_plasma = 999;
2025 start_ammo_fuel = 999;
2029 start_ammo_shells = cvar("g_start_ammo_shells");
2030 start_ammo_nails = cvar("g_start_ammo_nails");
2031 start_ammo_rockets = cvar("g_start_ammo_rockets");
2032 start_ammo_cells = cvar("g_start_ammo_cells");
2033 start_ammo_plasma = cvar("g_start_ammo_plasma");
2034 start_ammo_fuel = cvar("g_start_ammo_fuel");
2035 random_start_weapons_count = cvar("g_random_start_weapons_count");
2036 SetResource(random_start_ammo, RES_SHELLS, cvar("g_random_start_shells"));
2037 SetResource(random_start_ammo, RES_BULLETS, cvar("g_random_start_bullets"));
2038 SetResource(random_start_ammo, RES_ROCKETS, cvar("g_random_start_rockets"));
2039 SetResource(random_start_ammo, RES_CELLS, cvar("g_random_start_cells"));
2040 SetResource(random_start_ammo, RES_PLASMA, cvar("g_random_start_plasma"));
2043 warmup_start_ammo_shells = start_ammo_shells;
2044 warmup_start_ammo_nails = start_ammo_nails;
2045 warmup_start_ammo_rockets = start_ammo_rockets;
2046 warmup_start_ammo_cells = start_ammo_cells;
2047 warmup_start_ammo_plasma = start_ammo_plasma;
2048 warmup_start_ammo_fuel = start_ammo_fuel;
2049 warmup_start_health = start_health;
2050 warmup_start_armorvalue = start_armorvalue;
2051 warmup_start_weapons = start_weapons;
2052 warmup_start_weapons_default = start_weapons_default;
2053 warmup_start_weapons_defaultmask = start_weapons_defaultmask;
2057 warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
2058 warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
2059 warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
2060 warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
2061 warmup_start_ammo_plasma = cvar("g_warmup_start_ammo_plasma");
2062 warmup_start_ammo_fuel = cvar("g_warmup_start_ammo_fuel");
2063 warmup_start_health = cvar("g_warmup_start_health");
2064 warmup_start_armorvalue = cvar("g_warmup_start_armor");
2065 warmup_start_weapons = '0 0 0';
2066 warmup_start_weapons_default = '0 0 0';
2067 warmup_start_weapons_defaultmask = '0 0 0';
2068 FOREACH(Weapons, it != WEP_Null, {
2069 int w = want_weapon(it, autocvar_g_warmup_allguns);
2070 WepSet s = it.m_wepset;
2072 warmup_start_weapons |= s;
2074 warmup_start_weapons_default |= s;
2076 warmup_start_weapons_defaultmask |= s;
2080 if (autocvar_g_jetpack)
2081 start_items |= ITEM_Jetpack.m_itemid;
2083 MUTATOR_CALLHOOK(SetStartItems);
2085 if (start_items & ITEM_Jetpack.m_itemid)
2087 start_items |= ITEM_JetpackRegen.m_itemid;
2088 start_ammo_fuel = max(start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
2089 warmup_start_ammo_fuel = max(warmup_start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
2092 start_ammo_shells = max(0, start_ammo_shells);
2093 start_ammo_nails = max(0, start_ammo_nails);
2094 start_ammo_rockets = max(0, start_ammo_rockets);
2095 start_ammo_cells = max(0, start_ammo_cells);
2096 start_ammo_plasma = max(0, start_ammo_plasma);
2097 start_ammo_fuel = max(0, start_ammo_fuel);
2098 SetResource(random_start_ammo, RES_SHELLS, max(0, GetResource(random_start_ammo, RES_SHELLS)));
2099 SetResource(random_start_ammo, RES_BULLETS, max(0, GetResource(random_start_ammo, RES_BULLETS)));
2100 SetResource(random_start_ammo, RES_ROCKETS, max(0, GetResource(random_start_ammo, RES_ROCKETS)));
2101 SetResource(random_start_ammo, RES_CELLS, max(0, GetResource(random_start_ammo, RES_CELLS)));
2102 SetResource(random_start_ammo, RES_PLASMA, max(0, GetResource(random_start_ammo, RES_PLASMA)));
2104 warmup_start_ammo_shells = max(0, warmup_start_ammo_shells);
2105 warmup_start_ammo_nails = max(0, warmup_start_ammo_nails);
2106 warmup_start_ammo_rockets = max(0, warmup_start_ammo_rockets);
2107 warmup_start_ammo_cells = max(0, warmup_start_ammo_cells);
2108 warmup_start_ammo_plasma = max(0, warmup_start_ammo_plasma);
2109 warmup_start_ammo_fuel = max(0, warmup_start_ammo_fuel);
2112 void readlevelcvars()
2114 serverflags &= ~SERVERFLAG_ALLOW_FULLBRIGHT;
2115 if(cvar("sv_allow_fullbright"))
2116 serverflags |= SERVERFLAG_ALLOW_FULLBRIGHT;
2118 serverflags &= ~SERVERFLAG_FORBID_PICKUPTIMER;
2119 if(cvar("sv_forbid_pickuptimer"))
2120 serverflags |= SERVERFLAG_FORBID_PICKUPTIMER;
2122 sv_ready_restart_after_countdown = cvar("sv_ready_restart_after_countdown");
2124 if(cvar("g_campaign"))
2125 warmup_stage = 0; // no warmup during campaign
2128 warmup_stage = autocvar_g_warmup;
2129 if (warmup_stage < 0 || warmup_stage > 1)
2130 warmup_limit = -1; // don't start until there's enough players
2131 else if (warmup_stage == 1)
2133 // this code is duplicated in ReadyCount()
2134 warmup_limit = cvar("g_warmup_limit");
2135 if(warmup_limit == 0)
2136 warmup_limit = autocvar_timelimit * 60;
2140 g_pickup_respawntime_weapon = cvar("g_pickup_respawntime_weapon");
2141 g_pickup_respawntime_superweapon = cvar("g_pickup_respawntime_superweapon");
2142 g_pickup_respawntime_ammo = cvar("g_pickup_respawntime_ammo");
2143 g_pickup_respawntime_short = cvar("g_pickup_respawntime_short");
2144 g_pickup_respawntime_medium = cvar("g_pickup_respawntime_medium");
2145 g_pickup_respawntime_long = cvar("g_pickup_respawntime_long");
2146 g_pickup_respawntime_powerup = cvar("g_pickup_respawntime_powerup");
2147 g_pickup_respawntimejitter_weapon = cvar("g_pickup_respawntimejitter_weapon");
2148 g_pickup_respawntimejitter_superweapon = cvar("g_pickup_respawntimejitter_superweapon");
2149 g_pickup_respawntimejitter_ammo = cvar("g_pickup_respawntimejitter_ammo");
2150 g_pickup_respawntimejitter_short = cvar("g_pickup_respawntimejitter_short");
2151 g_pickup_respawntimejitter_medium = cvar("g_pickup_respawntimejitter_medium");
2152 g_pickup_respawntimejitter_long = cvar("g_pickup_respawntimejitter_long");
2153 g_pickup_respawntimejitter_powerup = cvar("g_pickup_respawntimejitter_powerup");
2155 g_pickup_shells = cvar("g_pickup_shells");
2156 g_pickup_shells_max = cvar("g_pickup_shells_max");
2157 g_pickup_nails = cvar("g_pickup_nails");
2158 g_pickup_nails_max = cvar("g_pickup_nails_max");
2159 g_pickup_rockets = cvar("g_pickup_rockets");
2160 g_pickup_rockets_max = cvar("g_pickup_rockets_max");
2161 g_pickup_cells = cvar("g_pickup_cells");
2162 g_pickup_cells_max = cvar("g_pickup_cells_max");
2163 g_pickup_plasma = cvar("g_pickup_plasma");
2164 g_pickup_plasma_max = cvar("g_pickup_plasma_max");
2165 g_pickup_fuel = cvar("g_pickup_fuel");
2166 g_pickup_fuel_jetpack = cvar("g_pickup_fuel_jetpack");
2167 g_pickup_fuel_max = cvar("g_pickup_fuel_max");
2168 g_pickup_armorsmall = cvar("g_pickup_armorsmall");
2169 g_pickup_armorsmall_max = cvar("g_pickup_armorsmall_max");
2170 g_pickup_armorsmall_anyway = cvar("g_pickup_armorsmall_anyway");
2171 g_pickup_armormedium = cvar("g_pickup_armormedium");
2172 g_pickup_armormedium_max = cvar("g_pickup_armormedium_max");
2173 g_pickup_armormedium_anyway = cvar("g_pickup_armormedium_anyway");
2174 g_pickup_armorbig = cvar("g_pickup_armorbig");
2175 g_pickup_armorbig_max = cvar("g_pickup_armorbig_max");
2176 g_pickup_armorbig_anyway = cvar("g_pickup_armorbig_anyway");
2177 g_pickup_armormega = cvar("g_pickup_armormega");
2178 g_pickup_armormega_max = cvar("g_pickup_armormega_max");
2179 g_pickup_armormega_anyway = cvar("g_pickup_armormega_anyway");
2180 g_pickup_healthsmall = cvar("g_pickup_healthsmall");
2181 g_pickup_healthsmall_max = cvar("g_pickup_healthsmall_max");
2182 g_pickup_healthsmall_anyway = cvar("g_pickup_healthsmall_anyway");
2183 g_pickup_healthmedium = cvar("g_pickup_healthmedium");
2184 g_pickup_healthmedium_max = cvar("g_pickup_healthmedium_max");
2185 g_pickup_healthmedium_anyway = cvar("g_pickup_healthmedium_anyway");
2186 g_pickup_healthbig = cvar("g_pickup_healthbig");
2187 g_pickup_healthbig_max = cvar("g_pickup_healthbig_max");
2188 g_pickup_healthbig_anyway = cvar("g_pickup_healthbig_anyway");
2189 g_pickup_healthmega = cvar("g_pickup_healthmega");
2190 g_pickup_healthmega_max = cvar("g_pickup_healthmega_max");
2191 g_pickup_healthmega_anyway = cvar("g_pickup_healthmega_anyway");
2193 g_pickup_ammo_anyway = cvar("g_pickup_ammo_anyway");
2194 g_pickup_weapons_anyway = cvar("g_pickup_weapons_anyway");
2196 g_weapon_stay = cvar(strcat("g_", GetGametype(), "_weapon_stay"));
2198 g_weapon_stay = cvar("g_weapon_stay");
2200 MUTATOR_CALLHOOK(ReadLevelCvars);
2202 if (!warmup_stage && !autocvar_g_campaign)
2203 game_starttime = time + cvar("g_start_delay");
2205 FOREACH(Weapons, it != WEP_Null, { it.wr_init(it); });
2207 readplayerstartcvars();
2210 void InitializeEntity(entity e, void(entity this) func, int order)
2214 if (!e || e.initialize_entity)
2216 // make a proxy initializer entity
2218 e = new(initialize_entity);
2222 e.initialize_entity = func;
2223 e.initialize_entity_order = order;
2225 cur = initialize_entity_first;
2229 if (!cur || cur.initialize_entity_order > order)
2231 // insert between prev and cur
2233 prev.initialize_entity_next = e;
2235 initialize_entity_first = e;
2236 e.initialize_entity_next = cur;
2240 cur = cur.initialize_entity_next;
2243 void InitializeEntitiesRun()
2245 entity startoflist = initialize_entity_first;
2246 initialize_entity_first = NULL;
2247 delete_fn = remove_except_protected;
2248 for (entity e = startoflist; e; e = e.initialize_entity_next)
2250 e.remove_except_protected_forbidden = 1;
2252 for (entity e = startoflist; e; )
2254 e.remove_except_protected_forbidden = 0;
2255 e.initialize_entity_order = 0;
2256 entity next = e.initialize_entity_next;
2257 e.initialize_entity_next = NULL;
2258 var void(entity this) func = e.initialize_entity;
2259 e.initialize_entity = func_null;
2260 if (e.classname == "initialize_entity")
2262 entity wrappee = e.enemy;
2266 //dprint("Delayed initialization: ", e.classname, "\n");
2274 backtrace(strcat("Null function in: ", e.classname, "\n"));
2278 delete_fn = remove_unsafely;
2281 // deferred dropping
2282 // ported from VM_SV_droptofloor TODO: make a common function for the client-side?
2283 void DropToFloor_Handler(entity this)
2285 if(!this || wasfreed(this))
2287 // no modifying free entities
2291 vector end = this.origin;
2292 if (autocvar_sv_mapformat_is_quake3)
2294 else if (autocvar_sv_mapformat_is_quake2)
2297 end.z -= 256; // Quake, QuakeWorld
2299 // NOTE: SV_NudgeOutOfSolid is used in the engine here
2300 if(autocvar_sv_gameplayfix_droptofloorstartsolid_nudgetocorrect)
2302 _Movetype_UnstickEntity(this);
2303 move_out_of_solid(this);
2306 tracebox(this.origin, this.mins, this.maxs, end, MOVE_NORMAL, this);
2308 if(trace_startsolid && autocvar_sv_gameplayfix_droptofloorstartsolid)
2311 offset = 0.5 * (this.mins + this.maxs);
2312 offset.z = this.mins.z;
2313 org = this.origin + offset;
2314 traceline(org, end, MOVE_NORMAL, this);
2315 trace_endpos = trace_endpos - offset;
2316 if(trace_startsolid)
2318 LOG_DEBUGF("DropToFloor_Handler: %v could not fix badly placed entity", this.origin);
2319 _Movetype_LinkEdict(this, false);
2321 this.groundentity = NULL;
2323 else if(trace_fraction < 1)
2325 LOG_DEBUGF("DropToFloor_Handler: %v fixed badly placed entity", this.origin);
2326 setorigin(this, trace_endpos);
2327 if(autocvar_sv_gameplayfix_droptofloorstartsolid_nudgetocorrect)
2329 _Movetype_UnstickEntity(this);
2330 move_out_of_solid(this);
2333 this.groundentity = trace_ent;
2334 // if support is destroyed, keep suspended (gross hack for floating items in various maps)
2335 this.move_suspendedinair = true;
2340 if(!trace_allsolid && trace_fraction < 1)
2342 setorigin(this, trace_endpos);
2344 this.groundentity = trace_ent;
2345 // if support is destroyed, keep suspended (gross hack for floating items in various maps)
2346 this.move_suspendedinair = true;
2350 // if we can't get the entity out of solid, mark it as on ground so physics doesn't attempt to drop it
2351 // hacky workaround for #2774
2355 this.dropped_origin = this.origin;
2358 void droptofloor(entity this)
2360 InitializeEntity(this, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
2363 bool autocvar_sv_gameplayfix_multiplethinksperframe = true;
2364 void RunThink(entity this, float dt)
2366 // don't let things stay in the past.
2367 // it is possible to start that way by a trigger with a local time.
2368 if(this.nextthink <= 0 || this.nextthink > time + dt)
2371 float oldtime = time; // do we need to save this?
2373 for (int iterations = 0; iterations < 128 && !wasfreed(this); iterations++)
2375 time = max(oldtime, this.nextthink);
2379 getthink(this)(this);
2380 // mods often set nextthink to time to cause a think every frame,
2381 // we don't want to loop in that case, so exit if the new nextthink is
2382 // <= the time the qc was told, also exit if it is past the end of the
2384 if(this.nextthink <= time || this.nextthink > oldtime + dt || !autocvar_sv_gameplayfix_multiplethinksperframe)
2391 bool autocvar_sv_freezenonclients;
2392 void Physics_Frame()
2394 if(autocvar_sv_freezenonclients)
2397 IL_EACH(g_moveables, true,
2399 if(IS_CLIENT(it) || it.move_movetype == MOVETYPE_PHYSICS)
2402 //set_movetype(it, it.move_movetype);
2403 // inline the set_movetype function, since this is called a lot
2404 it.movetype = (it.move_qcphysics) ? MOVETYPE_QCENTITY : it.move_movetype;
2406 if(it.move_qcphysics && it.move_movetype != MOVETYPE_NONE)
2407 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2409 if(it.movetype >= MOVETYPE_USER_FIRST && it.movetype <= MOVETYPE_USER_LAST) // these cases have no think handling
2411 if(it.move_movetype == MOVETYPE_PUSH || it.move_movetype == MOVETYPE_FAKEPUSH)
2412 continue; // these movetypes have no regular think function
2413 // handle thinking here
2414 if (getthink(it) && it.nextthink > 0 && it.nextthink <= time + PHYS_INPUT_TIMELENGTH)
2415 RunThink(it, PHYS_INPUT_TIMELENGTH);
2419 if(autocvar_sv_gameplayfix_delayprojectiles >= 0)
2422 // make a second pass to see if any ents spawned this frame and make
2423 // sure they run their move/think. this is verified by checking .move_time, which will never be 0 if the entity has moved
2424 // MOVETYPE_NONE is also checked as .move_time WILL be 0 with that movetype
2425 IL_EACH(g_moveables, it.move_qcphysics,
2427 if(IS_CLIENT(it) || it.move_time || it.move_movetype == MOVETYPE_NONE || it.move_movetype == MOVETYPE_PHYSICS)
2429 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2433 void systems_update();
2436 anticheat_endframe();
2440 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2441 entity e = IS_SPEC(it) ? it.enemy : it;
2442 if (e.typehitsound) {
2443 STAT(TYPEHIT_TIME, it) = time;
2444 } else if (e.killsound) {
2445 STAT(KILL_TIME, it) = time;
2446 } else if (e.hitsound_damage_dealt) {
2447 STAT(HIT_TIME, it) = time;
2448 // NOTE: this is not accurate as client code doesn't need so much accuracy for its purposes
2449 STAT(HITSOUND_DAMAGE_DEALT_TOTAL, it) += ceil(e.hitsound_damage_dealt);
2452 // add 1 frametime because after this, engine SV_Physics
2453 // increases time by a frametime and then networks the frame
2454 // add another frametime because client shows everything with
2455 // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2457 float altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2458 FOREACH_CLIENT(true, {
2459 it.typehitsound = false;
2460 it.hitsound_damage_dealt = 0;
2461 it.killsound = false;
2462 antilag_record(it, CS(it), altime);
2464 IL_EACH(g_monsters, true,
2466 antilag_record(it, it, altime);
2468 IL_EACH(g_projectiles, it.classname == "nade",
2470 antilag_record(it, it, altime);
2479 * returns true if redirecting
2481 float redirection_timeout;
2482 float redirection_nextthink;
2483 float RedirectionThink()
2485 float clients_found;
2487 if(redirection_target == "")
2490 if(!redirection_timeout)
2492 cvar_set("sv_public", "-2");
2493 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2494 if(redirection_target == "self")
2495 bprint("^3SERVER NOTICE:^7 restarting the server\n");
2497 bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2500 if(time < redirection_nextthink)
2503 redirection_nextthink = time + 1;
2506 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2508 LOG_INFO("Redirecting: sending connect command to ", it.netname);
2509 if(redirection_target == "self")
2510 stuffcmd(it, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2512 stuffcmd(it, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2516 LOG_INFO("Redirecting: ", ftos(clients_found), " clients left.");
2518 if(time > redirection_timeout || clients_found == 0)
2519 localcmd("\nwait; wait; wait; quit\n");
2526 // Loaded from a save game
2527 // some things then break, so let's work around them...
2529 // Progs DB (capture records)
2530 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2534 MapInfo_Enumerate();
2535 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2538 TargetMusic_RestoreGame();
2545 if(world_initialized > 0)
2547 world_initialized = 0;
2549 // if a timeout is active, reset the slowmo value to normal
2550 if(timeout_status == TIMEOUT_ACTIVE)
2551 cvar_set("slowmo", ftos(orig_slowmo));
2553 LOG_TRACE("Saving persistent data...");
2556 // playerstats with unfinished match
2557 PlayerStats_GameReport(false);
2559 if(!cheatcount_total)
2561 if(autocvar_sv_db_saveasdump)
2562 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2564 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2566 if(autocvar_developer > 0)
2568 if(autocvar_sv_db_saveasdump)
2569 db_dump(TemporaryDB, "server-temp.db");
2571 db_save(TemporaryDB, "server-temp.db");
2573 CheatShutdown(); // must be after cheatcount check
2574 db_close(ServerProgsDB);
2575 db_close(TemporaryDB);
2576 LOG_TRACE("Saving persistent data... done!");
2577 // tell the bot system the game is ending now
2580 WeaponStats_Shutdown();
2583 strfree(sv_termsofservice_url_escaped);
2585 else if(world_initialized == 0)
2587 LOG_INFO("NOTE: crashed before even initializing the world, not saving persistent data");
2591 __init_dedicated_server_shutdown();