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