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