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