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