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