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