]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/g_world.qc
change g_maplist_mostrecent_count behaviour to insert the new map AFTER, not BEFORE...
[divverent/nexuiz.git] / data / qcsrc / server / g_world.qc
1 float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
2 string redirection_target;
3 float world_initialized;
4
5 string GetMapname();
6 string GetGametype();
7 void GotoNextMap();
8 void ShuffleMaplist()
9 float() DoNextMapOverride;
10
11 void SetDefaultAlpha()
12 {
13         if(cvar("g_running_guns"))
14         {
15                 default_player_alpha = -1;
16                 default_weapon_alpha = +1;
17         }
18         else if(g_cloaked)
19         {
20                 default_player_alpha = cvar("g_balance_cloaked_alpha");
21                 default_weapon_alpha = default_player_alpha;
22         }
23         else
24         {
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;
29         }
30 }
31
32 void fteqcc_testbugs()
33 {
34         float a, b;
35
36         if(!cvar("developer_fteqccbugs"))
37                 return;
38
39         dprint("*** fteqcc test: checking for bugs...\n");
40
41         a = 1;
42         b = 5;
43         if(sqrt(a) - sqrt(b - a) == 0)
44                 dprint("*** fteqcc test: found same-function-twice bug\n");
45         else
46                 dprint("*** fteqcc test: same-function-twice bug got FINALLY FIXED! HOORAY!\n");
47
48         world.cnt = -10;
49         world.enemy = world;
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");
53         else
54                 dprint("*** fteqcc test: += bug got FINALLY FIXED! HOORAY!\n");
55         world.cnt = 0;
56 }
57
58 /**
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.
62  */
63 void timeoutHandler_Think() {
64         local string timeStr;
65         local entity plr;
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);
73                                 }
74                         }
75                         remainingLeadTime -= 1;
76                         //think again in 1 second:
77                         self.nextthink = time + 1;
78                 }
79                 else {
80                         //now pause the game:
81                         timeoutStatus = 2;
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;
86                         }
87                         self.nextthink = time;
88                 }
89         }
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);
96                                 }
97                         }
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");
100                         }
101                         remainingTimeoutTime -= 1;
102                         self.nextthink = time + TIMEOUT_SLOWMO_VALUE;
103                 }
104                 else {
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;
111                         }
112                         //get rid of the countdown message
113                         FOR_EACH_REALCLIENT(plr) {
114                                 if(plr.classname == "player") {
115                                         centerprint_atprio(plr, CENTERPRIO_SPAM, "");
116                                 }
117                         }
118                         remove(self);
119                         return;
120                 }
121                 
122         }
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, "");
127                         }
128                 }
129                 remove(self);
130                 return;
131         }
132 }
133
134 float GotoFirstMap()
135 {
136         if(cvar("_sv_init"))
137         {
138                 cvar_set("_sv_init", "0");
139                 if(cvar("g_maplist_shuffle"))
140                         ShuffleMaplist();
141                 tokenizebyseparator(cvar_string("g_maplist"), " ");
142                 {
143                         cvar_set("nextmap", argv(0));
144
145                         MapInfo_Enumerate();
146                         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 0, (g_maplist_allow_hidden ? MAPINFO_FLAG_HIDDEN : 0), 0);
147
148                         if(!DoNextMapOverride())
149                                 GotoNextMap();
150
151                         return 1;
152                 }
153         }
154         return 0;
155 }
156
157 void cvar_changes_init()
158 {
159         float h;
160         string k, v, d;
161         float n, i;
162
163         if(cvar_changes)
164                 strunzone(cvar_changes);
165         cvar_changes = string_null;
166
167         h = buf_create();
168         buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
169         n = buf_getsize(h);
170
171         for(i = 0; i < n; ++i)
172         {
173                 k = bufstr_get(h, i);
174
175 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
176 #define BADCVAR(p) if(k == p) continue
177                 // internal
178                 BADPREFIX("csqc_");
179                 BADPREFIX("cvar_check_");
180                 BADCVAR("gamecfg");
181                 BADCVAR("g_configversion");
182                 BADCVAR("g_maplist_index");
183                 BADCVAR("halflifebsp");
184
185                 // client
186                 BADPREFIX("cl_");
187                 BADPREFIX("con_");
188                 BADPREFIX("g_campaign");
189                 BADPREFIX("gl_");
190                 BADPREFIX("joy");
191                 BADPREFIX("menu_");
192                 BADPREFIX("net_slist_");
193                 BADPREFIX("r_");
194                 BADPREFIX("sbar_");
195                 BADPREFIX("scr_");
196                 BADPREFIX("userbind");
197                 BADPREFIX("v_");
198                 BADPREFIX("vid_");
199                 BADCVAR("mod_q3bsp_lightmapmergepower");
200                 BADCVAR("mod_q3bsp_nolightmaps");
201
202                 // private
203                 BADPREFIX("g_ban_");
204                 BADPREFIX("g_chat_flood_");
205                 BADPREFIX("rcon_");
206                 BADPREFIX("settemp_");
207                 BADPREFIX("sv_allowdownloads_");
208                 BADPREFIX("sv_autodemo");
209                 BADPREFIX("sv_curl_");
210                 BADPREFIX("sv_eventlog");
211                 BADPREFIX("sv_logscores_");
212                 BADPREFIX("sv_master");
213                 BADCVAR("g_banned_list");
214                 BADCVAR("log_dest_udp");
215                 BADCVAR("log_file");
216                 BADCVAR("net_address");
217                 BADCVAR("port");
218                 BADCVAR("savedgamecfg");
219                 BADCVAR("sv_heartbeatperoid");
220                 BADCVAR("sv_vote_master_password");
221                 BADCVAR("sys_colortranslation");
222                 BADCVAR("sys_specialcharactertranslation");
223                 BADCVAR("timestamps");
224
225                 // mapinfo
226                 BADCVAR("timelimit");
227                 BADCVAR("fraglimit");
228                 BADCVAR("g_arena");
229                 BADCVAR("g_assault");
230                 BADCVAR("g_ctf");
231                 BADCVAR("g_dm");
232                 BADCVAR("g_domination");
233                 BADCVAR("g_keyhunt");
234                 BADCVAR("g_keyhunt_teams");
235                 BADCVAR("g_onslaught");
236                 BADCVAR("g_race");
237                 BADCVAR("g_runematch");
238                 BADCVAR("g_tdm");
239                 BADCVAR("teamplay");
240
241                 // long
242                 BADCVAR("hostname");
243                 BADCVAR("g_maplist");
244                 BADCVAR("g_maplist_mostrecent");
245                 BADCVAR("sv_motd");
246 #undef BADPREFIX
247 #undef BADCVAR
248
249                 v = cvar_string(k);
250                 d = cvar_defstring(k);
251                 if(v != d)
252                 {
253                         cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
254                         if(strlen(cvar_changes) > 16384)
255                         {
256                                 cvar_changes = "// too many settings have been changed to show them here\n";
257                                 break;
258                         }
259                 }
260         }
261         buf_del(h);
262         if(cvar_changes == "")
263                 cvar_changes = "// this server runs at default settings\n";
264         else
265                 cvar_changes = strcat("// this server runs at modified settings:\n", cvar_changes);
266         cvar_changes = strzone(cvar_changes);
267 }
268
269 void detect_maptype()
270 {
271 #if 0
272         vector o, v;
273         float i;
274
275         for(;;)
276         {
277                 o = world.mins;
278                 o_x += random() * (world.maxs_x - world.mins_x);
279                 o_y += random() * (world.maxs_y - world.mins_y);
280                 o_z += random() * (world.maxs_z - world.mins_z);
281
282                 tracebox(o, PL_MIN, PL_MAX, o - '0 0 32768', MOVE_WORLDONLY, world);
283                 if(trace_fraction == 1)
284                         continue;
285                 
286                 v = trace_endpos;
287
288                 for(i = 0; i < 64; i += 4)
289                 {
290                         tracebox(o, '-1 -1 -1' * i, '1 1 1' * i, o - '0 0 32768', MOVE_WORLDONLY, world);
291         if(trace_fraction == 1)
292                 continue;
293                         print(ftos(i), " -> ", vtos(trace_endpos), "\n");
294                 }
295
296                 break;
297         }
298 #endif
299 }
300
301 entity randomseed;
302 float RandomSeed_Send(entity to, float sf)
303 {
304         WriteByte(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
305         WriteShort(MSG_ENTITY, self.cnt);
306         return TRUE;
307 }
308 void RandomSeed_Think()
309 {
310         self.cnt = bound(0, floor(random() * 65536), 65535);
311         self.nextthink = time + 5;
312
313         self.SendFlags |= 1;
314 }
315 void RandomSeed_Spawn()
316 {
317         randomseed = spawn();
318         randomseed.think = RandomSeed_Think;
319         Net_LinkEntity(randomseed, FALSE, 0, RandomSeed_Send);
320
321         entity oldself;
322         oldself = self;
323         self = randomseed;
324         self.think(); // sets random seed and nextthink
325         self = oldself;
326 }
327
328 void Map_MarkAsRecent(string m);
329 float world_already_spawned;
330 void RegisterWeapons();
331 void Nagger_Init();
332 void ClientInit_Spawn();
333 void spawnfunc_worldspawn (void)
334 {
335         float fd, l, i, j, n;
336         string s, col;
337
338         dprint_load(); // load dprint status from cvar
339
340         if(world_already_spawned)
341                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
342         world_already_spawned = TRUE;
343
344         remove = remove_safely; // during spawning, watch what you remove!
345
346         if(cvar_string("cvar_check_default") != "bypass")
347         {
348                 if(cvar_string("cvar_check_default") != CVAR_CHECK_DEFAULT)
349                         error("Config file mismatch! Please update defaultNexuiz.cfg to match the QuakeC code!");
350
351                 if(cvar_string("cvar_check_weapons") != CVAR_CHECK_WEAPONS)
352                         error("Config file mismatch! Please update weapons.cfg and weaponsPro.cfg to match the QuakeC code!");
353         }
354
355         compressShortVector_init();
356
357         local entity head;
358         head = nextent(world);
359         maxclients = 0;
360         while(head)
361         {
362                 ++maxclients;
363                 head = nextent(head);
364         }
365
366         // needs to be done so early as they would still spawn
367         RegisterWeapons();
368
369         if(GotoFirstMap())
370         {
371                 world_initialized = -1; // don't complain
372                 return;
373         }
374
375         if(sv_cheats)
376                 ServerProgsDB = db_create();
377         else
378                 ServerProgsDB = db_load("server.db");
379
380         TemporaryDB = db_create();
381
382         /*
383         TODO sound pack system
384         // initialize sound pack system
385         soundpack = cvar_string("g_soundpack");
386         if(soundpack != "")
387                 soundpack = strcat(soundpack, "/");
388         soundpack = strzone(soundpack);
389         */
390
391         // 0 normal
392         lightstyle(0, "m");
393
394         // 1 FLICKER (first variety)
395         lightstyle(1, "mmnmmommommnonmmonqnmmo");
396
397         // 2 SLOW STRONG PULSE
398         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
399
400         // 3 CANDLE (first variety)
401         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
402
403         // 4 FAST STROBE
404         lightstyle(4, "mamamamamama");
405
406         // 5 GENTLE PULSE 1
407         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
408
409         // 6 FLICKER (second variety)
410         lightstyle(6, "nmonqnmomnmomomno");
411
412         // 7 CANDLE (second variety)
413         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
414
415         // 8 CANDLE (third variety)
416         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
417
418         // 9 SLOW STROBE (fourth variety)
419         lightstyle(9, "aaaaaaaazzzzzzzz");
420
421         // 10 FLUORESCENT FLICKER
422         lightstyle(10, "mmamammmmammamamaaamammma");
423
424         // 11 SLOW PULSE NOT FADE TO BLACK
425         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
426
427         // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
428
429         // 63 testing
430         lightstyle(63, "a");
431
432         if(cvar("g_campaign"))
433                 CampaignPreInit();
434
435         Map_MarkAsRecent(mapname);
436
437         InitGameplayMode();
438         readlevelcvars();
439         GrappleHookInit();
440
441         player_count = 0;
442         bot_waypoints_for_items = cvar("g_waypoints_for_items");
443         if(bot_waypoints_for_items == 1)
444                 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
445                         bot_waypoints_for_items = 0;
446
447         // for setting by mapinfo
448         q3acompat_machineshotgunswap = cvar("sv_q3acompat_machineshotgunswap");
449         cvar_set("sv_q3acompat_machineshotgunswap", "0");
450
451         precache();
452
453         WaypointSprite_Init();
454
455         //if (g_domination)
456         //      dom_init();
457
458         GameLogInit(); // prepare everything
459         if(cvar("sv_eventlog"))
460         {
461                 s = strcat(cvar_string("sv_eventlog_files_counter"), ".");
462                 s = strcat(s, ftos(random()));
463                 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
464                 s = ":gameinfo:mutators:LIST";
465                 if(cvar("g_grappling_hook"))
466                         s = strcat(s, ":grappling_hook");
467                 if(!cvar("g_use_ammunition"))
468                         s = strcat(s, ":no_use_ammunition");
469                 if(!cvar("g_pickup_items"))
470                         s = strcat(s, ":no_pickup_items");
471                 if(cvar("g_instagib"))
472                         s = strcat(s, ":instagib");
473                 if(cvar_string("g_weaponarena") != "0")
474                         s = strcat(s, ":", cvar_string("g_weaponarena"), " arena");
475                 if(cvar("g_nixnex"))
476                         s = strcat(s, ":nixnex");
477                 if(cvar("g_vampire"))
478                         s = strcat(s, ":vampire");
479                 if(cvar("g_laserguided_missile"))
480                         s = strcat(s, ":laserguided_missile");
481                 if(cvar("g_norecoil"))
482                         s = strcat(s, ":norecoil");
483                 if(cvar("g_midair"))
484                         s = strcat(s, ":midair");
485                 if(cvar("g_minstagib"))
486                         s = strcat(s, ":minstagib");
487                 GameLogEcho(s);
488                 GameLogEcho(":gameinfo:end");
489         }
490
491         cvar_set("nextmap", "");
492
493         SetDefaultAlpha();
494
495         if(cvar("g_campaign"))
496                 CampaignPostInit();
497
498         fteqcc_testbugs();
499
500         Ban_LoadBans();
501
502         //initialise globals related to sv_timeout
503         sys_ticrate = cvar("sys_ticrate");
504         orig_slowmo = cvar("slowmo");
505
506         MapInfo_Enumerate();
507         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 0, (g_maplist_allow_hidden ? MAPINFO_FLAG_HIDDEN : 0), 1);
508
509         if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
510         {
511                 fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
512                 if(fd != -1)
513                 {
514                         while((s = fgets(fd)))
515                         {
516                                 l = tokenize_sane(s);
517                                 if(l < 2)
518                                         continue;
519                                 if(argv(0) == "cd")
520                                 {
521                                         print("Found ^1DEPRECATED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
522                                         print("  cdtrack ", argv(2), "\n");
523                                 }
524                                 else if(argv(0) == "fog")
525                                 {
526                                         print("Found ^1DEPRECATED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
527                                         print("  \"fog\" \"", s, "\"\n");
528                                 }
529                                 else if(argv(0) == "set")
530                                 {
531                                         print("Found ^1DEPRECATED^7 set command in .cfg file; put this line in mapinfo instead:\n");
532                                         print("  clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
533                                 }
534                                 else if(argv(0) != "//")
535                                 {
536                                         print("Found ^1DEPRECATED^7 set command in .cfg file; put this line in mapinfo instead:\n");
537                                         print("  clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
538                                 }
539                         }
540                         fclose(fd);
541                 }
542         }
543
544         addstat(STAT_SYS_TICRATE, AS_FLOAT, stat_sys_ticrate);
545         addstat(STAT_WEAPONS, AS_INT, weapons);
546         addstat(STAT_SWITCHWEAPON, AS_INT, switchweapon);
547         addstat(STAT_GAMESTARTTIME, AS_FLOAT, stat_game_starttime);
548         addstat(STAT_ALLOW_OLDNEXBEAM, AS_INT, stat_allow_oldnexbeam);
549         Nagger_Init();
550         
551         addstat(STAT_STRENGTH_FINISHED, AS_FLOAT, strength_finished);
552         addstat(STAT_INVINCIBLE_FINISHED, AS_FLOAT, invincible_finished);
553
554         addstat(STAT_PRESSED_KEYS, AS_FLOAT, pressedkeys);
555
556         next_pingtime = time + 5;
557         InitializeEntity(self, cvar_changes_init, INITPRIO_CVARS);
558
559         detect_maptype();
560
561         lsmaps_reply = "^7Maps available: ";
562         for(i = 0, j = 0; i < MapInfo_count; ++i)
563         {
564                 if(MapInfo_Get_ByID(i))
565                         if not(MapInfo_Map_flags & MAPINFO_FLAG_HIDDEN)
566                         {
567                                 if(mod(i, 2))
568                                         col = "^2";
569                                 else
570                                         col = "^3";
571                                 ++j;
572                                 lsmaps_reply = strcat(lsmaps_reply, col, MapInfo_Map_bspname, " ");
573                         }
574         }
575         lsmaps_reply = strzone(strcat(lsmaps_reply, "\n"));
576
577         maplist_reply = "^7Maps in list: ";
578         n = tokenize_sane(cvar_string("g_maplist"));
579         for(i = 0, j = 0; i < n; ++i)
580         {
581                 if(MapInfo_CheckMap(argv(i)))
582                 {
583                         if(mod(j, 2))
584                                 col = "^2";
585                         else
586                                 col = "^3";
587                         maplist_reply = strcat(maplist_reply, col, argv(i), " ");
588                         ++j;
589                 }
590         }
591         maplist_reply = strzone(strcat(maplist_reply, "\n"));
592
593         records_reply = strzone(getrecords());
594
595         ClientInit_Spawn();
596         RandomSeed_Spawn();
597
598         world_initialized = 1;
599 }
600
601 void spawnfunc_light (void)
602 {
603         //makestatic (self); // Who the f___ did that?
604         remove(self);
605 }
606
607 float TryFile( string pFilename )
608 {
609         local float lHandle;
610         dprint("TryFile(\"", pFilename, "\")\n");
611         lHandle = fopen( pFilename, FILE_READ );
612         if( lHandle != -1 ) {
613                 fclose( lHandle );
614                 return TRUE;
615         } else {
616                 return FALSE;
617         }
618 };
619
620 string GetGametype()
621 {
622         return GametypeNameFromType(game);
623 }
624
625 string getmapname_stored;
626 string GetMapname()
627 {
628         return mapname;
629 }
630
631 float Map_Count, Map_Current;
632 string Map_Current_Name;
633
634 // NOTE: this now expects the map list to be already tokenize()d and the count in Map_Count
635 float GetMaplistPosition()
636 {
637         float pos, idx;
638         string map;
639
640         map = GetMapname();
641         idx = cvar("g_maplist_index");
642
643         if(idx >= 0)
644                 if(idx < Map_Count)
645                         if(map == argv(idx))
646                                 return idx;
647
648         for(pos = 0; pos < Map_Count; ++pos)
649                 if(map == argv(pos))
650                         return pos;
651
652         // resume normal maplist rotation if current map is not in g_maplist
653         return idx;
654 }
655
656 float MapHasRightSize(string map)
657 {
658         float fh;
659         if(currentbots || cvar("bot_number") || player_count < cvar("minplayers"))
660         if(cvar("g_maplist_check_waypoints"))
661         {
662                 dprint("checkwp "); dprint(map);
663                 fh = fopen(strcat("maps/", map, ".waypoints"), FILE_READ);
664                 if(fh < 0)
665                 {
666                         dprint(": no waypoints\n");
667                         return FALSE;
668                 }
669                 dprint(": has waypoints\n");
670                 fclose(fh);
671         }
672
673         // open map size restriction file
674         dprint("opensize "); dprint(map);
675         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
676         if(fh >= 0)
677         {
678                 float mapmin, mapmax;
679                 dprint(": ok, ");
680                 mapmin = stof(fgets(fh));
681                 mapmax = stof(fgets(fh));
682                 fclose(fh);
683                 if(player_count < mapmin)
684                 {
685                         dprint("not enough\n");
686                         return FALSE;
687                 }
688                 if(player_count > mapmax)
689                 {
690                         dprint("too many\n");
691                         return FALSE;
692                 }
693                 dprint("right size\n");
694                 return TRUE;
695         }
696         dprint(": not found\n");
697         return TRUE;
698 }
699
700 string Map_Filename(float position)
701 {
702         return strcat("maps/", argv(position), ".bsp");
703 }
704
705 string strwords(string s, float w)
706 {
707         float endpos;
708         for(endpos = 0; w && endpos >= 0; --w)
709                 endpos = strstrofs(s, " ", endpos + 1);
710         if(endpos < 0)
711                 return s;
712         else
713                 return substring(s, 0, endpos);
714 }
715
716 float strhasword(string s, string w)
717 {
718         return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
719 }
720
721 void Map_MarkAsRecent(string m)
722 {
723         cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", cvar_string("g_maplist_mostrecent")), max(0, cvar("g_maplist_mostrecent_count"))));
724 }
725
726 float Map_IsRecent(string m)
727 {
728         return strhasword(cvar_string("g_maplist_mostrecent"), m);
729 }
730
731 float Map_Check(float position, float pass)
732 {
733         string filename;
734         string map_next;
735         map_next = argv(position);
736         if(pass <= 1)
737         {
738                 if(Map_IsRecent(map_next))
739                         return 0;
740         }
741         filename = Map_Filename(position);
742         if(MapInfo_CheckMap(map_next))
743         {
744                 if(pass == 2)
745                         return 1;
746                 if(MapHasRightSize(map_next))
747                         return 1;
748                 return 0;
749         }
750         else
751                 dprint( "Couldn't select '", filename, "'..\n" );
752
753         return 0;
754 }
755
756 void Map_Goto_SetStr(string nextmapname)
757 {
758         if(getmapname_stored != "")
759                 strunzone(getmapname_stored);
760         if(nextmapname == "")
761                 getmapname_stored = "";
762         else
763                 getmapname_stored = strzone(nextmapname);
764 }
765
766 void Map_Goto_SetFloat(float position)
767 {
768         cvar_set("g_maplist_index", ftos(position));
769         Map_Goto_SetStr(argv(position));
770 }
771
772 void GameResetCfg()
773 {
774         // settings persist, except...
775         if(cvar("g_campaign"))
776                 localcmd("\nexec mutator_reset.cfg\n");
777         localcmd("\nsettemp_restore\n");
778 };
779
780 void Map_Goto()
781 {
782         GameResetCfg();
783         MapInfo_LoadMap(getmapname_stored);
784 }
785
786 // return codes of map selectors:
787 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
788 //   -2 = permanent failure
789 float() MaplistMethod_Iterate = // usual method
790 {
791         float pass, i;
792
793         for(pass = 1; pass <= 2; ++pass)
794         {
795                 for(i = 1; i < Map_Count; ++i)
796                 {
797                         float mapindex;
798                         mapindex = mod(i + Map_Current, Map_Count);
799                         if(Map_Check(mapindex, pass))
800                                 return mapindex;
801                 }
802         }
803         return -1;
804 }
805
806 float() MaplistMethod_Repeat = // fallback method
807 {
808         if(Map_Check(Map_Current, 2))
809                 return Map_Current;
810         return -2;
811 }
812
813 float() MaplistMethod_Random = // random map selection
814 {
815         float i, imax;
816
817         imax = 42;
818
819         for(i = 0; i <= imax; ++i)
820         {
821                 float mapindex;
822                 mapindex = mod(Map_Current + floor(random() * (Map_Count - 1) + 1), Map_Count); // any OTHER map
823                 if(Map_Check(mapindex, 1))
824                         return mapindex;
825         }
826         return -1;
827 }
828
829 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
830 // the exponent sets a bias on the map selection:
831 // the higher the exponent, the less likely "shortly repeated" same maps are
832 {
833         float i, j, imax, insertpos;
834
835         imax = 42;
836
837         for(i = 0; i <= imax; ++i)
838         {
839                 string newlist;
840
841                 // now reinsert this at another position
842                 insertpos = pow(random(), 1 / exponent);       // ]0, 1]
843                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
844                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
845                 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
846
847                 // insert the current map there
848                 newlist = "";
849                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
850                         newlist = strcat(newlist, " ", argv(j));
851                 newlist = strcat(newlist, " ", argv(0));       // now insert the just selected map
852                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
853                         newlist = strcat(newlist, " ", argv(j));
854                 newlist = substring(newlist, 1, strlen(newlist) - 1);
855                 cvar_set("g_maplist", newlist);
856                 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
857
858                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
859                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
860                 if(Map_Check(Map_Current, 1))
861                         return Map_Current;
862         }
863         return -1;
864 }
865
866 void Maplist_Init()
867 {
868         Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
869         if(Map_Count == 0)
870         {
871                 bprint( "Maplist is empty!  Resetting it to default map list.\n" );
872                 cvar_set("g_maplist", MapInfo_ListAllowedMaps(0, MAPINFO_FLAG_HIDDEN));
873                 if(cvar("g_maplist_shuffle"))
874                         ShuffleMaplist();
875                 localcmd("\nmenu_cmd sync\n");
876                 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
877         }
878         if(Map_Count == 0)
879                 error("empty maplist, cannot select a new map");
880         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
881
882         if(Map_Current_Name)
883                 strunzone(Map_Current_Name);
884         Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
885         // this may or may not be correct, but who cares, in the worst case a map
886         // isn't chosen in the first pass that should have been
887 }
888
889 string GetNextMap()
890 {
891         float nextMap;
892
893         Maplist_Init();
894         nextMap = -1;
895
896         if(nextMap == -1)
897                 if(cvar("g_maplist_shuffle") > 0)
898                         nextMap = MaplistMethod_Shuffle(cvar("g_maplist_shuffle") + 1);
899
900         if(nextMap == -1)
901                 if(cvar("g_maplist_selectrandom"))
902                         nextMap = MaplistMethod_Random();
903
904         if(nextMap == -1)
905                 nextMap = MaplistMethod_Iterate();
906
907         if(nextMap == -1)
908                 nextMap = MaplistMethod_Repeat();
909
910         if(nextMap >= 0)
911         {
912                 Map_Goto_SetFloat(nextMap);
913                 return getmapname_stored;
914         }
915
916         return "";
917 };
918
919 float DoNextMapOverride()
920 {
921         if(cvar("g_campaign"))
922         {
923                 CampaignPostIntermission();
924                 alreadychangedlevel = TRUE;
925                 return TRUE;
926         }
927         if(cvar("quit_when_empty"))
928         {
929                 if(player_count <= currentbots)
930                 {
931                         localcmd("quit\n");
932                         alreadychangedlevel = TRUE;
933                         return TRUE;
934                 }
935         }
936         if(cvar_string("quit_and_redirect") != "")
937         {
938                 redirection_target = strzone(cvar_string("quit_and_redirect"));
939                 alreadychangedlevel = TRUE;
940                 return TRUE;
941         }
942         if (cvar("samelevel")) // if samelevel is set, stay on same level
943         {
944                 // 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)
945                 //localcmd(strcat("exec \"maps/", mapname, ".mapcfg\"\n"));
946                 // so instead just restart the current map using the restart command (DOES NOT WORK PROPERLY WITH exit_cfg STUFF)
947                 localcmd("restart\n");
948                 //changelevel (mapname);
949                 alreadychangedlevel = TRUE;
950                 return TRUE;
951         }
952         if(cvar_string("nextmap") != "")
953                 if(MapInfo_CheckMap(cvar_string("nextmap")))
954                 {
955                         Map_Goto_SetStr(cvar_string("nextmap"));
956                         Map_Goto();
957                         alreadychangedlevel = TRUE;
958                         return TRUE;
959                 }
960         if(cvar("lastlevel"))
961         {
962                 GameResetCfg();
963                 localcmd("set lastlevel 0\ntogglemenu\n");
964                 alreadychangedlevel = TRUE;
965                 return TRUE;
966         }
967         return FALSE;
968 };
969
970 void GotoNextMap()
971 {
972         //local string nextmap;
973         //local float n, nummaps;
974         //local string s;
975         if (alreadychangedlevel)
976                 return;
977         alreadychangedlevel = TRUE;
978
979         {
980                 string nextMap;
981                 float allowReset;
982
983                 for(allowReset = 1; allowReset >= 0; --allowReset)
984                 {
985                         nextMap = GetNextMap();
986                         if(nextMap != "")
987                                 break;
988
989                         if(allowReset)
990                         {
991                                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
992                                 cvar_set("g_maplist", MapInfo_ListAllowedMaps(0, MAPINFO_FLAG_HIDDEN));
993                                 if(cvar("g_maplist_shuffle"))
994                                         ShuffleMaplist();
995                                 localcmd("\nmenu_cmd sync\n");
996                         }
997                         else
998                         {
999                                 error("Everything is broken - not even the default map list works. Please report this to the developers.");
1000                         }
1001                 }
1002                 Map_Goto();
1003         }
1004 };
1005
1006
1007 /*
1008 ============
1009 IntermissionThink
1010
1011 When the player presses attack or jump, change to the next level
1012 ============
1013 */
1014 .float autoscreenshot;
1015 void() MapVote_Start;
1016 void() MapVote_Think;
1017 float mapvote_initialized;
1018 void IntermissionThink()
1019 {
1020         FixIntermissionClient(self);
1021
1022         if(cvar("sv_autoscreenshot"))
1023         if(self.autoscreenshot > 0)
1024         if(time > self.autoscreenshot)
1025         {
1026                 self.autoscreenshot = -1;
1027                 if(clienttype(self) == CLIENTTYPE_REAL)
1028                         stuffcmd(self, "\nscreenshot\necho \"^5A screenshot has been taken at request of the server.\"\n");
1029                 return;
1030         }
1031
1032         if (time < intermission_exittime)
1033                 return;
1034
1035         if(!mapvote_initialized)
1036                 if (time < intermission_exittime + 10 && !self.BUTTON_ATCK && !self.BUTTON_JUMP && !self.BUTTON_ATCK2 && !self.BUTTON_HOOK && !self.BUTTON_USE)
1037                         return;
1038
1039         MapVote_Start();
1040 };
1041
1042 /*
1043 ============
1044 FindIntermission
1045
1046 Returns the entity to view from
1047 ============
1048 */
1049 /*
1050 entity FindIntermission()
1051 {
1052         local   entity spot;
1053         local   float cyc;
1054
1055 // look for info_intermission first
1056         spot = find (world, classname, "info_intermission");
1057         if (spot)
1058         {       // pick a random one
1059                 cyc = random() * 4;
1060                 while (cyc > 1)
1061                 {
1062                         spot = find (spot, classname, "info_intermission");
1063                         if (!spot)
1064                                 spot = find (spot, classname, "info_intermission");
1065                         cyc = cyc - 1;
1066                 }
1067                 return spot;
1068         }
1069
1070 // then look for the start position
1071         spot = find (world, classname, "info_player_start");
1072         if (spot)
1073                 return spot;
1074
1075 // testinfo_player_start is only found in regioned levels
1076         spot = find (world, classname, "testplayerstart");
1077         if (spot)
1078                 return spot;
1079
1080 // then look for the start position
1081         spot = find (world, classname, "info_player_deathmatch");
1082         if (spot)
1083                 return spot;
1084
1085         //objerror ("FindIntermission: no spot");
1086         return world;
1087 };
1088 */
1089
1090 /*
1091 ===============================================================================
1092
1093 RULES
1094
1095 ===============================================================================
1096 */
1097
1098 void DumpStats(float final)
1099 {
1100         local float file;
1101         local string s;
1102         local float to_console;
1103         local float to_eventlog;
1104         local float to_file;
1105         local float i;
1106
1107         to_console = cvar("sv_logscores_console");
1108         to_eventlog = cvar("sv_eventlog");
1109         to_file = cvar("sv_logscores_file");
1110
1111         if(!final)
1112         {
1113                 to_console = TRUE; // always print printstats replies
1114                 to_eventlog = FALSE; // but never print them to the event log
1115         }
1116
1117         if(to_eventlog)
1118                 if(cvar("sv_eventlog_console"))
1119                         to_console = FALSE; // otherwise we get the output twice
1120
1121         if(final)
1122                 s = ":scores:";
1123         else
1124                 s = ":status:";
1125         s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1126
1127         if(to_console)
1128                 print(s, "\n");
1129         if(to_eventlog)
1130                 GameLogEcho(s);
1131         if(to_file)
1132         {
1133                 file = fopen(cvar_string("sv_logscores_filename"), FILE_APPEND);
1134                 if(file == -1)
1135                         to_file = FALSE;
1136                 else
1137                         fputs(file, strcat(s, "\n"));
1138         }
1139
1140         s = strcat(":labels:player:", GetPlayerScoreString(world, 0));
1141         if(to_console)
1142                 print(s, "\n");
1143         if(to_eventlog)
1144                 GameLogEcho(s);
1145         if(to_file)
1146                 fputs(file, strcat(s, "\n"));
1147
1148         FOR_EACH_CLIENT(other)
1149         {
1150                 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && cvar("sv_logscores_bots")))
1151                 {
1152                         s = strcat(":player:see-labels:", GetPlayerScoreString(other, 0), ":");
1153                         s = strcat(s, ftos(rint(time - other.jointime)), ":");
1154                         if(other.classname == "player" || g_arena || g_lms)
1155                                 s = strcat(s, ftos(other.team), ":");
1156                         else
1157                                 s = strcat(s, "spectator:");
1158
1159                         if(to_console)
1160                                 print(s, other.netname, "\n");
1161                         if(to_eventlog)
1162                                 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname));
1163                         if(to_file)
1164                                 fputs(file, strcat(s, other.netname, "\n"));
1165                 }
1166         }
1167
1168         if(teamplay)
1169         {
1170                 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1171                 if(to_console)
1172                         print(s, "\n");
1173                 if(to_eventlog)
1174                         GameLogEcho(s);
1175                 if(to_file)
1176                         fputs(file, strcat(s, "\n"));
1177         
1178                 for(i = 1; i < 16; ++i)
1179                 {
1180                         s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1181                         s = strcat(s, ":", ftos(i));
1182                         if(to_console)
1183                                 print(s, "\n");
1184                         if(to_eventlog)
1185                                 GameLogEcho(s);
1186                         if(to_file)
1187                                 fputs(file, strcat(s, "\n"));
1188                 }
1189         }
1190
1191         if(to_console)
1192                 print(":end\n");
1193         if(to_eventlog)
1194                 GameLogEcho(":end");
1195         if(to_file)
1196         {
1197                 fputs(file, ":end\n");
1198                 fclose(file);
1199         }
1200 }
1201
1202 void FixIntermissionClient(entity e)
1203 {
1204         string s;
1205         if(!e.autoscreenshot) // initial call
1206         {
1207                 e.angles = e.v_angle;
1208                 e.angles_x = -e.angles_x;
1209                 e.autoscreenshot = time + 0.8;  // used for autoscreenshot
1210                 e.health = -2342;
1211                 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1212                 e.solid = SOLID_NOT;
1213                 e.movetype = MOVETYPE_NONE;
1214                 e.takedamage = DAMAGE_NO;
1215                 if(e.weaponentity)
1216                         e.weaponentity.effects = EF_NODRAW;
1217                 if(clienttype(e) == CLIENTTYPE_REAL)
1218                 {
1219                         stuffcmd(e, "\nscr_printspeed 1000000\n");
1220                         s = cvar_string("sv_intermission_cdtrack");
1221                         if(s != "")
1222                                 stuffcmd(e, strcat("\ncd loop ", s, "\n"));
1223                         msg_entity = e;
1224                         WriteByte(MSG_ONE, SVC_INTERMISSION);
1225                 }
1226         }
1227
1228         //e.velocity = '0 0 0';
1229         //e.fixangle = TRUE;
1230
1231         // TODO halt weapon animation
1232 }
1233
1234
1235 /*
1236 go to the next level for deathmatch
1237 only called if a time or frag limit has expired
1238 */
1239 void NextLevel()
1240 {
1241         float minTotalFrags;
1242         float maxTotalFrags;
1243         float score;
1244         float f;
1245
1246         gameover = TRUE;
1247
1248         intermission_running = 1;
1249
1250 // enforce a wait time before allowing changelevel
1251         if(player_count > 0)
1252                 intermission_exittime = time + cvar("sv_mapchange_delay");
1253         else
1254                 intermission_exittime = -1;
1255
1256         /*
1257         WriteByte (MSG_ALL, SVC_CDTRACK);
1258         WriteByte (MSG_ALL, 3);
1259         WriteByte (MSG_ALL, 3);
1260         // done in FixIntermission
1261         */
1262
1263         //pos = FindIntermission ();
1264
1265         VoteReset();
1266
1267         DumpStats(TRUE);
1268
1269         if(cvar("sv_eventlog"))
1270                 GameLogEcho(":gameover");
1271
1272         GameLogClose();
1273
1274         FOR_EACH_CLIENT(other)
1275         {
1276                 FixIntermissionClient(other);
1277
1278                 if(other.winning)
1279                         bprint(other.netname, " ^7wins.\n");
1280         }
1281
1282         minTotalFrags = 0;
1283         maxTotalFrags = 0;
1284         FOR_EACH_PLAYER(other)
1285         {
1286                 if(maxTotalFrags < other.totalfrags)
1287                         maxTotalFrags = other.totalfrags;
1288                 if(minTotalFrags > other.totalfrags)
1289                         minTotalFrags = other.totalfrags;
1290         }
1291
1292         if(!currentbots)
1293         {
1294                 FOR_EACH_PLAYER(other)
1295                 {
1296                         score = (other.totalfrags - minTotalFrags) / max(maxTotalFrags - minTotalFrags, 1);
1297                         f = bound(0, other.play_time / max(time, 1), 1);
1298                         // store some statistics?
1299                 }
1300         }
1301
1302         if(cvar("g_campaign"))
1303                 CampaignPreIntermission();
1304
1305         // WriteByte (MSG_ALL, SVC_INTERMISSION);
1306 };
1307
1308 /*
1309 ============
1310 CheckRules_Player
1311
1312 Exit deathmatch games upon conditions
1313 ============
1314 */
1315 void CheckRules_Player()
1316 {
1317         if (gameover)   // someone else quit the game already
1318                 return;
1319
1320         if(self.deadflag == DEAD_NO)
1321                 self.play_time += frametime;
1322
1323         // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1324         //   (div0: and that in CheckRules_World please)
1325 };
1326
1327 float checkrules_oneminutewarning;
1328
1329 float checkrules_equality;
1330 float checkrules_suddendeathwarning;
1331 float checkrules_suddendeathend;
1332 float checkrules_overtimesadded; //how many overtimes have been already added
1333 float checkrules_status;
1334
1335 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1336 float WINNING_YES = 1; // winner found
1337 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1338 float WINNING_STARTSUDDENDEATHOVERTIME = 3; // no winner, enter suddendeath overtime NOW
1339
1340 void InitiateOvertime()
1341 {
1342         // Check first whether normal overtimes could be added before initiating suddendeath mode
1343         // - for this timelimit_overtime needs to be >0 of course
1344         // - also check the winning condition calculated in the previous frame and only add normal overtime
1345         //   again, if at the point at which timelimit would be extended again, still no winner was found
1346         if ((checkrules_overtimesadded < cvar("timelimit_overtimes")) && cvar("timelimit_overtime") && (checkrules_status == WINNING_NEVER)) 
1347         {
1348                 ++checkrules_overtimesadded;
1349                 //add one more overtime by simply extending the timelimit
1350                 float tl;
1351                 tl = cvar("timelimit");
1352                 tl += cvar("timelimit_overtime");
1353                 cvar_set("timelimit", ftos(tl));
1354                 string minutesPlural;
1355                 if (cvar("timelimit_overtime") == 1)
1356                         minutesPlural = " ^3minute";
1357                 else
1358                         minutesPlural = " ^3minutes";
1359                 
1360                 bcenterprint(
1361                         strcat(
1362                                 "^3Now playing ^1OVERTIME^3!\n\n^3Added ^1",
1363                                 ftos(cvar("timelimit_overtime")),
1364                                 minutesPlural,
1365                                 " to the game!"
1366                         )
1367                 );
1368         }
1369         else 
1370         {
1371                 if(!checkrules_suddendeathend)
1372                         checkrules_suddendeathend = time + 60 * cvar("timelimit_suddendeath");
1373         }
1374 }
1375
1376 float GetWinningCode(float fraglimitreached, float equality)
1377 {
1378         if(equality)
1379                 if(fraglimitreached)
1380                         return WINNING_STARTSUDDENDEATHOVERTIME;
1381                 else
1382                         return WINNING_NEVER;
1383         else
1384                 if(fraglimitreached)
1385                         return WINNING_YES;
1386                 else
1387                         return WINNING_NO;
1388 }
1389
1390 // set the .winning flag for exactly those players with a given field value
1391 void SetWinners(.float field, float value)
1392 {
1393         entity head;
1394         FOR_EACH_PLAYER(head)
1395                 head.winning = (head.field == value);
1396 }
1397
1398 // set the .winning flag for those players with a given field value
1399 void AddWinners(.float field, float value)
1400 {
1401         entity head;
1402         FOR_EACH_PLAYER(head)
1403                 if(head.field == value)
1404                         head.winning = 1;
1405 }
1406
1407 // clear the .winning flags
1408 void ClearWinners(void)
1409 {
1410         entity head;
1411         FOR_EACH_PLAYER(head)
1412                 head.winning = 0;
1413 }
1414
1415 // Onslaught winning condition:
1416 // game terminates if only one team has a working generator (or none)
1417 float WinningCondition_Onslaught()
1418 {
1419         entity head;
1420         local float t1, t2, t3, t4;
1421
1422         WinningConditionHelper(); // set worldstatus
1423
1424         // first check if the game has ended
1425         t1 = t2 = t3 = t4 = 0;
1426         head = find(world, classname, "onslaught_generator");
1427         while (head)
1428         {
1429                 if (head.health > 0)
1430                 {
1431                         if (head.team == COLOR_TEAM1) t1 = 1;
1432                         if (head.team == COLOR_TEAM2) t2 = 1;
1433                         if (head.team == COLOR_TEAM3) t3 = 1;
1434                         if (head.team == COLOR_TEAM4) t4 = 1;
1435                 }
1436                 head = find(head, classname, "onslaught_generator");
1437         }
1438         if (t1 + t2 + t3 + t4 < 2)
1439         {
1440                 // game over, only one team remains (or none)
1441                 ClearWinners();
1442                 if (t1) SetWinners(team, COLOR_TEAM1);
1443                 if (t2) SetWinners(team, COLOR_TEAM2);
1444                 if (t3) SetWinners(team, COLOR_TEAM3);
1445                 if (t4) SetWinners(team, COLOR_TEAM4);
1446                 dprint("Have a winner, ending game.\n");
1447                 return WINNING_YES;
1448         }
1449
1450         // Two or more teams remain
1451         return WINNING_NO;
1452 }
1453
1454 float LMS_NewPlayerLives()
1455 {
1456         float fl;
1457         fl = cvar("fraglimit");
1458         if(fl == 0)
1459                 fl = 999;
1460
1461         // first player has left the game for dying too much? Nobody else can get in.
1462         if(lms_lowest_lives < 1)
1463                 return 0;
1464
1465         if(!cvar("g_lms_join_anytime"))
1466                 if(lms_lowest_lives < fl - cvar("g_lms_last_join"))
1467                         return 0;
1468
1469         return bound(1, lms_lowest_lives, fl);
1470 }
1471
1472 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1473 // they win. Otherwise the defending team wins once the timelimit passes.
1474 void assault_new_round();
1475 float WinningCondition_Assault()
1476 {
1477         local float status;
1478
1479         WinningConditionHelper(); // set worldstatus
1480
1481         status = WINNING_NO;
1482         // as the timelimit has not yet passed just assume the defending team will win
1483         if(assault_attacker_team == COLOR_TEAM1)
1484         {
1485                 SetWinners(team, COLOR_TEAM2);
1486         }
1487         else
1488         {
1489                 SetWinners(team, COLOR_TEAM1);
1490         }
1491
1492         local entity ent;
1493         ent = find(world, classname, "target_assault_roundend");
1494         if(ent)
1495         {
1496                 if(ent.winning) // round end has been triggered by attacking team
1497                 {
1498                         bprint("ASSAULT: round completed...\n");
1499                         SetWinners(team, assault_attacker_team);
1500
1501                         TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 666 - TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 0));
1502
1503                         if(ent.cnt == 1) // this was the second round
1504                         {
1505                                 status = WINNING_YES;
1506                         }
1507                         else
1508                         {
1509                                 local entity oldself;
1510                                 oldself = self;
1511                                 self = ent;
1512                                 assault_new_round();
1513                                 self = oldself;
1514                         }
1515                 }
1516         }
1517
1518         return status;
1519 }
1520
1521 // LMS winning condition: game terminates if and only if there's at most one
1522 // one player who's living lives. Top two scores being equal cancels the time
1523 // limit.
1524 float WinningCondition_LMS()
1525 {
1526         entity head, head2;
1527         float have_player;
1528         float have_players;
1529         float l;
1530
1531         have_player = FALSE;
1532         have_players = FALSE;
1533         l = LMS_NewPlayerLives();
1534
1535         head = find(world, classname, "player");
1536         if(head)
1537                 have_player = TRUE;
1538         head2 = find(head, classname, "player");
1539         if(head2)
1540                 have_players = TRUE;
1541
1542         if(have_player)
1543         {
1544                 // we have at least one player
1545                 if(have_players)
1546                 {
1547                         // two or more active players - continue with the game
1548                 }
1549                 else
1550                 {
1551                         // exactly one player?
1552
1553                         ClearWinners();
1554                         SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1555
1556                         if(l)
1557                         {
1558                                 // game still running (that is, nobody got removed from the game by a frag yet)? then continue
1559                                 return WINNING_NO;
1560                         }
1561                         else
1562                         {
1563                                 // a winner!
1564                                 // and assign him his first place
1565                                 PlayerScore_Add(head, SP_LMS_RANK, 1);
1566                                 return WINNING_YES;
1567                         }
1568                 }
1569         }
1570         else
1571         {
1572                 // nobody is playing at all...
1573                 if(l)
1574                 {
1575                         // wait for players...
1576                 }
1577                 else
1578                 {
1579                         // SNAFU (maybe a draw game?)
1580                         ClearWinners();
1581                         dprint("No players, ending game.\n");
1582                         return WINNING_YES;
1583                 }
1584         }
1585
1586         // When we get here, we have at least two players who are actually LIVING,
1587         // now check if the top two players have equal score.
1588         WinningConditionHelper();
1589
1590         ClearWinners();
1591         if(WinningConditionHelper_winner)
1592                 WinningConditionHelper_winner.winning = TRUE;
1593         if(WinningConditionHelper_equality)
1594                 return WINNING_NEVER;
1595
1596         // Top two have different scores? Way to go for our beloved TIMELIMIT!
1597         return WINNING_NO;
1598 }
1599
1600 void ShuffleMaplist()
1601 {
1602         string result;
1603         float start;
1604         float litems;
1605         float selected;
1606         float i;
1607
1608         result = cvar_string("g_maplist");
1609         litems = tokenizebyseparator(result, " ");
1610
1611         for(start = 0; start < litems - 1; ++start)
1612         {
1613                 result = "";
1614
1615                 // select a random item
1616                 selected = floor(random() * (litems - start) + start);
1617
1618                 // shift this item to the place start
1619                 for(i = 0; i < start; ++i)
1620                         result = strcat(result, " ", argv(i));
1621                 result = strcat(result, " ", argv(selected));
1622                 for(i = start; i < litems; ++i)
1623                         if(i != selected)
1624                                 result = strcat(result, " ", argv(i));
1625                 result = substring(result, 1, strlen(result) - 1);
1626
1627                 litems = tokenizebyseparator(result, " ");
1628
1629                 //dprint(result, "\n");
1630         }
1631
1632         cvar_set("g_maplist", result);
1633 }
1634
1635 float leaderfrags;
1636 float WinningCondition_Scores(float limit)
1637 {
1638         // TODO make everything use THIS winning condition (except LMS)
1639         WinningConditionHelper();
1640         
1641         if(teams_matter)
1642         {
1643                 team1_score = TeamScore_GetCompareValue(COLOR_TEAM1);
1644                 team2_score = TeamScore_GetCompareValue(COLOR_TEAM2);
1645                 team3_score = TeamScore_GetCompareValue(COLOR_TEAM3);
1646                 team4_score = TeamScore_GetCompareValue(COLOR_TEAM4);
1647         }
1648         
1649         ClearWinners();
1650         if(WinningConditionHelper_winner)
1651                 WinningConditionHelper_winner.winning = 1;
1652         if(WinningConditionHelper_winnerteam >= 0)
1653                 SetWinners(team, WinningConditionHelper_winnerteam);
1654
1655         if(WinningConditionHelper_lowerisbetter)
1656         {
1657                 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1658                 limit = -limit;
1659         }
1660
1661         if(g_dm || g_tdm || g_arena || (g_race && !g_race_qualifying))
1662         // these modes always score in increments of 1, thus this makes sense
1663         {
1664                 if(leaderfrags != WinningConditionHelper_topscore)
1665                 {
1666                         leaderfrags = WinningConditionHelper_topscore;
1667
1668                         if (limit)
1669                         if (leaderfrags == limit - 1)
1670                                 play2all("announcer/robotic/1fragleft.wav");
1671                         else if (leaderfrags == limit - 2)
1672                                 play2all("announcer/robotic/2fragsleft.wav");
1673                         else if (leaderfrags == limit - 3)
1674                                 play2all("announcer/robotic/3fragsleft.wav");
1675                 }
1676         }
1677
1678         return GetWinningCode(limit && WinningConditionHelper_topscore && (WinningConditionHelper_topscore >= limit), WinningConditionHelper_equality);
1679 }
1680
1681 float WinningCondition_Race(float fraglimit)
1682 {
1683         float wc;
1684         entity p;
1685         wc = WinningCondition_Scores(fraglimit);
1686
1687         // ALWAYS initiate overtime, unless EVERYONE has finished the race!
1688         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1689         // do NOT support equality when the laps are all raced!
1690         {
1691                 FOR_EACH_PLAYER(p)
1692                         if not(p.race_completed)
1693                                 return WINNING_STARTSUDDENDEATHOVERTIME;
1694                 return WINNING_YES;
1695         }
1696         return wc;
1697 }
1698
1699 void ReadyRestart();
1700 float WinningCondition_QualifyingThenRace(float limit)
1701 {
1702         float wc;
1703         wc = WinningCondition_Scores(limit);
1704
1705         // NEVER initiate overtime
1706         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1707         {
1708                 return WINNING_YES;
1709         }
1710
1711         return wc;
1712 }
1713
1714 float WinningCondition_RanOutOfSpawns()
1715 {
1716         entity head;
1717
1718         if(!have_team_spawns)
1719                 return WINNING_NO;
1720
1721         if(!some_spawn_has_been_used)
1722                 return WINNING_NO;
1723
1724         team1_score = team2_score = team3_score = team4_score = 0;
1725
1726         FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
1727         {
1728                 if(head.team == COLOR_TEAM1)
1729                         team1_score = 1;
1730                 else if(head.team == COLOR_TEAM2)
1731                         team2_score = 1;
1732                 else if(head.team == COLOR_TEAM3)
1733                         team3_score = 1;
1734                 else if(head.team == COLOR_TEAM4)
1735                         team4_score = 1;
1736         }
1737
1738         for(head = world; (head = find(head, classname, "info_player_deathmatch")) != world; )
1739         {
1740                 if(head.team == COLOR_TEAM1)
1741                         team1_score = 1;
1742                 else if(head.team == COLOR_TEAM2)
1743                         team2_score = 1;
1744                 else if(head.team == COLOR_TEAM3)
1745                         team3_score = 1;
1746                 else if(head.team == COLOR_TEAM4)
1747                         team4_score = 1;
1748         }
1749
1750         ClearWinners();
1751         if(team1_score + team2_score + team3_score + team4_score == 0)
1752         {
1753                 checkrules_equality = TRUE;
1754                 return WINNING_YES;
1755         }
1756         else if(team1_score + team2_score + team3_score + team4_score == 1)
1757         {
1758                 float t, i;
1759                 if(team1_score) t = COLOR_TEAM1;
1760                 if(team2_score) t = COLOR_TEAM2;
1761                 if(team3_score) t = COLOR_TEAM3;
1762                 if(team4_score) t = COLOR_TEAM4;
1763                 CheckAllowedTeams(world);
1764                 for(i = 0; i < MAX_TEAMSCORE; ++i)
1765                 {
1766                         if(t != COLOR_TEAM1) if(c1 >= 0) TeamScore_AddToTeam(COLOR_TEAM1, i, -1000);
1767                         if(t != COLOR_TEAM2) if(c2 >= 0) TeamScore_AddToTeam(COLOR_TEAM2, i, -1000);
1768                         if(t != COLOR_TEAM3) if(c3 >= 0) TeamScore_AddToTeam(COLOR_TEAM3, i, -1000);
1769                         if(t != COLOR_TEAM4) if(c4 >= 0) TeamScore_AddToTeam(COLOR_TEAM4, i, -1000);
1770                 }
1771
1772                 AddWinners(team, t);
1773                 return WINNING_YES;
1774         }
1775         else
1776                 return WINNING_NO;
1777 }
1778
1779 /*
1780 ============
1781 CheckRules_World
1782
1783 Exit deathmatch games upon conditions
1784 ============
1785 */
1786 void CheckRules_World()
1787 {
1788         local float timelimit;
1789         local float fraglimit;
1790
1791         VoteThink();
1792         MapVote_Think();
1793
1794         SetDefaultAlpha();
1795
1796         /*
1797         MapVote_Think should now do that part
1798         if (intermission_running)
1799                 if (time >= intermission_exittime + 60)
1800                 {
1801                         if(!DoNextMapOverride())
1802                                 GotoNextMap();
1803                         return;
1804                 }
1805         */
1806
1807         if (gameover)   // someone else quit the game already
1808         {
1809                 if(player_count == 0) // Nobody there? Then let's go to the next map
1810                         MapVote_Start();
1811                         // this will actually check the player count in the next frame
1812                         // again, but this shouldn't hurt
1813                 return;
1814         }
1815
1816         timelimit = cvar("timelimit") * 60;
1817         fraglimit = cvar("fraglimit");
1818
1819         if(inWarmupStage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1820         {
1821                 if(timelimit > 0)
1822                         timelimit = 0; // timelimit is not made for warmup
1823                 if(fraglimit > 0)
1824                         fraglimit = 0; // no fraglimit for now
1825         }
1826
1827         if(timelimit > 0)
1828         {
1829                 timelimit += game_starttime;
1830         }
1831         else if (timelimit < 0)
1832         {
1833                 // endmatch
1834                 NextLevel();
1835                 return;
1836         }
1837
1838         if(checkrules_suddendeathend)
1839         {
1840                 if(!checkrules_suddendeathwarning)
1841                 {
1842                         checkrules_suddendeathwarning = TRUE;
1843                         if(g_race && !g_race_qualifying)
1844                                 bcenterprint("^3Everyone, finish your lap! The race is over!");
1845                         else
1846                                 bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
1847                 }
1848         }
1849         else
1850         {
1851                 if (timelimit && time >= timelimit)
1852                 {
1853                         if(g_race && g_race_qualifying == 2 && timelimit > 0)
1854                         {
1855                                 float totalplayers;
1856                                 float playerswithlaps;
1857                                 float readyplayers;
1858                                 entity head;
1859                                 totalplayers = playerswithlaps = readyplayers = 0;
1860                                 FOR_EACH_PLAYER(head)
1861                                 {
1862                                         ++totalplayers;
1863                                         if(PlayerScore_Add(head, SP_RACE_FASTEST, 0))
1864                                                 ++playerswithlaps;
1865                                         if(head.ready)
1866                                                 ++readyplayers;
1867                                 }
1868
1869                                 // at least 2/3 of the players have completed a lap: start the RACE
1870                                 // otherwise, the players should end the qualifying on their own
1871                                 if(readyplayers || ((totalplayers >= 3) && (playerswithlaps * 3 >= totalplayers * 2)))
1872                                 {
1873                                         checkrules_suddendeathend = 0;
1874                                         ReadyRestart(); // go to race
1875                                 }
1876                                 else
1877                                         InitiateOvertime();
1878                         }
1879                         else
1880                                 InitiateOvertime();
1881                 }
1882         }
1883
1884         if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1885         {
1886                 NextLevel();
1887                 return;
1888         }
1889
1890         if (!checkrules_oneminutewarning && timelimit > 0 && time > timelimit - 60)
1891         {
1892                 checkrules_oneminutewarning = TRUE;
1893                 play2all("announcer/robotic/1minuteremains.wav");
1894         }
1895
1896         checkrules_status = WinningCondition_RanOutOfSpawns();
1897         if(checkrules_status == WINNING_YES)
1898         {
1899                 bprint("Hey! Someone ran out of spawns!\n");
1900         }
1901         else if(g_race && !g_race_qualifying && timelimit >= 0)
1902         {
1903                 checkrules_status = WinningCondition_Race(fraglimit);
1904         }
1905         else if(g_race && g_race_qualifying == 2 && timelimit >= 0)
1906         {
1907                 checkrules_status = WinningCondition_QualifyingThenRace(fraglimit);
1908         }
1909         else if(g_assault)
1910         {
1911                 checkrules_status = WinningCondition_Assault(); // TODO remove this?
1912         }
1913         else if(g_lms)
1914         {
1915                 checkrules_status = WinningCondition_LMS();
1916         }
1917         else if (g_onslaught)
1918         {
1919                 checkrules_status = WinningCondition_Onslaught(); // TODO remove this?
1920         }
1921         else
1922         {
1923                 checkrules_status = WinningCondition_Scores(fraglimit);
1924         }
1925
1926         if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
1927         {
1928                 checkrules_status = WINNING_NEVER;
1929                 InitiateOvertime();
1930         }
1931
1932         if(checkrules_status == WINNING_NEVER)
1933                 // equality cases! Nobody wins if the overtime ends in a draw.
1934                 ClearWinners();
1935
1936         if(checkrules_suddendeathend)
1937                 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
1938                         checkrules_status = WINNING_YES;
1939
1940         if(checkrules_status == WINNING_YES)
1941                 NextLevel();
1942 };
1943
1944 float mapvote_nextthink;
1945 float mapvote_initialized;
1946 float mapvote_keeptwotime;
1947 float mapvote_timeout;
1948 string mapvote_message;
1949 string mapvote_screenshot_dir;
1950
1951 float mapvote_count;
1952 float mapvote_count_real;
1953 string mapvote_maps[MAPVOTE_COUNT];
1954 float mapvote_maps_suggested[MAPVOTE_COUNT];
1955 string mapvote_suggestions[MAPVOTE_COUNT];
1956 float mapvote_suggestion_ptr;
1957 float mapvote_maxlen;
1958 float mapvote_voters;
1959 float mapvote_votes[MAPVOTE_COUNT];
1960 float mapvote_run;
1961 float mapvote_detail;
1962 float mapvote_abstain;
1963 .float mapvote;
1964
1965 void MapVote_ClearAllVotes()
1966 {
1967         FOR_EACH_CLIENT(other)
1968                 other.mapvote = 0;
1969 }
1970
1971 string MapVote_Suggest(string m)
1972 {
1973         float i;
1974         if(m == "")
1975                 return "That's not how to use this command.";
1976         if(!cvar("g_maplist_votable_suggestions"))
1977                 return "Suggestions are not accepted on this server.";
1978         if(mapvote_initialized)
1979                 return "Can't suggest - voting is already in progress!";
1980         m = MapInfo_FixName(m);
1981         if(!m)
1982                 return "The map you suggested is not available on this server.";
1983         if(!cvar("g_maplist_votable_override_mostrecent"))
1984                 if(Map_IsRecent(m))
1985                         return "This server does not allow for recent maps to be played again. Please be patient for some rounds.";
1986
1987         if(!MapInfo_CheckMap(m))
1988                 return "The map you suggested does not support the current game mode.";
1989         for(i = 0; i < mapvote_suggestion_ptr; ++i)
1990                 if(mapvote_suggestions[i] == m)
1991                         return "This map was already suggested.";
1992         if(mapvote_suggestion_ptr >= MAPVOTE_COUNT)
1993         {
1994                 i = floor(random() * mapvote_suggestion_ptr);
1995         }
1996         else
1997         {
1998                 i = mapvote_suggestion_ptr;
1999                 mapvote_suggestion_ptr += 1;
2000         }
2001         if(mapvote_suggestions[i] != "")
2002                 strunzone(mapvote_suggestions[i]);
2003         mapvote_suggestions[i] = strzone(m);
2004         if(cvar("sv_eventlog"))
2005                 GameLogEcho(strcat(":vote:suggested:", m, ":", ftos(self.playerid)));
2006         return strcat("Suggestion of ", m, " accepted.");
2007 }
2008
2009 void MapVote_AddVotable(string nextMap, float isSuggestion)
2010 {
2011         float j;
2012         if(nextMap == "")
2013                 return;
2014         for(j = 0; j < mapvote_count; ++j)
2015                 if(mapvote_maps[j] == nextMap)
2016                         return;
2017         if(strlen(nextMap) > mapvote_maxlen)
2018                 mapvote_maxlen = strlen(nextMap);
2019         mapvote_maps[mapvote_count] = strzone(nextMap);
2020         mapvote_maps_suggested[mapvote_count] = isSuggestion;
2021         mapvote_count += 1;
2022 }
2023
2024 void MapVote_Spawn();
2025 void MapVote_Init()
2026 {
2027         float i;
2028         float nmax, smax;
2029
2030         MapVote_ClearAllVotes();
2031
2032         mapvote_count = 0;
2033         mapvote_detail = !cvar("g_maplist_votable_nodetail");
2034         mapvote_abstain = cvar("g_maplist_votable_abstain");
2035
2036         if(mapvote_abstain)
2037                 nmax = min(MAPVOTE_COUNT - 1, cvar("g_maplist_votable"));
2038         else
2039                 nmax = min(MAPVOTE_COUNT, cvar("g_maplist_votable"));
2040         smax = min3(nmax, cvar("g_maplist_votable_suggestions"), mapvote_suggestion_ptr);
2041
2042         if(mapvote_suggestion_ptr)
2043                 for(i = 0; i < 100 && mapvote_count < smax; ++i)
2044                         MapVote_AddVotable(mapvote_suggestions[floor(random() * mapvote_suggestion_ptr)], TRUE);
2045
2046         for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2047                 MapVote_AddVotable(GetNextMap(), FALSE);
2048
2049         if(mapvote_count == 0)
2050         {
2051                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
2052                 cvar_set("g_maplist", MapInfo_ListAllowedMaps(0, MAPINFO_FLAG_HIDDEN));
2053                 if(cvar("g_maplist_shuffle"))
2054                         ShuffleMaplist();
2055                 localcmd("\nmenu_cmd sync\n");
2056                 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2057                         MapVote_AddVotable(GetNextMap(), FALSE);
2058         }
2059
2060         mapvote_count_real = mapvote_count;
2061         if(mapvote_abstain)
2062                 MapVote_AddVotable("don't care", 0);
2063
2064         //dprint("mapvote count is ", ftos(mapvote_count), "\n");
2065
2066         mapvote_keeptwotime = time + cvar("g_maplist_votable_keeptwotime");
2067         mapvote_timeout = time + cvar("g_maplist_votable_timeout");
2068         if(mapvote_count_real < 3 || mapvote_keeptwotime <= time)
2069                 mapvote_keeptwotime = 0;
2070         mapvote_message = "Choose a map and press its key!";
2071
2072         mapvote_screenshot_dir = cvar_string("g_maplist_votable_screenshot_dir");
2073         if(mapvote_screenshot_dir == "")
2074                 mapvote_screenshot_dir = "maps";
2075         mapvote_screenshot_dir = strzone(mapvote_screenshot_dir);
2076
2077         MapVote_Spawn();
2078 }
2079
2080 void MapVote_SendPicture(float id)
2081 {
2082         msg_entity = self;
2083         WriteByte(MSG_ONE, SVC_TEMPENTITY);
2084         WriteByte(MSG_ONE, TE_CSQC_PICTURE);
2085         WriteByte(MSG_ONE, id);
2086         WritePicture(MSG_ONE, strcat(mapvote_screenshot_dir, "/", mapvote_maps[id]), 3072);
2087 }
2088
2089 float GameCommand_MapVote(string cmd)
2090 {
2091         if(!intermission_running)
2092                 return FALSE;
2093
2094         if(cmd == "mv_getpic")
2095         {
2096                 MapVote_SendPicture(stof(argv(1)));
2097                 return TRUE;
2098         }
2099
2100         return FALSE;
2101 }
2102
2103 float MapVote_GetMapMask()
2104 {
2105         float mask, i, power;
2106         mask = 0;
2107         for(i = 0, power = 1; i < mapvote_count; ++i, power *= 2)
2108                 if(mapvote_maps[i] != "")
2109                         mask |= power;
2110         return mask;
2111 }
2112
2113 entity mapvote_ent;
2114 float MapVote_SendEntity(entity to, float sf)
2115 {
2116         string mapfile, pakfile;
2117         float i, o;
2118
2119         WriteByte(MSG_ENTITY, ENT_CLIENT_MAPVOTE);
2120         WriteByte(MSG_ENTITY, sf);
2121
2122         if(sf & 1)
2123         {
2124                 // flag 1 == initialization
2125                 WriteString(MSG_ENTITY, mapvote_screenshot_dir);
2126                 WriteByte(MSG_ENTITY, mapvote_count);
2127                 WriteByte(MSG_ENTITY, mapvote_abstain);
2128                 WriteByte(MSG_ENTITY, mapvote_detail);
2129                 WriteCoord(MSG_ENTITY, mapvote_timeout);
2130                 if(mapvote_count <= 8)
2131                         WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2132                 else
2133                         WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2134                 for(i = 0; i < mapvote_count; ++i)
2135                         if(mapvote_maps[i] != "")
2136                         {
2137                                 WriteString(MSG_ENTITY, mapvote_maps[i]);
2138                                 mapfile = strcat(mapvote_screenshot_dir, "/", mapvote_maps[i]);
2139                                 pakfile = whichpack(strcat(mapfile, ".tga"));
2140                                 if(pakfile == "")
2141                                         pakfile = whichpack(strcat(mapfile, ".jpg"));
2142                                 if(pakfile == "")
2143                                         pakfile = whichpack(strcat(mapfile, ".png"));
2144                                 for(o = strstr(pakfile, "/", 0)+1; o > 0; o = strstr(pakfile, "/", 0)+1)
2145                                         pakfile = substring(pakfile, o, 999);
2146                                 WriteString(MSG_ENTITY, pakfile);
2147                         }
2148         }
2149
2150         if(sf & 2)
2151         {
2152                 // flag 2 == update of mask
2153                 if(mapvote_count <= 8)
2154                         WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2155                 else
2156                         WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2157         }
2158
2159         if(sf & 4)
2160         {
2161                 if(mapvote_detail)
2162                         for(i = 0; i < mapvote_count; ++i)
2163                                 if(mapvote_maps[i] != "")
2164                                         WriteByte(MSG_ENTITY, mapvote_votes[i]);
2165
2166                 WriteByte(MSG_ENTITY, to.mapvote);
2167         }
2168
2169         return TRUE;
2170 }
2171
2172 void MapVote_Spawn()
2173 {
2174         Net_LinkEntity(mapvote_ent = spawn(), FALSE, 0, MapVote_SendEntity);
2175 }
2176
2177 void MapVote_TouchMask()
2178 {
2179         mapvote_ent.SendFlags |= 2;
2180 }
2181
2182 void MapVote_TouchVotes(entity voter)
2183 {
2184         mapvote_ent.SendFlags |= 4;
2185 }
2186
2187 float MapVote_Finished(float mappos)
2188 {
2189         string result;
2190         float i;
2191         float didntvote;
2192
2193         if(cvar("sv_eventlog"))
2194         {
2195                 result = strcat(":vote:finished:", mapvote_maps[mappos]);
2196                 result = strcat(result, ":", ftos(mapvote_votes[mappos]), "::");
2197                 didntvote = mapvote_voters;
2198                 for(i = 0; i < mapvote_count; ++i)
2199                         if(mapvote_maps[i] != "")
2200                         {
2201                                 didntvote -= mapvote_votes[i];
2202                                 if(i != mappos)
2203                                 {
2204                                         result = strcat(result, ":", mapvote_maps[i]);
2205                                         result = strcat(result, ":", ftos(mapvote_votes[i]));
2206                                 }
2207                         }
2208                 result = strcat(result, ":didn't vote:", ftos(didntvote));
2209
2210                 GameLogEcho(result);
2211                 if(mapvote_maps_suggested[mappos])
2212                         GameLogEcho(strcat(":vote:suggestion_accepted:", mapvote_maps[mappos]));
2213         }
2214
2215         FOR_EACH_REALCLIENT(other)
2216                 FixClientCvars(other);
2217
2218         Map_Goto_SetStr(mapvote_maps[mappos]);
2219         Map_Goto();
2220         alreadychangedlevel = TRUE;
2221         return TRUE;
2222 }
2223 void MapVote_CheckRules_1()
2224 {
2225         float i;
2226
2227         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
2228         {
2229                 //dprint("Map ", ftos(i), ": "); dprint(mapvote_maps[i], "\n");
2230                 mapvote_votes[i] = 0;
2231         }
2232
2233         mapvote_voters = 0;
2234         FOR_EACH_REALCLIENT(other)
2235         {
2236                 ++mapvote_voters;
2237                 if(other.mapvote)
2238                 {
2239                         i = other.mapvote - 1;
2240                         //dprint("Player ", other.netname, " vote = ", ftos(other.mapvote - 1), "\n");
2241                         mapvote_votes[i] = mapvote_votes[i] + 1;
2242                 }
2243         }
2244 }
2245
2246 float MapVote_CheckRules_2()
2247 {
2248         float i;
2249         float firstPlace, secondPlace;
2250         float firstPlaceVotes, secondPlaceVotes;
2251         float mapvote_voters_real;
2252         string result;
2253
2254         mapvote_voters_real = mapvote_voters;
2255         if(mapvote_abstain)
2256                 mapvote_voters_real -= mapvote_votes[mapvote_count - 1];
2257
2258         RandomSelection_Init();
2259         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2260                 RandomSelection_Add(world, i, 1, mapvote_votes[i]);
2261         firstPlace = RandomSelection_chosen_float;
2262         firstPlaceVotes = RandomSelection_best_priority;
2263         //dprint("First place: ", ftos(firstPlace), "\n");
2264         //dprint("First place votes: ", ftos(firstPlaceVotes), "\n");
2265
2266         RandomSelection_Init();
2267         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2268                 if(i != firstPlace)
2269                         RandomSelection_Add(world, i, 1, mapvote_votes[i]);
2270         secondPlace = RandomSelection_chosen_float;
2271         secondPlaceVotes = RandomSelection_best_priority;
2272         //dprint("Second place: ", ftos(secondPlace), "\n");
2273         //dprint("Second place votes: ", ftos(secondPlaceVotes), "\n");
2274
2275         if(firstPlace == -1)
2276                 error("No first place in map vote... WTF?");
2277
2278         if(secondPlace == -1 || time > mapvote_timeout || (mapvote_voters_real - firstPlaceVotes) < firstPlaceVotes)
2279                 return MapVote_Finished(firstPlace);
2280
2281         if(mapvote_keeptwotime)
2282                 if(time > mapvote_keeptwotime || (mapvote_voters_real - firstPlaceVotes - secondPlaceVotes) < secondPlaceVotes)
2283                 {
2284                         float didntvote;
2285                         MapVote_TouchMask();
2286                         mapvote_message = "Now decide between the TOP TWO!";
2287                         mapvote_keeptwotime = 0;
2288                         result = strcat(":vote:keeptwo:", mapvote_maps[firstPlace]);
2289                         result = strcat(result, ":", ftos(firstPlaceVotes));
2290                         result = strcat(result, ":", mapvote_maps[secondPlace]);
2291                         result = strcat(result, ":", ftos(secondPlaceVotes), "::");
2292                         didntvote = mapvote_voters;
2293                         for(i = 0; i < mapvote_count; ++i)
2294                                 if(mapvote_maps[i] != "")
2295                                 {
2296                                         didntvote -= mapvote_votes[i];
2297                                         if(i != firstPlace)
2298                                                 if(i != secondPlace)
2299                                                 {
2300                                                         result = strcat(result, ":", mapvote_maps[i]);
2301                                                         result = strcat(result, ":", ftos(mapvote_votes[i]));
2302                                                         if(i < mapvote_count_real)
2303                                                         {
2304                                                                 strunzone(mapvote_maps[i]);
2305                                                                 mapvote_maps[i] = "";
2306                                                         }
2307                                                 }
2308                                 }
2309                         result = strcat(result, ":didn't vote:", ftos(didntvote));
2310                         if(cvar("sv_eventlog"))
2311                                 GameLogEcho(result);
2312                 }
2313
2314         return FALSE;
2315 }
2316 void MapVote_Tick()
2317 {
2318         float keeptwo;
2319         float totalvotes;
2320
2321         keeptwo = mapvote_keeptwotime;
2322         MapVote_CheckRules_1(); // count
2323         if(MapVote_CheckRules_2()) // decide
2324                 return;
2325
2326         totalvotes = 0;
2327         FOR_EACH_REALCLIENT(other)
2328         {
2329                 // hide scoreboard again
2330                 if(other.health != 2342)
2331                 {
2332                         other.health = 2342;
2333                         other.impulse = 0;
2334                         if(clienttype(other) == CLIENTTYPE_REAL)
2335                         {
2336                                 msg_entity = other;
2337                                 WriteByte(MSG_ONE, SVC_FINALE);
2338                                 WriteString(MSG_ONE, "");
2339                         }
2340                 }
2341
2342                 // notify about keep-two
2343                 if(keeptwo != 0 && mapvote_keeptwotime == 0)
2344                         play2(other, "misc/invshot.wav");
2345
2346                 // clear possibly invalid votes
2347                 if(mapvote_maps[other.mapvote - 1] == "")
2348                         other.mapvote = 0;
2349                 // use impulses as new vote
2350                 if(other.impulse >= 1 && other.impulse <= mapvote_count)
2351                         if(mapvote_maps[other.impulse - 1] != "")
2352                         {
2353                                 other.mapvote = other.impulse;
2354                                 MapVote_TouchVotes(other);
2355                         }
2356                 other.impulse = 0;
2357
2358                 if(other.mapvote)
2359                         ++totalvotes;
2360         }
2361
2362         MapVote_CheckRules_1(); // just count
2363 }
2364 void MapVote_Start()
2365 {
2366         if(mapvote_run)
2367                 return;
2368
2369         MapInfo_Enumerate();
2370         if(MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 0, (g_maplist_allow_hidden ? MAPINFO_FLAG_HIDDEN : 0), 1))
2371                 mapvote_run = TRUE;
2372 }
2373 void MapVote_Think()
2374 {
2375         if(!mapvote_run)
2376                 return;
2377
2378         if(alreadychangedlevel)
2379                 return;
2380
2381         if(time < mapvote_nextthink)
2382                 return;
2383         //dprint("tick\n");
2384
2385         mapvote_nextthink = time + 0.5;
2386
2387         if(!mapvote_initialized)
2388         {
2389                 mapvote_initialized = TRUE;
2390                 if(DoNextMapOverride())
2391                         return;
2392                 if(!cvar("g_maplist_votable") || player_count <= 0)
2393                 {
2394                         GotoNextMap();
2395                         return;
2396                 }
2397                 MapVote_Init();
2398         }
2399
2400         MapVote_Tick();
2401 };
2402
2403 string GotoMap(string m)
2404 {
2405         if(!MapInfo_CheckMap(m))
2406                 return "The map you chose is not available on this server.";
2407         cvar_set("nextmap", m);
2408         cvar_set("timelimit", "-1");
2409         if(mapvote_initialized || alreadychangedlevel)
2410         {
2411                 if(DoNextMapOverride())
2412                         return "Map switch initiated.";
2413                 else
2414                         return "Hm... no. For some reason I like THIS map more.";
2415         }
2416         else
2417                 return "Map switch will happen after scoreboard.";
2418 }
2419
2420
2421 void EndFrame()
2422 {
2423         FOR_EACH_REALCLIENT(self)
2424         {
2425                 if(self.classname == "spectator")
2426                 {
2427                         if(self.enemy.typehitsound)
2428                                 play2(self, "misc/typehit.wav");
2429                         else if(self.enemy.hitsound && self.cvar_cl_hitsound)
2430                                 play2(self, "misc/hit.wav");
2431                 }
2432                 else
2433                 {
2434                         if(self.typehitsound)
2435                                 play2(self, "misc/typehit.wav");
2436                         else if(self.hitsound && self.cvar_cl_hitsound)
2437                                 play2(self, "misc/hit.wav");
2438                 }
2439         }
2440         FOR_EACH_CLIENT(self)
2441         {
2442                 self.hitsound = FALSE;
2443                 self.typehitsound = FALSE;
2444         }
2445 }
2446
2447
2448 /*
2449  * RedirectionThink:
2450  * returns TRUE if redirecting
2451  */
2452 float redirection_timeout;
2453 float redirection_nextthink;
2454 float RedirectionThink()
2455 {
2456         float clients_found;
2457
2458         if(redirection_target == "")
2459                 return FALSE;
2460
2461         if(!redirection_timeout)
2462         {
2463                 cvar_set("sv_public", "-2");
2464                 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2465                 if(redirection_target == "self")
2466                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2467                 else
2468                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2469         }
2470
2471         if(time < redirection_nextthink)
2472                 return TRUE;
2473
2474         redirection_nextthink = time + 1;
2475
2476         clients_found = 0;
2477         FOR_EACH_REALCLIENT(self)
2478         {
2479                 print("Redirecting: sending connect command to ", self.netname, "\n");
2480                 if(redirection_target == "self")
2481                         stuffcmd(self, "\ndisconnect; reconnect\n");
2482                 else
2483                         stuffcmd(self, strcat("\ndisconnect; connect ", redirection_target, "\n"));
2484                 ++clients_found;
2485         }
2486
2487         print("Redirecting: ", ftos(clients_found), " clients left.\n");
2488
2489         if(time > redirection_timeout || clients_found == 0)
2490                 localcmd("\nwait; wait; wait; quit\n");
2491
2492         return TRUE;
2493 }
2494
2495 void RestoreGame()
2496 {
2497         // Loaded from a save game
2498         // some things then break, so let's work around them...
2499
2500         // Progs DB (capture records)
2501         if(sv_cheats)
2502                 ServerProgsDB = db_create();
2503         else
2504                 ServerProgsDB = db_load("server.db");
2505
2506         // Mapinfo
2507         MapInfo_Shutdown();
2508         MapInfo_Enumerate();
2509         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 0, (g_maplist_allow_hidden ? MAPINFO_FLAG_HIDDEN : 0), 1);
2510 }
2511
2512 void SV_Shutdown()
2513 {
2514         if(world_initialized > 0)
2515         {
2516                 world_initialized = 0;
2517                 print("Saving persistent data...\n");
2518                 Ban_SaveBans();
2519                 if(!sv_cheats)
2520                         db_save(ServerProgsDB, "server.db");
2521                 if(cvar("developer"))
2522                         db_save(TemporaryDB, "server-temp.db");
2523                 db_close(ServerProgsDB);
2524                 db_close(TemporaryDB);
2525                 print("done!\n");
2526                 // tell the bot system the game is ending now
2527                 bot_endgame();
2528
2529                 MapInfo_Shutdown();
2530         }
2531         else if(world_initialized == 0)
2532         {
2533                 print("NOTE: crashed before even initializing the world, not saving persistent data\n");
2534         }
2535 }