]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/g_world.qc
Revert "revert the mapvote change, it didnt really work online.", and fix it
[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 #define MAPVOTE_SCREENSHOT_DIRS_COUNT 4
2077 string mapvote_screenshot_dirs[MAPVOTE_SCREENSHOT_DIRS_COUNT];
2078 float mapvote_screenshot_dirs_count;
2079
2080 float mapvote_count;
2081 float mapvote_count_real;
2082 string mapvote_maps[MAPVOTE_COUNT];
2083 float mapvote_maps_screenshot_dir[MAPVOTE_COUNT];
2084 string mapvote_maps_pakfile[MAPVOTE_COUNT];
2085 float mapvote_maps_suggested[MAPVOTE_COUNT];
2086 string mapvote_suggestions[MAPVOTE_COUNT];
2087 float mapvote_suggestion_ptr;
2088 float mapvote_maxlen;
2089 float mapvote_voters;
2090 float mapvote_votes[MAPVOTE_COUNT];
2091 float mapvote_run;
2092 float mapvote_detail;
2093 float mapvote_abstain;
2094 .float mapvote;
2095
2096 void MapVote_ClearAllVotes()
2097 {
2098         FOR_EACH_CLIENT(other)
2099                 other.mapvote = 0;
2100 }
2101
2102 string MapVote_Suggest(string m)
2103 {
2104         float i;
2105         if(m == "")
2106                 return "That's not how to use this command.";
2107         if(!cvar("g_maplist_votable_suggestions"))
2108                 return "Suggestions are not accepted on this server.";
2109         if(mapvote_initialized)
2110                 return "Can't suggest - voting is already in progress!";
2111         m = MapInfo_FixName(m);
2112         if(!m)
2113                 return "The map you suggested is not available on this server.";
2114         if(!cvar("g_maplist_votable_suggestions_override_mostrecent"))
2115                 if(Map_IsRecent(m))
2116                         return "This server does not allow for recent maps to be played again. Please be patient for some rounds.";
2117
2118         if(!MapInfo_CheckMap(m))
2119                 return "The map you suggested does not support the current game mode.";
2120         for(i = 0; i < mapvote_suggestion_ptr; ++i)
2121                 if(mapvote_suggestions[i] == m)
2122                         return "This map was already suggested.";
2123         if(mapvote_suggestion_ptr >= MAPVOTE_COUNT)
2124         {
2125                 i = floor(random() * mapvote_suggestion_ptr);
2126         }
2127         else
2128         {
2129                 i = mapvote_suggestion_ptr;
2130                 mapvote_suggestion_ptr += 1;
2131         }
2132         if(mapvote_suggestions[i] != "")
2133                 strunzone(mapvote_suggestions[i]);
2134         mapvote_suggestions[i] = strzone(m);
2135         if(cvar("sv_eventlog"))
2136                 GameLogEcho(strcat(":vote:suggested:", m, ":", ftos(self.playerid)));
2137         return strcat("Suggestion of ", m, " accepted.");
2138 }
2139
2140 void MapVote_AddVotable(string nextMap, float isSuggestion)
2141 {
2142         float j, i, o;
2143         string pakfile, mapfile;
2144
2145         if(nextMap == "")
2146                 return;
2147         for(j = 0; j < mapvote_count; ++j)
2148                 if(mapvote_maps[j] == nextMap)
2149                         return;
2150         if(strlen(nextMap) > mapvote_maxlen)
2151                 mapvote_maxlen = strlen(nextMap);
2152         mapvote_maps[mapvote_count] = strzone(nextMap);
2153         mapvote_maps_suggested[mapvote_count] = isSuggestion;
2154
2155         for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2156         {
2157                 mapfile = strcat(mapvote_screenshot_dirs[i], "/", mapvote_maps[i]);
2158                 pakfile = whichpack(strcat(mapfile, ".tga"));
2159                 if(pakfile == "")
2160                         pakfile = whichpack(strcat(mapfile, ".jpg"));
2161                 if(pakfile == "")
2162                         pakfile = whichpack(strcat(mapfile, ".png"));
2163                 if(pakfile != "")
2164                         break;
2165         }
2166         if(i >= mapvote_screenshot_dirs_count)
2167                 i = 0; // FIXME maybe network this error case, as that means there is no mapshot on the server?
2168         for(o = strstr(pakfile, "/", 0)+1; o > 0; o = strstr(pakfile, "/", 0)+1)
2169                 pakfile = substring(pakfile, o, -1);
2170
2171         mapvote_maps_screenshot_dir[mapvote_count] = i;
2172         mapvote_maps_pakfile[mapvote_count] = strzone(pakfile);
2173
2174         mapvote_count += 1;
2175 }
2176
2177 void MapVote_Spawn();
2178 void MapVote_Init()
2179 {
2180         float i;
2181         float nmax, smax;
2182
2183         MapVote_ClearAllVotes();
2184
2185         mapvote_count = 0;
2186         mapvote_detail = !cvar("g_maplist_votable_nodetail");
2187         mapvote_abstain = cvar("g_maplist_votable_abstain");
2188
2189         if(mapvote_abstain)
2190                 nmax = min(MAPVOTE_COUNT - 1, cvar("g_maplist_votable"));
2191         else
2192                 nmax = min(MAPVOTE_COUNT, cvar("g_maplist_votable"));
2193         smax = min3(nmax, cvar("g_maplist_votable_suggestions"), mapvote_suggestion_ptr);
2194
2195         // we need this for AddVotable, as that cycles through the screenshot dirs
2196         mapvote_screenshot_dirs_count = tokenize_console(cvar_string("g_maplist_votable_screenshot_dir"));
2197         if(mapvote_screenshot_dirs_count == 0)
2198                 mapvote_screenshot_dirs_count = tokenize_console("maps levelshots");
2199         mapvote_screenshot_dirs_count = min(mapvote_screenshot_dirs_count, MAPVOTE_SCREENSHOT_DIRS_COUNT);
2200         for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2201                 mapvote_screenshot_dirs[i] = strzone(argv(i));
2202
2203         if(mapvote_suggestion_ptr)
2204                 for(i = 0; i < 100 && mapvote_count < smax; ++i)
2205                         MapVote_AddVotable(mapvote_suggestions[floor(random() * mapvote_suggestion_ptr)], TRUE);
2206
2207         for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2208                 MapVote_AddVotable(GetNextMap(), FALSE);
2209
2210         if(mapvote_count == 0)
2211         {
2212                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
2213                 cvar_set("g_maplist", MapInfo_ListAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
2214                 if(cvar("g_maplist_shuffle"))
2215                         ShuffleMaplist();
2216                 localcmd("\nmenu_cmd sync\n");
2217                 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2218                         MapVote_AddVotable(GetNextMap(), FALSE);
2219         }
2220
2221         mapvote_count_real = mapvote_count;
2222         if(mapvote_abstain)
2223                 MapVote_AddVotable("don't care", 0);
2224
2225         //dprint("mapvote count is ", ftos(mapvote_count), "\n");
2226
2227         mapvote_keeptwotime = time + cvar("g_maplist_votable_keeptwotime");
2228         mapvote_timeout = time + cvar("g_maplist_votable_timeout");
2229         if(mapvote_count_real < 3 || mapvote_keeptwotime <= time)
2230                 mapvote_keeptwotime = 0;
2231         mapvote_message = "Choose a map and press its key!";
2232
2233         MapVote_Spawn();
2234 }
2235
2236 void MapVote_SendPicture(float id)
2237 {
2238         msg_entity = self;
2239         WriteByte(MSG_ONE, SVC_TEMPENTITY);
2240         WriteByte(MSG_ONE, TE_CSQC_PICTURE);
2241         WriteByte(MSG_ONE, id);
2242         WritePicture(MSG_ONE, strcat(mapvote_screenshot_dirs[mapvote_maps_screenshot_dir[id]], "/", mapvote_maps[id]), 3072);
2243 }
2244
2245 float GameCommand_MapVote(string cmd)
2246 {
2247         if(!intermission_running)
2248                 return FALSE;
2249
2250         if(cmd == "mv_getpic")
2251         {
2252                 MapVote_SendPicture(stof(argv(1)));
2253                 return TRUE;
2254         }
2255
2256         return FALSE;
2257 }
2258
2259 float MapVote_GetMapMask()
2260 {
2261         float mask, i, power;
2262         mask = 0;
2263         for(i = 0, power = 1; i < mapvote_count; ++i, power *= 2)
2264                 if(mapvote_maps[i] != "")
2265                         mask |= power;
2266         return mask;
2267 }
2268
2269 entity mapvote_ent;
2270 float MapVote_SendEntity(entity to, float sf)
2271 {
2272         float i;
2273
2274         if(sf & 1)
2275                 sf &~= 2; // if we send 1, we don't need to also send 2
2276
2277         WriteByte(MSG_ENTITY, ENT_CLIENT_MAPVOTE);
2278         WriteByte(MSG_ENTITY, sf);
2279
2280         if(sf & 1)
2281         {
2282                 // flag 1 == initialization
2283                 for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2284                         WriteString(MSG_ENTITY, mapvote_screenshot_dirs[i]);
2285                 WriteString(MSG_ENTITY, "");
2286                 WriteByte(MSG_ENTITY, mapvote_count);
2287                 WriteByte(MSG_ENTITY, mapvote_abstain);
2288                 WriteByte(MSG_ENTITY, mapvote_detail);
2289                 WriteCoord(MSG_ENTITY, mapvote_timeout);
2290                 if(mapvote_count <= 8)
2291                         WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2292                 else
2293                         WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2294                 for(i = 0; i < mapvote_count; ++i)
2295                         if(mapvote_maps[i] != "")
2296                         {
2297                                 if(mapvote_abstain && i == mapvote_count - 1)
2298                                 {
2299                                         WriteString(MSG_ENTITY, ""); // abstain needs no text
2300                                         WriteByte(MSG_ENTITY, 0); // abstain needs no screenshot dir
2301                                         WriteString(MSG_ENTITY, ""); // abstain needs no pack
2302                                 }
2303                                 else
2304                                 {
2305                                         WriteString(MSG_ENTITY, mapvote_maps[i]);
2306                                         WriteByte(MSG_ENTITY, mapvote_maps_screenshot_dir[i]);
2307                                         WriteString(MSG_ENTITY, mapvote_maps_pakfile[i]);
2308                                 }
2309                         }
2310         }
2311
2312         if(sf & 2)
2313         {
2314                 // flag 2 == update of mask
2315                 if(mapvote_count <= 8)
2316                         WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2317                 else
2318                         WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2319         }
2320
2321         if(sf & 4)
2322         {
2323                 if(mapvote_detail)
2324                         for(i = 0; i < mapvote_count; ++i)
2325                                 if(mapvote_maps[i] != "")
2326                                         WriteByte(MSG_ENTITY, mapvote_votes[i]);
2327
2328                 WriteByte(MSG_ENTITY, to.mapvote);
2329         }
2330
2331         return TRUE;
2332 }
2333
2334 void MapVote_Spawn()
2335 {
2336         Net_LinkEntity(mapvote_ent = spawn(), FALSE, 0, MapVote_SendEntity);
2337 }
2338
2339 void MapVote_TouchMask()
2340 {
2341         mapvote_ent.SendFlags |= 2;
2342 }
2343
2344 void MapVote_TouchVotes(entity voter)
2345 {
2346         mapvote_ent.SendFlags |= 4;
2347 }
2348
2349 float MapVote_Finished(float mappos)
2350 {
2351         string result;
2352         float i;
2353         float didntvote;
2354
2355         if(cvar("sv_eventlog"))
2356         {
2357                 result = strcat(":vote:finished:", mapvote_maps[mappos]);
2358                 result = strcat(result, ":", ftos(mapvote_votes[mappos]), "::");
2359                 didntvote = mapvote_voters;
2360                 for(i = 0; i < mapvote_count; ++i)
2361                         if(mapvote_maps[i] != "")
2362                         {
2363                                 didntvote -= mapvote_votes[i];
2364                                 if(i != mappos)
2365                                 {
2366                                         result = strcat(result, ":", mapvote_maps[i]);
2367                                         result = strcat(result, ":", ftos(mapvote_votes[i]));
2368                                 }
2369                         }
2370                 result = strcat(result, ":didn't vote:", ftos(didntvote));
2371
2372                 GameLogEcho(result);
2373                 if(mapvote_maps_suggested[mappos])
2374                         GameLogEcho(strcat(":vote:suggestion_accepted:", mapvote_maps[mappos]));
2375         }
2376
2377         FOR_EACH_REALCLIENT(other)
2378                 FixClientCvars(other);
2379
2380         Map_Goto_SetStr(mapvote_maps[mappos]);
2381         Map_Goto();
2382         alreadychangedlevel = TRUE;
2383         return TRUE;
2384 }
2385 void MapVote_CheckRules_1()
2386 {
2387         float i;
2388
2389         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
2390         {
2391                 //dprint("Map ", ftos(i), ": "); dprint(mapvote_maps[i], "\n");
2392                 mapvote_votes[i] = 0;
2393         }
2394
2395         mapvote_voters = 0;
2396         FOR_EACH_REALCLIENT(other)
2397         {
2398                 ++mapvote_voters;
2399                 if(other.mapvote)
2400                 {
2401                         i = other.mapvote - 1;
2402                         //dprint("Player ", other.netname, " vote = ", ftos(other.mapvote - 1), "\n");
2403                         mapvote_votes[i] = mapvote_votes[i] + 1;
2404                 }
2405         }
2406 }
2407
2408 float MapVote_CheckRules_2()
2409 {
2410         float i;
2411         float firstPlace, secondPlace;
2412         float firstPlaceVotes, secondPlaceVotes;
2413         float mapvote_voters_real;
2414         string result;
2415
2416         if(mapvote_count_real == 1)
2417                 return MapVote_Finished(0);
2418
2419         mapvote_voters_real = mapvote_voters;
2420         if(mapvote_abstain)
2421                 mapvote_voters_real -= mapvote_votes[mapvote_count - 1];
2422
2423         RandomSelection_Init();
2424         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2425                 RandomSelection_Add(world, i, string_null, 1, mapvote_votes[i]);
2426         firstPlace = RandomSelection_chosen_float;
2427         firstPlaceVotes = RandomSelection_best_priority;
2428         //dprint("First place: ", ftos(firstPlace), "\n");
2429         //dprint("First place votes: ", ftos(firstPlaceVotes), "\n");
2430
2431         RandomSelection_Init();
2432         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2433                 if(i != firstPlace)
2434                         RandomSelection_Add(world, i, string_null, 1, mapvote_votes[i]);
2435         secondPlace = RandomSelection_chosen_float;
2436         secondPlaceVotes = RandomSelection_best_priority;
2437         //dprint("Second place: ", ftos(secondPlace), "\n");
2438         //dprint("Second place votes: ", ftos(secondPlaceVotes), "\n");
2439
2440         if(firstPlace == -1)
2441                 error("No first place in map vote... WTF?");
2442
2443         if(secondPlace == -1 || time > mapvote_timeout || (mapvote_voters_real - firstPlaceVotes) < firstPlaceVotes)
2444                 return MapVote_Finished(firstPlace);
2445
2446         if(mapvote_keeptwotime)
2447                 if(time > mapvote_keeptwotime || (mapvote_voters_real - firstPlaceVotes - secondPlaceVotes) < secondPlaceVotes)
2448                 {
2449                         float didntvote;
2450                         MapVote_TouchMask();
2451                         mapvote_message = "Now decide between the TOP TWO!";
2452                         mapvote_keeptwotime = 0;
2453                         result = strcat(":vote:keeptwo:", mapvote_maps[firstPlace]);
2454                         result = strcat(result, ":", ftos(firstPlaceVotes));
2455                         result = strcat(result, ":", mapvote_maps[secondPlace]);
2456                         result = strcat(result, ":", ftos(secondPlaceVotes), "::");
2457                         didntvote = mapvote_voters;
2458                         for(i = 0; i < mapvote_count; ++i)
2459                                 if(mapvote_maps[i] != "")
2460                                 {
2461                                         didntvote -= mapvote_votes[i];
2462                                         if(i != firstPlace)
2463                                                 if(i != secondPlace)
2464                                                 {
2465                                                         result = strcat(result, ":", mapvote_maps[i]);
2466                                                         result = strcat(result, ":", ftos(mapvote_votes[i]));
2467                                                         if(i < mapvote_count_real)
2468                                                         {
2469                                                                 strunzone(mapvote_maps[i]);
2470                                                                 mapvote_maps[i] = "";
2471                                                                 strunzone(mapvote_maps_pakfile[i]);
2472                                                                 mapvote_maps_pakfile[i] = "";
2473                                                         }
2474                                                 }
2475                                 }
2476                         result = strcat(result, ":didn't vote:", ftos(didntvote));
2477                         if(cvar("sv_eventlog"))
2478                                 GameLogEcho(result);
2479                 }
2480
2481         return FALSE;
2482 }
2483 void MapVote_Tick()
2484 {
2485         float keeptwo;
2486         float totalvotes;
2487
2488         keeptwo = mapvote_keeptwotime;
2489         MapVote_CheckRules_1(); // count
2490         if(MapVote_CheckRules_2()) // decide
2491                 return;
2492
2493         totalvotes = 0;
2494         FOR_EACH_REALCLIENT(other)
2495         {
2496                 // hide scoreboard again
2497                 if(other.health != 2342)
2498                 {
2499                         other.health = 2342;
2500                         other.impulse = 0;
2501                         if(clienttype(other) == CLIENTTYPE_REAL)
2502                         {
2503                                 msg_entity = other;
2504                                 WriteByte(MSG_ONE, SVC_FINALE);
2505                                 WriteString(MSG_ONE, "");
2506                         }
2507                 }
2508
2509                 // clear possibly invalid votes
2510                 if(mapvote_maps[other.mapvote - 1] == "")
2511                         other.mapvote = 0;
2512                 // use impulses as new vote
2513                 if(other.impulse >= 1 && other.impulse <= mapvote_count)
2514                         if(mapvote_maps[other.impulse - 1] != "")
2515                         {
2516                                 other.mapvote = other.impulse;
2517                                 MapVote_TouchVotes(other);
2518                         }
2519                 other.impulse = 0;
2520
2521                 if(other.mapvote)
2522                         ++totalvotes;
2523         }
2524
2525         MapVote_CheckRules_1(); // just count
2526 }
2527 void MapVote_Start()
2528 {
2529         if(mapvote_run)
2530                 return;
2531
2532         MapInfo_Enumerate();
2533         if(MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1))
2534                 mapvote_run = TRUE;
2535 }
2536 void MapVote_Think()
2537 {
2538         if(!mapvote_run)
2539                 return;
2540
2541         if(alreadychangedlevel)
2542                 return;
2543
2544         if(time < mapvote_nextthink)
2545                 return;
2546         //dprint("tick\n");
2547
2548         mapvote_nextthink = time + 0.5;
2549
2550         if(!mapvote_initialized)
2551         {
2552                 if(cvar("rescan_pending") == 1)
2553                 {
2554                         cvar_set("rescan_pending", "2");
2555                         localcmd("fs_rescan\nrescan_pending 3\n");
2556                         return;
2557                 }
2558                 else if(cvar("rescan_pending") == 2)
2559                 {
2560                         return;
2561                 }
2562                 else if(cvar("rescan_pending") == 3)
2563                 {
2564                         // now build missing mapinfo files
2565                         if(!MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1))
2566                                 return;
2567
2568                         // we're done, start the timer
2569                         cvar_set("rescan_pending", "0");
2570                 }
2571
2572                 mapvote_initialized = TRUE;
2573                 if(DoNextMapOverride())
2574                         return;
2575                 if(!cvar("g_maplist_votable") || player_count <= 0)
2576                 {
2577                         GotoNextMap();
2578                         return;
2579                 }
2580                 MapVote_Init();
2581         }
2582
2583         MapVote_Tick();
2584 };
2585
2586 string GotoMap(string m)
2587 {
2588         if(!MapInfo_CheckMap(m))
2589                 return "The map you chose is not available on this server.";
2590         cvar_set("nextmap", m);
2591         cvar_set("timelimit", "-1");
2592         if(mapvote_initialized || alreadychangedlevel)
2593         {
2594                 if(DoNextMapOverride())
2595                         return "Map switch initiated.";
2596                 else
2597                         return "Hm... no. For some reason I like THIS map more.";
2598         }
2599         else
2600                 return "Map switch will happen after scoreboard.";
2601 }
2602
2603
2604 void EndFrame()
2605 {
2606         float altime;
2607         FOR_EACH_REALCLIENT(self)
2608         {
2609                 if(self.classname == "spectator")
2610                 {
2611                         if(self.enemy.typehitsound)
2612                                 play2(self, "misc/typehit.wav");
2613                         else if(self.enemy.hitsound && self.cvar_cl_hitsound)
2614                                 play2(self, "misc/hit.wav");
2615                 }
2616                 else
2617                 {
2618                         if(self.typehitsound)
2619                                 play2(self, "misc/typehit.wav");
2620                         else if(self.hitsound && self.cvar_cl_hitsound)
2621                                 play2(self, "misc/hit.wav");
2622                 }
2623         }
2624         altime = time + frametime * (1 + cvar("g_antilag_nudge"));
2625         // add 1 frametime because after this, engine SV_Physics
2626         // increases time by a frametime and then networks the frame
2627         // add another frametime because client shows everything with
2628         // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2629         // needed!
2630         FOR_EACH_CLIENT(self)
2631         {
2632                 self.hitsound = FALSE;
2633                 self.typehitsound = FALSE;
2634                 antilag_record(self, altime);
2635         }
2636 }
2637
2638
2639 /*
2640  * RedirectionThink:
2641  * returns TRUE if redirecting
2642  */
2643 float redirection_timeout;
2644 float redirection_nextthink;
2645 float RedirectionThink()
2646 {
2647         float clients_found;
2648
2649         if(redirection_target == "")
2650                 return FALSE;
2651
2652         if(!redirection_timeout)
2653         {
2654                 cvar_set("sv_public", "-2");
2655                 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2656                 if(redirection_target == "self")
2657                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2658                 else
2659                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2660         }
2661
2662         if(time < redirection_nextthink)
2663                 return TRUE;
2664
2665         redirection_nextthink = time + 1;
2666
2667         clients_found = 0;
2668         FOR_EACH_REALCLIENT(self)
2669         {
2670                 print("Redirecting: sending connect command to ", self.netname, "\n");
2671                 if(redirection_target == "self")
2672                         stuffcmd(self, "\ndisconnect; reconnect\n");
2673                 else
2674                         stuffcmd(self, strcat("\ndisconnect; connect ", redirection_target, "\n"));
2675                 ++clients_found;
2676         }
2677
2678         print("Redirecting: ", ftos(clients_found), " clients left.\n");
2679
2680         if(time > redirection_timeout || clients_found == 0)
2681                 localcmd("\nwait; wait; wait; quit\n");
2682
2683         return TRUE;
2684 }
2685
2686 void RestoreGame()
2687 {
2688         // Loaded from a save game
2689         // some things then break, so let's work around them...
2690
2691         // Progs DB (capture records)
2692         if(sv_cheats)
2693                 ServerProgsDB = db_create();
2694         else
2695                 ServerProgsDB = db_load("server.db");
2696
2697         // Mapinfo
2698         MapInfo_Shutdown();
2699         MapInfo_Enumerate();
2700         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2701         WeaponStats_Init();
2702 }
2703
2704 void SV_Shutdown()
2705 {
2706         if(gameover > 1) // shutting down already?
2707                 return;
2708
2709         gameover = 2; // 2 = server shutting down
2710
2711         if(world_initialized > 0)
2712         {
2713                 world_initialized = 0;
2714                 print("Saving persistent data...\n");
2715                 Ban_SaveBans();
2716                 if(!sv_cheats)
2717                         db_save(ServerProgsDB, "server.db");
2718                 if(cvar("developer"))
2719                         db_save(TemporaryDB, "server-temp.db");
2720                 db_close(ServerProgsDB);
2721                 db_close(TemporaryDB);
2722                 print("done!\n");
2723                 // tell the bot system the game is ending now
2724                 bot_endgame();
2725
2726                 WeaponStats_Shutdown();
2727                 MapInfo_Shutdown();
2728         }
2729         else if(world_initialized == 0)
2730         {
2731                 print("NOTE: crashed before even initializing the world, not saving persistent data\n");
2732         }
2733 }