1 #define LATENCY_THINKRATE 10
6 void PingPLReport_Think()
11 delta = 3 / maxclients;
12 if(delta < sys_frametime)
14 self.nextthink = time + delta;
16 e = edict_num(self.cnt + 1);
19 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
20 WriteByte(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
21 WriteByte(MSG_BROADCAST, self.cnt);
22 WriteShort(MSG_BROADCAST, max(1, e.ping));
23 WriteByte(MSG_BROADCAST, ceil(e.ping_packetloss * 255));
24 WriteByte(MSG_BROADCAST, ceil(e.ping_movementloss * 255));
26 // record latency times for clients throughout the match so we can report it to playerstats
27 if(time > (e.latency_time + LATENCY_THINKRATE))
29 e.latency_sum += e.ping;
31 e.latency_time = time;
32 //print("sum: ", ftos(e.latency_sum), ", cnt: ", ftos(e.latency_cnt), ", avg: ", ftos(e.latency_sum / e.latency_cnt), ".\n");
37 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
38 WriteByte(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
39 WriteByte(MSG_BROADCAST, self.cnt);
40 WriteShort(MSG_BROADCAST, 0);
41 WriteByte(MSG_BROADCAST, 0);
42 WriteByte(MSG_BROADCAST, 0);
44 self.cnt = (self.cnt + 1) % maxclients;
46 void PingPLReport_Spawn()
48 pingplreport = spawn();
49 pingplreport.classname = "pingplreport";
50 pingplreport.think = PingPLReport_Think;
51 pingplreport.nextthink = time;
54 const float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
55 string redirection_target;
56 float world_initialized;
59 void GotoNextMap(float reinit);
60 void ShuffleMaplist();
61 float(float reinit) DoNextMapOverride;
63 void SetDefaultAlpha()
65 if(autocvar_g_running_guns)
67 default_player_alpha = -1;
68 default_weapon_alpha = +1;
72 default_player_alpha = autocvar_g_balance_cloaked_alpha;
73 default_weapon_alpha = default_player_alpha;
77 default_player_alpha = autocvar_g_player_alpha;
78 if(default_player_alpha == 0)
79 default_player_alpha = 1;
80 default_weapon_alpha = default_player_alpha;
89 // cvar_set("_sv_init", "0");
90 // we do NOT set this to 0 any more, so someone "accidentally" changing
91 // to this "init" map on a dedicated server will cause no permanent
93 if(autocvar_g_maplist_shuffle)
95 n = tokenizebyseparator(autocvar_g_maplist, " ");
96 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
99 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
101 if(!DoNextMapOverride(1))
109 self.nextthink = time;
113 self.nextthink = time + 1;
114 print("Waiting for _sv_init being set to 1 by initialization scripts...\n");
118 void cvar_changes_init()
122 float n, i, adding, pureadding;
125 strunzone(cvar_changes);
126 cvar_changes = string_null;
128 strunzone(cvar_purechanges);
129 cvar_purechanges = string_null;
130 cvar_purechanges_count = 0;
133 buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
139 for(i = 0; i < n; ++i)
141 k = bufstr_get(h, i);
143 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
144 #define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
145 #define BADCVAR(p) if(k == p) continue
147 // general excludes and namespaces for server admin used cvars
148 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
152 BADPREFIX("cvar_check_");
154 BADCVAR("g_configversion");
155 BADCVAR("g_maplist_index");
156 BADCVAR("halflifebsp");
157 BADPREFIX("sv_world");
163 BADPREFIX("scoreboard_");
164 BADPREFIX("g_campaign");
165 BADPREFIX("g_waypointsprite_");
171 BADPREFIX("net_slist_");
177 BADPREFIX("sensitivity");
178 BADPREFIX("userbind");
181 BADPREFIX("crosshair");
182 BADCVAR("mod_q3bsp_lightmapmergepower");
183 BADCVAR("mod_q3bsp_nolightmaps");
185 BADCVAR("mastervolume");
187 BADCVAR("bgmvolume");
190 BADCVAR("developer");
191 BADCVAR("log_dest_udp");
192 BADCVAR("net_address");
193 BADCVAR("net_address_ipv6");
195 BADCVAR("savedgamecfg");
196 BADCVAR("serverconfig");
197 BADCVAR("sv_autoscreenshot");
198 BADCVAR("sv_heartbeatperiod");
199 BADCVAR("sv_vote_master_password");
200 BADCVAR("sys_colortranslation");
201 BADCVAR("sys_specialcharactertranslation");
202 BADCVAR("timeformat");
203 BADCVAR("timestamps");
204 BADPREFIX("developer_");
206 BADPREFIX("g_banned_list");
207 BADPREFIX("g_chat_flood_");
208 BADPREFIX("g_ghost_items");
209 BADPREFIX("g_playerstats_");
210 BADPREFIX("g_respawn_ghosts");
211 BADPREFIX("g_voice_flood_");
212 BADPREFIX("log_file");
214 BADPREFIX("sv_allowdownloads");
215 BADPREFIX("sv_autodemo");
216 BADPREFIX("sv_curl_");
217 BADPREFIX("sv_eventlog");
218 BADPREFIX("sv_logscores_");
219 BADPREFIX("sv_master");
220 BADPREFIX("sv_weaponstats_");
221 BADPREFIX("sv_waypointsprite_");
222 BADCVAR("rescan_pending");
224 // these can contain player IDs, so better hide
225 BADPREFIX("g_forced_team_");
228 BADCVAR("fraglimit");
229 BADCVAR("g_assault");
231 BADCVAR("g_ca_teams");
235 BADCVAR("g_domination");
236 BADCVAR("g_domination_default_teams");
237 BADCVAR("g_freezetag");
238 BADCVAR("g_freezetag_teams");
239 BADCVAR("g_keepaway");
240 BADCVAR("g_keyhunt");
241 BADCVAR("g_keyhunt_teams");
243 BADCVAR("g_nexball");
244 BADCVAR("g_onslaught");
246 BADCVAR("g_race_qualifying_timelimit");
248 BADCVAR("g_tdm_teams");
249 BADCVAR("leadlimit");
252 BADCVAR("timelimit");
256 BADCVAR("g_maplist");
257 BADCVAR("g_maplist_mostrecent");
261 d = cvar_defstring(k);
267 cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
268 if(strlen(cvar_changes) > 16384)
270 cvar_changes = "// too many settings have been changed to show them here\n";
275 // now check if the changes are actually gameplay relevant
277 // does nothing visible
278 BADCVAR("captureleadlimit_override");
279 BADCVAR("g_balance_kill_delay");
280 BADCVAR("g_ca_point_leadlimit");
281 BADCVAR("g_ctf_captimerecord_always");
282 BADCVAR("g_ctf_flag_glowtrails");
283 BADCVAR("g_ctf_flag_pickup_verbosename");
284 BADCVAR("g_domination_point_leadlimit");
285 BADCVAR("g_forced_respawn");
286 BADCVAR("g_keyhunt_point_leadlimit");
288 BADCVAR("g_nexball_goalleadlimit");
289 BADCVAR("leadlimit_and_fraglimit");
290 BADCVAR("leadlimit_override");
292 BADCVAR("sv_allow_fullbright");
293 BADCVAR("sv_checkforpacketsduringsleep");
294 BADCVAR("sv_fraginfo");
295 BADCVAR("sv_timeout");
296 BADPREFIX("sv_timeout_");
297 BADPREFIX("crypto_");
298 BADPREFIX("g_chat_");
299 BADPREFIX("g_ctf_captimerecord_");
300 BADPREFIX("g_maplist_votable_");
304 BADPREFIX("sv_cullentities_");
305 BADPREFIX("sv_fraginfo_");
306 BADPREFIX("sv_maxidle_");
307 BADPREFIX("sv_vote_");
308 BADPREFIX("timelimit_");
309 BADCVAR("gameversion");
310 BADPREFIX("gameversion_");
311 BADCVAR("sv_namechangetimer");
313 // allowed changes to server admins (please sync this to server.cfg)
317 // :%s,//\([^ ]*\).*,BADCVAR("\1");,
319 // yes, this does contain some redundant stuff, don't really care
320 BADCVAR("bot_config_file");
321 BADCVAR("bot_number");
322 BADCVAR("bot_prefix");
323 BADCVAR("bot_suffix");
324 BADCVAR("capturelimit_override");
325 BADCVAR("fraglimit_override");
327 BADCVAR("g_antilag");
328 BADCVAR("g_balance_teams");
329 BADCVAR("g_balance_teams_prevent_imbalance");
330 BADCVAR("g_balance_teams_scorefactor");
331 BADCVAR("g_ban_sync_trusted_servers");
332 BADCVAR("g_ban_sync_uri");
333 BADCVAR("g_ca_teams_override");
334 BADCVAR("g_ctf_ignore_frags");
335 BADCVAR("g_domination_point_limit");
336 BADCVAR("g_freezetag_teams_override");
337 BADCVAR("g_friendlyfire");
338 BADCVAR("g_fullbrightitems");
339 BADCVAR("g_fullbrightplayers");
340 BADCVAR("g_keyhunt_point_limit");
341 BADCVAR("g_keyhunt_teams_override");
342 BADCVAR("g_lms_lives_override");
343 BADCVAR("g_maplist");
344 BADCVAR("g_maplist_check_waypoints");
345 BADCVAR("g_maplist_mostrecent_count");
346 BADCVAR("g_maplist_shuffle");
347 BADCVAR("g_maplist_votable");
348 BADCVAR("g_maplist_votable_abstain");
349 BADCVAR("g_maplist_votable_nodetail");
350 BADCVAR("g_maplist_votable_suggestions");
351 BADCVAR("g_maxplayers");
352 BADCVAR("g_mirrordamage");
353 BADCVAR("g_nexball_goallimit");
354 BADCVAR("g_powerups");
355 BADCVAR("g_start_delay");
357 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
360 BADCVAR("maxplayers");
361 BADCVAR("minplayers");
362 BADCVAR("net_address");
364 BADCVAR("rcon_password");
365 BADCVAR("rcon_restricted_commands");
366 BADCVAR("rcon_restricted_password");
368 BADCVAR("sv_adminnick");
369 BADCVAR("sv_autoscreenshot");
370 BADCVAR("sv_autotaunt");
371 BADCVAR("sv_curl_defaulturl");
372 BADCVAR("sv_defaultcharacter");
373 BADCVAR("sv_defaultplayercolors");
374 BADCVAR("sv_defaultplayermodel");
375 BADCVAR("sv_defaultplayerskin");
376 BADCVAR("sv_maxidle");
377 BADCVAR("sv_maxrate");
379 BADCVAR("sv_public");
380 BADCVAR("sv_ready_restart");
381 BADCVAR("sv_status_privacy");
383 BADCVAR("sv_vote_call");
384 BADCVAR("sv_vote_commands");
385 BADCVAR("sv_vote_majority_factor");
386 BADCVAR("sv_vote_master");
387 BADCVAR("sv_vote_master_commands");
388 BADCVAR("sv_vote_master_password");
389 BADCVAR("sv_vote_simple_majority_factor");
390 BADCVAR("teamplay_mode");
391 BADCVAR("timelimit_override");
392 BADCVAR("g_spawnshieldtime");
393 BADPREFIX("g_warmup_");
394 BADPREFIX("sv_ready_restart_");
396 // mutators that announce themselves properly to the server browser
397 BADCVAR("g_instagib");
398 BADCVAR("g_new_toys");
400 BADCVAR("g_grappling_hook");
401 BADCVAR("g_jetpack");
408 cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
409 if(strlen(cvar_purechanges) > 16384)
411 cvar_purechanges = "// too many settings have been changed to show them here\n";
415 ++cvar_purechanges_count;
416 // WARNING: this variable is used for the server list
417 // NEVER dare to skip this code!
418 // Hacks to intentionally appearing as "pure server" even though you DO have
419 // modified settings may be punished by removal from the server list.
420 // You can do to the variables cvar_changes and cvar_purechanges all you want,
424 if(cvar_changes == "")
425 cvar_changes = "// this server runs at default server settings\n";
427 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
428 cvar_changes = strzone(cvar_changes);
429 if(cvar_purechanges == "")
430 cvar_purechanges = "// this server runs at default gameplay settings\n";
432 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
433 cvar_purechanges = strzone(cvar_purechanges);
436 void detect_maptype()
445 o_x += random() * (world.maxs_x - world.mins_x);
446 o_y += random() * (world.maxs_y - world.mins_y);
447 o_z += random() * (world.maxs_z - world.mins_z);
449 tracebox(o, PL_MIN, PL_MAX, o - '0 0 32768', MOVE_WORLDONLY, world);
450 if(trace_fraction == 1)
455 for(i = 0; i < 64; i += 4)
457 tracebox(o, '-1 -1 -1' * i, '1 1 1' * i, o - '0 0 32768', MOVE_WORLDONLY, world);
458 if(trace_fraction == 1)
460 print(ftos(i), " -> ", vtos(trace_endpos), "\n");
469 float RandomSeed_Send(entity to, float sf)
471 WriteByte(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
472 WriteShort(MSG_ENTITY, self.cnt);
475 void RandomSeed_Think()
477 self.cnt = bound(0, floor(random() * 65536), 65535);
478 self.nextthink = time + 5;
482 void RandomSeed_Spawn()
484 randomseed = spawn();
485 randomseed.think = RandomSeed_Think;
486 Net_LinkEntity(randomseed, FALSE, 0, RandomSeed_Send);
491 self.think(); // sets random seed and nextthink
495 void spawnfunc___init_dedicated_server(void)
497 // handler for _init/_init map (only for dedicated server initialization)
499 world_initialized = -1; // don't complain
501 cvar_string = cvar_string_normal;
502 cvar_set = cvar_set_normal;
504 remove = remove_unsafely;
508 e.think = GotoFirstMap;
509 e.nextthink = time; // this is usually 1 at this point
512 e.classname = "info_player_deathmatch"; // safeguard against player joining
514 self.classname = "worldspawn"; // safeguard against various stuff ;)
516 // needs to be done so early because of the constants they create
517 CALL_ACCUMULATED_FUNCTION(RegisterWeapons);
518 CALL_ACCUMULATED_FUNCTION(RegisterMonsters);
519 CALL_ACCUMULATED_FUNCTION(RegisterGametypes);
520 CALL_ACCUMULATED_FUNCTION(RegisterNotifications);
521 CALL_ACCUMULATED_FUNCTION(RegisterDeathtypes);
522 CALL_ACCUMULATED_FUNCTION(RegisterBuffs);
525 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
528 void Map_MarkAsRecent(string m);
529 float world_already_spawned;
531 void Item_ItemsTime_Init();
532 void ClientInit_Spawn();
533 void WeaponStats_Init();
534 void WeaponStats_Shutdown();
535 void spawnfunc_worldspawn (void)
537 float fd, l, i, j, n;
541 cvar_string = cvar_string_normal;
542 cvar_set = cvar_set_normal;
544 if(world_already_spawned)
545 error("world already spawned - you may have EXACTLY ONE worldspawn!");
546 world_already_spawned = TRUE;
548 remove = remove_safely; // during spawning, watch what you remove!
550 cvar_changes_init(); // do this very early now so it REALLY matches the server config
552 compressShortVector_init();
555 head = nextent(world);
560 head = nextent(head);
563 server_is_dedicated = (stof(cvar_defstring("is_dedicated")) ? TRUE : FALSE);
565 // needs to be done so early because of the constants they create
566 CALL_ACCUMULATED_FUNCTION(RegisterWeapons);
567 CALL_ACCUMULATED_FUNCTION(RegisterMonsters);
568 CALL_ACCUMULATED_FUNCTION(RegisterGametypes);
569 CALL_ACCUMULATED_FUNCTION(RegisterNotifications);
570 CALL_ACCUMULATED_FUNCTION(RegisterDeathtypes);
571 CALL_ACCUMULATED_FUNCTION(RegisterBuffs);
573 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
575 TemporaryDB = db_create();
580 // 1 FLICKER (first variety)
581 lightstyle(1, "mmnmmommommnonmmonqnmmo");
583 // 2 SLOW STRONG PULSE
584 lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
586 // 3 CANDLE (first variety)
587 lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
590 lightstyle(4, "mamamamamama");
593 lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
595 // 6 FLICKER (second variety)
596 lightstyle(6, "nmonqnmomnmomomno");
598 // 7 CANDLE (second variety)
599 lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
601 // 8 CANDLE (third variety)
602 lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
604 // 9 SLOW STROBE (fourth variety)
605 lightstyle(9, "aaaaaaaazzzzzzzz");
607 // 10 FLUORESCENT FLICKER
608 lightstyle(10, "mmamammmmammamamaaamammma");
610 // 11 SLOW PULSE NOT FADE TO BLACK
611 lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
613 // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
618 if(autocvar_g_campaign)
621 Map_MarkAsRecent(mapname);
623 PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
625 precache_model ("null"); // we need this one before InitGameplayMode
631 bot_waypoints_for_items = autocvar_g_waypoints_for_items;
632 if(bot_waypoints_for_items == 1)
633 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
634 bot_waypoints_for_items = 0;
638 WaypointSprite_Init();
640 GameLogInit(); // prepare everything
642 // changing the logic generating it is okay. But:
643 // it HAS to stay <= 64 chars
644 // character set: ASCII 33-126 without the following characters: : ; ' " \ $
645 if(autocvar_sv_eventlog)
647 s = sprintf("%d.%s.%06d", ftos(autocvar_sv_eventlog_files_counter), strftime(FALSE, "%s"), floor(random() * 1000000));
648 matchid = strzone(s);
650 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
651 s = ":gameinfo:mutators:LIST";
654 MUTATOR_CALLHOOK(BuildMutatorsString);
657 // simple, probably not good in the mutator system
658 if(autocvar_g_grappling_hook)
659 s = strcat(s, ":grappling_hook");
661 // initialiation stuff, not good in the mutator system
662 if(!autocvar_g_use_ammunition)
663 s = strcat(s, ":no_use_ammunition");
665 // initialiation stuff, not good in the mutator system
666 if(autocvar_g_pickup_items == 0)
667 s = strcat(s, ":no_pickup_items");
668 if(autocvar_g_pickup_items > 0)
669 s = strcat(s, ":pickup_items");
671 // initialiation stuff, not good in the mutator system
672 if(autocvar_g_weaponarena != "0")
673 s = strcat(s, ":", autocvar_g_weaponarena, " arena");
675 // TODO to mutator system
676 if(autocvar_g_norecoil)
677 s = strcat(s, ":norecoil");
679 // TODO to mutator system
680 if(autocvar_g_powerups == 0)
681 s = strcat(s, ":no_powerups");
682 if(autocvar_g_powerups > 0)
683 s = strcat(s, ":powerups");
686 GameLogEcho(":gameinfo:end");
689 matchid = strzone(ftos(random()));
691 cvar_set("nextmap", "");
695 if(autocvar_g_campaign)
701 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
703 if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
705 fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
708 while((s = fgets(fd)))
710 l = tokenize_console(s);
715 print("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
716 print(" cdtrack ", argv(2), "\n");
718 else if(argv(0) == "fog")
720 print("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
721 print(" \"fog\" \"", s, "\"\n");
723 else if(argv(0) == "set")
725 print("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
726 print(" clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
728 else if(argv(0) != "//")
730 print("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
731 print(" clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
741 addstat(STAT_SWITCHWEAPON, AS_INT, switchweapon);
742 addstat(STAT_SWITCHINGWEAPON, AS_INT, switchingweapon);
743 addstat(STAT_GAMESTARTTIME, AS_FLOAT, stat_game_starttime);
744 addstat(STAT_ROUNDSTARTTIME, AS_FLOAT, stat_round_starttime);
745 addstat(STAT_ALLOW_OLDVORTEXBEAM, AS_INT, stat_allow_oldvortexbeam);
748 addstat(STAT_STRENGTH_FINISHED, AS_FLOAT, strength_finished);
749 addstat(STAT_INVINCIBLE_FINISHED, AS_FLOAT, invincible_finished);
750 addstat(STAT_SUPERWEAPONS_FINISHED, AS_FLOAT, superweapons_finished);
751 addstat(STAT_PRESSED_KEYS, AS_FLOAT, pressedkeys);
752 addstat(STAT_FUEL, AS_INT, ammo_fuel);
753 addstat(STAT_PLASMA, AS_INT, ammo_plasma);
754 addstat(STAT_SHOTORG, AS_INT, stat_shotorg);
755 addstat(STAT_LEADLIMIT, AS_FLOAT, stat_leadlimit);
756 addstat(STAT_WEAPON_CLIPLOAD, AS_INT, clip_load);
757 addstat(STAT_WEAPON_CLIPSIZE, AS_INT, clip_size);
758 addstat(STAT_LAST_PICKUP, AS_FLOAT, last_pickup);
759 addstat(STAT_HIT_TIME, AS_FLOAT, hit_time);
760 addstat(STAT_DAMAGE_DEALT_TOTAL, AS_INT, damage_dealt_total);
761 addstat(STAT_TYPEHIT_TIME, AS_FLOAT, typehit_time);
762 addstat(STAT_LAYED_MINES, AS_INT, minelayer_mines);
764 addstat(STAT_VORTEX_CHARGE, AS_FLOAT, vortex_charge);
765 addstat(STAT_VORTEX_CHARGEPOOL, AS_FLOAT, vortex_chargepool_ammo);
767 addstat(STAT_HAGAR_LOAD, AS_INT, hagar_load);
769 addstat(STAT_ARC_HEAT, AS_FLOAT, arc_heat_percent);
772 addstat(STAT_ARMOR_LARGE_TIME, AS_FLOAT, item_armor_large_time);
773 addstat(STAT_HEALTH_MEGA_TIME, AS_FLOAT, item_health_mega_time);
774 addstat(STAT_INVISIBLE_TIME, AS_FLOAT, item_invisible_time);
775 addstat(STAT_SPEED_TIME, AS_FLOAT, item_speed_time);
776 addstat(STAT_EXTRALIFE_TIME, AS_FLOAT, item_extralife_time);
777 addstat(STAT_STRENGTH_TIME, AS_FLOAT, item_strength_time);
778 addstat(STAT_SHIELD_TIME, AS_FLOAT, item_shield_time);
779 addstat(STAT_FUELREGEN_TIME, AS_FLOAT, item_fuelregen_time);
780 addstat(STAT_JETPACK_TIME, AS_FLOAT, item_jetpack_time);
781 addstat(STAT_SUPERWEAPONS_TIME, AS_FLOAT, item_superweapons_time);
782 Item_ItemsTime_Init();
785 addstat(STAT_FROZEN, AS_INT, frozen);
786 addstat(STAT_REVIVE_PROGRESS, AS_FLOAT, revive_progress);
788 // g_movementspeed hack
789 addstat(STAT_MOVEVARS_AIRSPEEDLIMIT_NONQW, AS_FLOAT, stat_sv_airspeedlimit_nonqw);
790 addstat(STAT_MOVEVARS_MAXSPEED, AS_FLOAT, stat_sv_maxspeed);
791 addstat(STAT_MOVEVARS_AIRACCEL_QW, AS_FLOAT, stat_sv_airaccel_qw);
792 addstat(STAT_MOVEVARS_AIRSTRAFEACCEL_QW, AS_FLOAT, stat_sv_airstrafeaccel_qw);
795 addstat(STAT_SECRETS_TOTAL, AS_FLOAT, stat_secrets_total);
796 addstat(STAT_SECRETS_FOUND, AS_FLOAT, stat_secrets_found);
799 addstat(STAT_MONSTERS_TOTAL, AS_FLOAT, stat_monsters_total);
800 addstat(STAT_MONSTERS_KILLED, AS_FLOAT, stat_monsters_killed);
803 addstat(STAT_RESPAWN_TIME, AS_FLOAT, stat_respawn_time);
805 next_pingtime = time + 5;
809 // set up information replies for clients and server to use
810 maplist_reply = strzone(getmaplist());
811 lsmaps_reply = strzone(getlsmaps());
812 monsterlist_reply = strzone(getmonsterlist());
813 for(i = 0; i < 10; ++i)
817 records_reply[i] = strzone(s);
819 ladder_reply = strzone(getladder());
820 rankings_reply = strzone(getrankings());
825 PingPLReport_Spawn();
829 localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
831 // fill sv_curl_serverpackages from .serverpackage files
832 if(autocvar_sv_curl_serverpackages_auto)
835 n = tokenize_console(cvar_string("sv_curl_serverpackages"));
836 for(i = 0; i < n; ++i)
837 if(substring(argv(i), -18, -1) != "-serverpackage.txt")
838 if(substring(argv(i), -14, -1) != ".serverpackage") // OLD legacy
839 s = strcat(s, " ", argv(i));
840 fd = search_begin("*-serverpackage.txt", TRUE, FALSE);
843 j = search_getsize(fd);
844 for(i = 0; i < j; ++i)
845 s = strcat(s, " ", search_getfilename(fd, i));
848 fd = search_begin("*.serverpackage", TRUE, FALSE);
851 j = search_getsize(fd);
852 for(i = 0; i < j; ++i)
853 s = strcat(s, " ", search_getfilename(fd, i));
856 cvar_set("sv_curl_serverpackages", substring(s, 1, -1));
859 // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
861 // physics/balance/config changes that count as mod
862 if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
863 modname = cvar_string("g_mod_physics");
864 if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance"))
865 modname = cvar_string("g_mod_balance");
866 if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
867 modname = cvar_string("g_mod_config");
868 // extra mutators that deserve to count as mod
869 MUTATOR_CALLHOOK(SetModname);
872 modname = strzone(modname);
874 WinningConditionHelper(); // set worldstatus
876 world_initialized = 1;
879 void spawnfunc_light (void)
881 //makestatic (self); // Who the f___ did that?
887 return MapInfo_Type_ToString(MapInfo_LoadedGametype);
895 float Map_Count, Map_Current;
896 string Map_Current_Name;
898 // NOTE: this now expects the map list to be already tokenized and the count in Map_Count
899 float GetMaplistPosition()
905 idx = autocvar_g_maplist_index;
912 for(pos = 0; pos < Map_Count; ++pos)
916 // resume normal maplist rotation if current map is not in g_maplist
920 float MapHasRightSize(string map)
923 if(currentbots || autocvar_bot_number || player_count < autocvar_minplayers)
924 if(autocvar_g_maplist_check_waypoints)
926 dprint("checkwp "); dprint(map);
927 if(!fexists(strcat("maps/", map, ".waypoints")))
929 dprint(": no waypoints\n");
932 dprint(": has waypoints\n");
935 // open map size restriction file
936 dprint("opensize "); dprint(map);
937 fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
940 float mapmin, mapmax;
942 mapmin = stof(fgets(fh));
943 mapmax = stof(fgets(fh));
945 if(player_count < mapmin)
947 dprint("not enough\n");
950 if(player_count > mapmax)
952 dprint("too many\n");
955 dprint("right size\n");
958 dprint(": not found\n");
962 string Map_Filename(float position)
964 return strcat("maps/", argv(position), ".bsp");
967 string strwords(string s, float w)
970 for(endpos = 0; w && endpos >= 0; --w)
971 endpos = strstrofs(s, " ", endpos + 1);
975 return substring(s, 0, endpos);
978 float strhasword(string s, string w)
980 return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
983 void Map_MarkAsRecent(string m)
985 cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", autocvar_g_maplist_mostrecent), max(0, autocvar_g_maplist_mostrecent_count)));
988 float Map_IsRecent(string m)
990 return strhasword(autocvar_g_maplist_mostrecent, m);
993 float Map_Check(float position, float pass)
997 map_next = argv(position);
1000 if(Map_IsRecent(map_next))
1003 filename = Map_Filename(position);
1004 if(MapInfo_CheckMap(map_next))
1008 if(MapHasRightSize(map_next))
1013 dprint( "Couldn't select '", filename, "'..\n" );
1018 void Map_Goto_SetStr(string nextmapname)
1020 if(getmapname_stored != "")
1021 strunzone(getmapname_stored);
1022 if(nextmapname == "")
1023 getmapname_stored = "";
1025 getmapname_stored = strzone(nextmapname);
1028 void Map_Goto_SetFloat(float position)
1030 cvar_set("g_maplist_index", ftos(position));
1031 Map_Goto_SetStr(argv(position));
1034 void Map_Goto(float reinit)
1036 MapInfo_LoadMap(getmapname_stored, reinit);
1039 // return codes of map selectors:
1040 // -1 = temporary failure (that is, try some method that is guaranteed to succeed)
1041 // -2 = permanent failure
1042 float() MaplistMethod_Iterate = // usual method
1046 dprint("Trying MaplistMethod_Iterate\n");
1048 for(pass = 1; pass <= 2; ++pass)
1050 for(i = 1; i < Map_Count; ++i)
1053 mapindex = (i + Map_Current) % Map_Count;
1054 if(Map_Check(mapindex, pass))
1061 float() MaplistMethod_Repeat = // fallback method
1063 dprint("Trying MaplistMethod_Repeat\n");
1065 if(Map_Check(Map_Current, 2))
1070 float() MaplistMethod_Random = // random map selection
1074 dprint("Trying MaplistMethod_Random\n");
1078 for(i = 0; i <= imax; ++i)
1081 mapindex = (Map_Current + floor(random() * (Map_Count - 1) + 1)) % Map_Count; // any OTHER map
1082 if(Map_Check(mapindex, 1))
1088 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
1089 // the exponent sets a bias on the map selection:
1090 // the higher the exponent, the less likely "shortly repeated" same maps are
1092 float i, j, imax, insertpos;
1094 dprint("Trying MaplistMethod_Shuffle\n");
1098 for(i = 0; i <= imax; ++i)
1102 // now reinsert this at another position
1103 insertpos = pow(random(), 1 / exponent); // ]0, 1]
1104 insertpos = insertpos * (Map_Count - 1); // ]0, Map_Count - 1]
1105 insertpos = ceil(insertpos) + 1; // {2, 3, 4, ..., Map_Count}
1106 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
1108 // insert the current map there
1110 for(j = 1; j < insertpos; ++j) // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
1111 newlist = strcat(newlist, " ", argv(j));
1112 newlist = strcat(newlist, " ", argv(0)); // now insert the just selected map
1113 for(j = insertpos; j < Map_Count; ++j) // i == Map_Count: no loop, has just been inserted as last
1114 newlist = strcat(newlist, " ", argv(j));
1115 newlist = substring(newlist, 1, strlen(newlist) - 1);
1116 cvar_set("g_maplist", newlist);
1117 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1119 // NOTE: the selected map has just been inserted at (insertpos-1)th position
1120 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
1121 if(Map_Check(Map_Current, 1))
1129 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1131 for (i = 0; i < Map_Count; ++i)
1132 if (Map_Check(i, 2))
1136 bprint( "Maplist contains no usable maps! Resetting it to default map list.\n" );
1137 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags() | MAPINFO_FLAG_NOAUTOMAPLIST));
1138 if(autocvar_g_maplist_shuffle)
1140 localcmd("\nmenu_cmd sync\n");
1141 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1144 error("empty maplist, cannot select a new map");
1145 Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
1147 if(Map_Current_Name)
1148 strunzone(Map_Current_Name);
1149 Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
1150 // this may or may not be correct, but who cares, in the worst case a map
1151 // isn't chosen in the first pass that should have been
1162 if(autocvar_g_maplist_shuffle > 0)
1163 nextMap = MaplistMethod_Shuffle(autocvar_g_maplist_shuffle + 1);
1166 if(autocvar_g_maplist_selectrandom)
1167 nextMap = MaplistMethod_Random();
1170 nextMap = MaplistMethod_Iterate();
1173 nextMap = MaplistMethod_Repeat();
1177 Map_Goto_SetFloat(nextMap);
1178 return getmapname_stored;
1184 float DoNextMapOverride(float reinit)
1186 if(autocvar_g_campaign)
1188 CampaignPostIntermission();
1189 alreadychangedlevel = TRUE;
1192 if(autocvar_quit_when_empty)
1194 if(player_count <= currentbots)
1197 alreadychangedlevel = TRUE;
1201 if(autocvar_quit_and_redirect != "")
1203 redirection_target = strzone(autocvar_quit_and_redirect);
1204 alreadychangedlevel = TRUE;
1207 if (!reinit && autocvar_samelevel) // if samelevel is set, stay on same level
1209 localcmd("restart\n");
1210 alreadychangedlevel = TRUE;
1213 if(autocvar_nextmap != "")
1216 m = GameTypeVote_MapInfo_FixName(autocvar_nextmap);
1217 cvar_set("nextmap",m);
1219 if(!m || gametypevote)
1221 if(autocvar_sv_vote_gametype)
1227 if(MapInfo_CheckMap(m))
1231 alreadychangedlevel = TRUE;
1235 if(!reinit && autocvar_lastlevel)
1237 cvar_settemp_restore();
1238 localcmd("set lastlevel 0\ntogglemenu 1\n");
1239 alreadychangedlevel = TRUE;
1245 void GotoNextMap(float reinit)
1250 if (alreadychangedlevel)
1252 alreadychangedlevel = TRUE;
1256 nextMap = GetNextMap();
1258 error("Everything is broken - cannot find a next map. Please report this to the developers.");
1267 When the player presses attack or jump, change to the next level
1270 .float autoscreenshot;
1271 void IntermissionThink()
1273 FixIntermissionClient(self);
1275 float server_screenshot = (autocvar_sv_autoscreenshot && self.cvar_cl_autoscreenshot);
1276 float client_screenshot = (self.cvar_cl_autoscreenshot == 2);
1278 if( (server_screenshot || client_screenshot)
1279 && ((self.autoscreenshot > 0) && (time > self.autoscreenshot)) )
1281 self.autoscreenshot = -1;
1282 if(IS_REAL_CLIENT(self)) { stuffcmd(self, sprintf("\nscreenshot screenshots/autoscreenshot/%s-%s.jpg; echo \"^5A screenshot has been taken at request of the server.\"\n", GetMapname(), strftime(FALSE, "%s"))); }
1286 if (time < intermission_exittime)
1289 if(!mapvote_initialized)
1290 if (time < intermission_exittime + 10 && !(self.BUTTON_ATCK || self.BUTTON_JUMP || self.BUTTON_ATCK2 || self.BUTTON_HOOK || self.BUTTON_USE))
1300 Returns the entity to view from
1304 entity FindIntermission()
1309 // look for info_intermission first
1310 spot = find (world, classname, "info_intermission");
1312 { // pick a random one
1316 spot = find (spot, classname, "info_intermission");
1318 spot = find (spot, classname, "info_intermission");
1324 // then look for the start position
1325 spot = find (world, classname, "info_player_start");
1329 // testinfo_player_start is only found in regioned levels
1330 spot = find (world, classname, "testplayerstart");
1334 // then look for the start position
1335 spot = find (world, classname, "info_player_deathmatch");
1339 //objerror ("FindIntermission: no spot");
1345 ===============================================================================
1349 ===============================================================================
1352 void DumpStats(float final)
1361 to_console = autocvar_sv_logscores_console;
1362 to_eventlog = autocvar_sv_eventlog;
1363 to_file = autocvar_sv_logscores_file;
1367 to_console = TRUE; // always print printstats replies
1368 to_eventlog = FALSE; // but never print them to the event log
1372 if(autocvar_sv_eventlog_console)
1373 to_console = FALSE; // otherwise we get the output twice
1379 s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1389 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1393 fputs(file, strcat(s, "\n"));
1396 s = strcat(":labels:player:", GetPlayerScoreString(world, 0));
1402 fputs(file, strcat(s, "\n"));
1404 FOR_EACH_CLIENT(other)
1406 if ((IS_REAL_CLIENT(other)) || (IS_BOT_CLIENT(other) && autocvar_sv_logscores_bots))
1408 s = strcat(":player:see-labels:", GetPlayerScoreString(other, 0), ":");
1409 s = strcat(s, ftos(rint(time - other.jointime)), ":");
1410 if(IS_PLAYER(other) || other.caplayer == 1 || g_lms)
1411 s = strcat(s, ftos(other.team), ":");
1413 s = strcat(s, "spectator:");
1416 print(s, other.netname, "\n");
1418 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname));
1420 fputs(file, strcat(s, other.netname, "\n"));
1426 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1432 fputs(file, strcat(s, "\n"));
1434 for(i = 1; i < 16; ++i)
1436 s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1437 s = strcat(s, ":", ftos(i));
1443 fputs(file, strcat(s, "\n"));
1450 GameLogEcho(":end");
1453 fputs(file, ":end\n");
1458 void FixIntermissionClient(entity e)
1461 if(!e.autoscreenshot) // initial call
1463 e.autoscreenshot = time + 0.8; // used for autoscreenshot
1465 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1466 e.solid = SOLID_NOT;
1467 e.movetype = MOVETYPE_NONE;
1468 e.takedamage = DAMAGE_NO;
1471 e.weaponentity.effects = EF_NODRAW;
1472 if (e.weaponentity.weaponentity)
1473 e.weaponentity.weaponentity.effects = EF_NODRAW;
1475 if(IS_REAL_CLIENT(e))
1477 stuffcmd(e, "\nscr_printspeed 1000000\n");
1478 s = autocvar_sv_intermission_cdtrack;
1480 stuffcmd(e, strcat("\ncd loop ", s, "\n"));
1482 WriteByte(MSG_ONE, SVC_INTERMISSION);
1488 go to the next level for deathmatch
1489 only called if a time or frag limit has expired
1495 intermission_running = 1;
1497 // enforce a wait time before allowing changelevel
1498 if(player_count > 0)
1499 intermission_exittime = time + autocvar_sv_mapchange_delay;
1501 intermission_exittime = -1;
1504 WriteByte (MSG_ALL, SVC_CDTRACK);
1505 WriteByte (MSG_ALL, 3);
1506 WriteByte (MSG_ALL, 3);
1507 // done in FixIntermission
1510 //pos = FindIntermission ();
1517 PlayerStats_GameReport(TRUE);
1518 WeaponStats_Shutdown();
1520 Kill_Notification(NOTIF_ALL, world, MSG_CENTER, 0); // kill all centerprints now
1522 if(autocvar_sv_eventlog)
1523 GameLogEcho(":gameover");
1527 FOR_EACH_PLAYER(other) {
1528 FixIntermissionClient(other);
1530 bprint(other.netname, " ^7wins.\n");
1533 if(autocvar_g_campaign)
1534 CampaignPreIntermission();
1536 MUTATOR_CALLHOOK(MatchEnd);
1538 localcmd("\nsv_hook_gameend\n");
1545 Exit deathmatch games upon conditions
1548 void CheckRules_Player()
1550 if (gameover) // someone else quit the game already
1553 if(self.deadflag == DEAD_NO)
1554 self.play_time += frametime;
1556 // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1557 // (div0: and that in CheckRules_World please)
1560 float checkrules_equality;
1561 float checkrules_suddendeathwarning;
1562 float checkrules_suddendeathend;
1563 float checkrules_overtimesadded; //how many overtimes have been already added
1565 const float WINNING_NO = 0; // no winner, but time limits may terminate the game
1566 const float WINNING_YES = 1; // winner found
1567 const float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1568 const float WINNING_STARTSUDDENDEATHOVERTIME = 3; // no winner, enter suddendeath overtime NOW
1570 float InitiateSuddenDeath()
1572 // Check first whether normal overtimes could be added before initiating suddendeath mode
1573 // - for this timelimit_overtime needs to be >0 of course
1574 // - also check the winning condition calculated in the previous frame and only add normal overtime
1575 // again, if at the point at which timelimit would be extended again, still no winner was found
1576 if (!autocvar_g_campaign && (checkrules_overtimesadded >= 0) && (checkrules_overtimesadded < autocvar_timelimit_overtimes || autocvar_timelimit_overtimes < 0) && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1578 return 1; // need to call InitiateOvertime later
1582 if(!checkrules_suddendeathend)
1584 if(autocvar_g_campaign)
1585 checkrules_suddendeathend = time; // no suddendeath in campaign
1587 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1588 if(g_race && !g_race_qualifying)
1589 race_StartCompleting();
1595 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1597 ++checkrules_overtimesadded;
1598 //add one more overtime by simply extending the timelimit
1600 tl = autocvar_timelimit;
1601 tl += autocvar_timelimit_overtime;
1602 cvar_set("timelimit", ftos(tl));
1604 Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime * 60);
1607 float GetWinningCode(float fraglimitreached, float equality)
1609 if(autocvar_g_campaign == 1)
1610 if(fraglimitreached)
1617 if(fraglimitreached)
1618 return WINNING_STARTSUDDENDEATHOVERTIME;
1620 return WINNING_NEVER;
1622 if(fraglimitreached)
1628 // set the .winning flag for exactly those players with a given field value
1629 void SetWinners(.float field, float value)
1632 FOR_EACH_PLAYER(head)
1633 head.winning = (head.field == value);
1636 // set the .winning flag for those players with a given field value
1637 void AddWinners(.float field, float value)
1640 FOR_EACH_PLAYER(head)
1641 if(head.field == value)
1645 // clear the .winning flags
1646 void ClearWinners(void)
1649 FOR_EACH_PLAYER(head)
1653 // Onslaught winning condition:
1654 // game terminates if only one team has a working generator (or none)
1655 float WinningCondition_Onslaught()
1658 float t1, t2, t3, t4;
1660 WinningConditionHelper(); // set worldstatus
1665 // first check if the game has ended
1666 t1 = t2 = t3 = t4 = 0;
1667 head = find(world, classname, "onslaught_generator");
1670 if (head.health > 0)
1672 if (head.team == NUM_TEAM_1) t1 = 1;
1673 if (head.team == NUM_TEAM_2) t2 = 1;
1674 if (head.team == NUM_TEAM_3) t3 = 1;
1675 if (head.team == NUM_TEAM_4) t4 = 1;
1677 head = find(head, classname, "onslaught_generator");
1679 if (t1 + t2 + t3 + t4 < 2)
1681 // game over, only one team remains (or none)
1683 if (t1) SetWinners(team, NUM_TEAM_1);
1684 if (t2) SetWinners(team, NUM_TEAM_2);
1685 if (t3) SetWinners(team, NUM_TEAM_3);
1686 if (t4) SetWinners(team, NUM_TEAM_4);
1687 dprint("Have a winner, ending game.\n");
1691 // Two or more teams remain
1695 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1696 // they win. Otherwise the defending team wins once the timelimit passes.
1697 void assault_new_round();
1698 float WinningCondition_Assault()
1702 WinningConditionHelper(); // set worldstatus
1704 status = WINNING_NO;
1705 // as the timelimit has not yet passed just assume the defending team will win
1706 if(assault_attacker_team == NUM_TEAM_1)
1708 SetWinners(team, NUM_TEAM_2);
1712 SetWinners(team, NUM_TEAM_1);
1716 ent = find(world, classname, "target_assault_roundend");
1719 if(ent.winning) // round end has been triggered by attacking team
1721 bprint("ASSAULT: round completed...\n");
1722 SetWinners(team, assault_attacker_team);
1724 TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 666 - TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 0));
1726 if(ent.cnt == 1 || autocvar_g_campaign) // this was the second round
1728 status = WINNING_YES;
1735 assault_new_round();
1744 // LMS winning condition: game terminates if and only if there's at most one
1745 // one player who's living lives. Top two scores being equal cancels the time
1747 float WinningCondition_LMS()
1754 have_player = FALSE;
1755 have_players = FALSE;
1756 l = LMS_NewPlayerLives();
1758 head = find(world, classname, "player");
1761 head2 = find(head, classname, "player");
1763 have_players = TRUE;
1767 // we have at least one player
1770 // two or more active players - continue with the game
1774 // exactly one player?
1777 SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1781 // game still running (that is, nobody got removed from the game by a frag yet)? then continue
1787 // and assign him his first place
1788 PlayerScore_Add(head, SP_LMS_RANK, 1);
1795 // nobody is playing at all...
1798 // wait for players...
1802 // SNAFU (maybe a draw game?)
1804 dprint("No players, ending game.\n");
1809 // When we get here, we have at least two players who are actually LIVING,
1810 // now check if the top two players have equal score.
1811 WinningConditionHelper();
1814 if(WinningConditionHelper_winner)
1815 WinningConditionHelper_winner.winning = TRUE;
1816 if(WinningConditionHelper_topscore == WinningConditionHelper_secondscore)
1817 return WINNING_NEVER;
1819 // Top two have different scores? Way to go for our beloved TIMELIMIT!
1823 void ShuffleMaplist()
1825 cvar_set("g_maplist", shufflewords(autocvar_g_maplist));
1829 float WinningCondition_Scores(float limit, float leadlimit)
1833 // TODO make everything use THIS winning condition (except LMS)
1834 WinningConditionHelper();
1838 team1_score = TeamScore_GetCompareValue(NUM_TEAM_1);
1839 team2_score = TeamScore_GetCompareValue(NUM_TEAM_2);
1840 team3_score = TeamScore_GetCompareValue(NUM_TEAM_3);
1841 team4_score = TeamScore_GetCompareValue(NUM_TEAM_4);
1845 if(WinningConditionHelper_winner)
1846 WinningConditionHelper_winner.winning = 1;
1847 if(WinningConditionHelper_winnerteam >= 0)
1848 SetWinners(team, WinningConditionHelper_winnerteam);
1850 if(WinningConditionHelper_lowerisbetter)
1852 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1853 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1857 if(WinningConditionHelper_zeroisworst)
1858 leadlimit = 0; // not supported in this mode
1860 if(g_dm || g_tdm || g_ca || g_freezetag || (g_race && !g_race_qualifying) || g_nexball)
1861 // these modes always score in increments of 1, thus this makes sense
1863 if(leaderfrags != WinningConditionHelper_topscore)
1865 leaderfrags = WinningConditionHelper_topscore;
1868 if (leaderfrags == limit - 1)
1869 Send_Notification(NOTIF_ALL, world, MSG_ANNCE, ANNCE_REMAINING_FRAG_1);
1870 else if (leaderfrags == limit - 2)
1871 Send_Notification(NOTIF_ALL, world, MSG_ANNCE, ANNCE_REMAINING_FRAG_2);
1872 else if (leaderfrags == limit - 3)
1873 Send_Notification(NOTIF_ALL, world, MSG_ANNCE, ANNCE_REMAINING_FRAG_3);
1877 limitreached = FALSE;
1879 if(WinningConditionHelper_topscore >= limit)
1880 limitreached = TRUE;
1883 float leadlimitreached;
1884 leadlimitreached = (WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1885 if(autocvar_leadlimit_and_fraglimit)
1886 limitreached = (limitreached && leadlimitreached);
1888 limitreached = (limitreached || leadlimitreached);
1892 game_completion_ratio = max(game_completion_ratio, bound(0, WinningConditionHelper_topscore / limit, 1));
1894 return GetWinningCode(
1895 WinningConditionHelper_topscore && limitreached,
1896 WinningConditionHelper_equality
1900 float WinningCondition_Race(float fraglimit)
1911 if(p.race_completed)
1916 wc = WinningCondition_Scores(fraglimit, 0);
1918 // ALWAYS initiate overtime, unless EVERYONE has finished the race!
1919 if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1920 // do NOT support equality when the laps are all raced!
1921 return WINNING_STARTSUDDENDEATHOVERTIME;
1923 return WINNING_NEVER;
1926 float WinningCondition_QualifyingThenRace(float limit)
1929 wc = WinningCondition_Scores(limit, 0);
1931 // NEVER initiate overtime
1932 if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1940 float WinningCondition_RanOutOfSpawns()
1944 if(have_team_spawns <= 0)
1947 if(autocvar_g_spawn_useallspawns <= 0)
1950 if(!some_spawn_has_been_used)
1953 team1_score = team2_score = team3_score = team4_score = 0;
1955 FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
1957 if(head.team == NUM_TEAM_1)
1959 else if(head.team == NUM_TEAM_2)
1961 else if(head.team == NUM_TEAM_3)
1963 else if(head.team == NUM_TEAM_4)
1967 for(head = world; (head = find(head, classname, "info_player_deathmatch")) != world; )
1969 if(head.team == NUM_TEAM_1)
1971 else if(head.team == NUM_TEAM_2)
1973 else if(head.team == NUM_TEAM_3)
1975 else if(head.team == NUM_TEAM_4)
1980 if(team1_score + team2_score + team3_score + team4_score == 0)
1982 checkrules_equality = TRUE;
1985 else if(team1_score + team2_score + team3_score + team4_score == 1)
1990 else if(team2_score)
1992 else if(team3_score)
1994 else // if(team4_score)
1996 CheckAllowedTeams(world);
1997 for(i = 0; i < MAX_TEAMSCORE; ++i)
1999 if(t != NUM_TEAM_1) if(c1 >= 0) TeamScore_AddToTeam(NUM_TEAM_1, i, -1000);
2000 if(t != NUM_TEAM_2) if(c2 >= 0) TeamScore_AddToTeam(NUM_TEAM_2, i, -1000);
2001 if(t != NUM_TEAM_3) if(c3 >= 0) TeamScore_AddToTeam(NUM_TEAM_3, i, -1000);
2002 if(t != NUM_TEAM_4) if(c4 >= 0) TeamScore_AddToTeam(NUM_TEAM_4, i, -1000);
2005 AddWinners(team, t);
2016 Exit deathmatch games upon conditions
2019 void ReadyRestart();
2020 void CheckRules_World()
2031 if (gameover) // someone else quit the game already
2033 if(player_count == 0) // Nobody there? Then let's go to the next map
2035 // this will actually check the player count in the next frame
2036 // again, but this shouldn't hurt
2040 timelimit = autocvar_timelimit * 60;
2041 fraglimit = autocvar_fraglimit;
2042 leadlimit = autocvar_leadlimit;
2044 if(warmup_stage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
2047 timelimit = 0; // timelimit is not made for warmup
2049 fraglimit = 0; // no fraglimit for now
2050 leadlimit = 0; // no leadlimit for now
2055 timelimit += game_starttime;
2057 else if (timelimit < 0)
2065 timelimit = 0; // ONS has its own overtime rule
2070 if(timelimit > game_starttime)
2071 game_completion_ratio = (time - game_starttime) / (timelimit - game_starttime);
2073 game_completion_ratio = 0;
2075 if(checkrules_suddendeathend)
2077 if(!checkrules_suddendeathwarning)
2079 checkrules_suddendeathwarning = TRUE;
2080 if(g_race && !g_race_qualifying)
2081 Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_RACE_FINISHLAP);
2083 Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_OVERTIME_FRAG);
2088 if (timelimit && time >= timelimit)
2090 if(g_race && (g_race_qualifying == 2) && timelimit > 0)
2093 float playerswithlaps;
2096 totalplayers = playerswithlaps = readyplayers = 0;
2097 FOR_EACH_PLAYER(head)
2100 if(PlayerScore_Add(head, SP_RACE_FASTEST, 0))
2106 // at least 2 of the players have completed a lap: start the RACE
2107 // otherwise, the players should end the qualifying on their own
2108 if(readyplayers || playerswithlaps >= 2)
2110 checkrules_suddendeathend = 0;
2111 ReadyRestart(); // go to race
2115 wantovertime |= InitiateSuddenDeath();
2118 wantovertime |= InitiateSuddenDeath();
2122 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
2128 float checkrules_status;
2129 checkrules_status = WinningCondition_RanOutOfSpawns();
2130 if(checkrules_status == WINNING_YES)
2132 bprint("Hey! Someone ran out of spawns!\n");
2134 else if(g_race && !g_race_qualifying && timelimit >= 0)
2136 checkrules_status = WinningCondition_Race(fraglimit);
2137 //print("WC_RACE yields ", ftos(checkrules_status), "\n");
2139 else if(g_race && g_race_qualifying == 2 && timelimit >= 0)
2141 checkrules_status = WinningCondition_QualifyingThenRace(fraglimit);
2142 //print("WC_QUALIFYING_THEN_RACE yields ", ftos(checkrules_status), "\n");
2146 checkrules_status = WinningCondition_Assault(); // TODO remove this?
2150 checkrules_status = WinningCondition_LMS();
2152 else if (g_onslaught)
2154 checkrules_status = WinningCondition_Onslaught(); // TODO remove this?
2158 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
2159 //print("WC_SCORES yields ", ftos(checkrules_status), "\n");
2162 if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
2164 checkrules_status = WINNING_NEVER;
2165 checkrules_overtimesadded = -1;
2166 wantovertime |= InitiateSuddenDeath();
2169 if(checkrules_status == WINNING_NEVER)
2170 // equality cases! Nobody wins if the overtime ends in a draw.
2175 if(checkrules_status == WINNING_NEVER)
2178 checkrules_status = WINNING_YES;
2181 if(checkrules_suddendeathend)
2182 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
2183 checkrules_status = WINNING_YES;
2185 if(checkrules_status == WINNING_YES)
2187 //print("WINNING\n");
2192 string GotoMap(string m)
2194 m = GameTypeVote_MapInfo_FixName(m);
2196 return "The map you suggested is not available on this server.";
2197 if (!autocvar_sv_vote_gametype)
2198 if(!MapInfo_CheckMap(m))
2199 return "The map you suggested does not support the current game mode.";
2200 cvar_set("nextmap", m);
2201 cvar_set("timelimit", "-1");
2202 if(mapvote_initialized || alreadychangedlevel)
2204 if(DoNextMapOverride(0))
2205 return "Map switch initiated.";
2207 return "Hm... no. For some reason I like THIS map more.";
2210 return "Map switch will happen after scoreboard.";
2216 anticheat_endframe();
2219 FOR_EACH_REALCLIENT(self)
2221 entity e = IS_SPEC(self) ? self.enemy : self;
2223 self.typehit_time = time;
2224 else if(e.damage_dealt)
2226 self.hit_time = time;
2227 self.damage_dealt_total += ceil(e.damage_dealt);
2230 altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2231 // add 1 frametime because after this, engine SV_Physics
2232 // increases time by a frametime and then networks the frame
2233 // add another frametime because client shows everything with
2234 // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2236 FOR_EACH_CLIENT(self)
2238 self.typehitsound = FALSE;
2239 self.damage_dealt = 0;
2240 antilag_record(self, altime);
2242 FOR_EACH_MONSTER(self)
2243 antilag_record(self, altime);
2249 * returns TRUE if redirecting
2251 float redirection_timeout;
2252 float redirection_nextthink;
2253 float RedirectionThink()
2255 float clients_found;
2257 if(redirection_target == "")
2260 if(!redirection_timeout)
2262 cvar_set("sv_public", "-2");
2263 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2264 if(redirection_target == "self")
2265 bprint("^3SERVER NOTICE:^7 restarting the server\n");
2267 bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2270 if(time < redirection_nextthink)
2273 redirection_nextthink = time + 1;
2276 FOR_EACH_REALCLIENT(self)
2279 print("Redirecting: sending connect command to ", self.netname, "\n");
2280 if(redirection_target == "self")
2281 stuffcmd(self, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2283 stuffcmd(self, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2287 print("Redirecting: ", ftos(clients_found), " clients left.\n");
2289 if(time > redirection_timeout || clients_found == 0)
2290 localcmd("\nwait; wait; wait; quit\n");
2295 void TargetMusic_RestoreGame();
2298 // Loaded from a save game
2299 // some things then break, so let's work around them...
2301 // Progs DB (capture records)
2302 ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2306 MapInfo_Enumerate();
2307 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2310 TargetMusic_RestoreGame();
2317 if(world_initialized > 0)
2319 world_initialized = 0;
2320 print("Saving persistent data...\n");
2323 // playerstats with unfinished match
2324 PlayerStats_GameReport(FALSE);
2326 if(!cheatcount_total)
2328 if(autocvar_sv_db_saveasdump)
2329 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2331 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2333 if(autocvar_developer)
2335 if(autocvar_sv_db_saveasdump)
2336 db_dump(TemporaryDB, "server-temp.db");
2338 db_save(TemporaryDB, "server-temp.db");
2340 CheatShutdown(); // must be after cheatcount check
2341 db_close(ServerProgsDB);
2342 db_close(TemporaryDB);
2344 // tell the bot system the game is ending now
2347 WeaponStats_Shutdown();
2350 else if(world_initialized == 0)
2352 print("NOTE: crashed before even initializing the world, not saving persistent data\n");