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