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