92e4b8ac18ac0a0c4c264fd311fc5297a7ac987f
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / clientcommands.qc
1 entity nagger;
2 float readycount;
3 float Nagger_SendEntity(entity to, float sendflags)
4 {
5         float nags, i, f, b;
6         entity e;
7         WriteByte(MSG_ENTITY, ENT_CLIENT_NAGGER);
8
9         nags = 0;
10         if(readycount)
11         {
12                 nags |= 1;
13                 if(to.ready == 0)
14                         nags |= 2;
15         }
16         if(votecalled)
17         {
18                 nags |= 4;
19                 if(to.vote_vote == 0)
20                         nags |= 8;
21         }
22         if(inWarmupStage)
23                 nags |= 16;
24
25         if(sendflags & 128)
26                 nags |= 128;
27
28         WriteByte(MSG_ENTITY, nags);
29
30         if(nags & 128)
31         {
32                 WriteString(MSG_ENTITY, votecalledvote_display);
33         }
34
35         if(nags & 1)
36         {
37                 for(i = 1; i <= maxclients; i += 8)
38                 {
39                         for(f = 0, e = edict_num(i), b = 1; b < 256; b *= 2, e = nextent(e))
40                                 if(clienttype(e) != CLIENTTYPE_REAL || e.ready)
41                                         f |= b;
42                         WriteByte(MSG_ENTITY, f);
43                 }
44         }
45
46         return TRUE;
47 }
48 void Nagger_Init()
49 {
50         Net_LinkEntity(nagger = spawn(), FALSE, 0, Nagger_SendEntity);
51 }
52 void Nagger_VoteChanged()
53 {
54         if(nagger)
55                 nagger.SendFlags |= 128;
56 }
57 void Nagger_VoteCountChanged()
58 {
59         if(nagger)
60                 nagger.SendFlags |= 1;
61 }
62 void Nagger_ReadyCounted()
63 {
64         if(nagger)
65                 nagger.SendFlags |= 1;
66 }
67
68 void ReadyCount();
69 string MapVote_Suggest(string m);
70
71 entity GetPlayer(string name)
72 {
73         float num;
74         entity e;
75         string ns;
76
77         if(substring(name, 0, 1) == "#") {
78                 num = stof(substring(name, 1, 999));
79                 if(num >= 1 && num <= maxclients) {
80                         for((e = world); num > 0; --num, (e = nextent(e)))
81                                 ;
82                         //if(clienttype(e) == CLIENTTYPE_REAL)
83                         if(e.classname == "player")
84                                 return e;
85                 }
86         } else {
87                 ns = strdecolorize(name);
88                 FOR_EACH_REALPLAYER(e) {
89                         if(!strcasecmp(strdecolorize(e.netname), ns)) {
90                                 return e;
91                         }
92                 }
93         }
94         return world;
95 }
96
97 //float ctf_clientcommand();
98 float readyrestart_happened;
99 .float lms_spectate_warning;
100 void spawnfunc_func_breakable();
101
102 .float cmd_floodtime;
103 .float cmd_floodcount;
104 float cmd_floodcheck()
105 {
106         if (timeoutStatus != 2)
107         {
108                 if(time == self.cmd_floodtime)
109                 {
110                         self.cmd_floodcount += 1;
111                         if(self.cmd_floodcount > 8)
112                                 return TRUE;
113                 }
114                 else
115                 {
116                         self.cmd_floodtime = time;
117                         self.cmd_floodcount = 1;
118                 }
119         }
120         return FALSE;
121 }
122
123 void SV_ParseClientCommand(string s) {
124         string cmd;
125         float tokens;
126         float i;
127         entity e;
128
129         tokens = tokenize_console(s);
130
131         cmd = argv(0);
132         if(cmd != "reportcvar")
133         if(cmd != "sentcvar")
134         if(cmd != "pause")
135         if(cmd != "prespawn")
136         if(cmd != "spawn")
137         if(cmd != "begin")
138         {
139                 if(cmd_floodcheck())
140                         return;
141         }
142
143         if(GameCommand_Vote(s, self)) {
144                 return;
145         } else if(GameCommand_MapVote(argv(0))) {
146                 return;
147         } else if(cmd == "autoswitch") {
148                 // be backwards compatible with older clients (enabled)
149                 self.autoswitch = ("0" != argv(1));
150                 local string autoswitchmsg;
151                 if (self.autoswitch) {
152                         autoswitchmsg = "on";
153                 } else {
154                         autoswitchmsg = "off";
155                 }
156                 sprint(self, strcat("^1autoswitch turned ", autoswitchmsg, "\n"));
157         } else if(cmd == "clientversion") {
158                 if not(self.flags & FL_CLIENT)
159                         return;
160                 if (argv(1) == "$gameversion") {
161                         //versionmsg = "^1client is too old to get versioninfo.\nUPDATE!!! (http://www.xonotic.com)^8";
162                         // either that or someone wants to be funny
163                         self.version = 1;
164                 } else {
165                         self.version = stof(argv(1));
166                 }
167                 if(self.version != autocvar_gameversion)
168                 {
169                         self.classname = "observer";
170                         self.version_mismatch = 1;
171                         PutClientInServer();
172                 } else if(autocvar_g_campaign || autocvar_g_balance_teams || autocvar_g_balance_teams_force) {
173                         //JoinBestTeam(self, FALSE, TRUE);
174                 } else if(teams_matter && !autocvar_sv_spectate && !(self.team_forced > 0)) {
175                         self.classname = "observer";
176                         stuffcmd(self,"menu_showteamselect\n");
177                 }
178         } else if(cmd == "reportcvar") { // old system
179                 if(substring(argv(2), 0, 1) == "$") // undefined cvar: use the default value on the server then
180                 {
181                         s = strcat(substring(s, argv_start_index(0), argv_end_index(1) - argv_start_index(0)), " \"", cvar_defstring(argv(1)), "\"");
182                         tokens = tokenize_console(s);
183                 }
184                 GetCvars(1);
185         } else if(cmd == "sentcvar") { // new system
186                 if(tokens == 2) // undefined cvar: use the default value on the server then
187                 {
188                         s = strcat(substring(s, argv_start_index(0), argv_end_index(1) - argv_start_index(0)), " \"", cvar_defstring(argv(1)), "\"");
189                         tokens = tokenize_console(s);
190                 }
191                 GetCvars(1);
192         } else if(cmd == "spectate") {
193                 if(cmd_floodcheck())
194                         return;
195                 if not(self.flags & FL_CLIENT)
196                         return;
197                 if(g_arena)
198                         return;
199                 if(g_lms)
200                 {
201                         if(self.lms_spectate_warning)
202                         {
203                                 // mark player as spectator
204                                 PlayerScore_Add(self, SP_LMS_RANK, 666 - PlayerScore_Add(self, SP_LMS_RANK, 0));
205                         }
206                         else
207                         {
208                                 self.lms_spectate_warning = 1;
209                                 sprint(self, "WARNING: you won't be able to enter the game again after spectating in LMS. Use the same command again to spectate anyway.\n");
210                                 return;
211                         }
212                 }
213                 if(self.classname == "player" && autocvar_sv_spectate == 1) {
214                         if(self.flagcarried)
215                                 DropFlag(self.flagcarried, world, world);
216                         if(self.ballcarried && g_nexball)
217                                 DropBall(self.ballcarried, self.origin, self.velocity);
218                         WaypointSprite_PlayerDead();
219                         self.classname = "observer";
220                         if(g_ca)
221                                 self.caplayer = 0;
222                         if(blockSpectators)
223                                 sprint(self, strcat("^7You have to become a player within the next ", ftos(autocvar_g_maxplayers_spectator_blocktime), " seconds, otherwise you will be kicked, because spectators aren't allowed at this time!\n"));
224                         PutClientInServer();
225                 }
226         } else if(cmd == "join") {
227                 if not(self.flags & FL_CLIENT)
228                         return;
229                 if(!g_arena)
230                 if (self.classname != "player" && !lockteams)
231                 {
232                         if(isJoinAllowed()) {
233                                 self.classname = "player";
234                                 if(g_ca)
235                                         self.caplayer = 1;
236                                 PlayerScore_Clear(self);
237                                 bprint ("^4", self.netname, "^4 is playing now\n");
238                                 PutClientInServer();
239                                 if(autocvar_g_campaign)
240                                         campaign_bots_may_start = 1;
241                         }
242                         else {
243                                 //player may not join because of g_maxplayers is set
244                                 centerprint_atprio(self, CENTERPRIO_MAPVOTE, PREVENT_JOIN_TEXT);
245                         }
246                 }
247         } else if( cmd == "selectteam" ) {
248                 if not(self.flags & FL_CLIENT)
249                         return;
250                 if( !teams_matter ) {
251                         sprint( self, "selectteam can only be used in teamgames\n");
252                 } else if(autocvar_g_campaign) {
253                         //JoinBestTeam(self, 0);
254                 } else if(self.team_forced > 0) {
255                         sprint( self, "selectteam can not be used as your team is forced\n");
256                 } else if(lockteams) {
257                         sprint( self, "^7The game has already begun, you must wait until the next map to be able to join a team.\n");
258                 } else if( argv(1) == "red" ) {
259                         DoTeamChange(COLOR_TEAM1);
260                 } else if( argv(1) == "blue" ) {
261                         DoTeamChange(COLOR_TEAM2);
262                 } else if( argv(1) == "yellow" ) {
263                         DoTeamChange(COLOR_TEAM3);
264                 } else if( argv(1) == "pink" ) {
265                         DoTeamChange(COLOR_TEAM4);
266                 } else if( argv(1) == "auto" ) {
267                         DoTeamChange(-1);
268                 } else {
269                         sprint( self, strcat( "selectteam none/red/blue/yellow/pink/auto - \"", argv(1), "\" not recognised\n" ) );
270                 }
271         } else if(cmd == "ready") {
272                 if not(self.flags & FL_CLIENT)
273                         return;
274
275                 if((inWarmupStage && 0 >= g_warmup_limit) // with unlimited warmup players have to be able to restart
276                    || autocvar_sv_ready_restart || g_race_qualifying == 2)
277                 {
278                         if(!readyrestart_happened || autocvar_sv_ready_restart_repeatable)
279                         {
280                                 if (self.ready) // toggle
281                                 {
282                                         self.ready = FALSE;
283                                         bprint(self.netname, "^2 is ^1NOT^2 ready\n");
284                                 }
285                                 else
286                                 {
287                                         self.ready = TRUE;
288                                         bprint(self.netname, "^2 is ready\n");
289                                 }
290
291                                 // cannot reset the game while a timeout is active!
292                                 if(!timeoutStatus)
293                                         ReadyCount();
294                         } else {
295                                 sprint(self, "^1Game has already been restarted\n");
296                         }
297                 }
298         } else if(cmd == "maplist") {
299                 sprint(self, maplist_reply);
300         } else if(cmd == "lsmaps") {
301                 sprint(self, lsmaps_reply);
302         } else if(cmd == "lsnewmaps") {
303                 sprint(self, lsnewmaps_reply);
304         } else if(cmd == "records") {
305                 for(i = 0; i < 10; ++i)
306                         sprint(self, records_reply[i]);
307         } else if(cmd == "ladder") {
308                 sprint(self, ladder_reply);
309         } else if(cmd == "rankings") {
310                 sprint(self, rankings_reply);
311         } else if(cmd == "voice") {
312                 if(tokens >= 3)
313                         VoiceMessage(argv(1), substring(s, argv_start_index(2), argv_end_index(-1) - argv_start_index(2)));
314                 else
315                         VoiceMessage(argv(1), "");
316         } else if(cmd == "say") {
317                 if(tokens >= 2)
318                         Say(self, FALSE, world, substring(s, argv_start_index(1), argv_end_index(-1) - argv_start_index(1)), 1);
319                 //clientcommand(self, formatmessage(s));
320         } else if(cmd == "say_team") {
321                 if(tokens >= 2)
322                         Say(self, TRUE, world, substring(s, argv_start_index(1), argv_end_index(-1) - argv_start_index(1)), 1);
323                 //clientcommand(self, formatmessage(s));
324         } else if(cmd == "tell") {
325                 e = GetCommandPlayerSlotTargetFromTokenizedCommand(tokens, 1);
326                 if(e && tokens > ParseCommandPlayerSlotTarget_firsttoken)
327                 {
328                         Say(self, FALSE, e, substring(s, argv_start_index(ParseCommandPlayerSlotTarget_firsttoken), argv_end_index(-1) - argv_start_index(ParseCommandPlayerSlotTarget_firsttoken)), TRUE);
329                 }
330                 else
331                 {
332                         if(tokens > ParseCommandPlayerSlotTarget_firsttoken)
333                                 trigger_magicear_processmessage_forallears(self, -1, world, substring(s, argv_start_index(ParseCommandPlayerSlotTarget_firsttoken), argv_end_index(-1) - argv_start_index(ParseCommandPlayerSlotTarget_firsttoken)));
334                         sprint(self, "ERROR: usage: tell # playerid text...\n");
335                 }
336                 //clientcommand(self, formatmessage(s));
337         } else if(cmd == "info") {
338                 cmd = cvar_string_builtin(strcat("sv_info_", argv(1))); // This needed fixed for the cvar check
339                 if(cmd == "")
340                         sprint(self, "ERROR: unsupported info command\n");
341                 else
342                         wordwrap_sprint(cmd, 1111);
343         } else if(cmd == "suggestmap") {
344                 sprint(self, strcat(MapVote_Suggest(argv(1)), "\n"));
345         } else if(cmd == "timeout") {
346                 if not(self.flags & FL_CLIENT)
347                         return;
348                 if(autocvar_sv_timeout) {
349                         if(self.classname == "player") {
350                                 if(votecalled)
351                                         sprint(self, "^7Error: you can not call a timeout while a vote is active!\n");
352                                 else
353                                         evaluateTimeout();
354                         }
355                         else
356                                 sprint(self, "^7Error: only players can call a timeout!\n");
357                 }
358         } else if(cmd == "timein") {
359                 if not(self.flags & FL_CLIENT)
360                         return;
361                 if(autocvar_sv_timeout) {
362                         evaluateTimein();
363                 }
364         } else if(cmd == "teamstatus") {
365                 Score_NicePrint(self);
366         } else if(cmd == "cvar_changes") {
367                 sprint(self, cvar_changes);
368         } else if(cmd == "cvar_purechanges") {
369                 sprint(self, cvar_purechanges);
370         } else if(CheatCommand(tokens)) {
371         } else {
372                 //if(ctf_clientcommand())
373                 //      return;
374                 // grep for Cmd_AddCommand_WithClientCommand to find them all
375                 if(cmd != "status")
376                 //if(cmd != "say") // handled above
377                 //if(cmd != "say_team") // handled above
378                 if(cmd != "kill")
379                 if(cmd != "pause")
380                 if(cmd != "ping")
381                 if(cmd != "name")
382                 if(cmd != "color")
383                 if(cmd != "rate")
384                 if(cmd != "pmodel")
385                 if(cmd != "playermodel")
386                 if(cmd != "playerskin")
387                 if(cmd != "prespawn")
388                 if(cmd != "spawn")
389                 if(cmd != "begin")
390                 if(cmd != "pings")
391                 if(cmd != "sv_startdownload")
392                 if(cmd != "download")
393                 {
394                         print("WARNING: Invalid clientcommand by ", self.netname, ": ", s, "\n");
395                         return;
396                 }
397
398                 if(self.jointime > 0 && time > self.jointime + 10 && time > self.nickspamtime) // allow any changes in the first 10 seconds since joining
399                 if(cmd == "name" || cmd == "playermodel") // TODO also playerskin and color?
400                 {
401                         if(self.nickspamtime == 0 || time > self.nickspamtime + autocvar_g_nick_flood_timeout)
402                                 // good, no serious flood
403                                 self.nickspamcount = 1;
404                         else
405                                 self.nickspamcount += 1;
406                         self.nickspamtime = time + autocvar_g_nick_flood_penalty;
407
408                         if (timeoutStatus == 2) //when game is paused, no flood protection
409                                 self.nickspamcount = self.nickspamtime = 0;
410                 }
411
412                 clientcommand(self,s);
413         }
414 }
415
416 void ReadyRestartForce()
417 {
418         local entity e;
419
420         bprint("^1Server is restarting...\n");
421
422         VoteReset();
423
424         // clear overtime
425         if (checkrules_overtimesadded > 0 && g_race_qualifying != 2) {
426                 //we have to decrease timelimit to its original value again!!
427                 float newTL;
428                 newTL = autocvar_timelimit;
429                 newTL -= checkrules_overtimesadded * autocvar_timelimit_overtime;
430                 cvar_set("timelimit", ftos(newTL));
431         }
432
433         checkrules_suddendeathend = checkrules_overtimesadded = checkrules_suddendeathwarning = 0;
434
435
436         readyrestart_happened = 1;
437         game_starttime = time;
438         if(!g_ca && !g_arena)
439                 game_starttime += RESTART_COUNTDOWN;
440         restart_mapalreadyrestarted = 0; //reset this var, needed when cvar sv_ready_restart_repeatable is in use
441
442         inWarmupStage = 0; //once the game is restarted the game is in match stage
443
444         //reset the .ready status of all players (also spectators)
445         FOR_EACH_CLIENTSLOT(e)
446                 e.ready = 0;
447         readycount = 0;
448         Nagger_ReadyCounted(); // NOTE: this causes a resend of that entity, and will also turn off warmup state on the client
449
450         if(autocvar_teamplay_lockonrestart && teams_matter) {
451                 lockteams = 1;
452                 bprint("^1The teams are now locked.\n");
453         }
454
455         //initiate the restart-countdown-announcer entity
456         if(autocvar_sv_ready_restart_after_countdown && !g_ca && !g_arena)
457         {
458                 restartTimer = spawn();
459                 restartTimer.think = restartTimer_Think;
460                 restartTimer.nextthink = game_starttime;
461         }
462
463         //after a restart every players number of allowed timeouts gets reset, too
464         if(autocvar_sv_timeout)
465         {
466                 FOR_EACH_REALPLAYER(e)
467                         e.allowedTimeouts = autocvar_sv_timeout_number;
468         }
469
470         //reset map immediately if this cvar is not set
471         if (!autocvar_sv_ready_restart_after_countdown)
472                 reset_map(TRUE);
473
474         if(autocvar_sv_eventlog)
475                 GameLogEcho(":restart");
476 }
477
478 void ReadyRestart()
479 {
480         // no arena, assault support yet...
481         if(g_arena | g_assault | gameover | intermission_running | race_completing)
482                 localcmd("restart\n");
483         else
484                 localcmd("\nsv_hook_gamerestart\n");
485
486         ReadyRestartForce();
487
488         // reset ALL scores, but only do that at the beginning
489         //of the countdown if sv_ready_restart_after_countdown is off!
490         //Otherwise scores could be manipulated during the countdown!
491         if (!autocvar_sv_ready_restart_after_countdown)
492                 Score_ClearAll();
493 }
494
495 /**
496  * Counts how many players are ready. If not enough players are ready, the function
497  * does nothing. If all players are ready, the timelimit will be extended and the
498  * restart_countdown variable is set to allow other functions like PlayerPostThink
499  * to detect that the countdown is now active. If the cvar sv_ready_restart_after_countdown
500  * is not set the map will be resetted.
501  *
502  * Function is called after the server receives a 'ready' sign from a player.
503  */
504 void ReadyCount()
505 {
506         local entity e;
507         local float r, p;
508
509         r = p = 0;
510
511         FOR_EACH_REALPLAYER(e)
512         {
513                 p += 1;
514                 if(e.ready)
515                         r += 1;
516         }
517
518         readycount = r;
519
520         Nagger_ReadyCounted();
521
522         if(r) // at least one is ready
523         if(r == p) // and, everyone is ready
524                 ReadyRestart();
525 }
526
527 /**
528  * Restarts the map after the countdown is over (and cvar sv_ready_restart_after_countdown
529  * is set)
530  */
531 void restartTimer_Think() {
532         restart_mapalreadyrestarted = 1;
533         reset_map(TRUE);
534         Score_ClearAll();
535         remove(self);
536         return;
537 }
538
539 /**
540  * Checks whether the player who calls the timeout is allowed to do so.
541  * If so, it initializes the timeout countdown. It also checks whether another
542  * timeout was already running at this time and reacts correspondingly.
543  *
544  * affected globals/fields: .allowedTimeouts, remainingTimeoutTime, remainingLeadTime,
545  *                          timeoutInitiator, timeoutStatus, timeoutHandler
546  *
547  * This function is called when a player issues the calltimeout command.
548  */
549 void evaluateTimeout() {
550         if (inWarmupStage && !g_warmup_allow_timeout)
551                 return sprint(self, "^7Error: You can not call a timeout in warmup-stage!\n");
552         if (time < game_starttime )
553                 return sprint(self, "^7Error: You can not call a timeout while the map is being restarted!\n");
554         if (timeoutStatus != 2) {
555                 //if the map uses a timelimit make sure that timeout cannot be called right before the map ends
556                 if (autocvar_timelimit) {
557                         //a timelimit was used
558                         local float myTl;
559                         myTl = autocvar_timelimit;
560
561                         local float lastPossibleTimeout;
562                         lastPossibleTimeout = (myTl*60) - autocvar_sv_timeout_leadtime - 1;
563
564                         if (lastPossibleTimeout < time - game_starttime)
565                                 return sprint(self, "^7Error: It is too late to call a timeout now!\n");
566                 }
567         }
568         //player may not call a timeout if he has no calls left
569         if (self.allowedTimeouts < 1)
570                 return sprint(self, "^7Error: You already used all your timeout calls for this map!\n");
571         //now all required checks are passed
572         self.allowedTimeouts -= 1;
573         bprint(self.netname, " ^7called a timeout (", ftos(self.allowedTimeouts), " timeouts left)!\n"); //write a bprint who started the timeout (and how many he has left)
574         remainingTimeoutTime = autocvar_sv_timeout_length;
575         remainingLeadTime = autocvar_sv_timeout_leadtime;
576         timeoutInitiator = self;
577         if (timeoutStatus == 0) { //if another timeout was already active, don't change its status (which was 1 or 2) to 1, only change it to 1 if no timeout was active yet
578                 timeoutStatus = 1;
579                 //create the timeout indicator which centerprints the information to all players and takes care of pausing/unpausing
580                 timeoutHandler = spawn();
581                 timeoutHandler.think = timeoutHandler_Think;
582         }
583         timeoutHandler.nextthink = time; //always let the entity think asap
584
585         //inform all connected clients about the timeout call
586         Announce("timeoutcalled");
587 }
588
589 /**
590  * Checks whether a player is allowed to resume the game. If he is allowed to do it,
591  * and the lead time for the timeout is still active, this countdown just will be aborted (the
592  * game will never be paused). Otherwise the remainingTimeoutTime will be set to the corresponding
593  * value of the cvar sv_timeout_resumetime.
594  *
595  * This function is called when a player issues the resumegame command.
596  */
597 void evaluateTimein() {
598         if (!timeoutStatus)
599                 return sprint(self, "^7Error: There is no active timeout which could be aborted!\n");
600         if (self != timeoutInitiator)
601                 return sprint(self, "^7Error: You may not abort the active timeout. Only the player who called it can do that!\n");
602         if (timeoutStatus == 1) {
603                 remainingTimeoutTime = timeoutStatus = 0;
604                 timeoutHandler.nextthink = time; //timeoutHandler has to take care of it immediately
605                 bprint(strcat("^7The timeout was aborted by ", self.netname, " !\n"));
606         }
607         else if (timeoutStatus == 2) {
608                 //only shorten the remainingTimeoutTime if it makes sense
609                 if( remainingTimeoutTime > (autocvar_sv_timeout_resumetime + 1) ) {
610                         bprint(strcat("^1Attention: ^7", self.netname, " resumed the game! Prepare for battle!\n"));
611                         remainingTimeoutTime = autocvar_sv_timeout_resumetime;
612                         timeoutHandler.nextthink = time; //timeoutHandler has to take care of it immediately
613                 }
614                 else
615                         sprint(self, "^7Error: Your resumegame call was discarded!\n");
616
617         }
618 }