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