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