]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/g_world.qc
Ignore sv_mapformat_is_quake3 when checking cvar purity. Fixes #1472
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / g_world.qc
1 #include "g_world.qh"
2 #include "_all.qh"
3
4 #include "anticheat.qh"
5 #include "antilag.qh"
6 #include "bot/bot.qh"
7 #include "campaign.qh"
8 #include "cheats.qh"
9 #include "cl_client.qh"
10 #include "command/common.qh"
11 #include "command/getreplies.qh"
12 #include "command/sv_cmd.qh"
13 #include "command/vote.qh"
14 #include "g_hook.qh"
15 #include "ipban.qh"
16 #include "mapvoting.qh"
17 #include "mutators/mutators_include.qh"
18 #include "race.qh"
19 #include "scores.qh"
20 #include "secret.qh"
21 #include "teamplay.qh"
22 #include "waypointsprites.qh"
23 #include "weapons/weaponstats.qh"
24 #include "../common/buffs.qh"
25 #include "../common/constants.qh"
26 #include "../common/deathtypes.qh"
27 #include "../common/mapinfo.qh"
28 #include "../common/monsters/monsters.qh"
29 #include "../common/monsters/sv_monsters.qh"
30 #include "../common/notifications.qh"
31 #include "../common/playerstats.qh"
32 #include "../common/stats.qh"
33 #include "../common/teams.qh"
34 #include "../common/util.qh"
35 #include "../common/weapons/weapons.qh"
36
37 const float LATENCY_THINKRATE = 10;
38 .float latency_sum;
39 .float latency_cnt;
40 .float latency_time;
41 entity pingplreport;
42 void PingPLReport_Think()
43 {
44         float delta;
45         entity e;
46
47         delta = 3 / maxclients;
48         if(delta < sys_frametime)
49                 delta = 0;
50         self.nextthink = time + delta;
51
52         e = edict_num(self.cnt + 1);
53         if(IS_REAL_CLIENT(e))
54         {
55                 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
56                 WriteByte(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
57                 WriteByte(MSG_BROADCAST, self.cnt);
58                 WriteShort(MSG_BROADCAST, max(1, e.ping));
59                 WriteByte(MSG_BROADCAST, ceil(e.ping_packetloss * 255));
60                 WriteByte(MSG_BROADCAST, ceil(e.ping_movementloss * 255));
61
62                 // record latency times for clients throughout the match so we can report it to playerstats
63                 if(time > (e.latency_time + LATENCY_THINKRATE))
64                 {
65                         e.latency_sum += e.ping;
66                         e.latency_cnt += 1;
67                         e.latency_time = time;
68                         //print("sum: ", ftos(e.latency_sum), ", cnt: ", ftos(e.latency_cnt), ", avg: ", ftos(e.latency_sum / e.latency_cnt), ".\n");
69                 }
70         }
71         else
72         {
73                 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
74                 WriteByte(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
75                 WriteByte(MSG_BROADCAST, self.cnt);
76                 WriteShort(MSG_BROADCAST, 0);
77                 WriteByte(MSG_BROADCAST, 0);
78                 WriteByte(MSG_BROADCAST, 0);
79         }
80         self.cnt = (self.cnt + 1) % maxclients;
81 }
82 void PingPLReport_Spawn()
83 {
84         pingplreport = spawn();
85         pingplreport.classname = "pingplreport";
86         pingplreport.think = PingPLReport_Think;
87         pingplreport.nextthink = time;
88 }
89
90 const float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
91 string redirection_target;
92 float world_initialized;
93
94 string GetGametype();
95 void ShuffleMaplist();
96
97 void SetDefaultAlpha()
98 {
99         if(autocvar_g_running_guns)
100         {
101                 default_player_alpha = -1;
102                 default_weapon_alpha = +1;
103         }
104         else if(g_cloaked)
105         {
106                 default_player_alpha = autocvar_g_balance_cloaked_alpha;
107                 default_weapon_alpha = default_player_alpha;
108         }
109         else
110         {
111                 default_player_alpha = autocvar_g_player_alpha;
112                 if(default_player_alpha == 0)
113                         default_player_alpha = 1;
114                 default_weapon_alpha = default_player_alpha;
115         }
116 }
117
118 void GotoFirstMap()
119 {
120         float n;
121         if(autocvar__sv_init)
122         {
123                 // cvar_set("_sv_init", "0");
124                 // we do NOT set this to 0 any more, so someone "accidentally" changing
125                 // to this "init" map on a dedicated server will cause no permanent
126                 // harm
127                 if(autocvar_g_maplist_shuffle)
128                         ShuffleMaplist();
129                 n = tokenizebyseparator(autocvar_g_maplist, " ");
130                 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
131
132                 MapInfo_Enumerate();
133                 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
134
135                 if(!DoNextMapOverride(1))
136                         GotoNextMap(1);
137
138                 return;
139         }
140
141         if(time < 5)
142         {
143                 self.nextthink = time;
144         }
145         else
146         {
147                 self.nextthink = time + 1;
148                 print("Waiting for _sv_init being set to 1 by initialization scripts...\n");
149         }
150 }
151
152 void cvar_changes_init()
153 {
154         float h;
155         string k, v, d;
156         float n, i, adding, pureadding;
157
158         if(cvar_changes)
159                 strunzone(cvar_changes);
160         cvar_changes = string_null;
161         if(cvar_purechanges)
162                 strunzone(cvar_purechanges);
163         cvar_purechanges = string_null;
164         cvar_purechanges_count = 0;
165
166         h = buf_create();
167         buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
168         n = buf_getsize(h);
169
170         adding = true;
171         pureadding = true;
172
173         for(i = 0; i < n; ++i)
174         {
175                 k = bufstr_get(h, i);
176
177 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
178 #define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
179 #define BADCVAR(p) if(k == p) continue
180
181                 // general excludes and namespaces for server admin used cvars
182                 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
183
184                 // internal
185                 BADPREFIX("csqc_");
186                 BADPREFIX("cvar_check_");
187                 BADCVAR("gamecfg");
188                 BADCVAR("g_configversion");
189                 BADCVAR("g_maplist_index");
190                 BADCVAR("halflifebsp");
191                 BADCVAR("sv_mapformat_is_quake3");
192                 BADPREFIX("sv_world");
193
194                 // client
195                 BADPREFIX("chase_");
196                 BADPREFIX("cl_");
197                 BADPREFIX("con_");
198                 BADPREFIX("scoreboard_");
199                 BADPREFIX("g_campaign");
200                 BADPREFIX("g_waypointsprite_");
201                 BADPREFIX("gl_");
202                 BADPREFIX("joy");
203                 BADPREFIX("hud_");
204                 BADPREFIX("m_");
205                 BADPREFIX("menu_");
206                 BADPREFIX("net_slist_");
207                 BADPREFIX("r_");
208                 BADPREFIX("sbar_");
209                 BADPREFIX("scr_");
210                 BADPREFIX("snd_");
211                 BADPREFIX("show");
212                 BADPREFIX("sensitivity");
213                 BADPREFIX("userbind");
214                 BADPREFIX("v_");
215                 BADPREFIX("vid_");
216                 BADPREFIX("crosshair");
217                 BADCVAR("mod_q3bsp_lightmapmergepower");
218                 BADCVAR("mod_q3bsp_nolightmaps");
219                 BADCVAR("fov");
220                 BADCVAR("mastervolume");
221                 BADCVAR("volume");
222                 BADCVAR("bgmvolume");
223
224                 // private
225                 BADCVAR("developer");
226                 BADCVAR("log_dest_udp");
227                 BADCVAR("net_address");
228                 BADCVAR("net_address_ipv6");
229                 BADCVAR("port");
230                 BADCVAR("savedgamecfg");
231                 BADCVAR("serverconfig");
232                 BADCVAR("sv_autoscreenshot");
233                 BADCVAR("sv_heartbeatperiod");
234                 BADCVAR("sv_vote_master_password");
235                 BADCVAR("sys_colortranslation");
236                 BADCVAR("sys_specialcharactertranslation");
237                 BADCVAR("timeformat");
238                 BADCVAR("timestamps");
239                 BADPREFIX("developer_");
240                 BADPREFIX("g_ban_");
241                 BADPREFIX("g_banned_list");
242                 BADPREFIX("g_chat_flood_");
243                 BADPREFIX("g_ghost_items");
244                 BADPREFIX("g_playerstats_");
245                 BADPREFIX("g_respawn_ghosts");
246                 BADPREFIX("g_voice_flood_");
247                 BADPREFIX("log_file");
248                 BADPREFIX("rcon_");
249                 BADPREFIX("sv_allowdownloads");
250                 BADPREFIX("sv_autodemo");
251                 BADPREFIX("sv_curl_");
252                 BADPREFIX("sv_eventlog");
253                 BADPREFIX("sv_logscores_");
254                 BADPREFIX("sv_master");
255                 BADPREFIX("sv_weaponstats_");
256                 BADPREFIX("sv_waypointsprite_");
257                 BADCVAR("rescan_pending");
258
259                 // these can contain player IDs, so better hide
260                 BADPREFIX("g_forced_team_");
261
262                 // mapinfo
263                 BADCVAR("fraglimit");
264                 BADCVAR("g_assault");
265                 BADCVAR("g_ca");
266                 BADCVAR("g_ca_teams");
267                 BADCVAR("g_ctf");
268                 BADCVAR("g_cts");
269                 BADCVAR("g_dm");
270                 BADCVAR("g_domination");
271                 BADCVAR("g_domination_default_teams");
272                 BADCVAR("g_freezetag");
273                 BADCVAR("g_freezetag_teams");
274                 BADCVAR("g_keepaway");
275                 BADCVAR("g_keyhunt");
276                 BADCVAR("g_keyhunt_teams");
277                 BADCVAR("g_lms");
278                 BADCVAR("g_nexball");
279                 BADCVAR("g_onslaught");
280                 BADCVAR("g_race");
281                 BADCVAR("g_race_qualifying_timelimit");
282                 BADCVAR("g_tdm");
283                 BADCVAR("g_tdm_teams");
284                 BADCVAR("leadlimit");
285                 BADCVAR("nextmap");
286                 BADCVAR("teamplay");
287                 BADCVAR("timelimit");
288
289                 // long
290                 BADCVAR("hostname");
291                 BADCVAR("g_maplist");
292                 BADCVAR("g_maplist_mostrecent");
293                 BADCVAR("sv_motd");
294
295                 v = cvar_string(k);
296                 d = cvar_defstring(k);
297                 if(v == d)
298                         continue;
299
300                 if(adding)
301                 {
302                         cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
303                         if(strlen(cvar_changes) > 16384)
304                         {
305                                 cvar_changes = "// too many settings have been changed to show them here\n";
306                                 adding = 0;
307                         }
308                 }
309
310                 // now check if the changes are actually gameplay relevant
311
312                 // does nothing visible
313                 BADCVAR("captureleadlimit_override");
314                 BADCVAR("g_balance_kill_delay");
315                 BADCVAR("g_ca_point_limit");
316                 BADCVAR("g_ca_point_leadlimit");
317                 BADCVAR("g_ctf_captimerecord_always");
318                 BADCVAR("g_ctf_flag_glowtrails");
319                 BADCVAR("g_ctf_flag_pickup_verbosename");
320                 BADCVAR("g_domination_point_leadlimit");
321                 BADCVAR("g_forced_respawn");
322                 BADCVAR("g_freezetag_point_limit");
323                 BADCVAR("g_freezetag_point_leadlimit");
324                 BADCVAR("g_keyhunt_point_leadlimit");
325                 BADPREFIX("g_mod_");
326                 BADCVAR("g_invasion_point_limit");
327                 BADCVAR("g_nexball_goalleadlimit");
328                 BADCVAR("g_tdm_point_limit");
329                 BADCVAR("g_tdm_point_leadlimit");
330                 BADCVAR("leadlimit_and_fraglimit");
331                 BADCVAR("leadlimit_override");
332                 BADCVAR("pausable");
333                 BADCVAR("sv_allow_fullbright");
334                 BADCVAR("sv_checkforpacketsduringsleep");
335                 BADCVAR("sv_fraginfo");
336                 BADCVAR("sv_timeout");
337                 BADPREFIX("sv_timeout_");
338                 BADPREFIX("crypto_");
339                 BADPREFIX("g_chat_");
340                 BADPREFIX("g_ctf_captimerecord_");
341                 BADPREFIX("g_maplist_votable_");
342                 BADPREFIX("net_");
343                 BADPREFIX("prvm_");
344                 BADPREFIX("skill_");
345                 BADPREFIX("sv_cullentities_");
346                 BADPREFIX("sv_fraginfo_");
347                 BADPREFIX("sv_maxidle_");
348                 BADPREFIX("sv_vote_");
349                 BADPREFIX("timelimit_");
350                 BADCVAR("gameversion");
351                 BADPREFIX("gameversion_");
352                 BADCVAR("sv_namechangetimer");
353
354                 // allowed changes to server admins (please sync this to server.cfg)
355                 // vi commands:
356                 //   :/"impure"/,$d
357                 //   :g!,^\/\/[^ /],d
358                 //   :%s,//\([^ ]*\).*,BADCVAR("\1");,
359                 //   :%!sort
360                 // yes, this does contain some redundant stuff, don't really care
361                 BADCVAR("bot_config_file");
362                 BADCVAR("bot_number");
363                 BADCVAR("bot_prefix");
364                 BADCVAR("bot_suffix");
365                 BADCVAR("capturelimit_override");
366                 BADCVAR("fraglimit_override");
367                 BADCVAR("gametype");
368                 BADCVAR("g_antilag");
369                 BADCVAR("g_balance_teams");
370                 BADCVAR("g_balance_teams_prevent_imbalance");
371                 BADCVAR("g_balance_teams_scorefactor");
372                 BADCVAR("g_ban_sync_trusted_servers");
373                 BADCVAR("g_ban_sync_uri");
374                 BADCVAR("g_ca_teams_override");
375                 BADCVAR("g_ctf_ignore_frags");
376                 BADCVAR("g_domination_point_limit");
377                 BADCVAR("g_freezetag_teams_override");
378                 BADCVAR("g_friendlyfire");
379                 BADCVAR("g_fullbrightitems");
380                 BADCVAR("g_fullbrightplayers");
381                 BADCVAR("g_keyhunt_point_limit");
382                 BADCVAR("g_keyhunt_teams_override");
383                 BADCVAR("g_lms_lives_override");
384                 BADCVAR("g_maplist");
385                 BADCVAR("g_maplist_check_waypoints");
386                 BADCVAR("g_maplist_mostrecent_count");
387                 BADCVAR("g_maplist_shuffle");
388                 BADCVAR("g_maplist_votable");
389                 BADCVAR("g_maplist_votable_abstain");
390                 BADCVAR("g_maplist_votable_nodetail");
391                 BADCVAR("g_maplist_votable_suggestions");
392                 BADCVAR("g_maxplayers");
393                 BADCVAR("g_mirrordamage");
394                 BADCVAR("g_nexball_goallimit");
395                 BADCVAR("g_powerups");
396                 BADCVAR("g_start_delay");
397                 BADCVAR("g_warmup");
398                 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
399                 BADCVAR("hostname");
400                 BADCVAR("log_file");
401                 BADCVAR("maxplayers");
402                 BADCVAR("minplayers");
403                 BADCVAR("net_address");
404                 BADCVAR("port");
405                 BADCVAR("rcon_password");
406                 BADCVAR("rcon_restricted_commands");
407                 BADCVAR("rcon_restricted_password");
408                 BADCVAR("skill");
409                 BADCVAR("sv_adminnick");
410                 BADCVAR("sv_autoscreenshot");
411                 BADCVAR("sv_autotaunt");
412                 BADCVAR("sv_curl_defaulturl");
413                 BADCVAR("sv_defaultcharacter");
414                 BADCVAR("sv_defaultplayercolors");
415                 BADCVAR("sv_defaultplayermodel");
416                 BADCVAR("sv_defaultplayerskin");
417                 BADCVAR("sv_maxidle");
418                 BADCVAR("sv_maxrate");
419                 BADCVAR("sv_motd");
420                 BADCVAR("sv_public");
421                 BADCVAR("sv_ready_restart");
422                 BADCVAR("sv_status_privacy");
423                 BADCVAR("sv_taunt");
424                 BADCVAR("sv_vote_call");
425                 BADCVAR("sv_vote_commands");
426                 BADCVAR("sv_vote_majority_factor");
427                 BADCVAR("sv_vote_master");
428                 BADCVAR("sv_vote_master_commands");
429                 BADCVAR("sv_vote_master_password");
430                 BADCVAR("sv_vote_simple_majority_factor");
431                 BADCVAR("teamplay_mode");
432                 BADCVAR("timelimit_override");
433                 BADCVAR("g_spawnshieldtime");
434                 BADPREFIX("g_warmup_");
435                 BADPREFIX("sv_ready_restart_");
436
437                 // mutators that announce themselves properly to the server browser
438                 BADCVAR("g_instagib");
439                 BADCVAR("g_new_toys");
440                 BADCVAR("g_nix");
441                 BADCVAR("g_grappling_hook");
442                 BADCVAR("g_jetpack");
443
444 #undef BADPREFIX
445 #undef BADCVAR
446
447                 if(pureadding)
448                 {
449                         cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
450                         if(strlen(cvar_purechanges) > 16384)
451                         {
452                                 cvar_purechanges = "// too many settings have been changed to show them here\n";
453                                 pureadding = 0;
454                         }
455                 }
456                 ++cvar_purechanges_count;
457                 // WARNING: this variable is used for the server list
458                 // NEVER dare to skip this code!
459                 // Hacks to intentionally appearing as "pure server" even though you DO have
460                 // modified settings may be punished by removal from the server list.
461                 // You can do to the variables cvar_changes and cvar_purechanges all you want,
462                 // though.
463         }
464         buf_del(h);
465         if(cvar_changes == "")
466                 cvar_changes = "// this server runs at default server settings\n";
467         else
468                 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
469         cvar_changes = strzone(cvar_changes);
470         if(cvar_purechanges == "")
471                 cvar_purechanges = "// this server runs at default gameplay settings\n";
472         else
473                 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
474         cvar_purechanges = strzone(cvar_purechanges);
475 }
476
477 void detect_maptype()
478 {
479 #if 0
480         vector o, v;
481         float i;
482
483         for (;;)
484         {
485                 o = world.mins;
486                 o.x += random() * (world.maxs.x - world.mins.x);
487                 o.y += random() * (world.maxs.y - world.mins.y);
488                 o.z += random() * (world.maxs.z - world.mins.z);
489
490                 tracebox(o, PL_MIN, PL_MAX, o - '0 0 32768', MOVE_WORLDONLY, world);
491                 if(trace_fraction == 1)
492                         continue;
493
494                 v = trace_endpos;
495
496                 for(i = 0; i < 64; i += 4)
497                 {
498                         tracebox(o, '-1 -1 -1' * i, '1 1 1' * i, o - '0 0 32768', MOVE_WORLDONLY, world);
499         if(trace_fraction == 1)
500                 continue;
501                         print(ftos(i), " -> ", vtos(trace_endpos), "\n");
502                 }
503
504                 break;
505         }
506 #endif
507 }
508
509 entity randomseed;
510 float RandomSeed_Send(entity to, int sf)
511 {
512         WriteByte(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
513         WriteShort(MSG_ENTITY, self.cnt);
514         return true;
515 }
516 void RandomSeed_Think()
517 {
518         self.cnt = bound(0, floor(random() * 65536), 65535);
519         self.nextthink = time + 5;
520
521         self.SendFlags |= 1;
522 }
523 void RandomSeed_Spawn()
524 {
525         randomseed = spawn();
526         randomseed.think = RandomSeed_Think;
527         Net_LinkEntity(randomseed, false, 0, RandomSeed_Send);
528
529         entity oldself;
530         oldself = self;
531         self = randomseed;
532         self.think(); // sets random seed and nextthink
533         self = oldself;
534 }
535
536 void spawnfunc___init_dedicated_server(void)
537 {
538         // handler for _init/_init map (only for dedicated server initialization)
539
540         world_initialized = -1; // don't complain
541         cvar = cvar_normal;
542         cvar_string = cvar_string_normal;
543         cvar_set = cvar_set_normal;
544
545         remove = remove_unsafely;
546
547         entity e;
548         e = spawn();
549         e.think = GotoFirstMap;
550         e.nextthink = time; // this is usually 1 at this point
551
552         e = spawn();
553         e.classname = "info_player_deathmatch"; // safeguard against player joining
554
555         self.classname = "worldspawn"; // safeguard against various stuff ;)
556
557         // needs to be done so early because of the constants they create
558         CALL_ACCUMULATED_FUNCTION(RegisterWeapons);
559         CALL_ACCUMULATED_FUNCTION(RegisterMonsters);
560         CALL_ACCUMULATED_FUNCTION(RegisterGametypes);
561         CALL_ACCUMULATED_FUNCTION(RegisterNotifications);
562         CALL_ACCUMULATED_FUNCTION(RegisterDeathtypes);
563         CALL_ACCUMULATED_FUNCTION(RegisterBuffs);
564
565         MapInfo_Enumerate();
566         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
567 }
568
569 void Map_MarkAsRecent(string m);
570 float world_already_spawned;
571 void Nagger_Init();
572 void ClientInit_Spawn();
573 void WeaponStats_Init();
574 void WeaponStats_Shutdown();
575 void spawnfunc_worldspawn (void)
576 {
577         float fd, l, j, n;
578         string s;
579
580         cvar = cvar_normal;
581         cvar_string = cvar_string_normal;
582         cvar_set = cvar_set_normal;
583
584         if(world_already_spawned)
585                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
586         world_already_spawned = true;
587
588         remove = remove_safely; // during spawning, watch what you remove!
589
590         cvar_changes_init(); // do this very early now so it REALLY matches the server config
591
592         compressShortVector_init();
593
594         entity head;
595         head = nextent(world);
596         maxclients = 0;
597         while(head)
598         {
599                 ++maxclients;
600                 head = nextent(head);
601         }
602
603         server_is_dedicated = (stof(cvar_defstring("is_dedicated")) ? true : false);
604
605         // needs to be done so early because of the constants they create
606         CALL_ACCUMULATED_FUNCTION(RegisterWeapons);
607         CALL_ACCUMULATED_FUNCTION(RegisterMonsters);
608         CALL_ACCUMULATED_FUNCTION(RegisterGametypes);
609         CALL_ACCUMULATED_FUNCTION(RegisterNotifications);
610         CALL_ACCUMULATED_FUNCTION(RegisterDeathtypes);
611         CALL_ACCUMULATED_FUNCTION(RegisterBuffs);
612
613         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
614
615         TemporaryDB = db_create();
616
617         // 0 normal
618         lightstyle(0, "m");
619
620         // 1 FLICKER (first variety)
621         lightstyle(1, "mmnmmommommnonmmonqnmmo");
622
623         // 2 SLOW STRONG PULSE
624         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
625
626         // 3 CANDLE (first variety)
627         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
628
629         // 4 FAST STROBE
630         lightstyle(4, "mamamamamama");
631
632         // 5 GENTLE PULSE 1
633         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
634
635         // 6 FLICKER (second variety)
636         lightstyle(6, "nmonqnmomnmomomno");
637
638         // 7 CANDLE (second variety)
639         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
640
641         // 8 CANDLE (third variety)
642         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
643
644         // 9 SLOW STROBE (fourth variety)
645         lightstyle(9, "aaaaaaaazzzzzzzz");
646
647         // 10 FLUORESCENT FLICKER
648         lightstyle(10, "mmamammmmammamamaaamammma");
649
650         // 11 SLOW PULSE NOT FADE TO BLACK
651         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
652
653         // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
654
655         // 63 testing
656         lightstyle(63, "a");
657
658         if(autocvar_g_campaign)
659                 CampaignPreInit();
660
661         Map_MarkAsRecent(mapname);
662
663         PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
664
665         precache_model ("null"); // we need this one before InitGameplayMode
666         InitGameplayMode();
667         readlevelcvars();
668         GrappleHookInit();
669
670         player_count = 0;
671         bot_waypoints_for_items = autocvar_g_waypoints_for_items;
672         if(bot_waypoints_for_items == 1)
673                 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
674                         bot_waypoints_for_items = 0;
675
676         precache();
677
678         WaypointSprite_Init();
679
680         GameLogInit(); // prepare everything
681         // NOTE for matchid:
682         // changing the logic generating it is okay. But:
683         // it HAS to stay <= 64 chars
684         // character set: ASCII 33-126 without the following characters: : ; ' " \ $
685         if(autocvar_sv_eventlog)
686         {
687                 s = sprintf("%d.%s.%06d", itos(autocvar_sv_eventlog_files_counter), strftime(false, "%s"), floor(random() * 1000000));
688                 matchid = strzone(s);
689
690                 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
691                 s = ":gameinfo:mutators:LIST";
692
693                 ret_string = s;
694                 MUTATOR_CALLHOOK(BuildMutatorsString);
695                 s = ret_string;
696
697                 // simple, probably not good in the mutator system
698                 if(autocvar_g_grappling_hook)
699                         s = strcat(s, ":grappling_hook");
700
701                 // initialiation stuff, not good in the mutator system
702                 if(!autocvar_g_use_ammunition)
703                         s = strcat(s, ":no_use_ammunition");
704
705                 // initialiation stuff, not good in the mutator system
706                 if(autocvar_g_pickup_items == 0)
707                         s = strcat(s, ":no_pickup_items");
708                 if(autocvar_g_pickup_items > 0)
709                         s = strcat(s, ":pickup_items");
710
711                 // initialiation stuff, not good in the mutator system
712                 if(autocvar_g_weaponarena != "0")
713                         s = strcat(s, ":", autocvar_g_weaponarena, " arena");
714
715                 // TODO to mutator system
716                 if(autocvar_g_norecoil)
717                         s = strcat(s, ":norecoil");
718
719                 // TODO to mutator system
720                 if(autocvar_g_powerups == 0)
721                         s = strcat(s, ":no_powerups");
722                 if(autocvar_g_powerups > 0)
723                         s = strcat(s, ":powerups");
724
725                 GameLogEcho(s);
726                 GameLogEcho(":gameinfo:end");
727         }
728         else
729                 matchid = strzone(ftos(random()));
730
731         cvar_set("nextmap", "");
732
733         SetDefaultAlpha();
734
735         if(autocvar_g_campaign)
736                 CampaignPostInit();
737
738         Ban_LoadBans();
739
740         MapInfo_Enumerate();
741         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
742
743         if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
744         {
745                 fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
746                 if(fd != -1)
747                 {
748                         while((s = fgets(fd)))
749                         {
750                                 l = tokenize_console(s);
751                                 if(l < 2)
752                                         continue;
753                                 if(argv(0) == "cd")
754                                 {
755                                         print("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
756                                         print("  cdtrack ", argv(2), "\n");
757                                 }
758                                 else if(argv(0) == "fog")
759                                 {
760                                         print("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
761                                         print("  \"fog\" \"", s, "\"\n");
762                                 }
763                                 else if(argv(0) == "set")
764                                 {
765                                         print("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
766                                         print("  clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
767                                 }
768                                 else if(argv(0) != "//")
769                                 {
770                                         print("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
771                                         print("  clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
772                                 }
773                         }
774                         fclose(fd);
775                 }
776         }
777
778         WeaponStats_Init();
779
780         WepSet_AddStat();
781         addstat(STAT_SWITCHWEAPON, AS_INT, switchweapon);
782         addstat(STAT_SWITCHINGWEAPON, AS_INT, switchingweapon);
783         addstat(STAT_GAMESTARTTIME, AS_FLOAT, stat_game_starttime);
784         addstat(STAT_ROUNDSTARTTIME, AS_FLOAT, stat_round_starttime);
785         addstat(STAT_ALLOW_OLDVORTEXBEAM, AS_INT, stat_allow_oldvortexbeam);
786         Nagger_Init();
787
788         addstat(STAT_STRENGTH_FINISHED, AS_FLOAT, strength_finished);
789         addstat(STAT_INVINCIBLE_FINISHED, AS_FLOAT, invincible_finished);
790         addstat(STAT_SUPERWEAPONS_FINISHED, AS_FLOAT, superweapons_finished);
791         addstat(STAT_PRESSED_KEYS, AS_FLOAT, pressedkeys);
792         addstat(STAT_FUEL, AS_INT, ammo_fuel);
793         addstat(STAT_PLASMA, AS_INT, ammo_plasma);
794         addstat(STAT_SHOTORG, AS_INT, stat_shotorg);
795         addstat(STAT_LEADLIMIT, AS_FLOAT, stat_leadlimit);
796         addstat(STAT_WEAPON_CLIPLOAD, AS_INT, clip_load);
797         addstat(STAT_WEAPON_CLIPSIZE, AS_INT, clip_size);
798         addstat(STAT_LAST_PICKUP, AS_FLOAT, last_pickup);
799         addstat(STAT_HIT_TIME, AS_FLOAT, hit_time);
800         addstat(STAT_DAMAGE_DEALT_TOTAL, AS_INT, damage_dealt_total);
801         addstat(STAT_TYPEHIT_TIME, AS_FLOAT, typehit_time);
802         addstat(STAT_LAYED_MINES, AS_INT, minelayer_mines);
803
804         addstat(STAT_VORTEX_CHARGE, AS_FLOAT, vortex_charge);
805         addstat(STAT_VORTEX_CHARGEPOOL, AS_FLOAT, vortex_chargepool_ammo);
806
807         addstat(STAT_HAGAR_LOAD, AS_INT, hagar_load);
808
809         addstat(STAT_ARC_HEAT, AS_FLOAT, arc_heat_percent);
810
811         // freeze attacks
812         addstat(STAT_FROZEN, AS_INT, frozen);
813         addstat(STAT_REVIVE_PROGRESS, AS_FLOAT, revive_progress);
814
815         // g_movementspeed hack
816         addstat(STAT_MOVEVARS_AIRSPEEDLIMIT_NONQW, AS_FLOAT, stat_sv_airspeedlimit_nonqw);
817         addstat(STAT_MOVEVARS_MAXSPEED, AS_FLOAT, stat_sv_maxspeed);
818         addstat(STAT_MOVEVARS_AIRACCEL_QW, AS_FLOAT, stat_sv_airaccel_qw);
819         addstat(STAT_MOVEVARS_AIRSTRAFEACCEL_QW, AS_FLOAT, stat_sv_airstrafeaccel_qw);
820
821         // secrets
822         addstat(STAT_SECRETS_TOTAL, AS_FLOAT, stat_secrets_total);
823         addstat(STAT_SECRETS_FOUND, AS_FLOAT, stat_secrets_found);
824
825         // monsters
826         addstat(STAT_MONSTERS_TOTAL, AS_FLOAT, stat_monsters_total);
827         addstat(STAT_MONSTERS_KILLED, AS_FLOAT, stat_monsters_killed);
828
829         // misc
830         addstat(STAT_RESPAWN_TIME, AS_FLOAT, stat_respawn_time);
831
832         next_pingtime = time + 5;
833
834         detect_maptype();
835
836         // set up information replies for clients and server to use
837         maplist_reply = strzone(getmaplist());
838         lsmaps_reply = strzone(getlsmaps());
839         monsterlist_reply = strzone(getmonsterlist());
840         for(int i = 0; i < 10; ++i)
841         {
842                 s = getrecords(i);
843                 if (s)
844                         records_reply[i] = strzone(s);
845         }
846         ladder_reply = strzone(getladder());
847         rankings_reply = strzone(getrankings());
848
849         // begin other init
850         ClientInit_Spawn();
851         RandomSeed_Spawn();
852         PingPLReport_Spawn();
853
854         CheatInit();
855
856         localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
857
858         // fill sv_curl_serverpackages from .serverpackage files
859         if(autocvar_sv_curl_serverpackages_auto)
860         {
861                 s = "";
862                 n = tokenize_console(cvar_string("sv_curl_serverpackages"));
863                 for(int i = 0; i < n; ++i)
864                         if(substring(argv(i), -18, -1) != "-serverpackage.txt")
865                         if(substring(argv(i), -14, -1) != ".serverpackage") // OLD legacy
866                                 s = strcat(s, " ", argv(i));
867                 fd = search_begin("*-serverpackage.txt", true, false);
868                 if(fd >= 0)
869                 {
870                         j = search_getsize(fd);
871                         for(int i = 0; i < j; ++i)
872                                 s = strcat(s, " ", search_getfilename(fd, i));
873                         search_end(fd);
874                 }
875                 fd = search_begin("*.serverpackage", true, false);
876                 if(fd >= 0)
877                 {
878                         j = search_getsize(fd);
879                         for(int i = 0; i < j; ++i)
880                                 s = strcat(s, " ", search_getfilename(fd, i));
881                         search_end(fd);
882                 }
883                 cvar_set("sv_curl_serverpackages", substring(s, 1, -1));
884         }
885
886         // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
887         modname = "Xonotic";
888         // physics/balance/config changes that count as mod
889         if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
890                 modname = cvar_string("g_mod_physics");
891         if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance"))
892                 modname = cvar_string("g_mod_balance");
893         if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
894                 modname = cvar_string("g_mod_config");
895         // extra mutators that deserve to count as mod
896         MUTATOR_CALLHOOK(SetModname);
897
898         // save it for later
899         modname = strzone(modname);
900
901         WinningConditionHelper(); // set worldstatus
902
903         world_initialized = 1;
904 }
905
906 void spawnfunc_light (void)
907 {
908         //makestatic (self); // Who the f___ did that?
909         remove(self);
910 }
911
912 string GetGametype()
913 {
914         return MapInfo_Type_ToString(MapInfo_LoadedGametype);
915 }
916
917 string GetMapname()
918 {
919         return mapname;
920 }
921
922 float Map_Count, Map_Current;
923 string Map_Current_Name;
924
925 // NOTE: this now expects the map list to be already tokenized and the count in Map_Count
926 float GetMaplistPosition()
927 {
928         float pos, idx;
929         string map;
930
931         map = GetMapname();
932         idx = autocvar_g_maplist_index;
933
934         if(idx >= 0)
935                 if(idx < Map_Count)
936                         if(map == argv(idx))
937                                 return idx;
938
939         for(pos = 0; pos < Map_Count; ++pos)
940                 if(map == argv(pos))
941                         return pos;
942
943         // resume normal maplist rotation if current map is not in g_maplist
944         return idx;
945 }
946
947 float MapHasRightSize(string map)
948 {
949         float fh;
950         if(currentbots || autocvar_bot_number || player_count < autocvar_minplayers)
951         if(autocvar_g_maplist_check_waypoints)
952         {
953                 dprint("checkwp "); dprint(map);
954                 if(!fexists(strcat("maps/", map, ".waypoints")))
955                 {
956                         dprint(": no waypoints\n");
957                         return false;
958                 }
959                 dprint(": has waypoints\n");
960         }
961
962         // open map size restriction file
963         dprint("opensize "); dprint(map);
964         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
965         if(fh >= 0)
966         {
967                 float mapmin, mapmax;
968                 dprint(": ok, ");
969                 mapmin = stof(fgets(fh));
970                 mapmax = stof(fgets(fh));
971                 fclose(fh);
972                 if(player_count < mapmin)
973                 {
974                         dprint("not enough\n");
975                         return false;
976                 }
977                 if(player_count > mapmax)
978                 {
979                         dprint("too many\n");
980                         return false;
981                 }
982                 dprint("right size\n");
983                 return true;
984         }
985         dprint(": not found\n");
986         return true;
987 }
988
989 string Map_Filename(float position)
990 {
991         return strcat("maps/", argv(position), ".bsp");
992 }
993
994 string strwords(string s, float w)
995 {
996         float endpos;
997         for(endpos = 0; w && endpos >= 0; --w)
998                 endpos = strstrofs(s, " ", endpos + 1);
999         if(endpos < 0)
1000                 return s;
1001         else
1002                 return substring(s, 0, endpos);
1003 }
1004
1005 float strhasword(string s, string w)
1006 {
1007         return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
1008 }
1009
1010 void Map_MarkAsRecent(string m)
1011 {
1012         cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", autocvar_g_maplist_mostrecent), max(0, autocvar_g_maplist_mostrecent_count)));
1013 }
1014
1015 float Map_IsRecent(string m)
1016 {
1017         return strhasword(autocvar_g_maplist_mostrecent, m);
1018 }
1019
1020 float Map_Check(float position, float pass)
1021 {
1022         string filename;
1023         string map_next;
1024         map_next = argv(position);
1025         if(pass <= 1)
1026         {
1027                 if(Map_IsRecent(map_next))
1028                         return 0;
1029         }
1030         filename = Map_Filename(position);
1031         if(MapInfo_CheckMap(map_next))
1032         {
1033                 if(pass == 2)
1034                         return 1;
1035                 if(MapHasRightSize(map_next))
1036                         return 1;
1037                 return 0;
1038         }
1039         else
1040                 dprint( "Couldn't select '", filename, "'..\n" );
1041
1042         return 0;
1043 }
1044
1045 void Map_Goto_SetStr(string nextmapname)
1046 {
1047         if(getmapname_stored != "")
1048                 strunzone(getmapname_stored);
1049         if(nextmapname == "")
1050                 getmapname_stored = "";
1051         else
1052                 getmapname_stored = strzone(nextmapname);
1053 }
1054
1055 void Map_Goto_SetFloat(float position)
1056 {
1057         cvar_set("g_maplist_index", ftos(position));
1058         Map_Goto_SetStr(argv(position));
1059 }
1060
1061 void Map_Goto(float reinit)
1062 {
1063         MapInfo_LoadMap(getmapname_stored, reinit);
1064 }
1065
1066 // return codes of map selectors:
1067 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
1068 //   -2 = permanent failure
1069 float() MaplistMethod_Iterate = // usual method
1070 {
1071         float pass, i;
1072
1073         dprint("Trying MaplistMethod_Iterate\n");
1074
1075         for(pass = 1; pass <= 2; ++pass)
1076         {
1077                 for(i = 1; i < Map_Count; ++i)
1078                 {
1079                         float mapindex;
1080                         mapindex = (i + Map_Current) % Map_Count;
1081                         if(Map_Check(mapindex, pass))
1082                                 return mapindex;
1083                 }
1084         }
1085         return -1;
1086 }
1087
1088 float() MaplistMethod_Repeat = // fallback method
1089 {
1090         dprint("Trying MaplistMethod_Repeat\n");
1091
1092         if(Map_Check(Map_Current, 2))
1093                 return Map_Current;
1094         return -2;
1095 }
1096
1097 float() MaplistMethod_Random = // random map selection
1098 {
1099         float i, imax;
1100
1101         dprint("Trying MaplistMethod_Random\n");
1102
1103         imax = 42;
1104
1105         for(i = 0; i <= imax; ++i)
1106         {
1107                 float mapindex;
1108                 mapindex = (Map_Current + floor(random() * (Map_Count - 1) + 1)) % Map_Count; // any OTHER map
1109                 if(Map_Check(mapindex, 1))
1110                         return mapindex;
1111         }
1112         return -1;
1113 }
1114
1115 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
1116 // the exponent sets a bias on the map selection:
1117 // the higher the exponent, the less likely "shortly repeated" same maps are
1118 {
1119         float i, j, imax, insertpos;
1120
1121         dprint("Trying MaplistMethod_Shuffle\n");
1122
1123         imax = 42;
1124
1125         for(i = 0; i <= imax; ++i)
1126         {
1127                 string newlist;
1128
1129                 // now reinsert this at another position
1130                 insertpos = pow(random(), 1 / exponent);       // ]0, 1]
1131                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
1132                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
1133                 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
1134
1135                 // insert the current map there
1136                 newlist = "";
1137                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
1138                         newlist = strcat(newlist, " ", argv(j));
1139                 newlist = strcat(newlist, " ", argv(0));       // now insert the just selected map
1140                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
1141                         newlist = strcat(newlist, " ", argv(j));
1142                 newlist = substring(newlist, 1, strlen(newlist) - 1);
1143                 cvar_set("g_maplist", newlist);
1144                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1145
1146                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
1147                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
1148                 if(Map_Check(Map_Current, 1))
1149                         return Map_Current;
1150         }
1151         return -1;
1152 }
1153
1154 void Maplist_Init()
1155 {
1156         Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1157         float i;
1158         for (i = 0; i < Map_Count; ++i)
1159                 if (Map_Check(i, 2))
1160                         break;
1161         if (i == Map_Count)
1162         {
1163                 bprint( "Maplist contains no usable maps!  Resetting it to default map list.\n" );
1164                 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags() | MAPINFO_FLAG_NOAUTOMAPLIST));
1165                 if(autocvar_g_maplist_shuffle)
1166                         ShuffleMaplist();
1167                 localcmd("\nmenu_cmd sync\n");
1168                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1169         }
1170         if(Map_Count == 0)
1171                 error("empty maplist, cannot select a new map");
1172         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
1173
1174         if(Map_Current_Name)
1175                 strunzone(Map_Current_Name);
1176         Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
1177         // this may or may not be correct, but who cares, in the worst case a map
1178         // isn't chosen in the first pass that should have been
1179 }
1180
1181 string GetNextMap()
1182 {
1183         float nextMap;
1184
1185         Maplist_Init();
1186         nextMap = -1;
1187
1188         if(nextMap == -1)
1189                 if(autocvar_g_maplist_shuffle > 0)
1190                         nextMap = MaplistMethod_Shuffle(autocvar_g_maplist_shuffle + 1);
1191
1192         if(nextMap == -1)
1193                 if(autocvar_g_maplist_selectrandom)
1194                         nextMap = MaplistMethod_Random();
1195
1196         if(nextMap == -1)
1197                 nextMap = MaplistMethod_Iterate();
1198
1199         if(nextMap == -1)
1200                 nextMap = MaplistMethod_Repeat();
1201
1202         if(nextMap >= 0)
1203         {
1204                 Map_Goto_SetFloat(nextMap);
1205                 return getmapname_stored;
1206         }
1207
1208         return "";
1209 }
1210
1211 float DoNextMapOverride(float reinit)
1212 {
1213         if(autocvar_g_campaign)
1214         {
1215                 CampaignPostIntermission();
1216                 alreadychangedlevel = true;
1217                 return true;
1218         }
1219         if(autocvar_quit_when_empty)
1220         {
1221                 if(player_count <= currentbots)
1222                 {
1223                         localcmd("quit\n");
1224                         alreadychangedlevel = true;
1225                         return true;
1226                 }
1227         }
1228         if(autocvar_quit_and_redirect != "")
1229         {
1230                 redirection_target = strzone(autocvar_quit_and_redirect);
1231                 alreadychangedlevel = true;
1232                 return true;
1233         }
1234         if (!reinit && autocvar_samelevel) // if samelevel is set, stay on same level
1235         {
1236                 localcmd("restart\n");
1237                 alreadychangedlevel = true;
1238                 return true;
1239         }
1240         if(autocvar_nextmap != "")
1241         {
1242                 string m;
1243                 m = GameTypeVote_MapInfo_FixName(autocvar_nextmap);
1244                 cvar_set("nextmap",m);
1245
1246                 if(!m || gametypevote)
1247                         return false;
1248                 if(autocvar_sv_vote_gametype)
1249                 {
1250                         Map_Goto_SetStr(m);
1251                         return false;
1252                 }
1253
1254                 if(MapInfo_CheckMap(m))
1255                 {
1256                         Map_Goto_SetStr(m);
1257                         Map_Goto(reinit);
1258                         alreadychangedlevel = true;
1259                         return true;
1260                 }
1261         }
1262         if(!reinit && autocvar_lastlevel)
1263         {
1264                 cvar_settemp_restore();
1265                 localcmd("set lastlevel 0\ntogglemenu 1\n");
1266                 alreadychangedlevel = true;
1267                 return true;
1268         }
1269         return false;
1270 }
1271
1272 void GotoNextMap(float reinit)
1273 {
1274         //string nextmap;
1275         //float n, nummaps;
1276         //string s;
1277         if (alreadychangedlevel)
1278                 return;
1279         alreadychangedlevel = true;
1280
1281         string nextMap;
1282
1283         nextMap = GetNextMap();
1284         if(nextMap == "")
1285                 error("Everything is broken - cannot find a next map. Please report this to the developers.");
1286         Map_Goto(reinit);
1287 }
1288
1289
1290 /*
1291 ============
1292 IntermissionThink
1293
1294 When the player presses attack or jump, change to the next level
1295 ============
1296 */
1297 .float autoscreenshot;
1298 void IntermissionThink()
1299 {
1300         FixIntermissionClient(self);
1301
1302         float server_screenshot = (autocvar_sv_autoscreenshot && self.cvar_cl_autoscreenshot);
1303         float client_screenshot = (self.cvar_cl_autoscreenshot == 2);
1304
1305         if( (server_screenshot || client_screenshot)
1306                 && ((self.autoscreenshot > 0) && (time > self.autoscreenshot)) )
1307         {
1308                 self.autoscreenshot = -1;
1309                 if(IS_REAL_CLIENT(self)) { stuffcmd(self, sprintf("\nscreenshot screenshots/autoscreenshot/%s-%s.jpg; echo \"^5A screenshot has been taken at request of the server.\"\n", GetMapname(), strftime(false, "%s"))); }
1310                 return;
1311         }
1312
1313         if (time < intermission_exittime)
1314                 return;
1315
1316         if(!mapvote_initialized)
1317                 if (time < intermission_exittime + 10 && !(self.BUTTON_ATCK || self.BUTTON_JUMP || self.BUTTON_ATCK2 || self.BUTTON_HOOK || self.BUTTON_USE))
1318                         return;
1319
1320         MapVote_Start();
1321 }
1322
1323 /*
1324 ============
1325 FindIntermission
1326
1327 Returns the entity to view from
1328 ============
1329 */
1330 /*
1331 entity FindIntermission()
1332 {
1333         local   entity spot;
1334         local   float cyc;
1335
1336 // look for info_intermission first
1337         spot = find (world, classname, "info_intermission");
1338         if (spot)
1339         {       // pick a random one
1340                 cyc = random() * 4;
1341                 while (cyc > 1)
1342                 {
1343                         spot = find (spot, classname, "info_intermission");
1344                         if (!spot)
1345                                 spot = find (spot, classname, "info_intermission");
1346                         cyc = cyc - 1;
1347                 }
1348                 return spot;
1349         }
1350
1351 // then look for the start position
1352         spot = find (world, classname, "info_player_start");
1353         if (spot)
1354                 return spot;
1355
1356 // testinfo_player_start is only found in regioned levels
1357         spot = find (world, classname, "testplayerstart");
1358         if (spot)
1359                 return spot;
1360
1361 // then look for the start position
1362         spot = find (world, classname, "info_player_deathmatch");
1363         if (spot)
1364                 return spot;
1365
1366         //objerror ("FindIntermission: no spot");
1367         return world;
1368 }
1369 */
1370
1371 /*
1372 ===============================================================================
1373
1374 RULES
1375
1376 ===============================================================================
1377 */
1378
1379 void DumpStats(float final)
1380 {
1381         float file;
1382         string s;
1383         float to_console;
1384         float to_eventlog;
1385         float to_file;
1386         float i;
1387
1388         to_console = autocvar_sv_logscores_console;
1389         to_eventlog = autocvar_sv_eventlog;
1390         to_file = autocvar_sv_logscores_file;
1391
1392         if(!final)
1393         {
1394                 to_console = true; // always print printstats replies
1395                 to_eventlog = false; // but never print them to the event log
1396         }
1397
1398         if(to_eventlog)
1399                 if(autocvar_sv_eventlog_console)
1400                         to_console = false; // otherwise we get the output twice
1401
1402         if(final)
1403                 s = ":scores:";
1404         else
1405                 s = ":status:";
1406         s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1407
1408         if(to_console)
1409                 print(s, "\n");
1410         if(to_eventlog)
1411                 GameLogEcho(s);
1412
1413         file = -1;
1414         if(to_file)
1415         {
1416                 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1417                 if(file == -1)
1418                         to_file = false;
1419                 else
1420                         fputs(file, strcat(s, "\n"));
1421         }
1422
1423         s = strcat(":labels:player:", GetPlayerScoreString(world, 0));
1424         if(to_console)
1425                 print(s, "\n");
1426         if(to_eventlog)
1427                 GameLogEcho(s);
1428         if(to_file)
1429                 fputs(file, strcat(s, "\n"));
1430
1431         FOR_EACH_CLIENT(other)
1432         {
1433                 if ((IS_REAL_CLIENT(other)) || (IS_BOT_CLIENT(other) && autocvar_sv_logscores_bots))
1434                 {
1435                         s = strcat(":player:see-labels:", GetPlayerScoreString(other, 0), ":");
1436                         s = strcat(s, ftos(rint(time - other.jointime)), ":");
1437                         if(IS_PLAYER(other) || other.caplayer == 1 || g_lms)
1438                                 s = strcat(s, ftos(other.team), ":");
1439                         else
1440                                 s = strcat(s, "spectator:");
1441
1442                         if(to_console)
1443                                 print(s, other.netname, "\n");
1444                         if(to_eventlog)
1445                                 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname));
1446                         if(to_file)
1447                                 fputs(file, strcat(s, other.netname, "\n"));
1448                 }
1449         }
1450
1451         if(teamplay)
1452         {
1453                 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1454                 if(to_console)
1455                         print(s, "\n");
1456                 if(to_eventlog)
1457                         GameLogEcho(s);
1458                 if(to_file)
1459                         fputs(file, strcat(s, "\n"));
1460
1461                 for(i = 1; i < 16; ++i)
1462                 {
1463                         s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1464                         s = strcat(s, ":", ftos(i));
1465                         if(to_console)
1466                                 print(s, "\n");
1467                         if(to_eventlog)
1468                                 GameLogEcho(s);
1469                         if(to_file)
1470                                 fputs(file, strcat(s, "\n"));
1471                 }
1472         }
1473
1474         if(to_console)
1475                 print(":end\n");
1476         if(to_eventlog)
1477                 GameLogEcho(":end");
1478         if(to_file)
1479         {
1480                 fputs(file, ":end\n");
1481                 fclose(file);
1482         }
1483 }
1484
1485 void FixIntermissionClient(entity e)
1486 {
1487         string s;
1488         if(!e.autoscreenshot) // initial call
1489         {
1490                 e.autoscreenshot = time + 0.8;  // used for autoscreenshot
1491                 e.health = -2342;
1492                 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1493                 e.solid = SOLID_NOT;
1494                 e.movetype = MOVETYPE_NONE;
1495                 e.takedamage = DAMAGE_NO;
1496                 if(e.weaponentity)
1497                 {
1498                         e.weaponentity.effects = EF_NODRAW;
1499                         if (e.weaponentity.weaponentity)
1500                                 e.weaponentity.weaponentity.effects = EF_NODRAW;
1501                 }
1502                 if(IS_REAL_CLIENT(e))
1503                 {
1504                         stuffcmd(e, "\nscr_printspeed 1000000\n");
1505                         s = autocvar_sv_intermission_cdtrack;
1506                         if(s != "")
1507                                 stuffcmd(e, strcat("\ncd loop ", s, "\n"));
1508                         msg_entity = e;
1509                         WriteByte(MSG_ONE, SVC_INTERMISSION);
1510                 }
1511         }
1512 }
1513
1514 /*
1515 go to the next level for deathmatch
1516 only called if a time or frag limit has expired
1517 */
1518 void NextLevel()
1519 {
1520         gameover = true;
1521
1522         intermission_running = 1;
1523
1524 // enforce a wait time before allowing changelevel
1525         if(player_count > 0)
1526                 intermission_exittime = time + autocvar_sv_mapchange_delay;
1527         else
1528                 intermission_exittime = -1;
1529
1530         /*
1531         WriteByte (MSG_ALL, SVC_CDTRACK);
1532         WriteByte (MSG_ALL, 3);
1533         WriteByte (MSG_ALL, 3);
1534         // done in FixIntermission
1535         */
1536
1537         //pos = FindIntermission ();
1538
1539         VoteReset();
1540
1541         DumpStats(true);
1542
1543         // send statistics
1544         PlayerStats_GameReport(true);
1545         WeaponStats_Shutdown();
1546
1547         Kill_Notification(NOTIF_ALL, world, MSG_CENTER, 0); // kill all centerprints now
1548
1549         if(autocvar_sv_eventlog)
1550                 GameLogEcho(":gameover");
1551
1552         GameLogClose();
1553
1554         FOR_EACH_PLAYER(other) {
1555                 FixIntermissionClient(other);
1556                 if(other.winning)
1557                         bprint(other.netname, " ^7wins.\n");
1558         }
1559
1560         if(autocvar_g_campaign)
1561                 CampaignPreIntermission();
1562
1563         MUTATOR_CALLHOOK(MatchEnd);
1564
1565         localcmd("\nsv_hook_gameend\n");
1566 }
1567
1568 /*
1569 ============
1570 CheckRules_Player
1571
1572 Exit deathmatch games upon conditions
1573 ============
1574 */
1575 void CheckRules_Player()
1576 {
1577         if (gameover)   // someone else quit the game already
1578                 return;
1579
1580         if(self.deadflag == DEAD_NO)
1581                 self.play_time += frametime;
1582
1583         // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1584         //   (div0: and that in CheckRules_World please)
1585 }
1586
1587
1588 float InitiateSuddenDeath()
1589 {
1590         // Check first whether normal overtimes could be added before initiating suddendeath mode
1591         // - for this timelimit_overtime needs to be >0 of course
1592         // - also check the winning condition calculated in the previous frame and only add normal overtime
1593         //   again, if at the point at which timelimit would be extended again, still no winner was found
1594         if (!autocvar_g_campaign && (checkrules_overtimesadded >= 0) && (checkrules_overtimesadded < autocvar_timelimit_overtimes || autocvar_timelimit_overtimes < 0) && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1595         {
1596                 return 1; // need to call InitiateOvertime later
1597         }
1598         else
1599         {
1600                 if(!checkrules_suddendeathend)
1601                 {
1602                         if(autocvar_g_campaign)
1603                                 checkrules_suddendeathend = time; // no suddendeath in campaign
1604                         else
1605                                 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1606                         if(g_race && !g_race_qualifying)
1607                                 race_StartCompleting();
1608                 }
1609                 return 0;
1610         }
1611 }
1612
1613 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1614 {
1615         ++checkrules_overtimesadded;
1616         //add one more overtime by simply extending the timelimit
1617         float tl;
1618         tl = autocvar_timelimit;
1619         tl += autocvar_timelimit_overtime;
1620         cvar_set("timelimit", ftos(tl));
1621
1622         Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime * 60);
1623 }
1624
1625 float GetWinningCode(float fraglimitreached, float equality)
1626 {
1627         if(autocvar_g_campaign == 1)
1628                 if(fraglimitreached)
1629                         return WINNING_YES;
1630                 else
1631                         return WINNING_NO;
1632
1633         else
1634                 if(equality)
1635                         if(fraglimitreached)
1636                                 return WINNING_STARTSUDDENDEATHOVERTIME;
1637                         else
1638                                 return WINNING_NEVER;
1639                 else
1640                         if(fraglimitreached)
1641                                 return WINNING_YES;
1642                         else
1643                                 return WINNING_NO;
1644 }
1645
1646 // set the .winning flag for exactly those players with a given field value
1647 void SetWinners(.float field, float value)
1648 {
1649         entity head;
1650         FOR_EACH_PLAYER(head)
1651                 head.winning = (head.(field) == value);
1652 }
1653
1654 // set the .winning flag for those players with a given field value
1655 void AddWinners(.float field, float value)
1656 {
1657         entity head;
1658         FOR_EACH_PLAYER(head)
1659                 if (head.(field) == value)
1660                         head.winning = 1;
1661 }
1662
1663 // clear the .winning flags
1664 void ClearWinners(void)
1665 {
1666         entity head;
1667         FOR_EACH_PLAYER(head)
1668                 head.winning = 0;
1669 }
1670
1671 // Onslaught winning condition:
1672 // game terminates if only one team has a working generator (or none)
1673 float WinningCondition_Onslaught()
1674 {
1675         entity head;
1676         float t1, t2, t3, t4;
1677
1678         WinningConditionHelper(); // set worldstatus
1679
1680         if(warmup_stage)
1681                 return WINNING_NO;
1682
1683         // first check if the game has ended
1684         t1 = t2 = t3 = t4 = 0;
1685         head = find(world, classname, "onslaught_generator");
1686         while (head)
1687         {
1688                 if (head.health > 0)
1689                 {
1690                         if (head.team == NUM_TEAM_1) t1 = 1;
1691                         if (head.team == NUM_TEAM_2) t2 = 1;
1692                         if (head.team == NUM_TEAM_3) t3 = 1;
1693                         if (head.team == NUM_TEAM_4) t4 = 1;
1694                 }
1695                 head = find(head, classname, "onslaught_generator");
1696         }
1697         if (t1 + t2 + t3 + t4 < 2)
1698         {
1699                 // game over, only one team remains (or none)
1700                 ClearWinners();
1701                 if (t1) SetWinners(team, NUM_TEAM_1);
1702                 if (t2) SetWinners(team, NUM_TEAM_2);
1703                 if (t3) SetWinners(team, NUM_TEAM_3);
1704                 if (t4) SetWinners(team, NUM_TEAM_4);
1705                 dprint("Have a winner, ending game.\n");
1706                 return WINNING_YES;
1707         }
1708
1709         // Two or more teams remain
1710         return WINNING_NO;
1711 }
1712
1713 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1714 // they win. Otherwise the defending team wins once the timelimit passes.
1715 void assault_new_round();
1716 float WinningCondition_Assault()
1717 {
1718         float status;
1719
1720         WinningConditionHelper(); // set worldstatus
1721
1722         status = WINNING_NO;
1723         // as the timelimit has not yet passed just assume the defending team will win
1724         if(assault_attacker_team == NUM_TEAM_1)
1725         {
1726                 SetWinners(team, NUM_TEAM_2);
1727         }
1728         else
1729         {
1730                 SetWinners(team, NUM_TEAM_1);
1731         }
1732
1733         entity ent;
1734         ent = find(world, classname, "target_assault_roundend");
1735         if(ent)
1736         {
1737                 if(ent.winning) // round end has been triggered by attacking team
1738                 {
1739                         bprint("ASSAULT: round completed...\n");
1740                         SetWinners(team, assault_attacker_team);
1741
1742                         TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 666 - TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 0));
1743
1744                         if(ent.cnt == 1 || autocvar_g_campaign) // this was the second round
1745                         {
1746                                 status = WINNING_YES;
1747                         }
1748                         else
1749                         {
1750                                 entity oldself;
1751                                 oldself = self;
1752                                 self = ent;
1753                                 assault_new_round();
1754                                 self = oldself;
1755                         }
1756                 }
1757         }
1758
1759         return status;
1760 }
1761
1762 // LMS winning condition: game terminates if and only if there's at most one
1763 // one player who's living lives. Top two scores being equal cancels the time
1764 // limit.
1765 float WinningCondition_LMS()
1766 {
1767         entity head, head2;
1768         float have_player;
1769         float have_players;
1770         float l;
1771
1772         have_player = false;
1773         have_players = false;
1774         l = LMS_NewPlayerLives();
1775
1776         head = find(world, classname, "player");
1777         if(head)
1778                 have_player = true;
1779         head2 = find(head, classname, "player");
1780         if(head2)
1781                 have_players = true;
1782
1783         if(have_player)
1784         {
1785                 // we have at least one player
1786                 if(have_players)
1787                 {
1788                         // two or more active players - continue with the game
1789                 }
1790                 else
1791                 {
1792                         // exactly one player?
1793
1794                         ClearWinners();
1795                         SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1796
1797                         if(l)
1798                         {
1799                                 // game still running (that is, nobody got removed from the game by a frag yet)? then continue
1800                                 return WINNING_NO;
1801                         }
1802                         else
1803                         {
1804                                 // a winner!
1805                                 // and assign him his first place
1806                                 PlayerScore_Add(head, SP_LMS_RANK, 1);
1807                                 return WINNING_YES;
1808                         }
1809                 }
1810         }
1811         else
1812         {
1813                 // nobody is playing at all...
1814                 if(l)
1815                 {
1816                         // wait for players...
1817                 }
1818                 else
1819                 {
1820                         // SNAFU (maybe a draw game?)
1821                         ClearWinners();
1822                         dprint("No players, ending game.\n");
1823                         return WINNING_YES;
1824                 }
1825         }
1826
1827         // When we get here, we have at least two players who are actually LIVING,
1828         // now check if the top two players have equal score.
1829         WinningConditionHelper();
1830
1831         ClearWinners();
1832         if(WinningConditionHelper_winner)
1833                 WinningConditionHelper_winner.winning = true;
1834         if(WinningConditionHelper_topscore == WinningConditionHelper_secondscore)
1835                 return WINNING_NEVER;
1836
1837         // Top two have different scores? Way to go for our beloved TIMELIMIT!
1838         return WINNING_NO;
1839 }
1840
1841 void ShuffleMaplist()
1842 {
1843         cvar_set("g_maplist", shufflewords(autocvar_g_maplist));
1844 }
1845
1846 float leaderfrags;
1847 float WinningCondition_Scores(float limit, float leadlimit)
1848 {
1849         float limitreached;
1850
1851         // TODO make everything use THIS winning condition (except LMS)
1852         WinningConditionHelper();
1853
1854         if(teamplay)
1855         {
1856                 team1_score = TeamScore_GetCompareValue(NUM_TEAM_1);
1857                 team2_score = TeamScore_GetCompareValue(NUM_TEAM_2);
1858                 team3_score = TeamScore_GetCompareValue(NUM_TEAM_3);
1859                 team4_score = TeamScore_GetCompareValue(NUM_TEAM_4);
1860         }
1861
1862         ClearWinners();
1863         if(WinningConditionHelper_winner)
1864                 WinningConditionHelper_winner.winning = 1;
1865         if(WinningConditionHelper_winnerteam >= 0)
1866                 SetWinners(team, WinningConditionHelper_winnerteam);
1867
1868         if(WinningConditionHelper_lowerisbetter)
1869         {
1870                 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1871                 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1872                 limit = -limit;
1873         }
1874
1875         if(WinningConditionHelper_zeroisworst)
1876                 leadlimit = 0; // not supported in this mode
1877
1878         if(g_dm || g_tdm || g_ca || g_freezetag || (g_race && !g_race_qualifying) || g_nexball)
1879         // these modes always score in increments of 1, thus this makes sense
1880         {
1881                 if(leaderfrags != WinningConditionHelper_topscore)
1882                 {
1883                         leaderfrags = WinningConditionHelper_topscore;
1884
1885                         if (limit)
1886                         if (leaderfrags == limit - 1)
1887                                 Send_Notification(NOTIF_ALL, world, MSG_ANNCE, ANNCE_REMAINING_FRAG_1);
1888                         else if (leaderfrags == limit - 2)
1889                                 Send_Notification(NOTIF_ALL, world, MSG_ANNCE, ANNCE_REMAINING_FRAG_2);
1890                         else if (leaderfrags == limit - 3)
1891                                 Send_Notification(NOTIF_ALL, world, MSG_ANNCE, ANNCE_REMAINING_FRAG_3);
1892                 }
1893         }
1894
1895         limitreached = false;
1896         if(limit)
1897                 if(WinningConditionHelper_topscore >= limit)
1898                         limitreached = true;
1899         if(leadlimit)
1900         {
1901                 float leadlimitreached;
1902                 leadlimitreached = (WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1903                 if(autocvar_leadlimit_and_fraglimit)
1904                         limitreached = (limitreached && leadlimitreached);
1905                 else
1906                         limitreached = (limitreached || leadlimitreached);
1907         }
1908
1909         if(limit)
1910                 game_completion_ratio = max(game_completion_ratio, bound(0, WinningConditionHelper_topscore / limit, 1));
1911
1912         return GetWinningCode(
1913                 WinningConditionHelper_topscore && limitreached,
1914                 WinningConditionHelper_equality
1915         );
1916 }
1917
1918 float WinningCondition_Race(float fraglimit)
1919 {
1920         float wc;
1921         entity p;
1922         float n, c;
1923
1924         n = 0;
1925         c = 0;
1926         FOR_EACH_PLAYER(p)
1927         {
1928                 ++n;
1929                 if(p.race_completed)
1930                         ++c;
1931         }
1932         if(n && (n == c))
1933                 return WINNING_YES;
1934         wc = WinningCondition_Scores(fraglimit, 0);
1935
1936         // ALWAYS initiate overtime, unless EVERYONE has finished the race!
1937         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1938         // do NOT support equality when the laps are all raced!
1939                 return WINNING_STARTSUDDENDEATHOVERTIME;
1940         else
1941                 return WINNING_NEVER;
1942 }
1943
1944 float WinningCondition_QualifyingThenRace(float limit)
1945 {
1946         float wc;
1947         wc = WinningCondition_Scores(limit, 0);
1948
1949         // NEVER initiate overtime
1950         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1951         {
1952                 return WINNING_YES;
1953         }
1954
1955         return wc;
1956 }
1957
1958 float WinningCondition_RanOutOfSpawns()
1959 {
1960         entity head;
1961
1962         if(have_team_spawns <= 0)
1963                 return WINNING_NO;
1964
1965         if(!autocvar_g_spawn_useallspawns)
1966                 return WINNING_NO;
1967
1968         if(!some_spawn_has_been_used)
1969                 return WINNING_NO;
1970
1971         team1_score = team2_score = team3_score = team4_score = 0;
1972
1973         FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
1974         {
1975                 if(head.team == NUM_TEAM_1)
1976                         team1_score = 1;
1977                 else if(head.team == NUM_TEAM_2)
1978                         team2_score = 1;
1979                 else if(head.team == NUM_TEAM_3)
1980                         team3_score = 1;
1981                 else if(head.team == NUM_TEAM_4)
1982                         team4_score = 1;
1983         }
1984
1985         for(head = world; (head = find(head, classname, "info_player_deathmatch")) != world; )
1986         {
1987                 if(head.team == NUM_TEAM_1)
1988                         team1_score = 1;
1989                 else if(head.team == NUM_TEAM_2)
1990                         team2_score = 1;
1991                 else if(head.team == NUM_TEAM_3)
1992                         team3_score = 1;
1993                 else if(head.team == NUM_TEAM_4)
1994                         team4_score = 1;
1995         }
1996
1997         ClearWinners();
1998         if(team1_score + team2_score + team3_score + team4_score == 0)
1999         {
2000                 checkrules_equality = true;
2001                 return WINNING_YES;
2002         }
2003         else if(team1_score + team2_score + team3_score + team4_score == 1)
2004         {
2005                 float t, i;
2006                 if(team1_score)
2007                         t = NUM_TEAM_1;
2008                 else if(team2_score)
2009                         t = NUM_TEAM_2;
2010                 else if(team3_score)
2011                         t = NUM_TEAM_3;
2012                 else // if(team4_score)
2013                         t = NUM_TEAM_4;
2014                 CheckAllowedTeams(world);
2015                 for(i = 0; i < MAX_TEAMSCORE; ++i)
2016                 {
2017                         if(t != NUM_TEAM_1) if(c1 >= 0) TeamScore_AddToTeam(NUM_TEAM_1, i, -1000);
2018                         if(t != NUM_TEAM_2) if(c2 >= 0) TeamScore_AddToTeam(NUM_TEAM_2, i, -1000);
2019                         if(t != NUM_TEAM_3) if(c3 >= 0) TeamScore_AddToTeam(NUM_TEAM_3, i, -1000);
2020                         if(t != NUM_TEAM_4) if(c4 >= 0) TeamScore_AddToTeam(NUM_TEAM_4, i, -1000);
2021                 }
2022
2023                 AddWinners(team, t);
2024                 return WINNING_YES;
2025         }
2026         else
2027                 return WINNING_NO;
2028 }
2029
2030 /*
2031 ============
2032 CheckRules_World
2033
2034 Exit deathmatch games upon conditions
2035 ============
2036 */
2037 void CheckRules_World()
2038 {
2039         float timelimit;
2040         float fraglimit;
2041         float leadlimit;
2042
2043         VoteThink();
2044         MapVote_Think();
2045
2046         SetDefaultAlpha();
2047
2048         if (gameover)   // someone else quit the game already
2049         {
2050                 if(player_count == 0) // Nobody there? Then let's go to the next map
2051                         MapVote_Start();
2052                         // this will actually check the player count in the next frame
2053                         // again, but this shouldn't hurt
2054                 return;
2055         }
2056
2057         timelimit = autocvar_timelimit * 60;
2058         fraglimit = autocvar_fraglimit;
2059         leadlimit = autocvar_leadlimit;
2060
2061         if(warmup_stage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
2062         {
2063                 if(timelimit > 0)
2064                         timelimit = 0; // timelimit is not made for warmup
2065                 if(fraglimit > 0)
2066                         fraglimit = 0; // no fraglimit for now
2067                 leadlimit = 0; // no leadlimit for now
2068         }
2069
2070         if(timelimit > 0)
2071         {
2072                 timelimit += game_starttime;
2073         }
2074         else if (timelimit < 0)
2075         {
2076                 // endmatch
2077                 NextLevel();
2078                 return;
2079         }
2080
2081         if(g_onslaught)
2082                 timelimit = 0; // ONS has its own overtime rule
2083
2084         float wantovertime;
2085         wantovertime = 0;
2086
2087         if(timelimit > game_starttime)
2088                 game_completion_ratio = (time - game_starttime) / (timelimit - game_starttime);
2089         else
2090                 game_completion_ratio = 0;
2091
2092         if(checkrules_suddendeathend)
2093         {
2094                 if(!checkrules_suddendeathwarning)
2095                 {
2096                         checkrules_suddendeathwarning = true;
2097                         if(g_race && !g_race_qualifying)
2098                                 Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_RACE_FINISHLAP);
2099                         else
2100                                 Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_OVERTIME_FRAG);
2101                 }
2102         }
2103         else
2104         {
2105                 if (timelimit && time >= timelimit)
2106                 {
2107                         if(g_race && (g_race_qualifying == 2) && timelimit > 0)
2108                         {
2109                                 float totalplayers;
2110                                 float playerswithlaps;
2111                                 float readyplayers;
2112                                 entity head;
2113                                 totalplayers = playerswithlaps = readyplayers = 0;
2114                                 FOR_EACH_PLAYER(head)
2115                                 {
2116                                         ++totalplayers;
2117                                         if(PlayerScore_Add(head, SP_RACE_FASTEST, 0))
2118                                                 ++playerswithlaps;
2119                                         if(head.ready)
2120                                                 ++readyplayers;
2121                                 }
2122
2123                                 // at least 2 of the players have completed a lap: start the RACE
2124                                 // otherwise, the players should end the qualifying on their own
2125                                 if(readyplayers || playerswithlaps >= 2)
2126                                 {
2127                                         checkrules_suddendeathend = 0;
2128                                         ReadyRestart(); // go to race
2129                                         return;
2130                                 }
2131                                 else
2132                                         wantovertime |= InitiateSuddenDeath();
2133                         }
2134                         else
2135                                 wantovertime |= InitiateSuddenDeath();
2136                 }
2137         }
2138
2139         if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
2140         {
2141                 NextLevel();
2142                 return;
2143         }
2144
2145         float checkrules_status;
2146         checkrules_status = WinningCondition_RanOutOfSpawns();
2147         if(checkrules_status == WINNING_YES)
2148         {
2149                 bprint("Hey! Someone ran out of spawns!\n");
2150         }
2151         else if(g_race && !g_race_qualifying && timelimit >= 0)
2152         {
2153                 checkrules_status = WinningCondition_Race(fraglimit);
2154                 //print("WC_RACE yields ", ftos(checkrules_status), "\n");
2155         }
2156         else if(g_race && g_race_qualifying == 2 && timelimit >= 0)
2157         {
2158                 checkrules_status = WinningCondition_QualifyingThenRace(fraglimit);
2159                 //print("WC_QUALIFYING_THEN_RACE yields ", ftos(checkrules_status), "\n");
2160         }
2161         else if(g_assault)
2162         {
2163                 checkrules_status = WinningCondition_Assault(); // TODO remove this?
2164         }
2165         else if(g_lms)
2166         {
2167                 checkrules_status = WinningCondition_LMS();
2168         }
2169         else if (g_onslaught)
2170         {
2171                 checkrules_status = WinningCondition_Onslaught(); // TODO remove this?
2172         }
2173         else
2174         {
2175                 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
2176                 //print("WC_SCORES yields ", ftos(checkrules_status), "\n");
2177         }
2178
2179         if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
2180         {
2181                 checkrules_status = WINNING_NEVER;
2182                 checkrules_overtimesadded = -1;
2183                 wantovertime |= InitiateSuddenDeath();
2184         }
2185
2186         if(checkrules_status == WINNING_NEVER)
2187                 // equality cases! Nobody wins if the overtime ends in a draw.
2188                 ClearWinners();
2189
2190         if(wantovertime)
2191         {
2192                 if(checkrules_status == WINNING_NEVER)
2193                         InitiateOvertime();
2194                 else
2195                         checkrules_status = WINNING_YES;
2196         }
2197
2198         if(checkrules_suddendeathend)
2199                 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
2200                         checkrules_status = WINNING_YES;
2201
2202         if(checkrules_status == WINNING_YES)
2203         {
2204                 //print("WINNING\n");
2205                 NextLevel();
2206         }
2207 }
2208
2209 string GotoMap(string m)
2210 {
2211         m = GameTypeVote_MapInfo_FixName(m);
2212         if (!m)
2213                 return "The map you suggested is not available on this server.";
2214         if (!autocvar_sv_vote_gametype)
2215         if(!MapInfo_CheckMap(m))
2216                 return "The map you suggested does not support the current game mode.";
2217         cvar_set("nextmap", m);
2218         cvar_set("timelimit", "-1");
2219         if(mapvote_initialized || alreadychangedlevel)
2220         {
2221                 if(DoNextMapOverride(0))
2222                         return "Map switch initiated.";
2223                 else
2224                         return "Hm... no. For some reason I like THIS map more.";
2225         }
2226         else
2227                 return "Map switch will happen after scoreboard.";
2228 }
2229
2230
2231 void EndFrame()
2232 {
2233         anticheat_endframe();
2234
2235         float altime;
2236         FOR_EACH_REALCLIENT(self)
2237         {
2238                 entity e = IS_SPEC(self) ? self.enemy : self;
2239                 if(e.typehitsound)
2240                         self.typehit_time = time;
2241                 else if(e.damage_dealt)
2242                 {
2243                         self.hit_time = time;
2244                         self.damage_dealt_total += ceil(e.damage_dealt);
2245                 }
2246         }
2247         altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2248         // add 1 frametime because after this, engine SV_Physics
2249         // increases time by a frametime and then networks the frame
2250         // add another frametime because client shows everything with
2251         // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2252         // needed!
2253         FOR_EACH_CLIENT(self)
2254         {
2255                 self.typehitsound = false;
2256                 self.damage_dealt = 0;
2257                 antilag_record(self, altime);
2258         }
2259         FOR_EACH_MONSTER(self)
2260                 antilag_record(self, altime);
2261 }
2262
2263
2264 /*
2265  * RedirectionThink:
2266  * returns true if redirecting
2267  */
2268 float redirection_timeout;
2269 float redirection_nextthink;
2270 float RedirectionThink()
2271 {
2272         float clients_found;
2273
2274         if(redirection_target == "")
2275                 return false;
2276
2277         if(!redirection_timeout)
2278         {
2279                 cvar_set("sv_public", "-2");
2280                 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2281                 if(redirection_target == "self")
2282                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2283                 else
2284                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2285         }
2286
2287         if(time < redirection_nextthink)
2288                 return true;
2289
2290         redirection_nextthink = time + 1;
2291
2292         clients_found = 0;
2293         FOR_EACH_REALCLIENT(self)
2294         {
2295                 // TODO add timer
2296                 print("Redirecting: sending connect command to ", self.netname, "\n");
2297                 if(redirection_target == "self")
2298                         stuffcmd(self, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2299                 else
2300                         stuffcmd(self, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2301                 ++clients_found;
2302         }
2303
2304         print("Redirecting: ", ftos(clients_found), " clients left.\n");
2305
2306         if(time > redirection_timeout || clients_found == 0)
2307                 localcmd("\nwait; wait; wait; quit\n");
2308
2309         return true;
2310 }
2311
2312 void TargetMusic_RestoreGame();
2313 void RestoreGame()
2314 {
2315         // Loaded from a save game
2316         // some things then break, so let's work around them...
2317
2318         // Progs DB (capture records)
2319         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2320
2321         // Mapinfo
2322         MapInfo_Shutdown();
2323         MapInfo_Enumerate();
2324         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2325         WeaponStats_Init();
2326
2327         TargetMusic_RestoreGame();
2328 }
2329
2330 void Shutdown()
2331 {
2332         gameover = 2;
2333
2334         if(world_initialized > 0)
2335         {
2336                 world_initialized = 0;
2337                 print("Saving persistent data...\n");
2338                 Ban_SaveBans();
2339
2340                 // playerstats with unfinished match
2341                 PlayerStats_GameReport(false);
2342
2343                 if(!cheatcount_total)
2344                 {
2345                         if(autocvar_sv_db_saveasdump)
2346                                 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2347                         else
2348                                 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2349                 }
2350                 if(autocvar_developer)
2351                 {
2352                         if(autocvar_sv_db_saveasdump)
2353                                 db_dump(TemporaryDB, "server-temp.db");
2354                         else
2355                                 db_save(TemporaryDB, "server-temp.db");
2356                 }
2357                 CheatShutdown(); // must be after cheatcount check
2358                 db_close(ServerProgsDB);
2359                 db_close(TemporaryDB);
2360                 print("done!\n");
2361                 // tell the bot system the game is ending now
2362                 bot_endgame();
2363
2364                 WeaponStats_Shutdown();
2365                 MapInfo_Shutdown();
2366         }
2367         else if(world_initialized == 0)
2368         {
2369                 print("NOTE: crashed before even initializing the world, not saving persistent data\n");
2370         }
2371 }