3 #include <common/constants.qh>
4 #include <common/deathtypes/all.qh>
5 #include <common/gamemodes/_mod.qh>
6 #include <common/gamemodes/sv_rules.qh>
7 #include <common/items/_mod.qh>
8 #include <common/mapinfo.qh>
9 #include <common/mapobjects/target/music.qh>
10 #include <common/mapobjects/trigger/hurt.qh>
11 #include <common/mapobjects/trigger/secret.qh>
12 #include <common/mapobjects/triggers.qh>
13 #include <common/monsters/_mod.qh>
14 #include <common/monsters/sv_monsters.qh>
15 #include <common/net_linked.qh>
16 #include <common/notifications/all.qh>
17 #include <common/physics/player.qh>
18 #include <common/playerstats.qh>
19 #include <common/state.qh>
20 #include <common/stats.qh>
21 #include <common/teams.qh>
22 #include <common/util.qh>
23 #include <common/vehicles/all.qh>
24 #include <common/weapons/_all.qh>
25 #include <server/anticheat.qh>
26 #include <server/antilag.qh>
27 #include <server/bot/api.qh>
28 #include <server/campaign.qh>
29 #include <server/cheats.qh>
30 #include <server/client.qh>
31 #include <server/command/common.qh>
32 #include <server/command/getreplies.qh>
33 #include <server/command/sv_cmd.qh>
34 #include <server/command/vote.qh>
35 #include <server/damage.qh>
36 #include <server/gamelog.qh>
37 #include <server/hook.qh>
38 #include <server/intermission.qh>
39 #include <server/ipban.qh>
40 #include <server/items/items.qh>
41 #include <server/main.qh>
42 #include <server/mapvoting.qh>
43 #include <server/mutators/_mod.qh>
44 #include <server/race.qh>
45 #include <server/scores.qh>
46 #include <server/scores_rules.qh>
47 #include <server/spawnpoints.qh>
48 #include <server/teamplay.qh>
49 #include <server/weapons/common.qh>
50 #include <server/weapons/weaponstats.qh>
52 const float LATENCY_THINKRATE = 10;
57 void PingPLReport_Think(entity this)
62 delta = 3 / maxclients;
63 if(delta < sys_frametime)
65 this.nextthink = time + delta;
67 e = edict_num(this.cnt + 1);
68 if(IS_CLIENT(e) && IS_REAL_CLIENT(e))
70 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
71 WriteByte(MSG_BROADCAST, this.cnt);
72 WriteShort(MSG_BROADCAST, bound(1, CS(e).ping, 65535));
73 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_packetloss * 255), 255));
74 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_movementloss * 255), 255));
76 // record latency times for clients throughout the match so we can report it to playerstats
77 if(time > (CS(e).latency_time + LATENCY_THINKRATE))
79 CS(e).latency_sum += CS(e).ping;
80 CS(e).latency_cnt += 1;
81 CS(e).latency_time = time;
82 //print("sum: ", ftos(CS(e).latency_sum), ", cnt: ", ftos(CS(e).latency_cnt), ", avg: ", ftos(CS(e).latency_sum / CS(e).latency_cnt), ".\n");
87 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
88 WriteByte(MSG_BROADCAST, this.cnt);
89 WriteShort(MSG_BROADCAST, 0);
90 WriteByte(MSG_BROADCAST, 0);
91 WriteByte(MSG_BROADCAST, 0);
93 this.cnt = (this.cnt + 1) % maxclients;
95 void PingPLReport_Spawn()
97 pingplreport = new_pure(pingplreport);
98 setthink(pingplreport, PingPLReport_Think);
99 pingplreport.nextthink = time;
102 const float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
103 float world_initialized;
105 void SetDefaultAlpha()
107 if (!MUTATOR_CALLHOOK(SetDefaultAlpha))
109 default_player_alpha = autocvar_g_player_alpha;
110 if(default_player_alpha == 0)
111 default_player_alpha = 1;
112 default_weapon_alpha = default_player_alpha;
116 void GotoFirstMap(entity this)
119 if(autocvar__sv_init)
121 // cvar_set("_sv_init", "0");
122 // we do NOT set this to 0 any more, so someone "accidentally" changing
123 // to this "init" map on a dedicated server will cause no permanent
125 if(autocvar_g_maplist_shuffle)
127 n = tokenizebyseparator(autocvar_g_maplist, " ");
128 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
131 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
133 if(!DoNextMapOverride(1))
141 this.nextthink = time;
145 this.nextthink = time + 1;
146 LOG_INFO("Waiting for _sv_init being set to 1 by initialization scripts...");
150 void cvar_changes_init()
154 float n, i, adding, pureadding;
156 strfree(cvar_changes);
157 strfree(cvar_purechanges);
158 cvar_purechanges_count = 0;
161 buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
167 for(i = 0; i < n; ++i)
169 k = bufstr_get(h, i);
171 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
172 #define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
173 #define BADCVAR(p) if(k == p) 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_teams");
283 BADCVAR("g_invasion_type");
284 BADCVAR("g_jailbreak");
285 BADCVAR("g_jailbreak_teams");
286 BADCVAR("g_keepaway");
287 BADCVAR("g_keyhunt");
288 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");
305 BADCVAR("leadlimit");
308 BADCVAR("timelimit");
309 BADCVAR("g_mapinfo_settemp_acl");
310 BADCVAR("g_mapinfo_ignore_warnings");
311 BADCVAR("g_maplist_ignore_sizes");
312 BADCVAR("g_maplist_sizes_count_bots");
316 BADCVAR("hostname_full");
317 BADCVAR("g_maplist");
318 BADCVAR("g_maplist_mostrecent");
321 BADPREFIX("g_teamnames_");
324 d = cvar_defstring(k);
330 cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
331 if(strlen(cvar_changes) > 16384)
333 cvar_changes = "// too many settings have been changed to show them here\n";
338 // now check if the changes are actually gameplay relevant
340 // does nothing gameplay relevant
341 BADCVAR("captureleadlimit_override");
342 BADCVAR("condump_stripcolors");
343 BADCVAR("gameversion");
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_ctf_captimerecord_always");
355 BADCVAR("g_ctf_flag_glowtrails");
356 BADCVAR("g_ctf_dynamiclights");
357 BADCVAR("g_ctf_flag_pickup_verbosename");
358 BADPRESUFFIX("g_ctf_flag_", "_model");
359 BADPRESUFFIX("g_ctf_flag_", "_skin");
360 BADCVAR("g_domination_point_leadlimit");
361 BADCVAR("g_forced_respawn");
362 BADCVAR("g_freezetag_point_leadlimit");
363 BADCVAR("g_freezetag_point_limit");
364 BADCVAR("g_freezetag_revive_respawn");
365 BADCVAR("g_freezetag_round_stop");
366 BADCVAR("g_freezetag_round_respawn");
367 BADCVAR("g_glowtrails");
369 BADCVAR("g_casings");
370 BADCVAR("g_invasion_point_limit");
371 BADCVAR("g_jump_grunt");
372 BADCVAR("g_keepaway_ballcarrier_effects");
373 BADCVAR("g_keepawayball_effects");
374 BADCVAR("g_keyhunt_point_leadlimit");
375 BADCVAR("g_nexball_goalleadlimit");
376 BADCVAR("g_new_toys_autoreplace");
377 BADCVAR("g_new_toys_use_pickupsound");
378 BADCVAR("g_physics_predictall");
379 BADCVAR("g_piggyback");
380 BADCVAR("g_playerclip_collisions");
381 BADCVAR("g_spawn_alloweffects");
382 BADCVAR("g_tdm_point_leadlimit");
383 BADCVAR("g_tdm_point_limit");
384 BADCVAR("leadlimit_and_fraglimit");
385 BADCVAR("leadlimit_override");
387 BADCVAR("sv_announcer");
388 BADCVAR("sv_checkforpacketsduringsleep");
389 BADCVAR("sv_damagetext");
390 BADCVAR("sv_db_saveasdump");
391 BADCVAR("sv_intermission_cdtrack");
392 BADCVAR("sv_mapchange_delay");
393 BADCVAR("sv_minigames");
394 BADCVAR("sv_namechangetimer");
395 BADCVAR("sv_precacheplayermodels");
397 BADCVAR("sv_stepheight");
398 BADCVAR("sv_timeout");
399 BADCVAR("sv_weapons_modeloverride");
400 BADCVAR("w_prop_interval");
402 BADPREFIX("crypto_");
403 BADPREFIX("gameversion_");
404 BADPREFIX("g_chat_");
405 BADPREFIX("g_ctf_captimerecord_");
406 BADPREFIX("g_hats_");
407 BADPREFIX("g_maplist_");
409 BADPREFIX("g_respawn_");
411 BADPREFIX("notification_");
414 BADPREFIX("sv_allow_");
415 BADPREFIX("sv_cullentities_");
416 BADPREFIX("sv_maxidle_");
417 BADPREFIX("sv_minigames_");
418 BADPREFIX("sv_radio_");
419 BADPREFIX("sv_timeout_");
420 BADPREFIX("sv_vote_");
421 BADPREFIX("timelimit_");
422 BADPREFIX("sv_chat_");
423 BADPREFIX("sv_jingle_");
425 // allowed changes to server admins (please sync this to server.cfg)
429 // :%s,//\([^ ]*\).*,BADCVAR("\1");,
431 // yes, this does contain some redundant stuff, don't really care
432 BADPREFIX("bot_ai_");
433 BADCVAR("bot_config_file");
434 BADCVAR("bot_number");
435 BADCVAR("bot_prefix");
436 BADCVAR("bot_suffix");
437 BADCVAR("capturelimit_override");
438 BADCVAR("fraglimit_override");
440 BADCVAR("g_antilag");
441 BADCVAR("g_balance_teams");
442 BADCVAR("g_balance_teams_prevent_imbalance");
443 BADCVAR("g_balance_teams_scorefactor");
444 BADCVAR("g_ban_sync_trusted_servers");
445 BADCVAR("g_ban_sync_uri");
447 BADCVAR("g_ca_teams_override");
448 BADCVAR("g_ctf_fullbrightflags");
449 BADCVAR("g_ctf_ignore_frags");
450 BADCVAR("g_ctf_leaderboard");
451 BADCVAR("g_domination_point_limit");
452 BADCVAR("g_domination_teams_override");
453 BADCVAR("g_freezetag_teams_override");
454 BADCVAR("g_friendlyfire");
455 BADCVAR("g_fullbrightitems");
456 BADCVAR("g_fullbrightplayers");
457 BADCVAR("g_keyhunt_point_limit");
458 BADCVAR("g_keyhunt_teams_override");
459 BADCVAR("g_lms_lives_override");
460 BADCVAR("g_maplist");
461 BADCVAR("g_maxplayers");
462 BADCVAR("g_mirrordamage");
463 BADCVAR("g_nexball_goallimit");
464 BADCVAR("g_norecoil");
465 BADCVAR("g_physics_clientselect");
467 BADCVAR("g_powerups");
468 BADCVAR("g_player_brightness");
469 BADCVAR("g_rocket_flying");
470 BADCVAR("g_rocket_flying_disabledelays");
471 BADCVAR("g_spawnshieldtime");
472 BADCVAR("g_start_delay");
473 BADCVAR("g_superspectate");
474 BADCVAR("g_tdm_teams_override");
476 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
479 BADCVAR("maxplayers");
480 BADCVAR("minplayers");
481 BADCVAR("minplayers_per_team");
482 BADCVAR("net_address");
484 BADCVAR("rcon_password");
485 BADCVAR("rcon_restricted_commands");
486 BADCVAR("rcon_restricted_password");
488 BADCVAR("sv_adminnick");
489 BADCVAR("sv_autoscreenshot");
490 BADCVAR("sv_autotaunt");
491 BADCVAR("sv_curl_defaulturl");
492 BADCVAR("sv_defaultcharacter");
493 BADCVAR("sv_defaultcharacterskin");
494 BADCVAR("sv_defaultplayercolors");
495 BADCVAR("sv_defaultplayermodel");
496 BADCVAR("sv_defaultplayerskin");
497 BADCVAR("sv_maxidle");
498 BADCVAR("sv_maxrate");
500 BADCVAR("sv_public");
501 BADCVAR("sv_ready_restart");
502 BADCVAR("sv_status_privacy");
504 BADCVAR("sv_vote_call");
505 BADCVAR("sv_vote_commands");
506 BADCVAR("sv_vote_majority_factor");
507 BADCVAR("sv_vote_master");
508 BADCVAR("sv_vote_master_commands");
509 BADCVAR("sv_vote_master_password");
510 BADCVAR("sv_vote_simple_majority_factor");
511 BADCVAR("teamplay_mode");
512 BADCVAR("timelimit_override");
513 BADPREFIX("g_warmup_");
514 BADPREFIX("sv_info_");
515 BADPREFIX("sv_ready_restart_");
517 // mutators that announce themselves properly to the server browser
518 BADCVAR("g_instagib");
519 BADCVAR("g_new_toys");
521 BADCVAR("g_grappling_hook");
522 BADCVAR("g_jetpack");
524 // temporary for testing
525 // TODO remove before 0.8.3 release
526 BADCVAR("g_ca_weaponarena");
527 BADCVAR("g_freezetag_weaponarena");
528 BADCVAR("g_lms_weaponarena");
529 BADCVAR("g_ctf_stalemate_time");
531 if(cvar_string("g_mod_balance") == "Testing")
533 // (temporary) while using the Testing balance, any weapon balance cvars are allowed to be changed
534 BADPREFIX("g_balance_");
543 cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
544 if(strlen(cvar_purechanges) > 16384)
546 cvar_purechanges = "// too many settings have been changed to show them here\n";
550 ++cvar_purechanges_count;
551 // WARNING: this variable is used for the server list
552 // NEVER dare to skip this code!
553 // Hacks to intentionally appearing as "pure server" even though you DO have
554 // modified settings may be punished by removal from the server list.
555 // You can do to the variables cvar_changes and cvar_purechanges all you want,
559 if(cvar_changes == "")
560 cvar_changes = "// this server runs at default server settings\n";
562 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
563 cvar_changes = strzone(cvar_changes);
564 if(cvar_purechanges == "")
565 cvar_purechanges = "// this server runs at default gameplay settings\n";
567 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
568 cvar_purechanges = strzone(cvar_purechanges);
572 bool RandomSeed_Send(entity this, entity to, int sf)
574 WriteHeader(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
575 WriteShort(MSG_ENTITY, this.cnt);
578 void RandomSeed_Think(entity this)
580 this.cnt = bound(0, floor(random() * 65536), 65535);
581 this.nextthink = time + 5;
585 void RandomSeed_Spawn()
587 randomseed = new_pure(randomseed);
588 setthink(randomseed, RandomSeed_Think);
589 Net_LinkEntity(randomseed, false, 0, RandomSeed_Send);
591 getthink(randomseed)(randomseed); // sets random seed and nextthink
594 spawnfunc(__init_dedicated_server)
596 // handler for _init/_init map (only for dedicated server initialization)
598 world_initialized = -1; // don't complain
600 delete_fn = remove_unsafely;
602 entity e = new(GotoFirstMap);
603 setthink(e, GotoFirstMap);
604 e.nextthink = time; // this is usually 1 at this point
606 e = new(info_player_deathmatch); // safeguard against player joining
608 // assign reflectively to avoid "assignment to world" warning
609 for (int i = 0, n = numentityfields(); i < n; ++i) {
610 string k = entityfieldname(i);
611 if (k == "classname") {
612 // safeguard against various stuff ;)
613 putentityfieldstring(i, this, "worldspawn");
618 // needs to be done so early because of the constants they create
621 static_init_precache();
623 IL_PUSH(g_spawnpoints, e); // just incase
626 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
629 void __init_dedicated_server_shutdown() {
633 STATIC_INIT_EARLY(maxclients)
636 for (entity head = nextent(NULL); head; head = nextent(head)) {
641 void GameplayMode_DelayedInit(entity this)
643 if(!scores_initialized)
644 ScoreRules_generic();
647 void InitGameplayMode()
651 // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
653 // assign reflectively to avoid "assignment to world" warning
654 int done = 0; for (int i = 0, n = numentityfields(); i < n; ++i) {
655 string k = entityfieldname(i); vector v = (k == "mins") ? mi_min : (k == "maxs") ? mi_max : '0 0 0';
657 putentityfieldstring(i, world, sprintf("%v", v));
658 if (++done == 2) break;
661 // currently, NetRadiant's limit is 131072 qu for each side
662 // distance from one corner of a 131072qu cube to the opposite corner is approx. 227023 qu
663 // set the distance according to map size but don't go over the limit to avoid issues with float precision
664 // in case somebody makes extremely large maps
665 max_shot_distance = min(230000, vlen(world.maxs - world.mins));
667 MapInfo_LoadMapSettings(mapname);
668 GameRules_teams(false);
670 if (!cvar_value_issafe(world.fog))
672 LOG_INFO("The current map contains a potentially harmful fog setting, ignored");
673 world.fog = string_null;
675 if(MapInfo_Map_fog != "")
677 if(MapInfo_Map_fog == "none")
678 world.fog = string_null;
680 world.fog = strzone(MapInfo_Map_fog);
682 clientstuff = strzone(MapInfo_Map_clientstuff);
684 MapInfo_ClearTemps();
686 gamemode_name = MapInfo_Type_ToText(MapInfo_LoadedGametype);
688 cache_mutatormsg = strzone("");
689 cache_lastmutatormsg = strzone("");
691 InitializeEntity(NULL, GameplayMode_DelayedInit, INITPRIO_GAMETYPE_FALLBACK);
694 bool world_already_spawned;
695 spawnfunc(worldspawn)
697 server_is_dedicated = boolean(stof(cvar_defstring("is_dedicated")));
699 bool wantrestart = false;
701 if (!server_is_dedicated)
703 // force unloading of server pk3 files when starting a listen server
704 // localcmd("\nfs_rescan\n"); // FIXME: does more harm than good, has unintended side effects. What we really want is to unload temporary pk3s only
705 // restore csqc_progname too
706 string expect = "csprogs.dat";
707 wantrestart = cvar_string("csqc_progname") != expect;
708 cvar_set("csqc_progname", expect);
712 // Try to use versioned csprogs from pk3
713 // Only ever use versioned csprogs.dat files on dedicated servers;
714 // we need to reset csqc_progname on clients ourselves, and it's easier if the client's release name is constant
715 string pk3csprogs = "csprogs-" WATERMARK ".dat";
716 // This always works; fall back to it if a versioned csprogs.dat is suddenly missing
717 string select = "csprogs.dat";
718 if (fexists(pk3csprogs)) select = pk3csprogs;
719 if (cvar_string("csqc_progname") != select)
721 cvar_set("csqc_progname", select);
724 // Check for updates on startup
725 // We do it this way for atomicity so that connecting clients still match the server progs and don't disconnect
726 int sentinel = fopen("progs.txt", FILE_READ);
729 string switchversion = fgets(sentinel);
731 if (switchversion != "" && switchversion != WATERMARK)
733 LOG_INFOF("Switching progs: " WATERMARK " -> %s", switchversion);
734 // if it doesn't exist, assume either:
735 // a) the current program was overwritten
736 // b) this is a client only update
737 string newprogs = sprintf("progs-%s.dat", switchversion);
738 if (fexists(newprogs))
740 cvar_set("sv_progs", newprogs);
743 string newcsprogs = sprintf("csprogs-%s.dat", switchversion);
744 if (fexists(newcsprogs))
746 cvar_set("csqc_progname", newcsprogs);
754 LOG_INFO("Restart requested");
755 changelevel(mapname);
756 // let initialization continue, shutdown depends on it
760 if(world_already_spawned)
761 error("world already spawned - you may have EXACTLY ONE worldspawn!");
762 world_already_spawned = true;
764 delete_fn = remove_safely; // during spawning, watch what you remove!
766 cvar_changes_init(); // do this very early now so it REALLY matches the server config
768 // needs to be done so early because of the constants they create
771 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
773 TemporaryDB = db_create();
778 // 1 FLICKER (first variety)
779 lightstyle(1, "mmnmmommommnonmmonqnmmo");
781 // 2 SLOW STRONG PULSE
782 lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
784 // 3 CANDLE (first variety)
785 lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
788 lightstyle(4, "mamamamamama");
791 lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
793 // 6 FLICKER (second variety)
794 lightstyle(6, "nmonqnmomnmomomno");
796 // 7 CANDLE (second variety)
797 lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
799 // 8 CANDLE (third variety)
800 lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
802 // 9 SLOW STROBE (fourth variety)
803 lightstyle(9, "aaaaaaaazzzzzzzz");
805 // 10 FLUORESCENT FLICKER
806 lightstyle(10, "mmamammmmammamamaaamammma");
808 // 11 SLOW PULSE NOT FADE TO BLACK
809 lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
811 // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
816 if(autocvar_g_campaign)
819 Map_MarkAsRecent(mapname);
821 PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
825 static_init_precache();
828 GameRules_limit_fallbacks();
830 if(warmup_limit == 0)
831 warmup_limit = (autocvar_timelimit > 0) ? autocvar_timelimit * 60 : autocvar_timelimit;
834 bot_waypoints_for_items = autocvar_g_waypoints_for_items;
835 if(bot_waypoints_for_items == 1)
836 if(this.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
837 bot_waypoints_for_items = 0;
839 WaypointSprite_Init();
841 GameLogInit(); // prepare everything
843 // changing the logic generating it is okay. But:
844 // it HAS to stay <= 64 chars
845 // character set: ASCII 33-126 without the following characters: : ; ' " \ $
846 if(autocvar_sv_eventlog)
848 string s = sprintf("%s.%s.%06d", itos(autocvar_sv_eventlog_files_counter), strftime(false, "%s"), floor(random() * 1000000));
849 matchid = strzone(s);
851 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
852 s = ":gameinfo:mutators:LIST";
854 MUTATOR_CALLHOOK(BuildMutatorsString, s);
855 s = M_ARGV(0, string);
857 // initialiation stuff, not good in the mutator system
858 if(!autocvar_g_use_ammunition)
859 s = strcat(s, ":no_use_ammunition");
861 // initialiation stuff, not good in the mutator system
862 if(autocvar_g_pickup_items == 0)
863 s = strcat(s, ":no_pickup_items");
864 if(autocvar_g_pickup_items > 0)
865 s = strcat(s, ":pickup_items");
867 // initialiation stuff, not good in the mutator system
868 if(autocvar_g_weaponarena != "0")
869 s = strcat(s, ":", autocvar_g_weaponarena, " arena");
871 // TODO to mutator system
872 if(autocvar_g_norecoil)
873 s = strcat(s, ":norecoil");
875 // TODO to mutator system
876 if(autocvar_g_powerups == 0)
877 s = strcat(s, ":no_powerups");
878 if(autocvar_g_powerups > 0)
879 s = strcat(s, ":powerups");
882 GameLogEcho(":gameinfo:end");
885 matchid = strzone(ftos(random()));
887 cvar_set("nextmap", "");
891 if(autocvar_g_campaign)
897 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
899 if(fexists(strcat("scripts/", mapname, ".arena")))
900 cvar_settemp("sv_q3acompat_machineshotgunswap", "1");
902 if(fexists(strcat("scripts/", mapname, ".defi")))
903 cvar_settemp("sv_q3defragcompat", "1");
905 if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
907 int fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
911 while((s = fgets(fd)))
913 int l = tokenize_console(s);
918 string trackname = argv(2);
919 LOG_INFO("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:");
920 LOG_INFO(" cdtrack ", trackname);
921 if (cvar_value_issafe(trackname))
923 string newstuff = strcat(clientstuff, "cd loop \"", trackname, "\"\n");
924 strcpy(clientstuff, newstuff);
927 else if(argv(0) == "fog")
929 LOG_INFO("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:");
930 LOG_INFO(" \"fog\" \"", s, "\"");
932 else if(argv(0) == "set")
934 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
935 LOG_INFO(" clientsettemp_for_type all ", argv(1), " ", argv(2));
937 else if(argv(0) != "//")
939 LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
940 LOG_INFO(" clientsettemp_for_type all ", argv(0), " ", argv(1));
951 // set up information replies for clients and server to use
952 maplist_reply = strzone(getmaplist());
953 lsmaps_reply = strzone(getlsmaps());
954 monsterlist_reply = strzone(getmonsterlist());
955 for(int i = 0; i < 10; ++i)
957 string s = getrecords(i);
959 records_reply[i] = strzone(s);
961 ladder_reply = strzone(getladder());
962 rankings_reply = strzone(getrankings());
967 PingPLReport_Spawn();
971 if (!wantrestart) localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
973 // fill sv_curl_serverpackages from .serverpackage files
974 if (autocvar_sv_curl_serverpackages_auto)
976 string s = "csprogs-" WATERMARK ".dat";
977 // remove automatically managed files from the list to prevent duplicates
978 for (int i = 0, n = tokenize_console(cvar_string("sv_curl_serverpackages")); i < n; ++i)
980 string pkg = argv(i);
981 if (startsWith(pkg, "csprogs-")) continue;
982 if (endsWith(pkg, "-serverpackage.txt")) continue;
983 if (endsWith(pkg, ".serverpackage")) continue; // OLD legacy
986 // add automatically managed files to the list
987 #define X(match) MACRO_BEGIN \
988 int fd = search_begin(match, true, false); \
991 for (int i = 0, j = search_getsize(fd); i < j; ++i) \
993 s = cons(s, search_getfilename(fd, i)); \
998 X("*-serverpackage.txt");
999 X("*.serverpackage");
1001 cvar_set("sv_curl_serverpackages", s);
1004 // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
1005 modname = "Xonotic";
1006 // physics/balance/config changes that count as mod
1007 if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
1008 modname = cvar_string("g_mod_physics");
1009 if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance") && cvar_string("g_mod_balance") != "Testing")
1010 modname = cvar_string("g_mod_balance");
1011 if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
1012 modname = cvar_string("g_mod_config");
1013 // extra mutators that deserve to count as mod
1014 MUTATOR_CALLHOOK(SetModname, modname);
1015 modname = M_ARGV(0, string);
1017 // save it for later
1018 modname = strzone(modname);
1020 WinningConditionHelper(this); // set worldstatus
1022 world_initialized = 1;
1023 __spawnfunc_spawn_all();
1026 round_handler_Activate(true);
1031 //makestatic (this); // Who the f___ did that?
1035 bool MoveToRandomLocationWithinBounds(entity e, vector boundmin, vector boundmax, float goodcontents, float badcontents, float badsurfaceflags, int attempts, float maxaboveground, float minviewdistance)
1037 float m = e.dphitcontentsmask;
1038 e.dphitcontentsmask = goodcontents | badcontents;
1040 vector org = boundmin;
1041 vector delta = boundmax - boundmin;
1045 int j; // used after the loop
1046 for(j = 0; j < attempts; ++j)
1048 start.x = org.x + random() * delta.x;
1049 start.y = org.y + random() * delta.y;
1050 start.z = org.z + random() * delta.z;
1052 // rule 1: start inside world bounds, and outside
1053 // solid, and don't start from somewhere where you can
1054 // fall down to evil
1055 tracebox(start, e.mins, e.maxs, start - '0 0 1' * delta.z, MOVE_NORMAL, e);
1056 if (trace_fraction >= 1)
1058 if (trace_startsolid)
1060 if (trace_dphitcontents & badcontents)
1062 if (trace_dphitq3surfaceflags & badsurfaceflags)
1065 // rule 2: if we are too high, lower the point
1066 if (trace_fraction * delta.z > maxaboveground)
1067 start = trace_endpos + '0 0 1' * maxaboveground;
1068 vector enddown = trace_endpos;
1070 // rule 3: make sure we aren't outside the map. This only works
1071 // for somewhat well formed maps. A good rule of thumb is that
1072 // the map should have a convex outside hull.
1073 // these can be traceLINES as we already verified the starting box
1074 vector mstart = start + 0.5 * (e.mins + e.maxs);
1075 traceline(mstart, mstart + '1 0 0' * delta.x, MOVE_NORMAL, e);
1076 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1078 traceline(mstart, mstart - '1 0 0' * delta.x, MOVE_NORMAL, e);
1079 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1081 traceline(mstart, mstart + '0 1 0' * delta.y, MOVE_NORMAL, e);
1082 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1084 traceline(mstart, mstart - '0 1 0' * delta.y, MOVE_NORMAL, e);
1085 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1087 traceline(mstart, mstart + '0 0 1' * delta.z, MOVE_NORMAL, e);
1088 if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1091 // rule 4: we must "see" some spawnpoint or item
1093 IL_EACH(g_spawnpoints, checkpvs(mstart, it),
1095 if((traceline(mstart, it.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1103 int items_checked = 0;
1104 IL_EACH(g_items, checkpvs(mstart, it),
1106 if((traceline(mstart, it.origin + (it.mins + it.maxs) * 0.5, MOVE_NORMAL, e), trace_fraction) >= 1)
1113 if(items_checked >= attempts)
1121 // find a random vector to "look at"
1122 end.x = org.x + random() * delta.x;
1123 end.y = org.y + random() * delta.y;
1124 end.z = org.z + random() * delta.z;
1125 end = start + normalize(end - start) * vlen(delta);
1127 // rule 4: start TO end must not be too short
1128 tracebox(start, e.mins, e.maxs, end, MOVE_NORMAL, e);
1129 if(trace_startsolid)
1131 if(trace_fraction < minviewdistance / vlen(delta))
1134 // rule 5: don't want to look at sky
1135 if(trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
1138 // rule 6: we must not end up in trigger_hurt
1139 if(tracebox_hits_trigger_hurt(start, e.mins, e.maxs, enddown))
1145 e.dphitcontentsmask = m;
1149 setorigin(e, start);
1150 e.angles = vectoangles(end - start);
1151 LOG_DEBUG("Needed ", ftos(j + 1), " attempts");
1157 float MoveToRandomMapLocation(entity e, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1159 return MoveToRandomLocationWithinBounds(e, world.mins, world.maxs, goodcontents, badcontents, badsurfaceflags, attempts, maxaboveground, minviewdistance);
1163 ===============================================================================
1167 ===============================================================================
1170 void DumpStats(float final)
1179 to_console = autocvar_sv_logscores_console;
1180 to_eventlog = autocvar_sv_eventlog;
1181 to_file = autocvar_sv_logscores_file;
1185 to_console = true; // always print printstats replies
1186 to_eventlog = false; // but never print them to the event log
1190 if(autocvar_sv_eventlog_console)
1191 to_console = false; // otherwise we get the output twice
1197 s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1207 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1211 fputs(file, strcat(s, "\n"));
1214 s = strcat(":labels:player:", GetPlayerScoreString(NULL, 0));
1220 fputs(file, strcat(s, "\n"));
1222 FOREACH_CLIENT(IS_REAL_CLIENT(it) || (IS_BOT_CLIENT(it) && autocvar_sv_logscores_bots), {
1223 s = strcat(":player:see-labels:", GetPlayerScoreString(it, 0), ":");
1224 s = strcat(s, ftos(rint(time - CS(it).jointime)), ":");
1225 if(IS_PLAYER(it) || MUTATOR_CALLHOOK(GetPlayerStatus, it))
1226 s = strcat(s, ftos(it.team), ":");
1228 s = strcat(s, "spectator:");
1231 LOG_INFO(s, playername(it.netname, it.team, false));
1233 GameLogEcho(strcat(s, ftos(it.playerid), ":", playername(it.netname, it.team, false)));
1235 fputs(file, strcat(s, playername(it.netname, it.team, false), "\n"));
1240 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1246 fputs(file, strcat(s, "\n"));
1248 for(i = 1; i < 16; ++i)
1250 s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1251 s = strcat(s, ":", ftos(i));
1257 fputs(file, strcat(s, "\n"));
1264 GameLogEcho(":end");
1267 fputs(file, ":end\n");
1273 go to the next level for deathmatch
1274 only called if a time or frag limit has expired
1278 game_stopped = true;
1279 intermission_running = 1; // game over
1281 // enforce a wait time before allowing changelevel
1282 if(player_count > 0)
1283 intermission_exittime = time + autocvar_sv_mapchange_delay;
1285 intermission_exittime = -1;
1288 WriteByte (MSG_ALL, SVC_CDTRACK);
1289 WriteByte (MSG_ALL, 3);
1290 WriteByte (MSG_ALL, 3);
1291 // done in FixIntermission
1294 //pos = FindIntermission ();
1296 sound(NULL, CH_INFO, SND_ENDMATCH, VOL_BASE, ATTN_NONE);
1303 PlayerStats_GameReport(true);
1304 WeaponStats_Shutdown();
1306 Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_Null); // kill all centerprints now
1308 // send winner notification
1310 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, APP_TEAM_NUM(WinningConditionHelper_winnerteam, ANNCE_TEAM_WINS));
1313 if(autocvar_sv_eventlog)
1314 GameLogEcho(":gameover");
1318 FOREACH_CLIENT(IS_PLAYER(it), {
1319 FixIntermissionClient(it);
1321 bprint(playername(it.netname, it.team, false), " ^7wins.\n");
1324 target_music_kill();
1327 if(autocvar_sv_jingle_end) {
1328 int jingles_len = 0;
1332 FOREACH_WORD(autocvar_sv_jingle_end_list, it,
1334 jingles[jingles_len] = it;
1339 int song_to_play = rint(random() * (jingles_len - 1));
1341 FOREACH_CLIENT(IS_REAL_CLIENT(it),
1343 stuffcmd(it, "cd stop\n");
1344 _sound(it, CH_INFO, strcat("jingle/", jingles[song_to_play], ".ogg"), VOL_BASE * autocvar_sv_jingle_end_volume, ATTEN_NORM);
1349 if(autocvar_g_campaign)
1350 CampaignPreIntermission();
1352 MUTATOR_CALLHOOK(MatchEnd);
1354 localcmd("\nsv_hook_gameend\n");
1358 float InitiateSuddenDeath()
1360 // Check first whether normal overtimes could be added before initiating suddendeath mode
1361 // - for this timelimit_overtime needs to be >0 of course
1362 // - also check the winning condition calculated in the previous frame and only add normal overtime
1363 // again, if at the point at which timelimit would be extended again, still no winner was found
1364 if (!autocvar_g_campaign && checkrules_overtimesadded >= 0
1365 && (checkrules_overtimesadded < autocvar_timelimit_overtimes || autocvar_timelimit_overtimes < 0)
1366 && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1368 return 1; // need to call InitiateOvertime later
1372 if(!checkrules_suddendeathend)
1374 if(autocvar_g_campaign)
1375 checkrules_suddendeathend = time; // no suddendeath in campaign
1377 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1378 if(g_race && !g_race_qualifying)
1379 race_StartCompleting();
1385 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1387 ++checkrules_overtimesadded;
1388 //add one more overtime by simply extending the timelimit
1389 cvar_set("timelimit", ftos(autocvar_timelimit + autocvar_timelimit_overtime));
1390 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime * 60);
1392 sound(NULL, CH_INFO, SND_OVERTIME, VOL_BASE, ATTN_NONE);
1393 if(checkrules_overtimesadded == 1) {
1394 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_OVERTIME);
1395 overtime_starttime = time;
1399 float GetWinningCode(float fraglimitreached, float equality)
1401 if(autocvar_g_campaign == 1)
1403 if(fraglimitreached)
1412 if(fraglimitreached)
1413 return WINNING_STARTSUDDENDEATHOVERTIME;
1415 return WINNING_NEVER;
1419 if(fraglimitreached)
1427 // set the .winning flag for exactly those players with a given field value
1428 void SetWinners(.float field, float value)
1430 FOREACH_CLIENT(IS_PLAYER(it), { it.winning = (it.(field) == value); });
1433 // set the .winning flag for those players with a given field value
1434 void AddWinners(.float field, float value)
1436 FOREACH_CLIENT(IS_PLAYER(it), {
1437 if(it.(field) == value)
1442 // clear the .winning flags
1445 FOREACH_CLIENT(IS_PLAYER(it), { it.winning = 0; });
1448 void AnnounceNewLeader()
1451 if (WinningConditionHelper_equality)
1452 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_TEAM_LEADS_TIED);
1454 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, APP_TEAM_NUM(WinningConditionHelper_winnerteam, ANNCE_TEAM_LEADS));
1456 if (WinningConditionHelper_equality)
1458 Send_Notification(NOTIF_ONE, WinningConditionHelper_equality_one, MSG_ANNCE, ANNCE_LEAD_TIED);
1459 Send_Notification(NOTIF_ONE, WinningConditionHelper_equality_two, MSG_ANNCE, ANNCE_LEAD_TIED);
1463 Send_Notification(NOTIF_ONE, WinningConditionHelper_winner, MSG_ANNCE, ANNCE_LEAD_GAINED);
1464 Send_Notification(NOTIF_ONE, WinningConditionHelper_second, MSG_ANNCE, ANNCE_LEAD_LOST);
1469 float WinningCondition_Scores(float limit, float leadlimit)
1471 // TODO make everything use THIS winning condition (except LMS)
1472 WinningConditionHelper(NULL);
1476 for (int i = 1; i < 5; ++i)
1478 Team_SetTeamScore(Team_GetTeamFromIndex(i),
1479 TeamScore_GetCompareValue(Team_IndexToTeam(i)));
1484 if(WinningConditionHelper_winner)
1485 WinningConditionHelper_winner.winning = 1;
1486 if(WinningConditionHelper_winnerteam >= 0)
1487 SetWinners(team, WinningConditionHelper_winnerteam);
1489 if(WinningConditionHelper_lowerisbetter)
1491 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1492 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1496 if(WinningConditionHelper_zeroisworst)
1497 leadlimit = 0; // not supported in this mode
1499 if(MUTATOR_CALLHOOK(Scores_CountFragsRemaining))
1501 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1507 fragsleft = FLOAT_MAX;
1508 float leadingfragsleft = FLOAT_MAX;
1510 fragsleft = limit - WinningConditionHelper_topscore;
1512 leadingfragsleft = WinningConditionHelper_secondscore + leadlimit - WinningConditionHelper_topscore;
1514 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1515 fragsleft = max(fragsleft, leadingfragsleft);
1517 fragsleft = min(fragsleft, leadingfragsleft);
1520 if (fragsleft_last != fragsleft) // do not announce same remaining frags multiple times
1523 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_1);
1524 else if (fragsleft == 2)
1525 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_2);
1526 else if (fragsleft == 3)
1527 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_3);
1529 fragsleft_last = fragsleft;
1533 // z411 - lead announcer
1534 if(MUTATOR_CALLHOOK(Scores_AnnounceLeads)) {
1535 if (Score_NewLeader())
1536 AnnounceNewLeader();
1539 bool fraglimit_reached = (limit && WinningConditionHelper_topscore >= limit);
1540 bool leadlimit_reached = (leadlimit && WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1543 // only respect leadlimit_and_fraglimit when both limits are set or the game will never end
1544 if (limit && leadlimit && autocvar_leadlimit_and_fraglimit)
1545 limit_reached = (fraglimit_reached && leadlimit_reached);
1547 limit_reached = (fraglimit_reached || leadlimit_reached);
1549 return GetWinningCode(
1550 WinningConditionHelper_topscore && limit_reached,
1551 WinningConditionHelper_equality
1555 float WinningCondition_RanOutOfSpawns()
1557 if(have_team_spawns <= 0)
1560 if(!autocvar_g_spawn_useallspawns)
1563 if(!some_spawn_has_been_used)
1566 for (int i = 1; i < 5; ++i)
1568 Team_SetTeamScore(Team_GetTeamFromIndex(i), 0);
1571 FOREACH_CLIENT(IS_PLAYER(it) && !IS_DEAD(it),
1573 if (Team_IsValidTeam(it.team))
1575 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1579 IL_EACH(g_spawnpoints, true,
1581 if (Team_IsValidTeam(it.team))
1583 Team_SetTeamScore(Team_GetTeam(it.team), 1);
1588 float team1_score = Team_GetTeamScore(Team_GetTeamFromIndex(1));
1589 float team2_score = Team_GetTeamScore(Team_GetTeamFromIndex(2));
1590 float team3_score = Team_GetTeamScore(Team_GetTeamFromIndex(3));
1591 float team4_score = Team_GetTeamScore(Team_GetTeamFromIndex(4));
1592 if(team1_score + team2_score + team3_score + team4_score == 0)
1594 checkrules_equality = true;
1597 else if(team1_score + team2_score + team3_score + team4_score == 1)
1602 else if(team2_score)
1604 else if(team3_score)
1606 else // if(team4_score)
1608 entity balance = TeamBalance_CheckAllowedTeams(NULL);
1609 for(i = 0; i < MAX_TEAMSCORE; ++i)
1611 for (int j = 1; j <= NUM_TEAMS; ++j)
1617 if (!TeamBalance_IsTeamAllowed(balance, j))
1621 TeamScore_AddToTeam(Team_IndexToTeam(j), i, -1000);
1625 AddWinners(team, t);
1636 Exit deathmatch games upon conditions
1639 void CheckRules_World()
1646 if (intermission_running) // someone else quit the game already
1648 if(player_count == 0) // Nobody there? Then let's go to the next map
1650 // this will actually check the player count in the next frame
1651 // again, but this shouldn't hurt
1655 // z411 don't check rules if we're in a timeout
1656 if (game_timeout) return;
1658 float timelimit = autocvar_timelimit * 60;
1659 float fraglimit = autocvar_fraglimit;
1660 float leadlimit = autocvar_leadlimit;
1661 if (leadlimit < 0) leadlimit = 0;
1663 if(warmup_stage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1666 timelimit = 0; // timelimit is not made for warmup
1668 fraglimit = 0; // no fraglimit for now
1669 leadlimit = 0; // no leadlimit for now
1674 timelimit += game_starttime;
1676 else if (timelimit < 0)
1686 if(checkrules_suddendeathend)
1688 if(!checkrules_suddendeathwarning)
1690 checkrules_suddendeathwarning = true;
1691 if(g_race && !g_race_qualifying)
1692 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_RACE_FINISHLAP);
1694 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_FRAG);
1695 sound(NULL, CH_INFO, SND_OVERTIME, VOL_BASE, ATTN_NONE);
1696 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_SUDDENDEATH);
1701 if (timelimit && time >= timelimit)
1703 if(g_race && (g_race_qualifying == 2) && timelimit > 0)
1706 float playerswithlaps;
1708 totalplayers = playerswithlaps = readyplayers = 0;
1709 FOREACH_CLIENT(IS_PLAYER(it), {
1711 if(GameRules_scoring_add(it, RACE_FASTEST, 0))
1717 // at least 2 of the players have completed a lap: start the RACE
1718 // otherwise, the players should end the qualifying on their own
1719 if(readyplayers || playerswithlaps >= 2)
1721 checkrules_suddendeathend = 0;
1722 ReadyRestart(); // go to race
1726 wantovertime |= InitiateSuddenDeath();
1729 wantovertime |= InitiateSuddenDeath();
1733 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1739 int checkrules_status = WinningCondition_RanOutOfSpawns();
1740 if(checkrules_status == WINNING_YES)
1741 bprint("Hey! Someone ran out of spawns!\n");
1742 else if(MUTATOR_CALLHOOK(CheckRules_World, checkrules_status, timelimit, fraglimit))
1743 checkrules_status = M_ARGV(0, float);
1745 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
1747 if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
1749 checkrules_status = WINNING_NEVER;
1750 checkrules_overtimesadded = -1;
1751 wantovertime |= InitiateSuddenDeath();
1754 if(checkrules_status == WINNING_NEVER)
1755 // equality cases! Nobody wins if the overtime ends in a draw.
1760 if(checkrules_status == WINNING_NEVER)
1763 checkrules_status = WINNING_YES;
1766 if(checkrules_suddendeathend)
1767 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
1768 checkrules_status = WINNING_YES;
1770 if(checkrules_status == WINNING_YES)
1772 //print("WINNING\n");
1777 float want_weapon(entity weaponinfo, float allguns)
1780 bool allow_mutatorblocked = false;
1782 if(!weaponinfo.m_id)
1785 bool mutator_returnvalue = MUTATOR_CALLHOOK(WantWeapon, weaponinfo, d, allguns, allow_mutatorblocked);
1786 d = M_ARGV(1, float);
1787 allguns = M_ARGV(2, bool);
1788 allow_mutatorblocked = M_ARGV(3, bool);
1791 d = boolean((weaponinfo.spawnflags & WEP_FLAG_NORMAL) && !(weaponinfo.spawnflags & (WEP_FLAG_HIDDEN | WEP_FLAG_SPECIALATTACK)));
1792 else if(!mutator_returnvalue)
1793 d = !(!weaponinfo.weaponstart);
1795 if(!allow_mutatorblocked && (weaponinfo.spawnflags & WEP_FLAG_MUTATORBLOCKED)) // never default mutator blocked guns
1798 float t = weaponinfo.weaponstartoverride;
1800 //LOG_INFOF("want_weapon: %s - d: %d t: %d\n", weaponinfo.netname, d, t);
1805 // 4: is set by default?
1814 /// Weapons the player normally starts with outside weapon arena.
1815 WepSet weapons_start()
1817 WepSet ret = '0 0 0';
1818 FOREACH(Weapons, it != WEP_Null, {
1819 int w = want_weapon(it, false);
1826 WepSet weapons_all()
1828 WepSet ret = '0 0 0';
1829 FOREACH(Weapons, it != WEP_Null, {
1830 if (!(it.spawnflags & (WEP_FLAG_MUTATORBLOCKED | WEP_FLAG_SPECIALATTACK)))
1836 WepSet weapons_devall()
1838 WepSet ret = '0 0 0';
1839 FOREACH(Weapons, it != WEP_Null,
1846 WepSet weapons_most()
1848 WepSet ret = '0 0 0';
1849 FOREACH(Weapons, it != WEP_Null, {
1850 if ((it.spawnflags & WEP_FLAG_NORMAL) && !(it.spawnflags & (WEP_FLAG_MUTATORBLOCKED | WEP_FLAG_HIDDEN | WEP_FLAG_SPECIALATTACK)))
1856 void weaponarena_available_all_update(entity this)
1858 if (weaponsInMapAll)
1860 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | (weaponsInMapAll & weapons_all());
1864 // if no weapons are available on the map, just fall back to all weapons arena
1865 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_all();
1869 void weaponarena_available_devall_update(entity this)
1871 if (weaponsInMapAll)
1873 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | weaponsInMapAll;
1877 // if no weapons are available on the map, just fall back to devall weapons arena
1878 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_devall();
1882 void weaponarena_available_most_update(entity this)
1884 if (weaponsInMapAll)
1886 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | (weaponsInMapAll & weapons_most());
1890 // if no weapons are available on the map, just fall back to most weapons arena
1891 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_most();
1895 void readplayerstartcvars()
1897 // initialize starting values for players
1898 start_weapons = '0 0 0';
1899 start_weapons_default = '0 0 0';
1900 start_weapons_defaultmask = '0 0 0';
1902 start_ammo_shells = 0;
1903 start_ammo_nails = 0;
1904 start_ammo_rockets = 0;
1905 start_ammo_cells = 0;
1906 start_ammo_plasma = 0;
1907 if (random_start_ammo == NULL)
1909 random_start_ammo = new(random_start_ammo);
1911 start_health = cvar("g_balance_health_start");
1912 start_armorvalue = cvar("g_balance_armor_start");
1915 g_weaponarena_weapons = '0 0 0';
1917 string s = cvar_string("g_weaponarena");
1919 MUTATOR_CALLHOOK(SetWeaponArena, s);
1920 s = M_ARGV(0, string);
1922 if (s == "0" || s == "")
1926 else if (s == "off")
1928 // forcibly turn off weaponarena
1930 else if (s == "all" || s == "1")
1933 g_weaponarena_list = "All Weapons";
1934 g_weaponarena_weapons = weapons_all();
1936 else if (s == "devall")
1939 g_weaponarena_list = "Dev All Weapons";
1940 g_weaponarena_weapons = weapons_devall();
1942 else if (s == "most")
1945 g_weaponarena_list = "Most Weapons";
1946 g_weaponarena_weapons = weapons_most();
1948 else if (s == "all_available")
1951 g_weaponarena_list = "All Available Weapons";
1953 // this needs to run after weaponsInMapAll is initialized
1954 InitializeEntity(NULL, weaponarena_available_all_update, INITPRIO_FINDTARGET);
1956 else if (s == "devall_available")
1959 g_weaponarena_list = "Dev All Available Weapons";
1961 // this needs to run after weaponsInMapAll is initialized
1962 InitializeEntity(NULL, weaponarena_available_devall_update, INITPRIO_FINDTARGET);
1964 else if (s == "most_available")
1967 g_weaponarena_list = "Most Available Weapons";
1969 // this needs to run after weaponsInMapAll is initialized
1970 InitializeEntity(NULL, weaponarena_available_most_update, INITPRIO_FINDTARGET);
1972 else if (s == "none")
1975 g_weaponarena_list = "No Weapons";
1980 float t = tokenize_console(s);
1981 g_weaponarena_list = "";
1982 for (int j = 0; j < t; ++j)
1985 Weapon wep = Weapon_from_name(s);
1988 g_weaponarena_weapons |= (wep.m_wepset);
1989 g_weaponarena_list = strcat(g_weaponarena_list, wep.m_name, " & ");
1992 g_weaponarena_list = strzone(substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3));
1997 g_weapon_stay = 0; // incompatible
1998 start_weapons = g_weaponarena_weapons;
1999 start_items |= IT_UNLIMITED_AMMO | IT_UNLIMITED_SUPERWEAPONS;
2003 FOREACH(Weapons, it != WEP_Null, {
2004 int w = want_weapon(it, false);
2005 WepSet s = it.m_wepset;
2009 start_weapons_default |= s;
2011 start_weapons_defaultmask |= s;
2015 if(cvar("g_balance_superweapons_time") < 0)
2016 start_items |= IT_UNLIMITED_SUPERWEAPONS;
2018 if(!cvar("g_use_ammunition"))
2019 start_items |= IT_UNLIMITED_AMMO;
2021 if(start_items & IT_UNLIMITED_AMMO)
2023 start_ammo_shells = 999;
2024 start_ammo_nails = 999;
2025 start_ammo_rockets = 999;
2026 start_ammo_cells = 999;
2027 start_ammo_plasma = 999;
2028 start_ammo_fuel = 999;
2032 start_ammo_shells = cvar("g_start_ammo_shells");
2033 start_ammo_nails = cvar("g_start_ammo_nails");
2034 start_ammo_rockets = cvar("g_start_ammo_rockets");
2035 start_ammo_cells = cvar("g_start_ammo_cells");
2036 start_ammo_plasma = cvar("g_start_ammo_plasma");
2037 start_ammo_fuel = cvar("g_start_ammo_fuel");
2038 random_start_weapons_count = cvar("g_random_start_weapons_count");
2039 SetResource(random_start_ammo, RES_SHELLS, cvar("g_random_start_shells"));
2040 SetResource(random_start_ammo, RES_BULLETS, cvar("g_random_start_bullets"));
2041 SetResource(random_start_ammo, RES_ROCKETS,cvar("g_random_start_rockets"));
2042 SetResource(random_start_ammo, RES_CELLS, cvar("g_random_start_cells"));
2043 SetResource(random_start_ammo, RES_PLASMA, cvar("g_random_start_plasma"));
2046 warmup_start_ammo_shells = start_ammo_shells;
2047 warmup_start_ammo_nails = start_ammo_nails;
2048 warmup_start_ammo_rockets = start_ammo_rockets;
2049 warmup_start_ammo_cells = start_ammo_cells;
2050 warmup_start_ammo_plasma = start_ammo_plasma;
2051 warmup_start_ammo_fuel = start_ammo_fuel;
2052 warmup_start_health = start_health;
2053 warmup_start_armorvalue = start_armorvalue;
2054 warmup_start_weapons = start_weapons;
2055 warmup_start_weapons_default = start_weapons_default;
2056 warmup_start_weapons_defaultmask = start_weapons_defaultmask;
2060 warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
2061 warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
2062 warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
2063 warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
2064 warmup_start_ammo_plasma = cvar("g_warmup_start_ammo_plasma");
2065 warmup_start_ammo_fuel = cvar("g_warmup_start_ammo_fuel");
2066 warmup_start_health = cvar("g_warmup_start_health");
2067 warmup_start_armorvalue = cvar("g_warmup_start_armor");
2068 warmup_start_weapons = '0 0 0';
2069 warmup_start_weapons_default = '0 0 0';
2070 warmup_start_weapons_defaultmask = '0 0 0';
2071 FOREACH(Weapons, it != WEP_Null, {
2072 int w = want_weapon(it, autocvar_g_warmup_allguns);
2073 WepSet s = it.m_wepset;
2075 warmup_start_weapons |= s;
2077 warmup_start_weapons_default |= s;
2079 warmup_start_weapons_defaultmask |= s;
2083 if (autocvar_g_jetpack)
2084 start_items |= ITEM_Jetpack.m_itemid;
2086 MUTATOR_CALLHOOK(SetStartItems);
2088 if (start_items & ITEM_Jetpack.m_itemid)
2090 start_items |= ITEM_JetpackRegen.m_itemid;
2091 start_ammo_fuel = max(start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
2092 warmup_start_ammo_fuel = max(warmup_start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
2095 start_ammo_shells = max(0, start_ammo_shells);
2096 start_ammo_nails = max(0, start_ammo_nails);
2097 start_ammo_rockets = max(0, start_ammo_rockets);
2098 start_ammo_cells = max(0, start_ammo_cells);
2099 start_ammo_plasma = max(0, start_ammo_plasma);
2100 start_ammo_fuel = max(0, start_ammo_fuel);
2101 SetResource(random_start_ammo, RES_SHELLS,
2102 max(0, GetResource(random_start_ammo, RES_SHELLS)));
2103 SetResource(random_start_ammo, RES_BULLETS,
2104 max(0, GetResource(random_start_ammo, RES_BULLETS)));
2105 SetResource(random_start_ammo, RES_ROCKETS,
2106 max(0, GetResource(random_start_ammo, RES_ROCKETS)));
2107 SetResource(random_start_ammo, RES_CELLS,
2108 max(0, GetResource(random_start_ammo, RES_CELLS)));
2109 SetResource(random_start_ammo, RES_PLASMA,
2110 max(0, GetResource(random_start_ammo, RES_PLASMA)));
2112 warmup_start_ammo_shells = max(0, warmup_start_ammo_shells);
2113 warmup_start_ammo_nails = max(0, warmup_start_ammo_nails);
2114 warmup_start_ammo_rockets = max(0, warmup_start_ammo_rockets);
2115 warmup_start_ammo_cells = max(0, warmup_start_ammo_cells);
2116 warmup_start_ammo_plasma = max(0, warmup_start_ammo_plasma);
2117 warmup_start_ammo_fuel = max(0, warmup_start_ammo_fuel);
2120 void readlevelcvars()
2122 if(cvar("sv_allow_fullbright"))
2123 serverflags |= SERVERFLAG_ALLOW_FULLBRIGHT;
2125 sv_ready_restart_after_countdown = cvar("sv_ready_restart_after_countdown");
2127 warmup_stage = cvar("g_warmup");
2128 warmup_limit = cvar("g_warmup_limit");
2130 if(cvar("g_campaign"))
2131 warmup_stage = 0; // no warmup during campaign
2133 g_pickup_respawntime_weapon = cvar("g_pickup_respawntime_weapon");
2134 g_pickup_respawntime_superweapon = cvar("g_pickup_respawntime_superweapon");
2135 g_pickup_respawntime_ammo = cvar("g_pickup_respawntime_ammo");
2136 g_pickup_respawntime_short = cvar("g_pickup_respawntime_short");
2137 g_pickup_respawntime_medium = cvar("g_pickup_respawntime_medium");
2138 g_pickup_respawntime_long = cvar("g_pickup_respawntime_long");
2139 g_pickup_respawntime_powerup = cvar("g_pickup_respawntime_powerup");
2140 g_pickup_respawntimejitter_weapon = cvar("g_pickup_respawntimejitter_weapon");
2141 g_pickup_respawntimejitter_superweapon = cvar("g_pickup_respawntimejitter_superweapon");
2142 g_pickup_respawntimejitter_ammo = cvar("g_pickup_respawntimejitter_ammo");
2143 g_pickup_respawntimejitter_short = cvar("g_pickup_respawntimejitter_short");
2144 g_pickup_respawntimejitter_medium = cvar("g_pickup_respawntimejitter_medium");
2145 g_pickup_respawntimejitter_long = cvar("g_pickup_respawntimejitter_long");
2146 g_pickup_respawntimejitter_powerup = cvar("g_pickup_respawntimejitter_powerup");
2148 g_pickup_shells = cvar("g_pickup_shells");
2149 g_pickup_shells_max = cvar("g_pickup_shells_max");
2150 g_pickup_nails = cvar("g_pickup_nails");
2151 g_pickup_nails_max = cvar("g_pickup_nails_max");
2152 g_pickup_rockets = cvar("g_pickup_rockets");
2153 g_pickup_rockets_max = cvar("g_pickup_rockets_max");
2154 g_pickup_cells = cvar("g_pickup_cells");
2155 g_pickup_cells_max = cvar("g_pickup_cells_max");
2156 g_pickup_plasma = cvar("g_pickup_plasma");
2157 g_pickup_plasma_max = cvar("g_pickup_plasma_max");
2158 g_pickup_fuel = cvar("g_pickup_fuel");
2159 g_pickup_fuel_jetpack = cvar("g_pickup_fuel_jetpack");
2160 g_pickup_fuel_max = cvar("g_pickup_fuel_max");
2161 g_pickup_armorsmall = cvar("g_pickup_armorsmall");
2162 g_pickup_armorsmall_max = cvar("g_pickup_armorsmall_max");
2163 g_pickup_armorsmall_anyway = cvar("g_pickup_armorsmall_anyway");
2164 g_pickup_armormedium = cvar("g_pickup_armormedium");
2165 g_pickup_armormedium_max = cvar("g_pickup_armormedium_max");
2166 g_pickup_armormedium_anyway = cvar("g_pickup_armormedium_anyway");
2167 g_pickup_armorbig = cvar("g_pickup_armorbig");
2168 g_pickup_armorbig_max = cvar("g_pickup_armorbig_max");
2169 g_pickup_armorbig_anyway = cvar("g_pickup_armorbig_anyway");
2170 g_pickup_armormega = cvar("g_pickup_armormega");
2171 g_pickup_armormega_max = cvar("g_pickup_armormega_max");
2172 g_pickup_armormega_anyway = cvar("g_pickup_armormega_anyway");
2173 g_pickup_healthsmall = cvar("g_pickup_healthsmall");
2174 g_pickup_healthsmall_max = cvar("g_pickup_healthsmall_max");
2175 g_pickup_healthsmall_anyway = cvar("g_pickup_healthsmall_anyway");
2176 g_pickup_healthmedium = cvar("g_pickup_healthmedium");
2177 g_pickup_healthmedium_max = cvar("g_pickup_healthmedium_max");
2178 g_pickup_healthmedium_anyway = cvar("g_pickup_healthmedium_anyway");
2179 g_pickup_healthbig = cvar("g_pickup_healthbig");
2180 g_pickup_healthbig_max = cvar("g_pickup_healthbig_max");
2181 g_pickup_healthbig_anyway = cvar("g_pickup_healthbig_anyway");
2182 g_pickup_healthmega = cvar("g_pickup_healthmega");
2183 g_pickup_healthmega_max = cvar("g_pickup_healthmega_max");
2184 g_pickup_healthmega_anyway = cvar("g_pickup_healthmega_anyway");
2186 g_pickup_ammo_anyway = cvar("g_pickup_ammo_anyway");
2187 g_pickup_weapons_anyway = cvar("g_pickup_weapons_anyway");
2189 g_weapon_stay = cvar(strcat("g_", GetGametype(), "_weapon_stay"));
2191 g_weapon_stay = cvar("g_weapon_stay");
2193 MUTATOR_CALLHOOK(ReadLevelCvars);
2196 game_starttime = time + cvar("g_start_delay");
2198 FOREACH(Weapons, it != WEP_Null, { it.wr_init(it); });
2200 readplayerstartcvars();
2203 void InitializeEntity(entity e, void(entity this) func, int order)
2207 if (!e || e.initialize_entity)
2209 // make a proxy initializer entity
2211 e = new(initialize_entity);
2215 e.initialize_entity = func;
2216 e.initialize_entity_order = order;
2218 cur = initialize_entity_first;
2222 if (!cur || cur.initialize_entity_order > order)
2224 // insert between prev and cur
2226 prev.initialize_entity_next = e;
2228 initialize_entity_first = e;
2229 e.initialize_entity_next = cur;
2233 cur = cur.initialize_entity_next;
2236 void InitializeEntitiesRun()
2238 entity startoflist = initialize_entity_first;
2239 initialize_entity_first = NULL;
2240 delete_fn = remove_except_protected;
2241 for (entity e = startoflist; e; e = e.initialize_entity_next)
2243 e.remove_except_protected_forbidden = 1;
2245 for (entity e = startoflist; e; )
2247 e.remove_except_protected_forbidden = 0;
2248 e.initialize_entity_order = 0;
2249 entity next = e.initialize_entity_next;
2250 e.initialize_entity_next = NULL;
2251 var void(entity this) func = e.initialize_entity;
2252 e.initialize_entity = func_null;
2253 if (e.classname == "initialize_entity")
2255 entity wrappee = e.enemy;
2259 //dprint("Delayed initialization: ", e.classname, "\n");
2267 backtrace(strcat("Null function in: ", e.classname, "\n"));
2271 delete_fn = remove_unsafely;
2274 // deferred dropping
2275 void DropToFloor_Handler(entity this)
2277 WITHSELF(this, builtin_droptofloor());
2278 this.dropped_origin = this.origin;
2281 void droptofloor(entity this)
2283 InitializeEntity(this, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
2286 bool autocvar_sv_gameplayfix_multiplethinksperframe = true;
2287 void RunThink(entity this)
2289 // don't let things stay in the past.
2290 // it is possible to start that way by a trigger with a local time.
2291 if(this.nextthink <= 0 || this.nextthink > time + frametime)
2294 float oldtime = time; // do we need to save this?
2296 for (int iterations = 0; iterations < 128 && !wasfreed(this); iterations++)
2298 time = max(oldtime, this.nextthink);
2302 getthink(this)(this);
2303 // mods often set nextthink to time to cause a think every frame,
2304 // we don't want to loop in that case, so exit if the new nextthink is
2305 // <= the time the qc was told, also exit if it is past the end of the
2307 if(this.nextthink <= time || this.nextthink > oldtime + frametime || !autocvar_sv_gameplayfix_multiplethinksperframe)
2314 bool autocvar_sv_freezenonclients;
2315 void Physics_Frame()
2317 if(autocvar_sv_freezenonclients || game_timeout)
2320 IL_EACH(g_moveables, true,
2322 if(IS_CLIENT(it) || it.move_movetype == MOVETYPE_PHYSICS)
2325 //set_movetype(it, it.move_movetype);
2326 // inline the set_movetype function, since this is called a lot
2327 it.movetype = (it.move_qcphysics) ? MOVETYPE_QCENTITY : it.move_movetype;
2329 if(it.move_qcphysics && it.move_movetype != MOVETYPE_NONE)
2330 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2332 if(it.movetype >= MOVETYPE_USER_FIRST && it.movetype <= MOVETYPE_USER_LAST) // these cases have no think handling
2334 if(it.move_movetype == MOVETYPE_PUSH || it.move_movetype == MOVETYPE_FAKEPUSH)
2335 continue; // these movetypes have no regular think function
2336 // handle thinking here
2337 if (getthink(it) && it.nextthink > 0 && it.nextthink <= time + frametime)
2342 if(autocvar_sv_gameplayfix_delayprojectiles >= 0)
2345 // make a second pass to see if any ents spawned this frame and make
2346 // sure they run their move/think. this is verified by checking .move_time, which will never be 0 if the entity has moved
2347 // MOVETYPE_NONE is also checked as .move_time WILL be 0 with that movetype
2348 IL_EACH(g_moveables, it.move_qcphysics,
2350 if(IS_CLIENT(it) || it.move_time || it.move_movetype == MOVETYPE_NONE || it.move_movetype == MOVETYPE_PHYSICS)
2352 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2356 void systems_update();
2359 anticheat_endframe();
2363 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2364 entity e = IS_SPEC(it) ? it.enemy : it;
2365 if (e.typehitsound) {
2366 STAT(TYPEHIT_TIME, it) = time;
2367 } else if (e.killsound) {
2368 STAT(KILL_TIME, it) = time;
2369 } else if (e.damage_dealt) {
2370 STAT(HIT_TIME, it) = time;
2371 STAT(DAMAGE_DEALT_TOTAL, it) += ceil(e.damage_dealt);
2374 // add 1 frametime because after this, engine SV_Physics
2375 // increases time by a frametime and then networks the frame
2376 // add another frametime because client shows everything with
2377 // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2379 float altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2380 FOREACH_CLIENT(true, {
2381 it.typehitsound = false;
2382 it.damage_dealt = 0;
2383 it.killsound = false;
2384 antilag_record(it, CS(it), altime);
2386 IL_EACH(g_monsters, true,
2388 antilag_record(it, it, altime);
2390 IL_EACH(g_projectiles, it.classname == "nade",
2392 antilag_record(it, it, altime);
2401 * returns true if redirecting
2403 float redirection_timeout;
2404 float redirection_nextthink;
2405 float RedirectionThink()
2407 float clients_found;
2409 if(redirection_target == "")
2412 if(!redirection_timeout)
2414 cvar_set("sv_public", "-2");
2415 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2416 if(redirection_target == "self")
2417 bprint("^3SERVER NOTICE:^7 restarting the server\n");
2419 bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2422 if(time < redirection_nextthink)
2425 redirection_nextthink = time + 1;
2428 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2430 LOG_INFO("Redirecting: sending connect command to ", it.netname);
2431 if(redirection_target == "self")
2432 stuffcmd(it, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2434 stuffcmd(it, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2438 LOG_INFO("Redirecting: ", ftos(clients_found), " clients left.");
2440 if(time > redirection_timeout || clients_found == 0)
2441 localcmd("\nwait; wait; wait; quit\n");
2448 // Loaded from a save game
2449 // some things then break, so let's work around them...
2451 // Progs DB (capture records)
2452 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2456 MapInfo_Enumerate();
2457 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2460 TargetMusic_RestoreGame();
2467 if(world_initialized > 0)
2469 world_initialized = 0;
2471 // if a timeout is active, reset the slowmo value to normal
2472 if(timeout_status == TIMEOUT_ACTIVE)
2473 cvar_set("slowmo", ftos(orig_slowmo));
2475 LOG_TRACE("Saving persistent data...");
2478 // playerstats with unfinished match
2479 PlayerStats_GameReport(false);
2481 if(!cheatcount_total)
2483 if(autocvar_sv_db_saveasdump)
2484 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2486 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2488 if(autocvar_developer > 0)
2490 if(autocvar_sv_db_saveasdump)
2491 db_dump(TemporaryDB, "server-temp.db");
2493 db_save(TemporaryDB, "server-temp.db");
2495 CheatShutdown(); // must be after cheatcount check
2496 db_close(ServerProgsDB);
2497 db_close(TemporaryDB);
2498 LOG_TRACE("Saving persistent data... done!");
2499 // tell the bot system the game is ending now
2502 WeaponStats_Shutdown();
2505 else if(world_initialized == 0)
2507 LOG_INFO("NOTE: crashed before even initializing the world, not saving persistent data");
2511 __init_dedicated_server_shutdown();