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