1/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
2/* If you are missing that file, acquire a complete release at teeworlds.com. */
3#include "gamecontext.h"
4
5#include "entities/character.h"
6#include "gamemodes/ddnet.h"
7#include "gamemodes/mod.h"
8#include "player.h"
9#include "score.h"
10#include "teeinfo.h"
11
12#include <antibot/antibot_data.h>
13
14#include <base/aio.h>
15#include <base/dbg.h>
16#include <base/fs.h>
17#include <base/io.h>
18#include <base/logger.h>
19#include <base/math.h>
20#include <base/mem.h>
21#include <base/secure.h>
22#include <base/str.h>
23#include <base/time.h>
24
25#include <engine/console.h>
26#include <engine/engine.h>
27#include <engine/map.h>
28#include <engine/server/authmanager.h>
29#include <engine/server/server.h>
30#include <engine/shared/config.h>
31#include <engine/shared/datafile.h>
32#include <engine/shared/json.h>
33#include <engine/shared/linereader.h>
34#include <engine/shared/memheap.h>
35#include <engine/shared/protocol.h>
36#include <engine/shared/protocolglue.h>
37#include <engine/storage.h>
38
39#include <generated/protocol.h>
40#include <generated/protocol7.h>
41#include <generated/protocolglue.h>
42
43#include <game/collision.h>
44#include <game/gamecore.h>
45#include <game/mapitems.h>
46#include <game/version.h>
47
48#include <memory>
49#include <vector>
50
51// Not thread-safe!
52class CClientChatLogger : public ILogger
53{
54 CGameContext *m_pGameServer;
55 int m_ClientId;
56 ILogger *m_pOuterLogger;
57
58public:
59 CClientChatLogger(CGameContext *pGameServer, int ClientId, ILogger *pOuterLogger) :
60 m_pGameServer(pGameServer),
61 m_ClientId(ClientId),
62 m_pOuterLogger(pOuterLogger)
63 {
64 }
65 void Log(const CLogMessage *pMessage) override;
66};
67
68void CClientChatLogger::Log(const CLogMessage *pMessage)
69{
70 if(str_comp(a: pMessage->m_aSystem, b: "chatresp") == 0)
71 {
72 if(m_Filter.Filters(pMessage))
73 {
74 return;
75 }
76 m_pGameServer->SendChatTarget(To: m_ClientId, pText: pMessage->Message());
77 }
78 else
79 {
80 m_pOuterLogger->Log(pMessage);
81 }
82}
83
84CGameContext::CGameContext(bool Resetting) :
85 m_Mutes("mutes"),
86 m_VoteMutes("votemutes")
87{
88 m_Resetting = false;
89 m_pServer = nullptr;
90
91 std::fill(first: std::begin(arr&: m_apPlayers), last: std::end(arr&: m_apPlayers), value: nullptr);
92 mem_zero(block: &m_aLastPlayerInput, size: sizeof(m_aLastPlayerInput));
93 std::fill(first: std::begin(arr&: m_aPlayerHasInput), last: std::end(arr&: m_aPlayerHasInput), value: false);
94
95 m_pController = nullptr;
96
97 m_pVoteOptionFirst = nullptr;
98 m_pVoteOptionLast = nullptr;
99 m_LastMapVote = 0;
100
101 m_SqlRandomMapResult = nullptr;
102
103 m_pLoadMapInfoResult = nullptr;
104 m_aMapInfoMessage[0] = '\0';
105
106 m_pScore = nullptr;
107
108 m_VoteCreator = -1;
109 m_VoteType = VOTE_TYPE_UNKNOWN;
110 m_VoteCloseTime = 0;
111 m_VoteUpdate = false;
112 m_VotePos = 0;
113 m_aVoteDescription[0] = '\0';
114 m_aSixupVoteDescription[0] = '\0';
115 m_aVoteCommand[0] = '\0';
116 m_aVoteReason[0] = '\0';
117 m_NumVoteOptions = 0;
118 m_VoteEnforce = VOTE_ENFORCE_UNKNOWN;
119
120 m_LatestLog = 0;
121 mem_zero(block: &m_aLogs, size: sizeof(m_aLogs));
122
123 str_copy(dst&: m_aVersionString, GAME_VERSION);
124 if(GIT_SHORTREV_HASH != nullptr)
125 {
126 str_append(dst&: m_aVersionString, src: " ");
127 str_append(dst&: m_aVersionString, src: GIT_SHORTREV_HASH);
128 }
129
130 if(!Resetting)
131 {
132 m_pMap = CreateMap();
133 std::fill(first: std::begin(arr&: m_apSavedTees), last: std::end(arr&: m_apSavedTees), value: nullptr);
134 std::fill(first: std::begin(arr&: m_apSavedTeams), last: std::end(arr&: m_apSavedTeams), value: nullptr);
135 std::fill(first: std::begin(arr&: m_aTeamMapping), last: std::end(arr&: m_aTeamMapping), value: -1);
136 m_NonEmptySince = 0;
137 m_pVoteOptionHeap = new CHeap();
138 }
139
140 m_aDeleteTempfile[0] = 0;
141 m_TeeHistorianActive = false;
142}
143
144CGameContext::~CGameContext()
145{
146 for(auto &pPlayer : m_apPlayers)
147 delete pPlayer;
148
149 if(!m_Resetting)
150 {
151 m_pMap->Unload();
152 m_pMap = nullptr;
153
154 for(auto &pSavedTee : m_apSavedTees)
155 delete pSavedTee;
156
157 for(auto &pSavedTeam : m_apSavedTeams)
158 delete pSavedTeam;
159
160 delete m_pVoteOptionHeap;
161 }
162
163 delete m_pScore;
164 m_pScore = nullptr;
165}
166
167void CGameContext::Clear()
168{
169 CHeap *pVoteOptionHeap = m_pVoteOptionHeap;
170 CVoteOptionServer *pVoteOptionFirst = m_pVoteOptionFirst;
171 CVoteOptionServer *pVoteOptionLast = m_pVoteOptionLast;
172 int NumVoteOptions = m_NumVoteOptions;
173 CTuningParams Tuning = m_aTuningList[0];
174 CMutes Mutes = m_Mutes;
175 CMutes VoteMutes = m_VoteMutes;
176 std::unique_ptr<IMap> pMap;
177 std::swap(x&: pMap, y&: m_pMap);
178
179 m_Resetting = true;
180 this->~CGameContext();
181 new(this) CGameContext(true);
182
183 m_pVoteOptionHeap = pVoteOptionHeap;
184 m_pVoteOptionFirst = pVoteOptionFirst;
185 m_pVoteOptionLast = pVoteOptionLast;
186 m_NumVoteOptions = NumVoteOptions;
187 m_aTuningList[0] = Tuning;
188 m_Mutes = Mutes;
189 m_VoteMutes = VoteMutes;
190 std::swap(x&: pMap, y&: m_pMap);
191}
192
193void CGameContext::TeeHistorianWrite(const void *pData, int DataSize, void *pUser)
194{
195 CGameContext *pSelf = (CGameContext *)pUser;
196 aio_write(aio: pSelf->m_pTeeHistorianFile, buffer: pData, size: DataSize);
197}
198
199std::optional<std::vector<int>> CGameContext::ClientsForVictim(int ClientId, const char *pVictim, void *pUser)
200{
201 CGameContext *pSelf = (CGameContext *)pUser;
202 std::vector<int> vClientIds;
203
204 if(!str_comp(a: pVictim, b: "me"))
205 {
206 if(ClientId < 0)
207 return std::nullopt;
208 vClientIds.emplace_back(args&: ClientId);
209 }
210 else if(!str_comp(a: pVictim, b: "all"))
211 {
212 const int MaxClients = pSelf->Server()->MaxClients();
213 for(int i = 0; i < MaxClients; i++)
214 {
215 if(!pSelf->Server()->ClientIngame(ClientId: i))
216 continue;
217
218 vClientIds.emplace_back(args&: i);
219 }
220 }
221 else
222 {
223 return std::nullopt;
224 }
225
226 return std::make_optional(t: std::move(vClientIds));
227}
228
229void CGameContext::CommandCallback(int ClientId, int FlagMask, const char *pCmd, IConsole::IResult *pResult, void *pUser)
230{
231 CGameContext *pSelf = (CGameContext *)pUser;
232 if(pSelf->m_TeeHistorianActive)
233 {
234 pSelf->m_TeeHistorian.RecordConsoleCommand(ClientId, FlagMask, pCmd, pResult);
235 }
236}
237
238CNetObj_PlayerInput CGameContext::GetLastPlayerInput(int ClientId) const
239{
240 dbg_assert(0 <= ClientId && ClientId < MAX_CLIENTS, "invalid ClientId");
241 return m_aLastPlayerInput[ClientId];
242}
243
244CCharacter *CGameContext::GetPlayerChar(int ClientId)
245{
246 if(ClientId < 0 || ClientId >= MAX_CLIENTS || !m_apPlayers[ClientId])
247 return nullptr;
248 return m_apPlayers[ClientId]->GetCharacter();
249}
250
251const CCharacter *CGameContext::GetPlayerChar(int ClientId) const
252{
253 if(ClientId < 0 || ClientId >= MAX_CLIENTS || !m_apPlayers[ClientId])
254 return nullptr;
255 return m_apPlayers[ClientId]->GetCharacter();
256}
257
258const CPlayer *CGameContext::FindPlayerByName(const char *pName) const
259{
260 std::optional<int> ClientId = FindClientIdByName(pName);
261 if(!ClientId.has_value())
262 return nullptr;
263 return m_apPlayers[ClientId.value()];
264}
265
266CPlayer *CGameContext::FindPlayerByName(const char *pName)
267{
268 std::optional<int> ClientId = FindClientIdByName(pName);
269 if(!ClientId.has_value())
270 return nullptr;
271 return m_apPlayers[ClientId.value()];
272}
273
274std::optional<int> CGameContext::FindClientIdByName(const char *pName) const
275{
276 if(!pName)
277 return std::nullopt;
278
279 for(int ClientId = 0; ClientId < MAX_CLIENTS; ClientId++)
280 {
281 if(!Server()->ClientIngame(ClientId))
282 continue;
283 if(str_comp(a: pName, b: Server()->ClientName(ClientId)))
284 continue;
285
286 return ClientId;
287 }
288 return std::nullopt;
289}
290
291bool CGameContext::EmulateBug(int Bug) const
292{
293 return m_MapBugs.Contains(Bug);
294}
295
296void CGameContext::FillAntibot(CAntibotRoundData *pData)
297{
298 if(!pData->m_Map.m_pTiles)
299 {
300 Collision()->FillAntibot(pMapData: &pData->m_Map);
301 }
302 pData->m_Tick = Server()->Tick();
303 mem_zero(block: pData->m_aCharacters, size: sizeof(pData->m_aCharacters));
304 for(int i = 0; i < MAX_CLIENTS; i++)
305 {
306 CAntibotCharacterData *pChar = &pData->m_aCharacters[i];
307 for(auto &LatestInput : pChar->m_aLatestInputs)
308 {
309 LatestInput.m_Direction = 0;
310 LatestInput.m_TargetX = -1;
311 LatestInput.m_TargetY = -1;
312 LatestInput.m_Jump = -1;
313 LatestInput.m_Fire = -1;
314 LatestInput.m_Hook = -1;
315 LatestInput.m_PlayerFlags = -1;
316 LatestInput.m_WantedWeapon = -1;
317 LatestInput.m_NextWeapon = -1;
318 LatestInput.m_PrevWeapon = -1;
319 }
320 pChar->m_Alive = false;
321 pChar->m_Pause = false;
322 pChar->m_Team = -1;
323
324 pChar->m_Pos = vec2(-1, -1);
325 pChar->m_Vel = vec2(0, 0);
326 pChar->m_Angle = -1;
327 pChar->m_HookedPlayer = -1;
328 pChar->m_SpawnTick = -1;
329 pChar->m_WeaponChangeTick = -1;
330
331 if(m_apPlayers[i])
332 {
333 str_copy(dst&: pChar->m_aName, src: Server()->ClientName(ClientId: i));
334 CCharacter *pGameChar = m_apPlayers[i]->GetCharacter();
335 pChar->m_Alive = (bool)pGameChar;
336 pChar->m_Pause = m_apPlayers[i]->IsPaused();
337 pChar->m_Team = m_apPlayers[i]->GetTeam();
338 if(pGameChar)
339 {
340 pGameChar->FillAntibot(pData: pChar);
341 }
342 }
343 }
344}
345
346void CGameContext::CreateDamageInd(vec2 Pos, float Angle, int Amount, CClientMask Mask)
347{
348 float a = 3 * pi / 2 + Angle;
349 float s = a - pi / 3;
350 float e = a + pi / 3;
351 for(int i = 0; i < Amount; i++)
352 {
353 float f = mix(a: s, b: e, amount: (i + 1) / (float)(Amount + 1));
354 CNetEvent_DamageInd *pEvent = m_Events.Create<CNetEvent_DamageInd>(Mask);
355 if(pEvent)
356 {
357 pEvent->m_X = round_truncate(f: Pos.x);
358 pEvent->m_Y = round_truncate(f: Pos.y);
359 pEvent->m_Angle = (int)(f * 256.0f);
360 }
361 }
362}
363
364void CGameContext::CreateHammerHit(vec2 Pos, CClientMask Mask)
365{
366 CNetEvent_HammerHit *pEvent = m_Events.Create<CNetEvent_HammerHit>(Mask);
367 if(pEvent)
368 {
369 pEvent->m_X = (int)Pos.x;
370 pEvent->m_Y = (int)Pos.y;
371 }
372}
373
374void CGameContext::CreateExplosion(vec2 Pos, int Owner, int Weapon, bool NoDamage, int ActivatedTeam, CClientMask Mask)
375{
376 // create the event
377 CNetEvent_Explosion *pEvent = m_Events.Create<CNetEvent_Explosion>(Mask);
378 if(pEvent)
379 {
380 pEvent->m_X = round_truncate(f: Pos.x);
381 pEvent->m_Y = round_truncate(f: Pos.y);
382 }
383
384 // deal damage
385 CEntity *apEnts[MAX_CLIENTS];
386 float Radius = 135.0f;
387 float InnerRadius = 48.0f;
388 int Num = m_World.FindEntities(Pos, Radius, ppEnts: apEnts, Max: MAX_CLIENTS, Type: CGameWorld::ENTTYPE_CHARACTER);
389 CClientMask TeamMask = CClientMask().set();
390 for(int i = 0; i < Num; i++)
391 {
392 auto *pChr = static_cast<CCharacter *>(apEnts[i]);
393 vec2 Diff = pChr->m_Pos - Pos;
394 vec2 ForceDir(0, 1);
395 float l = length(a: Diff);
396 if(l)
397 ForceDir = normalize(v: Diff);
398 l = 1 - std::clamp(val: (l - InnerRadius) / (Radius - InnerRadius), lo: 0.0f, hi: 1.0f);
399 float Strength;
400 if(Owner == -1 || !m_apPlayers[Owner] || !m_apPlayers[Owner]->m_TuneZone)
401 Strength = GlobalTuning()->m_ExplosionStrength;
402 else
403 Strength = TuningList()[m_apPlayers[Owner]->m_TuneZone].m_ExplosionStrength;
404
405 float Dmg = Strength * l;
406 if(!(int)Dmg)
407 continue;
408
409 if((GetPlayerChar(ClientId: Owner) ? !GetPlayerChar(ClientId: Owner)->GrenadeHitDisabled() : g_Config.m_SvHit) || NoDamage || Owner == pChr->GetPlayer()->GetCid())
410 {
411 if(Owner != -1 && pChr->IsAlive() && !pChr->CanCollide(ClientId: Owner))
412 continue;
413 if(Owner == -1 && ActivatedTeam != -1 && pChr->IsAlive() && pChr->Team() != ActivatedTeam)
414 continue;
415
416 // Explode at most once per team
417 int PlayerTeam = pChr->Team();
418 if((GetPlayerChar(ClientId: Owner) ? GetPlayerChar(ClientId: Owner)->GrenadeHitDisabled() : !g_Config.m_SvHit) || NoDamage)
419 {
420 if(PlayerTeam == TEAM_SUPER)
421 continue;
422 if(!TeamMask.test(position: PlayerTeam))
423 continue;
424 TeamMask.reset(pos: PlayerTeam);
425 }
426
427 pChr->TakeDamage(Force: ForceDir * Dmg * 2, Dmg: (int)Dmg, From: Owner, Weapon);
428 }
429 }
430}
431
432void CGameContext::CreatePlayerSpawn(vec2 Pos, CClientMask Mask)
433{
434 CNetEvent_Spawn *pEvent = m_Events.Create<CNetEvent_Spawn>(Mask);
435 if(pEvent)
436 {
437 pEvent->m_X = (int)Pos.x;
438 pEvent->m_Y = (int)Pos.y;
439 }
440}
441
442void CGameContext::CreateDeath(vec2 Pos, int ClientId, CClientMask Mask)
443{
444 CNetEvent_Death *pEvent = m_Events.Create<CNetEvent_Death>(Mask);
445 if(pEvent)
446 {
447 pEvent->m_X = (int)Pos.x;
448 pEvent->m_Y = (int)Pos.y;
449 pEvent->m_ClientId = ClientId;
450 }
451}
452
453void CGameContext::CreateBirthdayEffect(vec2 Pos, CClientMask Mask)
454{
455 CNetEvent_Birthday *pEvent = m_Events.Create<CNetEvent_Birthday>(Mask);
456 if(pEvent)
457 {
458 pEvent->m_X = (int)Pos.x;
459 pEvent->m_Y = (int)Pos.y;
460 }
461}
462
463void CGameContext::CreateFinishEffect(vec2 Pos, CClientMask Mask)
464{
465 CNetEvent_Finish *pEvent = m_Events.Create<CNetEvent_Finish>(Mask);
466 if(pEvent)
467 {
468 pEvent->m_X = (int)Pos.x;
469 pEvent->m_Y = (int)Pos.y;
470 }
471}
472
473void CGameContext::CreateSound(vec2 Pos, int Sound, CClientMask Mask)
474{
475 if(Sound < 0)
476 return;
477
478 // create a sound
479 CNetEvent_SoundWorld *pEvent = m_Events.Create<CNetEvent_SoundWorld>(Mask);
480 if(pEvent)
481 {
482 pEvent->m_X = round_truncate(f: Pos.x);
483 pEvent->m_Y = round_truncate(f: Pos.y);
484 pEvent->m_SoundId = Sound;
485 }
486}
487
488void CGameContext::CreateSoundGlobal(int Sound, int Target) const
489{
490 if(Sound < 0)
491 return;
492
493 CNetMsg_Sv_SoundGlobal Msg;
494 Msg.m_SoundId = Sound;
495 if(Target == -2)
496 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_NOSEND, ClientId: -1);
497 else
498 {
499 int Flag = MSGFLAG_VITAL;
500 if(Target != -1)
501 Flag |= MSGFLAG_NORECORD;
502 Server()->SendPackMsg(pMsg: &Msg, Flags: Flag, ClientId: Target);
503 }
504}
505
506void CGameContext::SnapSwitchers(int SnappingClient)
507{
508 if(Switchers().empty())
509 return;
510
511 CPlayer *pPlayer = SnappingClient != SERVER_DEMO_CLIENT ? m_apPlayers[SnappingClient] : nullptr;
512 int Team = pPlayer && pPlayer->GetCharacter() ? pPlayer->GetCharacter()->Team() : 0;
513
514 if(pPlayer && (pPlayer->GetTeam() == TEAM_SPECTATORS || pPlayer->IsPaused()) && pPlayer->SpectatorId() != SPEC_FREEVIEW && m_apPlayers[pPlayer->SpectatorId()] && m_apPlayers[pPlayer->SpectatorId()]->GetCharacter())
515 Team = m_apPlayers[pPlayer->SpectatorId()]->GetCharacter()->Team();
516
517 if(Team == TEAM_SUPER)
518 return;
519
520 int SentTeam = Team;
521 if(g_Config.m_SvTeam == SV_TEAM_FORCED_SOLO)
522 SentTeam = 0;
523 else if(SnappingClient != SERVER_DEMO_CLIENT)
524 SentTeam = m_pController->Teams().TeamForClient(Team: SentTeam, ClientId: SnappingClient);
525
526 CNetObj_SwitchState SwitchState = {};
527
528 SwitchState.m_HighestSwitchNumber = std::clamp(val: (int)Switchers().size() - 1, lo: 0, hi: 255);
529 std::fill(first: std::begin(arr&: SwitchState.m_aStatus), last: std::end(arr&: SwitchState.m_aStatus), value: 0);
530
531 std::vector<std::pair<int, int>> vEndTicks; // <EndTick, SwitchNumber>
532
533 for(int i = 0; i <= SwitchState.m_HighestSwitchNumber; i++)
534 {
535 int Status = (int)Switchers()[i].m_aStatus[Team];
536 SwitchState.m_aStatus[i / 32] |= (Status << (i % 32));
537
538 int EndTick = Switchers()[i].m_aEndTick[Team];
539 if(EndTick > 0 && EndTick < Server()->Tick() + 3 * Server()->TickSpeed() && Switchers()[i].m_aLastUpdateTick[Team] < Server()->Tick())
540 {
541 // only keep track of EndTicks that have less than three second left and are not currently being updated by a player being present on a switch tile, to limit how often these are sent
542 vEndTicks.emplace_back(args&: Switchers()[i].m_aEndTick[Team], args&: i);
543 }
544 }
545
546 // send the endtick of switchers that are about to toggle back (up to four, prioritizing those with the earliest endticks)
547 std::fill(first: std::begin(arr&: SwitchState.m_aSwitchNumbers), last: std::end(arr&: SwitchState.m_aSwitchNumbers), value: 0);
548 std::fill(first: std::begin(arr&: SwitchState.m_aEndTicks), last: std::end(arr&: SwitchState.m_aEndTicks), value: 0);
549
550 std::sort(first: vEndTicks.begin(), last: vEndTicks.end());
551 const size_t NumTimedSwitchers = std::min(a: vEndTicks.size(), b: std::size(SwitchState.m_aEndTicks));
552
553 for(size_t i = 0; i < NumTimedSwitchers; i++)
554 {
555 SwitchState.m_aSwitchNumbers[i] = vEndTicks[i].second;
556 SwitchState.m_aEndTicks[i] = vEndTicks[i].first;
557 }
558
559 Server()->SnapNewItem(Id: SentTeam, Data: SwitchState);
560}
561
562void CGameContext::SnapLaserObject(const CSnapContext &Context, int SnapId, const vec2 &To, const vec2 &From, int StartTick, int Owner, int LaserType, int Subtype, int SwitchNumber) const
563{
564 if(Context.GetClientVersion() >= VERSION_DDNET_MULTI_LASER)
565 {
566 CNetObj_DDNetLaser Laser = {};
567 Laser.m_ToX = round_to_int(f: To.x);
568 Laser.m_ToY = round_to_int(f: To.y);
569 Laser.m_FromX = round_to_int(f: From.x);
570 Laser.m_FromY = round_to_int(f: From.y);
571 Laser.m_StartTick = StartTick;
572 Laser.m_Owner = Owner;
573 Laser.m_Type = LaserType;
574 Laser.m_Subtype = Subtype;
575 Laser.m_SwitchNumber = SwitchNumber;
576 Laser.m_Flags = 0;
577 if(!Server()->Translate(Target&: Laser.m_Owner, ClientId: Context.ClientId()))
578 Laser.m_Owner = -1;
579 Server()->SnapNewItem(Id: SnapId, Data: Laser);
580 }
581 else
582 {
583 CNetObj_Laser Laser = {};
584 Laser.m_X = round_to_int(f: To.x);
585 Laser.m_Y = round_to_int(f: To.y);
586 Laser.m_FromX = round_to_int(f: From.x);
587 Laser.m_FromY = round_to_int(f: From.y);
588 Laser.m_StartTick = StartTick;
589 Server()->SnapNewItem(Id: SnapId, Data: Laser);
590 }
591}
592
593void CGameContext::SnapPickup(const CSnapContext &Context, int SnapId, const vec2 &Pos, int Type, int SubType, int SwitchNumber, int Flags) const
594{
595 if(Type == POWERUP_FREEZE && Context.GetClientVersion() < VERSION_DDNET_PICKUP_FREEZE)
596 {
597 Type = POWERUP_HEALTH;
598 }
599 if(Context.IsSixup())
600 {
601 protocol7::CNetObj_Pickup Pickup = {};
602 Pickup.m_X = (int)Pos.x;
603 Pickup.m_Y = (int)Pos.y;
604 Pickup.m_Type = PickupType_SixToSeven(Type6: Type, SubType6: SubType);
605 Server()->SnapNewItem(Id: SnapId, Data: Pickup);
606 }
607 else if(Context.GetClientVersion() >= VERSION_DDNET_ENTITY_NETOBJS)
608 {
609 CNetObj_DDNetPickup Pickup = {};
610 Pickup.m_X = (int)Pos.x;
611 Pickup.m_Y = (int)Pos.y;
612 Pickup.m_Type = Type;
613 Pickup.m_Subtype = SubType;
614 Pickup.m_SwitchNumber = SwitchNumber;
615 Pickup.m_Flags = Flags;
616 Server()->SnapNewItem(Id: SnapId, Data: Pickup);
617 }
618 else
619 {
620 CNetObj_Pickup Pickup = {};
621
622 Pickup.m_X = (int)Pos.x;
623 Pickup.m_Y = (int)Pos.y;
624
625 Pickup.m_Type = Type;
626 if(Context.GetClientVersion() < VERSION_DDNET_WEAPON_SHIELDS)
627 {
628 if(Type >= POWERUP_ARMOR_SHOTGUN && Type <= POWERUP_ARMOR_LASER)
629 {
630 Pickup.m_Type = POWERUP_ARMOR;
631 }
632 }
633 Pickup.m_Subtype = SubType;
634
635 Server()->SnapNewItem(Id: SnapId, Data: Pickup);
636 }
637}
638
639void CGameContext::CallVote(int ClientId, const char *pDesc, const char *pCmd, const char *pReason, const char *pChatmsg, const char *pSixupDesc)
640{
641 // check if a vote is already running
642 if(m_VoteCloseTime)
643 return;
644
645 int64_t Now = Server()->Tick();
646 CPlayer *pPlayer = m_apPlayers[ClientId];
647
648 if(!pPlayer)
649 return;
650
651 SendChat(ClientId: -1, Team: TEAM_ALL, pText: pChatmsg, SpamProtectionClientId: -1, VersionFlags: FLAG_SIX);
652 if(!pSixupDesc)
653 pSixupDesc = pDesc;
654
655 m_VoteCreator = ClientId;
656 StartVote(pDesc, pCommand: pCmd, pReason, pSixupDesc);
657 pPlayer->m_Vote = 1;
658 pPlayer->m_VotePos = m_VotePos = 1;
659 pPlayer->m_LastVoteCall = Now;
660
661 CNetMsg_Sv_YourVote Msg = {.m_Voted: pPlayer->m_Vote};
662 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId);
663}
664
665void CGameContext::SendChatTarget(int To, const char *pText, int VersionFlags) const
666{
667 CNetMsg_Sv_Chat Msg;
668 Msg.m_Team = 0;
669 Msg.m_ClientId = -1;
670 Msg.m_pMessage = pText;
671
672 if(g_Config.m_SvDemoChat)
673 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_NOSEND, ClientId: SERVER_DEMO_CLIENT);
674
675 if(To == -1)
676 {
677 for(int i = 0; i < Server()->MaxClients(); i++)
678 {
679 if(!((Server()->IsSixup(ClientId: i) && (VersionFlags & FLAG_SIXUP)) ||
680 (!Server()->IsSixup(ClientId: i) && (VersionFlags & FLAG_SIX))))
681 continue;
682
683 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId: i);
684 }
685 }
686 else
687 {
688 if(!((Server()->IsSixup(ClientId: To) && (VersionFlags & FLAG_SIXUP)) ||
689 (!Server()->IsSixup(ClientId: To) && (VersionFlags & FLAG_SIX))))
690 return;
691
692 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId: To);
693 }
694}
695
696void CGameContext::SendChatTeam(int Team, const char *pText) const
697{
698 for(int i = 0; i < MAX_CLIENTS; i++)
699 if(m_apPlayers[i] != nullptr && GetDDRaceTeam(ClientId: i) == Team)
700 SendChatTarget(To: i, pText);
701}
702
703void CGameContext::SendChat(int ChatterClientId, int Team, const char *pText, int SpamProtectionClientId, int VersionFlags)
704{
705 dbg_assert(ChatterClientId >= -1 && ChatterClientId < MAX_CLIENTS, "ChatterClientId invalid: %d", ChatterClientId);
706
707 if(SpamProtectionClientId >= 0 && SpamProtectionClientId < MAX_CLIENTS)
708 if(ProcessSpamProtection(ClientId: SpamProtectionClientId))
709 return;
710
711 char aText[MAX_CHAT_LENGTH];
712 str_copy(dst&: aText, src: pText);
713 const char *pTeamString = Team == TEAM_ALL ? "chat" : "teamchat";
714 if(ChatterClientId == -1)
715 {
716 log_info(pTeamString, "*** %s", aText);
717 }
718 else
719 {
720 log_info(pTeamString, "%d:%d:%s: %s", ChatterClientId, Team, Server()->ClientName(ChatterClientId), aText);
721 }
722
723 if(Team == TEAM_ALL)
724 {
725 CNetMsg_Sv_Chat Msg;
726 Msg.m_Team = 0;
727 Msg.m_ClientId = ChatterClientId;
728 Msg.m_pMessage = aText;
729
730 // pack one for the recording only
731 if(g_Config.m_SvDemoChat)
732 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_NOSEND, ClientId: SERVER_DEMO_CLIENT);
733
734 // send to the clients
735 for(int i = 0; i < Server()->MaxClients(); i++)
736 {
737 if(!m_apPlayers[i])
738 continue;
739 bool Send = (Server()->IsSixup(ClientId: i) && (VersionFlags & FLAG_SIXUP)) ||
740 (!Server()->IsSixup(ClientId: i) && (VersionFlags & FLAG_SIX));
741
742 if(!m_apPlayers[i]->m_DND && Send)
743 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId: i);
744 }
745
746 char aBuf[sizeof(aText) + 8];
747 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "Chat: %s", aText);
748 LogEvent(Description: aBuf, ClientId: ChatterClientId);
749 }
750 else
751 {
752 CTeamsCore *pTeams = &m_pController->Teams().m_Core;
753 CNetMsg_Sv_Chat Msg;
754 Msg.m_Team = 1;
755 Msg.m_ClientId = ChatterClientId;
756 Msg.m_pMessage = aText;
757
758 // pack one for the recording only
759 if(g_Config.m_SvDemoChat)
760 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_NOSEND, ClientId: SERVER_DEMO_CLIENT);
761
762 // send to the clients
763 for(int i = 0; i < Server()->MaxClients(); i++)
764 {
765 if(m_apPlayers[i] != nullptr)
766 {
767 if(Team == TEAM_SPECTATORS)
768 {
769 if(m_apPlayers[i]->GetTeam() == TEAM_SPECTATORS)
770 {
771 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId: i);
772 }
773 }
774 else
775 {
776 if(pTeams->Team(ClientId: i) == Team && m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS)
777 {
778 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId: i);
779 }
780 }
781 }
782 }
783 }
784}
785
786void CGameContext::SendStartWarning(int ClientId, const char *pMessage)
787{
788 CCharacter *pChr = GetPlayerChar(ClientId);
789 if(pChr && pChr->m_LastStartWarning < Server()->Tick() - 3 * Server()->TickSpeed())
790 {
791 SendChatTarget(To: ClientId, pText: pMessage);
792 pChr->m_LastStartWarning = Server()->Tick();
793 }
794}
795
796void CGameContext::SendEmoticon(int ClientId, int Emoticon, int TargetClientId) const
797{
798 CNetMsg_Sv_Emoticon Msg;
799 Msg.m_ClientId = ClientId;
800 Msg.m_Emoticon = Emoticon;
801 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId: TargetClientId);
802}
803
804void CGameContext::SendWeaponPickup(int ClientId, int Weapon) const
805{
806 CNetMsg_Sv_WeaponPickup Msg;
807 Msg.m_Weapon = Weapon;
808 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId);
809}
810
811void CGameContext::SendMotd(int ClientId) const
812{
813 CNetMsg_Sv_Motd Msg;
814 Msg.m_pMessage = g_Config.m_SvMotd;
815 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId);
816}
817
818void CGameContext::SendSettings(int ClientId) const
819{
820 protocol7::CNetMsg_Sv_ServerSettings Msg;
821 Msg.m_KickVote = g_Config.m_SvVoteKick;
822 Msg.m_KickMin = g_Config.m_SvVoteKickMin;
823 Msg.m_SpecVote = g_Config.m_SvVoteSpectate;
824 Msg.m_TeamLock = 0;
825 Msg.m_TeamBalance = 0;
826 Msg.m_PlayerSlots = Server()->MaxClients() - g_Config.m_SvSpectatorSlots;
827 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId);
828}
829
830void CGameContext::SendServerAlert(const char *pMessage)
831{
832 for(int ClientId = 0; ClientId < Server()->MaxClients(); ClientId++)
833 {
834 if(!m_apPlayers[ClientId])
835 {
836 continue;
837 }
838
839 if(m_apPlayers[ClientId]->GetClientVersion() >= VERSION_DDNET_IMPORTANT_ALERT)
840 {
841 CNetMsg_Sv_ServerAlert Msg;
842 Msg.m_pMessage = pMessage;
843 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId);
844 }
845 else
846 {
847 char aBroadcastText[1024 + 32];
848 str_copy(dst&: aBroadcastText, src: "SERVER ALERT\n\n");
849 str_append(dst&: aBroadcastText, src: pMessage);
850 SendBroadcast(pText: aBroadcastText, ClientId, IsImportant: true);
851 }
852 }
853
854 // Record server alert to demos exactly once
855 // TODO: Workaround https://github.com/ddnet/ddnet/issues/11144 by using client ID 0,
856 // otherwise the message is recorded multiple times.
857 CNetMsg_Sv_ServerAlert Msg;
858 Msg.m_pMessage = pMessage;
859 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_NOSEND, ClientId: 0);
860}
861
862void CGameContext::SendModeratorAlert(int ToClientId, const char *pMessage)
863{
864 dbg_assert(in_range(ToClientId, 0, MAX_CLIENTS - 1), "SendImportantAlert ToClientId invalid: %d", ToClientId);
865 dbg_assert(m_apPlayers[ToClientId] != nullptr, "Client not online: %d", ToClientId);
866
867 const int ClientVersion = m_apPlayers[ToClientId]->GetClientVersion();
868 if(ClientVersion >= VERSION_DDNET_IMPORTANT_ALERT)
869 {
870 CNetMsg_Sv_ModeratorAlert Msg;
871 Msg.m_pMessage = pMessage;
872 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId: ToClientId);
873
874 if(ClientVersion < VERSION_DDNET_IMPORTANT_ALERT_DUMMY_FIXED)
875 {
876 log_info("moderator_alert", "Notice: player uses an old client version and may not see moderator alerts: %s (ID %d)", Server()->ClientName(ToClientId), ToClientId);
877 }
878 }
879 else
880 {
881 char aBroadcastText[1024 + 32];
882 str_copy(dst&: aBroadcastText, src: "MODERATOR ALERT\n\n");
883 str_append(dst&: aBroadcastText, src: pMessage);
884 SendBroadcast(pText: aBroadcastText, ClientId: ToClientId, IsImportant: true);
885 log_info("moderator_alert", "Notice: player uses an old client version and may not see moderator alerts: %s (ID %d)", Server()->ClientName(ToClientId), ToClientId);
886 }
887}
888
889void CGameContext::SendBroadcast(const char *pText, int ClientId, bool IsImportant)
890{
891 CNetMsg_Sv_Broadcast Msg;
892 Msg.m_pMessage = pText;
893
894 if(ClientId == -1)
895 {
896 dbg_assert(IsImportant, "broadcast messages to all players must be important");
897 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId);
898
899 for(auto &pPlayer : m_apPlayers)
900 {
901 if(pPlayer)
902 {
903 pPlayer->m_LastBroadcastImportance = true;
904 pPlayer->m_LastBroadcast = Server()->Tick();
905 }
906 }
907 return;
908 }
909
910 if(!m_apPlayers[ClientId])
911 return;
912
913 if(!IsImportant && m_apPlayers[ClientId]->m_LastBroadcastImportance && m_apPlayers[ClientId]->m_LastBroadcast > Server()->Tick() - Server()->TickSpeed() * 10)
914 return;
915
916 // Broadcasts to individual players are not recorded in demos
917 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId);
918 m_apPlayers[ClientId]->m_LastBroadcast = Server()->Tick();
919 m_apPlayers[ClientId]->m_LastBroadcastImportance = IsImportant;
920}
921
922void CGameContext::SendRename7(int ClientId)
923{
924 dbg_assert(in_range(ClientId, 0, MAX_CLIENTS - 1), "Invalid ClientId: %d", ClientId);
925 dbg_assert(m_apPlayers[ClientId] != nullptr, "Client not online: %d", ClientId);
926
927 CPlayer *pPlayer = m_apPlayers[ClientId];
928
929 protocol7::CNetMsg_Sv_ClientDrop Drop;
930 Drop.m_ClientId = ClientId;
931 Drop.m_pReason = "";
932 Drop.m_Silent = true;
933
934 protocol7::CNetMsg_Sv_ClientInfo Info;
935 Info.m_ClientId = ClientId;
936 Info.m_pName = Server()->ClientName(ClientId);
937 Info.m_Country = Server()->ClientCountry(ClientId);
938 Info.m_pClan = Server()->ClientClan(ClientId);
939 Info.m_Local = 0;
940 Info.m_Silent = true;
941 Info.m_Team = pPlayer->GetTeam();
942
943 for(int p = 0; p < protocol7::NUM_SKINPARTS; p++)
944 {
945 Info.m_apSkinPartNames[p] = pPlayer->TeeInfos().m_aaSkinPartNames[p];
946 Info.m_aSkinPartColors[p] = pPlayer->TeeInfos().m_aSkinPartColors[p];
947 Info.m_aUseCustomColors[p] = pPlayer->TeeInfos().m_aUseCustomColors[p];
948 }
949
950 for(int i = 0; i < Server()->MaxClients(); i++)
951 {
952 if(i != ClientId)
953 {
954 Server()->SendPackMsg(pMsg: &Drop, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId: i);
955 Server()->SendPackMsg(pMsg: &Info, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId: i);
956 }
957 }
958}
959
960void CGameContext::SendSkinChange7(int ClientId)
961{
962 dbg_assert(in_range(ClientId, 0, MAX_CLIENTS - 1), "Invalid ClientId: %d", ClientId);
963 dbg_assert(m_apPlayers[ClientId] != nullptr, "Client not online: %d", ClientId);
964
965 const CTeeInfo &Info = m_apPlayers[ClientId]->TeeInfos();
966 protocol7::CNetMsg_Sv_SkinChange Msg;
967 Msg.m_ClientId = ClientId;
968 for(int Part = 0; Part < protocol7::NUM_SKINPARTS; Part++)
969 {
970 Msg.m_apSkinPartNames[Part] = Info.m_aaSkinPartNames[Part];
971 Msg.m_aSkinPartColors[Part] = Info.m_aSkinPartColors[Part];
972 Msg.m_aUseCustomColors[Part] = Info.m_aUseCustomColors[Part];
973 }
974
975 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId: -1);
976}
977
978void CGameContext::StartVote(const char *pDesc, const char *pCommand, const char *pReason, const char *pSixupDesc)
979{
980 // reset votes
981 m_VoteEnforce = VOTE_ENFORCE_UNKNOWN;
982 for(auto &pPlayer : m_apPlayers)
983 {
984 if(pPlayer)
985 {
986 pPlayer->m_Vote = 0;
987 pPlayer->m_VotePos = 0;
988 }
989 }
990
991 // start vote
992 m_VoteCloseTime = time_get() + time_freq() * g_Config.m_SvVoteTime;
993 str_copy(dst&: m_aVoteDescription, src: pDesc);
994 str_copy(dst&: m_aSixupVoteDescription, src: pSixupDesc);
995 str_copy(dst&: m_aVoteCommand, src: pCommand);
996 str_copy(dst&: m_aVoteReason, src: pReason);
997 SendVoteSet(ClientId: -1);
998 m_VoteUpdate = true;
999}
1000
1001void CGameContext::EndVote()
1002{
1003 m_VoteCloseTime = 0;
1004 SendVoteSet(ClientId: -1);
1005}
1006
1007void CGameContext::SendVoteSet(int ClientId)
1008{
1009 ::CNetMsg_Sv_VoteSet Msg6;
1010 protocol7::CNetMsg_Sv_VoteSet Msg7;
1011
1012 Msg7.m_ClientId = m_VoteCreator;
1013 if(m_VoteCloseTime)
1014 {
1015 Msg6.m_Timeout = Msg7.m_Timeout = (m_VoteCloseTime - time_get()) / time_freq();
1016 Msg6.m_pDescription = m_aVoteDescription;
1017 Msg6.m_pReason = Msg7.m_pReason = m_aVoteReason;
1018
1019 Msg7.m_pDescription = m_aSixupVoteDescription;
1020 if(IsKickVote())
1021 Msg7.m_Type = protocol7::VOTE_START_KICK;
1022 else if(IsSpecVote())
1023 Msg7.m_Type = protocol7::VOTE_START_SPEC;
1024 else if(IsOptionVote())
1025 Msg7.m_Type = protocol7::VOTE_START_OP;
1026 else
1027 Msg7.m_Type = protocol7::VOTE_UNKNOWN;
1028 }
1029 else
1030 {
1031 Msg6.m_Timeout = Msg7.m_Timeout = 0;
1032 Msg6.m_pDescription = Msg7.m_pDescription = "";
1033 Msg6.m_pReason = Msg7.m_pReason = "";
1034
1035 if(m_VoteEnforce == VOTE_ENFORCE_NO || m_VoteEnforce == VOTE_ENFORCE_NO_ADMIN)
1036 Msg7.m_Type = protocol7::VOTE_END_FAIL;
1037 else if(m_VoteEnforce == VOTE_ENFORCE_YES || m_VoteEnforce == VOTE_ENFORCE_YES_ADMIN)
1038 Msg7.m_Type = protocol7::VOTE_END_PASS;
1039 else if(m_VoteEnforce == VOTE_ENFORCE_ABORT || m_VoteEnforce == VOTE_ENFORCE_CANCEL)
1040 Msg7.m_Type = protocol7::VOTE_END_ABORT;
1041 else
1042 Msg7.m_Type = protocol7::VOTE_UNKNOWN;
1043
1044 if(m_VoteEnforce == VOTE_ENFORCE_NO_ADMIN || m_VoteEnforce == VOTE_ENFORCE_YES_ADMIN)
1045 Msg7.m_ClientId = -1;
1046 }
1047
1048 if(ClientId == -1)
1049 {
1050 for(int i = 0; i < Server()->MaxClients(); i++)
1051 {
1052 if(!m_apPlayers[i])
1053 continue;
1054 if(!Server()->IsSixup(ClientId: i))
1055 {
1056 Server()->SendPackMsg(pMsg: &Msg6, Flags: MSGFLAG_VITAL, ClientId: i);
1057 }
1058 else
1059 {
1060 // 0.7 clients need the client id in order to show the vote and the name of the caller, so its important that we get him in
1061 m_PlayerMapping.ForceInsertPlayer(Insert: m_VoteCreator, ClientId: i);
1062 Server()->SendPackMsg(pMsg: &Msg7, Flags: MSGFLAG_VITAL, ClientId: i);
1063 }
1064 }
1065 }
1066 else
1067 {
1068 if(!Server()->IsSixup(ClientId))
1069 {
1070 Server()->SendPackMsg(pMsg: &Msg6, Flags: MSGFLAG_VITAL, ClientId);
1071 }
1072 else
1073 {
1074 // 0.7 clients need the client id in order to show the vote and the name of the caller, so its important that we get him in
1075 m_PlayerMapping.ForceInsertPlayer(Insert: m_VoteCreator, ClientId);
1076 Server()->SendPackMsg(pMsg: &Msg7, Flags: MSGFLAG_VITAL, ClientId);
1077 }
1078 }
1079}
1080
1081void CGameContext::SendVoteStatus(int ClientId, int Total, int Yes, int No)
1082{
1083 if(ClientId == -1)
1084 {
1085 for(int i = 0; i < MAX_CLIENTS; ++i)
1086 if(Server()->ClientIngame(ClientId: i))
1087 SendVoteStatus(ClientId: i, Total, Yes, No);
1088 return;
1089 }
1090
1091 const int MaxClients = Server()->GetMaxClients(ClientId);
1092 if(Total > MaxClients && !Server()->ClientSupportsServerMaxClients(ClientId))
1093 {
1094 Yes = (Yes * MaxClients) / (float)Total;
1095 No = (No * MaxClients) / (float)Total;
1096 Total = MaxClients;
1097 }
1098
1099 CNetMsg_Sv_VoteStatus Msg = {.m_Yes: 0};
1100 Msg.m_Total = Total;
1101 Msg.m_Yes = Yes;
1102 Msg.m_No = No;
1103 Msg.m_Pass = Total - (Yes + No);
1104
1105 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId);
1106}
1107
1108void CGameContext::AbortVoteKickOnDisconnect(int ClientId)
1109{
1110 if(m_VoteCloseTime && ((str_startswith(str: m_aVoteCommand, prefix: "kick ") && str_toint(str: &m_aVoteCommand[5]) == ClientId) ||
1111 (str_startswith(str: m_aVoteCommand, prefix: "set_team ") && str_toint(str: &m_aVoteCommand[9]) == ClientId)))
1112 m_VoteEnforce = VOTE_ENFORCE_ABORT;
1113}
1114
1115void CGameContext::SendTuningParams(int ClientId, int Zone)
1116{
1117 if(ClientId == -1)
1118 {
1119 for(int i = 0; i < MAX_CLIENTS; ++i)
1120 {
1121 if(m_apPlayers[i])
1122 {
1123 if(m_apPlayers[i]->GetCharacter())
1124 {
1125 if(m_apPlayers[i]->GetCharacter()->m_TuneZone == Zone)
1126 SendTuningParams(ClientId: i, Zone);
1127 }
1128 else if(m_apPlayers[i]->m_TuneZone == Zone)
1129 {
1130 SendTuningParams(ClientId: i, Zone);
1131 }
1132 }
1133 }
1134 return;
1135 }
1136
1137 dbg_assert(0 <= ClientId && ClientId < MAX_CLIENTS, "Invalid ClientId: %d", ClientId);
1138 dbg_assert(m_apPlayers[ClientId], "client %d without player", ClientId);
1139
1140 CTuningParams Params = m_aTuningList[Zone];
1141
1142 CCharacter *pCharacter = m_apPlayers[ClientId]->GetCharacter();
1143 int NeededFakeTuning = pCharacter ? pCharacter->NeededFaketuning() : 0;
1144
1145 if(NeededFakeTuning & FAKETUNE_SOLO)
1146 {
1147 Params.m_PlayerCollision = 0;
1148 Params.m_PlayerHooking = 0;
1149 }
1150
1151 if(NeededFakeTuning & FAKETUNE_NOCOLL)
1152 {
1153 Params.m_PlayerCollision = 0;
1154 }
1155
1156 if(NeededFakeTuning & FAKETUNE_NOHOOK)
1157 {
1158 Params.m_PlayerHooking = 0;
1159 }
1160
1161 if(NeededFakeTuning & FAKETUNE_NOJUMP)
1162 {
1163 Params.m_GroundJumpImpulse = 0;
1164 }
1165
1166 if(NeededFakeTuning & FAKETUNE_JETPACK)
1167 {
1168 Params.m_JetpackStrength = 0;
1169 }
1170
1171 if(NeededFakeTuning & FAKETUNE_NOHAMMER)
1172 {
1173 Params.m_HammerStrength = 0;
1174 }
1175
1176 CMsgPacker Msg(NETMSGTYPE_SV_TUNEPARAMS);
1177 const int *pParams = Params.NetworkArray();
1178 for(int i = 0; i < CTuningParams::Num(); i++)
1179 {
1180 static_assert(offsetof(CTuningParams, m_LaserDamage) / sizeof(CTuneParam) == 30);
1181 if(i == 30 && Server()->IsSixup(ClientId)) // laser_damage was removed in 0.7
1182 {
1183 continue;
1184 }
1185 Msg.AddInt(i: pParams[i]);
1186 }
1187 Server()->SendMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId);
1188}
1189
1190void CGameContext::OnPreTickTeehistorian()
1191{
1192 if(!m_TeeHistorianActive)
1193 return;
1194
1195 for(int i = 0; i < MAX_CLIENTS; i++)
1196 {
1197 if(m_apPlayers[i] != nullptr)
1198 m_TeeHistorian.RecordPlayerTeam(ClientId: i, Team: GetDDRaceTeam(ClientId: i));
1199 else
1200 m_TeeHistorian.RecordPlayerTeam(ClientId: i, Team: 0);
1201 }
1202 for(int i = 0; i < TEAM_SUPER; i++)
1203 {
1204 m_TeeHistorian.RecordTeamPractice(Team: i, Practice: m_pController->Teams().IsPractice(Team: i));
1205 }
1206}
1207
1208void CGameContext::OnTick()
1209{
1210 if(m_TeeHistorianActive)
1211 {
1212 int Error = aio_error(aio: m_pTeeHistorianFile);
1213 if(Error)
1214 {
1215 dbg_msg(sys: "teehistorian", fmt: "error writing to file, err=%d", Error);
1216 Server()->SetErrorShutdown("teehistorian io error");
1217 }
1218
1219 if(!m_TeeHistorian.Starting())
1220 {
1221 m_TeeHistorian.EndInputs();
1222 m_TeeHistorian.EndTick();
1223 }
1224 m_TeeHistorian.BeginTick(Tick: Server()->Tick());
1225 m_TeeHistorian.BeginPlayers();
1226 }
1227
1228 // copy tuning
1229 *m_World.GetTuning(i: 0) = m_aTuningList[0];
1230 m_World.Tick();
1231 m_PlayerMapping.Tick();
1232
1233 m_pController->Tick();
1234
1235 for(int i = 0; i < MAX_CLIENTS; i++)
1236 {
1237 if(m_apPlayers[i])
1238 {
1239 IServer::CClientInfo Info;
1240 if(m_apPlayers[i]->m_DDNetVersionKickTick > 0 && Server()->Tick() >= m_apPlayers[i]->m_DDNetVersionKickTick && !Server()->IsSixup(ClientId: i) &&
1241 Server()->GetClientInfo(ClientId: i, pInfo: &Info) && Info.m_DDNetVersion < VERSION_DDNET_OLD)
1242 {
1243 if(!g_Config.m_SvVanillaConnections)
1244 {
1245 Server()->Kick(ClientId: i, pReason: "Old Teeworlds 0.6 versions are unsupported. Use DDNet client or Teeworlds 0.7");
1246 continue;
1247 }
1248 m_apPlayers[i]->m_DDNetVersionKickTick = -1;
1249 }
1250
1251 // send vote options
1252 ProgressVoteOptions(ClientId: i);
1253
1254 m_apPlayers[i]->Tick();
1255 m_apPlayers[i]->PostTick();
1256 }
1257 }
1258
1259 for(auto &pPlayer : m_apPlayers)
1260 {
1261 if(pPlayer)
1262 pPlayer->PostPostTick();
1263 }
1264
1265 // update voting
1266 if(m_VoteCloseTime)
1267 {
1268 // abort the kick-vote on player-leave
1269 if(m_VoteEnforce == VOTE_ENFORCE_ABORT)
1270 {
1271 SendChat(ChatterClientId: -1, Team: TEAM_ALL, pText: "Vote aborted");
1272 EndVote();
1273 }
1274 else if(m_VoteEnforce == VOTE_ENFORCE_CANCEL)
1275 {
1276 char aBuf[64];
1277 if(m_VoteCreator == -1)
1278 {
1279 str_copy(dst&: aBuf, src: "Vote canceled");
1280 }
1281 else
1282 {
1283 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "'%s' canceled their vote", Server()->ClientName(ClientId: m_VoteCreator));
1284 }
1285 SendChat(ChatterClientId: -1, Team: TEAM_ALL, pText: aBuf);
1286 EndVote();
1287 }
1288 else
1289 {
1290 int Total = 0, Yes = 0, No = 0;
1291 bool Veto = false, VetoStop = false;
1292 if(m_VoteUpdate)
1293 {
1294 // count votes
1295 const NETADDR *apAddresses[MAX_CLIENTS] = {nullptr};
1296 const NETADDR *pFirstAddress = nullptr;
1297 bool SinglePlayer = true;
1298 for(int i = 0; i < MAX_CLIENTS; i++)
1299 {
1300 if(m_apPlayers[i])
1301 {
1302 apAddresses[i] = Server()->ClientAddr(ClientId: i);
1303 if(!pFirstAddress)
1304 {
1305 pFirstAddress = apAddresses[i];
1306 }
1307 else if(SinglePlayer && net_addr_comp_noport(a: pFirstAddress, b: apAddresses[i]) != 0)
1308 {
1309 SinglePlayer = false;
1310 }
1311 }
1312 }
1313
1314 // remember checked players, only the first player with a specific ip will be handled
1315 bool aVoteChecked[MAX_CLIENTS] = {false};
1316 int64_t Now = Server()->Tick();
1317 for(int i = 0; i < MAX_CLIENTS; i++)
1318 {
1319 if(!m_apPlayers[i] || aVoteChecked[i])
1320 continue;
1321
1322 if((IsKickVote() || IsSpecVote()) && (m_apPlayers[i]->GetTeam() == TEAM_SPECTATORS ||
1323 (GetPlayerChar(ClientId: m_VoteCreator) && GetPlayerChar(ClientId: i) &&
1324 GetPlayerChar(ClientId: m_VoteCreator)->Team() != GetPlayerChar(ClientId: i)->Team())))
1325 continue;
1326
1327 if(m_apPlayers[i]->IsAfk() && i != m_VoteCreator)
1328 continue;
1329
1330 // can't vote in kick and spec votes in the beginning after joining
1331 if((IsKickVote() || IsSpecVote()) && Now < m_apPlayers[i]->m_FirstVoteTick)
1332 continue;
1333
1334 // connecting clients with spoofed ips can clog slots without being ingame
1335 if(!Server()->ClientIngame(ClientId: i))
1336 continue;
1337
1338 // don't count votes by blacklisted clients
1339 if(g_Config.m_SvDnsblVote && !m_pServer->DnsblWhite(ClientId: i) && !SinglePlayer)
1340 continue;
1341
1342 int CurVote = m_apPlayers[i]->m_Vote;
1343 int CurVotePos = m_apPlayers[i]->m_VotePos;
1344
1345 // only allow IPs to vote once, but keep veto ability
1346 // check for more players with the same ip (only use the vote of the one who voted first)
1347 for(int j = i + 1; j < MAX_CLIENTS; j++)
1348 {
1349 if(!m_apPlayers[j] || aVoteChecked[j] || net_addr_comp_noport(a: apAddresses[j], b: apAddresses[i]) != 0)
1350 continue;
1351
1352 // count the latest vote by this ip
1353 if(CurVotePos < m_apPlayers[j]->m_VotePos)
1354 {
1355 CurVote = m_apPlayers[j]->m_Vote;
1356 CurVotePos = m_apPlayers[j]->m_VotePos;
1357 }
1358
1359 aVoteChecked[j] = true;
1360 }
1361
1362 Total++;
1363 if(CurVote > 0)
1364 Yes++;
1365 else if(CurVote < 0)
1366 No++;
1367
1368 // veto right for players who have been active on server for long and who're not afk
1369 if(!IsKickVote() && !IsSpecVote() && g_Config.m_SvVoteVetoTime)
1370 {
1371 // look through all players with same IP again, including the current player
1372 for(int j = i; j < MAX_CLIENTS; j++)
1373 {
1374 // no need to check ip address of current player
1375 if(i != j && (!m_apPlayers[j] || net_addr_comp_noport(a: apAddresses[j], b: apAddresses[i]) != 0))
1376 continue;
1377
1378 if(m_apPlayers[j] && !m_apPlayers[j]->IsAfk() && m_apPlayers[j]->GetTeam() != TEAM_SPECTATORS &&
1379 ((Server()->Tick() - m_apPlayers[j]->m_JoinTick) / (Server()->TickSpeed() * 60) > g_Config.m_SvVoteVetoTime ||
1380 (m_apPlayers[j]->GetCharacter() && m_apPlayers[j]->GetCharacter()->m_DDRaceState == ERaceState::STARTED &&
1381 (Server()->Tick() - m_apPlayers[j]->GetCharacter()->m_StartTime) / (Server()->TickSpeed() * 60) > g_Config.m_SvVoteVetoTime)))
1382 {
1383 if(CurVote == 0)
1384 Veto = true;
1385 else if(CurVote < 0)
1386 VetoStop = true;
1387 break;
1388 }
1389 }
1390 }
1391 }
1392
1393 if(g_Config.m_SvVoteMaxTotal && Total > g_Config.m_SvVoteMaxTotal &&
1394 (IsKickVote() || IsSpecVote()))
1395 Total = g_Config.m_SvVoteMaxTotal;
1396
1397 if((Yes > Total / (100.0f / g_Config.m_SvVoteYesPercentage)) && !Veto)
1398 m_VoteEnforce = VOTE_ENFORCE_YES;
1399 else if(No >= Total - Total / (100.0f / g_Config.m_SvVoteYesPercentage))
1400 m_VoteEnforce = VOTE_ENFORCE_NO;
1401
1402 if(VetoStop)
1403 m_VoteEnforce = VOTE_ENFORCE_NO;
1404
1405 m_VoteWillPass = Yes > (Yes + No) / (100.0f / g_Config.m_SvVoteYesPercentage);
1406 }
1407
1408 if(time_get() > m_VoteCloseTime && !g_Config.m_SvVoteMajority)
1409 m_VoteEnforce = (m_VoteWillPass && !Veto) ? VOTE_ENFORCE_YES : VOTE_ENFORCE_NO;
1410
1411 // / Ensure minimum time for vote to end when moderating.
1412 if(m_VoteEnforce == VOTE_ENFORCE_YES && !(PlayerModerating() &&
1413 (IsKickVote() || IsSpecVote()) && time_get() < m_VoteCloseTime))
1414 {
1415 Server()->SetRconCid(IServer::RCON_CID_VOTE);
1416 Console()->ExecuteLine(pStr: m_aVoteCommand, ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
1417 Server()->SetRconCid(IServer::RCON_CID_SERV);
1418 EndVote();
1419 SendChat(ChatterClientId: -1, Team: TEAM_ALL, pText: "Vote passed", SpamProtectionClientId: -1, VersionFlags: FLAG_SIX);
1420
1421 if(m_VoteCreator != -1 && m_apPlayers[m_VoteCreator] && !IsKickVote() && !IsSpecVote())
1422 m_apPlayers[m_VoteCreator]->m_LastVoteCall = 0;
1423 }
1424 else if(m_VoteEnforce == VOTE_ENFORCE_YES_ADMIN)
1425 {
1426 Server()->SetRconCid(IServer::RCON_CID_VOTE);
1427 Console()->ExecuteLine(pStr: m_aVoteCommand, ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
1428 Server()->SetRconCid(IServer::RCON_CID_SERV);
1429 EndVote();
1430 SendChat(ChatterClientId: -1, Team: TEAM_ALL, pText: "Vote passed enforced by authorized player", SpamProtectionClientId: -1, VersionFlags: FLAG_SIX);
1431
1432 if(m_VoteCreator != -1 && m_apPlayers[m_VoteCreator])
1433 m_apPlayers[m_VoteCreator]->m_LastVoteCall = 0;
1434 }
1435 else if(m_VoteEnforce == VOTE_ENFORCE_NO_ADMIN)
1436 {
1437 EndVote();
1438 SendChat(ChatterClientId: -1, Team: TEAM_ALL, pText: "Vote failed enforced by authorized player", SpamProtectionClientId: -1, VersionFlags: FLAG_SIX);
1439 }
1440 else if(m_VoteEnforce == VOTE_ENFORCE_NO || (time_get() > m_VoteCloseTime && g_Config.m_SvVoteMajority))
1441 {
1442 EndVote();
1443 if(VetoStop || (m_VoteWillPass && Veto))
1444 SendChat(ChatterClientId: -1, Team: TEAM_ALL, pText: "Vote failed because of veto. Find an empty server instead", SpamProtectionClientId: -1, VersionFlags: FLAG_SIX);
1445 else
1446 SendChat(ChatterClientId: -1, Team: TEAM_ALL, pText: "Vote failed", SpamProtectionClientId: -1, VersionFlags: FLAG_SIX);
1447 }
1448 else if(m_VoteUpdate)
1449 {
1450 m_VoteUpdate = false;
1451 SendVoteStatus(ClientId: -1, Total, Yes, No);
1452 }
1453 }
1454 }
1455
1456 if(Server()->Tick() % (Server()->TickSpeed() / 2) == 0)
1457 {
1458 m_Mutes.UnmuteExpired();
1459 m_VoteMutes.UnmuteExpired();
1460 }
1461
1462 if(Server()->Tick() % (g_Config.m_SvAnnouncementInterval * Server()->TickSpeed() * 60) == 0)
1463 {
1464 const char *pLine = Server()->GetAnnouncementLine();
1465 if(pLine)
1466 SendChat(ChatterClientId: -1, Team: TEAM_ALL, pText: pLine);
1467 }
1468
1469 for(auto &Switcher : Switchers())
1470 {
1471 for(int j = 0; j < NUM_DDRACE_TEAMS; ++j)
1472 {
1473 if(Switcher.m_aEndTick[j] <= Server()->Tick() && Switcher.m_aType[j] == TILE_SWITCHTIMEDOPEN)
1474 {
1475 Switcher.m_aStatus[j] = false;
1476 Switcher.m_aEndTick[j] = 0;
1477 Switcher.m_aType[j] = TILE_SWITCHCLOSE;
1478 }
1479 else if(Switcher.m_aEndTick[j] <= Server()->Tick() && Switcher.m_aType[j] == TILE_SWITCHTIMEDCLOSE)
1480 {
1481 Switcher.m_aStatus[j] = true;
1482 Switcher.m_aEndTick[j] = 0;
1483 Switcher.m_aType[j] = TILE_SWITCHOPEN;
1484 }
1485 }
1486 }
1487
1488 if(m_SqlRandomMapResult != nullptr && m_SqlRandomMapResult->m_Completed)
1489 {
1490 if(m_SqlRandomMapResult->m_Success)
1491 {
1492 if(m_SqlRandomMapResult->m_ClientId != -1 && m_apPlayers[m_SqlRandomMapResult->m_ClientId] && m_SqlRandomMapResult->m_aMessage[0] != '\0')
1493 SendChat(ChatterClientId: -1, Team: TEAM_ALL, pText: m_SqlRandomMapResult->m_aMessage);
1494 if(m_SqlRandomMapResult->m_aMap[0] != '\0')
1495 Server()->ChangeMap(pMap: m_SqlRandomMapResult->m_aMap);
1496 else
1497 m_LastMapVote = 0;
1498 }
1499 m_SqlRandomMapResult = nullptr;
1500 }
1501
1502 // check for map info result from database
1503 if(m_pLoadMapInfoResult != nullptr && m_pLoadMapInfoResult->m_Completed)
1504 {
1505 if(m_pLoadMapInfoResult->m_Success && m_pLoadMapInfoResult->m_Data.m_aaMessages[0][0] != '\0')
1506 {
1507 str_copy(dst&: m_aMapInfoMessage, src: m_pLoadMapInfoResult->m_Data.m_aaMessages[0]);
1508 CNetMsg_Sv_MapInfo MapInfoMsg;
1509 MapInfoMsg.m_pDescription = m_aMapInfoMessage;
1510 Server()->SendPackMsg(pMsg: &MapInfoMsg, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId: -1);
1511 }
1512 m_pLoadMapInfoResult = nullptr;
1513 }
1514
1515 // Record player position at the end of the tick
1516 if(m_TeeHistorianActive)
1517 {
1518 for(int i = 0; i < MAX_CLIENTS; i++)
1519 {
1520 if(m_apPlayers[i] && m_apPlayers[i]->GetCharacter())
1521 {
1522 CNetObj_CharacterCore Char;
1523 m_apPlayers[i]->GetCharacter()->GetCore().Write(pObjCore: &Char);
1524 m_TeeHistorian.RecordPlayer(ClientId: i, pChar: &Char);
1525 }
1526 else
1527 {
1528 m_TeeHistorian.RecordDeadPlayer(ClientId: i);
1529 }
1530 }
1531 m_TeeHistorian.EndPlayers();
1532 m_TeeHistorian.BeginInputs();
1533 }
1534 // Warning: do not put code in this function directly above or below this comment
1535}
1536
1537void CGameContext::PreInputClients(int ClientId, bool *pClients)
1538{
1539 if(!pClients || !m_apPlayers[ClientId])
1540 return;
1541
1542 CCharacter *pInputChr = m_apPlayers[ClientId]->GetCharacter();
1543 if(!pInputChr || m_apPlayers[ClientId]->GetTeam() == TEAM_SPECTATORS || m_apPlayers[ClientId]->IsAfk())
1544 return;
1545
1546 const int Team = GetDDRaceTeam(ClientId);
1547
1548 for(int Id = 0; Id < MAX_CLIENTS; Id++)
1549 {
1550 if(ClientId == Id)
1551 continue;
1552
1553 CPlayer *pPlayer = m_apPlayers[Id];
1554 if(!pPlayer)
1555 continue;
1556
1557 if(pPlayer->GetTeam() == TEAM_SPECTATORS || Team != GetDDRaceTeam(ClientId: Id) || pPlayer->IsAfk())
1558 continue;
1559
1560 if(Server()->GetClientVersion(ClientId: Id) < VERSION_DDNET_PREINPUT)
1561 continue;
1562
1563 if(!pInputChr->CanSnapCharacter(SnappingClient: Id) || pInputChr->NetworkClipped(SnappingClient: Id))
1564 continue;
1565
1566 pClients[Id] = true;
1567 }
1568}
1569
1570// Server hooks
1571void CGameContext::OnClientPrepareInput(int ClientId, void *pInput)
1572{
1573 CNetObj_PlayerInput *pPlayerInput = static_cast<CNetObj_PlayerInput *>(pInput);
1574
1575 if(Server()->IsSixup(ClientId))
1576 pPlayerInput->m_PlayerFlags = PlayerFlags_SevenToSix(Flags: pPlayerInput->m_PlayerFlags);
1577
1578 constexpr int MaxTarget = 1 << 20;
1579 pPlayerInput->m_TargetX = std::clamp(val: pPlayerInput->m_TargetX, lo: -MaxTarget, hi: MaxTarget);
1580 pPlayerInput->m_TargetY = std::clamp(val: pPlayerInput->m_TargetY, lo: -MaxTarget, hi: MaxTarget);
1581
1582 if(pPlayerInput->m_WantedWeapon < 0 || pPlayerInput->m_WantedWeapon > NUM_WEAPONS)
1583 pPlayerInput->m_WantedWeapon = 0;
1584}
1585
1586void CGameContext::OnClientDirectInput(int ClientId, const void *pInput)
1587{
1588 const CNetObj_PlayerInput *pPlayerInput = static_cast<const CNetObj_PlayerInput *>(pInput);
1589
1590 if(!m_pController->IsGamePaused())
1591 m_apPlayers[ClientId]->OnDirectInput(pNewInput: pPlayerInput);
1592
1593 int Flags = pPlayerInput->m_PlayerFlags;
1594 if((Flags & 256) || (Flags & 512))
1595 {
1596 Server()->Kick(ClientId, pReason: "please update your client or use DDNet client");
1597 }
1598}
1599
1600void CGameContext::OnClientPredictedInput(int ClientId, const void *pInput)
1601{
1602 const CNetObj_PlayerInput *pApplyInput = static_cast<const CNetObj_PlayerInput *>(pInput);
1603
1604 if(pApplyInput == nullptr)
1605 {
1606 // early return if no input at all has been sent by a player
1607 if(!m_aPlayerHasInput[ClientId])
1608 {
1609 return;
1610 }
1611 // set to last sent input when no new input has been sent
1612 pApplyInput = &m_aLastPlayerInput[ClientId];
1613 }
1614
1615 if(!m_pController->IsGamePaused())
1616 m_apPlayers[ClientId]->OnPredictedInput(pNewInput: pApplyInput);
1617}
1618
1619void CGameContext::OnClientPredictedEarlyInput(int ClientId, const void *pInput)
1620{
1621 const CNetObj_PlayerInput *pApplyInput = static_cast<const CNetObj_PlayerInput *>(pInput);
1622
1623 if(pApplyInput == nullptr)
1624 {
1625 // early return if no input at all has been sent by a player
1626 if(!m_aPlayerHasInput[ClientId])
1627 {
1628 return;
1629 }
1630 // set to last sent input when no new input has been sent
1631 pApplyInput = &m_aLastPlayerInput[ClientId];
1632 }
1633 else
1634 {
1635 // Store input in this function and not in `OnClientPredictedInput`,
1636 // because this function is called on all inputs, while
1637 // `OnClientPredictedInput` is only called on the first input of each
1638 // tick.
1639 mem_copy(dest: &m_aLastPlayerInput[ClientId], source: pApplyInput, size: sizeof(m_aLastPlayerInput[ClientId]));
1640 m_aPlayerHasInput[ClientId] = true;
1641 }
1642
1643 if(!m_pController->IsGamePaused())
1644 m_apPlayers[ClientId]->OnPredictedEarlyInput(pNewInput: pApplyInput);
1645
1646 if(m_TeeHistorianActive)
1647 {
1648 m_TeeHistorian.RecordPlayerInput(ClientId, UniqueClientId: m_apPlayers[ClientId]->GetUniqueCid(), pInput: pApplyInput);
1649 }
1650}
1651
1652void CGameContext::ProgressVoteOptions(int ClientId)
1653{
1654 CPlayer *pPl = m_apPlayers[ClientId];
1655
1656 if(pPl->m_SendVoteIndex == -1)
1657 return; // we didn't start sending options yet
1658
1659 if(pPl->m_SendVoteIndex > m_NumVoteOptions)
1660 return; // shouldn't happen / fail silently
1661
1662 int VotesLeft = m_NumVoteOptions - pPl->m_SendVoteIndex;
1663 int NumVotesToSend = std::min(a: g_Config.m_SvSendVotesPerTick, b: VotesLeft);
1664
1665 if(!VotesLeft)
1666 {
1667 // player has up to date vote option list
1668 return;
1669 }
1670
1671 // build vote option list msg
1672 int CurIndex = 0;
1673
1674 CNetMsg_Sv_VoteOptionListAdd OptionMsg;
1675 OptionMsg.m_pDescription0 = "";
1676 OptionMsg.m_pDescription1 = "";
1677 OptionMsg.m_pDescription2 = "";
1678 OptionMsg.m_pDescription3 = "";
1679 OptionMsg.m_pDescription4 = "";
1680 OptionMsg.m_pDescription5 = "";
1681 OptionMsg.m_pDescription6 = "";
1682 OptionMsg.m_pDescription7 = "";
1683 OptionMsg.m_pDescription8 = "";
1684 OptionMsg.m_pDescription9 = "";
1685 OptionMsg.m_pDescription10 = "";
1686 OptionMsg.m_pDescription11 = "";
1687 OptionMsg.m_pDescription12 = "";
1688 OptionMsg.m_pDescription13 = "";
1689 OptionMsg.m_pDescription14 = "";
1690
1691 const CVoteOptionServer *pCurrent;
1692 if(pPl->m_SendVoteIndex == 0)
1693 pCurrent = m_pVoteOptionFirst;
1694 else
1695 pCurrent = pPl->m_pLastSentVoteOption == nullptr ? nullptr : pPl->m_pLastSentVoteOption->m_pNext;
1696
1697 while(CurIndex < NumVotesToSend && pCurrent != nullptr)
1698 {
1699 switch(CurIndex)
1700 {
1701 case 0: OptionMsg.m_pDescription0 = pCurrent->m_aDescription; break;
1702 case 1: OptionMsg.m_pDescription1 = pCurrent->m_aDescription; break;
1703 case 2: OptionMsg.m_pDescription2 = pCurrent->m_aDescription; break;
1704 case 3: OptionMsg.m_pDescription3 = pCurrent->m_aDescription; break;
1705 case 4: OptionMsg.m_pDescription4 = pCurrent->m_aDescription; break;
1706 case 5: OptionMsg.m_pDescription5 = pCurrent->m_aDescription; break;
1707 case 6: OptionMsg.m_pDescription6 = pCurrent->m_aDescription; break;
1708 case 7: OptionMsg.m_pDescription7 = pCurrent->m_aDescription; break;
1709 case 8: OptionMsg.m_pDescription8 = pCurrent->m_aDescription; break;
1710 case 9: OptionMsg.m_pDescription9 = pCurrent->m_aDescription; break;
1711 case 10: OptionMsg.m_pDescription10 = pCurrent->m_aDescription; break;
1712 case 11: OptionMsg.m_pDescription11 = pCurrent->m_aDescription; break;
1713 case 12: OptionMsg.m_pDescription12 = pCurrent->m_aDescription; break;
1714 case 13: OptionMsg.m_pDescription13 = pCurrent->m_aDescription; break;
1715 case 14: OptionMsg.m_pDescription14 = pCurrent->m_aDescription; break;
1716 }
1717
1718 pPl->m_pLastSentVoteOption = pCurrent;
1719 CurIndex++;
1720 pCurrent = pCurrent->m_pNext;
1721 }
1722
1723 // send msg
1724 if(pPl->m_SendVoteIndex == 0)
1725 {
1726 CNetMsg_Sv_VoteOptionGroupStart StartMsg;
1727 Server()->SendPackMsg(pMsg: &StartMsg, Flags: MSGFLAG_VITAL, ClientId);
1728 }
1729
1730 OptionMsg.m_NumOptions = NumVotesToSend;
1731 Server()->SendPackMsg(pMsg: &OptionMsg, Flags: MSGFLAG_VITAL, ClientId);
1732
1733 pPl->m_SendVoteIndex += NumVotesToSend;
1734
1735 if(pPl->m_SendVoteIndex == m_NumVoteOptions)
1736 {
1737 CNetMsg_Sv_VoteOptionGroupEnd EndMsg;
1738 Server()->SendPackMsg(pMsg: &EndMsg, Flags: MSGFLAG_VITAL, ClientId);
1739 }
1740}
1741
1742void CGameContext::OnClientEnter(int ClientId)
1743{
1744 if(m_TeeHistorianActive)
1745 {
1746 m_TeeHistorian.RecordPlayerReady(ClientId);
1747 }
1748 m_pController->OnPlayerConnect(pPlayer: m_apPlayers[ClientId]);
1749
1750 IServer::CClientInfo Info;
1751 if(Server()->GetClientInfo(ClientId, pInfo: &Info))
1752 {
1753 // 0.7 clients can send ddnet message, F-Client does that for example
1754 if(Info.m_GotDDNetVersion)
1755 {
1756 if(OnClientDDNetVersionKnown(ClientId))
1757 {
1758 return; // kicked
1759 }
1760 }
1761 }
1762
1763 if(!Server()->ClientPrevIngame(ClientId))
1764 {
1765 if(g_Config.m_SvWelcome[0] != 0)
1766 SendChatTarget(To: ClientId, pText: g_Config.m_SvWelcome);
1767
1768 if(g_Config.m_SvShowOthersDefault > SHOW_OTHERS_OFF)
1769 {
1770 if(g_Config.m_SvShowOthers)
1771 SendChatTarget(To: ClientId, pText: "You can see other players. To disable this use DDNet client and type /showothers");
1772
1773 m_apPlayers[ClientId]->m_ShowOthers = g_Config.m_SvShowOthersDefault;
1774 }
1775 }
1776 m_VoteUpdate = true;
1777
1778 // the player map has to be initialized before anything can be mapped into it
1779 m_PlayerMapping.InitPlayerMap(ClientId);
1780
1781 SendStartMessages(ClientId);
1782
1783 Server()->ExpireServerInfo();
1784
1785 // send map info if loaded from database
1786 if(m_aMapInfoMessage[0] != '\0')
1787 {
1788 CNetMsg_Sv_MapInfo MapInfoMsg;
1789 MapInfoMsg.m_pDescription = m_aMapInfoMessage;
1790 Server()->SendPackMsg(pMsg: &MapInfoMsg, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId);
1791 }
1792
1793 mem_zero(block: &m_aLastPlayerInput[ClientId], size: sizeof(m_aLastPlayerInput[ClientId]));
1794 m_aPlayerHasInput[ClientId] = false;
1795
1796 // initial chat delay
1797 if(g_Config.m_SvChatInitialDelay != 0 && m_apPlayers[ClientId]->m_JoinTick > m_NonEmptySince + 10 * Server()->TickSpeed())
1798 {
1799 char aBuf[128];
1800 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "This server has an initial chat delay, you will need to wait %d seconds before talking.", g_Config.m_SvChatInitialDelay);
1801 SendChatTarget(To: ClientId, pText: aBuf);
1802 m_Mutes.Mute(pAddr: Server()->ClientAddr(ClientId), Seconds: g_Config.m_SvChatInitialDelay, pReason: "Initial chat delay", pClientName: Server()->ClientName(ClientId), InitialDelay: true);
1803 }
1804
1805 LogEvent(Description: "Connect", ClientId);
1806}
1807
1808bool CGameContext::OnClientDataPersist(int ClientId, void *pData)
1809{
1810 CPersistentClientData *pPersistent = (CPersistentClientData *)pData;
1811 if(!m_apPlayers[ClientId])
1812 {
1813 return false;
1814 }
1815 new(pPersistent) CPersistentClientData();
1816 pPersistent->m_IsSpectator = m_apPlayers[ClientId]->GetTeam() == TEAM_SPECTATORS;
1817 pPersistent->m_IsAfk = m_apPlayers[ClientId]->IsAfk();
1818 pPersistent->m_LastWhisperTo = m_apPlayers[ClientId]->m_LastWhisperTo;
1819 return true;
1820}
1821
1822void CGameContext::OnClientConnected(int ClientId, void *pData)
1823{
1824 CPersistentClientData *pPersistentData = (CPersistentClientData *)pData;
1825 bool Spec = false;
1826 bool Afk = true;
1827 int LastWhisperTo = -1;
1828 if(pPersistentData)
1829 {
1830 Spec = pPersistentData->m_IsSpectator;
1831 Afk = pPersistentData->m_IsAfk;
1832 LastWhisperTo = pPersistentData->m_LastWhisperTo;
1833 }
1834 else
1835 {
1836 // new player connected, clear whispers waiting for the old player with this id
1837 for(auto &pPlayer : m_apPlayers)
1838 {
1839 if(pPlayer && pPlayer->m_LastWhisperTo == ClientId)
1840 pPlayer->m_LastWhisperTo = -1;
1841 }
1842 }
1843
1844 {
1845 bool Empty = true;
1846 for(auto &pPlayer : m_apPlayers)
1847 {
1848 // connecting clients with spoofed ips can clog slots without being ingame
1849 if(pPlayer && Server()->ClientIngame(ClientId: pPlayer->GetCid()))
1850 {
1851 Empty = false;
1852 break;
1853 }
1854 }
1855 if(Empty)
1856 {
1857 m_NonEmptySince = Server()->Tick();
1858 }
1859 }
1860
1861 // Check which team the player should be on
1862 const int StartTeam = (Spec || g_Config.m_SvTournamentMode) ? TEAM_SPECTATORS : m_pController->GetAutoTeam(NotThisId: ClientId);
1863 CreatePlayer(ClientId, StartTeam, Afk, LastWhisperTo);
1864
1865 SendMotd(ClientId);
1866 SendSettings(ClientId);
1867
1868 Server()->ExpireServerInfo();
1869}
1870
1871void CGameContext::OnClientInfoChange(int ClientId)
1872{
1873 if(m_apPlayers[ClientId])
1874 m_apPlayers[ClientId]->InvalidateClientInfo();
1875}
1876
1877void CGameContext::OnClientDrop(int ClientId, const char *pReason)
1878{
1879 LogEvent(Description: "Disconnect", ClientId);
1880
1881 AbortVoteKickOnDisconnect(ClientId);
1882 m_pController->OnPlayerDisconnect(pPlayer: m_apPlayers[ClientId], pReason);
1883 delete m_apPlayers[ClientId];
1884 m_apPlayers[ClientId] = nullptr;
1885
1886 delete m_apSavedTees[ClientId];
1887 m_apSavedTees[ClientId] = nullptr;
1888
1889 const int SavedTeam = m_aTeamMapping[ClientId];
1890 m_aTeamMapping[ClientId] = -1;
1891 if(SavedTeam != -1)
1892 {
1893 bool TeamStillPending = false;
1894 for(int MappedTeam : m_aTeamMapping)
1895 TeamStillPending |= MappedTeam == SavedTeam;
1896 if(!TeamStillPending)
1897 {
1898 delete m_apSavedTeams[SavedTeam];
1899 m_apSavedTeams[SavedTeam] = nullptr;
1900 }
1901 }
1902
1903 if(g_Config.m_SvTeam == SV_TEAM_FORCED_SOLO && PracticeByDefault())
1904 m_pController->Teams().SetPractice(Team: GetDDRaceTeam(ClientId), Enabled: true);
1905
1906 m_VoteUpdate = true;
1907 if(m_VoteCreator == ClientId)
1908 {
1909 m_VoteCreator = -1;
1910 }
1911
1912 // update spectator modes
1913 for(auto &pPlayer : m_apPlayers)
1914 {
1915 if(pPlayer && pPlayer->SpectatorId() == ClientId)
1916 pPlayer->SetSpectatorId(SPEC_FREEVIEW);
1917 }
1918
1919 // update conversation targets
1920 for(auto &pPlayer : m_apPlayers)
1921 {
1922 if(pPlayer && pPlayer->m_LastWhisperTo == ClientId)
1923 pPlayer->m_LastWhisperTo = -1;
1924 }
1925
1926 protocol7::CNetMsg_Sv_ClientDrop Msg;
1927 Msg.m_ClientId = ClientId;
1928 Msg.m_pReason = pReason;
1929 Msg.m_Silent = true;
1930 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId: -1);
1931
1932 Server()->ExpireServerInfo();
1933}
1934
1935void CGameContext::TeehistorianRecordAntibot(const void *pData, int DataSize)
1936{
1937 if(m_TeeHistorianActive)
1938 {
1939 m_TeeHistorian.RecordAntibot(pData, DataSize);
1940 }
1941}
1942
1943void CGameContext::TeehistorianRecordPlayerJoin(int ClientId, bool Sixup)
1944{
1945 if(m_TeeHistorianActive)
1946 {
1947 m_TeeHistorian.RecordPlayerJoin(ClientId, Protocol: !Sixup ? CTeeHistorian::PROTOCOL_6 : CTeeHistorian::PROTOCOL_7);
1948 }
1949}
1950
1951void CGameContext::TeehistorianRecordPlayerDrop(int ClientId, const char *pReason)
1952{
1953 if(m_TeeHistorianActive)
1954 {
1955 m_TeeHistorian.RecordPlayerDrop(ClientId, pReason);
1956 }
1957}
1958
1959void CGameContext::TeehistorianRecordPlayerRejoin(int ClientId)
1960{
1961 if(m_TeeHistorianActive)
1962 {
1963 m_TeeHistorian.RecordPlayerRejoin(ClientId);
1964 }
1965}
1966
1967void CGameContext::TeehistorianRecordPlayerName(int ClientId, const char *pName)
1968{
1969 if(m_TeeHistorianActive)
1970 {
1971 m_TeeHistorian.RecordPlayerName(ClientId, pName);
1972 }
1973}
1974
1975void CGameContext::TeehistorianRecordPlayerFinish(int ClientId, int TimeTicks)
1976{
1977 if(m_TeeHistorianActive)
1978 {
1979 m_TeeHistorian.RecordPlayerFinish(ClientId, TimeTicks);
1980 }
1981}
1982
1983void CGameContext::TeehistorianRecordTeamFinish(int TeamId, int TimeTicks)
1984{
1985 if(m_TeeHistorianActive)
1986 {
1987 m_TeeHistorian.RecordTeamFinish(TeamId, TimeTicks);
1988 }
1989}
1990
1991void CGameContext::TeehistorianRecordAuthLogin(int ClientId, const char *pRoleName, const char *pAuthName)
1992{
1993 if(m_TeeHistorianActive)
1994 {
1995 m_TeeHistorian.RecordAuthLogin(ClientId, pRoleName, pAuthName);
1996 }
1997}
1998
1999bool CGameContext::OnClientDDNetVersionKnown(int ClientId)
2000{
2001 IServer::CClientInfo Info;
2002 dbg_assert(Server()->GetClientInfo(ClientId, &Info), "failed to get client info");
2003 int ClientVersion = Info.m_DDNetVersion;
2004 dbg_msg(sys: "ddnet", fmt: "cid=%d version=%d", ClientId, ClientVersion);
2005
2006 if(m_TeeHistorianActive)
2007 {
2008 if(Info.m_pConnectionId && Info.m_pDDNetVersionStr)
2009 {
2010 m_TeeHistorian.RecordDDNetVersion(ClientId, ConnectionId: *Info.m_pConnectionId, DDNetVersion: ClientVersion, pDDNetVersionStr: Info.m_pDDNetVersionStr);
2011 }
2012 else
2013 {
2014 m_TeeHistorian.RecordDDNetVersionOld(ClientId, DDNetVersion: ClientVersion);
2015 }
2016 }
2017
2018 // Autoban known bot versions.
2019 if(g_Config.m_SvBannedVersions[0] != '\0' && IsVersionBanned(Version: ClientVersion))
2020 {
2021 Server()->Kick(ClientId, pReason: "unsupported client");
2022 return true;
2023 }
2024
2025 CPlayer *pPlayer = m_apPlayers[ClientId];
2026 if(ClientVersion >= VERSION_DDNET_GAMETICK)
2027 pPlayer->m_TimerType = g_Config.m_SvDefaultTimerType;
2028
2029 // First update the teams state.
2030 m_pController->Teams().SendTeamsState(ClientId);
2031
2032 // Then send records.
2033 SendRecord(ClientId);
2034
2035 // And report correct tunings.
2036 if(ClientVersion < VERSION_DDNET_EARLY_VERSION)
2037 SendTuningParams(ClientId, Zone: pPlayer->m_TuneZone);
2038
2039 // Tell old clients to update.
2040 if(ClientVersion < VERSION_DDNET_UPDATER_FIXED && g_Config.m_SvClientSuggestionOld[0] != '\0')
2041 SendBroadcast(pText: g_Config.m_SvClientSuggestionOld, ClientId);
2042 // Tell known bot clients that they're botting and we know it.
2043 if(((ClientVersion >= 15 && ClientVersion < 100) || ClientVersion == 502) && g_Config.m_SvClientSuggestionBot[0] != '\0')
2044 SendBroadcast(pText: g_Config.m_SvClientSuggestionBot, ClientId);
2045
2046 m_PlayerMapping.UpdateTeamsState(ClientId);
2047
2048 return false;
2049}
2050
2051void *CGameContext::PreProcessMsg(int *pMsgId, CUnpacker *pUnpacker, int ClientId)
2052{
2053 if(Server()->IsSixup(ClientId) && *pMsgId < OFFSET_UUID)
2054 {
2055 void *pRawMsg = m_NetObjHandler7.SecureUnpackMsg(Type: *pMsgId, pUnpacker);
2056 if(!pRawMsg)
2057 return nullptr;
2058
2059 CPlayer *pPlayer = m_apPlayers[ClientId];
2060 static char s_aRawMsg[1024];
2061
2062 if(*pMsgId == protocol7::NETMSGTYPE_CL_SAY)
2063 {
2064 protocol7::CNetMsg_Cl_Say *pMsg7 = (protocol7::CNetMsg_Cl_Say *)pRawMsg;
2065 // Should probably use a placement new to start the lifetime of the object to avoid future weirdness
2066 ::CNetMsg_Cl_Say *pMsg = (::CNetMsg_Cl_Say *)s_aRawMsg;
2067
2068 if(pMsg7->m_Mode == protocol7::CHAT_WHISPER)
2069 {
2070 if(!Server()->ReverseTranslate(Target&: pMsg7->m_Target, ClientId))
2071 return nullptr;
2072 if(!CheckClientId(ClientId: pMsg7->m_Target) || !Server()->ClientIngame(ClientId: pMsg7->m_Target))
2073 return nullptr;
2074 if(ProcessSpamProtection(ClientId))
2075 return nullptr;
2076
2077 WhisperId(ClientId, VictimId: pMsg7->m_Target, pMessage: pMsg7->m_pMessage);
2078 return nullptr;
2079 }
2080 else
2081 {
2082 pMsg->m_Team = pMsg7->m_Mode == protocol7::CHAT_TEAM;
2083 pMsg->m_pMessage = pMsg7->m_pMessage;
2084 }
2085 }
2086 else if(*pMsgId == protocol7::NETMSGTYPE_CL_STARTINFO)
2087 {
2088 protocol7::CNetMsg_Cl_StartInfo *pMsg7 = (protocol7::CNetMsg_Cl_StartInfo *)pRawMsg;
2089 ::CNetMsg_Cl_StartInfo *pMsg = (::CNetMsg_Cl_StartInfo *)s_aRawMsg;
2090
2091 pMsg->m_pName = pMsg7->m_pName;
2092 pMsg->m_pClan = pMsg7->m_pClan;
2093 pMsg->m_Country = pMsg7->m_Country;
2094
2095 CTeeInfo TeeInfos(pMsg7->m_apSkinPartNames, pMsg7->m_aUseCustomColors, pMsg7->m_aSkinPartColors);
2096 TeeInfos.FromSixup();
2097 pPlayer->SetTeeInfos(TeeInfos);
2098
2099 str_copy(dst: s_aRawMsg + sizeof(*pMsg), src: pPlayer->TeeInfos().m_aSkinName, dst_size: sizeof(s_aRawMsg) - sizeof(*pMsg));
2100
2101 pMsg->m_pSkin = s_aRawMsg + sizeof(*pMsg);
2102 pMsg->m_UseCustomColor = pPlayer->TeeInfos().m_UseCustomColor;
2103 pMsg->m_ColorBody = pPlayer->TeeInfos().m_ColorBody;
2104 pMsg->m_ColorFeet = pPlayer->TeeInfos().m_ColorFeet;
2105 }
2106 else if(*pMsgId == protocol7::NETMSGTYPE_CL_SKINCHANGE)
2107 {
2108 protocol7::CNetMsg_Cl_SkinChange *pMsg = (protocol7::CNetMsg_Cl_SkinChange *)pRawMsg;
2109 if(g_Config.m_SvSpamprotection && pPlayer->m_LastChangeInfo &&
2110 pPlayer->m_LastChangeInfo + Server()->TickSpeed() * g_Config.m_SvInfoChangeDelay > Server()->Tick())
2111 return nullptr;
2112
2113 pPlayer->m_LastChangeInfo = Server()->Tick();
2114
2115 CTeeInfo Info(pMsg->m_apSkinPartNames, pMsg->m_aUseCustomColors, pMsg->m_aSkinPartColors);
2116 Info.FromSixup();
2117 pPlayer->SetTeeInfos(Info);
2118 SendSkinChange7(ClientId);
2119
2120 return nullptr;
2121 }
2122 else if(*pMsgId == protocol7::NETMSGTYPE_CL_SETSPECTATORMODE)
2123 {
2124 protocol7::CNetMsg_Cl_SetSpectatorMode *pMsg7 = (protocol7::CNetMsg_Cl_SetSpectatorMode *)pRawMsg;
2125 ::CNetMsg_Cl_SetSpectatorMode *pMsg = (::CNetMsg_Cl_SetSpectatorMode *)s_aRawMsg;
2126
2127 if(pMsg7->m_SpecMode == protocol7::SPEC_FREEVIEW)
2128 pMsg->m_SpectatorId = SPEC_FREEVIEW;
2129 else if(pMsg7->m_SpecMode == protocol7::SPEC_PLAYER)
2130 pMsg->m_SpectatorId = pMsg7->m_SpectatorId;
2131 else
2132 pMsg->m_SpectatorId = SPEC_FREEVIEW; // Probably not needed
2133 }
2134 else if(*pMsgId == protocol7::NETMSGTYPE_CL_SETTEAM)
2135 {
2136 protocol7::CNetMsg_Cl_SetTeam *pMsg7 = (protocol7::CNetMsg_Cl_SetTeam *)pRawMsg;
2137 ::CNetMsg_Cl_SetTeam *pMsg = (::CNetMsg_Cl_SetTeam *)s_aRawMsg;
2138
2139 pMsg->m_Team = pMsg7->m_Team;
2140 }
2141 else if(*pMsgId == protocol7::NETMSGTYPE_CL_COMMAND)
2142 {
2143 protocol7::CNetMsg_Cl_Command *pMsg7 = (protocol7::CNetMsg_Cl_Command *)pRawMsg;
2144 ::CNetMsg_Cl_Say *pMsg = (::CNetMsg_Cl_Say *)s_aRawMsg;
2145
2146 str_format(buffer: s_aRawMsg + sizeof(*pMsg), buffer_size: sizeof(s_aRawMsg) - sizeof(*pMsg), format: "/%s %s", pMsg7->m_pName, pMsg7->m_pArguments);
2147 pMsg->m_pMessage = s_aRawMsg + sizeof(*pMsg);
2148 pMsg->m_Team = 0;
2149
2150 *pMsgId = NETMSGTYPE_CL_SAY;
2151 return s_aRawMsg;
2152 }
2153 else if(*pMsgId == protocol7::NETMSGTYPE_CL_CALLVOTE)
2154 {
2155 protocol7::CNetMsg_Cl_CallVote *pMsg7 = (protocol7::CNetMsg_Cl_CallVote *)pRawMsg;
2156
2157 if(pMsg7->m_Force)
2158 {
2159 if(!Server()->IsRconAuthed(ClientId))
2160 {
2161 return nullptr;
2162 }
2163 char aCommand[IConsole::CMDLINE_LENGTH];
2164 str_format(buffer: aCommand, buffer_size: sizeof(aCommand), format: "force_vote \"%s\" \"%s\" \"%s\"", pMsg7->m_pType, pMsg7->m_pValue, pMsg7->m_pReason);
2165 Console()->ExecuteLine(pStr: aCommand, ClientId, InterpretSemicolons: false);
2166 return nullptr;
2167 }
2168
2169 ::CNetMsg_Cl_CallVote *pMsg = (::CNetMsg_Cl_CallVote *)s_aRawMsg;
2170 pMsg->m_pValue = pMsg7->m_pValue;
2171 pMsg->m_pReason = pMsg7->m_pReason;
2172 pMsg->m_pType = pMsg7->m_pType;
2173 }
2174 else if(*pMsgId == protocol7::NETMSGTYPE_CL_EMOTICON)
2175 {
2176 protocol7::CNetMsg_Cl_Emoticon *pMsg7 = (protocol7::CNetMsg_Cl_Emoticon *)pRawMsg;
2177 ::CNetMsg_Cl_Emoticon *pMsg = (::CNetMsg_Cl_Emoticon *)s_aRawMsg;
2178
2179 pMsg->m_Emoticon = pMsg7->m_Emoticon;
2180 }
2181 else if(*pMsgId == protocol7::NETMSGTYPE_CL_VOTE)
2182 {
2183 protocol7::CNetMsg_Cl_Vote *pMsg7 = (protocol7::CNetMsg_Cl_Vote *)pRawMsg;
2184 ::CNetMsg_Cl_Vote *pMsg = (::CNetMsg_Cl_Vote *)s_aRawMsg;
2185
2186 pMsg->m_Vote = pMsg7->m_Vote;
2187 }
2188
2189 *pMsgId = Msg_SevenToSix(a: *pMsgId);
2190
2191 return s_aRawMsg;
2192 }
2193 else
2194 return m_NetObjHandler.SecureUnpackMsg(Type: *pMsgId, pUnpacker);
2195}
2196
2197void CGameContext::CensorMessage(char *pCensoredMessage, const char *pMessage, int Size)
2198{
2199 str_copy(dst: pCensoredMessage, src: pMessage, dst_size: Size);
2200
2201 for(auto &Item : m_vCensorlist)
2202 {
2203 char *pCurLoc = pCensoredMessage;
2204 while(true)
2205 {
2206 const char *pEndMatch;
2207 pCurLoc = (char *)str_utf8_find_nocase(haystack: pCurLoc, needle: Item.c_str(), end: &pEndMatch);
2208 if(!pCurLoc)
2209 {
2210 break;
2211 }
2212 while(pCurLoc < pEndMatch)
2213 {
2214 *pCurLoc = '*';
2215 pCurLoc++;
2216 }
2217 }
2218 }
2219}
2220
2221void CGameContext::OnMessage(int MsgId, CUnpacker *pUnpacker, int ClientId)
2222{
2223 if(m_TeeHistorianActive)
2224 {
2225 if(m_NetObjHandler.TeeHistorianRecordMsg(Type: MsgId))
2226 {
2227 m_TeeHistorian.RecordPlayerMessage(ClientId, pMsg: pUnpacker->CompleteData(), MsgSize: pUnpacker->CompleteSize());
2228 }
2229 }
2230
2231 void *pRawMsg = PreProcessMsg(pMsgId: &MsgId, pUnpacker, ClientId);
2232
2233 if(!pRawMsg)
2234 return;
2235
2236 if(Server()->ClientIngame(ClientId))
2237 {
2238 switch(MsgId)
2239 {
2240 case NETMSGTYPE_CL_SAY:
2241 OnSayNetMessage(pMsg: static_cast<CNetMsg_Cl_Say *>(pRawMsg), ClientId, pUnpacker);
2242 break;
2243 case NETMSGTYPE_CL_CALLVOTE:
2244 OnCallVoteNetMessage(pMsg: static_cast<CNetMsg_Cl_CallVote *>(pRawMsg), ClientId);
2245 break;
2246 case NETMSGTYPE_CL_VOTE:
2247 OnVoteNetMessage(pMsg: static_cast<CNetMsg_Cl_Vote *>(pRawMsg), ClientId);
2248 break;
2249 case NETMSGTYPE_CL_SETTEAM:
2250 OnSetTeamNetMessage(pMsg: static_cast<CNetMsg_Cl_SetTeam *>(pRawMsg), ClientId);
2251 break;
2252 case NETMSGTYPE_CL_ISDDNETLEGACY:
2253 OnIsDDNetLegacyNetMessage(pMsg: static_cast<CNetMsg_Cl_IsDDNetLegacy *>(pRawMsg), ClientId, pUnpacker);
2254 break;
2255 case NETMSGTYPE_CL_SHOWOTHERSLEGACY:
2256 OnShowOthersLegacyNetMessage(pMsg: static_cast<CNetMsg_Cl_ShowOthersLegacy *>(pRawMsg), ClientId);
2257 break;
2258 case NETMSGTYPE_CL_SHOWOTHERS:
2259 OnShowOthersNetMessage(pMsg: static_cast<CNetMsg_Cl_ShowOthers *>(pRawMsg), ClientId);
2260 break;
2261 case NETMSGTYPE_CL_SHOWDISTANCE:
2262 OnShowDistanceNetMessage(pMsg: static_cast<CNetMsg_Cl_ShowDistance *>(pRawMsg), ClientId);
2263 break;
2264 case NETMSGTYPE_CL_CAMERAINFO:
2265 OnCameraInfoNetMessage(pMsg: static_cast<CNetMsg_Cl_CameraInfo *>(pRawMsg), ClientId);
2266 break;
2267 case NETMSGTYPE_CL_PRACTICETELEPORT:
2268 OnPracticeTeleportNetMessage(pMsg: static_cast<CNetMsg_Cl_PracticeTeleport *>(pRawMsg), ClientId);
2269 break;
2270 case NETMSGTYPE_CL_SETSPECTATORMODE:
2271 OnSetSpectatorModeNetMessage(pMsg: static_cast<CNetMsg_Cl_SetSpectatorMode *>(pRawMsg), ClientId);
2272 break;
2273 case NETMSGTYPE_CL_CHANGEINFO:
2274 OnChangeInfoNetMessage(pMsg: static_cast<CNetMsg_Cl_ChangeInfo *>(pRawMsg), ClientId);
2275 break;
2276 case NETMSGTYPE_CL_EMOTICON:
2277 OnEmoticonNetMessage(pMsg: static_cast<CNetMsg_Cl_Emoticon *>(pRawMsg), ClientId);
2278 break;
2279 case NETMSGTYPE_CL_KILL:
2280 OnKillNetMessage(pMsg: static_cast<CNetMsg_Cl_Kill *>(pRawMsg), ClientId);
2281 break;
2282 case NETMSGTYPE_CL_ENABLESPECTATORCOUNT:
2283 OnEnableSpectatorCountNetMessage(pMsg: static_cast<CNetMsg_Cl_EnableSpectatorCount *>(pRawMsg), ClientId);
2284 break;
2285 default:
2286 break;
2287 }
2288 }
2289 if(MsgId == NETMSGTYPE_CL_STARTINFO)
2290 {
2291 OnStartInfoNetMessage(pMsg: static_cast<CNetMsg_Cl_StartInfo *>(pRawMsg), ClientId);
2292 }
2293}
2294
2295void CGameContext::OnSayNetMessage(const CNetMsg_Cl_Say *pMsg, int ClientId, const CUnpacker *pUnpacker)
2296{
2297 CPlayer *pPlayer = m_apPlayers[ClientId];
2298 bool Check = !pPlayer->m_NotEligibleForFinish && pPlayer->m_EligibleForFinishCheck + 10 * time_freq() >= time_get();
2299 if(Check && str_comp(a: pMsg->m_pMessage, b: "xd sure chillerbot.png is lyfe") == 0 && pMsg->m_Team == 0)
2300 {
2301 if(m_TeeHistorianActive)
2302 {
2303 m_TeeHistorian.RecordPlayerMessage(ClientId, pMsg: pUnpacker->CompleteData(), MsgSize: pUnpacker->CompleteSize());
2304 }
2305
2306 pPlayer->m_NotEligibleForFinish = true;
2307 dbg_msg(sys: "hack", fmt: "bot detected, cid=%d", ClientId);
2308 return;
2309 }
2310 int Team = pMsg->m_Team;
2311
2312 // trim right and set maximum length to 256 utf8-characters
2313 int Length = 0;
2314 const char *p = pMsg->m_pMessage;
2315 const char *pEnd = nullptr;
2316 while(*p)
2317 {
2318 const char *pStrOld = p;
2319 int Code = str_utf8_decode(ptr: &p);
2320
2321 // check if unicode is not empty
2322 if(!str_utf8_isspace(code: Code))
2323 {
2324 pEnd = nullptr;
2325 }
2326 else if(pEnd == nullptr)
2327 pEnd = pStrOld;
2328
2329 if(++Length >= MAX_CHAT_LENGTH)
2330 {
2331 *(const_cast<char *>(p)) = 0;
2332 break;
2333 }
2334 }
2335 if(pEnd != nullptr)
2336 *(const_cast<char *>(pEnd)) = 0;
2337
2338 // drop empty and autocreated spam messages (more than 32 characters per second)
2339 if(Length == 0 || (pMsg->m_pMessage[0] != '/' && (g_Config.m_SvSpamprotection && pPlayer->m_LastChat && pPlayer->m_LastChat + Server()->TickSpeed() * ((31 + Length) / 32) > Server()->Tick())))
2340 return;
2341
2342 int GameTeam = GetDDRaceTeam(ClientId: pPlayer->GetCid());
2343 if(Team)
2344 Team = ((pPlayer->GetTeam() == TEAM_SPECTATORS) ? TEAM_SPECTATORS : GameTeam);
2345 else
2346 Team = TEAM_ALL;
2347
2348 if(pMsg->m_pMessage[0] == '/')
2349 {
2350 const char *pWhisper;
2351 if((pWhisper = str_startswith_nocase(str: pMsg->m_pMessage + 1, prefix: "w ")))
2352 {
2353 Whisper(ClientId: pPlayer->GetCid(), pStr: const_cast<char *>(pWhisper));
2354 }
2355 else if((pWhisper = str_startswith_nocase(str: pMsg->m_pMessage + 1, prefix: "whisper ")))
2356 {
2357 Whisper(ClientId: pPlayer->GetCid(), pStr: const_cast<char *>(pWhisper));
2358 }
2359 else if((pWhisper = str_startswith_nocase(str: pMsg->m_pMessage + 1, prefix: "c ")))
2360 {
2361 Converse(ClientId: pPlayer->GetCid(), pStr: const_cast<char *>(pWhisper));
2362 }
2363 else if((pWhisper = str_startswith_nocase(str: pMsg->m_pMessage + 1, prefix: "converse ")))
2364 {
2365 Converse(ClientId: pPlayer->GetCid(), pStr: const_cast<char *>(pWhisper));
2366 }
2367 else
2368 {
2369 if(g_Config.m_SvSpamprotection && !str_startswith(str: pMsg->m_pMessage + 1, prefix: "timeout ") && pPlayer->m_aLastCommands[0] && pPlayer->m_aLastCommands[0] + Server()->TickSpeed() > Server()->Tick() && pPlayer->m_aLastCommands[1] && pPlayer->m_aLastCommands[1] + Server()->TickSpeed() > Server()->Tick() && pPlayer->m_aLastCommands[2] && pPlayer->m_aLastCommands[2] + Server()->TickSpeed() > Server()->Tick() && pPlayer->m_aLastCommands[3] && pPlayer->m_aLastCommands[3] + Server()->TickSpeed() > Server()->Tick())
2370 return;
2371
2372 int64_t Now = Server()->Tick();
2373 pPlayer->m_aLastCommands[pPlayer->m_LastCommandPos] = Now;
2374 pPlayer->m_LastCommandPos = (pPlayer->m_LastCommandPos + 1) % 4;
2375
2376 Console()->SetFlagMask(CFGFLAG_CHAT);
2377 {
2378 CClientChatLogger Logger(this, ClientId, log_get_scope_logger());
2379 CLogScope Scope(&Logger);
2380 Console()->ExecuteLine(pStr: pMsg->m_pMessage + 1, ClientId, InterpretSemicolons: false);
2381 }
2382 // m_apPlayers[ClientId] can be nullptr, if the player used a
2383 // timeout code and replaced another client.
2384 log_trace("chat-command", "%d used %s", ClientId, pMsg->m_pMessage);
2385
2386 Console()->SetFlagMask(CFGFLAG_SERVER);
2387 }
2388 }
2389 else
2390 {
2391 pPlayer->UpdatePlaytime();
2392 char aCensoredMessage[256];
2393 CensorMessage(pCensoredMessage: aCensoredMessage, pMessage: pMsg->m_pMessage, Size: sizeof(aCensoredMessage));
2394 SendChat(ChatterClientId: ClientId, Team, pText: aCensoredMessage, SpamProtectionClientId: ClientId);
2395 }
2396}
2397
2398void CGameContext::OnCallVoteNetMessage(const CNetMsg_Cl_CallVote *pMsg, int ClientId)
2399{
2400 if(str_comp_nocase(a: pMsg->m_pType, b: "option") != 0 && m_PlayerMapping.DoSeeOthers(ClientId, SelectedId: str_toint(str: pMsg->m_pValue), DoByVote: true))
2401 return;
2402
2403 if(RateLimitPlayerVote(ClientId) || m_VoteCloseTime)
2404 return;
2405
2406 m_apPlayers[ClientId]->UpdatePlaytime();
2407
2408 m_VoteType = VOTE_TYPE_UNKNOWN;
2409 char aChatmsg[512] = {0};
2410 char aDesc[VOTE_DESC_LENGTH] = {0};
2411 char aSixupDesc[VOTE_DESC_LENGTH] = {0};
2412 char aCmd[VOTE_CMD_LENGTH] = {0};
2413 char aReason[VOTE_REASON_LENGTH] = "No reason given";
2414 if(pMsg->m_pReason[0])
2415 {
2416 str_copy(dst&: aReason, src: pMsg->m_pReason);
2417 }
2418
2419 if(str_comp_nocase(a: pMsg->m_pType, b: "option") == 0)
2420 {
2421 CVoteOptionServer *pOption = m_pVoteOptionFirst;
2422 while(pOption)
2423 {
2424 if(str_comp_nocase(a: pMsg->m_pValue, b: pOption->m_aDescription) == 0)
2425 {
2426 if(!Console()->LineIsValid(pStr: pOption->m_aCommand))
2427 {
2428 SendChatTarget(To: ClientId, pText: "Invalid option");
2429 return;
2430 }
2431 if((str_find(haystack: pOption->m_aCommand, needle: "sv_map ") != nullptr || str_find(haystack: pOption->m_aCommand, needle: "change_map ") != nullptr || str_find(haystack: pOption->m_aCommand, needle: "random_map") != nullptr || str_find(haystack: pOption->m_aCommand, needle: "random_unfinished_map") != nullptr) && RateLimitPlayerMapVote(ClientId))
2432 {
2433 return;
2434 }
2435
2436 str_format(buffer: aChatmsg, buffer_size: sizeof(aChatmsg), format: "'%s' called vote to change server option '%s' (%s)", Server()->ClientName(ClientId),
2437 pOption->m_aDescription, aReason);
2438 str_copy(dst&: aDesc, src: pOption->m_aDescription);
2439
2440 if((str_endswith(str: pOption->m_aCommand, suffix: "random_map") || str_endswith(str: pOption->m_aCommand, suffix: "random_unfinished_map")))
2441 {
2442 if(str_length(str: aReason) == 1 && aReason[0] >= '0' && aReason[0] <= '5')
2443 {
2444 int Stars = aReason[0] - '0';
2445 str_format(buffer: aCmd, buffer_size: sizeof(aCmd), format: "%s %d", pOption->m_aCommand, Stars);
2446 }
2447 else if(str_length(str: aReason) == 3 && aReason[1] == '-' && aReason[0] >= '0' && aReason[0] <= '5' && aReason[2] >= '0' && aReason[2] <= '5')
2448 {
2449 int Start = aReason[0] - '0';
2450 int End = aReason[2] - '0';
2451 str_format(buffer: aCmd, buffer_size: sizeof(aCmd), format: "%s %d %d", pOption->m_aCommand, Start, End);
2452 }
2453 else
2454 {
2455 str_copy(dst&: aCmd, src: pOption->m_aCommand);
2456 }
2457 }
2458 else
2459 {
2460 str_copy(dst&: aCmd, src: pOption->m_aCommand);
2461 }
2462
2463 m_LastMapVote = time_get();
2464 break;
2465 }
2466
2467 pOption = pOption->m_pNext;
2468 }
2469
2470 if(!pOption)
2471 {
2472 if(!Server()->IsRconAuthedAdmin(ClientId)) // allow admins to call any vote they want
2473 {
2474 str_format(buffer: aChatmsg, buffer_size: sizeof(aChatmsg), format: "'%s' isn't an option on this server", pMsg->m_pValue);
2475 SendChatTarget(To: ClientId, pText: aChatmsg);
2476 return;
2477 }
2478 else
2479 {
2480 str_format(buffer: aChatmsg, buffer_size: sizeof(aChatmsg), format: "'%s' called vote to change server option '%s'", Server()->ClientName(ClientId), pMsg->m_pValue);
2481 str_copy(dst&: aDesc, src: pMsg->m_pValue);
2482 str_copy(dst&: aCmd, src: pMsg->m_pValue);
2483 }
2484 }
2485
2486 m_VoteType = VOTE_TYPE_OPTION;
2487 }
2488 else if(str_comp_nocase(a: pMsg->m_pType, b: "kick") == 0)
2489 {
2490 if(!g_Config.m_SvVoteKick && !Server()->IsRconAuthed(ClientId)) // allow admins to call kick votes even if they are forbidden
2491 {
2492 SendChatTarget(To: ClientId, pText: "Server does not allow voting to kick players");
2493 return;
2494 }
2495 if(!Server()->IsRconAuthed(ClientId) && time_get() < m_apPlayers[ClientId]->m_LastKickVote + (time_freq() * g_Config.m_SvVoteKickDelay))
2496 {
2497 str_format(buffer: aChatmsg, buffer_size: sizeof(aChatmsg), format: "There's a %d second wait time between kick votes for each player please wait %d second(s)",
2498 g_Config.m_SvVoteKickDelay,
2499 (int)((m_apPlayers[ClientId]->m_LastKickVote + g_Config.m_SvVoteKickDelay * time_freq() - time_get()) / time_freq()));
2500 SendChatTarget(To: ClientId, pText: aChatmsg);
2501 return;
2502 }
2503
2504 if(g_Config.m_SvVoteKickMin && !GetDDRaceTeam(ClientId))
2505 {
2506 const NETADDR *apAddresses[MAX_CLIENTS];
2507 for(int i = 0; i < MAX_CLIENTS; i++)
2508 {
2509 if(m_apPlayers[i])
2510 {
2511 apAddresses[i] = Server()->ClientAddr(ClientId: i);
2512 }
2513 }
2514 int NumPlayers = 0;
2515 for(int i = 0; i < MAX_CLIENTS; ++i)
2516 {
2517 if(m_apPlayers[i] && m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS && !GetDDRaceTeam(ClientId: i))
2518 {
2519 NumPlayers++;
2520 for(int j = 0; j < i; j++)
2521 {
2522 if(m_apPlayers[j] && m_apPlayers[j]->GetTeam() != TEAM_SPECTATORS && !GetDDRaceTeam(ClientId: j))
2523 {
2524 if(!net_addr_comp_noport(a: apAddresses[i], b: apAddresses[j]))
2525 {
2526 NumPlayers--;
2527 break;
2528 }
2529 }
2530 }
2531 }
2532 }
2533
2534 if(NumPlayers < g_Config.m_SvVoteKickMin)
2535 {
2536 str_format(buffer: aChatmsg, buffer_size: sizeof(aChatmsg), format: "Kick voting requires %d players", g_Config.m_SvVoteKickMin);
2537 SendChatTarget(To: ClientId, pText: aChatmsg);
2538 return;
2539 }
2540 }
2541
2542 int KickId = str_toint(str: pMsg->m_pValue);
2543
2544 if(!Server()->ReverseTranslate(Target&: KickId, ClientId))
2545 {
2546 return;
2547 }
2548 if(KickId < 0 || KickId >= MAX_CLIENTS || !m_apPlayers[KickId])
2549 {
2550 SendChatTarget(To: ClientId, pText: "Invalid client id to kick");
2551 return;
2552 }
2553 if(KickId == ClientId)
2554 {
2555 SendChatTarget(To: ClientId, pText: "You can't kick yourself");
2556 return;
2557 }
2558
2559 int Authed = Server()->GetAuthedState(ClientId);
2560 int KickedAuthed = Server()->GetAuthedState(ClientId: KickId);
2561 if(KickedAuthed > Authed)
2562 {
2563 SendChatTarget(To: ClientId, pText: "You can't kick authorized players");
2564 char aBufKick[128];
2565 str_format(buffer: aBufKick, buffer_size: sizeof(aBufKick), format: "'%s' called for vote to kick you", Server()->ClientName(ClientId));
2566 SendChatTarget(To: KickId, pText: aBufKick);
2567 return;
2568 }
2569
2570 // Don't allow kicking if a player has no character
2571 if(!GetPlayerChar(ClientId) || !GetPlayerChar(ClientId: KickId))
2572 {
2573 SendChatTarget(To: ClientId, pText: "You can kick only your team member");
2574 return;
2575 }
2576
2577 if(GetDDRaceTeam(ClientId) != GetDDRaceTeam(ClientId: KickId))
2578 {
2579 if(!g_Config.m_SvVoteKickMuteTime)
2580 {
2581 str_format(buffer: aChatmsg, buffer_size: sizeof(aChatmsg), format: "'%s' called for vote to mute '%s' (%s)", Server()->ClientName(ClientId), Server()->ClientName(ClientId: KickId), aReason);
2582 str_format(buffer: aSixupDesc, buffer_size: sizeof(aSixupDesc), format: "%2d: %s", KickId, Server()->ClientName(ClientId: KickId));
2583 str_format(buffer: aCmd, buffer_size: sizeof(aCmd), format: "muteid %d %d Muted by vote", KickId, g_Config.m_SvVoteKickMuteTime);
2584 str_format(buffer: aDesc, buffer_size: sizeof(aDesc), format: "Mute '%s'", Server()->ClientName(ClientId: KickId));
2585 }
2586 else
2587 {
2588 SendChatTarget(To: ClientId, pText: "You can kick only your team member");
2589 return;
2590 }
2591 }
2592 else
2593 {
2594 str_format(buffer: aChatmsg, buffer_size: sizeof(aChatmsg), format: "'%s' called for vote to kick '%s' (%s)", Server()->ClientName(ClientId), Server()->ClientName(ClientId: KickId), aReason);
2595 str_format(buffer: aSixupDesc, buffer_size: sizeof(aSixupDesc), format: "%2d: %s", KickId, Server()->ClientName(ClientId: KickId));
2596 if(!GetDDRaceTeam(ClientId))
2597 {
2598 if(!g_Config.m_SvVoteKickBantime)
2599 {
2600 str_format(buffer: aCmd, buffer_size: sizeof(aCmd), format: "kick %d Kicked by vote", KickId);
2601 str_format(buffer: aDesc, buffer_size: sizeof(aDesc), format: "Kick '%s'", Server()->ClientName(ClientId: KickId));
2602 }
2603 else
2604 {
2605 str_format(buffer: aCmd, buffer_size: sizeof(aCmd), format: "ban %s %d Banned by vote", Server()->ClientAddrString(ClientId: KickId, IncludePort: false), g_Config.m_SvVoteKickBantime);
2606 str_format(buffer: aDesc, buffer_size: sizeof(aDesc), format: "Ban '%s'", Server()->ClientName(ClientId: KickId));
2607 }
2608 }
2609 else
2610 {
2611 str_format(buffer: aCmd, buffer_size: sizeof(aCmd), format: "uninvite %d %d; set_team_ddr %d 0", KickId, GetDDRaceTeam(ClientId: KickId), KickId);
2612 str_format(buffer: aDesc, buffer_size: sizeof(aDesc), format: "Move '%s' to team 0", Server()->ClientName(ClientId: KickId));
2613 }
2614 }
2615 m_apPlayers[ClientId]->m_LastKickVote = time_get();
2616 m_VoteType = VOTE_TYPE_KICK;
2617 m_VoteVictim = KickId;
2618 }
2619 else if(str_comp_nocase(a: pMsg->m_pType, b: "spectate") == 0)
2620 {
2621 if(!g_Config.m_SvVoteSpectate)
2622 {
2623 SendChatTarget(To: ClientId, pText: "Server does not allow voting to move players to spectators");
2624 return;
2625 }
2626
2627 int SpectateId = str_toint(str: pMsg->m_pValue);
2628
2629 if(!Server()->ReverseTranslate(Target&: SpectateId, ClientId))
2630 {
2631 return;
2632 }
2633 if(SpectateId < 0 || SpectateId >= MAX_CLIENTS || !m_apPlayers[SpectateId] || m_apPlayers[SpectateId]->GetTeam() == TEAM_SPECTATORS)
2634 {
2635 SendChatTarget(To: ClientId, pText: "Invalid client id to move to spectators");
2636 return;
2637 }
2638 if(SpectateId == ClientId)
2639 {
2640 SendChatTarget(To: ClientId, pText: "You can't move yourself to spectators");
2641 return;
2642 }
2643 int Authed = Server()->GetAuthedState(ClientId);
2644 int SpectateAuthed = Server()->GetAuthedState(ClientId: SpectateId);
2645 if(SpectateAuthed > Authed)
2646 {
2647 SendChatTarget(To: ClientId, pText: "You can't move authorized players to spectators");
2648 char aBufSpectate[128];
2649 str_format(buffer: aBufSpectate, buffer_size: sizeof(aBufSpectate), format: "'%s' called for vote to move you to spectators", Server()->ClientName(ClientId));
2650 SendChatTarget(To: SpectateId, pText: aBufSpectate);
2651 return;
2652 }
2653
2654 if(!GetPlayerChar(ClientId) || !GetPlayerChar(ClientId: SpectateId) || GetDDRaceTeam(ClientId) != GetDDRaceTeam(ClientId: SpectateId))
2655 {
2656 SendChatTarget(To: ClientId, pText: "You can only move your team member to spectators");
2657 return;
2658 }
2659
2660 str_format(buffer: aSixupDesc, buffer_size: sizeof(aSixupDesc), format: "%2d: %s", SpectateId, Server()->ClientName(ClientId: SpectateId));
2661 if(g_Config.m_SvPauseable && g_Config.m_SvVotePause)
2662 {
2663 str_format(buffer: aChatmsg, buffer_size: sizeof(aChatmsg), format: "'%s' called for vote to pause '%s' for %d seconds (%s)", Server()->ClientName(ClientId), Server()->ClientName(ClientId: SpectateId), g_Config.m_SvVotePauseTime, aReason);
2664 str_format(buffer: aDesc, buffer_size: sizeof(aDesc), format: "Pause '%s' (%ds)", Server()->ClientName(ClientId: SpectateId), g_Config.m_SvVotePauseTime);
2665 str_format(buffer: aCmd, buffer_size: sizeof(aCmd), format: "uninvite %d %d; force_pause %d %d", SpectateId, GetDDRaceTeam(ClientId: SpectateId), SpectateId, g_Config.m_SvVotePauseTime);
2666 }
2667 else
2668 {
2669 str_format(buffer: aChatmsg, buffer_size: sizeof(aChatmsg), format: "'%s' called for vote to move '%s' to spectators (%s)", Server()->ClientName(ClientId), Server()->ClientName(ClientId: SpectateId), aReason);
2670 str_format(buffer: aDesc, buffer_size: sizeof(aDesc), format: "Move '%s' to spectators", Server()->ClientName(ClientId: SpectateId));
2671 str_format(buffer: aCmd, buffer_size: sizeof(aCmd), format: "uninvite %d %d; set_team %d -1 %d", SpectateId, GetDDRaceTeam(ClientId: SpectateId), SpectateId, g_Config.m_SvVoteSpectateRejoindelay);
2672 }
2673 m_VoteType = VOTE_TYPE_SPECTATE;
2674 m_VoteVictim = SpectateId;
2675 }
2676
2677 if(aCmd[0] && str_comp_nocase(a: aCmd, b: "info") != 0)
2678 CallVote(ClientId, pDesc: aDesc, pCmd: aCmd, pReason: aReason, pChatmsg: aChatmsg, pSixupDesc: aSixupDesc[0] ? aSixupDesc : nullptr);
2679}
2680
2681void CGameContext::OnVoteNetMessage(const CNetMsg_Cl_Vote *pMsg, int ClientId)
2682{
2683 if(!m_VoteCloseTime)
2684 return;
2685
2686 CPlayer *pPlayer = m_apPlayers[ClientId];
2687
2688 if(g_Config.m_SvSpamprotection && pPlayer->m_LastVoteTry && pPlayer->m_LastVoteTry + Server()->TickSpeed() * 3 > Server()->Tick())
2689 return;
2690
2691 pPlayer->m_LastVoteTry = Server()->Tick();
2692 pPlayer->UpdatePlaytime();
2693
2694 if(!pMsg->m_Vote)
2695 return;
2696
2697 // Allow the vote creator to cancel the vote
2698 if(pPlayer->GetCid() == m_VoteCreator && pMsg->m_Vote == -1)
2699 {
2700 m_VoteEnforce = VOTE_ENFORCE_CANCEL;
2701 return;
2702 }
2703
2704 pPlayer->m_Vote = pMsg->m_Vote;
2705 pPlayer->m_VotePos = ++m_VotePos;
2706 m_VoteUpdate = true;
2707
2708 CNetMsg_Sv_YourVote Msg = {.m_Voted: pMsg->m_Vote};
2709 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId);
2710}
2711
2712void CGameContext::OnSetTeamNetMessage(const CNetMsg_Cl_SetTeam *pMsg, int ClientId)
2713{
2714 if(m_pController->IsGamePaused())
2715 return;
2716
2717 CPlayer *pPlayer = m_apPlayers[ClientId];
2718
2719 if(pPlayer->GetTeam() == pMsg->m_Team)
2720 return;
2721 if(g_Config.m_SvSpamprotection && pPlayer->m_LastSetTeam && pPlayer->m_LastSetTeam + Server()->TickSpeed() * g_Config.m_SvTeamChangeDelay > Server()->Tick())
2722 return;
2723
2724 // Kill Protection
2725 CCharacter *pChr = pPlayer->GetCharacter();
2726 if(pChr)
2727 {
2728 int CurrTime = (Server()->Tick() - pChr->m_StartTime) / Server()->TickSpeed();
2729 if(g_Config.m_SvKillProtection != 0 && CurrTime >= (60 * g_Config.m_SvKillProtection) && pChr->m_DDRaceState == ERaceState::STARTED)
2730 {
2731 SendChatTarget(To: ClientId, pText: "Kill Protection enabled. If you really want to join the spectators, first type /kill");
2732 return;
2733 }
2734 }
2735
2736 if(pPlayer->m_TeamChangeTick > Server()->Tick())
2737 {
2738 pPlayer->m_LastSetTeam = Server()->Tick();
2739 int TimeLeft = (pPlayer->m_TeamChangeTick - Server()->Tick()) / Server()->TickSpeed();
2740 char aTime[32];
2741 str_time(centisecs: (int64_t)TimeLeft * 100, format: ETimeFormat::HOURS, buffer: aTime, buffer_size: sizeof(aTime));
2742 char aBuf[128];
2743 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "Time to wait before changing team: %s", aTime);
2744 SendBroadcast(pText: aBuf, ClientId);
2745 return;
2746 }
2747
2748 // Switch team on given client and kill/respawn them
2749 char aTeamJoinError[512];
2750 if(m_pController->CanJoinTeam(Team: pMsg->m_Team, NotThisId: ClientId, pErrorReason: aTeamJoinError, ErrorReasonSize: sizeof(aTeamJoinError)))
2751 {
2752 if(pPlayer->GetTeam() == TEAM_SPECTATORS || pMsg->m_Team == TEAM_SPECTATORS)
2753 m_VoteUpdate = true;
2754 m_pController->DoTeamChange(pPlayer, Team: pMsg->m_Team, DoChatMsg: true);
2755 pPlayer->m_TeamChangeTick = Server()->Tick();
2756 }
2757 else
2758 SendBroadcast(pText: aTeamJoinError, ClientId);
2759}
2760
2761void CGameContext::OnIsDDNetLegacyNetMessage(const CNetMsg_Cl_IsDDNetLegacy *pMsg, int ClientId, CUnpacker *pUnpacker)
2762{
2763 IServer::CClientInfo Info;
2764 if(Server()->GetClientInfo(ClientId, pInfo: &Info) && Info.m_GotDDNetVersion)
2765 {
2766 return;
2767 }
2768 int DDNetVersion = pUnpacker->GetInt();
2769 if(pUnpacker->Error() || DDNetVersion < 0)
2770 {
2771 DDNetVersion = VERSION_DDRACE;
2772 }
2773 Server()->SetClientDDNetVersion(ClientId, DDNetVersion);
2774 if(OnClientDDNetVersionKnown(ClientId))
2775 return;
2776 // Initial identification, currently identified as 16p client, make sure we allow 64 slots
2777 CPlayerMapping::CSixupCfg SixupCfg;
2778 SixupCfg.m_ClearSlots = true;
2779 m_PlayerMapping.InitPlayerMap(ClientId, SixupCfg);
2780}
2781
2782void CGameContext::OnShowOthersLegacyNetMessage(const CNetMsg_Cl_ShowOthersLegacy *pMsg, int ClientId)
2783{
2784 if(g_Config.m_SvShowOthers && !g_Config.m_SvShowOthersDefault)
2785 {
2786 CPlayer *pPlayer = m_apPlayers[ClientId];
2787 pPlayer->m_ShowOthers = pMsg->m_Show;
2788 }
2789}
2790
2791void CGameContext::OnShowOthersNetMessage(const CNetMsg_Cl_ShowOthers *pMsg, int ClientId)
2792{
2793 if(g_Config.m_SvShowOthers && !g_Config.m_SvShowOthersDefault)
2794 {
2795 CPlayer *pPlayer = m_apPlayers[ClientId];
2796 pPlayer->m_ShowOthers = pMsg->m_Show;
2797 }
2798}
2799
2800void CGameContext::OnShowDistanceNetMessage(const CNetMsg_Cl_ShowDistance *pMsg, int ClientId)
2801{
2802 CPlayer *pPlayer = m_apPlayers[ClientId];
2803 pPlayer->m_ShowDistance = vec2(pMsg->m_X, pMsg->m_Y);
2804}
2805
2806void CGameContext::OnCameraInfoNetMessage(const CNetMsg_Cl_CameraInfo *pMsg, int ClientId)
2807{
2808 CPlayer *pPlayer = m_apPlayers[ClientId];
2809 pPlayer->m_CameraInfo.Write(pMsg);
2810}
2811
2812void CGameContext::OnPracticeTeleportNetMessage(const CNetMsg_Cl_PracticeTeleport *pMsg, int ClientId)
2813{
2814 CPlayer *pPlayer = m_apPlayers[ClientId];
2815 if(!pPlayer)
2816 return;
2817 CCharacter *pChr = pPlayer->GetCharacter();
2818 if(!pChr)
2819 return;
2820
2821 CGameTeams &Teams = m_pController->Teams();
2822 if(!Teams.IsPractice(Team: GetDDRaceTeam(ClientId)))
2823 {
2824 SendChatTarget(To: ClientId, pText: "You're not in a team with /practice turned on. Note that you can't earn a rank with practice enabled.");
2825 return;
2826 }
2827
2828 PracticeTeleport(pChr, Pos: vec2((float)pMsg->m_X, (float)pMsg->m_Y));
2829}
2830
2831void CGameContext::OnSetSpectatorModeNetMessage(const CNetMsg_Cl_SetSpectatorMode *pMsg, int ClientId)
2832{
2833 if(m_pController->IsGamePaused())
2834 return;
2835
2836 CPlayer *pPlayer = m_apPlayers[ClientId];
2837 if((g_Config.m_SvSpamprotection && pPlayer->m_LastSetSpectatorMode && pPlayer->m_LastSetSpectatorMode + Server()->TickSpeed() / 4 > Server()->Tick()))
2838 return;
2839
2840 pPlayer->m_LastSetSpectatorMode = Server()->Tick();
2841 int SpectatorId = std::clamp(val: pMsg->m_SpectatorId, lo: (int)SPEC_FOLLOW, hi: MAX_CLIENTS - 1);
2842
2843 if(m_PlayerMapping.DoSeeOthers(ClientId, SelectedId: SpectatorId))
2844 return;
2845
2846 if(SpectatorId >= 0)
2847 if(!Server()->ReverseTranslate(Target&: SpectatorId, ClientId))
2848 return;
2849
2850 pPlayer->UpdatePlaytime();
2851 if(SpectatorId >= 0 && (!m_apPlayers[SpectatorId] || m_apPlayers[SpectatorId]->GetTeam() == TEAM_SPECTATORS))
2852 SendChatTarget(To: ClientId, pText: "Invalid spectator id used");
2853 else
2854 pPlayer->SetSpectatorId(SpectatorId);
2855}
2856
2857void CGameContext::OnChangeInfoNetMessage(const CNetMsg_Cl_ChangeInfo *pMsg, int ClientId)
2858{
2859 CPlayer *pPlayer = m_apPlayers[ClientId];
2860 if(g_Config.m_SvSpamprotection && pPlayer->m_LastChangeInfo && pPlayer->m_LastChangeInfo + Server()->TickSpeed() * g_Config.m_SvInfoChangeDelay > Server()->Tick())
2861 return;
2862
2863 bool SixupNeedsUpdate = false;
2864
2865 pPlayer->m_LastChangeInfo = Server()->Tick();
2866 pPlayer->UpdatePlaytime();
2867
2868 if(g_Config.m_SvSpamprotection)
2869 {
2870 CNetMsg_Sv_ChangeInfoCooldown ChangeInfoCooldownMsg;
2871 ChangeInfoCooldownMsg.m_WaitUntil = Server()->Tick() + Server()->TickSpeed() * g_Config.m_SvInfoChangeDelay;
2872 Server()->SendPackMsg(pMsg: &ChangeInfoCooldownMsg, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId);
2873 }
2874
2875 // set infos
2876 if(Server()->WouldClientNameChange(ClientId, pNameRequest: pMsg->m_pName) && !ProcessSpamProtection(ClientId))
2877 {
2878 char aOldName[MAX_NAME_LENGTH];
2879 str_copy(dst&: aOldName, src: Server()->ClientName(ClientId));
2880
2881 Server()->SetClientName(ClientId, pName: pMsg->m_pName);
2882
2883 char aChatText[256];
2884 str_format(buffer: aChatText, buffer_size: sizeof(aChatText), format: "'%s' changed name to '%s'", aOldName, Server()->ClientName(ClientId));
2885 SendChat(ChatterClientId: -1, Team: TEAM_ALL, pText: aChatText);
2886
2887 // reload scores
2888 Score()->PlayerData(Id: ClientId)->Reset();
2889 Server()->SetClientScore(ClientId, Score: std::nullopt);
2890 Score()->LoadPlayerData(ClientId);
2891
2892 SixupNeedsUpdate = true;
2893
2894 LogEvent(Description: "Name change", ClientId);
2895 }
2896
2897 if(Server()->WouldClientClanChange(ClientId, pClanRequest: pMsg->m_pClan))
2898 {
2899 SixupNeedsUpdate = true;
2900 Server()->SetClientClan(ClientId, pClan: pMsg->m_pClan);
2901 }
2902
2903 if(Server()->ClientCountry(ClientId) != pMsg->m_Country)
2904 {
2905 SixupNeedsUpdate = true;
2906 Server()->SetClientCountry(ClientId, Country: pMsg->m_Country);
2907 }
2908
2909 pPlayer->SetTeeInfos(pSkinName: pMsg->m_pSkin, UseCustomColor: pMsg->m_UseCustomColor, ColorBody: pMsg->m_ColorBody, ColorFeet: pMsg->m_ColorFeet);
2910
2911 if(SixupNeedsUpdate)
2912 {
2913 SendRename7(ClientId);
2914 }
2915 else
2916 {
2917 SendSkinChange7(ClientId);
2918 }
2919
2920 Server()->ExpireServerInfo();
2921}
2922
2923void CGameContext::OnEmoticonNetMessage(const CNetMsg_Cl_Emoticon *pMsg, int ClientId)
2924{
2925 if(m_pController->IsGamePaused())
2926 return;
2927
2928 CPlayer *pPlayer = m_apPlayers[ClientId];
2929
2930 auto &&CheckPreventEmote = [&](int64_t LastEmote, int64_t DelayInMs) {
2931 return (LastEmote * (int64_t)1000) + (int64_t)Server()->TickSpeed() * DelayInMs > ((int64_t)Server()->Tick() * (int64_t)1000);
2932 };
2933
2934 if(g_Config.m_SvSpamprotection && CheckPreventEmote((int64_t)pPlayer->m_LastEmote, (int64_t)g_Config.m_SvEmoticonMsDelay))
2935 return;
2936
2937 CCharacter *pChr = pPlayer->GetCharacter();
2938
2939 // player needs a character to send emotes
2940 if(!pChr)
2941 return;
2942
2943 pPlayer->m_LastEmote = Server()->Tick();
2944 pPlayer->UpdatePlaytime();
2945
2946 // check if the global emoticon is prevented and emotes are only send to nearby players
2947 if(g_Config.m_SvSpamprotection && CheckPreventEmote((int64_t)pPlayer->m_LastEmoteGlobal, (int64_t)g_Config.m_SvGlobalEmoticonMsDelay))
2948 {
2949 for(int i = 0; i < MAX_CLIENTS; ++i)
2950 {
2951 if(m_apPlayers[i] && pChr->CanSnapCharacter(SnappingClient: i) && pChr->IsSnappingCharacterInView(SnappingClientId: i))
2952 {
2953 SendEmoticon(ClientId, Emoticon: pMsg->m_Emoticon, TargetClientId: i);
2954 }
2955 }
2956 }
2957 else
2958 {
2959 // else send emoticons to all players
2960 pPlayer->m_LastEmoteGlobal = Server()->Tick();
2961 SendEmoticon(ClientId, Emoticon: pMsg->m_Emoticon, TargetClientId: -1);
2962 }
2963
2964 if(g_Config.m_SvEmotionalTees == 1 && pPlayer->m_EyeEmoteEnabled)
2965 {
2966 int EmoteType = EMOTE_NORMAL;
2967 switch(pMsg->m_Emoticon)
2968 {
2969 case EMOTICON_EXCLAMATION:
2970 case EMOTICON_GHOST:
2971 case EMOTICON_QUESTION:
2972 case EMOTICON_WTF:
2973 EmoteType = EMOTE_SURPRISE;
2974 break;
2975 case EMOTICON_DOTDOT:
2976 case EMOTICON_DROP:
2977 case EMOTICON_ZZZ:
2978 EmoteType = EMOTE_BLINK;
2979 break;
2980 case EMOTICON_EYES:
2981 case EMOTICON_HEARTS:
2982 case EMOTICON_MUSIC:
2983 EmoteType = EMOTE_HAPPY;
2984 break;
2985 case EMOTICON_OOP:
2986 case EMOTICON_SORRY:
2987 case EMOTICON_SUSHI:
2988 EmoteType = EMOTE_PAIN;
2989 break;
2990 case EMOTICON_DEVILTEE:
2991 case EMOTICON_SPLATTEE:
2992 case EMOTICON_ZOMG:
2993 EmoteType = EMOTE_ANGRY;
2994 break;
2995 default:
2996 break;
2997 }
2998 pChr->SetEmote(Emote: EmoteType, Tick: Server()->Tick() + 2 * Server()->TickSpeed());
2999 }
3000}
3001
3002void CGameContext::OnKillNetMessage(const CNetMsg_Cl_Kill *pMsg, int ClientId)
3003{
3004 if(m_pController->IsGamePaused())
3005 return;
3006
3007 if(IsRunningKickOrSpecVote(ClientId) && GetDDRaceTeam(ClientId))
3008 {
3009 SendChatTarget(To: ClientId, pText: "You are running a vote please try again after the vote is done!");
3010 return;
3011 }
3012 CPlayer *pPlayer = m_apPlayers[ClientId];
3013 if(pPlayer->m_LastKill && pPlayer->m_LastKill + Server()->TickSpeed() * g_Config.m_SvKillDelay > Server()->Tick())
3014 return;
3015 if(pPlayer->IsPaused())
3016 return;
3017
3018 CCharacter *pChr = pPlayer->GetCharacter();
3019 if(!pChr)
3020 return;
3021
3022 // Kill Protection
3023 int CurrTime = (Server()->Tick() - pChr->m_StartTime) / Server()->TickSpeed();
3024 if(g_Config.m_SvKillProtection != 0 && CurrTime >= (60 * g_Config.m_SvKillProtection) && pChr->m_DDRaceState == ERaceState::STARTED)
3025 {
3026 SendChatTarget(To: ClientId, pText: "Kill Protection enabled. If you really want to kill, type /kill");
3027 return;
3028 }
3029
3030 pPlayer->m_LastKill = Server()->Tick();
3031 pPlayer->KillCharacter(Weapon: WEAPON_SELF);
3032 pPlayer->Respawn();
3033}
3034
3035void CGameContext::OnEnableSpectatorCountNetMessage(const CNetMsg_Cl_EnableSpectatorCount *pMsg, int ClientId)
3036{
3037 CPlayer *pPlayer = m_apPlayers[ClientId];
3038 if(!pPlayer)
3039 return;
3040
3041 pPlayer->m_EnableSpectatorCount = pMsg->m_Enable;
3042}
3043
3044void CGameContext::OnStartInfoNetMessage(const CNetMsg_Cl_StartInfo *pMsg, int ClientId)
3045{
3046 CPlayer *pPlayer = m_apPlayers[ClientId];
3047
3048 if(pPlayer->m_IsReady)
3049 return;
3050
3051 pPlayer->m_LastChangeInfo = Server()->Tick();
3052
3053 // set start infos
3054 Server()->SetClientName(ClientId, pName: pMsg->m_pName);
3055 // trying to set client name can delete the player object, check if it still exists
3056 if(!m_apPlayers[ClientId])
3057 {
3058 return;
3059 }
3060 Server()->SetClientClan(ClientId, pClan: pMsg->m_pClan);
3061 // trying to set client clan can delete the player object, check if it still exists
3062 if(!m_apPlayers[ClientId])
3063 {
3064 return;
3065 }
3066 Server()->SetClientCountry(ClientId, Country: pMsg->m_Country);
3067 pPlayer->SetTeeInfos(pSkinName: pMsg->m_pSkin, UseCustomColor: pMsg->m_UseCustomColor, ColorBody: pMsg->m_ColorBody, ColorFeet: pMsg->m_ColorFeet);
3068
3069 // send clear vote options
3070 CNetMsg_Sv_VoteClearOptions ClearMsg;
3071 Server()->SendPackMsg(pMsg: &ClearMsg, Flags: MSGFLAG_VITAL, ClientId);
3072
3073 // begin sending vote options
3074 pPlayer->m_SendVoteIndex = 0;
3075
3076 // send tuning parameters to client
3077 SendTuningParams(ClientId, Zone: pPlayer->m_TuneZone);
3078
3079 // client is ready to enter
3080 pPlayer->m_IsReady = true;
3081 CNetMsg_Sv_ReadyToEnter ReadyMsg;
3082 Server()->SendPackMsg(pMsg: &ReadyMsg, Flags: MSGFLAG_VITAL | MSGFLAG_FLUSH, ClientId);
3083
3084 Server()->ExpireServerInfo();
3085}
3086
3087void CGameContext::ConTuneParam(IConsole::IResult *pResult, void *pUserData)
3088{
3089 CGameContext *pSelf = (CGameContext *)pUserData;
3090 const char *pParamName = pResult->GetString(Index: 0);
3091
3092 if(pResult->NumArguments() == 2)
3093 {
3094 float NewValue = pResult->GetFloat(Index: 1);
3095 if(pSelf->GlobalTuning()->Set(pName: pParamName, Value: NewValue) && pSelf->GlobalTuning()->Get(pName: pParamName, pValue: &NewValue))
3096 {
3097 log_info("tuning", "%s changed to %.2f", pParamName, NewValue);
3098 pSelf->SendTuningParams(ClientId: -1);
3099 }
3100 else
3101 {
3102 log_error("tuning", "No such tuning parameter: %s", pParamName);
3103 }
3104 }
3105 else
3106 {
3107 float Value;
3108 if(pSelf->GlobalTuning()->Get(pName: pParamName, pValue: &Value))
3109 {
3110 log_info("tuning", "%s %.2f", pParamName, Value);
3111 }
3112 else
3113 {
3114 log_error("tuning", "No such tuning parameter: %s", pParamName);
3115 }
3116 }
3117}
3118
3119void CGameContext::ConToggleTuneParam(IConsole::IResult *pResult, void *pUserData)
3120{
3121 CGameContext *pSelf = (CGameContext *)pUserData;
3122 const char *pParamName = pResult->GetString(Index: 0);
3123 float OldValue;
3124
3125 if(!pSelf->GlobalTuning()->Get(pName: pParamName, pValue: &OldValue))
3126 {
3127 log_error("tuning", "No such tuning parameter: %s", pParamName);
3128 return;
3129 }
3130
3131 float NewValue = absolute(a: OldValue - pResult->GetFloat(Index: 1)) < 0.0001f ? pResult->GetFloat(Index: 2) : pResult->GetFloat(Index: 1);
3132
3133 pSelf->GlobalTuning()->Set(pName: pParamName, Value: NewValue);
3134 pSelf->GlobalTuning()->Get(pName: pParamName, pValue: &NewValue);
3135
3136 log_info("tuning", "%s changed to %.2f", pParamName, NewValue);
3137 pSelf->SendTuningParams(ClientId: -1);
3138}
3139
3140void CGameContext::ConTuneReset(IConsole::IResult *pResult, void *pUserData)
3141{
3142 CGameContext *pSelf = (CGameContext *)pUserData;
3143 if(pResult->NumArguments())
3144 {
3145 const char *pParamName = pResult->GetString(Index: 0);
3146 float DefaultValue = 0.0f;
3147
3148 if(CTuningParams::DEFAULT.Get(pName: pParamName, pValue: &DefaultValue) && pSelf->GlobalTuning()->Set(pName: pParamName, Value: DefaultValue) && pSelf->GlobalTuning()->Get(pName: pParamName, pValue: &DefaultValue))
3149 {
3150 log_info("tuning", "%s reset to %.2f", pParamName, DefaultValue);
3151 pSelf->SendTuningParams(ClientId: -1);
3152 }
3153 else
3154 {
3155 log_error("tuning", "No such tuning parameter: %s", pParamName);
3156 }
3157 }
3158 else
3159 {
3160 pSelf->ResetTuning();
3161 log_info("tuning", "Tuning reset");
3162 }
3163}
3164
3165void CGameContext::ConTunes(IConsole::IResult *pResult, void *pUserData)
3166{
3167 CGameContext *pSelf = (CGameContext *)pUserData;
3168 for(int i = 0; i < CTuningParams::Num(); i++)
3169 {
3170 float Value;
3171 pSelf->GlobalTuning()->Get(Index: i, pValue: &Value);
3172 log_info("tuning", "%s %.2f", CTuningParams::Name(i), Value);
3173 }
3174}
3175
3176void CGameContext::ConTuneZone(IConsole::IResult *pResult, void *pUserData)
3177{
3178 CGameContext *pSelf = (CGameContext *)pUserData;
3179 int List = pResult->GetInteger(Index: 0);
3180 const char *pParamName = pResult->GetString(Index: 1);
3181 float NewValue = pResult->GetFloat(Index: 2);
3182
3183 if(List >= 0 && List < TuneZone::NUM)
3184 {
3185 if(pSelf->TuningList()[List].Set(pName: pParamName, Value: NewValue) && pSelf->TuningList()[List].Get(pName: pParamName, pValue: &NewValue))
3186 {
3187 log_info("tuning", "%s in zone %d changed to %.2f", pParamName, List, NewValue);
3188 pSelf->SendTuningParams(ClientId: -1, Zone: List);
3189 }
3190 else
3191 {
3192 log_error("tuning", "No such tuning parameter: %s", pParamName);
3193 }
3194 }
3195}
3196
3197void CGameContext::ConTuneDumpZone(IConsole::IResult *pResult, void *pUserData)
3198{
3199 CGameContext *pSelf = (CGameContext *)pUserData;
3200 int List = pResult->GetInteger(Index: 0);
3201 if(List >= 0 && List < TuneZone::NUM)
3202 {
3203 for(int i = 0; i < CTuningParams::Num(); i++)
3204 {
3205 float Value;
3206 pSelf->TuningList()[List].Get(Index: i, pValue: &Value);
3207 log_info("tuning", "zone %d: %s %.2f", List, CTuningParams::Name(i), Value);
3208 }
3209 }
3210}
3211
3212void CGameContext::ConTuneResetZone(IConsole::IResult *pResult, void *pUserData)
3213{
3214 CGameContext *pSelf = (CGameContext *)pUserData;
3215 if(pResult->NumArguments())
3216 {
3217 int List = pResult->GetInteger(Index: 0);
3218 if(List >= 0 && List < TuneZone::NUM)
3219 {
3220 pSelf->TuningList()[List] = CTuningParams::DEFAULT;
3221 log_info("tuning", "Tunezone %d reset", List);
3222 pSelf->SendTuningParams(ClientId: -1, Zone: List);
3223 }
3224 }
3225 else
3226 {
3227 for(int i = 0; i < TuneZone::NUM; i++)
3228 {
3229 *(pSelf->TuningList() + i) = CTuningParams::DEFAULT;
3230 pSelf->SendTuningParams(ClientId: -1, Zone: i);
3231 }
3232 log_info("tuning", "All Tunezones reset");
3233 }
3234}
3235
3236void CGameContext::ConTuneSetZoneMsgEnter(IConsole::IResult *pResult, void *pUserData)
3237{
3238 CGameContext *pSelf = (CGameContext *)pUserData;
3239 if(pResult->NumArguments())
3240 {
3241 int List = pResult->GetInteger(Index: 0);
3242 if(List >= 0 && List < TuneZone::NUM)
3243 {
3244 str_copy(dst&: pSelf->m_aaZoneEnterMsg[List], src: pResult->GetString(Index: 1));
3245 }
3246 }
3247}
3248
3249void CGameContext::ConTuneSetZoneMsgLeave(IConsole::IResult *pResult, void *pUserData)
3250{
3251 CGameContext *pSelf = (CGameContext *)pUserData;
3252 if(pResult->NumArguments())
3253 {
3254 int List = pResult->GetInteger(Index: 0);
3255 if(List >= 0 && List < TuneZone::NUM)
3256 {
3257 str_copy(dst&: pSelf->m_aaZoneLeaveMsg[List], src: pResult->GetString(Index: 1));
3258 }
3259 }
3260}
3261
3262void CGameContext::ConMapbug(IConsole::IResult *pResult, void *pUserData)
3263{
3264 CGameContext *pSelf = (CGameContext *)pUserData;
3265
3266 if(pSelf->m_pController)
3267 {
3268 log_info("mapbugs", "can't add map bugs after the game started");
3269 return;
3270 }
3271
3272 const char *pMapBugName = pResult->GetString(Index: 0);
3273 switch(pSelf->m_MapBugs.Update(pBug: pMapBugName))
3274 {
3275 case EMapBugUpdate::OK:
3276 break;
3277 case EMapBugUpdate::OVERRIDDEN:
3278 log_info("mapbugs", "map-internal setting overridden by database");
3279 break;
3280 case EMapBugUpdate::NOTFOUND:
3281 log_info("mapbugs", "unknown map bug '%s', ignoring", pMapBugName);
3282 break;
3283 default:
3284 dbg_assert_failed("unreachable");
3285 }
3286}
3287
3288void CGameContext::ConSwitchOpen(IConsole::IResult *pResult, void *pUserData)
3289{
3290 CGameContext *pSelf = (CGameContext *)pUserData;
3291 int Switch = pResult->GetInteger(Index: 0);
3292
3293 if(in_range(a: Switch, upper: (int)pSelf->Switchers().size() - 1))
3294 {
3295 pSelf->Switchers()[Switch].m_Initial = false;
3296 log_info("server", "switch %d opened by default", Switch);
3297 }
3298}
3299
3300void CGameContext::ConPause(IConsole::IResult *pResult, void *pUserData)
3301{
3302 CGameContext *pSelf = (CGameContext *)pUserData;
3303 if(!pSelf->m_pController)
3304 return;
3305
3306 pSelf->m_pController->SetGamePaused(!pSelf->m_pController->IsGamePaused());
3307}
3308
3309void CGameContext::ConChangeMap(IConsole::IResult *pResult, void *pUserData)
3310{
3311 CGameContext *pSelf = (CGameContext *)pUserData;
3312 pSelf->m_pController->ChangeMap(pToMap: pResult->GetString(Index: 0));
3313}
3314
3315void CGameContext::ConRandomMap(IConsole::IResult *pResult, void *pUserData)
3316{
3317 CGameContext *pSelf = (CGameContext *)pUserData;
3318
3319 const int ClientId = pResult->m_ClientId == -1 ? pSelf->m_VoteCreator : pResult->m_ClientId;
3320 int MinStars = pResult->NumArguments() > 0 ? pResult->GetInteger(Index: 0) : -1;
3321 int MaxStars = pResult->NumArguments() > 1 ? pResult->GetInteger(Index: 1) : MinStars;
3322
3323 if(!in_range(a: MinStars, lower: -1, upper: 5) || !in_range(a: MaxStars, lower: -1, upper: 5))
3324 return;
3325
3326 pSelf->m_pScore->RandomMap(ClientId, MinStars, MaxStars);
3327}
3328
3329void CGameContext::ConRandomUnfinishedMap(IConsole::IResult *pResult, void *pUserData)
3330{
3331 CGameContext *pSelf = (CGameContext *)pUserData;
3332
3333 const int ClientId = pResult->m_ClientId == -1 ? pSelf->m_VoteCreator : pResult->m_ClientId;
3334 int MinStars = pResult->NumArguments() > 0 ? pResult->GetInteger(Index: 0) : -1;
3335 int MaxStars = pResult->NumArguments() > 1 ? pResult->GetInteger(Index: 1) : MinStars;
3336
3337 if(!in_range(a: MinStars, lower: -1, upper: 5) || !in_range(a: MaxStars, lower: -1, upper: 5))
3338 return;
3339
3340 pSelf->m_pScore->RandomUnfinishedMap(ClientId, MinStars, MaxStars);
3341}
3342
3343void CGameContext::ConRestart(IConsole::IResult *pResult, void *pUserData)
3344{
3345 CGameContext *pSelf = (CGameContext *)pUserData;
3346 if(pResult->NumArguments())
3347 pSelf->m_pController->DoWarmup(Seconds: pResult->GetInteger(Index: 0));
3348 else
3349 pSelf->m_pController->StartRound();
3350}
3351
3352void CGameContext::ConServerAlert(IConsole::IResult *pResult, void *pUserData)
3353{
3354 CGameContext *pSelf = (CGameContext *)pUserData;
3355
3356 char aBuf[1024];
3357 str_copy(dst&: aBuf, src: pResult->GetString(Index: 0));
3358 str_unescape_newlines(str: aBuf);
3359
3360 pSelf->SendServerAlert(pMessage: aBuf);
3361}
3362
3363void CGameContext::ConModAlert(IConsole::IResult *pResult, void *pUserData)
3364{
3365 CGameContext *pSelf = (CGameContext *)pUserData;
3366
3367 const int Victim = pResult->GetVictim(Slot: 0);
3368 if(!CheckClientId(ClientId: Victim) || !pSelf->m_apPlayers[Victim])
3369 {
3370 log_info("moderator_alert", "Client ID not found: %d", Victim);
3371 return;
3372 }
3373
3374 char aBuf[1024];
3375 str_copy(dst&: aBuf, src: pResult->GetString(Index: 1));
3376 str_unescape_newlines(str: aBuf);
3377
3378 pSelf->SendModeratorAlert(ToClientId: Victim, pMessage: aBuf);
3379}
3380
3381void CGameContext::ConBroadcast(IConsole::IResult *pResult, void *pUserData)
3382{
3383 CGameContext *pSelf = (CGameContext *)pUserData;
3384
3385 char aBuf[1024];
3386 str_copy(dst&: aBuf, src: pResult->GetString(Index: 0));
3387 str_unescape_newlines(str: aBuf);
3388
3389 pSelf->SendBroadcast(pText: aBuf, ClientId: -1);
3390}
3391
3392void CGameContext::ConSay(IConsole::IResult *pResult, void *pUserData)
3393{
3394 CGameContext *pSelf = (CGameContext *)pUserData;
3395 pSelf->SendChat(ChatterClientId: -1, Team: TEAM_ALL, pText: pResult->GetString(Index: 0));
3396}
3397
3398void CGameContext::ConSetTeam(IConsole::IResult *pResult, void *pUserData)
3399{
3400 CGameContext *pSelf = (CGameContext *)pUserData;
3401 if(!pSelf->m_pController)
3402 return;
3403 int Team = pResult->GetInteger(Index: 1);
3404 if(!pSelf->m_pController->IsValidTeam(Team))
3405 {
3406 log_info("server", "Invalid Team: %d", Team);
3407 return;
3408 }
3409
3410 int ClientId = pResult->GetVictim(Slot: 0);
3411 int Delay = pResult->NumArguments() > 2 ? pResult->GetInteger(Index: 2) : 0;
3412 if(!pSelf->m_apPlayers[ClientId])
3413 return;
3414
3415 log_info("server", "moved client %d to the %s", ClientId, pSelf->m_pController->GetTeamName(Team));
3416
3417 pSelf->m_apPlayers[ClientId]->Pause(State: CPlayer::PAUSE_NONE, Force: false); // reset /spec and /pause to allow rejoin
3418 pSelf->m_apPlayers[ClientId]->m_TeamChangeTick = pSelf->Server()->Tick() + pSelf->Server()->TickSpeed() * Delay * 60;
3419 pSelf->m_pController->DoTeamChange(pPlayer: pSelf->m_apPlayers[ClientId], Team, DoChatMsg: true);
3420 if(Team == TEAM_SPECTATORS)
3421 pSelf->m_apPlayers[ClientId]->Pause(State: CPlayer::PAUSE_NONE, Force: true);
3422}
3423
3424void CGameContext::ConHotReload(IConsole::IResult *pResult, void *pUserData)
3425{
3426 CGameContext *pSelf = (CGameContext *)pUserData;
3427 for(int i = 0; i < MAX_CLIENTS; i++)
3428 {
3429 if(!pSelf->GetPlayerChar(ClientId: i))
3430 continue;
3431
3432 CCharacter *pChar = pSelf->GetPlayerChar(ClientId: i);
3433
3434 // Save the tee individually
3435 delete pSelf->m_apSavedTees[i];
3436 pSelf->m_apSavedTees[i] = new CSaveHotReloadTee();
3437 pSelf->m_apSavedTees[i]->Save(pChr: pChar, AddPenalty: false);
3438
3439 // Save the team state
3440 pSelf->m_aTeamMapping[i] = pSelf->GetDDRaceTeam(ClientId: i);
3441 if(pSelf->m_aTeamMapping[i] == TEAM_SUPER)
3442 pSelf->m_aTeamMapping[i] = pChar->m_TeamBeforeSuper;
3443
3444 if(pSelf->m_apSavedTeams[pSelf->m_aTeamMapping[i]])
3445 continue;
3446
3447 pSelf->m_apSavedTeams[pSelf->m_aTeamMapping[i]] = new CSaveTeam();
3448 pSelf->m_apSavedTeams[pSelf->m_aTeamMapping[i]]->Save(pGameServer: pSelf, Team: pSelf->m_aTeamMapping[i], Dry: true, Force: true);
3449 }
3450 pSelf->Server()->ReloadMap();
3451}
3452
3453void CGameContext::ConAddVote(IConsole::IResult *pResult, void *pUserData)
3454{
3455 CGameContext *pSelf = (CGameContext *)pUserData;
3456 const char *pDescription = pResult->GetString(Index: 0);
3457 const char *pCommand = pResult->GetString(Index: 1);
3458
3459 pSelf->AddVote(pDescription, pCommand);
3460}
3461
3462void CGameContext::AddVote(const char *pDescription, const char *pCommand)
3463{
3464 if(m_NumVoteOptions == MAX_VOTE_OPTIONS)
3465 {
3466 log_error("server", "maximum number of vote options reached");
3467 return;
3468 }
3469
3470 // check for valid option
3471 if(!Console()->LineIsValid(pStr: pCommand) || str_length(str: pCommand) >= VOTE_CMD_LENGTH)
3472 {
3473 log_error("server", "skipped invalid command '%s'", pCommand);
3474 return;
3475 }
3476 while(*pDescription == ' ')
3477 pDescription++;
3478 if(str_length(str: pDescription) >= VOTE_DESC_LENGTH || *pDescription == 0)
3479 {
3480 log_error("server", "skipped invalid option '%s'", pDescription);
3481 return;
3482 }
3483
3484 // check for duplicate entry
3485 CVoteOptionServer *pOption = m_pVoteOptionFirst;
3486 while(pOption)
3487 {
3488 if(str_comp_nocase(a: pDescription, b: pOption->m_aDescription) == 0)
3489 {
3490 log_error("server", "option '%s' already exists", pDescription);
3491 return;
3492 }
3493 pOption = pOption->m_pNext;
3494 }
3495
3496 // add the option
3497 ++m_NumVoteOptions;
3498 int Len = str_length(str: pCommand);
3499
3500 pOption = (CVoteOptionServer *)m_pVoteOptionHeap->Allocate(Size: sizeof(CVoteOptionServer) + Len, Alignment: alignof(CVoteOptionServer));
3501 pOption->m_pNext = nullptr;
3502 pOption->m_pPrev = m_pVoteOptionLast;
3503 if(pOption->m_pPrev)
3504 pOption->m_pPrev->m_pNext = pOption;
3505 m_pVoteOptionLast = pOption;
3506 if(!m_pVoteOptionFirst)
3507 m_pVoteOptionFirst = pOption;
3508
3509 str_copy(dst&: pOption->m_aDescription, src: pDescription);
3510 str_copy(dst: pOption->m_aCommand, src: pCommand, dst_size: Len + 1);
3511}
3512
3513void CGameContext::ConRemoveVote(IConsole::IResult *pResult, void *pUserData)
3514{
3515 CGameContext *pSelf = (CGameContext *)pUserData;
3516 const char *pDescription = pResult->GetString(Index: 0);
3517
3518 // check for valid option
3519 CVoteOptionServer *pOption = pSelf->m_pVoteOptionFirst;
3520 while(pOption)
3521 {
3522 if(str_comp_nocase(a: pDescription, b: pOption->m_aDescription) == 0)
3523 break;
3524 pOption = pOption->m_pNext;
3525 }
3526 if(!pOption)
3527 {
3528 log_error("server", "option '%s' does not exist", pDescription);
3529 return;
3530 }
3531
3532 // start reloading vote option list
3533 // clear vote options
3534 CNetMsg_Sv_VoteClearOptions VoteClearOptionsMsg;
3535 pSelf->Server()->SendPackMsg(pMsg: &VoteClearOptionsMsg, Flags: MSGFLAG_VITAL, ClientId: -1);
3536
3537 // reset sending of vote options
3538 for(auto &pPlayer : pSelf->m_apPlayers)
3539 {
3540 if(pPlayer)
3541 pPlayer->m_SendVoteIndex = 0;
3542 }
3543
3544 // TODO: improve this
3545 // remove the option
3546 --pSelf->m_NumVoteOptions;
3547
3548 CHeap *pVoteOptionHeap = new CHeap();
3549 CVoteOptionServer *pVoteOptionFirst = nullptr;
3550 CVoteOptionServer *pVoteOptionLast = nullptr;
3551 int NumVoteOptions = pSelf->m_NumVoteOptions;
3552 for(CVoteOptionServer *pSrc = pSelf->m_pVoteOptionFirst; pSrc; pSrc = pSrc->m_pNext)
3553 {
3554 if(pSrc == pOption)
3555 continue;
3556
3557 // copy option
3558 int Len = str_length(str: pSrc->m_aCommand);
3559 CVoteOptionServer *pDst = (CVoteOptionServer *)pVoteOptionHeap->Allocate(Size: sizeof(CVoteOptionServer) + Len, Alignment: alignof(CVoteOptionServer));
3560 pDst->m_pNext = nullptr;
3561 pDst->m_pPrev = pVoteOptionLast;
3562 if(pDst->m_pPrev)
3563 pDst->m_pPrev->m_pNext = pDst;
3564 pVoteOptionLast = pDst;
3565 if(!pVoteOptionFirst)
3566 pVoteOptionFirst = pDst;
3567
3568 str_copy(dst&: pDst->m_aDescription, src: pSrc->m_aDescription);
3569 str_copy(dst: pDst->m_aCommand, src: pSrc->m_aCommand, dst_size: Len + 1);
3570 }
3571
3572 // clean up
3573 delete pSelf->m_pVoteOptionHeap;
3574 pSelf->m_pVoteOptionHeap = pVoteOptionHeap;
3575 pSelf->m_pVoteOptionFirst = pVoteOptionFirst;
3576 pSelf->m_pVoteOptionLast = pVoteOptionLast;
3577 pSelf->m_NumVoteOptions = NumVoteOptions;
3578}
3579
3580void CGameContext::ConForceVote(IConsole::IResult *pResult, void *pUserData)
3581{
3582 CGameContext *pSelf = (CGameContext *)pUserData;
3583 const char *pType = pResult->GetString(Index: 0);
3584 const char *pValue = pResult->GetString(Index: 1);
3585 const char *pReason = pResult->NumArguments() > 2 && pResult->GetString(Index: 2)[0] ? pResult->GetString(Index: 2) : "No reason given";
3586 char aBuf[128] = {0};
3587
3588 if(str_comp_nocase(a: pType, b: "option") == 0)
3589 {
3590 CVoteOptionServer *pOption = pSelf->m_pVoteOptionFirst;
3591 while(pOption)
3592 {
3593 if(str_comp_nocase(a: pValue, b: pOption->m_aDescription) == 0)
3594 {
3595 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "authorized player forced server option '%s' (%s)", pValue, pReason);
3596 pSelf->SendChatTarget(To: -1, pText: aBuf, VersionFlags: FLAG_SIX);
3597 // m_VoteCreator must be a valid client id or -1, but the command can also be executed by console pseudo clients (e.g. map configs)
3598 pSelf->m_VoteCreator = pResult->m_ClientId >= 0 ? pResult->m_ClientId : -1;
3599 pSelf->Console()->ExecuteLine(pStr: pOption->m_aCommand, ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
3600 break;
3601 }
3602
3603 pOption = pOption->m_pNext;
3604 }
3605
3606 if(!pOption)
3607 {
3608 log_error("server", "'%s' isn't an option on this server", pValue);
3609 return;
3610 }
3611 }
3612 else if(str_comp_nocase(a: pType, b: "kick") == 0)
3613 {
3614 if(pResult->m_ClientId >= 0 && !pSelf->Server()->ClientSupportsServerMaxClients(ClientId: pResult->m_ClientId))
3615 {
3616 log_error("server", "Your client does not see the real client IDs of this server. Use a more recent DDNet client.");
3617 return;
3618 }
3619 int KickId = str_toint(str: pValue);
3620 if(KickId < 0 || KickId >= MAX_CLIENTS || !pSelf->m_apPlayers[KickId])
3621 {
3622 log_error("server", "Invalid client id to kick");
3623 return;
3624 }
3625
3626 if(!g_Config.m_SvVoteKickBantime)
3627 {
3628 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "kick %d %s", KickId, pReason);
3629 pSelf->Console()->ExecuteLine(pStr: aBuf, ClientId: IConsole::CLIENT_ID_UNSPECIFIED, InterpretSemicolons: false);
3630 }
3631 else
3632 {
3633 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "ban %s %d %s", pSelf->Server()->ClientAddrString(ClientId: KickId, IncludePort: false), g_Config.m_SvVoteKickBantime, pReason);
3634 pSelf->Console()->ExecuteLine(pStr: aBuf, ClientId: IConsole::CLIENT_ID_UNSPECIFIED, InterpretSemicolons: false);
3635 }
3636 }
3637 else if(str_comp_nocase(a: pType, b: "spectate") == 0)
3638 {
3639 if(pResult->m_ClientId >= 0 && !pSelf->Server()->ClientSupportsServerMaxClients(ClientId: pResult->m_ClientId))
3640 {
3641 log_error("server", "Your client does not see the real client IDs of this server. Use a more recent DDNet client.");
3642 return;
3643 }
3644 int SpectateId = str_toint(str: pValue);
3645 if(SpectateId < 0 || SpectateId >= MAX_CLIENTS || !pSelf->m_apPlayers[SpectateId] || pSelf->m_apPlayers[SpectateId]->GetTeam() == TEAM_SPECTATORS)
3646 {
3647 log_error("server", "Invalid client id to move");
3648 return;
3649 }
3650
3651 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "'%s' was moved to spectator (%s)", pSelf->Server()->ClientName(ClientId: SpectateId), pReason);
3652 pSelf->SendChatTarget(To: -1, pText: aBuf);
3653 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "set_team %d -1 %d", SpectateId, g_Config.m_SvVoteSpectateRejoindelay);
3654 pSelf->Console()->ExecuteLine(pStr: aBuf, ClientId: IConsole::CLIENT_ID_UNSPECIFIED, InterpretSemicolons: false);
3655 }
3656}
3657
3658void CGameContext::ConClearVotes(IConsole::IResult *pResult, void *pUserData)
3659{
3660 CGameContext *pSelf = (CGameContext *)pUserData;
3661
3662 CNetMsg_Sv_VoteClearOptions VoteClearOptionsMsg;
3663 pSelf->Server()->SendPackMsg(pMsg: &VoteClearOptionsMsg, Flags: MSGFLAG_VITAL, ClientId: -1);
3664 pSelf->m_pVoteOptionHeap->Reset();
3665 pSelf->m_pVoteOptionFirst = nullptr;
3666 pSelf->m_pVoteOptionLast = nullptr;
3667 pSelf->m_NumVoteOptions = 0;
3668
3669 // reset sending of vote options
3670 for(auto &pPlayer : pSelf->m_apPlayers)
3671 {
3672 if(pPlayer)
3673 pPlayer->m_SendVoteIndex = 0;
3674 }
3675}
3676
3677struct CMapNameItem
3678{
3679 char m_aName[IO_MAX_PATH_LENGTH - 4];
3680 bool m_IsDirectory;
3681
3682 static bool CompareFilenameAscending(const CMapNameItem Lhs, const CMapNameItem Rhs)
3683 {
3684 if(str_comp(a: Rhs.m_aName, b: "..") == 0)
3685 return false;
3686 if(str_comp(a: Lhs.m_aName, b: "..") == 0)
3687 return true;
3688 if(Lhs.m_IsDirectory != Rhs.m_IsDirectory)
3689 return Lhs.m_IsDirectory;
3690 return str_comp_filenames(a: Lhs.m_aName, b: Rhs.m_aName) < 0;
3691 }
3692};
3693
3694void CGameContext::ConAddMapVotes(IConsole::IResult *pResult, void *pUserData)
3695{
3696 CGameContext *pSelf = (CGameContext *)pUserData;
3697
3698 const char *pDirectory = pResult->NumArguments() > 0 ? pResult->GetString(Index: 0) : "";
3699
3700 // Don't allow moving to parent directories
3701 if(str_find_nocase(haystack: pDirectory, needle: ".."))
3702 return;
3703
3704 char aPath[IO_MAX_PATH_LENGTH] = "maps/";
3705 str_append(dst&: aPath, src: pDirectory);
3706
3707 std::vector<CMapNameItem> vMapList;
3708 pSelf->Storage()->ListDirectory(Type: IStorage::TYPE_ALL, pPath: aPath, pfnCallback: MapScan, pUser: &vMapList);
3709 std::sort(first: vMapList.begin(), last: vMapList.end(), comp: CMapNameItem::CompareFilenameAscending);
3710
3711 for(const auto &Item : vMapList)
3712 {
3713 if(!str_comp(a: Item.m_aName, b: "..") && (!str_comp(a: aPath, b: "maps/")))
3714 continue;
3715
3716 char aDescription[VOTE_DESC_LENGTH];
3717 str_format(buffer: aDescription, buffer_size: sizeof(aDescription), format: "%s: %s%s", Item.m_IsDirectory ? "Directory" : "Map", Item.m_aName, Item.m_IsDirectory ? "/" : "");
3718
3719 char aOptionEscaped[IO_MAX_PATH_LENGTH * 2];
3720 {
3721 char *pDst = aOptionEscaped;
3722 str_escape(dst: &pDst, src: Item.m_aName, end: aOptionEscaped + sizeof(aOptionEscaped));
3723 }
3724
3725 char aDirectory[IO_MAX_PATH_LENGTH];
3726 str_copy(dst&: aDirectory, src: pDirectory);
3727
3728 if(!str_comp(a: Item.m_aName, b: ".."))
3729 {
3730 if(fs_parent_dir(path: aDirectory) != 0)
3731 {
3732 aDirectory[0] = '\0';
3733 }
3734 }
3735
3736 char aDirectoryEscaped[IO_MAX_PATH_LENGTH * 2];
3737 {
3738 char *pDst = aDirectoryEscaped;
3739 str_escape(dst: &pDst, src: aDirectory, end: aDirectoryEscaped + sizeof(aDirectoryEscaped));
3740 }
3741
3742 char aCommand[VOTE_CMD_LENGTH];
3743 if(!str_comp(a: Item.m_aName, b: ".."))
3744 {
3745 str_format(buffer: aCommand, buffer_size: sizeof(aCommand), format: "clear_votes; add_map_votes \"%s\"", aDirectoryEscaped);
3746 }
3747 else if(Item.m_IsDirectory)
3748 {
3749 str_format(buffer: aCommand, buffer_size: sizeof(aCommand), format: "clear_votes; add_map_votes \"%s/%s\"", aDirectoryEscaped, aOptionEscaped);
3750 }
3751 else
3752 {
3753 str_format(buffer: aCommand, buffer_size: sizeof(aCommand), format: "change_map \"%s%s%s\"", aDirectoryEscaped, aDirectoryEscaped[0] == '\0' ? "" : "/", aOptionEscaped);
3754 }
3755
3756 pSelf->AddVote(pDescription: aDescription, pCommand: aCommand);
3757 }
3758
3759 log_info("server", "added maps to votes");
3760}
3761
3762int CGameContext::MapScan(const char *pName, int IsDir, int DirType, void *pUserData)
3763{
3764 if((!IsDir && !str_endswith(str: pName, suffix: ".map")) || !str_comp(a: pName, b: "."))
3765 return 0;
3766
3767 CMapNameItem Item;
3768 Item.m_IsDirectory = IsDir;
3769 if(!IsDir)
3770 str_truncate(dst: Item.m_aName, dst_size: sizeof(Item.m_aName), src: pName, truncation_len: str_length(str: pName) - str_length(str: ".map"));
3771 else
3772 str_copy(dst&: Item.m_aName, src: pName);
3773 static_cast<std::vector<CMapNameItem> *>(pUserData)->push_back(x: Item);
3774
3775 return 0;
3776}
3777
3778void CGameContext::ConVote(IConsole::IResult *pResult, void *pUserData)
3779{
3780 CGameContext *pSelf = (CGameContext *)pUserData;
3781
3782 if(str_comp_nocase(a: pResult->GetString(Index: 0), b: "yes") == 0)
3783 pSelf->ForceVote(Success: true);
3784 else if(str_comp_nocase(a: pResult->GetString(Index: 0), b: "no") == 0)
3785 pSelf->ForceVote(Success: false);
3786}
3787
3788void CGameContext::ConVotes(IConsole::IResult *pResult, void *pUserData)
3789{
3790 CGameContext *pSelf = (CGameContext *)pUserData;
3791
3792 int Page = pResult->NumArguments() > 0 ? pResult->GetInteger(Index: 0) : 0;
3793 static const int s_EntriesPerPage = 20;
3794 const int Start = Page * s_EntriesPerPage;
3795 const int End = (Page + 1) * s_EntriesPerPage;
3796
3797 char aBuf[512];
3798 int Count = 0;
3799 for(CVoteOptionServer *pOption = pSelf->m_pVoteOptionFirst; pOption; pOption = pOption->m_pNext, Count++)
3800 {
3801 if(Count < Start || Count >= End)
3802 {
3803 continue;
3804 }
3805
3806 str_copy(dst&: aBuf, src: "add_vote \"");
3807 char *pDst = aBuf + str_length(str: aBuf);
3808 str_escape(dst: &pDst, src: pOption->m_aDescription, end: aBuf + sizeof(aBuf));
3809 str_append(dst&: aBuf, src: "\" \"");
3810 pDst = aBuf + str_length(str: aBuf);
3811 str_escape(dst: &pDst, src: pOption->m_aCommand, end: aBuf + sizeof(aBuf));
3812 str_append(dst&: aBuf, src: "\"");
3813
3814 log_info("votes", "%s", aBuf);
3815 }
3816 log_info("votes", "%d %s, showing entries %d - %d", Count, Count == 1 ? "vote" : "votes", Start, End - 1);
3817}
3818
3819void CGameContext::ConchainSpecialMotdupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
3820{
3821 pfnCallback(pResult, pCallbackUserData);
3822 if(pResult->NumArguments())
3823 {
3824 CGameContext *pSelf = (CGameContext *)pUserData;
3825 pSelf->SendMotd(ClientId: -1);
3826 }
3827}
3828
3829void CGameContext::ConchainSettingUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
3830{
3831 pfnCallback(pResult, pCallbackUserData);
3832 if(pResult->NumArguments())
3833 {
3834 CGameContext *pSelf = (CGameContext *)pUserData;
3835 pSelf->SendSettings(ClientId: -1);
3836 }
3837}
3838
3839void CGameContext::ConchainPracticeByDefaultUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
3840{
3841 const int OldValue = g_Config.m_SvPracticeByDefault;
3842 pfnCallback(pResult, pCallbackUserData);
3843
3844 if(pResult->NumArguments() && g_Config.m_SvTestingCommands)
3845 {
3846 CGameContext *pSelf = (CGameContext *)pUserData;
3847
3848 if(pSelf->m_pController == nullptr)
3849 return;
3850
3851 const int Enable = pResult->GetInteger(Index: 0);
3852 if(Enable == OldValue)
3853 return;
3854
3855 char aBuf[256];
3856 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "Practice is %s by default.", Enable ? "enabled" : "disabled");
3857 if(Enable)
3858 str_append(dst&: aBuf, src: " Join a team and /unpractice to turn it off for your team.");
3859
3860 pSelf->SendChat(ChatterClientId: -1, Team: TEAM_ALL, pText: aBuf);
3861
3862 for(int Team = 0; Team < NUM_DDRACE_TEAMS; Team++)
3863 {
3864 if(Team == TEAM_FLOCK || pSelf->m_pController->Teams().TeamSize(Team) == 0)
3865 {
3866 pSelf->m_pController->Teams().SetPractice(Team, Enabled: Enable);
3867 }
3868 }
3869 }
3870}
3871
3872void CGameContext::ConchainTeleOthersAuthLevel(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
3873{
3874 const char *pValue = pResult->GetString(Index: 0);
3875 if(pResult->NumArguments() && !CAuthManager::RoleNameToAuthLevel(pRoleName: pValue).has_value())
3876 {
3877 if(str_comp(a: pValue, b: "1") == 0)
3878 {
3879 log_warn("server", "got deprecated value %s for sv_tele_others_auth_level, please use \"helper\" instead", pValue);
3880 }
3881 else if(str_comp(a: pValue, b: "2") == 0)
3882 {
3883 log_warn("server", "got deprecated value %s for sv_tele_others_auth_level, please use \"moderator\" instead", pValue);
3884 }
3885 else if(str_comp(a: pValue, b: "3") == 0)
3886 {
3887 log_warn("server", "got deprecated value %s for sv_tele_others_auth_level, please use \"admin\" instead", pValue);
3888 }
3889 else
3890 {
3891 log_error("server", "Value can only be one of those: helper, moderator, admin");
3892 return;
3893 }
3894 }
3895
3896 pfnCallback(pResult, pCallbackUserData);
3897}
3898
3899void CGameContext::OnConsoleInit()
3900{
3901 m_pServer = Kernel()->RequestInterface<IServer>();
3902 m_pConfigManager = Kernel()->RequestInterface<IConfigManager>();
3903 m_pConfig = m_pConfigManager->Values();
3904 m_pConsole = Kernel()->RequestInterface<IConsole>();
3905 m_pEngine = Kernel()->RequestInterface<IEngine>();
3906 m_pStorage = Kernel()->RequestInterface<IStorage>();
3907
3908 Console()->Register(pName: "tune", pParams: "s[tuning] ?f[value]", Flags: CFGFLAG_SERVER | CFGFLAG_GAME, pfnFunc: ConTuneParam, pUser: this, pHelp: "Tune variable to value or show current value");
3909 Console()->Register(pName: "toggle_tune", pParams: "s[tuning] f[value 1] f[value 2]", Flags: CFGFLAG_SERVER, pfnFunc: ConToggleTuneParam, pUser: this, pHelp: "Toggle tune variable");
3910 Console()->Register(pName: "tune_reset", pParams: "?s[tuning]", Flags: CFGFLAG_SERVER, pfnFunc: ConTuneReset, pUser: this, pHelp: "Reset all or one tuning variable to default");
3911 Console()->Register(pName: "tunes", pParams: "", Flags: CFGFLAG_SERVER, pfnFunc: ConTunes, pUser: this, pHelp: "List all tuning variables and their values");
3912 Console()->Register(pName: "tune_zone", pParams: "i[zone] s[tuning] f[value]", Flags: CFGFLAG_SERVER | CFGFLAG_GAME, pfnFunc: ConTuneZone, pUser: this, pHelp: "Tune in zone a variable to value");
3913 Console()->Register(pName: "tune_zone_dump", pParams: "i[zone]", Flags: CFGFLAG_SERVER, pfnFunc: ConTuneDumpZone, pUser: this, pHelp: "Dump zone tuning in zone x");
3914 Console()->Register(pName: "tune_zone_reset", pParams: "?i[zone]", Flags: CFGFLAG_SERVER, pfnFunc: ConTuneResetZone, pUser: this, pHelp: "Reset zone tuning in zone x or in all zones");
3915 Console()->Register(pName: "tune_zone_enter", pParams: "i[zone] r[message]", Flags: CFGFLAG_SERVER | CFGFLAG_GAME, pfnFunc: ConTuneSetZoneMsgEnter, pUser: this, pHelp: "Which message to display on zone enter; use 0 for normal area");
3916 Console()->Register(pName: "tune_zone_leave", pParams: "i[zone] r[message]", Flags: CFGFLAG_SERVER | CFGFLAG_GAME, pfnFunc: ConTuneSetZoneMsgLeave, pUser: this, pHelp: "Which message to display on zone leave; use 0 for normal area");
3917 Console()->Register(pName: "mapbug", pParams: "s[mapbug]", Flags: CFGFLAG_SERVER | CFGFLAG_GAME, pfnFunc: ConMapbug, pUser: this, pHelp: "Enable map compatibility mode using the specified bug (example: grenade-doubleexplosion@ddnet.tw)");
3918 Console()->Register(pName: "switch_open", pParams: "i[switch]", Flags: CFGFLAG_SERVER | CFGFLAG_GAME, pfnFunc: ConSwitchOpen, pUser: this, pHelp: "Whether a switch is deactivated by default (otherwise activated)");
3919 Console()->Register(pName: "pause_game", pParams: "", Flags: CFGFLAG_SERVER, pfnFunc: ConPause, pUser: this, pHelp: "Pause/unpause game");
3920 Console()->Register(pName: "change_map", pParams: "r[map]", Flags: CFGFLAG_SERVER | CFGFLAG_STORE, pfnFunc: ConChangeMap, pUser: this, pHelp: "Change map");
3921 Console()->Register(pName: "random_map", pParams: "?i[stars] ?i[max stars]", Flags: CFGFLAG_SERVER | CFGFLAG_STORE, pfnFunc: ConRandomMap, pUser: this, pHelp: "Random map");
3922 Console()->Register(pName: "random_unfinished_map", pParams: "?i[stars] ?i[max stars]", Flags: CFGFLAG_SERVER | CFGFLAG_STORE, pfnFunc: ConRandomUnfinishedMap, pUser: this, pHelp: "Random unfinished map");
3923 Console()->Register(pName: "restart", pParams: "?i[seconds]", Flags: CFGFLAG_SERVER | CFGFLAG_STORE, pfnFunc: ConRestart, pUser: this, pHelp: "Restart in x seconds (0 = abort)");
3924 Console()->Register(pName: "server_alert", pParams: "r[message]", Flags: CFGFLAG_SERVER, pfnFunc: ConServerAlert, pUser: this, pHelp: "Send a server alert message to all players");
3925 Console()->Register(pName: "mod_alert", pParams: "v[id] r[message]", Flags: CFGFLAG_SERVER, pfnFunc: ConModAlert, pUser: this, pHelp: "Send a moderator alert message to player");
3926 Console()->Register(pName: "broadcast", pParams: "r[message]", Flags: CFGFLAG_SERVER, pfnFunc: ConBroadcast, pUser: this, pHelp: "Broadcast message");
3927 Console()->Register(pName: "say", pParams: "r[message]", Flags: CFGFLAG_SERVER, pfnFunc: ConSay, pUser: this, pHelp: "Say in chat");
3928 Console()->Register(pName: "set_team", pParams: "v[id] i[team-id] ?i[delay in minutes]", Flags: CFGFLAG_SERVER, pfnFunc: ConSetTeam, pUser: this, pHelp: "Set team for a player (spectators = -1, game = 0)");
3929 Console()->Register(pName: "hot_reload", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConHotReload, pUser: this, pHelp: "Reload the map while preserving the state of tees and teams");
3930 Console()->Register(pName: "reload_censorlist", pParams: "", Flags: CFGFLAG_SERVER, pfnFunc: ConReloadCensorlist, pUser: this, pHelp: "Reload the censorlist");
3931
3932 Console()->Register(pName: "add_vote", pParams: "s[name] r[command]", Flags: CFGFLAG_SERVER, pfnFunc: ConAddVote, pUser: this, pHelp: "Add a voting option");
3933 Console()->Register(pName: "remove_vote", pParams: "r[name]", Flags: CFGFLAG_SERVER, pfnFunc: ConRemoveVote, pUser: this, pHelp: "remove a voting option");
3934 Console()->Register(pName: "force_vote", pParams: "s[name] s[command] ?r[reason]", Flags: CFGFLAG_SERVER, pfnFunc: ConForceVote, pUser: this, pHelp: "Force a voting option");
3935 Console()->Register(pName: "clear_votes", pParams: "", Flags: CFGFLAG_SERVER, pfnFunc: ConClearVotes, pUser: this, pHelp: "Clears the voting options");
3936 Console()->Register(pName: "add_map_votes", pParams: "?s[directory]", Flags: CFGFLAG_SERVER, pfnFunc: ConAddMapVotes, pUser: this, pHelp: "Automatically adds voting options for all maps");
3937 Console()->Register(pName: "vote", pParams: "r['yes'|'no']", Flags: CFGFLAG_SERVER, pfnFunc: ConVote, pUser: this, pHelp: "Force a vote to yes/no");
3938 Console()->Register(pName: "votes", pParams: "?i[page]", Flags: CFGFLAG_SERVER, pfnFunc: ConVotes, pUser: this, pHelp: "Show all votes (page 0 by default, 20 entries per page)");
3939 Console()->Register(pName: "dump_antibot", pParams: "", Flags: CFGFLAG_SERVER | CFGFLAG_STORE, pfnFunc: ConDumpAntibot, pUser: this, pHelp: "Dumps the antibot status");
3940 Console()->Register(pName: "antibot", pParams: "r[command]", Flags: CFGFLAG_SERVER | CFGFLAG_STORE, pfnFunc: ConAntibot, pUser: this, pHelp: "Sends a command to the antibot");
3941
3942 Console()->Chain(pName: "sv_motd", pfnChainFunc: ConchainSpecialMotdupdate, pUser: this);
3943
3944 Console()->Chain(pName: "sv_vote_kick", pfnChainFunc: ConchainSettingUpdate, pUser: this);
3945 Console()->Chain(pName: "sv_vote_kick_min", pfnChainFunc: ConchainSettingUpdate, pUser: this);
3946 Console()->Chain(pName: "sv_vote_spectate", pfnChainFunc: ConchainSettingUpdate, pUser: this);
3947 Console()->Chain(pName: "sv_spectator_slots", pfnChainFunc: ConchainSettingUpdate, pUser: this);
3948
3949 RegisterDDRaceCommands();
3950 RegisterChatCommands();
3951}
3952
3953void CGameContext::RegisterDDRaceCommands()
3954{
3955 Console()->Register(pName: "kill_pl", pParams: "v[id] ?r[reason]", Flags: CFGFLAG_SERVER, pfnFunc: ConKillPlayer, pUser: this, pHelp: "Kills a player and announces the kill");
3956 Console()->Register(pName: "totele", pParams: "i[number]", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConToTeleporter, pUser: this, pHelp: "Teleports you to teleporter i");
3957 Console()->Register(pName: "totelecp", pParams: "i[number]", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConToCheckTeleporter, pUser: this, pHelp: "Teleports you to checkpoint teleporter i");
3958 Console()->Register(pName: "tele", pParams: "?v[id] ?v[id]", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConTeleport, pUser: this, pHelp: "Teleports player i (or you) to player i (or you to where you look at)");
3959 Console()->Register(pName: "addweapon", pParams: "i[weapon-id]", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConAddWeapon, pUser: this, pHelp: "Gives weapon with id i to you (all = -1, hammer = 0, gun = 1, shotgun = 2, grenade = 3, laser = 4, ninja = 5)");
3960 Console()->Register(pName: "removeweapon", pParams: "i[weapon-id]", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConRemoveWeapon, pUser: this, pHelp: "removes weapon with id i from you (all = -1, hammer = 0, gun = 1, shotgun = 2, grenade = 3, laser = 4, ninja = 5)");
3961 Console()->Register(pName: "shotgun", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConShotgun, pUser: this, pHelp: "Gives a shotgun to you");
3962 Console()->Register(pName: "grenade", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConGrenade, pUser: this, pHelp: "Gives a grenade launcher to you");
3963 Console()->Register(pName: "laser", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConLaser, pUser: this, pHelp: "Gives a laser to you");
3964 Console()->Register(pName: "rifle", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConLaser, pUser: this, pHelp: "Gives a laser to you");
3965 Console()->Register(pName: "jetpack", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConJetpack, pUser: this, pHelp: "Gives jetpack to you");
3966 Console()->Register(pName: "setjumps", pParams: "i[jumps]", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConSetJumps, pUser: this, pHelp: "Gives you as many jumps as you specify");
3967 Console()->Register(pName: "weapons", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConWeapons, pUser: this, pHelp: "Gives all weapons to you");
3968 Console()->Register(pName: "unshotgun", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConUnShotgun, pUser: this, pHelp: "Removes the shotgun from you");
3969 Console()->Register(pName: "ungrenade", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConUnGrenade, pUser: this, pHelp: "Removes the grenade launcher from you");
3970 Console()->Register(pName: "unlaser", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConUnLaser, pUser: this, pHelp: "Removes the laser from you");
3971 Console()->Register(pName: "unrifle", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConUnLaser, pUser: this, pHelp: "Removes the laser from you");
3972 Console()->Register(pName: "unjetpack", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConUnJetpack, pUser: this, pHelp: "Removes the jetpack from you");
3973 Console()->Register(pName: "unweapons", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConUnWeapons, pUser: this, pHelp: "Removes all weapons from you");
3974 Console()->Register(pName: "ninja", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConNinja, pUser: this, pHelp: "Makes you a ninja");
3975 Console()->Register(pName: "unninja", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConUnNinja, pUser: this, pHelp: "Removes ninja from you");
3976 Console()->Register(pName: "super", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConSuper, pUser: this, pHelp: "Makes you super");
3977 Console()->Register(pName: "unsuper", pParams: "", Flags: CFGFLAG_SERVER, pfnFunc: ConUnSuper, pUser: this, pHelp: "Removes super from you");
3978 Console()->Register(pName: "invincible", pParams: "?i['0'|'1']", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConToggleInvincible, pUser: this, pHelp: "Toggles invincible mode");
3979 Console()->Register(pName: "infinite_jump", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConEndlessJump, pUser: this, pHelp: "Gives you infinite jump");
3980 Console()->Register(pName: "uninfinite_jump", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConUnEndlessJump, pUser: this, pHelp: "Removes infinite jump from you");
3981 Console()->Register(pName: "endless_hook", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConEndlessHook, pUser: this, pHelp: "Gives you endless hook");
3982 Console()->Register(pName: "unendless_hook", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConUnEndlessHook, pUser: this, pHelp: "Removes endless hook from you");
3983 Console()->Register(pName: "setswitch", pParams: "i[switch] ?i['0'|'1'] ?i[seconds]", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConSetSwitch, pUser: this, pHelp: "Toggle or set the switch on or off for the specified time (or indefinitely by default)");
3984 Console()->Register(pName: "solo", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConSolo, pUser: this, pHelp: "Puts you into solo part");
3985 Console()->Register(pName: "unsolo", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConUnSolo, pUser: this, pHelp: "Puts you out of solo part");
3986 Console()->Register(pName: "freeze", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConFreeze, pUser: this, pHelp: "Puts you into freeze");
3987 Console()->Register(pName: "unfreeze", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConUnfreeze, pUser: this, pHelp: "Puts you out of freeze");
3988 Console()->Register(pName: "deep", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConDeep, pUser: this, pHelp: "Puts you into deep freeze");
3989 Console()->Register(pName: "undeep", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConUnDeep, pUser: this, pHelp: "Puts you out of deep freeze");
3990 Console()->Register(pName: "livefreeze", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConLiveFreeze, pUser: this, pHelp: "Makes you live frozen");
3991 Console()->Register(pName: "unlivefreeze", pParams: "", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConUnLiveFreeze, pUser: this, pHelp: "Puts you out of live freeze");
3992 Console()->Register(pName: "left", pParams: "?i[tiles]", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConGoLeft, pUser: this, pHelp: "Makes you move 1 tile left");
3993 Console()->Register(pName: "right", pParams: "?i[tiles]", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConGoRight, pUser: this, pHelp: "Makes you move 1 tile right");
3994 Console()->Register(pName: "up", pParams: "?i[tiles]", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConGoUp, pUser: this, pHelp: "Makes you move 1 tile up");
3995 Console()->Register(pName: "down", pParams: "?i[tiles]", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConGoDown, pUser: this, pHelp: "Makes you move 1 tile down");
3996
3997 Console()->Register(pName: "move", pParams: "i[x] i[y]", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConMove, pUser: this, pHelp: "Moves to the tile with x/y-number ii");
3998 Console()->Register(pName: "move_raw", pParams: "i[x] i[y]", Flags: CFGFLAG_SERVER | CMDFLAG_TEST, pfnFunc: ConMoveRaw, pUser: this, pHelp: "Moves to the point with x/y-coordinates ii");
3999 Console()->Register(pName: "force_pause", pParams: "v[id] i[seconds]", Flags: CFGFLAG_SERVER, pfnFunc: ConForcePause, pUser: this, pHelp: "Force i to pause for i seconds");
4000 Console()->Register(pName: "force_unpause", pParams: "v[id]", Flags: CFGFLAG_SERVER, pfnFunc: ConForcePause, pUser: this, pHelp: "Set force-pause timer of i to 0.");
4001
4002 Console()->Register(pName: "set_team_ddr", pParams: "v[id] i[team]", Flags: CFGFLAG_SERVER, pfnFunc: ConSetDDRTeam, pUser: this, pHelp: "Set ddrace team for a player");
4003 Console()->Register(pName: "uninvite", pParams: "v[id] i[team]", Flags: CFGFLAG_SERVER, pfnFunc: ConUninvite, pUser: this, pHelp: "Uninvite player from team");
4004
4005 Console()->Register(pName: "mute", pParams: "", Flags: CFGFLAG_SERVER, pfnFunc: ConMute, pUser: this, pHelp: "Deprecated. Use either 'muteid <client_id> <seconds> <reason>' or 'muteip <ip> <seconds> <reason>'");
4006 Console()->Register(pName: "muteid", pParams: "v[id] i[seconds] ?r[reason]", Flags: CFGFLAG_SERVER, pfnFunc: ConMuteId, pUser: this, pHelp: "Mute player with client ID");
4007 Console()->Register(pName: "muteip", pParams: "s[ip] i[seconds] ?r[reason]", Flags: CFGFLAG_SERVER, pfnFunc: ConMuteIp, pUser: this, pHelp: "Mute player with IP address");
4008 Console()->Register(pName: "unmute", pParams: "i[index]", Flags: CFGFLAG_SERVER, pfnFunc: ConUnmute, pUser: this, pHelp: "Unmute player with list index");
4009 Console()->Register(pName: "unmuteid", pParams: "v[id]", Flags: CFGFLAG_SERVER, pfnFunc: ConUnmuteId, pUser: this, pHelp: "Unmute player with client ID");
4010 Console()->Register(pName: "unmuteip", pParams: "s[ip]", Flags: CFGFLAG_SERVER, pfnFunc: ConUnmuteIp, pUser: this, pHelp: "Unmute player with IP address");
4011 Console()->Register(pName: "mutes", pParams: "?i[page]", Flags: CFGFLAG_SERVER, pfnFunc: ConMutes, pUser: this, pHelp: "Show list of mutes (page 1 by default, 20 entries per page)");
4012
4013 Console()->Register(pName: "vote_mute", pParams: "", Flags: CFGFLAG_SERVER, pfnFunc: ConVoteMute, pUser: this, pHelp: "Deprecated. Use either 'vote_muteid <client_id> <seconds> <reason>' or 'vote_muteip <ip> <seconds> <reason>'");
4014 Console()->Register(pName: "vote_muteid", pParams: "v[id] i[seconds] ?r[reason]", Flags: CFGFLAG_SERVER, pfnFunc: ConVoteMuteId, pUser: this, pHelp: "Remove right to vote from player with client ID");
4015 Console()->Register(pName: "vote_muteip", pParams: "s[ip] i[seconds] ?r[reason]", Flags: CFGFLAG_SERVER, pfnFunc: ConVoteMuteIp, pUser: this, pHelp: "Remove right to vote from player with IP address");
4016 Console()->Register(pName: "vote_unmute", pParams: "i[index]", Flags: CFGFLAG_SERVER, pfnFunc: ConVoteUnmute, pUser: this, pHelp: "Give back right to vote to player with list index");
4017 Console()->Register(pName: "vote_unmuteid", pParams: "v[id]", Flags: CFGFLAG_SERVER, pfnFunc: ConVoteUnmuteId, pUser: this, pHelp: "Give back right to vote to player with client ID");
4018 Console()->Register(pName: "vote_unmuteip", pParams: "s[ip]", Flags: CFGFLAG_SERVER, pfnFunc: ConVoteUnmuteIp, pUser: this, pHelp: "Give back right to vote to player with IP address");
4019 Console()->Register(pName: "vote_mutes", pParams: "?i[page]", Flags: CFGFLAG_SERVER, pfnFunc: ConVoteMutes, pUser: this, pHelp: "Show list of vote mutes (page 1 by default, 20 entries per page)");
4020
4021 Console()->Register(pName: "moderate", pParams: "", Flags: CFGFLAG_SERVER, pfnFunc: ConModerate, pUser: this, pHelp: "Enables/disables active moderator mode for the player");
4022 Console()->Register(pName: "vote_no", pParams: "", Flags: CFGFLAG_SERVER, pfnFunc: ConVoteNo, pUser: this, pHelp: "Same as \"vote no\"");
4023 Console()->Register(pName: "save_dry", pParams: "", Flags: CFGFLAG_SERVER, pfnFunc: ConDrySave, pUser: this, pHelp: "Dump the current savestring");
4024 Console()->Register(pName: "dump_log", pParams: "?i[seconds]", Flags: CFGFLAG_SERVER, pfnFunc: ConDumpLog, pUser: this, pHelp: "Show logs of the last i seconds");
4025
4026 Console()->Chain(pName: "sv_practice_by_default", pfnChainFunc: ConchainPracticeByDefaultUpdate, pUser: this);
4027 Console()->Chain(pName: "sv_tele_others_auth_level", pfnChainFunc: ConchainTeleOthersAuthLevel, pUser: this);
4028}
4029
4030void CGameContext::RegisterChatCommands()
4031{
4032 Console()->Register(pName: "rules", pParams: "", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConRules, pUser: this, pHelp: "Shows the server rules");
4033 Console()->Register(pName: "emote", pParams: "?s[emote name] i[duration in seconds]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConEyeEmote, pUser: this, pHelp: "Sets your tee's eye emote");
4034 Console()->Register(pName: "eyeemote", pParams: "?s['on'|'off'|'toggle']", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConSetEyeEmote, pUser: this, pHelp: "Toggles use of standard eye-emotes on/off, eyeemote s, where s = on for on, off for off, toggle for toggle and nothing to show current status");
4035 Console()->Register(pName: "settings", pParams: "?s[configname]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConSettings, pUser: this, pHelp: "Shows gameplay information for this server");
4036 Console()->Register(pName: "help", pParams: "?r[command]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConHelp, pUser: this, pHelp: "Shows help to command r, general help if left blank");
4037 Console()->Register(pName: "info", pParams: "", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConInfo, pUser: this, pHelp: "Shows info about this server");
4038 Console()->Register(pName: "list", pParams: "?s[filter]", Flags: CFGFLAG_CHAT, pfnFunc: ConList, pUser: this, pHelp: "List connected players with optional case-insensitive substring matching filter");
4039 Console()->Register(pName: "w", pParams: "s[player name] r[message]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER | CFGFLAG_NONTEEHISTORIC, pfnFunc: ConWhisper, pUser: this, pHelp: "Whisper something to someone (private message)");
4040 Console()->Register(pName: "whisper", pParams: "s[player name] r[message]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER | CFGFLAG_NONTEEHISTORIC, pfnFunc: ConWhisper, pUser: this, pHelp: "Whisper something to someone (private message)");
4041 Console()->Register(pName: "c", pParams: "r[message]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER | CFGFLAG_NONTEEHISTORIC, pfnFunc: ConConverse, pUser: this, pHelp: "Converse with the last person you whispered to (private message)");
4042 Console()->Register(pName: "converse", pParams: "r[message]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER | CFGFLAG_NONTEEHISTORIC, pfnFunc: ConConverse, pUser: this, pHelp: "Converse with the last person you whispered to (private message)");
4043 Console()->Register(pName: "pause", pParams: "?r[player name]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConTogglePause, pUser: this, pHelp: "Toggles pause");
4044 Console()->Register(pName: "spec", pParams: "?r[player name]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConToggleSpec, pUser: this, pHelp: "Toggles spec (if not available behaves as /pause)");
4045 Console()->Register(pName: "pausevoted", pParams: "", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConTogglePauseVoted, pUser: this, pHelp: "Toggles pause on the currently voted player");
4046 Console()->Register(pName: "specvoted", pParams: "", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConToggleSpecVoted, pUser: this, pHelp: "Toggles spec on the currently voted player");
4047 Console()->Register(pName: "dnd", pParams: "?i['0'|'1']", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER | CFGFLAG_NONTEEHISTORIC, pfnFunc: ConDND, pUser: this, pHelp: "Toggle Do Not Disturb (no chat and server messages)");
4048 Console()->Register(pName: "whispers", pParams: "?i['0'|'1']", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER | CFGFLAG_NONTEEHISTORIC, pfnFunc: ConWhispers, pUser: this, pHelp: "Toggle receiving whispers");
4049 Console()->Register(pName: "mapinfo", pParams: "?r[map]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConMapInfo, pUser: this, pHelp: "Show info about the map with name r gives (current map by default)");
4050 Console()->Register(pName: "timeout", pParams: "?s[code]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConTimeout, pUser: this, pHelp: "Set timeout protection code s");
4051 Console()->Register(pName: "practice", pParams: "?i['0'|'1']", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConPractice, pUser: this, pHelp: "Enable cheats for your current team's run, but you can't earn a rank");
4052 Console()->Register(pName: "unpractice", pParams: "", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER | CMDFLAG_PRACTICE, pfnFunc: ConUnPractice, pUser: this, pHelp: "Kills team and disables practice mode");
4053 Console()->Register(pName: "practicecmdlist", pParams: "", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConPracticeCmdList, pUser: this, pHelp: "List all commands that are available in practice mode");
4054 Console()->Register(pName: "swap", pParams: "?r[player name]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConSwap, pUser: this, pHelp: "Request to swap your tee with another team member");
4055 Console()->Register(pName: "cancelswap", pParams: "", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConCancelSwap, pUser: this, pHelp: "Cancel your swap request");
4056 Console()->Register(pName: "save", pParams: "?r[code]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConSave, pUser: this, pHelp: "Save team with code r.");
4057 Console()->Register(pName: "load", pParams: "?r[code]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConLoad, pUser: this, pHelp: "Load with code r. /load to check your existing saves");
4058 Console()->Register(pName: "map", pParams: "?r[map]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER | CFGFLAG_NONTEEHISTORIC, pfnFunc: ConMap, pUser: this, pHelp: "Vote a map by name");
4059
4060 Console()->Register(pName: "rankteam", pParams: "?r[player name]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConTeamRank, pUser: this, pHelp: "Shows the team rank of player with name r (your team rank by default)");
4061 Console()->Register(pName: "teamrank", pParams: "?r[player name]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConTeamRank, pUser: this, pHelp: "Shows the team rank of player with name r (your team rank by default)");
4062
4063 Console()->Register(pName: "rank", pParams: "?r[player name]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConRank, pUser: this, pHelp: "Shows the rank of player with name r (your rank by default)");
4064 Console()->Register(pName: "top5team", pParams: "?s[player name] ?i[rank to start with]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConTeamTop5, pUser: this, pHelp: "Shows five team ranks of the ladder or of a player beginning with rank i (1 by default, -1 for worst)");
4065 Console()->Register(pName: "teamtop5", pParams: "?s[player name] ?i[rank to start with]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConTeamTop5, pUser: this, pHelp: "Shows five team ranks of the ladder or of a player beginning with rank i (1 by default, -1 for worst)");
4066 Console()->Register(pName: "top", pParams: "?i[rank to start with]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConTop, pUser: this, pHelp: "Shows the top ranks of the global and regional ladder beginning with rank i (1 by default, -1 for worst)");
4067 Console()->Register(pName: "top5", pParams: "?i[rank to start with]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConTop, pUser: this, pHelp: "Shows the top ranks of the global and regional ladder beginning with rank i (1 by default, -1 for worst)");
4068 Console()->Register(pName: "times", pParams: "?s[player name] ?i[number of times to skip]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConTimes, pUser: this, pHelp: "/times ?s?i shows last 5 times of the server or of a player beginning with name s starting with time i (i = 1 by default, -1 for first)");
4069 Console()->Register(pName: "points", pParams: "?r[player name]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConPoints, pUser: this, pHelp: "Shows the global points of a player beginning with name r (your rank by default)");
4070 Console()->Register(pName: "top5points", pParams: "?i[number]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConTopPoints, pUser: this, pHelp: "Shows five points of the global point ladder beginning with rank i (1 by default)");
4071 Console()->Register(pName: "timecp", pParams: "?r[player name]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConTimeCP, pUser: this, pHelp: "Set your checkpoints based on another player");
4072
4073 Console()->Register(pName: "team", pParams: "?i[id]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConTeam, pUser: this, pHelp: "Lets you join team i (shows your team if left blank)");
4074 Console()->Register(pName: "lock", pParams: "?i['0'|'1']", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConLock, pUser: this, pHelp: "Toggle team lock so no one else can join and so the team restarts when a player dies. /lock 0 to unlock, /lock 1 to lock");
4075 Console()->Register(pName: "unlock", pParams: "", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConUnlock, pUser: this, pHelp: "Unlock a team");
4076 Console()->Register(pName: "invite", pParams: "r[player name]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConInvite, pUser: this, pHelp: "Invite a person to a locked team");
4077 Console()->Register(pName: "join", pParams: "r[player name]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConJoin, pUser: this, pHelp: "Join the team of the specified player");
4078 Console()->Register(pName: "team0mode", pParams: "?i['0'|'1']", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConTeam0Mode, pUser: this, pHelp: "Toggle team between team 0 and team mode. This mode will make your team behave like team 0.");
4079
4080 Console()->Register(pName: "showothers", pParams: "?i['0'|'1'|'2']", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConShowOthers, pUser: this, pHelp: "Whether to show players from other teams or not (off by default), optional i = 0 for off, i = 1 for on, i = 2 for own team only");
4081 Console()->Register(pName: "showall", pParams: "?i['0'|'1']", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConShowAll, pUser: this, pHelp: "Whether to show players at any distance (off by default), optional i = 0 for off else for on");
4082 Console()->Register(pName: "specteam", pParams: "?i['0'|'1']", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConSpecTeam, pUser: this, pHelp: "Whether to show players from other teams when spectating (on by default), optional i = 0 for off else for on");
4083 Console()->Register(pName: "ninjajetpack", pParams: "?i['0'|'1']", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConNinjaJetpack, pUser: this, pHelp: "Whether to use ninja jetpack or not. Makes jetpack look more awesome");
4084 Console()->Register(pName: "saytime", pParams: "?r[player name]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER | CFGFLAG_NONTEEHISTORIC, pfnFunc: ConSayTime, pUser: this, pHelp: "Privately messages someone's current time in this current running race (your time by default)");
4085 Console()->Register(pName: "saytimeall", pParams: "", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER | CFGFLAG_NONTEEHISTORIC, pfnFunc: ConSayTimeAll, pUser: this, pHelp: "Publicly messages everyone your current time in this current running race");
4086 Console()->Register(pName: "time", pParams: "", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConTime, pUser: this, pHelp: "Privately shows you your current time in this current running race in the broadcast message");
4087 Console()->Register(pName: "timer", pParams: "?s['gametimer'|'broadcast'|'both'|'none'|'cycle']", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConSetTimerType, pUser: this, pHelp: "Personal Setting of showing time in either broadcast or game/round timer, timer s, where s = broadcast for broadcast, gametimer for game/round timer, cycle for cycle, both for both, none for no timer and nothing to show current status");
4088 Console()->Register(pName: "r", pParams: "", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER | CMDFLAG_PRACTICE, pfnFunc: ConRescue, pUser: this, pHelp: "Teleport yourself out of freeze if auto rescue mode is enabled, otherwise it will set position for rescuing if grounded and teleport you out of freeze if not (use sv_rescue 1 to enable this feature)");
4089 Console()->Register(pName: "rescue", pParams: "", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER | CMDFLAG_PRACTICE, pfnFunc: ConRescue, pUser: this, pHelp: "Teleport yourself out of freeze if auto rescue mode is enabled, otherwise it will set position for rescuing if grounded and teleport you out of freeze if not (use sv_rescue 1 to enable this feature)");
4090 Console()->Register(pName: "back", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConBack, pUser: this, pHelp: "Teleport yourself to the last auto rescue position before you died (use sv_rescue 1 to enable this feature)");
4091 Console()->Register(pName: "rescuemode", pParams: "?r['auto'|'manual']", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER | CMDFLAG_PRACTICE, pfnFunc: ConRescueMode, pUser: this, pHelp: "Sets one of the two rescue modes (auto or manual). Prints current mode if no arguments provided");
4092 Console()->Register(pName: "tp", pParams: "?r[player name]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER | CMDFLAG_PRACTICE, pfnFunc: ConTeleTo, pUser: this, pHelp: "Depending on the number of supplied arguments, teleport yourself to; (0.) where you are spectating or aiming; (1.) the specified player name");
4093 Console()->Register(pName: "teleport", pParams: "?r[player name]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER | CMDFLAG_PRACTICE, pfnFunc: ConTeleTo, pUser: this, pHelp: "Depending on the number of supplied arguments, teleport yourself to; (0.) where you are spectating or aiming; (1.) the specified player name");
4094 Console()->Register(pName: "tpxy", pParams: "s[x] s[y]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER | CMDFLAG_PRACTICE, pfnFunc: ConTeleXY, pUser: this, pHelp: "Teleport yourself to the specified coordinates. A tilde (~) can be used to denote your current position, e.g. '/tpxy ~1 ~' to teleport one tile to the right");
4095 Console()->Register(pName: "lasttp", pParams: "", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER | CMDFLAG_PRACTICE, pfnFunc: ConLastTele, pUser: this, pHelp: "Teleport yourself to the last location you teleported to");
4096 Console()->Register(pName: "tc", pParams: "?r[player name]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER | CMDFLAG_PRACTICE, pfnFunc: ConTeleCursor, pUser: this, pHelp: "Teleport yourself to player or to where you are spectating/or looking if no player name is given");
4097 Console()->Register(pName: "telecursor", pParams: "?r[player name]", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER | CMDFLAG_PRACTICE, pfnFunc: ConTeleCursor, pUser: this, pHelp: "Teleport yourself to player or to where you are spectating/or looking if no player name is given");
4098 Console()->Register(pName: "totele", pParams: "i[number]", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeToTeleporter, pUser: this, pHelp: "Teleports you to teleporter i");
4099 Console()->Register(pName: "totelecp", pParams: "i[number]", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeToCheckTeleporter, pUser: this, pHelp: "Teleports you to checkpoint teleporter i");
4100 Console()->Register(pName: "unsolo", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeUnSolo, pUser: this, pHelp: "Puts you out of solo part");
4101 Console()->Register(pName: "solo", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeSolo, pUser: this, pHelp: "Puts you into solo part");
4102 Console()->Register(pName: "undeep", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeUnDeep, pUser: this, pHelp: "Puts you out of deep freeze");
4103 Console()->Register(pName: "deep", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeDeep, pUser: this, pHelp: "Puts you into deep freeze");
4104 Console()->Register(pName: "unlivefreeze", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeUnLiveFreeze, pUser: this, pHelp: "Puts you out of live freeze");
4105 Console()->Register(pName: "livefreeze", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeLiveFreeze, pUser: this, pHelp: "Makes you live frozen");
4106 Console()->Register(pName: "addweapon", pParams: "i[weapon-id]", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeAddWeapon, pUser: this, pHelp: "Gives weapon with id i to you (all = -1, hammer = 0, gun = 1, shotgun = 2, grenade = 3, laser = 4, ninja = 5)");
4107 Console()->Register(pName: "removeweapon", pParams: "i[weapon-id]", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeRemoveWeapon, pUser: this, pHelp: "removes weapon with id i from you (all = -1, hammer = 0, gun = 1, shotgun = 2, grenade = 3, laser = 4, ninja = 5)");
4108 Console()->Register(pName: "shotgun", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeShotgun, pUser: this, pHelp: "Gives a shotgun to you");
4109 Console()->Register(pName: "grenade", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeGrenade, pUser: this, pHelp: "Gives a grenade launcher to you");
4110 Console()->Register(pName: "laser", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeLaser, pUser: this, pHelp: "Gives a laser to you");
4111 Console()->Register(pName: "rifle", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeLaser, pUser: this, pHelp: "Gives a laser to you");
4112 Console()->Register(pName: "jetpack", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeJetpack, pUser: this, pHelp: "Gives jetpack to you");
4113 Console()->Register(pName: "setjumps", pParams: "i[jumps]", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeSetJumps, pUser: this, pHelp: "Gives you as many jumps as you specify");
4114 Console()->Register(pName: "weapons", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeWeapons, pUser: this, pHelp: "Gives all weapons to you");
4115 Console()->Register(pName: "unshotgun", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeUnShotgun, pUser: this, pHelp: "Removes the shotgun from you");
4116 Console()->Register(pName: "ungrenade", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeUnGrenade, pUser: this, pHelp: "Removes the grenade launcher from you");
4117 Console()->Register(pName: "unlaser", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeUnLaser, pUser: this, pHelp: "Removes the laser from you");
4118 Console()->Register(pName: "unrifle", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeUnLaser, pUser: this, pHelp: "Removes the laser from you");
4119 Console()->Register(pName: "unjetpack", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeUnJetpack, pUser: this, pHelp: "Removes the jetpack from you");
4120 Console()->Register(pName: "unweapons", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeUnWeapons, pUser: this, pHelp: "Removes all weapons from you");
4121 Console()->Register(pName: "ninja", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeNinja, pUser: this, pHelp: "Makes you a ninja");
4122 Console()->Register(pName: "unninja", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeUnNinja, pUser: this, pHelp: "Removes ninja from you");
4123 Console()->Register(pName: "infjump", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeEndlessJump, pUser: this, pHelp: "Gives you infinite jump");
4124 Console()->Register(pName: "uninfjump", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeUnEndlessJump, pUser: this, pHelp: "Removes infinite jump from you");
4125 Console()->Register(pName: "endless", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeEndlessHook, pUser: this, pHelp: "Gives you endless hook");
4126 Console()->Register(pName: "unendless", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeUnEndlessHook, pUser: this, pHelp: "Removes endless hook from you");
4127 Console()->Register(pName: "setswitch", pParams: "i[switch] ?i['0'|'1'] ?i[seconds]", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeSetSwitch, pUser: this, pHelp: "Toggle or set the switch on or off for the specified time (or indefinitely by default)");
4128 Console()->Register(pName: "invincible", pParams: "?i['0'|'1']", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeToggleInvincible, pUser: this, pHelp: "Toggles invincible mode");
4129 Console()->Register(pName: "collision", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeToggleCollision, pUser: this, pHelp: "Toggles collision");
4130 Console()->Register(pName: "hookcollision", pParams: "", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeToggleHookCollision, pUser: this, pHelp: "Toggles hook collision");
4131 Console()->Register(pName: "hitothers", pParams: "?s['all'|'hammer'|'shotgun'|'grenade'|'laser']", Flags: CFGFLAG_CHAT | CMDFLAG_PRACTICE, pfnFunc: ConPracticeToggleHitOthers, pUser: this, pHelp: "Toggles hit others");
4132
4133 Console()->Register(pName: "kill", pParams: "", Flags: CFGFLAG_CHAT | CFGFLAG_SERVER, pfnFunc: ConProtectedKill, pUser: this, pHelp: "Kill yourself when kill-protected during a long game (use f1, kill for regular kill)");
4134}
4135
4136void CGameContext::OnInit(const void *pPersistentData)
4137{
4138 const CPersistentData *pPersistent = (const CPersistentData *)pPersistentData;
4139
4140 m_pServer = Kernel()->RequestInterface<IServer>();
4141 m_pConfigManager = Kernel()->RequestInterface<IConfigManager>();
4142 m_pConfig = m_pConfigManager->Values();
4143 m_pConsole = Kernel()->RequestInterface<IConsole>();
4144 m_pEngine = Kernel()->RequestInterface<IEngine>();
4145 m_pStorage = Kernel()->RequestInterface<IStorage>();
4146 m_pAntibot = Kernel()->RequestInterface<IAntibot>();
4147 m_World.SetGameServer(this);
4148 m_Events.SetGameServer(this);
4149 m_PlayerMapping.Init(pGameServer: this);
4150
4151 m_GameUuid = RandomUuid();
4152 Console()->SetGetVictimsCommandCallback(pfnCallback: ClientsForVictim, pUser: this);
4153 Console()->SetTeeHistorianCommandCallback(pfnCallback: CommandCallback, pUser: this);
4154
4155 uint64_t aSeed[2];
4156 secure_random_fill(bytes: aSeed, length: sizeof(aSeed));
4157 m_Prng.Seed(aSeed);
4158 m_World.m_Core.m_pPrng = &m_Prng;
4159
4160 DeleteTempfile();
4161
4162 for(int i = 0; i < NUM_NETOBJTYPES; i++)
4163 {
4164 Server()->SnapSetStaticsize(ItemType: i, Size: m_NetObjHandler.GetObjSize(Type: i));
4165 }
4166
4167 // HACK: only set static size for items, which were available in the first 0.7 release
4168 // so new items don't break the snapshot delta
4169 static const int OLD_NUM_NETOBJTYPES = 23;
4170 for(int i = 0; i < OLD_NUM_NETOBJTYPES; i++)
4171 {
4172 Server()->SnapSetStaticsize7(ItemType: i, Size: m_NetObjHandler7.GetObjSize(Type: i));
4173 }
4174
4175 m_Layers.Init(pMap: Map(), GameOnly: false, InitializeTilemapSkip: false);
4176 m_Collision.Init(pLayers: &m_Layers);
4177 m_World.Init(pCollision: &m_Collision, pTuningList: m_aTuningList);
4178 m_MapBugs = CMapBugs::Create(pName: Map()->BaseName(), Size: Map()->Size(), Sha256: Map()->Sha256());
4179
4180 // Reset Tunezones
4181 for(int i = 0; i < TuneZone::NUM; i++)
4182 {
4183 TuningList()[i] = CTuningParams::DEFAULT;
4184 TuningList()[i].Set(pName: "gun_curvature", Value: 0);
4185 TuningList()[i].Set(pName: "gun_speed", Value: 1400);
4186 TuningList()[i].Set(pName: "shotgun_curvature", Value: 0);
4187 TuningList()[i].Set(pName: "shotgun_speed", Value: 500);
4188 TuningList()[i].Set(pName: "shotgun_speeddiff", Value: 0);
4189 }
4190
4191 for(int i = 0; i < TuneZone::NUM; i++)
4192 {
4193 // Send no text by default when changing tune zones.
4194 m_aaZoneEnterMsg[i][0] = 0;
4195 m_aaZoneLeaveMsg[i][0] = 0;
4196 }
4197 // Reset Tuning
4198 if(g_Config.m_SvTuneReset)
4199 {
4200 ResetTuning();
4201 }
4202 else
4203 {
4204 GlobalTuning()->Set(pName: "gun_speed", Value: 1400);
4205 GlobalTuning()->Set(pName: "gun_curvature", Value: 0);
4206 GlobalTuning()->Set(pName: "shotgun_speed", Value: 500);
4207 GlobalTuning()->Set(pName: "shotgun_speeddiff", Value: 0);
4208 GlobalTuning()->Set(pName: "shotgun_curvature", Value: 0);
4209 }
4210
4211 if(g_Config.m_SvDDRaceTuneReset)
4212 {
4213 g_Config.m_SvHit = 1;
4214 g_Config.m_SvEndlessDrag = 0;
4215 g_Config.m_SvOldLaser = 0;
4216 g_Config.m_SvOldTeleportHook = 0;
4217 g_Config.m_SvOldTeleportWeapons = 0;
4218 g_Config.m_SvTeleportHoldHook = 0;
4219 g_Config.m_SvTeam = SV_TEAM_ALLOWED;
4220 g_Config.m_SvShowOthersDefault = SHOW_OTHERS_OFF;
4221
4222 for(auto &Switcher : Switchers())
4223 Switcher.m_Initial = true;
4224 }
4225
4226 m_pConfigManager->SetGameSettingsReadOnly(false);
4227
4228 Console()->ExecuteFile(pFilename: g_Config.m_SvResetFile, ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
4229
4230 LoadMapSettings();
4231
4232 m_pConfigManager->SetGameSettingsReadOnly(true);
4233
4234 m_MapBugs.Dump();
4235
4236 if(g_Config.m_SvSoloServer)
4237 {
4238 g_Config.m_SvTeam = SV_TEAM_FORCED_SOLO;
4239 g_Config.m_SvShowOthersDefault = SHOW_OTHERS_ON;
4240
4241 GlobalTuning()->Set(pName: "player_collision", Value: 0);
4242 GlobalTuning()->Set(pName: "player_hooking", Value: 0);
4243
4244 for(int i = 0; i < TuneZone::NUM; i++)
4245 {
4246 TuningList()[i].Set(pName: "player_collision", Value: 0);
4247 TuningList()[i].Set(pName: "player_hooking", Value: 0);
4248 }
4249 }
4250
4251 if(!str_comp(a: Config()->m_SvGametype, b: "mod"))
4252 m_pController = new CGameControllerMod(this);
4253 else
4254 m_pController = new CGameControllerDDNet(this);
4255
4256 for(const char *pReservedGameType : {"DM", "TDM", "CTF", "LMS", "LTS"})
4257 {
4258 dbg_assert(str_comp(m_pController->m_pGameType, pReservedGameType) != 0, "Using reserved gametype '%s' is not allowed", m_pController->m_pGameType);
4259 }
4260
4261 ReadCensorList();
4262
4263 m_TeeHistorianActive = g_Config.m_SvTeeHistorian;
4264 if(m_TeeHistorianActive)
4265 {
4266 char aGameUuid[UUID_MAXSTRSIZE];
4267 FormatUuid(Uuid: m_GameUuid, pBuffer: aGameUuid, BufferLength: sizeof(aGameUuid));
4268
4269 char aFilename[IO_MAX_PATH_LENGTH];
4270 str_format(buffer: aFilename, buffer_size: sizeof(aFilename), format: "teehistorian/%s.teehistorian", aGameUuid);
4271
4272 IOHANDLE THFile = Storage()->OpenFile(pFilename: aFilename, Flags: IOFLAG_WRITE, Type: IStorage::TYPE_SAVE);
4273 if(!THFile)
4274 {
4275 dbg_msg(sys: "teehistorian", fmt: "failed to open '%s'", aFilename);
4276 Server()->SetErrorShutdown("teehistorian open error");
4277 return;
4278 }
4279 else
4280 {
4281 dbg_msg(sys: "teehistorian", fmt: "recording to '%s'", aFilename);
4282 }
4283 m_pTeeHistorianFile = aio_new(io: THFile);
4284
4285 char aVersion[128];
4286 if(GIT_SHORTREV_HASH)
4287 {
4288 str_format(buffer: aVersion, buffer_size: sizeof(aVersion), format: "%s (%s)", GAME_VERSION, GIT_SHORTREV_HASH);
4289 }
4290 else
4291 {
4292 str_copy(dst&: aVersion, GAME_VERSION);
4293 }
4294 CTeeHistorian::CGameInfo GameInfo;
4295 GameInfo.m_GameUuid = m_GameUuid;
4296 GameInfo.m_pServerVersion = aVersion;
4297 GameInfo.m_StartTime = time(timer: nullptr);
4298 GameInfo.m_pPrngDescription = m_Prng.Description();
4299
4300 GameInfo.m_pServerName = g_Config.m_SvName;
4301 GameInfo.m_ServerPort = Server()->Port();
4302 GameInfo.m_pGameType = m_pController->m_pGameType;
4303
4304 GameInfo.m_pConfig = &g_Config;
4305 GameInfo.m_pTuning = GlobalTuning();
4306 GameInfo.m_pUuids = &g_UuidManager;
4307
4308 GameInfo.m_pMapName = Map()->BaseName();
4309 GameInfo.m_MapSize = Map()->Size();
4310 GameInfo.m_MapSha256 = Map()->Sha256();
4311 GameInfo.m_MapCrc = Map()->Crc();
4312
4313 if(pPersistent)
4314 {
4315 GameInfo.m_HavePrevGameUuid = true;
4316 GameInfo.m_PrevGameUuid = pPersistent->m_PrevGameUuid;
4317 }
4318 else
4319 {
4320 GameInfo.m_HavePrevGameUuid = false;
4321 mem_zero(block: &GameInfo.m_PrevGameUuid, size: sizeof(GameInfo.m_PrevGameUuid));
4322 }
4323
4324 m_TeeHistorian.Reset(pGameInfo: &GameInfo, pfnWriteCallback: TeeHistorianWrite, pUser: this);
4325 }
4326
4327 Server()->DemoRecorder_HandleAutoStart();
4328
4329 if(!m_pScore)
4330 {
4331 m_pScore = new CScore(this, ((CServer *)Server())->DbPool());
4332 }
4333
4334 // load map info from database
4335 Score()->LoadMapInfo();
4336
4337 // create all entities from the game layer
4338 CreateAllEntities(Initial: true);
4339
4340 m_pAntibot->RoundStart(pGameServer: this);
4341}
4342
4343void CGameContext::CreateAllEntities(bool Initial)
4344{
4345 const CTile *pTiles = m_Collision.GameLayer();
4346 const CTile *pFront = m_Collision.FrontLayer();
4347 const CSwitchTile *pSwitch = m_Collision.SwitchLayer();
4348
4349 for(int y = 0; y < m_Collision.GetHeight(); y++)
4350 {
4351 for(int x = 0; x < m_Collision.GetWidth(); x++)
4352 {
4353 const int Index = y * m_Collision.GetWidth() + x;
4354
4355 // Game layer
4356 {
4357 const int GameIndex = pTiles[Index].m_Index;
4358 if(GameIndex == TILE_OLDLASER)
4359 {
4360 g_Config.m_SvOldLaser = 1;
4361 dbg_msg(sys: "game_layer", fmt: "found old laser tile");
4362 }
4363 else if(GameIndex == TILE_NPC)
4364 {
4365 GlobalTuning()->Set(pName: "player_collision", Value: 0);
4366 dbg_msg(sys: "game_layer", fmt: "found no collision tile");
4367 }
4368 else if(GameIndex == TILE_EHOOK)
4369 {
4370 g_Config.m_SvEndlessDrag = 1;
4371 dbg_msg(sys: "game_layer", fmt: "found unlimited hook time tile");
4372 }
4373 else if(GameIndex == TILE_NOHIT)
4374 {
4375 g_Config.m_SvHit = 0;
4376 dbg_msg(sys: "game_layer", fmt: "found no weapons hitting others tile");
4377 }
4378 else if(GameIndex == TILE_NPH)
4379 {
4380 GlobalTuning()->Set(pName: "player_hooking", Value: 0);
4381 dbg_msg(sys: "game_layer", fmt: "found no player hooking tile");
4382 }
4383 else if(GameIndex >= ENTITY_OFFSET)
4384 {
4385 m_pController->OnEntity(Index: GameIndex - ENTITY_OFFSET, x, y, Layer: LAYER_GAME, Flags: pTiles[Index].m_Flags, Initial);
4386 }
4387 }
4388
4389 if(pFront)
4390 {
4391 const int FrontIndex = pFront[Index].m_Index;
4392 if(FrontIndex == TILE_OLDLASER)
4393 {
4394 g_Config.m_SvOldLaser = 1;
4395 dbg_msg(sys: "front_layer", fmt: "found old laser tile");
4396 }
4397 else if(FrontIndex == TILE_NPC)
4398 {
4399 GlobalTuning()->Set(pName: "player_collision", Value: 0);
4400 dbg_msg(sys: "front_layer", fmt: "found no collision tile");
4401 }
4402 else if(FrontIndex == TILE_EHOOK)
4403 {
4404 g_Config.m_SvEndlessDrag = 1;
4405 dbg_msg(sys: "front_layer", fmt: "found unlimited hook time tile");
4406 }
4407 else if(FrontIndex == TILE_NOHIT)
4408 {
4409 g_Config.m_SvHit = 0;
4410 dbg_msg(sys: "front_layer", fmt: "found no weapons hitting others tile");
4411 }
4412 else if(FrontIndex == TILE_NPH)
4413 {
4414 GlobalTuning()->Set(pName: "player_hooking", Value: 0);
4415 dbg_msg(sys: "front_layer", fmt: "found no player hooking tile");
4416 }
4417 else if(FrontIndex >= ENTITY_OFFSET)
4418 {
4419 m_pController->OnEntity(Index: FrontIndex - ENTITY_OFFSET, x, y, Layer: LAYER_FRONT, Flags: pFront[Index].m_Flags, Initial);
4420 }
4421 }
4422
4423 if(pSwitch)
4424 {
4425 const int SwitchType = pSwitch[Index].m_Type;
4426 // TODO: Add off by default door here
4427 // if(SwitchType == TILE_DOOR_OFF)
4428 if(SwitchType >= ENTITY_OFFSET)
4429 {
4430 m_pController->OnEntity(Index: SwitchType - ENTITY_OFFSET, x, y, Layer: LAYER_SWITCH, Flags: pSwitch[Index].m_Flags, Initial, Number: pSwitch[Index].m_Number);
4431 }
4432 }
4433 }
4434 }
4435}
4436
4437CPlayer *CGameContext::CreatePlayer(int ClientId, int StartTeam, bool Afk, int LastWhisperTo)
4438{
4439 if(m_apPlayers[ClientId])
4440 delete m_apPlayers[ClientId];
4441 m_apPlayers[ClientId] = new(ClientId) CPlayer(this, m_NextUniqueClientId, ClientId, StartTeam);
4442 m_apPlayers[ClientId]->SetInitialAfk(Afk);
4443 m_apPlayers[ClientId]->m_LastWhisperTo = LastWhisperTo;
4444 m_NextUniqueClientId += 1;
4445 return m_apPlayers[ClientId];
4446}
4447
4448void CGameContext::DeleteTempfile()
4449{
4450 if(m_aDeleteTempfile[0] != 0)
4451 {
4452 Storage()->RemoveFile(pFilename: m_aDeleteTempfile, Type: IStorage::TYPE_SAVE);
4453 m_aDeleteTempfile[0] = 0;
4454 }
4455}
4456
4457bool CGameContext::OnMapChange(char *pNewMapName, int MapNameSize)
4458{
4459 char aConfig[IO_MAX_PATH_LENGTH];
4460 str_format(buffer: aConfig, buffer_size: sizeof(aConfig), format: "maps/%s.cfg", g_Config.m_SvMap);
4461
4462 CLineReader LineReader;
4463 if(!LineReader.OpenFile(File: Storage()->OpenFile(pFilename: aConfig, Flags: IOFLAG_READ, Type: IStorage::TYPE_ALL)))
4464 {
4465 // No map-specific config, just return.
4466 return true;
4467 }
4468
4469 std::shared_ptr<IMap> pImportedMap = CreateMap();
4470 if(!pImportedMap->Load(pFullName: g_Config.m_SvMap, pStorage: Storage(), pPath: pNewMapName, StorageType: IStorage::TYPE_ALL))
4471 {
4472 log_error("mapchange", "Failed to import settings from '%s': failed to open map '%s' for reading", aConfig, pNewMapName);
4473 return false;
4474 }
4475
4476 std::vector<const char *> vpLines;
4477 int TotalLength = 0;
4478 while(const char *pLine = LineReader.Get())
4479 {
4480 vpLines.push_back(x: pLine);
4481 TotalLength += str_length(str: pLine) + 1;
4482 }
4483
4484 char *pSettings = (char *)malloc(size: std::max(a: 1, b: TotalLength));
4485 int Offset = 0;
4486 for(const char *pLine : vpLines)
4487 {
4488 int Length = str_length(str: pLine) + 1;
4489 mem_copy(dest: pSettings + Offset, source: pLine, size: Length);
4490 Offset += Length;
4491 }
4492
4493 CDataFileWriter Writer;
4494
4495 int SettingsIndex = pImportedMap->NumData();
4496 bool FoundInfo = false;
4497 for(int i = 0; i < pImportedMap->NumItems(); i++)
4498 {
4499 int TypeId;
4500 int ItemId;
4501 void *pData = pImportedMap->GetItem(Index: i, pType: &TypeId, pId: &ItemId);
4502 int Size = pImportedMap->GetItemSize(Index: i);
4503 CMapItemInfoSettings MapInfo;
4504 if(TypeId == MAPITEMTYPE_INFO && ItemId == 0)
4505 {
4506 FoundInfo = true;
4507 if(Size >= (int)sizeof(CMapItemInfoSettings))
4508 {
4509 CMapItemInfoSettings *pInfo = (CMapItemInfoSettings *)pData;
4510 if(pInfo->m_Settings > -1)
4511 {
4512 SettingsIndex = pInfo->m_Settings;
4513 char *pMapSettings = (char *)pImportedMap->GetData(Index: SettingsIndex);
4514 int DataSize = pImportedMap->GetDataSize(Index: SettingsIndex);
4515 if(DataSize == TotalLength && mem_comp(a: pSettings, b: pMapSettings, size: DataSize) == 0)
4516 {
4517 // Configs coincide, no need to update map.
4518 free(ptr: pSettings);
4519 return true;
4520 }
4521 pImportedMap->UnloadData(Index: pInfo->m_Settings);
4522 }
4523 else
4524 {
4525 MapInfo = *pInfo;
4526 MapInfo.m_Settings = SettingsIndex;
4527 pData = &MapInfo;
4528 Size = sizeof(MapInfo);
4529 }
4530 }
4531 else
4532 {
4533 *(CMapItemInfo *)&MapInfo = *(CMapItemInfo *)pData;
4534 MapInfo.m_Settings = SettingsIndex;
4535 pData = &MapInfo;
4536 Size = sizeof(MapInfo);
4537 }
4538 }
4539 Writer.AddItem(Type: TypeId, Id: ItemId, Size, pData);
4540 }
4541
4542 if(!FoundInfo)
4543 {
4544 CMapItemInfoSettings Info;
4545 Info.m_Version = 1;
4546 Info.m_Author = -1;
4547 Info.m_MapVersion = -1;
4548 Info.m_Credits = -1;
4549 Info.m_License = -1;
4550 Info.m_Settings = SettingsIndex;
4551 Writer.AddItem(Type: MAPITEMTYPE_INFO, Id: 0, Size: sizeof(Info), pData: &Info);
4552 }
4553
4554 for(int i = 0; i < pImportedMap->NumData() || i == SettingsIndex; i++)
4555 {
4556 if(i == SettingsIndex)
4557 {
4558 Writer.AddData(Size: TotalLength, pData: pSettings);
4559 continue;
4560 }
4561 const void *pData = pImportedMap->GetData(Index: i);
4562 const int Size = pImportedMap->GetDataSize(Index: i);
4563 Writer.AddData(Size, pData);
4564 pImportedMap->UnloadData(Index: i);
4565 }
4566
4567 free(ptr: pSettings);
4568 pImportedMap->Unload();
4569
4570 char aTemp[IO_MAX_PATH_LENGTH];
4571 if(!Writer.Open(pStorage: Storage(), pFilename: IStorage::FormatTmpPath(aBuf: aTemp, BufSize: sizeof(aTemp), pPath: pNewMapName)))
4572 {
4573 log_error("mapchange", "Failed to import settings from '%s': failed to open map '%s' for writing", aConfig, aTemp);
4574 return false;
4575 }
4576 Writer.Finish();
4577 log_info("mapchange", "Imported settings from '%s' into '%s'", aConfig, aTemp);
4578
4579 str_copy(dst: pNewMapName, src: aTemp, dst_size: MapNameSize);
4580 str_copy(dst&: m_aDeleteTempfile, src: aTemp);
4581 return true;
4582}
4583
4584void CGameContext::OnShutdown(void *pPersistentData)
4585{
4586 CPersistentData *pPersistent = (CPersistentData *)pPersistentData;
4587
4588 if(pPersistent)
4589 {
4590 new(pPersistent) CPersistentData();
4591 pPersistent->m_PrevGameUuid = m_GameUuid;
4592 }
4593
4594 Antibot()->RoundEnd();
4595
4596 if(m_TeeHistorianActive)
4597 {
4598 m_TeeHistorian.Finish();
4599 aio_close(aio: m_pTeeHistorianFile);
4600 aio_wait(aio: m_pTeeHistorianFile);
4601 int Error = aio_error(aio: m_pTeeHistorianFile);
4602 if(Error)
4603 {
4604 dbg_msg(sys: "teehistorian", fmt: "error closing file, err=%d", Error);
4605 Server()->SetErrorShutdown("teehistorian close error");
4606 }
4607 aio_free(aio: m_pTeeHistorianFile);
4608 }
4609
4610 // Stop any demos being recorded.
4611 Server()->StopDemos();
4612
4613 DeleteTempfile();
4614 ConfigManager()->ResetGameSettings();
4615 Collision()->Unload();
4616 Layers()->Unload();
4617 delete m_pController;
4618 m_pController = nullptr;
4619 Clear();
4620}
4621
4622void CGameContext::LoadMapSettings()
4623{
4624 IMap *pMap = Map();
4625 int Start, Num;
4626 pMap->GetType(Type: MAPITEMTYPE_INFO, pStart: &Start, pNum: &Num);
4627 for(int i = Start; i < Start + Num; i++)
4628 {
4629 int ItemId;
4630 CMapItemInfoSettings *pItem = (CMapItemInfoSettings *)pMap->GetItem(Index: i, pType: nullptr, pId: &ItemId);
4631 int ItemSize = pMap->GetItemSize(Index: i);
4632 if(!pItem || ItemId != 0)
4633 continue;
4634
4635 if(ItemSize < (int)sizeof(CMapItemInfoSettings))
4636 break;
4637 if(!(pItem->m_Settings > -1))
4638 break;
4639
4640 int Size = pMap->GetDataSize(Index: pItem->m_Settings);
4641 char *pSettings = (char *)pMap->GetData(Index: pItem->m_Settings);
4642 char *pNext = pSettings;
4643 while(pNext < pSettings + Size)
4644 {
4645 int StrSize = str_length(str: pNext) + 1;
4646 Console()->ExecuteLine(pStr: pNext, ClientId: IConsole::CLIENT_ID_GAME);
4647 pNext += StrSize;
4648 }
4649 pMap->UnloadData(Index: pItem->m_Settings);
4650 break;
4651 }
4652
4653 char aBuf[IO_MAX_PATH_LENGTH];
4654 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "maps/%s.map.cfg", g_Config.m_SvMap);
4655 Console()->ExecuteFile(pFilename: aBuf, ClientId: IConsole::CLIENT_ID_NO_GAME);
4656}
4657
4658void CGameContext::OnSnap(int ClientId, bool GlobalSnap, bool RecordingDemo)
4659{
4660 // sixup should only snap during global snap
4661 dbg_assert(!Server()->IsSixup(ClientId) || GlobalSnap, "sixup should only snap during global snap");
4662
4663 // add tuning to demo
4664 if(RecordingDemo && mem_comp(a: &CTuningParams::DEFAULT, b: &m_aTuningList[0], size: sizeof(CTuningParams)) != 0)
4665 {
4666 CMsgPacker Msg(NETMSGTYPE_SV_TUNEPARAMS);
4667 int *pParams = (int *)&m_aTuningList[0];
4668 for(int i = 0; i < CTuningParams::Num(); i++)
4669 Msg.AddInt(i: pParams[i]);
4670 Server()->SendMsg(pMsg: &Msg, Flags: MSGFLAG_NOSEND, ClientId);
4671 }
4672
4673 m_pController->Snap(SnappingClient: ClientId);
4674
4675 for(auto &pPlayer : m_apPlayers)
4676 {
4677 if(pPlayer)
4678 pPlayer->Snap(SnappingClient: ClientId);
4679 }
4680
4681 if(ClientId > -1)
4682 m_apPlayers[ClientId]->FakeSnap();
4683
4684 m_World.Snap(SnappingClient: ClientId);
4685
4686 // events are only sent on global snapshots
4687 if(GlobalSnap)
4688 {
4689 m_Events.Snap(SnappingClient: ClientId);
4690 }
4691}
4692
4693void CGameContext::OnPostGlobalSnap()
4694{
4695 for(auto &pPlayer : m_apPlayers)
4696 {
4697 if(pPlayer && pPlayer->GetCharacter())
4698 pPlayer->GetCharacter()->PostGlobalSnap();
4699 }
4700 m_Events.Clear();
4701}
4702
4703bool CGameContext::IsClientReady(int ClientId) const
4704{
4705 return m_apPlayers[ClientId] && m_apPlayers[ClientId]->m_IsReady;
4706}
4707
4708bool CGameContext::IsClientPlayer(int ClientId) const
4709{
4710 return m_apPlayers[ClientId] && m_apPlayers[ClientId]->GetTeam() != TEAM_SPECTATORS;
4711}
4712
4713bool CGameContext::IsClientHighBandwidth(int ClientId) const
4714{
4715 // force high bandwidth is not supported for sixup
4716 return m_apPlayers[ClientId] && !Server()->IsSixup(ClientId) && Server()->IsRconAuthed(ClientId) &&
4717 (m_apPlayers[ClientId]->GetTeam() == TEAM_SPECTATORS || m_apPlayers[ClientId]->IsPaused());
4718}
4719
4720CUuid CGameContext::GameUuid() const { return m_GameUuid; }
4721const char *CGameContext::GameType() const
4722{
4723 dbg_assert(m_pController, "no controller");
4724 dbg_assert(m_pController->m_pGameType, "no gametype");
4725 return m_pController->m_pGameType;
4726}
4727const char *CGameContext::Version() const { return m_aVersionString; }
4728const char *CGameContext::NetVersion() const { return GAME_NETVERSION; }
4729
4730IGameServer *CreateGameServer() { return new CGameContext; }
4731
4732void CGameContext::OnSetAuthed(int ClientId, CRconRole *pRole)
4733{
4734 if(m_apPlayers[ClientId] && m_VoteCloseTime && pRole)
4735 {
4736 char aBuf[512];
4737 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "ban %s %d Banned by vote", Server()->ClientAddrString(ClientId, IncludePort: false), g_Config.m_SvVoteKickBantime);
4738 if(!str_comp_nocase(a: m_aVoteCommand, b: aBuf) && (m_VoteCreator == -1 || pRole->Rank() > Server()->GetAuthedState(ClientId: m_VoteCreator)))
4739 {
4740 m_VoteEnforce = CGameContext::VOTE_ENFORCE_NO_ADMIN;
4741 log_info("game", "Vote aborted by authorized login.");
4742 }
4743 }
4744
4745 if(m_TeeHistorianActive)
4746 {
4747 if(pRole)
4748 {
4749 m_TeeHistorian.RecordAuthLogin(
4750 ClientId,
4751 pRoleName: pRole->Name(),
4752 pAuthName: Server()->GetAuthName(ClientId));
4753 }
4754 else
4755 {
4756 m_TeeHistorian.RecordAuthLogout(ClientId);
4757 }
4758 }
4759}
4760
4761bool CGameContext::IsRunningVote(int ClientId) const
4762{
4763 return m_VoteCloseTime && m_VoteCreator == ClientId;
4764}
4765
4766bool CGameContext::IsRunningKickOrSpecVote(int ClientId) const
4767{
4768 return IsRunningVote(ClientId) && (IsKickVote() || IsSpecVote());
4769}
4770
4771void CGameContext::SendRecord(int ClientId)
4772{
4773 if(Server()->IsSixup(ClientId) || GetClientVersion(ClientId) >= VERSION_DDNET_MAP_BESTTIME)
4774 return;
4775
4776 CNetMsg_Sv_Record Msg;
4777 CNetMsg_Sv_RecordLegacy MsgLegacy;
4778 MsgLegacy.m_PlayerTimeBest = Msg.m_PlayerTimeBest = static_cast<int>(time_even_centiseconds_from_seconds(seconds: Score()->PlayerData(Id: ClientId)->m_BestTime.value_or(u: 0.0f)));
4779 MsgLegacy.m_ServerTimeBest = Msg.m_ServerTimeBest = m_pController->m_CurrentRecord.has_value() && !g_Config.m_SvHideScore ? static_cast<int>(time_even_centiseconds_from_seconds(seconds: m_pController->m_CurrentRecord.value())) : 0;
4780 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId);
4781 if(GetClientVersion(ClientId) < VERSION_DDNET_MSG_LEGACY)
4782 {
4783 Server()->SendPackMsg(pMsg: &MsgLegacy, Flags: MSGFLAG_VITAL, ClientId);
4784 }
4785}
4786
4787void CGameContext::SendFinish(int ClientId, float Time, std::optional<float> PreviousBestTime)
4788{
4789 int ClientVersion = m_apPlayers[ClientId]->GetClientVersion();
4790
4791 if(!Server()->IsSixup(ClientId))
4792 {
4793 CNetMsg_Sv_DDRaceTime Msg;
4794 CNetMsg_Sv_DDRaceTimeLegacy MsgLegacy;
4795 MsgLegacy.m_Time = Msg.m_Time = static_cast<int>(time_even_centiseconds_from_seconds(seconds: Time));
4796 MsgLegacy.m_Check = Msg.m_Check = 0;
4797 MsgLegacy.m_Finish = Msg.m_Finish = 1;
4798
4799 if(PreviousBestTime.has_value())
4800 {
4801 MsgLegacy.m_Check = Msg.m_Check = static_cast<int>(time_even_centiseconds_from_seconds(seconds: Time) - time_even_centiseconds_from_seconds(seconds: PreviousBestTime.value()));
4802 }
4803 if(VERSION_DDRACE <= ClientVersion)
4804 {
4805 if(ClientVersion < VERSION_DDNET_MSG_LEGACY)
4806 {
4807 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId);
4808 }
4809 else
4810 {
4811 Server()->SendPackMsg(pMsg: &MsgLegacy, Flags: MSGFLAG_VITAL, ClientId);
4812 }
4813 }
4814 }
4815
4816 CNetMsg_Sv_RaceFinish RaceFinishMsg;
4817 RaceFinishMsg.m_ClientId = ClientId;
4818 RaceFinishMsg.m_Time = static_cast<int>(time_milliseconds_from_seconds(seconds: Time));
4819 RaceFinishMsg.m_Diff = 0;
4820 if(PreviousBestTime.has_value())
4821 {
4822 RaceFinishMsg.m_Diff = static_cast<int>(time_milliseconds_from_seconds(seconds: Time) - time_milliseconds_from_seconds(seconds: PreviousBestTime.value()));
4823 }
4824 RaceFinishMsg.m_RecordPersonal = (!PreviousBestTime.has_value() || Time < PreviousBestTime.value());
4825 RaceFinishMsg.m_RecordServer = Time < m_pController->m_CurrentRecord;
4826 Server()->SendPackMsg(pMsg: &RaceFinishMsg, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId: g_Config.m_SvHideScore ? ClientId : -1);
4827}
4828
4829void CGameContext::SendSaveCode(int Team, int TeamSize, int State, const char *pError, const char *pSaveRequester, const char *pServerName, const char *pGeneratedCode, const char *pCode)
4830{
4831 char aBuf[512];
4832
4833 CMsgPacker Msg(NETMSGTYPE_SV_SAVECODE);
4834 Msg.AddInt(i: State);
4835 Msg.AddString(pStr: pError);
4836 Msg.AddString(pStr: pSaveRequester);
4837 Msg.AddString(pStr: pServerName);
4838 Msg.AddString(pStr: pGeneratedCode);
4839 Msg.AddString(pStr: pCode);
4840 char aTeamMembers[1024];
4841 aTeamMembers[0] = '\0';
4842 int NumMembersSent = 0;
4843 for(int MemberId = 0; MemberId < MAX_CLIENTS; MemberId++)
4844 {
4845 if(!m_apPlayers[MemberId])
4846 continue;
4847 if(GetDDRaceTeam(ClientId: MemberId) != Team)
4848 continue;
4849 if(NumMembersSent++ > 10)
4850 {
4851 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: " and %d others", (TeamSize - NumMembersSent) + 1);
4852 str_append(dst&: aTeamMembers, src: aBuf);
4853 break;
4854 }
4855
4856 if(NumMembersSent > 1)
4857 str_append(dst&: aTeamMembers, src: ", ");
4858 str_append(dst&: aTeamMembers, src: Server()->ClientName(ClientId: MemberId));
4859 }
4860 Msg.AddString(pStr: aTeamMembers);
4861
4862 for(int MemberId = 0; MemberId < MAX_CLIENTS; MemberId++)
4863 {
4864 if(!m_apPlayers[MemberId])
4865 continue;
4866 if(GetDDRaceTeam(ClientId: MemberId) != Team)
4867 continue;
4868
4869 if(GetClientVersion(ClientId: MemberId) >= VERSION_DDNET_SAVE_CODE)
4870 {
4871 Server()->SendMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId: MemberId);
4872 }
4873 else
4874 {
4875 switch(State)
4876 {
4877 case SAVESTATE_PENDING:
4878 if(pCode[0] == '\0')
4879 {
4880 str_format(buffer: aBuf,
4881 buffer_size: sizeof(aBuf),
4882 format: "Team save in progress. You'll be able to load with '/load %s'",
4883 pGeneratedCode);
4884 }
4885 else
4886 {
4887 str_format(buffer: aBuf,
4888 buffer_size: sizeof(aBuf),
4889 format: "Team save in progress. You'll be able to load with '/load %s' if save is successful or with '/load %s' if it fails",
4890 pCode,
4891 pGeneratedCode);
4892 }
4893 break;
4894 case SAVESTATE_DONE:
4895 if(str_comp(a: pServerName, b: g_Config.m_SvSqlServerName) == 0)
4896 {
4897 str_format(buffer: aBuf, buffer_size: sizeof(aBuf),
4898 format: "Team successfully saved by %s. Use '/load %s' to continue",
4899 pSaveRequester, pCode[0] ? pCode : pGeneratedCode);
4900 }
4901 else
4902 {
4903 str_format(buffer: aBuf, buffer_size: sizeof(aBuf),
4904 format: "Team successfully saved by %s. Use '/load %s' on %s to continue",
4905 pSaveRequester, pCode[0] ? pCode : pGeneratedCode, pServerName);
4906 }
4907 break;
4908 case SAVESTATE_FALLBACKFILE:
4909 SendBroadcast(pText: "Database connection failed, teamsave written to a file instead. On official DDNet servers this will automatically be inserted into the database every full hour.", ClientId: MemberId);
4910 if(str_comp(a: pServerName, b: g_Config.m_SvSqlServerName) == 0)
4911 {
4912 str_format(buffer: aBuf, buffer_size: sizeof(aBuf),
4913 format: "Team successfully saved by %s. The database connection failed, using generated save code instead to avoid collisions. Use '/load %s' to continue",
4914 pSaveRequester, pCode[0] ? pCode : pGeneratedCode);
4915 }
4916 else
4917 {
4918 str_format(buffer: aBuf, buffer_size: sizeof(aBuf),
4919 format: "Team successfully saved by %s. The database connection failed, using generated save code instead to avoid collisions. Use '/load %s' on %s to continue",
4920 pSaveRequester, pCode[0] ? pCode : pGeneratedCode, pServerName);
4921 }
4922 break;
4923 case SAVESTATE_ERROR:
4924 case SAVESTATE_WARNING:
4925 str_copy(dst&: aBuf, src: pError);
4926 break;
4927 default:
4928 dbg_assert_failed("Unexpected save state %d", State);
4929 }
4930 SendChatTarget(To: MemberId, pText: aBuf);
4931 }
4932 }
4933}
4934
4935bool CGameContext::ProcessSpamProtection(int ClientId, bool RespectChatInitialDelay)
4936{
4937 if(!m_apPlayers[ClientId])
4938 return false;
4939 if(g_Config.m_SvSpamprotection && m_apPlayers[ClientId]->m_LastChat && m_apPlayers[ClientId]->m_LastChat + Server()->TickSpeed() * g_Config.m_SvChatDelay > Server()->Tick())
4940 return true;
4941 else if(g_Config.m_SvDnsblChat && Server()->DnsblBlack(ClientId))
4942 {
4943 SendChatTarget(To: ClientId, pText: "Players are not allowed to chat from VPNs at this time");
4944 return true;
4945 }
4946 else
4947 m_apPlayers[ClientId]->m_LastChat = Server()->Tick();
4948
4949 const std::optional<CMute> Muted = m_Mutes.IsMuted(pAddr: Server()->ClientAddr(ClientId), RespectInitialDelay: RespectChatInitialDelay);
4950 if(Muted.has_value())
4951 {
4952 char aChatMessage[128];
4953 if(Muted->m_InitialDelay)
4954 {
4955 str_format(buffer: aChatMessage, buffer_size: sizeof(aChatMessage), format: "This server has an initial chat delay, you will be able to talk in %d seconds.", Muted->SecondsLeft());
4956 }
4957 else
4958 {
4959 str_format(buffer: aChatMessage, buffer_size: sizeof(aChatMessage), format: "You are not permitted to talk for the next %d seconds.", Muted->SecondsLeft());
4960 }
4961 SendChatTarget(To: ClientId, pText: aChatMessage);
4962 return true;
4963 }
4964
4965 if(g_Config.m_SvSpamMuteDuration && (m_apPlayers[ClientId]->m_ChatScore += g_Config.m_SvChatPenalty) > g_Config.m_SvChatThreshold)
4966 {
4967 MuteWithMessage(pAddr: Server()->ClientAddr(ClientId), Seconds: g_Config.m_SvSpamMuteDuration, pReason: "Spam protection", pDisplayName: Server()->ClientName(ClientId));
4968 m_apPlayers[ClientId]->m_ChatScore = 0;
4969 return true;
4970 }
4971
4972 return false;
4973}
4974
4975int CGameContext::GetDDRaceTeam(int ClientId) const
4976{
4977 return m_pController->Teams().m_Core.Team(ClientId);
4978}
4979
4980void CGameContext::ResetTuning()
4981{
4982 *GlobalTuning() = CTuningParams::DEFAULT;
4983 GlobalTuning()->Set(pName: "gun_speed", Value: 1400);
4984 GlobalTuning()->Set(pName: "gun_curvature", Value: 0);
4985 GlobalTuning()->Set(pName: "shotgun_speed", Value: 500);
4986 GlobalTuning()->Set(pName: "shotgun_speeddiff", Value: 0);
4987 GlobalTuning()->Set(pName: "shotgun_curvature", Value: 0);
4988 SendTuningParams(ClientId: -1);
4989}
4990
4991void CGameContext::Whisper(int ClientId, char *pStr)
4992{
4993 if(ProcessSpamProtection(ClientId))
4994 return;
4995
4996 pStr = str_skip_whitespaces(str: pStr);
4997
4998 const char *pName;
4999 int Victim;
5000 bool Error = false;
5001
5002 // add token
5003 if(*pStr == '"')
5004 {
5005 pStr++;
5006
5007 pName = pStr;
5008 char *pDst = pStr; // we might have to process escape data
5009 while(true)
5010 {
5011 if(pStr[0] == '"')
5012 {
5013 break;
5014 }
5015 else if(pStr[0] == '\\')
5016 {
5017 if(pStr[1] == '\\')
5018 pStr++; // skip due to escape
5019 else if(pStr[1] == '"')
5020 pStr++; // skip due to escape
5021 }
5022 else if(pStr[0] == 0)
5023 {
5024 Error = true;
5025 break;
5026 }
5027
5028 *pDst = *pStr;
5029 pDst++;
5030 pStr++;
5031 }
5032
5033 if(!Error)
5034 {
5035 *pDst = '\0';
5036 pStr++;
5037
5038 Victim = FindClientIdByName(pName).value_or(u: -1);
5039 }
5040 }
5041 else
5042 {
5043 pName = pStr;
5044 while(true)
5045 {
5046 if(pStr[0] == '\0')
5047 {
5048 Error = true;
5049 break;
5050 }
5051 if(pStr[0] == ' ')
5052 {
5053 pStr[0] = '\0';
5054
5055 Victim = FindClientIdByName(pName).value_or(u: -1);
5056
5057 pStr[0] = ' ';
5058 if(Victim != -1)
5059 break;
5060 }
5061 pStr++;
5062 }
5063 }
5064
5065 if(pStr[0] != ' ')
5066 {
5067 Error = true;
5068 }
5069
5070 *pStr = '\0';
5071 pStr++;
5072
5073 if(Error)
5074 {
5075 SendChatTarget(To: ClientId, pText: "Invalid whisper");
5076 return;
5077 }
5078
5079 if(!CheckClientId(ClientId: Victim))
5080 {
5081 char aBuf[256];
5082 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "No player with name \"%s\" found", pName);
5083 SendChatTarget(To: ClientId, pText: aBuf);
5084 return;
5085 }
5086
5087 WhisperId(ClientId, VictimId: Victim, pMessage: pStr);
5088}
5089
5090// Whispers are only recorded into the server demo when sv_demo_chat is set. Messages to 0.7 clients are
5091// packed in the 0.7 format and can never be recorded into the 0.6 demo.
5092int CGameContext::WhisperRecordFlag(int ClientId) const
5093{
5094 return g_Config.m_SvDemoChat && !Server()->IsSixup(ClientId) ? 0 : MSGFLAG_NORECORD;
5095}
5096
5097void CGameContext::WhisperId(int ClientId, int VictimId, const char *pMessage)
5098{
5099 dbg_assert(CheckClientId(ClientId) && m_apPlayers[ClientId] != nullptr, "ClientId invalid");
5100 dbg_assert(CheckClientId(VictimId) && m_apPlayers[VictimId] != nullptr, "VictimId invalid");
5101
5102 m_apPlayers[ClientId]->m_LastWhisperTo = VictimId;
5103
5104 char aCensoredMessage[256];
5105 CensorMessage(pCensoredMessage: aCensoredMessage, pMessage, Size: sizeof(aCensoredMessage));
5106
5107 char aBuf[256];
5108 protocol7::CNetMsg_Sv_Chat Msg;
5109 Msg.m_ClientId = ClientId;
5110 Msg.m_Mode = protocol7::CHAT_WHISPER;
5111 Msg.m_pMessage = aCensoredMessage;
5112 Msg.m_TargetId = VictimId;
5113
5114 if(Server()->IsSixup(ClientId) || GetClientVersion(ClientId) >= VERSION_DDNET_WHISPER)
5115 {
5116 // The translation layer will send the correct 0.6 packet after translating
5117 Msg.m_Mode = (int)protocol7::NUM_CHATS + TEAM_WHISPER_SEND;
5118 Server()->SendPackMsgTranslateChat(pMsg: &Msg, Flags: MSGFLAG_VITAL | WhisperRecordFlag(ClientId), ClientId);
5119 }
5120 else
5121 {
5122 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "[→ %s] %s", Server()->ClientName(ClientId: VictimId), aCensoredMessage);
5123 SendChatTarget(To: ClientId, pText: aBuf);
5124 }
5125
5126 if(!m_apPlayers[VictimId]->m_Whispers)
5127 {
5128 SendChatTarget(To: ClientId, pText: "This person has disabled receiving whispers");
5129 return;
5130 }
5131
5132 if(Server()->IsSixup(ClientId: VictimId) || GetClientVersion(ClientId: VictimId) >= VERSION_DDNET_WHISPER)
5133 {
5134 // The translation layer will send the correct 0.6 packet after translating
5135 Msg.m_Mode = (int)protocol7::NUM_CHATS + TEAM_WHISPER_RECV;
5136 Server()->SendPackMsgTranslateChat(pMsg: &Msg, Flags: MSGFLAG_VITAL | WhisperRecordFlag(ClientId: VictimId), ClientId: VictimId);
5137 }
5138 else
5139 {
5140 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "[← %s] %s", Server()->ClientName(ClientId), aCensoredMessage);
5141 SendChatTarget(To: VictimId, pText: aBuf);
5142 }
5143}
5144
5145void CGameContext::Converse(int ClientId, char *pStr)
5146{
5147 CPlayer *pPlayer = m_apPlayers[ClientId];
5148 if(!pPlayer)
5149 return;
5150
5151 if(ProcessSpamProtection(ClientId))
5152 return;
5153
5154 if(pPlayer->m_LastWhisperTo < 0)
5155 SendChatTarget(To: ClientId, pText: "You do not have an ongoing conversation. Whisper to someone to start one");
5156 else if(!m_apPlayers[pPlayer->m_LastWhisperTo])
5157 SendChatTarget(To: ClientId, pText: "The player you were whispering to hasn't reconnected yet or left. Please wait or whisper to someone else");
5158 else
5159 WhisperId(ClientId, VictimId: pPlayer->m_LastWhisperTo, pMessage: pStr);
5160}
5161
5162bool CGameContext::IsVersionBanned(int Version)
5163{
5164 char aVersion[16];
5165 str_format(buffer: aVersion, buffer_size: sizeof(aVersion), format: "%d", Version);
5166
5167 return str_in_list(list: g_Config.m_SvBannedVersions, delim: ",", needle: aVersion);
5168}
5169
5170void CGameContext::List(int ClientId, const char *pFilter)
5171{
5172 int Total = 0;
5173 char aBuf[256];
5174 int Bufcnt = 0;
5175 if(pFilter[0])
5176 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "Listing players with \"%s\" in name:", pFilter);
5177 else
5178 str_copy(dst&: aBuf, src: "Listing all players:");
5179 SendChatTarget(To: ClientId, pText: aBuf);
5180 for(int i = 0; i < MAX_CLIENTS; i++)
5181 {
5182 if(m_apPlayers[i])
5183 {
5184 Total++;
5185 const char *pName = Server()->ClientName(ClientId: i);
5186 if(str_utf8_find_nocase(haystack: pName, needle: pFilter) == nullptr)
5187 continue;
5188 if(Bufcnt + str_length(str: pName) + 4 > 256)
5189 {
5190 SendChatTarget(To: ClientId, pText: aBuf);
5191 Bufcnt = 0;
5192 }
5193 if(Bufcnt != 0)
5194 {
5195 str_format(buffer: &aBuf[Bufcnt], buffer_size: sizeof(aBuf) - Bufcnt, format: ", %s", pName);
5196 Bufcnt += 2 + str_length(str: pName);
5197 }
5198 else
5199 {
5200 str_copy(dst: &aBuf[Bufcnt], src: pName, dst_size: sizeof(aBuf) - Bufcnt);
5201 Bufcnt += str_length(str: pName);
5202 }
5203 }
5204 }
5205 if(Bufcnt != 0)
5206 SendChatTarget(To: ClientId, pText: aBuf);
5207 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%d players online", Total);
5208 SendChatTarget(To: ClientId, pText: aBuf);
5209}
5210
5211int CGameContext::GetClientVersion(int ClientId) const
5212{
5213 return Server()->GetClientVersion(ClientId);
5214}
5215
5216CClientMask CGameContext::ClientsMaskExcludeClientVersionAndHigher(int Version) const
5217{
5218 CClientMask Mask;
5219 for(int i = 0; i < MAX_CLIENTS; ++i)
5220 {
5221 if(GetClientVersion(ClientId: i) >= Version)
5222 continue;
5223 Mask.set(pos: i);
5224 }
5225 return Mask;
5226}
5227
5228bool CGameContext::PlayerModerating() const
5229{
5230 return std::any_of(first: std::begin(arr: m_apPlayers), last: std::end(arr: m_apPlayers), pred: [](const CPlayer *pPlayer) { return pPlayer && pPlayer->m_Moderating; });
5231}
5232
5233void CGameContext::ForceVote(bool Success)
5234{
5235 // check if there is a vote running
5236 if(!m_VoteCloseTime)
5237 return;
5238
5239 m_VoteEnforce = Success ? CGameContext::VOTE_ENFORCE_YES_ADMIN : CGameContext::VOTE_ENFORCE_NO_ADMIN;
5240 const char *pOption = Success ? "yes" : "no";
5241
5242 char aChatMessage[256];
5243 str_format(buffer: aChatMessage, buffer_size: sizeof(aChatMessage), format: "Authorized player forced vote '%s'", pOption);
5244 SendChatTarget(To: -1, pText: aChatMessage);
5245
5246 log_info("server", "Forcing vote '%s'", pOption);
5247}
5248
5249bool CGameContext::RateLimitPlayerVote(int ClientId)
5250{
5251 int64_t Now = Server()->Tick();
5252 int64_t TickSpeed = Server()->TickSpeed();
5253 CPlayer *pPlayer = m_apPlayers[ClientId];
5254
5255 if(g_Config.m_SvRconVote && !Server()->IsRconAuthed(ClientId))
5256 {
5257 SendChatTarget(To: ClientId, pText: "You can only vote after logging in.");
5258 return true;
5259 }
5260
5261 if(g_Config.m_SvDnsblVote && Server()->DistinctClientCount() > 1)
5262 {
5263 if(m_pServer->DnsblPending(ClientId))
5264 {
5265 SendChatTarget(To: ClientId, pText: "You are not allowed to vote because we're currently checking for VPNs. Try again in ~30 seconds.");
5266 return true;
5267 }
5268 else if(m_pServer->DnsblBlack(ClientId))
5269 {
5270 SendChatTarget(To: ClientId, pText: "You are not allowed to vote because you appear to be using a VPN. Try connecting without a VPN or contacting an admin if you think this is a mistake.");
5271 return true;
5272 }
5273 }
5274
5275 if(g_Config.m_SvSpamprotection && pPlayer->m_LastVoteTry && pPlayer->m_LastVoteTry + TickSpeed * 3 > Now)
5276 return true;
5277
5278 pPlayer->m_LastVoteTry = Now;
5279 if(m_VoteCloseTime)
5280 {
5281 SendChatTarget(To: ClientId, pText: "Wait for current vote to end before calling a new one.");
5282 return true;
5283 }
5284
5285 if(Now < pPlayer->m_FirstVoteTick)
5286 {
5287 char aChatMessage[64];
5288 str_format(buffer: aChatMessage, buffer_size: sizeof(aChatMessage), format: "You must wait %d seconds before making your first vote.", (int)((pPlayer->m_FirstVoteTick - Now) / TickSpeed) + 1);
5289 SendChatTarget(To: ClientId, pText: aChatMessage);
5290 return true;
5291 }
5292
5293 int TimeLeft = pPlayer->m_LastVoteCall + TickSpeed * g_Config.m_SvVoteDelay - Now;
5294 if(pPlayer->m_LastVoteCall && TimeLeft > 0)
5295 {
5296 char aChatMessage[64];
5297 str_format(buffer: aChatMessage, buffer_size: sizeof(aChatMessage), format: "You must wait %d seconds before making another vote.", (int)(TimeLeft / TickSpeed) + 1);
5298 SendChatTarget(To: ClientId, pText: aChatMessage);
5299 return true;
5300 }
5301
5302 const NETADDR *pAddr = Server()->ClientAddr(ClientId);
5303 std::optional<CMute> Muted = m_VoteMutes.IsMuted(pAddr, RespectInitialDelay: true);
5304 if(!Muted.has_value())
5305 {
5306 Muted = m_Mutes.IsMuted(pAddr, RespectInitialDelay: true);
5307 }
5308 if(Muted.has_value())
5309 {
5310 char aChatMessage[64];
5311 str_format(buffer: aChatMessage, buffer_size: sizeof(aChatMessage), format: "You are not permitted to vote for the next %d seconds.", Muted->SecondsLeft());
5312 SendChatTarget(To: ClientId, pText: aChatMessage);
5313 return true;
5314 }
5315 return false;
5316}
5317
5318bool CGameContext::RateLimitPlayerMapVote(int ClientId) const
5319{
5320 if(!Server()->IsRconAuthed(ClientId) && time_get() < m_LastMapVote + (time_freq() * g_Config.m_SvVoteMapTimeDelay))
5321 {
5322 char aChatMessage[128];
5323 str_format(buffer: aChatMessage, buffer_size: sizeof(aChatMessage), format: "There's a %d second delay between map-votes, please wait %d seconds.",
5324 g_Config.m_SvVoteMapTimeDelay, (int)((m_LastMapVote + g_Config.m_SvVoteMapTimeDelay * time_freq() - time_get()) / time_freq()));
5325 SendChatTarget(To: ClientId, pText: aChatMessage);
5326 return true;
5327 }
5328 return false;
5329}
5330
5331void CGameContext::OnUpdatePlayerServerInfo(CJsonWriter *pJsonWriter, int ClientId)
5332{
5333 if(!m_apPlayers[ClientId])
5334 return;
5335
5336 const CTeeInfo &TeeInfo = m_apPlayers[ClientId]->TeeInfos();
5337
5338 pJsonWriter->WriteAttribute(pName: "skin");
5339 pJsonWriter->BeginObject();
5340
5341 // 0.6
5342 if(!Server()->IsSixup(ClientId))
5343 {
5344 pJsonWriter->WriteAttribute(pName: "name");
5345 pJsonWriter->WriteStrValue(pValue: TeeInfo.m_aSkinName);
5346
5347 if(TeeInfo.m_UseCustomColor)
5348 {
5349 pJsonWriter->WriteAttribute(pName: "color_body");
5350 pJsonWriter->WriteIntValue(Value: TeeInfo.m_ColorBody);
5351
5352 pJsonWriter->WriteAttribute(pName: "color_feet");
5353 pJsonWriter->WriteIntValue(Value: TeeInfo.m_ColorFeet);
5354 }
5355 }
5356 // 0.7
5357 else
5358 {
5359 const char *apPartNames[protocol7::NUM_SKINPARTS] = {"body", "marking", "decoration", "hands", "feet", "eyes"};
5360
5361 for(int i = 0; i < protocol7::NUM_SKINPARTS; ++i)
5362 {
5363 pJsonWriter->WriteAttribute(pName: apPartNames[i]);
5364 pJsonWriter->BeginObject();
5365
5366 pJsonWriter->WriteAttribute(pName: "name");
5367 pJsonWriter->WriteStrValue(pValue: TeeInfo.m_aaSkinPartNames[i]);
5368
5369 if(TeeInfo.m_aUseCustomColors[i])
5370 {
5371 pJsonWriter->WriteAttribute(pName: "color");
5372 pJsonWriter->WriteIntValue(Value: TeeInfo.m_aSkinPartColors[i]);
5373 }
5374
5375 pJsonWriter->EndObject();
5376 }
5377 }
5378
5379 pJsonWriter->EndObject();
5380
5381 pJsonWriter->WriteAttribute(pName: "afk");
5382 pJsonWriter->WriteBoolValue(Value: m_apPlayers[ClientId]->IsAfk());
5383
5384 const int Team = m_pController->IsTeamPlay() ? m_apPlayers[ClientId]->GetTeam() : (m_apPlayers[ClientId]->GetTeam() == TEAM_SPECTATORS ? -1 : GetDDRaceTeam(ClientId));
5385
5386 pJsonWriter->WriteAttribute(pName: "team");
5387 pJsonWriter->WriteIntValue(Value: Team);
5388}
5389
5390void CGameContext::ReadCensorList()
5391{
5392 const char *pCensorFilename = "censorlist.txt";
5393 CLineReader LineReader;
5394 m_vCensorlist.clear();
5395 if(LineReader.OpenFile(File: Storage()->OpenFile(pFilename: pCensorFilename, Flags: IOFLAG_READ, Type: IStorage::TYPE_ALL)))
5396 {
5397 while(const char *pLine = LineReader.Get())
5398 {
5399 if(pLine[0] == '\0')
5400 {
5401 continue;
5402 }
5403 m_vCensorlist.emplace_back(args&: pLine);
5404 }
5405 }
5406 else
5407 {
5408 dbg_msg(sys: "censorlist", fmt: "failed to open '%s'", pCensorFilename);
5409 }
5410}
5411
5412bool CGameContext::PracticeByDefault() const
5413{
5414 return g_Config.m_SvPracticeByDefault && g_Config.m_SvTestingCommands;
5415}
5416
5417void CGameContext::SendStartMessages(int ClientId)
5418{
5419 if(Server()->IsSixup(ClientId))
5420 {
5421 {
5422 protocol7::CNetMsg_Sv_GameInfo Msg;
5423 Msg.m_GameFlags = m_pController->GameFlags();
5424 Msg.m_MatchCurrent = 1;
5425 Msg.m_MatchNum = 0;
5426 Msg.m_ScoreLimit = 0;
5427 Msg.m_TimeLimit = 0;
5428 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId);
5429 }
5430
5431 // /team is essential
5432 {
5433 protocol7::CNetMsg_Sv_CommandInfoRemove Msg;
5434 Msg.m_pName = "team";
5435 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId);
5436 }
5437 }
5438
5439 {
5440 CNetMsg_Sv_CommandInfoGroupStart Msg;
5441 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId);
5442 }
5443 for(const IConsole::ICommandInfo *pCmd = Console()->FirstCommandInfo(ClientId, FlagMask: CFGFLAG_CHAT);
5444 pCmd; pCmd = Console()->NextCommandInfo(pInfo: pCmd, ClientId, FlagMask: CFGFLAG_CHAT))
5445 {
5446 const char *pName = pCmd->Name();
5447
5448 if(Server()->IsSixup(ClientId))
5449 {
5450 if(!str_comp_nocase(a: pName, b: "w") || !str_comp_nocase(a: pName, b: "whisper"))
5451 continue;
5452
5453 if(!str_comp_nocase(a: pName, b: "r"))
5454 pName = "rescue";
5455
5456 protocol7::CNetMsg_Sv_CommandInfo Msg;
5457 Msg.m_pName = pName;
5458 Msg.m_pArgsFormat = pCmd->Params();
5459 Msg.m_pHelpText = pCmd->Help();
5460 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId);
5461 }
5462 else
5463 {
5464 CNetMsg_Sv_CommandInfo Msg;
5465 Msg.m_pName = pName;
5466 Msg.m_pArgsFormat = pCmd->Params();
5467 Msg.m_pHelpText = pCmd->Help();
5468 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId);
5469 }
5470 }
5471 {
5472 CNetMsg_Sv_CommandInfoGroupEnd Msg;
5473 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId);
5474 }
5475
5476 // send active vote
5477 if(m_VoteCloseTime)
5478 SendVoteSet(ClientId);
5479}
5480
5481void CGameContext::OnClientRejoin(int ClientId)
5482{
5483 if(!m_apPlayers[ClientId])
5484 return;
5485
5486 ReinitPlayerMap(ClientId, Timeout: false);
5487 SendStartMessages(ClientId);
5488 SendSettings(ClientId);
5489
5490 // send clear vote options
5491 CNetMsg_Sv_VoteClearOptions ClearMsg;
5492 Server()->SendPackMsg(pMsg: &ClearMsg, Flags: MSGFLAG_VITAL, ClientId);
5493
5494 // begin sending vote options
5495 m_apPlayers[ClientId]->m_SendVoteIndex = 0;
5496 SendTuningParams(ClientId, Zone: m_apPlayers[ClientId]->m_TuneZone);
5497}
5498
5499void CGameContext::ReinitPlayerMap(int ClientId, bool Timeout)
5500{
5501 // Timeout, when calling InitPlayerMap because that will make sure each disconnect packet gets sent out to 0.7 clients correctly before inserting
5502 // new players on their slots. will also trigger teams state update, otherwise you wouldn't see teams correctly in some cases.
5503 CPlayerMapping::CSixupCfg SixupCfg;
5504 SixupCfg.m_SkipTimeoutedId = Timeout;
5505 SixupCfg.m_ClearSlots = true;
5506 m_PlayerMapping.InitPlayerMap(ClientId, SixupCfg);
5507}
5508