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