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