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