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