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