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