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