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