1/* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */
2#include "teams.h"
3
4#include "gamecontroller.h"
5#include "player.h"
6#include "score.h"
7#include "teehistorian.h"
8
9#include <base/dbg.h>
10#include <base/str.h>
11#include <base/time.h>
12
13#include <engine/shared/config.h>
14#include <engine/shared/protocol.h>
15
16#include <game/mapitems.h>
17#include <game/server/entities/character.h>
18#include <game/server/gamecontext.h>
19#include <game/server/interactions.h>
20#include <game/team_state.h>
21
22#include <bitset>
23
24CGameTeams::CGameTeams(CGameContext *pGameContext) :
25 m_pGameContext(pGameContext)
26{
27 Reset();
28}
29
30void CGameTeams::Reset()
31{
32 m_Core.Reset();
33 UpdateLegacyTeamMap();
34 for(int i = 0; i < MAX_CLIENTS; ++i)
35 {
36 m_aTeeStarted[i] = false;
37 m_aTeeFinished[i] = false;
38 m_aLastChat[i] = 0;
39 SendTeamsState(ClientId: i);
40 }
41
42 for(int i = 0; i < NUM_DDRACE_TEAMS; ++i)
43 {
44 m_aTeamState[i] = ETeamState::EMPTY;
45 m_aTeamLocked[i] = false;
46 m_aTeamFlock[i] = false;
47 m_apSaveTeamResult[i] = nullptr;
48 m_aTeamSentStartWarning[i] = false;
49 if(m_pGameContext->PracticeByDefault())
50 m_aPractice[i] = true;
51 ResetRoundState(Team: i);
52 }
53}
54
55void CGameTeams::ResetRoundState(int Team)
56{
57 ResetInvited(Team);
58 if(Team != TEAM_SUPER)
59 ResetSwitchers(Team);
60
61 if(!m_pGameContext->PracticeByDefault())
62 m_aPractice[Team] = false;
63 m_aTeamUnfinishableKillTick[Team] = -1;
64 for(int i = 0; i < MAX_CLIENTS; i++)
65 {
66 if(m_Core.Team(ClientId: i) == Team && GameServer()->m_apPlayers[i])
67 {
68 GameServer()->m_apPlayers[i]->m_VotedForPractice = false;
69 GameServer()->m_apPlayers[i]->m_SwapTargetsClientId = -1;
70 m_aLastSwap[i] = 0;
71 }
72 }
73}
74
75void CGameTeams::ResetSwitchers(int Team)
76{
77 for(auto &Switcher : GameServer()->Switchers())
78 {
79 Switcher.m_aStatus[Team] = Switcher.m_Initial;
80 Switcher.m_aEndTick[Team] = 0;
81 Switcher.m_aType[Team] = TILE_SWITCHOPEN;
82 }
83}
84
85void CGameTeams::OnCharacterStart(int ClientId)
86{
87 int Tick = Server()->Tick();
88 CCharacter *pStartingChar = Character(ClientId);
89 if(!pStartingChar)
90 return;
91 if(g_Config.m_SvTeam == SV_TEAM_FORCED_SOLO && pStartingChar->m_DDRaceState == ERaceState::STARTED)
92 return;
93 if((g_Config.m_SvTeam == SV_TEAM_FORCED_SOLO || (m_Core.Team(ClientId) != TEAM_FLOCK && !m_aTeamFlock[m_Core.Team(ClientId)])) && pStartingChar->m_DDRaceState == ERaceState::FINISHED)
94 return;
95 if(g_Config.m_SvTeam != SV_TEAM_FORCED_SOLO &&
96 (m_Core.Team(ClientId) == TEAM_FLOCK || TeamFlock(Team: m_Core.Team(ClientId)) || m_Core.Team(ClientId) == TEAM_SUPER))
97 {
98 if(TeamFlock(Team: m_Core.Team(ClientId)) && (m_aTeamState[m_Core.Team(ClientId)] < ETeamState::STARTED))
99 ChangeTeamState(Team: m_Core.Team(ClientId), State: ETeamState::STARTED);
100
101 m_aTeeStarted[ClientId] = true;
102 pStartingChar->m_DDRaceState = ERaceState::STARTED;
103 pStartingChar->m_StartTime = Tick;
104 return;
105 }
106 bool Waiting = false;
107 for(int i = 0; i < MAX_CLIENTS; ++i)
108 {
109 if(m_Core.Team(ClientId) != m_Core.Team(ClientId: i))
110 continue;
111 CPlayer *pPlayer = GetPlayer(ClientId: i);
112 if(!pPlayer || !pPlayer->IsPlaying())
113 continue;
114 if(GetDDRaceState(Player: pPlayer) != ERaceState::FINISHED)
115 continue;
116
117 Waiting = true;
118 pStartingChar->m_DDRaceState = ERaceState::NONE;
119
120 if(m_aLastChat[ClientId] + Server()->TickSpeed() + g_Config.m_SvChatDelay < Tick)
121 {
122 char aBuf[128];
123 str_format(
124 buffer: aBuf,
125 buffer_size: sizeof(aBuf),
126 format: "%s has finished and didn't go through start yet, wait for them or join another team.",
127 Server()->ClientName(ClientId: i));
128 GameServer()->SendChatTarget(To: ClientId, pText: aBuf);
129 m_aLastChat[ClientId] = Tick;
130 }
131 if(m_aLastChat[i] + Server()->TickSpeed() + g_Config.m_SvChatDelay < Tick)
132 {
133 char aBuf[128];
134 str_format(
135 buffer: aBuf,
136 buffer_size: sizeof(aBuf),
137 format: "%s wants to start a new round, kill or walk to start.",
138 Server()->ClientName(ClientId));
139 GameServer()->SendChatTarget(To: i, pText: aBuf);
140 m_aLastChat[i] = Tick;
141 }
142 }
143
144 if(!Waiting)
145 {
146 m_aTeeStarted[ClientId] = true;
147 }
148
149 if(m_aTeamState[m_Core.Team(ClientId)] < ETeamState::STARTED && !Waiting)
150 {
151 ChangeTeamState(Team: m_Core.Team(ClientId), State: ETeamState::STARTED);
152 m_aTeamSentStartWarning[m_Core.Team(ClientId)] = false;
153 m_aTeamUnfinishableKillTick[m_Core.Team(ClientId)] = -1;
154
155 int NumPlayers = TeamSize(Team: m_Core.Team(ClientId));
156
157 char aBuf[512];
158 str_format(
159 buffer: aBuf,
160 buffer_size: sizeof(aBuf),
161 format: "Team %d started with %d player%s: ",
162 m_Core.Team(ClientId),
163 NumPlayers,
164 NumPlayers == 1 ? "" : "s");
165
166 bool First = true;
167
168 for(int i = 0; i < MAX_CLIENTS; ++i)
169 {
170 if(m_Core.Team(ClientId) == m_Core.Team(ClientId: i))
171 {
172 CPlayer *pPlayer = GetPlayer(ClientId: i);
173 // TODO: THE PROBLEM IS THAT THERE IS NO CHARACTER SO START TIME CAN'T BE SET!
174 if(pPlayer && (pPlayer->IsPlaying() || TeamLocked(Team: m_Core.Team(ClientId))))
175 {
176 SetDDRaceState(Player: pPlayer, DDRaceState: ERaceState::STARTED);
177 SetStartTime(Player: pPlayer, StartTime: Tick);
178
179 if(First)
180 First = false;
181 else
182 str_append(dst&: aBuf, src: ", ");
183
184 str_append(dst&: aBuf, src: GameServer()->Server()->ClientName(ClientId: i));
185 }
186 }
187 }
188
189 if(g_Config.m_SvTeam != SV_TEAM_FORCED_SOLO && g_Config.m_SvMaxTeamSize != 2 && g_Config.m_SvPauseable)
190 {
191 for(int i = 0; i < MAX_CLIENTS; ++i)
192 {
193 CPlayer *pPlayer = GetPlayer(ClientId: i);
194 if(m_Core.Team(ClientId) == m_Core.Team(ClientId: i) && pPlayer && (pPlayer->IsPlaying() || TeamLocked(Team: m_Core.Team(ClientId))))
195 {
196 GameServer()->SendChatTarget(To: i, pText: aBuf);
197 }
198 }
199 }
200 }
201}
202
203void CGameTeams::OnCharacterFinish(int ClientId)
204{
205 if(((m_Core.Team(ClientId) == TEAM_FLOCK || m_aTeamFlock[m_Core.Team(ClientId)]) && g_Config.m_SvTeam != SV_TEAM_FORCED_SOLO) || m_Core.Team(ClientId) == TEAM_SUPER)
206 {
207 CPlayer *pPlayer = GetPlayer(ClientId);
208 if(pPlayer && pPlayer->IsPlaying())
209 {
210 int TimeTicks = Server()->Tick() - GetStartTime(Player: pPlayer);
211 if(TimeTicks <= 0)
212 return;
213 char aTimestamp[TIMESTAMP_STR_LENGTH];
214 str_timestamp_format(buffer: aTimestamp, buffer_size: sizeof(aTimestamp), format: TimestampFormat::SPACE); // 2019-04-02 19:41:58
215
216 OnFinish(Player: pPlayer, TimeTicks, pTimestamp: aTimestamp);
217 }
218 }
219 else
220 {
221 if(m_aTeeStarted[ClientId])
222 {
223 m_aTeeFinished[ClientId] = true;
224 }
225 CheckTeamFinished(Team: m_Core.Team(ClientId));
226 }
227}
228
229void CGameTeams::Tick()
230{
231 int Now = Server()->Tick();
232
233 for(int i = 0; i < MAX_CLIENTS; i++)
234 {
235 CPlayerData *pData = GameServer()->Score()->PlayerData(Id: i);
236 if(!Server()->IsRecording(ClientId: i))
237 continue;
238
239 if(Now >= pData->m_RecordStopTick && pData->m_RecordStopTick != -1)
240 {
241 Server()->SaveDemo(ClientId: i, Time: pData->m_RecordFinishTime);
242 pData->m_RecordStopTick = -1;
243 }
244 }
245
246 for(int i = 0; i < TEAM_SUPER; i++)
247 {
248 if(m_aTeamUnfinishableKillTick[i] == -1 || m_aTeamState[i] != ETeamState::STARTED_UNFINISHABLE)
249 {
250 continue;
251 }
252 if(Now >= m_aTeamUnfinishableKillTick[i])
253 {
254 if(m_aPractice[i])
255 {
256 m_aTeamUnfinishableKillTick[i] = -1;
257 continue;
258 }
259 GameServer()->SendChatTeam(Team: i, pText: "Your team was killed because it couldn't finish anymore and hasn't entered /practice mode");
260 KillTeam(Team: i, NewStrongId: -1);
261 }
262 }
263
264 int Frequency = Server()->TickSpeed() * 60;
265 int Remainder = Server()->TickSpeed() * 30;
266 std::bitset<NUM_DDRACE_TEAMS> TeamHasWantedStartTime;
267 for(int i = 0; i < MAX_CLIENTS; i++)
268 {
269 CCharacter *pChar = GameServer()->m_apPlayers[i] ? GameServer()->m_apPlayers[i]->GetCharacter() : nullptr;
270 int Team = m_Core.Team(ClientId: i);
271 if(!pChar || m_aTeamState[Team] != ETeamState::STARTED || m_aTeamFlock[Team] || m_aTeeStarted[i] || m_aPractice[m_Core.Team(ClientId: i)])
272 {
273 continue;
274 }
275 if((Now - pChar->m_StartTime) % Frequency == Remainder)
276 {
277 TeamHasWantedStartTime.set(pos: m_Core.Team(ClientId: i));
278 }
279 }
280 TeamHasWantedStartTime.reset(pos: TEAM_FLOCK);
281 if(TeamHasWantedStartTime.none())
282 {
283 return;
284 }
285 for(int i = 0; i < MAX_CLIENTS; i++)
286 {
287 if(!TeamHasWantedStartTime.test(position: i))
288 {
289 continue;
290 }
291 if(TeamSize(Team: i) <= 1)
292 {
293 continue;
294 }
295 bool TeamHasCheatCharacter = false;
296 int NumPlayersNotStarted = 0;
297 char aPlayerNames[256];
298 aPlayerNames[0] = 0;
299 for(int j = 0; j < MAX_CLIENTS; j++)
300 {
301 if(Character(ClientId: j) && Character(ClientId: j)->m_DDRaceState == ERaceState::CHEATED)
302 TeamHasCheatCharacter = true;
303 if(m_Core.Team(ClientId: j) == i && !m_aTeeStarted[j])
304 {
305 if(aPlayerNames[0])
306 {
307 str_append(dst&: aPlayerNames, src: ", ");
308 }
309 str_append(dst&: aPlayerNames, src: Server()->ClientName(ClientId: j));
310 NumPlayersNotStarted += 1;
311 }
312 }
313 if(!aPlayerNames[0] || TeamHasCheatCharacter)
314 {
315 continue;
316 }
317 char aBuf[512];
318 str_format(buffer: aBuf, buffer_size: sizeof(aBuf),
319 format: "Your team has %d %s not started yet, they need "
320 "to touch the start before this team can finish: %s",
321 NumPlayersNotStarted,
322 NumPlayersNotStarted == 1 ? "player that has" : "players that have",
323 aPlayerNames);
324 GameServer()->SendChatTeam(Team: i, pText: aBuf);
325 }
326}
327
328void CGameTeams::CheckTeamFinished(int Team)
329{
330 if(TeamFinished(Team))
331 {
332 CPlayer *apTeamPlayers[MAX_CLIENTS];
333 unsigned int PlayersCount = 0;
334
335 for(int i = 0; i < MAX_CLIENTS; ++i)
336 {
337 if(Team == m_Core.Team(ClientId: i))
338 {
339 CPlayer *pPlayer = GetPlayer(ClientId: i);
340 if(pPlayer && pPlayer->IsPlaying())
341 {
342 m_aTeeStarted[i] = false;
343 m_aTeeFinished[i] = false;
344
345 apTeamPlayers[PlayersCount++] = pPlayer;
346 }
347 }
348 }
349
350 if(PlayersCount > 0)
351 {
352 int TimeTicks = Server()->Tick() - GetStartTime(Player: apTeamPlayers[0]);
353 float Time = (float)TimeTicks / (float)Server()->TickSpeed();
354 if(TimeTicks <= 0)
355 {
356 return;
357 }
358
359 if(m_aPractice[Team])
360 {
361 ChangeTeamState(Team, State: ETeamState::FINISHED);
362
363 const int Minutes = (int)Time / 60;
364 const float Seconds = Time - (Minutes * 60.0f);
365
366 char aBuf[256];
367 str_format(buffer: aBuf, buffer_size: sizeof(aBuf),
368 format: "Your team would've finished in: %d minute(s) %5.2f second(s). Since you had practice mode enabled your rank doesn't count.",
369 Minutes, Seconds);
370 GameServer()->SendChatTeam(Team, pText: aBuf);
371
372 for(unsigned int i = 0; i < PlayersCount; ++i)
373 {
374 SetDDRaceState(Player: apTeamPlayers[i], DDRaceState: ERaceState::FINISHED);
375 }
376
377 return;
378 }
379
380 char aTimestamp[TIMESTAMP_STR_LENGTH];
381 str_timestamp_format(buffer: aTimestamp, buffer_size: sizeof(aTimestamp), format: TimestampFormat::SPACE); // 2019-04-02 19:41:58
382
383 for(unsigned int i = 0; i < PlayersCount; ++i)
384 OnFinish(Player: apTeamPlayers[i], TimeTicks, pTimestamp: aTimestamp);
385 ChangeTeamState(Team, State: ETeamState::FINISHED); // TODO: Make it better
386 OnTeamFinish(Team, Players: apTeamPlayers, Size: PlayersCount, TimeTicks, pTimestamp: aTimestamp);
387 }
388 }
389}
390
391bool CGameTeams::CanJoinTeam(int ClientId, int Team, char *pError, int ErrorSize) const
392{
393 int CurrentTeam = m_Core.Team(ClientId);
394
395 if(ClientId < 0 || ClientId >= MAX_CLIENTS)
396 {
397 str_format(buffer: pError, buffer_size: ErrorSize, format: "Invalid client ID: %d", ClientId);
398 return false;
399 }
400 if(!IsValidTeamNumber(Team) && Team != TEAM_SUPER)
401 {
402 str_format(buffer: pError, buffer_size: ErrorSize, format: "Invalid team number: %d", Team);
403 return false;
404 }
405 if(Team != TEAM_SUPER && m_aTeamState[Team] > ETeamState::OPEN && !m_aPractice[Team] && !m_aTeamFlock[Team])
406 {
407 str_copy(dst: pError, src: "This team started already", dst_size: ErrorSize);
408 return false;
409 }
410 if(CurrentTeam == Team)
411 {
412 str_copy(dst: pError, src: "You are in this team already", dst_size: ErrorSize);
413 return false;
414 }
415 if(!Character(ClientId))
416 {
417 str_copy(dst: pError, src: "You can't change teams while you are dead/a spectator.", dst_size: ErrorSize);
418 return false;
419 }
420 if(Team == TEAM_SUPER && !Character(ClientId)->IsSuper())
421 {
422 str_copy(dst: pError, src: "You can't join super team if you don't have super rights", dst_size: ErrorSize);
423 return false;
424 }
425 if(Team != TEAM_SUPER && Character(ClientId)->m_DDRaceState != ERaceState::NONE && (m_aTeamState[CurrentTeam] < ETeamState::FINISHED || Team != 0))
426 {
427 str_copy(dst: pError, src: "You have started racing already", dst_size: ErrorSize);
428 return false;
429 }
430 // No cheating through noob filter with practice and then leaving team
431 if(m_aPractice[CurrentTeam] && !m_pGameContext->PracticeByDefault())
432 {
433 str_copy(dst: pError, src: "You have used practice mode already", dst_size: ErrorSize);
434 return false;
435 }
436
437 // you can not join a team which is currently in the process of saving,
438 // because the save-process can fail and then the team is reset into the game
439 if(Team != TEAM_SUPER && GetSaving(TeamId: Team))
440 {
441 str_copy(dst: pError, src: "This team is currently saving", dst_size: ErrorSize);
442 return false;
443 }
444 if(CurrentTeam != TEAM_SUPER && GetSaving(TeamId: CurrentTeam))
445 {
446 str_copy(dst: pError, src: "Your team is currently saving", dst_size: ErrorSize);
447 return false;
448 }
449
450 return true;
451}
452
453bool CGameTeams::SetCharacterTeam(int ClientId, int Team, char *pError, int ErrorSize)
454{
455 if(!CanJoinTeam(ClientId, Team, pError, ErrorSize))
456 return false;
457
458 SetForceCharacterTeam(ClientId, Team);
459 return true;
460}
461
462void CGameTeams::SetForceCharacterTeam(int ClientId, int Team)
463{
464 m_aTeeStarted[ClientId] = false;
465 m_aTeeFinished[ClientId] = false;
466 int OldTeam = m_Core.Team(ClientId);
467
468 if(Team != OldTeam && (OldTeam != TEAM_FLOCK || g_Config.m_SvTeam == SV_TEAM_FORCED_SOLO) && OldTeam != TEAM_SUPER && m_aTeamState[OldTeam] != ETeamState::EMPTY)
469 {
470 bool NoElseInOldTeam = TeamSize(Team: OldTeam) <= 1;
471 if(NoElseInOldTeam)
472 {
473 m_aTeamState[OldTeam] = ETeamState::EMPTY;
474
475 // unlock team when last player leaves
476 SetTeamLock(Team: OldTeam, Lock: false);
477 SetTeamFlock(Team: OldTeam, Mode: false);
478 ResetRoundState(Team: OldTeam);
479 // do not reset SaveTeamResult, because it should be logged into teehistorian even if the team leaves
480 }
481 }
482
483 m_Core.Team(ClientId, Team);
484 UpdateLegacyTeamMap();
485
486 if(OldTeam != Team)
487 {
488 for(int LoopClientId = 0; LoopClientId < MAX_CLIENTS; ++LoopClientId)
489 if(GetPlayer(ClientId: LoopClientId))
490 SendTeamsState(ClientId: LoopClientId);
491
492 if(GetPlayer(ClientId))
493 {
494 GetPlayer(ClientId)->m_VotedForPractice = false;
495 GetPlayer(ClientId)->m_SwapTargetsClientId = -1;
496 }
497 m_pGameContext->m_World.RemoveEntitiesFromPlayer(PlayerId: ClientId);
498 }
499
500 if(Team != TEAM_SUPER && (m_aTeamState[Team] == ETeamState::EMPTY || (m_aTeamLocked[Team] && !m_aTeamFlock[Team])))
501 {
502 if(!m_aTeamLocked[Team])
503 ChangeTeamState(Team, State: ETeamState::OPEN);
504
505 ResetSwitchers(Team);
506 }
507}
508
509int CGameTeams::TeamSize(int Team) const
510{
511 if(Team == TEAM_SUPER)
512 return -1;
513
514 int Count = 0;
515
516 for(int i = 0; i < MAX_CLIENTS; ++i)
517 if(m_Core.Team(ClientId: i) == Team)
518 Count++;
519
520 return Count;
521}
522
523void CGameTeams::ChangeTeamState(int Team, ETeamState State)
524{
525 m_aTeamState[Team] = State;
526}
527
528void CGameTeams::KillTeam(int Team, int NewStrongId, int ExceptId)
529{
530 CClientMask KilledMask;
531 for(int i = 0; i < MAX_CLIENTS; i++)
532 {
533 if(m_Core.Team(ClientId: i) == Team && GameServer()->m_apPlayers[i])
534 {
535 GameServer()->m_apPlayers[i]->m_VotedForPractice = false;
536 if(i != ExceptId)
537 {
538 if(GameServer()->m_apPlayers[i]->GetCharacter())
539 KilledMask.set(pos: i);
540 GameServer()->m_apPlayers[i]->KillCharacter(Weapon: WEAPON_SELF, SendKillMsg: false);
541 if(NewStrongId != -1 && i != NewStrongId)
542 {
543 GameServer()->m_apPlayers[i]->Respawn(WeakHook: true); // spawn the rest of team with weak hook on the killer
544 }
545 }
546 }
547 }
548
549 // send the team kill message, the team number can differ per client
550 CNetMsg_Sv_KillMsgTeam Msg;
551 Msg.m_Team = Team;
552 Msg.m_First = NewStrongId;
553
554 // pack one with the real team and id for the recording only, the per client messages are not recorded
555 CMsgPacker Packer(&Msg);
556 Msg.Pack(pPacker: &Packer);
557 Server()->SendMsg(pMsg: &Packer, Flags: MSGFLAG_NOSEND, ClientId: SERVER_DEMO_CLIENT);
558
559 for(int i = 0; i < MAX_CLIENTS; i++)
560 {
561 if(!Server()->ClientIngame(ClientId: i))
562 continue;
563 Msg.m_Team = TeamForClient(Team, ClientId: i);
564 if(Msg.m_Team == TEAM_FLOCK && Team != TEAM_FLOCK)
565 {
566 // The client resets prediction for every tee it thinks is in the killed team.
567 for(int Killed = 0; Killed < MAX_CLIENTS; Killed++)
568 {
569 if(!KilledMask.test(position: Killed))
570 continue;
571 CNetMsg_Sv_KillMsg KillMsg;
572 KillMsg.m_Killer = Killed;
573 KillMsg.m_Victim = Killed;
574 KillMsg.m_Weapon = WEAPON_SELF;
575 KillMsg.m_ModeSpecial = 0;
576 Server()->SendPackMsg(pMsg: &KillMsg, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId: i);
577 }
578 continue;
579 }
580 Server()->SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientId: i);
581 }
582}
583
584bool CGameTeams::TeamFinished(int Team)
585{
586 if(m_aTeamState[Team] != ETeamState::STARTED)
587 {
588 return false;
589 }
590 for(int i = 0; i < MAX_CLIENTS; ++i)
591 if(m_Core.Team(ClientId: i) == Team && !m_aTeeFinished[i])
592 return false;
593 return true;
594}
595
596CClientMask CGameTeams::TeamMask(int Team, int ExceptId, int Asker, int VersionFlags)
597{
598 if(Team == TEAM_SUPER)
599 {
600 if(ExceptId == -1)
601 return CClientMask().set();
602 return CClientMask().set().reset(pos: ExceptId);
603 }
604
605 CPlayer *pAsker = GetPlayer(ClientId: Asker);
606 CInteractions Interact;
607 Interact.Init(OwnerId: Asker, UniqueOwnerId: pAsker ? pAsker->GetUniqueCid() : 0);
608 Interact.FillOwnerConnected(
609 OwnerAlive: pAsker && pAsker->GetCharacter() && pAsker->GetCharacter()->IsAlive(),
610 DDRaceTeam: m_Core.Team(ClientId: Asker),
611 Solo: m_Core.GetSolo(ClientId: Asker),
612 NoHitOthers: false,
613 NoHitSelf: false); // TODO: these false values make little sense
614
615 CClientMask Mask;
616 for(int i = 0; i < MAX_CLIENTS; ++i)
617 {
618 if(i == ExceptId)
619 continue; // Explicitly excluded
620 if(!GetPlayer(ClientId: i))
621 continue; // Player doesn't exist
622 if(!((Server()->IsSixup(ClientId: i) && (VersionFlags & CGameContext::FLAG_SIXUP)) ||
623 (!Server()->IsSixup(ClientId: i) && (VersionFlags & CGameContext::FLAG_SIX))))
624 continue;
625 if(!Interact.CanSee(pGameServer: GameServer(), ClientId: i))
626 continue;
627
628 Mask.set(pos: i);
629 }
630 return Mask;
631}
632
633void CGameTeams::SendTeamsState(int ClientId)
634{
635 if(g_Config.m_SvTeam == SV_TEAM_FORCED_SOLO)
636 return;
637
638 if(!m_pGameContext->m_apPlayers[ClientId])
639 return;
640
641 CMsgPacker Msg(NETMSGTYPE_SV_TEAMSSTATE);
642 CMsgPacker MsgLegacy(NETMSGTYPE_SV_TEAMSSTATELEGACY);
643
644 bool PlayerMappingRequired = !Server()->ClientSupportsServerMaxClients(ClientId);
645
646 for(unsigned i = 0; i < MAX_CLIENTS; i++)
647 {
648 if(PlayerMappingRequired)
649 {
650 if(i >= (unsigned)Server()->GetMaxClients(ClientId))
651 break;
652
653 // see others selector
654 CPlayerMapping::ESeeOthersInd Indicator = GameServer()->m_PlayerMapping.SeeOthersInd(ClientId, MapId: i);
655 if(Indicator != CPlayerMapping::ESeeOthersInd::NONE)
656 {
657 // Team colors (49 and 28) are random and used for see-others feature (+spectate) to cycle the player map
658 int Team = -1;
659 if(Indicator == CPlayerMapping::ESeeOthersInd::BUTTON)
660 Team = 49;
661 else if(Indicator == CPlayerMapping::ESeeOthersInd::PLAYER)
662 Team = 28;
663
664 if(Team != -1)
665 {
666 Msg.AddInt(i: Team);
667 MsgLegacy.AddInt(i: Team);
668 continue;
669 }
670 }
671 }
672
673 int Team = 0;
674 int TranslatedId = i;
675 if(Server()->ReverseTranslate(Target&: TranslatedId, ClientId))
676 {
677 // TeamForClient is also used for the switch state snap and Sv_KillMsgTeam, which have to agree with the teams state
678 Team = TeamForClient(Team: m_Core.Team(ClientId: TranslatedId), ClientId);
679 }
680 Msg.AddInt(i: Team);
681 MsgLegacy.AddInt(i: Team);
682 }
683
684 int ClientVersion = GameServer()->GetClientVersion(ClientId);
685 Server()->SendMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId);
686 if(!Server()->IsSixup(ClientId) && VERSION_DDRACE < ClientVersion && ClientVersion < VERSION_DDNET_MSG_LEGACY)
687 {
688 Server()->SendMsg(pMsg: &MsgLegacy, Flags: MSGFLAG_VITAL, ClientId);
689 }
690}
691
692void CGameTeams::UpdateLegacyTeamMap()
693{
694 // Clients before VERSION_DDNET_128_TEAMS only know team numbers up to LEGACY_TEAM_SUPER. Only whether
695 // two team numbers are equal matters to a client, so the teams that such a client cannot represent are
696 // renumbered into the team numbers that are currently unused. This keeps collision and hook prediction
697 // correct, at the cost of showing a different team number than the one the player joined.
698 bool aTeamOccupied[NUM_DDRACE_TEAMS] = {};
699 for(int i = 0; i < MAX_CLIENTS; i++)
700 aTeamOccupied[m_Core.Team(ClientId: i)] = true;
701
702 // teams that the client can represent keep their own number
703 for(int Team = TEAM_FLOCK; Team < LEGACY_TEAM_SUPER; Team++)
704 m_aLegacyTeamMap[Team] = Team;
705 for(int Team = LEGACY_TEAM_SUPER; Team < TEAM_SUPER; Team++)
706 m_aLegacyTeamMap[Team] = TEAM_FLOCK;
707 m_aLegacyTeamMap[TEAM_SUPER] = LEGACY_TEAM_SUPER;
708
709 // the teams that are left get the numbers that no team is currently using
710 int NextNumber = TEAM_FLOCK + 1;
711 for(int Team = LEGACY_TEAM_SUPER; Team < TEAM_SUPER; Team++)
712 {
713 if(!aTeamOccupied[Team])
714 continue;
715
716 while(NextNumber < LEGACY_TEAM_SUPER && aTeamOccupied[NextNumber])
717 NextNumber++;
718 if(NextNumber == LEGACY_TEAM_SUPER)
719 break; // more teams than the client can represent, the rest stays TEAM_FLOCK
720
721 m_aLegacyTeamMap[Team] = NextNumber;
722 NextNumber++;
723 }
724}
725
726int CGameTeams::TeamForClient(int Team, int ClientId) const
727{
728 if(ClientSupportsServerNumTeams(ClientId))
729 return Team;
730 // If the team's slots are not reserved, dont highlight it. Causes mismatch between dummy and main when playermapping is active.
731 if(!Server()->ClientSupportsServerMaxClients(ClientId) && !GameServer()->m_PlayerMapping.ReserveTeamSlots(DDTeam: Team, ClientId))
732 return TEAM_FLOCK;
733 return m_aLegacyTeamMap[Team];
734}
735
736bool CGameTeams::ClientSupportsServerNumTeams(int ClientId) const
737{
738 const int ClientVersion = GameServer()->GetClientVersion(ClientId);
739 return ClientVersion >= VERSION_DDNET_128_TEAMS;
740}
741
742ERaceState CGameTeams::GetDDRaceState(const CPlayer *Player) const
743{
744 if(!Player)
745 return ERaceState::NONE;
746
747 const CCharacter *pChar = Player->GetCharacter();
748 if(pChar)
749 return pChar->m_DDRaceState;
750 return ERaceState::NONE;
751}
752
753void CGameTeams::SetDDRaceState(CPlayer *Player, ERaceState DDRaceState)
754{
755 if(!Player)
756 return;
757
758 CCharacter *pChar = Player->GetCharacter();
759 if(pChar)
760 pChar->m_DDRaceState = DDRaceState;
761}
762
763int CGameTeams::GetStartTime(CPlayer *Player)
764{
765 if(!Player)
766 return 0;
767
768 CCharacter *pChar = Player->GetCharacter();
769 if(pChar)
770 return pChar->m_StartTime;
771 return 0;
772}
773
774void CGameTeams::SetStartTime(CPlayer *Player, int StartTime)
775{
776 if(!Player)
777 return;
778
779 CCharacter *pChar = Player->GetCharacter();
780 if(pChar)
781 pChar->m_StartTime = StartTime;
782}
783
784void CGameTeams::SetLastTimeCp(CPlayer *Player, int LastTimeCp)
785{
786 if(!Player)
787 return;
788
789 CCharacter *pChar = Player->GetCharacter();
790 if(pChar)
791 pChar->m_LastTimeCp = LastTimeCp;
792}
793
794float *CGameTeams::GetCurrentTimeCp(CPlayer *Player)
795{
796 if(!Player)
797 return nullptr;
798
799 CCharacter *pChar = Player->GetCharacter();
800 if(pChar)
801 return pChar->m_aCurrentTimeCp;
802 return nullptr;
803}
804
805void CGameTeams::OnTeamFinish(int Team, CPlayer **Players, unsigned int Size, int TimeTicks, const char *pTimestamp)
806{
807 int aPlayerCids[MAX_CLIENTS];
808
809 for(unsigned int i = 0; i < Size; i++)
810 {
811 aPlayerCids[i] = Players[i]->GetCid();
812
813 if(g_Config.m_SvRejoinTeam0 && g_Config.m_SvTeam != SV_TEAM_FORCED_SOLO && (!IsValidTeamNumber(Team: m_Core.Team(ClientId: Players[i]->GetCid())) || !m_aTeamLocked[m_Core.Team(ClientId: Players[i]->GetCid())]))
814 {
815 SetForceCharacterTeam(ClientId: Players[i]->GetCid(), Team: TEAM_FLOCK);
816 char aBuf[512];
817 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "'%s' joined team 0",
818 GameServer()->Server()->ClientName(ClientId: Players[i]->GetCid()));
819 GameServer()->SendChat(ClientId: -1, Team: TEAM_ALL, pText: aBuf);
820 }
821 }
822
823 if(Size >= (unsigned int)g_Config.m_SvMinTeamSize)
824 GameServer()->Score()->SaveTeamScore(Team, pClientIds: aPlayerCids, Size, TimeTicks, pTimestamp);
825}
826
827void CGameTeams::OnFinish(CPlayer *pPlayer, int TimeTicks, const char *pTimestamp)
828{
829 if(!pPlayer || !pPlayer->IsPlaying())
830 return;
831
832 float Time = TimeTicks / (float)Server()->TickSpeed();
833
834 // TODO:DDRace:btd: this ugly
835 const int ClientId = pPlayer->GetCid();
836 CPlayerData *pData = GameServer()->Score()->PlayerData(Id: ClientId);
837
838 char aBuf[128];
839 SetLastTimeCp(Player: pPlayer, LastTimeCp: -1);
840 // Note that the "finished in" message is parsed by the client
841 str_format(buffer: aBuf, buffer_size: sizeof(aBuf),
842 format: "%s finished in: %d minute(s) %5.2f second(s)",
843 Server()->ClientName(ClientId), (int)Time / 60,
844 Time - ((int)Time / 60 * 60));
845 if(g_Config.m_SvHideScore)
846 GameServer()->SendChatTarget(To: ClientId, pText: aBuf, VersionFlags: CGameContext::FLAG_SIX);
847 else
848 GameServer()->SendChat(ClientId: -1, Team: TEAM_ALL, pText: aBuf, SpamProtectionClientId: -1., VersionFlags: CGameContext::FLAG_SIX);
849
850 float Diff = absolute(a: Time - pData->m_BestTime.value_or(u: 0.0f));
851
852 if(Time - pData->m_BestTime.value_or(u: 0.0f) < 0)
853 {
854 // new record \o/
855 pData->m_RecordStopTick = Server()->Tick() + Server()->TickSpeed();
856 pData->m_RecordFinishTime = Time;
857
858 if(Diff >= 60)
859 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "New record: %d minute(s) %5.2f second(s) better.",
860 (int)Diff / 60, Diff - ((int)Diff / 60 * 60));
861 else
862 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "New record: %5.2f second(s) better.",
863 Diff);
864 if(g_Config.m_SvHideScore)
865 GameServer()->SendChatTarget(To: ClientId, pText: aBuf, VersionFlags: CGameContext::FLAG_SIX);
866 else
867 GameServer()->SendChat(ClientId: -1, Team: TEAM_ALL, pText: aBuf, SpamProtectionClientId: -1, VersionFlags: CGameContext::FLAG_SIX);
868 }
869 else if(pData->m_BestTime.has_value()) // tee has already finished?
870 {
871 Server()->StopRecord(ClientId);
872
873 if(Diff <= 0.005f)
874 {
875 GameServer()->SendChatTarget(To: ClientId,
876 pText: "You finished with your best time.");
877 }
878 else
879 {
880 if(Diff >= 60)
881 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%d minute(s) %5.2f second(s) worse, better luck next time.",
882 (int)Diff / 60, Diff - ((int)Diff / 60 * 60));
883 else
884 str_format(buffer: aBuf, buffer_size: sizeof(aBuf),
885 format: "%5.2f second(s) worse, better luck next time.",
886 Diff);
887 GameServer()->SendChatTarget(To: ClientId, pText: aBuf, VersionFlags: CGameContext::FLAG_SIX); // this is private, sent only to the tee
888 }
889 }
890 else
891 {
892 pData->m_RecordStopTick = Server()->Tick() + Server()->TickSpeed();
893 pData->m_RecordFinishTime = Time;
894 }
895
896 GameServer()->SendFinish(ClientId, Time, PreviousBestTime: pData->m_BestTime);
897 bool CallSaveScore = g_Config.m_SvSaveWorseScores;
898 bool NeedToSendNewPersonalRecord = false;
899 if(!pData->m_BestTime || Time < pData->m_BestTime)
900 {
901 // update the score
902 pData->Set(Time, aTimeCp: GetCurrentTimeCp(Player: pPlayer));
903 CallSaveScore = true;
904 NeedToSendNewPersonalRecord = true;
905 }
906
907 if(CallSaveScore)
908 if(g_Config.m_SvNamelessScore || !str_startswith(str: Server()->ClientName(ClientId), prefix: "nameless tee"))
909 GameServer()->Score()->SaveScore(ClientId, TimeTicks, pTimestamp,
910 aTimeCp: GetCurrentTimeCp(Player: pPlayer), NotEligible: pPlayer->m_NotEligibleForFinish);
911
912 bool NeedToSendNewServerRecord = false;
913 // update server best time
914 if(!GameServer()->m_pController->m_CurrentRecord.has_value())
915 {
916 GameServer()->Score()->LoadBestTime();
917 }
918 else if(Time < GameServer()->m_pController->m_CurrentRecord)
919 {
920 // check for nameless
921 if(g_Config.m_SvNamelessScore || !str_startswith(str: Server()->ClientName(ClientId), prefix: "nameless tee"))
922 {
923 GameServer()->m_pController->m_CurrentRecord = Time;
924 NeedToSendNewServerRecord = true;
925 }
926 }
927
928 SetDDRaceState(Player: pPlayer, DDRaceState: ERaceState::FINISHED);
929 if(NeedToSendNewServerRecord)
930 {
931 for(int i = 0; i < MAX_CLIENTS; i++)
932 {
933 if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetClientVersion() >= VERSION_DDRACE)
934 {
935 GameServer()->SendRecord(ClientId: i);
936 }
937 }
938 }
939 if(!NeedToSendNewServerRecord && NeedToSendNewPersonalRecord && pPlayer->GetClientVersion() >= VERSION_DDRACE)
940 {
941 GameServer()->SendRecord(ClientId);
942 }
943
944 int TTime = (int)Time;
945 std::optional<float> Score = GameServer()->Score()->PlayerData(Id: ClientId)->m_BestTime;
946 if(!Score.has_value() || TTime < Score.value())
947 {
948 Server()->SetClientScore(ClientId, Score: TTime);
949 }
950
951 // Confetti
952 CCharacter *pChar = pPlayer->GetCharacter();
953 m_pGameContext->CreateFinishEffect(Pos: pChar->m_Pos, Mask: pChar->TeamMask());
954}
955
956CCharacter *CGameTeams::Character(int ClientId)
957{
958 return GameServer()->GetPlayerChar(ClientId);
959}
960
961const CCharacter *CGameTeams::Character(int ClientId) const
962{
963 return GameServer()->GetPlayerChar(ClientId);
964}
965
966CPlayer *CGameTeams::GetPlayer(int ClientId)
967{
968 return GameServer()->m_apPlayers[ClientId];
969}
970
971CGameContext *CGameTeams::GameServer()
972{
973 return m_pGameContext;
974}
975
976const CGameContext *CGameTeams::GameServer() const
977{
978 return m_pGameContext;
979}
980
981IServer *CGameTeams::Server()
982{
983 return m_pGameContext->Server();
984}
985
986const IServer *CGameTeams::Server() const
987{
988 return m_pGameContext->Server();
989}
990
991void CGameTeams::RequestTeamSwap(CPlayer *pPlayer, CPlayer *pTargetPlayer, int Team)
992{
993 if(!pPlayer || !pTargetPlayer)
994 return;
995
996 char aBuf[512];
997 if(pPlayer->m_SwapTargetsClientId == pTargetPlayer->GetCid())
998 {
999 str_format(buffer: aBuf, buffer_size: sizeof(aBuf),
1000 format: "You have already requested to swap with %s.", Server()->ClientName(ClientId: pTargetPlayer->GetCid()));
1001
1002 GameServer()->SendChatTarget(To: pPlayer->GetCid(), pText: aBuf);
1003 return;
1004 }
1005
1006 // Notification for the swap initiator
1007 str_format(buffer: aBuf, buffer_size: sizeof(aBuf),
1008 format: "You have requested to swap with %s. Use /cancelswap to cancel the request.",
1009 Server()->ClientName(ClientId: pTargetPlayer->GetCid()));
1010 GameServer()->SendChatTarget(To: pPlayer->GetCid(), pText: aBuf);
1011
1012 // Notification to the target swap player
1013 str_format(buffer: aBuf, buffer_size: sizeof(aBuf),
1014 format: "%s has requested to swap with you. To complete the swap process please wait %d seconds and then type /swap %s.",
1015 Server()->ClientName(ClientId: pPlayer->GetCid()), g_Config.m_SvSaveSwapGamesDelay, Server()->ClientName(ClientId: pPlayer->GetCid()));
1016 GameServer()->SendChatTarget(To: pTargetPlayer->GetCid(), pText: aBuf);
1017
1018 // Notification for the remaining team
1019 str_format(buffer: aBuf, buffer_size: sizeof(aBuf),
1020 format: "%s has requested to swap with %s.",
1021 Server()->ClientName(ClientId: pPlayer->GetCid()), Server()->ClientName(ClientId: pTargetPlayer->GetCid()));
1022 // Do not send the team notification for team 0
1023 if(Team != 0)
1024 {
1025 for(int i = 0; i < MAX_CLIENTS; i++)
1026 {
1027 if(m_Core.Team(ClientId: i) == Team && i != pTargetPlayer->GetCid() && i != pPlayer->GetCid())
1028 {
1029 GameServer()->SendChatTarget(To: i, pText: aBuf);
1030 }
1031 }
1032 }
1033
1034 pPlayer->m_SwapTargetsClientId = pTargetPlayer->GetCid();
1035 m_aLastSwap[pPlayer->GetCid()] = Server()->Tick();
1036}
1037
1038void CGameTeams::SwapTeamCharacters(CPlayer *pPrimaryPlayer, CPlayer *pTargetPlayer, int Team)
1039{
1040 if(!pPrimaryPlayer || !pTargetPlayer)
1041 return;
1042
1043 char aBuf[128];
1044
1045 int Since = (Server()->Tick() - m_aLastSwap[pTargetPlayer->GetCid()]) / Server()->TickSpeed();
1046 if(Since < g_Config.m_SvSaveSwapGamesDelay)
1047 {
1048 str_format(buffer: aBuf, buffer_size: sizeof(aBuf),
1049 format: "You have to wait %d seconds until you can swap.",
1050 g_Config.m_SvSaveSwapGamesDelay - Since);
1051
1052 GameServer()->SendChatTarget(To: pPrimaryPlayer->GetCid(), pText: aBuf);
1053
1054 return;
1055 }
1056
1057 pPrimaryPlayer->m_SwapTargetsClientId = -1;
1058 pTargetPlayer->m_SwapTargetsClientId = -1;
1059
1060 int TimeoutAfterDelay = g_Config.m_SvSaveSwapGamesDelay + g_Config.m_SvSwapTimeout;
1061 if(Since >= TimeoutAfterDelay)
1062 {
1063 str_format(buffer: aBuf, buffer_size: sizeof(aBuf),
1064 format: "Your swap request timed out %d seconds ago. Use /swap again to re-initiate it.",
1065 Since - g_Config.m_SvSwapTimeout);
1066
1067 GameServer()->SendChatTarget(To: pPrimaryPlayer->GetCid(), pText: aBuf);
1068
1069 return;
1070 }
1071
1072 CSaveTee PrimarySavedTee;
1073 PrimarySavedTee.Save(pChr: pPrimaryPlayer->GetCharacter());
1074
1075 CSaveTee SecondarySavedTee;
1076 SecondarySavedTee.Save(pChr: pTargetPlayer->GetCharacter());
1077
1078 PrimarySavedTee.Load(pChr: pTargetPlayer->GetCharacter());
1079 SecondarySavedTee.Load(pChr: pPrimaryPlayer->GetCharacter());
1080
1081 if(Team >= 1 && !m_aTeamFlock[Team])
1082 {
1083 for(const auto &pPlayer : GameServer()->m_apPlayers)
1084 {
1085 CCharacter *pChar = pPlayer ? pPlayer->GetCharacter() : nullptr;
1086 if(pChar && pChar->Team() == Team && pChar != pPrimaryPlayer->GetCharacter() && pChar != pTargetPlayer->GetCharacter())
1087 pChar->m_StartTime = pPrimaryPlayer->GetCharacter()->m_StartTime;
1088 }
1089 }
1090 std::swap(a&: m_aTeeStarted[pPrimaryPlayer->GetCid()], b&: m_aTeeStarted[pTargetPlayer->GetCid()]);
1091 std::swap(a&: m_aTeeFinished[pPrimaryPlayer->GetCid()], b&: m_aTeeFinished[pTargetPlayer->GetCid()]);
1092 std::swap(a&: pPrimaryPlayer->GetCharacter()->GetLastRescueTeeRef(Mode: RESCUEMODE_AUTO), b&: pTargetPlayer->GetCharacter()->GetLastRescueTeeRef(Mode: RESCUEMODE_AUTO));
1093 std::swap(a&: pPrimaryPlayer->GetCharacter()->GetLastRescueTeeRef(Mode: RESCUEMODE_MANUAL), b&: pTargetPlayer->GetCharacter()->GetLastRescueTeeRef(Mode: RESCUEMODE_MANUAL));
1094
1095 GameServer()->m_World.SwapClients(Client1: pPrimaryPlayer->GetCid(), Client2: pTargetPlayer->GetCid());
1096
1097 if(GameServer()->TeeHistorianActive())
1098 {
1099 GameServer()->TeeHistorian()->RecordPlayerSwap(ClientId1: pPrimaryPlayer->GetCid(), ClientId2: pTargetPlayer->GetCid());
1100 }
1101
1102 str_format(buffer: aBuf, buffer_size: sizeof(aBuf),
1103 format: "%s has swapped with %s.",
1104 Server()->ClientName(ClientId: pPrimaryPlayer->GetCid()), Server()->ClientName(ClientId: pTargetPlayer->GetCid()));
1105
1106 GameServer()->SendChatTeam(Team, pText: aBuf);
1107}
1108
1109void CGameTeams::CancelTeamSwap(CPlayer *pPlayer, int Team)
1110{
1111 if(!pPlayer)
1112 return;
1113
1114 char aBuf[128];
1115
1116 // Notification for the swap initiator
1117 str_format(buffer: aBuf, buffer_size: sizeof(aBuf),
1118 format: "You have canceled swap with %s.",
1119 Server()->ClientName(ClientId: pPlayer->m_SwapTargetsClientId));
1120 GameServer()->SendChatTarget(To: pPlayer->GetCid(), pText: aBuf);
1121
1122 // Notification to the target swap player
1123 str_format(buffer: aBuf, buffer_size: sizeof(aBuf),
1124 format: "%s has canceled swap with you.",
1125 Server()->ClientName(ClientId: pPlayer->GetCid()));
1126 GameServer()->SendChatTarget(To: pPlayer->m_SwapTargetsClientId, pText: aBuf);
1127
1128 // Notification for the remaining team
1129 str_format(buffer: aBuf, buffer_size: sizeof(aBuf),
1130 format: "%s has canceled swap with %s.",
1131 Server()->ClientName(ClientId: pPlayer->GetCid()), Server()->ClientName(ClientId: pPlayer->m_SwapTargetsClientId));
1132 // Do not send the team notification for team 0
1133 if(Team != 0)
1134 {
1135 for(int i = 0; i < MAX_CLIENTS; i++)
1136 {
1137 if(m_Core.Team(ClientId: i) == Team && i != pPlayer->m_SwapTargetsClientId && i != pPlayer->GetCid())
1138 {
1139 GameServer()->SendChatTarget(To: i, pText: aBuf);
1140 }
1141 }
1142 }
1143
1144 pPlayer->m_SwapTargetsClientId = -1;
1145}
1146
1147void CGameTeams::ProcessSaveTeam()
1148{
1149 for(int Team = 0; Team < NUM_DDRACE_TEAMS; Team++)
1150 {
1151 if(m_apSaveTeamResult[Team] == nullptr || !m_apSaveTeamResult[Team]->m_Completed)
1152 continue;
1153
1154 int Size = m_apSaveTeamResult[Team]->m_SavedTeam.GetMembersCount();
1155 int State = -1;
1156
1157 switch(m_apSaveTeamResult[Team]->m_Status)
1158 {
1159 case CScoreSaveResult::SAVE_FALLBACKFILE:
1160 State = SAVESTATE_FALLBACKFILE;
1161 break;
1162 case CScoreSaveResult::SAVE_WARNING:
1163 State = SAVESTATE_WARNING;
1164 break;
1165 case CScoreSaveResult::SAVE_SUCCESS:
1166 State = SAVESTATE_DONE;
1167 break;
1168 case CScoreSaveResult::SAVE_FAILED:
1169 State = SAVESTATE_ERROR;
1170 break;
1171 case CScoreSaveResult::LOAD_FAILED:
1172 case CScoreSaveResult::LOAD_SUCCESS:
1173 State = -1;
1174 break;
1175 }
1176
1177 if(State != -1)
1178 {
1179 GameServer()->SendSaveCode(
1180 Team,
1181 TeamSize: Size,
1182 State,
1183 pError: (State == SAVESTATE_DONE) ? "" : m_apSaveTeamResult[Team]->m_aMessage,
1184 pSaveRequester: m_apSaveTeamResult[Team]->m_aRequestingPlayer,
1185 pServerName: m_apSaveTeamResult[Team]->m_aServer,
1186 pGeneratedCode: m_apSaveTeamResult[Team]->m_aGeneratedCode,
1187 pCode: m_apSaveTeamResult[Team]->m_aCode);
1188 }
1189
1190 if(m_apSaveTeamResult[Team]->m_aBroadcast[0] != '\0')
1191 GameServer()->SendBroadcast(pText: m_apSaveTeamResult[Team]->m_aBroadcast, ClientId: -1);
1192
1193 switch(m_apSaveTeamResult[Team]->m_Status)
1194 {
1195 case CScoreSaveResult::SAVE_FALLBACKFILE:
1196 case CScoreSaveResult::SAVE_WARNING:
1197 case CScoreSaveResult::SAVE_SUCCESS:
1198 {
1199 if(GameServer()->TeeHistorianActive())
1200 {
1201 const char *pSaveState = m_apSaveTeamResult[Team]->m_SavedTeam.GetString();
1202 if(pSaveState)
1203 {
1204 GameServer()->TeeHistorian()->RecordTeamSaveSuccess(
1205 Team,
1206 SaveId: m_apSaveTeamResult[Team]->m_SaveId,
1207 pTeamSave: pSaveState);
1208 }
1209 }
1210 for(int i = 0; i < Size; i++)
1211 {
1212 const CSaveTee &SavedTee = m_apSaveTeamResult[Team]->m_SavedTeam.m_pSavedTees[i];
1213 if(SavedTee.IsHooking())
1214 {
1215 const int ClientId = SavedTee.GetClientId();
1216 if(GameServer()->m_apPlayers[ClientId] != nullptr)
1217 GameServer()->SendChatTarget(To: ClientId, pText: "Start holding the hook before loading the savegame to keep the hook");
1218 }
1219 }
1220 ResetSavedTeam(ClientId: m_apSaveTeamResult[Team]->m_RequestingPlayer, Team);
1221 char aSaveId[UUID_MAXSTRSIZE];
1222 FormatUuid(Uuid: m_apSaveTeamResult[Team]->m_SaveId, pBuffer: aSaveId, BufferLength: UUID_MAXSTRSIZE);
1223 dbg_msg(sys: "save", fmt: "Save successful: %s", aSaveId);
1224 break;
1225 }
1226 case CScoreSaveResult::SAVE_FAILED:
1227 if(GameServer()->TeeHistorianActive())
1228 GameServer()->TeeHistorian()->RecordTeamSaveFailure(Team);
1229 if(TeamSize(Team) > 0)
1230 {
1231 // load weak/strong order to prevent switching weak/strong while saving
1232 m_apSaveTeamResult[Team]->m_SavedTeam.Load(pGameServer: GameServer(), Team, KeepCurrentWeakStrong: false);
1233 }
1234 break;
1235 case CScoreSaveResult::LOAD_SUCCESS:
1236 {
1237 if(GameServer()->TeeHistorianActive())
1238 {
1239 const char *pSaveState = m_apSaveTeamResult[Team]->m_SavedTeam.GetString();
1240 if(pSaveState)
1241 {
1242 GameServer()->TeeHistorian()->RecordTeamLoadSuccess(
1243 Team,
1244 SaveId: m_apSaveTeamResult[Team]->m_SaveId,
1245 pTeamSave: pSaveState);
1246 }
1247 }
1248
1249 bool TeamValid = false;
1250 if(TeamSize(Team) > 0)
1251 {
1252 // keep current weak/strong order as on some maps there is no other way of switching
1253 TeamValid = m_apSaveTeamResult[Team]->m_SavedTeam.Load(pGameServer: GameServer(), Team, KeepCurrentWeakStrong: true);
1254 }
1255
1256 if(!TeamValid)
1257 {
1258 GameServer()->SendChatTeam(Team, pText: "Your team has been killed because it contains an invalid tee state");
1259 KillTeam(Team, NewStrongId: -1);
1260 }
1261
1262 char aSaveId[UUID_MAXSTRSIZE];
1263 FormatUuid(Uuid: m_apSaveTeamResult[Team]->m_SaveId, pBuffer: aSaveId, BufferLength: UUID_MAXSTRSIZE);
1264 dbg_msg(sys: "save", fmt: "Load successful: %s", aSaveId);
1265 break;
1266 }
1267 case CScoreSaveResult::LOAD_FAILED:
1268 if(GameServer()->TeeHistorianActive())
1269 GameServer()->TeeHistorian()->RecordTeamLoadFailure(Team);
1270 if(m_apSaveTeamResult[Team]->m_aMessage[0] != '\0')
1271 GameServer()->SendChatTarget(To: m_apSaveTeamResult[Team]->m_RequestingPlayer, pText: m_apSaveTeamResult[Team]->m_aMessage);
1272 break;
1273 }
1274 m_apSaveTeamResult[Team] = nullptr;
1275 }
1276}
1277
1278void CGameTeams::OnCharacterSpawn(int ClientId)
1279{
1280 m_Core.SetSolo(ClientId, Value: false);
1281 int Team = m_Core.Team(ClientId);
1282
1283 if(GetSaving(TeamId: Team))
1284 return;
1285
1286 if(!IsValidTeamNumber(Team) || Team == TEAM_FLOCK || g_Config.m_SvTeam == SV_TEAM_FORCED_SOLO ||
1287 (!m_aTeamLocked[Team] && !m_aTeamFlock[Team] && m_aTeamState[Team] > ETeamState::OPEN))
1288 {
1289 if(g_Config.m_SvTeam != SV_TEAM_FORCED_SOLO)
1290 SetForceCharacterTeam(ClientId, Team: TEAM_FLOCK);
1291 else
1292 SetForceCharacterTeam(ClientId, Team: ClientId); // initialize team
1293 if(!m_aTeamFlock[Team])
1294 CheckTeamFinished(Team);
1295 }
1296
1297 CPlayer *pPlayer = GetPlayer(ClientId);
1298 if(!g_Config.m_SvPauseable && pPlayer->IsPaused() == -1 * CPlayer::PAUSE_SPEC && !IsPractice(Team: m_Core.Team(ClientId)))
1299 pPlayer->Pause(State: CPlayer::PAUSE_PAUSED, Force: true);
1300}
1301
1302void CGameTeams::OnCharacterDeath(int ClientId, int Weapon)
1303{
1304 m_Core.SetSolo(ClientId, Value: false);
1305
1306 int Team = m_Core.Team(ClientId);
1307 if(GetSaving(TeamId: Team))
1308 return;
1309 bool Locked = TeamLocked(Team) && Weapon != WEAPON_GAME;
1310
1311 if(g_Config.m_SvTeam == SV_TEAM_FORCED_SOLO && Team != TEAM_SUPER)
1312 {
1313 ChangeTeamState(Team, State: ETeamState::OPEN);
1314 if(m_aPractice[Team])
1315 {
1316 if(Weapon != WEAPON_WORLD)
1317 {
1318 ResetRoundState(Team);
1319 }
1320 else
1321 {
1322 GameServer()->SendChatTeam(Team, pText: "You died, but will stay in practice until you use kill.");
1323 }
1324 }
1325 else
1326 {
1327 ResetRoundState(Team);
1328 }
1329 }
1330 else if(Locked)
1331 {
1332 SetForceCharacterTeam(ClientId, Team);
1333
1334 if(GetTeamState(Team) != ETeamState::OPEN && !m_aTeamFlock[m_Core.Team(ClientId)])
1335 {
1336 ChangeTeamState(Team, State: ETeamState::OPEN);
1337
1338 if(!m_pGameContext->PracticeByDefault())
1339 {
1340 if(!g_Config.m_SvPauseable)
1341 {
1342 for(int ClientId1 = 0; ClientId1 < MAX_CLIENTS; ClientId1++)
1343 {
1344 if(ClientId1 != ClientId && m_Core.Team(ClientId: ClientId1) == Team)
1345 {
1346 CPlayer *pPlayer = GameServer()->m_apPlayers[ClientId1];
1347 if(pPlayer && pPlayer->IsPaused() == -1 * CPlayer::PAUSE_SPEC)
1348 pPlayer->Pause(State: CPlayer::PAUSE_PAUSED, Force: true);
1349 }
1350 }
1351 }
1352 m_aPractice[Team] = false;
1353 }
1354
1355 if(TeamSize(Team) > 1)
1356 {
1357 // Disband team if the team has more players than allowed.
1358 if(TeamSize(Team) > g_Config.m_SvMaxTeamSize)
1359 {
1360 GameServer()->SendChatTeam(Team, pText: "This team was disbanded because there are more players than allowed in the team.");
1361 SetTeamLock(Team, Lock: false);
1362 KillTeam(Team, NewStrongId: Weapon == WEAPON_SELF ? ClientId : -1, ExceptId: ClientId);
1363 for(int MemberId = 0; MemberId < MAX_CLIENTS; MemberId++)
1364 {
1365 if(m_Core.Team(ClientId: MemberId) == Team && GameServer()->m_apPlayers[MemberId])
1366 SetForceCharacterTeam(ClientId: MemberId, Team: TEAM_FLOCK);
1367 }
1368 return;
1369 }
1370
1371 KillTeam(Team, NewStrongId: Weapon == WEAPON_SELF ? ClientId : -1, ExceptId: ClientId);
1372
1373 char aBuf[512];
1374 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "Everyone in your locked team was killed because '%s' %s.", Server()->ClientName(ClientId), Weapon == WEAPON_SELF ? "killed" : "died");
1375
1376 GameServer()->SendChatTeam(Team, pText: aBuf);
1377 }
1378 }
1379 }
1380 else
1381 {
1382 if(m_aTeamState[m_Core.Team(ClientId)] == ETeamState::STARTED && !m_aTeeStarted[ClientId] && !m_aTeamFlock[m_Core.Team(ClientId)])
1383 {
1384 char aBuf[128];
1385 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "This team cannot finish anymore because '%s' left the team before hitting the start", Server()->ClientName(ClientId));
1386 GameServer()->SendChatTeam(Team, pText: aBuf);
1387 GameServer()->SendChatTeam(Team, pText: "Enter /practice mode or restart to avoid the entire team being killed in 60 seconds");
1388
1389 m_aTeamUnfinishableKillTick[Team] = Server()->Tick() + 60 * Server()->TickSpeed();
1390 ChangeTeamState(Team, State: ETeamState::STARTED_UNFINISHABLE);
1391 }
1392 SetForceCharacterTeam(ClientId, Team: TEAM_FLOCK);
1393 if(!m_aTeamFlock[m_Core.Team(ClientId)])
1394 CheckTeamFinished(Team);
1395 }
1396}
1397
1398void CGameTeams::SetTeamLock(int Team, bool Lock)
1399{
1400 if(Team != TEAM_FLOCK && IsValidTeamNumber(Team))
1401 m_aTeamLocked[Team] = Lock;
1402}
1403
1404void CGameTeams::SetTeamFlock(int Team, bool Mode)
1405{
1406 if(Team != TEAM_FLOCK && IsValidTeamNumber(Team))
1407 m_aTeamFlock[Team] = Mode;
1408}
1409
1410void CGameTeams::ResetInvited(int Team)
1411{
1412 m_aInvited[Team].reset();
1413}
1414
1415void CGameTeams::SetClientInvited(int Team, int ClientId, bool Invited)
1416{
1417 if(Team != TEAM_FLOCK && IsValidTeamNumber(Team))
1418 {
1419 if(Invited)
1420 m_aInvited[Team].set(pos: ClientId);
1421 else
1422 m_aInvited[Team].reset(pos: ClientId);
1423 }
1424}
1425
1426void CGameTeams::KillCharacterOrTeam(int ClientId, int Team)
1427{
1428 if(g_Config.m_SvSoloServer || !g_Config.m_SvTeam)
1429 {
1430 GameServer()->m_apPlayers[ClientId]->KillCharacter(Weapon: WEAPON_SELF, SendKillMsg: true);
1431 }
1432 else
1433 {
1434 KillTeam(Team, NewStrongId: -1);
1435 }
1436}
1437
1438void CGameTeams::ResetSavedTeam(int ClientId, int Team)
1439{
1440 if(g_Config.m_SvTeam == SV_TEAM_FORCED_SOLO)
1441 {
1442 ChangeTeamState(Team, State: ETeamState::OPEN);
1443 ResetRoundState(Team);
1444 }
1445 else
1446 {
1447 for(int i = 0; i < MAX_CLIENTS; i++)
1448 {
1449 if(m_Core.Team(ClientId: i) == Team && GameServer()->m_apPlayers[i])
1450 {
1451 SetForceCharacterTeam(ClientId: i, Team: TEAM_FLOCK);
1452 }
1453 }
1454 }
1455}
1456
1457std::optional<int> CGameTeams::GetFirstEmptyTeam() const
1458{
1459 for(int i = 1; i < TEAM_SUPER; i++)
1460 if(m_aTeamState[i] == ETeamState::EMPTY)
1461 return i;
1462 return std::nullopt;
1463}
1464
1465bool CGameTeams::TeeStarted(int ClientId) const
1466{
1467 return m_aTeeStarted[ClientId];
1468}
1469
1470bool CGameTeams::TeeFinished(int ClientId) const
1471{
1472 return m_aTeeFinished[ClientId];
1473}
1474
1475ETeamState CGameTeams::GetTeamState(int Team) const
1476{
1477 return m_aTeamState[Team];
1478}
1479
1480bool CGameTeams::TeamLocked(int Team) const
1481{
1482 if(Team == TEAM_FLOCK || !IsValidTeamNumber(Team))
1483 return false;
1484
1485 return m_aTeamLocked[Team];
1486}
1487
1488bool CGameTeams::TeamFlock(int Team) const
1489{
1490 // this is for team0mode, TEAM_FLOCK is handled differently
1491 if(Team == TEAM_FLOCK || !IsValidTeamNumber(Team))
1492 return false;
1493
1494 return m_aTeamFlock[Team];
1495}
1496
1497bool CGameTeams::IsInvited(int Team, int ClientId) const
1498{
1499 return m_aInvited[Team].test(position: ClientId);
1500}
1501
1502bool CGameTeams::IsStarted(int Team) const
1503{
1504 return m_aTeamState[Team] == ETeamState::STARTED;
1505}
1506
1507void CGameTeams::SetStarted(int ClientId, bool Started)
1508{
1509 m_aTeeStarted[ClientId] = Started;
1510}
1511
1512void CGameTeams::SetFinished(int ClientId, bool Finished)
1513{
1514 m_aTeeFinished[ClientId] = Finished;
1515}
1516
1517void CGameTeams::SetSaving(int TeamId, std::shared_ptr<CScoreSaveResult> &SaveResult)
1518{
1519 m_apSaveTeamResult[TeamId] = SaveResult;
1520}
1521
1522bool CGameTeams::GetSaving(int TeamId) const
1523{
1524 if(!IsValidTeamNumber(Team: TeamId))
1525 return false;
1526 if(g_Config.m_SvTeam != SV_TEAM_FORCED_SOLO && TeamId == TEAM_FLOCK)
1527 return false;
1528
1529 return m_apSaveTeamResult[TeamId] != nullptr;
1530}
1531
1532void CGameTeams::SetPractice(int Team, bool Enabled)
1533{
1534 if(!IsValidTeamNumber(Team))
1535 return;
1536 if(g_Config.m_SvTeam != SV_TEAM_FORCED_SOLO && Team == TEAM_FLOCK)
1537 {
1538 // allow to enable practice in team 0, for practice by default
1539 if(!g_Config.m_SvTestingCommands)
1540 return;
1541 }
1542
1543 m_aPractice[Team] = Enabled;
1544}
1545
1546bool CGameTeams::IsPractice(int Team)
1547{
1548 if(!IsValidTeamNumber(Team))
1549 return false;
1550 if(g_Config.m_SvTeam != SV_TEAM_FORCED_SOLO && Team == TEAM_FLOCK)
1551 {
1552 if(GameServer()->PracticeByDefault())
1553 return true;
1554
1555 return false;
1556 }
1557
1558 return m_aPractice[Team];
1559}
1560
1561bool CGameTeams::IsValidTeamNumber(int Team) const
1562{
1563 return Team >= TEAM_FLOCK && Team < NUM_DDRACE_TEAMS - 1; // no TEAM_SUPER
1564}
1565