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