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