1 float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
2 string redirection_target;
3 float world_initialized;
9 float() DoNextMapOverride;
11 void SetDefaultAlpha()
13 if(cvar("g_running_guns"))
15 default_player_alpha = -1;
16 default_weapon_alpha = +1;
20 default_player_alpha = cvar("g_balance_cloaked_alpha");
21 default_weapon_alpha = default_player_alpha;
25 default_player_alpha = cvar("g_player_alpha");
26 if(default_player_alpha <= 0)
27 default_player_alpha = 1;
28 default_weapon_alpha = default_player_alpha;
32 void fteqcc_testbugs()
36 if(!cvar("developer_fteqccbugs"))
39 dprint("*** fteqcc test: checking for bugs...\n");
43 if(sqrt(a) - sqrt(b - a) == 0)
44 dprint("*** fteqcc test: found same-function-twice bug\n");
46 dprint("*** fteqcc test: same-function-twice bug got FINALLY FIXED! HOORAY!\n");
50 world.enemy.cnt += 10;
51 if(world.cnt > 0.2 || world.cnt < -0.2) // don't error out if it's just roundoff errors
52 dprint("*** fteqcc test: found += bug\n");
54 dprint("*** fteqcc test: += bug got FINALLY FIXED! HOORAY!\n");
59 * Takes care of pausing and unpausing the game.
60 * Centerprints the information about an upcoming or active timeout to all active
61 * players. Also plays reminder sounds.
63 void timeoutHandler_Think() {
66 if (timeoutStatus == 1) {
67 if (remainingLeadTime > 0) {
68 //centerprint the information to every player
69 timeStr = getTimeoutText(0);
70 FOR_EACH_REALCLIENT(plr) {
71 if(plr.classname == "player") {
72 centerprint_atprio(plr, CENTERPRIO_SPAM, timeStr);
75 remainingLeadTime -= 1;
76 //think again in 1 second:
77 self.nextthink = time + 1;
82 cvar_set("slowmo", ftos(TIMEOUT_SLOWMO_VALUE));
83 //copy .v_angle to .lastV_angle for every player in order to fix their view during pause (see PlayerPreThink)
84 FOR_EACH_REALPLAYER(plr) {
85 plr.lastV_angle = plr.v_angle;
87 self.nextthink = time;
90 else if (timeoutStatus == 2) {
91 if (remainingTimeoutTime > 0) {
92 timeStr = getTimeoutText(0);
93 FOR_EACH_REALCLIENT(plr) {
94 if(plr.classname == "player") {
95 centerprint_atprio(plr, CENTERPRIO_SPAM, timeStr);
98 if(remainingTimeoutTime == cvar("sv_timeout_resumetime")) { //play a warning sound when only <sv_timeout_resumetime> seconds are left
99 play2all("announcer/robotic/prepareforbattle.wav");
101 remainingTimeoutTime -= 1;
102 self.nextthink = time + TIMEOUT_SLOWMO_VALUE;
105 //unpause the game again
106 remainingTimeoutTime = timeoutStatus = 0;
107 cvar_set("slowmo", ftos(orig_slowmo));
108 //and unlock the fixed view again once there is no timeout active anymore
109 FOR_EACH_REALPLAYER(plr) {
110 plr.fixangle = FALSE;
112 //get rid of the countdown message
113 FOR_EACH_REALCLIENT(plr) {
114 if(plr.classname == "player") {
115 centerprint_atprio(plr, CENTERPRIO_SPAM, "");
123 else if (timeoutStatus == 0) { //if a player called the resumegame command (which set timeoutStatus to 0 already)
124 FOR_EACH_REALCLIENT(plr) {
125 if(plr.classname == "player") {
126 centerprint_atprio(plr, CENTERPRIO_SPAM, "");
138 cvar_set("_sv_init", "0");
139 if(cvar("g_maplist_shuffle"))
141 tokenizebyseparator(cvar_string("g_maplist"), " ");
143 cvar_set("nextmap", argv(0));
146 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 0, (g_maplist_allow_hidden ? MAPINFO_FLAG_HIDDEN : 0), 0);
148 if(!DoNextMapOverride())
157 void cvar_changes_init()
164 strunzone(cvar_changes);
165 cvar_changes = string_null;
166 fh = fopen("cvars.txt", FILE_READ);
169 while((s = fgets(fh)))
171 n = tokenize_sane(s);
178 d = cvar_defstring(k);
181 cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
182 if(strlen(cvar_changes) > 16384)
184 cvar_changes = "// too many settings have been changed to show them here\n";
190 if(cvar_changes == "")
191 cvar_changes = "// this server runs at default settings\n";
193 cvar_changes = strcat("// this server runs at modified settings:\n", cvar_changes);
194 cvar_changes = strzone(cvar_changes);
197 float world_already_spawned;
198 void RegisterWeapons();
200 void spawnfunc_worldspawn (void)
205 dprint_load(); // load dprint status from cvar
207 if(world_already_spawned)
208 error("world already spawned - you may have EXACTLY ONE worldspawn!");
209 world_already_spawned = TRUE;
211 remove = remove_safely; // during spawning, watch what you remove!
212 remove_empty_template = spawn(); // make an empty entity
214 compressShortVector_init();
217 head = nextent(world);
222 head = nextent(head);
225 // needs to be done so early as they would still spawn
232 ServerProgsDB = db_create();
234 ServerProgsDB = db_load("server.db");
236 TemporaryDB = db_create();
239 TODO sound pack system
240 // initialize sound pack system
241 soundpack = cvar_string("g_soundpack");
243 soundpack = strcat(soundpack, "/");
244 soundpack = strzone(soundpack);
250 // 1 FLICKER (first variety)
251 lightstyle(1, "mmnmmommommnonmmonqnmmo");
253 // 2 SLOW STRONG PULSE
254 lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
256 // 3 CANDLE (first variety)
257 lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
260 lightstyle(4, "mamamamamama");
263 lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
265 // 6 FLICKER (second variety)
266 lightstyle(6, "nmonqnmomnmomomno");
268 // 7 CANDLE (second variety)
269 lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
271 // 8 CANDLE (third variety)
272 lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
274 // 9 SLOW STROBE (fourth variety)
275 lightstyle(9, "aaaaaaaazzzzzzzz");
277 // 10 FLUORESCENT FLICKER
278 lightstyle(10, "mmamammmmammamamaaamammma");
280 // 11 SLOW PULSE NOT FADE TO BLACK
281 lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
283 // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
288 if(cvar("g_campaign"))
296 bot_waypoints_for_items = cvar("g_waypoints_for_items");
297 if(bot_waypoints_for_items == 1)
298 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
299 bot_waypoints_for_items = 0;
301 // for setting by mapinfo
302 q3acompat_machineshotgunswap = cvar("sv_q3acompat_machineshotgunswap");
303 cvar_set("sv_q3acompat_machineshotgunswap", "0");
307 WaypointSprite_Init();
312 GameLogInit(); // prepare everything
313 if(cvar("sv_eventlog"))
315 s = strcat(cvar_string("sv_eventlog_files_counter"), ".");
316 s = strcat(s, ftos(random()));
317 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
318 s = ":gameinfo:mutators:LIST";
319 if(cvar("g_grappling_hook"))
320 s = strcat(s, ":grappling_hook");
321 if(!cvar("g_use_ammunition"))
322 s = strcat(s, ":no_use_ammunition");
323 if(!cvar("g_pickup_items"))
324 s = strcat(s, ":no_pickup_items");
325 if(cvar("g_instagib"))
326 s = strcat(s, ":instagib");
327 if(cvar("g_rocketarena"))
328 s = strcat(s, ":rockerarena");
330 s = strcat(s, ":nixnex");
331 if(cvar("g_vampire"))
332 s = strcat(s, ":vampire");
333 if(cvar("g_laserguided_missile"))
334 s = strcat(s, ":laserguided_missile");
335 if(cvar("g_norecoil"))
336 s = strcat(s, ":norecoil");
338 s = strcat(s, ":midair");
339 if(cvar("g_minstagib"))
340 s = strcat(s, ":minstagib");
342 GameLogEcho(":gameinfo:end");
345 cvar_set("nextmap", "");
349 if(cvar("g_campaign"))
356 //initialise globals related to sv_timeout
357 sys_ticrate = cvar("sys_ticrate");
358 orig_slowmo = cvar("slowmo");
361 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 0, (g_maplist_allow_hidden ? MAPINFO_FLAG_HIDDEN : 0), 1);
363 if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
365 fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
368 while((s = fgets(fd)))
370 l = tokenize_sane(s);
375 print("Found ^1DEPRECATED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
376 print(" cdtrack ", argv(2), "\n");
378 else if(argv(0) == "fog")
380 print("Found ^1DEPRECATED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
381 print(" \"fog\" \"", s, "\"\n");
383 else if(argv(0) == "set")
385 print("Found ^1DEPRECATED^7 set command in .cfg file; put this line in mapinfo instead:\n");
386 print(" clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
388 else if(argv(0) != "//")
390 print("Found ^1DEPRECATED^7 set command in .cfg file; put this line in mapinfo instead:\n");
391 print(" clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
398 addstat(STAT_SYS_TICRATE, AS_FLOAT, stat_sys_ticrate);
399 addstat(STAT_WEAPONS, AS_INT, weapons);
400 addstat(STAT_SWITCHWEAPON, AS_INT, switchweapon);
401 addstat(STAT_GAMESTARTTIME, AS_FLOAT, stat_game_starttime);
404 next_pingtime = time + 5;
405 world_initialized = 1;
407 InitializeEntity(self, cvar_changes_init, INITPRIO_CVARS);
410 void spawnfunc_light (void)
412 //makestatic (self); // Who the f___ did that?
416 float TryFile( string pFilename )
419 dprint("TryFile(\"", pFilename, "\")\n");
420 lHandle = fopen( pFilename, FILE_READ );
421 if( lHandle != -1 ) {
431 return GametypeNameFromType(game);
434 string getmapname_stored;
440 float Map_Count, Map_Current;
441 string Map_Current_Name;
443 // NOTE: this now expects the map list to be already tokenize()d and the count in Map_Count
444 float GetMaplistPosition()
450 idx = cvar("g_maplist_index");
457 for(pos = 0; pos < Map_Count; ++pos)
461 // resume normal maplist rotation if current map is not in g_maplist
465 float MapHasRightSize(string map)
468 if(currentbots || cvar("bot_number") || player_count < cvar("minplayers"))
469 if(cvar("g_maplist_check_waypoints"))
471 dprint("checkwp "); dprint(map);
472 fh = fopen(strcat("maps/", map, ".waypoints"), FILE_READ);
475 dprint(": no waypoints\n");
478 dprint(": has waypoints\n");
482 // open map size restriction file
483 dprint("opensize "); dprint(map);
484 fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
487 float mapmin, mapmax;
489 mapmin = stof(fgets(fh));
490 mapmax = stof(fgets(fh));
492 if(player_count < mapmin)
494 dprint("not enough\n");
497 if(player_count > mapmax)
499 dprint("too many\n");
502 dprint("right size\n");
505 dprint(": not found\n");
509 string Map_Filename(float position)
511 return strcat("maps/", argv(position), ".bsp");
514 string strwords(string s, float w)
517 for(endpos = 0; w && endpos >= 0; --w)
518 endpos = strstrofs(s, " ", endpos + 1);
522 return substring(s, 0, endpos);
525 float strhasword(string s, string w)
527 return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
530 void Map_MarkAsRecent(string m)
532 cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", cvar_string("g_maplist_mostrecent")), cvar("g_maplist_mostrecent_count")));
535 float Map_IsRecent(string m)
537 return strhasword(cvar_string("g_maplist_mostrecent"), m);
540 float Map_Check(float position, float pass)
544 map_next = argv(position);
547 if(map_next == Map_Current_Name) // same map again in first pass?
549 if(Map_IsRecent(map_next))
552 filename = Map_Filename(position);
553 if(MapInfo_CheckMap(map_next))
557 if(MapHasRightSize(map_next))
562 dprint( "Couldn't select '", filename, "'..\n" );
567 void Map_Goto_SetStr(string nextmapname)
569 if(getmapname_stored != "")
570 strunzone(getmapname_stored);
571 if(nextmapname == "")
572 getmapname_stored = "";
574 getmapname_stored = strzone(nextmapname);
577 void Map_Goto_SetFloat(float position)
579 cvar_set("g_maplist_index", ftos(position));
580 Map_Goto_SetStr(argv(position));
585 // settings persist, except...
586 if(cvar("g_campaign"))
587 localcmd("\nexec mutator_reset.cfg\n");
588 localcmd("\nsettemp_restore\n");
593 Map_MarkAsRecent(getmapname_stored);
595 MapInfo_LoadMap(getmapname_stored);
598 // return codes of map selectors:
599 // -1 = temporary failure (that is, try some method that is guaranteed to succeed)
600 // -2 = permanent failure
601 float() MaplistMethod_Iterate = // usual method
605 for(pass = 1; pass <= 2; ++pass)
607 for(i = 1; i < Map_Count; ++i)
610 mapindex = mod(i + Map_Current, Map_Count);
611 if(Map_Check(mapindex, pass))
618 float() MaplistMethod_Repeat = // fallback method
620 if(Map_Check(Map_Current, 2))
625 float() MaplistMethod_Random = // random map selection
631 for(i = 0; i <= imax; ++i)
634 mapindex = mod(Map_Current + floor(random() * (Map_Count - 1) + 1), Map_Count); // any OTHER map
635 if(Map_Check(mapindex, 1))
641 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
642 // the exponent sets a bias on the map selection:
643 // the higher the exponent, the less likely "shortly repeated" same maps are
645 float i, j, imax, insertpos;
649 for(i = 0; i <= imax; ++i)
653 // now reinsert this at another position
654 insertpos = pow(random(), 1 / exponent); // ]0, 1]
655 insertpos = insertpos * (Map_Count - 1); // ]0, Map_Count - 1]
656 insertpos = ceil(insertpos) + 1; // {2, 3, 4, ..., Map_Count}
657 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
659 // insert the current map there
661 for(j = 1; j < insertpos; ++j) // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
662 newlist = strcat(newlist, " ", argv(j));
663 newlist = strcat(newlist, " ", argv(0)); // now insert the just selected map
664 for(j = insertpos; j < Map_Count; ++j) // i == Map_Count: no loop, has just been inserted as last
665 newlist = strcat(newlist, " ", argv(j));
666 newlist = substring(newlist, 1, strlen(newlist) - 1);
667 cvar_set("g_maplist", newlist);
668 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
670 // NOTE: the selected map has just been inserted at (insertpos-1)th position
671 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
672 if(Map_Check(Map_Current, 1))
681 temp = cvar_string("g_maplist");
682 Map_Count = tokenizebyseparator(temp, " ");
685 bprint( "Maplist is empty! Resetting it to default map list.\n" );
686 cvar_set("g_maplist", temp = MapInfo_ListAllowedMaps(0, MAPINFO_FLAG_HIDDEN));
687 localcmd("\nmenu_cmd sync\n");
688 Map_Count = tokenizebyseparator(temp, " ");
691 error("empty maplist, cannot select a new map");
692 Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
695 strunzone(Map_Current_Name);
696 Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
697 // this may or may not be correct, but who cares, in the worst case a map
698 // isn't chosen in the first pass that should have been
709 if(cvar("g_maplist_shuffle") > 0)
710 nextMap = MaplistMethod_Shuffle(cvar("g_maplist_shuffle") + 1);
713 if(cvar("g_maplist_selectrandom"))
714 nextMap = MaplistMethod_Random();
717 nextMap = MaplistMethod_Iterate();
720 nextMap = MaplistMethod_Repeat();
724 Map_Goto_SetFloat(nextMap);
725 return getmapname_stored;
731 float DoNextMapOverride()
733 if(cvar("g_campaign"))
735 CampaignPostIntermission();
736 alreadychangedlevel = TRUE;
739 if(cvar("quit_when_empty"))
741 if(player_count <= currentbots)
744 alreadychangedlevel = TRUE;
748 if(cvar_string("quit_and_redirect") != "")
750 redirection_target = strzone(cvar_string("quit_and_redirect"));
751 alreadychangedlevel = TRUE;
754 if (cvar("samelevel")) // if samelevel is set, stay on same level
756 // this does not work because it tries to exec maps/nexdm01.mapcfg (which doesn't exist, it should be trying maps/dm_nexdm01.mapcfg for example)
757 //localcmd(strcat("exec \"maps/", mapname, ".mapcfg\"\n"));
758 // so instead just restart the current map using the restart command (DOES NOT WORK PROPERLY WITH exit_cfg STUFF)
759 localcmd("restart\n");
760 //changelevel (mapname);
761 alreadychangedlevel = TRUE;
764 if(cvar_string("nextmap") != "")
765 if(MapInfo_CheckMap(cvar_string("nextmap")))
767 Map_Goto_SetStr(cvar_string("nextmap"));
769 alreadychangedlevel = TRUE;
772 if(cvar("lastlevel"))
775 localcmd("set lastlevel 0\ntogglemenu\n");
776 alreadychangedlevel = TRUE;
784 //local string nextmap;
785 //local float n, nummaps;
787 if (alreadychangedlevel)
789 alreadychangedlevel = TRUE;
795 for(allowReset = 1; allowReset >= 0; --allowReset)
797 nextMap = GetNextMap();
803 bprint( "Maplist contains no single playable map! Resetting it to default map list.\n" );
804 cvar_set("g_maplist", MapInfo_ListAllowedMaps(0, MAPINFO_FLAG_HIDDEN));
805 localcmd("\nmenu_cmd sync\n");
809 error("Everything is broken - not even the default map list works. Please report this to the developers.");
821 When the player presses attack or jump, change to the next level
824 .float autoscreenshot;
825 void() MapVote_Start;
826 void() MapVote_Think;
827 float mapvote_initialized;
828 void IntermissionThink()
830 FixIntermissionClient(self);
832 if(cvar("sv_autoscreenshot"))
833 if(self.autoscreenshot > 0)
834 if(time > self.autoscreenshot)
836 self.autoscreenshot = -1;
837 if(clienttype(self) == CLIENTTYPE_REAL)
838 stuffcmd(self, "\nscreenshot\necho \"^5A screenshot has been taken at request of the server.\"\n");
842 if (time < intermission_exittime)
845 if(!mapvote_initialized)
846 if (time < intermission_exittime + 10 && !self.BUTTON_ATCK && !self.BUTTON_JUMP && !self.BUTTON_ATCK2 && !self.BUTTON_HOOK && !self.BUTTON_USE)
856 Returns the entity to view from
860 entity FindIntermission()
865 // look for info_intermission first
866 spot = find (world, classname, "info_intermission");
868 { // pick a random one
872 spot = find (spot, classname, "info_intermission");
874 spot = find (spot, classname, "info_intermission");
880 // then look for the start position
881 spot = find (world, classname, "info_player_start");
885 // testinfo_player_start is only found in regioned levels
886 spot = find (world, classname, "testplayerstart");
890 // then look for the start position
891 spot = find (world, classname, "info_player_deathmatch");
895 //objerror ("FindIntermission: no spot");
901 ===============================================================================
905 ===============================================================================
908 void DumpStats(float final)
912 local float to_console;
913 local float to_eventlog;
917 to_console = cvar("sv_logscores_console");
918 to_eventlog = cvar("sv_eventlog");
919 to_file = cvar("sv_logscores_file");
923 to_console = TRUE; // always print printstats replies
924 to_eventlog = FALSE; // but never print them to the event log
928 if(cvar("sv_eventlog_console"))
929 to_console = FALSE; // otherwise we get the output twice
935 s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
943 file = fopen(cvar_string("sv_logscores_filename"), FILE_APPEND);
947 fputs(file, strcat(s, "\n"));
950 s = strcat(":labels:player:", GetPlayerScoreString(world, 0));
956 fputs(file, strcat(s, "\n"));
958 FOR_EACH_CLIENT(other)
960 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && cvar("sv_logscores_bots")))
962 s = strcat(":player:see-labels:", GetPlayerScoreString(other, 0), ":");
963 s = strcat(s, ftos(rint(time - other.jointime)), ":");
964 if(other.classname == "player" || g_arena || g_lms)
965 s = strcat(s, ftos(other.team), ":");
967 s = strcat(s, "spectator:");
970 print(s, other.netname, "\n");
972 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname));
974 fputs(file, strcat(s, other.netname, "\n"));
980 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
986 fputs(file, strcat(s, "\n"));
988 for(i = 1; i < 16; ++i)
990 s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
991 s = strcat(s, ":", ftos(i));
997 fputs(file, strcat(s, "\n"));
1004 GameLogEcho(":end");
1007 fputs(file, ":end\n");
1012 void FixIntermissionClient(entity e)
1015 if(!e.autoscreenshot) // initial call
1017 e.angles = e.v_angle;
1018 e.angles_x = -e.angles_x;
1019 e.autoscreenshot = time + 0.8; // used for autoscreenshot
1021 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1022 e.solid = SOLID_NOT;
1023 e.movetype = MOVETYPE_NONE;
1024 e.takedamage = DAMAGE_NO;
1026 e.weaponentity.effects = EF_NODRAW;
1027 if(clienttype(e) == CLIENTTYPE_REAL)
1029 stuffcmd(e, "\nscr_printspeed 1000000\n");
1030 s = cvar_string("sv_intermission_cdtrack");
1032 stuffcmd(e, strcat("\ncd loop ", s, "\n"));
1034 WriteByte(MSG_ONE, SVC_INTERMISSION);
1038 //e.velocity = '0 0 0';
1039 //e.fixangle = TRUE;
1041 // TODO halt weapon animation
1046 go to the next level for deathmatch
1047 only called if a time or frag limit has expired
1051 float minTotalFrags;
1052 float maxTotalFrags;
1058 intermission_running = 1;
1060 // enforce a wait time before allowing changelevel
1061 if(player_count > 0)
1062 intermission_exittime = time + cvar("sv_mapchange_delay");
1064 intermission_exittime = -1;
1067 WriteByte (MSG_ALL, SVC_CDTRACK);
1068 WriteByte (MSG_ALL, 3);
1069 WriteByte (MSG_ALL, 3);
1070 // done in FixIntermission
1073 //pos = FindIntermission ();
1079 if(cvar("sv_eventlog"))
1080 GameLogEcho(":gameover");
1084 FOR_EACH_CLIENT(other)
1086 FixIntermissionClient(other);
1089 bprint(other.netname, " ^7wins.\n");
1094 FOR_EACH_PLAYER(other)
1096 if(maxTotalFrags < other.totalfrags)
1097 maxTotalFrags = other.totalfrags;
1098 if(minTotalFrags > other.totalfrags)
1099 minTotalFrags = other.totalfrags;
1104 FOR_EACH_PLAYER(other)
1106 score = (other.totalfrags - minTotalFrags) / max(maxTotalFrags - minTotalFrags, 1);
1107 f = bound(0, other.play_time / max(time, 1), 1);
1108 // store some statistics?
1112 if(cvar("g_campaign"))
1113 CampaignPreIntermission();
1115 // WriteByte (MSG_ALL, SVC_INTERMISSION);
1122 Exit deathmatch games upon conditions
1125 void CheckRules_Player()
1127 if (gameover) // someone else quit the game already
1130 if(self.deadflag == DEAD_NO)
1131 self.play_time += frametime;
1133 // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1134 // (div0: and that in CheckRules_World please)
1137 float checkrules_oneminutewarning;
1139 float checkrules_equality;
1140 float checkrules_overtimewarning;
1141 float checkrules_overtimeend;
1143 void InitiateOvertime()
1145 if(!checkrules_overtimeend)
1146 checkrules_overtimeend = time + 60 * cvar("timelimit_maxovertime");
1149 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1150 float WINNING_YES = 1; // winner found
1151 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1152 float WINNING_STARTOVERTIME = 3; // no winner, enter overtime NOW
1154 float GetWinningCode(float fraglimitreached, float equality)
1157 if(fraglimitreached)
1158 return WINNING_STARTOVERTIME;
1160 return WINNING_NEVER;
1162 if(fraglimitreached)
1168 // set the .winning flag for exactly those players with a given field value
1169 void SetWinners(.float field, float value)
1172 FOR_EACH_PLAYER(head)
1173 head.winning = (head.field == value);
1176 // set the .winning flag for those players with a given field value
1177 void AddWinners(.float field, float value)
1180 FOR_EACH_PLAYER(head)
1181 if(head.field == value)
1185 // clear the .winning flags
1186 void ClearWinners(void)
1189 FOR_EACH_PLAYER(head)
1193 // Onslaught winning condition:
1194 // game terminates if only one team has a working generator (or none)
1195 float WinningCondition_Onslaught()
1198 local float t1, t2, t3, t4;
1199 // first check if the game has ended
1200 t1 = t2 = t3 = t4 = 0;
1201 head = find(world, classname, "onslaught_generator");
1204 if (head.health > 0)
1206 if (head.team == COLOR_TEAM1) t1 = 1;
1207 if (head.team == COLOR_TEAM2) t2 = 1;
1208 if (head.team == COLOR_TEAM3) t3 = 1;
1209 if (head.team == COLOR_TEAM4) t4 = 1;
1211 head = find(head, classname, "onslaught_generator");
1213 if (t1 + t2 + t3 + t4 < 2)
1215 // game over, only one team remains (or none)
1217 if (t1) SetWinners(team, COLOR_TEAM1);
1218 if (t2) SetWinners(team, COLOR_TEAM2);
1219 if (t3) SetWinners(team, COLOR_TEAM3);
1220 if (t4) SetWinners(team, COLOR_TEAM4);
1221 dprint("Have a winner, ending game.\n");
1225 // Two or more teams remain
1229 float LMS_NewPlayerLives()
1232 fl = cvar("fraglimit");
1236 // first player has left the game for dying too much? Nobody else can get in.
1237 if(lms_lowest_lives < 1)
1240 if(!cvar("g_lms_join_anytime"))
1241 if(lms_lowest_lives < fl - cvar("g_lms_last_join"))
1244 return bound(1, lms_lowest_lives, fl);
1247 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1248 // they win. Otherwise the defending team wins once the timelimit passes.
1249 void assault_new_round();
1250 float WinningCondition_Assault()
1253 status = WINNING_NO;
1255 // as the timelimit has not yet passed just assume the defending team will win
1256 if(assault_attacker_team == COLOR_TEAM1)
1258 SetWinners(team, COLOR_TEAM2);
1262 SetWinners(team, COLOR_TEAM1);
1266 ent = find(world, classname, "target_assault_roundend");
1269 if(ent.winning) // round end has been triggered by attacking team
1271 SetWinners(team, assault_attacker_team);
1272 if(assault_attacker_team == COLOR_TEAM1)
1274 team1_score = team1_score + 50;
1278 team2_score = team2_score + 50;
1281 if(ent.cnt == 1) // this was the second round
1283 status = WINNING_YES;
1287 local entity oldself;
1290 cvar_set("timelimit", ftos((2*time)/60)); // FIXME use game_starttime here
1291 assault_new_round();
1301 // LMS winning condition: game terminates if and only if there's at most one
1302 // one player who's living lives. Top two scores being equal cancels the time
1304 float WinningCondition_LMS()
1311 have_player = FALSE;
1312 have_players = FALSE;
1313 l = LMS_NewPlayerLives();
1315 head = find(world, classname, "player");
1318 head2 = find(head, classname, "player");
1320 have_players = TRUE;
1324 // we have at least one player
1327 // two or more active players - continue with the game
1331 // exactly one player?
1334 SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1338 // game still running (that is, nobody got removed from the game by a frag yet)? then continue
1344 // and assign him his first place
1345 PlayerScore_Add(head, SP_LMS_RANK, 1);
1352 // nobody is playing at all...
1355 // wait for players...
1359 // SNAFU (maybe a draw game?)
1361 dprint("No players, ending game.\n");
1366 // When we get here, we have at least two players who are actually LIVING,
1367 // now check if the top two players have equal score.
1368 WinningConditionHelper();
1371 if(WinningConditionHelper_winner)
1372 WinningConditionHelper_winner.winning = TRUE;
1373 if(WinningConditionHelper_equality)
1374 return WINNING_NEVER;
1376 // Top two have different scores? Way to go for our beloved TIMELIMIT!
1380 void print_to(entity e, string s)
1383 sprint(e, strcat(s, "\n"));
1388 void ShuffleMaplist()
1396 result = cvar_string("g_maplist");
1397 litems = tokenizebyseparator(result, " ");
1399 for(start = 0; start < litems - 1; ++start)
1403 // select a random item
1404 selected = floor(random() * (litems - start) + start);
1406 // shift this item to the place start
1407 for(i = 0; i < start; ++i)
1408 result = strcat(result, " ", argv(i));
1409 result = strcat(result, " ", argv(selected));
1410 for(i = start; i < litems; ++i)
1412 result = strcat(result, " ", argv(i));
1413 result = substring(result, 1, strlen(result) - 1);
1415 litems = tokenizebyseparator(result, " ");
1417 //dprint(result, "\n");
1420 cvar_set("g_maplist", result);
1423 float WinningCondition_Scores(float limit)
1425 // TODO make everything use THIS winning condition (except LMS)
1426 WinningConditionHelper();
1430 team1_score = TeamScore_GetCompareValue(COLOR_TEAM1);
1431 team2_score = TeamScore_GetCompareValue(COLOR_TEAM2);
1432 team3_score = TeamScore_GetCompareValue(COLOR_TEAM3);
1433 team4_score = TeamScore_GetCompareValue(COLOR_TEAM4);
1437 if(WinningConditionHelper_winner)
1438 WinningConditionHelper_winner.winning = 1;
1439 if(WinningConditionHelper_winnerteam >= 0)
1440 SetWinners(team, WinningConditionHelper_winnerteam);
1442 if(WinningConditionHelper_lowerisbetter)
1444 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1448 return GetWinningCode(limit && WinningConditionHelper_topscore && (WinningConditionHelper_topscore >= limit), WinningConditionHelper_equality);
1451 float WinningCondition_Race(float fraglimit)
1455 wc = WinningCondition_Scores(fraglimit);
1457 // ALWAYS initiate overtime, unless EVERYONE has finished the race!
1458 if(wc == WINNING_YES || wc == WINNING_STARTOVERTIME)
1459 // do NOT support equality when the laps are all raced!
1462 if not(p.race_completed)
1463 return WINNING_STARTOVERTIME;
1469 void ReadyRestart();
1470 float WinningCondition_QualifyingThenRace(float limit)
1473 wc = WinningCondition_Scores(limit);
1475 // NEVER initiate overtime
1476 if(wc == WINNING_YES || wc == WINNING_STARTOVERTIME)
1477 // do NOT support equality when the laps are all raced!
1480 float playerswithlaps;
1483 totalplayers = playerswithlaps = readyplayers = 0;
1484 FOR_EACH_PLAYER(head)
1487 if(PlayerScore_Add(head, SP_RACE_FASTEST, 0))
1493 // at least 2/3 of the players have completed a lap: start the RACE
1494 // otherwise, the players should end the qualifying on their own
1495 if(readyplayers || ((totalplayers >= 3) && (playerswithlaps * 3 >= totalplayers * 2)))
1497 checkrules_overtimeend = 0;
1499 return WINNING_NEVER;
1508 float WinningCondition_RanOutOfSpawns()
1512 if(!have_team_spawns)
1515 if(!some_spawn_has_been_used)
1518 team1_score = team2_score = team3_score = team4_score = 0;
1520 FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
1522 if(head.team == COLOR_TEAM1)
1524 else if(head.team == COLOR_TEAM2)
1526 else if(head.team == COLOR_TEAM3)
1528 else if(head.team == COLOR_TEAM4)
1532 for(head = world; (head = find(head, classname, "info_player_deathmatch")) != world; )
1534 if(head.team == COLOR_TEAM1)
1536 else if(head.team == COLOR_TEAM2)
1538 else if(head.team == COLOR_TEAM3)
1540 else if(head.team == COLOR_TEAM4)
1545 if(team1_score + team2_score + team3_score + team4_score == 0)
1547 checkrules_equality = TRUE;
1550 else if(team1_score + team2_score + team3_score + team4_score == 1)
1553 if(team1_score) t = COLOR_TEAM1;
1554 if(team2_score) t = COLOR_TEAM2;
1555 if(team3_score) t = COLOR_TEAM3;
1556 if(team4_score) t = COLOR_TEAM4;
1557 CheckAllowedTeams(world);
1558 for(i = 0; i < MAX_TEAMSCORE; ++i)
1560 if(t != COLOR_TEAM1) if(c1 >= 0) TeamScore_AddToTeam(COLOR_TEAM1, i, -1000);
1561 if(t != COLOR_TEAM2) if(c2 >= 0) TeamScore_AddToTeam(COLOR_TEAM2, i, -1000);
1562 if(t != COLOR_TEAM3) if(c3 >= 0) TeamScore_AddToTeam(COLOR_TEAM3, i, -1000);
1563 if(t != COLOR_TEAM4) if(c4 >= 0) TeamScore_AddToTeam(COLOR_TEAM4, i, -1000);
1566 AddWinners(team, t);
1577 Exit deathmatch games upon conditions
1580 void CheckRules_World()
1583 local float timelimit;
1584 local float fraglimit;
1592 MapVote_Think should now do that part
1593 if (intermission_running)
1594 if (time >= intermission_exittime + 60)
1596 if(!DoNextMapOverride())
1602 if (gameover) // someone else quit the game already
1604 if(player_count == 0) // Nobody there? Then let's go to the next map
1606 // this will actually check the player count in the next frame
1607 // again, but this shouldn't hurt
1611 timelimit = cvar("timelimit") * 60;
1612 fraglimit = cvar("fraglimit");
1614 if(inWarmupStage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1616 timelimit = 0; // timelimit is not made for warmup
1617 fraglimit = 0; // no fraglimit for now
1621 timelimit += game_starttime;
1623 if(checkrules_overtimeend)
1625 if(!checkrules_overtimewarning)
1627 checkrules_overtimewarning = TRUE;
1628 //announceall("announcer/robotic/1minuteremains.wav");
1629 if(g_race && !g_race_qualifying)
1630 bcenterprint("^3Everyone, finish your lap! The race is over!");
1632 bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
1637 if (timelimit && time >= timelimit)
1641 if (checkrules_overtimeend && time >= checkrules_overtimeend)
1647 if (!checkrules_oneminutewarning && timelimit > 0 && time > timelimit - 60)
1649 checkrules_oneminutewarning = TRUE;
1650 play2all("announcer/robotic/1minuteremains.wav");
1653 status = WinningCondition_RanOutOfSpawns();
1654 if(status == WINNING_YES)
1656 bprint("Hey! Someone ran out of spawns!\n");
1658 else if(g_race && !g_race_qualifying && timelimit >= 0)
1660 status = WinningCondition_Race(fraglimit);
1662 else if(g_race && g_race_qualifying == 2 && timelimit >= 0)
1664 status = WinningCondition_QualifyingThenRace(fraglimit);
1668 status = WinningCondition_Assault(); // TODO remove this?
1672 status = WinningCondition_LMS();
1674 else if (g_onslaught)
1676 status = WinningCondition_Onslaught(); // TODO remove this?
1680 status = WinningCondition_Scores(fraglimit);
1683 if(status == WINNING_STARTOVERTIME)
1685 status = WINNING_NEVER;
1689 if(status == WINNING_NEVER)
1690 // equality cases! Nobody wins if the overtime ends in a draw.
1693 if(checkrules_overtimeend)
1694 if(status != WINNING_NEVER || time >= checkrules_overtimeend)
1695 status = WINNING_YES;
1697 if(status == WINNING_YES)
1701 float mapvote_nextthink;
1702 float mapvote_initialized;
1703 float mapvote_keeptwotime;
1704 float mapvote_timeout;
1705 string mapvote_message;
1706 string mapvote_screenshot_dir;
1708 float mapvote_count;
1709 float mapvote_count_real;
1710 string mapvote_maps[MAPVOTE_COUNT];
1711 float mapvote_maps_suggested[MAPVOTE_COUNT];
1712 string mapvote_suggestions[MAPVOTE_COUNT];
1713 float mapvote_suggestion_ptr;
1714 float mapvote_maxlen;
1715 float mapvote_voters;
1716 float mapvote_votes[MAPVOTE_COUNT];
1718 float mapvote_detail;
1719 float mapvote_abstain;
1720 float mapvote_dirty;
1723 void MapVote_ClearAllVotes()
1725 FOR_EACH_CLIENT(other)
1729 string MapVote_Suggest(string m)
1733 return "That's not how to use this command.";
1734 if(!cvar("g_maplist_votable_suggestions"))
1735 return "Suggestions are not accepted on this server.";
1736 if(mapvote_initialized)
1737 return "Can't suggest - voting is already in progress!";
1738 m = MapInfo_FixName(m);
1740 return "The map you suggested is not available on this server.";
1741 if(!cvar("g_maplist_votable_override_mostrecent"))
1743 return "This server does not allow for recent maps to be played again. Please be patient for some rounds.";
1745 if(!MapInfo_CheckMap(m))
1746 return "The map you suggested does not support the current game mode.";
1747 for(i = 0; i < mapvote_suggestion_ptr; ++i)
1748 if(mapvote_suggestions[i] == m)
1749 return "This map was already suggested.";
1750 if(mapvote_suggestion_ptr >= MAPVOTE_COUNT)
1752 i = floor(random() * mapvote_suggestion_ptr);
1756 i = mapvote_suggestion_ptr;
1757 mapvote_suggestion_ptr += 1;
1759 if(mapvote_suggestions[i] != "")
1760 strunzone(mapvote_suggestions[i]);
1761 mapvote_suggestions[i] = strzone(m);
1762 if(cvar("sv_eventlog"))
1763 GameLogEcho(strcat(":vote:suggested:", m, ":", ftos(self.playerid)));
1764 return strcat("Suggestion of ", m, " accepted.");
1767 void MapVote_AddVotable(string nextMap, float isSuggestion)
1772 for(j = 0; j < mapvote_count; ++j)
1773 if(mapvote_maps[j] == nextMap)
1775 if(strlen(nextMap) > mapvote_maxlen)
1776 mapvote_maxlen = strlen(nextMap);
1777 mapvote_maps[mapvote_count] = strzone(nextMap);
1778 mapvote_maps_suggested[mapvote_count] = isSuggestion;
1782 void MapVote_SendData(float target);
1788 MapVote_ClearAllVotes();
1791 mapvote_detail = !cvar("g_maplist_votable_nodetail");
1792 mapvote_abstain = cvar("g_maplist_votable_abstain");
1795 nmax = min(MAPVOTE_COUNT - 1, cvar("g_maplist_votable"));
1797 nmax = min(MAPVOTE_COUNT, cvar("g_maplist_votable"));
1798 smax = min3(nmax, cvar("g_maplist_votable_suggestions"), mapvote_suggestion_ptr);
1800 if(mapvote_suggestion_ptr)
1801 for(i = 0; i < 100 && mapvote_count < smax; ++i)
1802 MapVote_AddVotable(mapvote_suggestions[floor(random() * mapvote_suggestion_ptr)], TRUE);
1804 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
1805 MapVote_AddVotable(GetNextMap(), FALSE);
1807 if(mapvote_count == 0)
1809 bprint( "Maplist contains no single playable map! Resetting it to default map list.\n" );
1810 cvar_set("g_maplist", MapInfo_ListAllowedMaps(0, MAPINFO_FLAG_HIDDEN));
1811 localcmd("\nmenu_cmd sync\n");
1812 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
1813 MapVote_AddVotable(GetNextMap(), FALSE);
1816 mapvote_count_real = mapvote_count;
1818 MapVote_AddVotable("don't care", 0);
1820 //dprint("mapvote count is ", ftos(mapvote_count), "\n");
1822 mapvote_keeptwotime = time + cvar("g_maplist_votable_keeptwotime");
1823 mapvote_timeout = time + cvar("g_maplist_votable_timeout");
1824 if(mapvote_count_real < 3 || mapvote_keeptwotime <= time)
1825 mapvote_keeptwotime = 0;
1826 mapvote_message = "Choose a map and press its key!";
1828 mapvote_screenshot_dir = cvar_string("g_maplist_votable_screenshot_dir");
1829 if(mapvote_screenshot_dir == "")
1830 mapvote_screenshot_dir = "maps";
1831 mapvote_screenshot_dir = strzone(mapvote_screenshot_dir);
1833 if(!cvar("g_maplist_textonly"))
1834 MapVote_SendData(MSG_ALL);
1837 void MapVote_SendPicture(float id)
1840 WriteByte(MSG_ONE, SVC_TEMPENTITY);
1841 WriteByte(MSG_ONE, TE_CSQC_MAPVOTE);
1842 WriteByte(MSG_ONE, MAPVOTE_NET_PIC);
1843 WriteByte(MSG_ONE, id);
1844 WritePicture(MSG_ONE, strcat(mapvote_screenshot_dir, "/", mapvote_maps[id]), 3072);
1847 float GameCommand_MapVote(string cmd)
1849 if(!intermission_running)
1851 if(!cvar("g_maplist_textonly"))
1853 if(cmd == "mv_getpic")
1855 MapVote_SendPicture(stof(argv(1)));
1863 float MapVote_GetMapMask()
1865 float mask, i, power;
1867 for(i = 0, power = 1; i < mapvote_count; ++i, power *= 2)
1868 if(mapvote_maps[i] != "")
1873 void MapVote_SendData(float targ)
1875 string mapfile, pakfile;
1877 WriteByte(targ, SVC_TEMPENTITY);
1878 WriteByte(targ, TE_CSQC_CONFIG);
1879 WriteString(targ, "mv_screenshot_dir");
1880 WriteString(targ, mapvote_screenshot_dir);
1882 WriteByte(targ, SVC_TEMPENTITY);
1883 WriteByte(targ, TE_CSQC_MAPVOTE);
1884 WriteByte(targ, MAPVOTE_NET_INIT);
1886 WriteByte(targ, mapvote_count);
1887 WriteByte(targ, mapvote_abstain);
1888 WriteByte(targ, mapvote_detail);
1889 WriteCoord(targ, mapvote_timeout);
1890 if(mapvote_count <= 8)
1891 WriteByte(targ, MapVote_GetMapMask());
1893 WriteShort(targ, MapVote_GetMapMask());
1894 for(i = 0; i < mapvote_count; ++i)
1895 if(mapvote_maps[i] != "")
1897 WriteString(targ, mapvote_maps[i]);
1898 mapfile = strcat(mapvote_screenshot_dir, "/", mapvote_maps[i]);
1899 pakfile = whichpack(strcat(mapfile, ".tga"));
1901 pakfile = whichpack(strcat(mapfile, ".jpg"));
1903 pakfile = whichpack(strcat(mapfile, ".png"));
1904 print("pakfile is ", pakfile, "\n");
1905 for(o = strstr(pakfile, "/", 0)+1; o > 0; o = strstr(pakfile, "/", 0)+1)
1906 pakfile = substring(pakfile, o, 999);
1907 WriteString(targ, pakfile);
1911 void MapVote_UpdateData(float targ)
1914 WriteByte(targ, SVC_TEMPENTITY);
1915 WriteByte(targ, TE_CSQC_MAPVOTE);
1916 WriteByte(targ, MAPVOTE_NET_UPDATE);
1917 if(mapvote_count <= 8)
1918 WriteByte(targ, MapVote_GetMapMask());
1920 WriteShort(targ, MapVote_GetMapMask());
1922 for(i = 0; i < mapvote_count; ++i)
1923 if(mapvote_maps[i] != "")
1924 WriteByte(targ, mapvote_votes[i]);
1927 void MapVote_TellVote(float targ, float vote)
1929 WriteByte(targ, SVC_TEMPENTITY);
1930 WriteByte(targ, TE_CSQC_MAPVOTE);
1931 WriteByte(targ, MAPVOTE_NET_OWNVOTE);
1932 WriteByte(targ, vote);
1935 float MapVote_Finished(float mappos)
1941 if(cvar("sv_eventlog"))
1943 result = strcat(":vote:finished:", mapvote_maps[mappos]);
1944 result = strcat(result, ":", ftos(mapvote_votes[mappos]), "::");
1945 didntvote = mapvote_voters;
1946 for(i = 0; i < mapvote_count; ++i)
1947 if(mapvote_maps[i] != "")
1949 didntvote -= mapvote_votes[i];
1952 result = strcat(result, ":", mapvote_maps[i]);
1953 result = strcat(result, ":", ftos(mapvote_votes[i]));
1956 result = strcat(result, ":didn't vote:", ftos(didntvote));
1958 GameLogEcho(result);
1959 if(mapvote_maps_suggested[mappos])
1960 GameLogEcho(strcat(":vote:suggestion_accepted:", mapvote_maps[mappos]));
1963 FOR_EACH_REALCLIENT(other)
1964 FixClientCvars(other);
1966 Map_Goto_SetStr(mapvote_maps[mappos]);
1968 alreadychangedlevel = TRUE;
1971 void MapVote_CheckRules_1()
1975 for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
1977 //dprint("Map ", ftos(i), ": "); dprint(mapvote_maps[i], "\n");
1978 mapvote_votes[i] = 0;
1982 FOR_EACH_REALCLIENT(other)
1987 i = other.mapvote - 1;
1988 //dprint("Player ", other.netname, " vote = ", ftos(other.mapvote - 1), "\n");
1989 mapvote_votes[i] = mapvote_votes[i] + 1;
1994 float MapVote_CheckRules_2()
1997 float firstPlace, secondPlace;
1998 float firstPlaceVotes, secondPlaceVotes;
1999 float mapvote_voters_real;
2002 mapvote_voters_real = mapvote_voters;
2004 mapvote_voters_real -= mapvote_votes[mapvote_count - 1];
2006 RandomSelection_Init();
2007 for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2008 RandomSelection_Add(world, i, 1, mapvote_votes[i]);
2009 firstPlace = RandomSelection_chosen_float;
2010 firstPlaceVotes = RandomSelection_best_priority;
2011 //dprint("First place: ", ftos(firstPlace), "\n");
2012 //dprint("First place votes: ", ftos(firstPlaceVotes), "\n");
2014 RandomSelection_Init();
2015 for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2017 RandomSelection_Add(world, i, 1, mapvote_votes[i]);
2018 secondPlace = RandomSelection_chosen_float;
2019 secondPlaceVotes = RandomSelection_best_priority;
2020 //dprint("Second place: ", ftos(secondPlace), "\n");
2021 //dprint("Second place votes: ", ftos(secondPlaceVotes), "\n");
2023 if(firstPlace == -1)
2024 error("No first place in map vote... WTF?");
2026 if(secondPlace == -1 || time > mapvote_timeout || (mapvote_voters_real - firstPlaceVotes) < firstPlaceVotes)
2027 return MapVote_Finished(firstPlace);
2029 if(mapvote_keeptwotime)
2030 if(time > mapvote_keeptwotime || (mapvote_voters_real - firstPlaceVotes - secondPlaceVotes) < secondPlaceVotes)
2033 mapvote_dirty = TRUE;
2034 mapvote_message = "Now decide between the TOP TWO!";
2035 mapvote_keeptwotime = 0;
2036 result = strcat(":vote:keeptwo:", mapvote_maps[firstPlace]);
2037 result = strcat(result, ":", ftos(firstPlaceVotes));
2038 result = strcat(result, ":", mapvote_maps[secondPlace]);
2039 result = strcat(result, ":", ftos(secondPlaceVotes), "::");
2040 didntvote = mapvote_voters;
2041 for(i = 0; i < mapvote_count; ++i)
2042 if(mapvote_maps[i] != "")
2044 didntvote -= mapvote_votes[i];
2046 if(i != secondPlace)
2048 result = strcat(result, ":", mapvote_maps[i]);
2049 result = strcat(result, ":", ftos(mapvote_votes[i]));
2050 if(i < mapvote_count_real)
2052 strunzone(mapvote_maps[i]);
2053 mapvote_maps[i] = "";
2057 result = strcat(result, ":didn't vote:", ftos(didntvote));
2058 if(cvar("sv_eventlog"))
2059 GameLogEcho(result);
2072 keeptwo = mapvote_keeptwotime;
2073 MapVote_CheckRules_1(); // count
2074 if(MapVote_CheckRules_2()) // decide
2078 FOR_EACH_REALCLIENT(other)
2080 // hide scoreboard again
2081 if(other.health != 2342)
2083 other.health = 2342;
2085 if(clienttype(other) == CLIENTTYPE_REAL)
2087 if(cvar("g_maplist_textonly"))
2088 stuffcmd(other, "\nin_bind 7 1 \"impulse 1\"; in_bind 7 2 \"impulse 2\"; in_bind 7 3 \"impulse 3\"; in_bind 7 4 \"impulse 4\"; in_bind 7 5 \"impulse 5\"; in_bind 7 6 \"impulse 6\"; in_bind 7 7 \"impulse 7\"; in_bind 7 8 \"impulse 8\"; in_bind 7 9 \"impulse 9\"; in_bind 7 0 \"impulse 10\"; in_bind 7 KP_1 \"impulse 1\"; in_bind 7 KP_2 \"impulse 2\"; in_bind 7 KP_3 \"impulse 3\"; in_bind 7 KP_4 \"impulse 4\"; in_bind 7 KP_5 \"impulse 5\"; in_bind 7 KP_6 \"impulse 6\"; in_bind 7 KP_7 \"impulse 7\"; in_bind 7 KP_8 \"impulse 8\"; in_bind 7 KP_9 \"impulse 9\"; in_bind 7 KP_0 \"impulse 10\"; in_bindmap 7 0\n");
2091 WriteByte(MSG_ONE, SVC_FINALE);
2092 WriteString(MSG_ONE, "");
2096 // notify about keep-two
2097 if(keeptwo != 0 && mapvote_keeptwotime == 0)
2098 play2(other, "misc/invshot.wav");
2100 // clear possibly invalid votes
2101 if(mapvote_maps[other.mapvote - 1] == "")
2103 // use impulses as new vote
2104 if(other.impulse >= 1 && other.impulse <= mapvote_count)
2105 if(mapvote_maps[other.impulse - 1] != "")
2107 other.mapvote = other.impulse;
2109 mapvote_dirty = TRUE;
2112 MapVote_TellVote(MSG_ONE, other.mapvote);
2120 MapVote_CheckRules_1(); // just count
2122 if(!cvar("g_maplist_textonly"))
2123 if(mapvote_dirty) // 1 if "keeptwo" or "impulse" happened before
2125 MapVote_UpdateData(MSG_BROADCAST);
2126 mapvote_dirty = FALSE;
2129 if(cvar("g_maplist_textonly"))
2131 FOR_EACH_REALCLIENT(other)
2133 // display voting screen
2134 msgstr = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
2135 msgstr = substring(msgstr, 0, strlen(msgstr) - mapvote_count);
2137 msgstr = substring(msgstr, 1, strlen(msgstr) - 1);
2138 msgstr = strcat(msgstr, mapvote_message);
2139 msgstr = strcat(msgstr, "\n\n");
2140 for(i = 0; i < mapvote_count; ++i)
2141 if(mapvote_maps[i] == "")
2142 msgstr = strcat(msgstr, "\n");
2145 tmp = mapvote_maps[i];
2146 tmp = strpad(mapvote_maxlen, tmp);
2147 tmp = strcat(ftos(mod(i + 1, 10)), ": ", tmp);
2150 tmp = strcat(tmp, " ^2(", ftos(mapvote_votes[i]), " vote");
2151 if(mapvote_votes[i] != 1)
2152 tmp = strcat(tmp, "s");
2153 tmp = strcat(tmp, ")");
2154 tmp = strpad(mapvote_maxlen + 15, tmp);
2157 if(i == mapvote_count - 1)
2158 msgstr = strcat(msgstr, "\n");
2159 if(other.mapvote == i + 1)
2160 msgstr = strcat(msgstr, "^3> ", tmp, "\n");
2162 msgstr = strcat(msgstr, "^7 ", tmp, "\n");
2165 msgstr = strcat(msgstr, "\n\n^2", ftos(totalvotes), " vote");
2167 msgstr = strcat(msgstr, "s");
2168 msgstr = strcat(msgstr, " cast");
2169 i = ceil(mapvote_timeout - time);
2170 msgstr = strcat(msgstr, "\n", ftos(i), " second");
2172 msgstr = strcat(msgstr, "s");
2173 msgstr = strcat(msgstr, " left");
2175 centerprint_atprio(other, CENTERPRIO_MAPVOTE, msgstr);
2179 void MapVote_Start()
2184 MapInfo_Enumerate();
2185 if(MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 0, (g_maplist_allow_hidden ? MAPINFO_FLAG_HIDDEN : 0), 1))
2188 void MapVote_Think()
2193 if(alreadychangedlevel)
2196 if(time < mapvote_nextthink)
2200 mapvote_nextthink = time + 0.5;
2202 if(!mapvote_initialized)
2204 mapvote_initialized = TRUE;
2205 if(DoNextMapOverride())
2207 if(!cvar("g_maplist_votable") || player_count <= 0)
2218 string GotoMap(string m)
2220 if(!MapInfo_CheckMap(m))
2221 return "The map you chose is not available on this server.";
2222 cvar_set("nextmap", m);
2223 cvar_set("timelimit", "-1");
2224 if(mapvote_initialized || alreadychangedlevel)
2226 if(DoNextMapOverride())
2227 return "Map switch initiated.";
2229 return "Hm... no. For some reason I like THIS map more.";
2232 return "Map switch will happen after scoreboard.";
2238 FOR_EACH_REALCLIENT(self)
2240 if(self.classname == "spectator")
2242 if(self.enemy.typehitsound)
2243 play2(self, "misc/typehit.wav");
2244 else if(self.enemy.hitsound)
2245 play2(self, "misc/hit.wav");
2249 if(self.typehitsound)
2250 play2(self, "misc/typehit.wav");
2251 else if(self.hitsound)
2252 play2(self, "misc/hit.wav");
2255 FOR_EACH_CLIENT(self)
2257 self.hitsound = FALSE;
2258 self.typehitsound = FALSE;
2265 * returns TRUE if redirecting
2267 float redirection_timeout;
2268 float redirection_nextthink;
2269 float RedirectionThink()
2271 float clients_found;
2273 if(redirection_target == "")
2276 if(!redirection_timeout)
2278 cvar_set("sv_public", "-2");
2279 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2280 if(redirection_target == "self")
2281 bprint("^3SERVER NOTICE:^7 restarting the server\n");
2283 bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2286 if(time < redirection_nextthink)
2289 redirection_nextthink = time + 1;
2292 FOR_EACH_REALCLIENT(self)
2294 print("Redirecting: sending connect command to ", self.netname, "\n");
2295 if(redirection_target == "self")
2296 stuffcmd(self, "\ndisconnect; reconnect\n");
2298 stuffcmd(self, strcat("\ndisconnect; connect ", redirection_target, "\n"));
2302 print("Redirecting: ", ftos(clients_found), " clients left.\n");
2304 if(time > redirection_timeout || clients_found == 0)
2305 localcmd("\nwait; wait; wait; quit\n");
2312 // Loaded from a save game
2313 // some things then break, so let's work around them...
2315 // Progs DB (capture records)
2317 ServerProgsDB = db_create();
2319 ServerProgsDB = db_load("server.db");
2323 MapInfo_Enumerate();
2324 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 0, (g_maplist_allow_hidden ? MAPINFO_FLAG_HIDDEN : 0), 1);
2329 if(world_initialized)
2331 world_initialized = 0;
2332 print("Saving persistent data...\n");
2335 db_save(ServerProgsDB, "server.db");
2336 if(cvar("developer"))
2337 db_save(TemporaryDB, "server-temp.db");
2338 db_close(ServerProgsDB);
2339 db_close(TemporaryDB);
2341 // tell the bot system the game is ending now
2348 print("NOTE: crashed before even initializing the world, not saving persistent data\n");