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
4#include "gameclient.h"
5
6#include "components/background.h"
7#include "components/binds.h"
8#include "components/broadcast.h"
9#include "components/camera.h"
10#include "components/chat.h"
11#include "components/console.h"
12#include "components/controls.h"
13#include "components/countryflags.h"
14#include "components/damageind.h"
15#include "components/debughud.h"
16#include "components/effects.h"
17#include "components/emoticon.h"
18#include "components/freezebars.h"
19#include "components/ghost.h"
20#include "components/hud.h"
21#include "components/infomessages.h"
22#include "components/items.h"
23#include "components/mapimages.h"
24#include "components/maplayers.h"
25#include "components/mapsounds.h"
26#include "components/menu_background.h"
27#include "components/menus.h"
28#include "components/motd.h"
29#include "components/nameplates.h"
30#include "components/particles.h"
31#include "components/players.h"
32#include "components/race_demo.h"
33#include "components/scoreboard.h"
34#include "components/skins.h"
35#include "components/skins7.h"
36#include "components/sounds.h"
37#include "components/spectator.h"
38#include "components/statboard.h"
39#include "components/voting.h"
40#include "lineinput.h"
41#include "prediction/entities/character.h"
42#include "prediction/entities/projectile.h"
43#include "race.h"
44#include "render.h"
45
46#include <base/dbg.h>
47#include <base/io.h>
48#include <base/log.h>
49#include <base/math.h>
50#include <base/mem.h>
51#include <base/str.h>
52#include <base/time.h>
53#include <base/vmath.h>
54
55#include <engine/client/checksum.h>
56#include <engine/client/enums.h>
57#include <engine/demo.h>
58#include <engine/discord.h>
59#include <engine/editor.h>
60#include <engine/engine.h>
61#include <engine/favorites.h>
62#include <engine/friends.h>
63#include <engine/graphics.h>
64#include <engine/map.h>
65#include <engine/serverbrowser.h>
66#include <engine/shared/config.h>
67#include <engine/shared/csv.h>
68#include <engine/sound.h>
69#include <engine/storage.h>
70#include <engine/textrender.h>
71#include <engine/updater.h>
72
73#include <generated/client_data.h>
74#include <generated/client_data7.h>
75#include <generated/protocol.h>
76#include <generated/protocol7.h>
77#include <generated/protocolglue.h>
78
79#include <game/client/projectile_data.h>
80#include <game/localization.h>
81#include <game/mapitems.h>
82#include <game/teamscore.h>
83#include <game/version.h>
84
85#include <chrono>
86#include <limits>
87
88using namespace std::chrono_literals;
89
90const char *CGameClient::Version() const { return GAME_VERSION; }
91const char *CGameClient::NetVersion() const { return GAME_NETVERSION; }
92const char *CGameClient::NetVersion7() const { return GAME_NETVERSION7; }
93int CGameClient::DDNetVersion() const { return DDNET_VERSION_NUMBER; }
94const char *CGameClient::DDNetVersionStr() const { return m_aDDNetVersionStr; }
95int CGameClient::ClientVersion7() const { return CLIENT_VERSION7; }
96const char *CGameClient::GetItemName(int Type) const { return m_NetObjHandler.GetObjName(Type); }
97
98void CGameClient::OnConsoleInit()
99{
100 m_pEngine = Kernel()->RequestInterface<IEngine>();
101 m_pClient = Kernel()->RequestInterface<IClient>();
102 m_pTextRender = Kernel()->RequestInterface<ITextRender>();
103 m_pSound = Kernel()->RequestInterface<ISound>();
104 m_pConfigManager = Kernel()->RequestInterface<IConfigManager>();
105 m_pConfig = m_pConfigManager->Values();
106 m_pInput = Kernel()->RequestInterface<IInput>();
107 m_pConsole = Kernel()->RequestInterface<IConsole>();
108 m_pStorage = Kernel()->RequestInterface<IStorage>();
109 m_pDemoPlayer = Kernel()->RequestInterface<IDemoPlayer>();
110 m_pServerBrowser = Kernel()->RequestInterface<IServerBrowser>();
111 m_pEditor = Kernel()->RequestInterface<IEditor>();
112 m_pFavorites = Kernel()->RequestInterface<IFavorites>();
113 m_pFriends = Kernel()->RequestInterface<IFriends>();
114 m_pFoes = Client()->Foes();
115 m_pDiscord = Kernel()->RequestInterface<IDiscord>();
116#if defined(CONF_AUTOUPDATE)
117 m_pUpdater = Kernel()->RequestInterface<IUpdater>();
118#endif
119 m_pHttp = Kernel()->RequestInterface<IHttp>();
120 m_pMap = CreateMap();
121
122 // make a list of all the systems, make sure to add them in the correct render order
123 m_vpAll.insert(position: m_vpAll.end(), l: {&m_Skins,
124 &m_Skins7,
125 &m_CountryFlags,
126 &m_MapImages,
127 &m_Effects, // doesn't render anything, just updates effects
128 &m_Binds,
129 &m_Binds.m_SpecialBinds,
130 &m_Controls,
131 &m_Camera,
132 &m_MultiView,
133 &m_Sounds,
134 &m_Voting,
135 &m_Particles, // doesn't render anything, just updates all the particles
136 &m_RaceDemo,
137 &m_MapSounds,
138 &m_Censor,
139 &m_Background, // render instead of m_MapLayersBackground when g_Config.m_ClOverlayEntities == 100
140 &m_MapLayersBackground, // first to render
141 &m_Particles.m_RenderTrail,
142 &m_Particles.m_RenderTrailExtra,
143 &m_Items,
144 &m_Ghost,
145 &m_Players,
146 &m_MapLayersForeground,
147 &m_Particles.m_RenderExplosions,
148 &m_NamePlates,
149 &m_Particles.m_RenderExtra,
150 &m_Particles.m_RenderGeneral,
151 &m_FreezeBars,
152 &m_DamageInd,
153 &m_Hud,
154 &m_Spectator,
155 &m_Emoticon,
156 &m_InfoMessages,
157 &m_Chat,
158 &m_Broadcast,
159 &m_ImportantAlert,
160 &m_DebugHud,
161 &m_TouchControls,
162 &m_Scoreboard,
163 &m_Statboard,
164 &m_Motd,
165 &m_Menus,
166 &m_KeyBinder,
167 &m_GameConsole,
168 &m_MenuBackground});
169
170 // build the input stack
171 m_vpInput.insert(position: m_vpInput.end(), l: {&m_KeyBinder, // this will take over all input when we want to bind a key
172 &m_Binds.m_SpecialBinds,
173 &m_GameConsole,
174 &m_Chat, // chat has higher prio, due to that you can quit it by pressing esc
175 &m_Scoreboard,
176 &m_Motd, // for pressing esc to remove it
177 &m_Spectator,
178 &m_Emoticon,
179 &m_ImportantAlert,
180 &m_Menus,
181 &m_Controls,
182 &m_TouchControls,
183 &m_Binds});
184
185 // initialize client data
186 for(int ClientId = 0; ClientId < MAX_CLIENTS; ClientId++)
187 {
188 CClientData &Client = m_aClients[ClientId];
189 Client.m_pGameClient = this;
190 Client.m_ClientId = ClientId;
191 }
192
193 // add basic console commands
194 Console()->Register(pName: "team", pParams: "i[team-id]", Flags: CFGFLAG_CLIENT, pfnFunc: ConTeam, pUser: this, pHelp: "Switch team");
195 Console()->Register(pName: "kill", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: ConKill, pUser: this, pHelp: "Kill yourself to restart");
196 Console()->Register(pName: "ready_change", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: ConReadyChange7, pUser: this, pHelp: "Change ready state (0.7 only)");
197
198 // register game commands to allow the client prediction to load settings from the map
199 Console()->Register(pName: "tune", pParams: "s[tuning] ?f[value]", Flags: CFGFLAG_GAME, pfnFunc: ConTuneParam, pUser: this, pHelp: "Tune variable to value");
200 Console()->Register(pName: "tune_zone", pParams: "i[zone] s[tuning] f[value]", Flags: CFGFLAG_GAME, pfnFunc: ConTuneZone, pUser: this, pHelp: "Tune in zone a variable to value");
201 Console()->Register(pName: "mapbug", pParams: "s[mapbug]", Flags: CFGFLAG_GAME, pfnFunc: ConMapbug, pUser: this, pHelp: "Enable map compatibility mode using the specified bug (example: grenade-doubleexplosion@ddnet.tw)");
202
203 for(auto &pComponent : m_vpAll)
204 pComponent->OnInterfacesInit(pClient: this);
205
206 m_LocalServer.OnInterfacesInit(pClient: this);
207
208 // let all the other components register their console commands
209 for(auto &pComponent : m_vpAll)
210 pComponent->OnConsoleInit();
211
212 Console()->Chain(pName: "cl_languagefile", pfnChainFunc: ConchainLanguageUpdate, pUser: this);
213
214 Console()->Chain(pName: "player_name", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
215 Console()->Chain(pName: "player_clan", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
216 Console()->Chain(pName: "player_country", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
217 Console()->Chain(pName: "player_use_custom_color", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
218 Console()->Chain(pName: "player_color_body", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
219 Console()->Chain(pName: "player_color_feet", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
220 Console()->Chain(pName: "player_skin", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
221
222 Console()->Chain(pName: "player7_skin", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
223 Console()->Chain(pName: "player7_skin_body", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
224 Console()->Chain(pName: "player7_skin_marking", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
225 Console()->Chain(pName: "player7_skin_decoration", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
226 Console()->Chain(pName: "player7_skin_hands", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
227 Console()->Chain(pName: "player7_skin_feet", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
228 Console()->Chain(pName: "player7_skin_eyes", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
229 Console()->Chain(pName: "player7_color_body", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
230 Console()->Chain(pName: "player7_color_marking", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
231 Console()->Chain(pName: "player7_color_decoration", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
232 Console()->Chain(pName: "player7_color_hands", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
233 Console()->Chain(pName: "player7_color_feet", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
234 Console()->Chain(pName: "player7_color_eyes", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
235 Console()->Chain(pName: "player7_use_custom_color_body", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
236 Console()->Chain(pName: "player7_use_custom_color_marking", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
237 Console()->Chain(pName: "player7_use_custom_color_decoration", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
238 Console()->Chain(pName: "player7_use_custom_color_hands", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
239 Console()->Chain(pName: "player7_use_custom_color_feet", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
240 Console()->Chain(pName: "player7_use_custom_color_eyes", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
241
242 Console()->Chain(pName: "dummy_name", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
243 Console()->Chain(pName: "dummy_clan", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
244 Console()->Chain(pName: "dummy_country", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
245 Console()->Chain(pName: "dummy_use_custom_color", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
246 Console()->Chain(pName: "dummy_color_body", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
247 Console()->Chain(pName: "dummy_color_feet", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
248 Console()->Chain(pName: "dummy_skin", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
249
250 Console()->Chain(pName: "dummy7_skin", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
251 Console()->Chain(pName: "dummy7_skin_body", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
252 Console()->Chain(pName: "dummy7_skin_marking", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
253 Console()->Chain(pName: "dummy7_skin_decoration", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
254 Console()->Chain(pName: "dummy7_skin_hands", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
255 Console()->Chain(pName: "dummy7_skin_feet", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
256 Console()->Chain(pName: "dummy7_skin_eyes", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
257 Console()->Chain(pName: "dummy7_color_body", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
258 Console()->Chain(pName: "dummy7_color_marking", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
259 Console()->Chain(pName: "dummy7_color_decoration", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
260 Console()->Chain(pName: "dummy7_color_hands", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
261 Console()->Chain(pName: "dummy7_color_feet", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
262 Console()->Chain(pName: "dummy7_color_eyes", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
263 Console()->Chain(pName: "dummy7_use_custom_color_body", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
264 Console()->Chain(pName: "dummy7_use_custom_color_marking", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
265 Console()->Chain(pName: "dummy7_use_custom_color_decoration", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
266 Console()->Chain(pName: "dummy7_use_custom_color_hands", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
267 Console()->Chain(pName: "dummy7_use_custom_color_feet", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
268 Console()->Chain(pName: "dummy7_use_custom_color_eyes", pfnChainFunc: ConchainSpecialDummyInfoupdate, pUser: this);
269
270 Console()->Chain(pName: "cl_skin_download_url", pfnChainFunc: ConchainRefreshSkins, pUser: this);
271 Console()->Chain(pName: "cl_skin_community_download_url", pfnChainFunc: ConchainRefreshSkins, pUser: this);
272 Console()->Chain(pName: "cl_skin_prefix", pfnChainFunc: ConchainRefreshSkins, pUser: this);
273 Console()->Chain(pName: "cl_download_skins", pfnChainFunc: ConchainRefreshSkins, pUser: this);
274 Console()->Chain(pName: "cl_download_community_skins", pfnChainFunc: ConchainRefreshSkins, pUser: this);
275 Console()->Chain(pName: "cl_vanilla_skins_only", pfnChainFunc: ConchainRefreshSkins, pUser: this);
276 Console()->Chain(pName: "events", pfnChainFunc: ConchainRefreshEventSkins, pUser: this);
277
278 Console()->Chain(pName: "cl_dummy", pfnChainFunc: ConchainSpecialDummy, pUser: this);
279
280 Console()->Chain(pName: "cl_menu_map", pfnChainFunc: ConchainMenuMap, pUser: this);
281}
282
283void CGameClient::InitializeLanguage()
284{
285 // set the language
286 g_Localization.LoadIndexfile(pStorage: Storage(), pConsole: Console());
287 if(g_Config.m_ClShowWelcome)
288 g_Localization.SelectDefaultLanguage(pConsole: Console(), pFilename: g_Config.m_ClLanguagefile, Length: sizeof(g_Config.m_ClLanguagefile));
289 g_Localization.Load(pFilename: g_Config.m_ClLanguagefile, pStorage: Storage(), pConsole: Console());
290}
291
292void CGameClient::ForceUpdateConsoleRemoteCompletionSuggestions()
293{
294 m_GameConsole.ForceUpdateRemoteCompletionSuggestions();
295}
296
297void CGameClient::OnInit()
298{
299 const int64_t OnInitStart = time_get();
300
301 Client()->SetLoadingCallback([this](IClient::ELoadingCallbackDetail Detail) {
302 const char *pTitle;
303 if(Detail == IClient::ELoadingCallbackDetail::DEMO || DemoPlayer()->IsPlaying())
304 {
305 pTitle = Localize(pStr: "Preparing demo playback");
306 }
307 else
308 {
309 pTitle = Localize(pStr: "Connected");
310 }
311
312 const char *pMessage;
313 switch(Detail)
314 {
315 case IClient::ELoadingCallbackDetail::MAP:
316 pMessage = Localize(pStr: "Loading map file from storage");
317 break;
318 case IClient::ELoadingCallbackDetail::DEMO:
319 pMessage = Localize(pStr: "Loading demo file from storage");
320 break;
321 default:
322 dbg_assert_failed("Invalid callback loading detail");
323 }
324 m_Menus.RenderLoading(pCaption: pTitle, pContent: pMessage, IncreaseCounter: 0);
325 });
326
327 m_pGraphics = Kernel()->RequestInterface<IGraphics>();
328
329 // propagate pointers
330 m_UI.Init(pKernel: Kernel());
331 m_UI.SetOnBackButtonPressedCallback([this]() {
332 m_BackButtonHandledKeyBind = m_KeyBinder.HasPendingKeyReader();
333 if(m_BackButtonHandledKeyBind)
334 m_KeyBinder.AbortPendingKey();
335 });
336 m_UI.SetDispatchInputCallback([this](const IInput::CEvent &Event) {
337 if(m_BackButtonHandledKeyBind)
338 {
339 if(Event.m_Flags & IInput::FLAG_RELEASE)
340 m_BackButtonHandledKeyBind = false;
341 return;
342 }
343 OnInput(Event);
344 });
345 m_RenderTools.Init(pGraphics: Graphics(), pTextRender: TextRender());
346 m_RenderMap.Init(pGraphics: Graphics(), pTextRender: TextRender());
347
348 if(GIT_SHORTREV_HASH)
349 {
350 str_format(buffer: m_aDDNetVersionStr, buffer_size: sizeof(m_aDDNetVersionStr), format: "%s %s (%s)", GAME_NAME, GAME_RELEASE_VERSION, GIT_SHORTREV_HASH);
351 }
352 else
353 {
354 str_format(buffer: m_aDDNetVersionStr, buffer_size: sizeof(m_aDDNetVersionStr), format: "%s %s", GAME_NAME, GAME_RELEASE_VERSION);
355 }
356
357 // TODO: this should be different
358 // setup item sizes
359 for(int i = 0; i < NUM_NETOBJTYPES; i++)
360 Client()->SnapSetStaticsize(ItemType: i, Size: m_NetObjHandler.GetObjSize(Type: i));
361 // HACK: only set static size for items, which were available in the first 0.7 release
362 // so new items don't break the snapshot delta
363 static const int OLD_NUM_NETOBJTYPES = 23;
364 for(int i = 0; i < OLD_NUM_NETOBJTYPES; i++)
365 Client()->SnapSetStaticsize7(ItemType: i, Size: m_NetObjHandler7.GetObjSize(Type: i));
366
367 if(!TextRender()->LoadFonts())
368 {
369 Client()->AddWarning(Warning: SWarning(Localize(pStr: "Some fonts could not be loaded. Check the local console for details.")));
370 }
371 TextRender()->SetFontLanguageVariant(g_Config.m_ClLanguagefile);
372
373 // update and swap after font loading, they are quite huge
374 Client()->UpdateAndSwap();
375
376 const char *pLoadingDDNetCaption = Localize(pStr: "Loading DDNet Client");
377 const char *pLoadingMessageComponents = Localize(pStr: "Initializing components");
378 const char *pLoadingMessageComponentsSpecial = Localize(pStr: "Why are you slowmo replaying to read this?");
379 char aLoadingMessage[256];
380
381 // init all components
382 int SkippedComps = 1;
383 int CompCounter = 1;
384 const int NumComponents = ComponentCount();
385 for(int i = NumComponents - 1; i >= 0; --i)
386 {
387 m_vpAll[i]->OnInit();
388 // try to render a frame after each component, also flushes GPU uploads
389 if(m_Menus.IsInit())
390 {
391 str_format(buffer: aLoadingMessage, buffer_size: std::size(aLoadingMessage), format: "%s [%d/%d]", CompCounter == NumComponents ? pLoadingMessageComponentsSpecial : pLoadingMessageComponents, CompCounter, NumComponents);
392 m_Menus.RenderLoading(pCaption: pLoadingDDNetCaption, pContent: aLoadingMessage, IncreaseCounter: SkippedComps);
393 SkippedComps = 1;
394 }
395 else
396 {
397 ++SkippedComps;
398 }
399 ++CompCounter;
400 }
401
402 // setup load amount, load textures
403 const char *pLoadingMessageAssets = Localize(pStr: "Initializing assets");
404 for(int i = 0; i < g_pData->m_NumImages; i++)
405 {
406 if(i == IMAGE_GAME)
407 LoadGameSkin(pPath: g_Config.m_ClAssetGame);
408 else if(i == IMAGE_EMOTICONS)
409 LoadEmoticonsSkin(pPath: g_Config.m_ClAssetEmoticons);
410 else if(i == IMAGE_PARTICLES)
411 LoadParticlesSkin(pPath: g_Config.m_ClAssetParticles);
412 else if(i == IMAGE_HUD)
413 LoadHudSkin(pPath: g_Config.m_ClAssetHud);
414 else if(i == IMAGE_EXTRAS)
415 LoadExtrasSkin(pPath: g_Config.m_ClAssetExtras);
416 else if(g_pData->m_aImages[i].m_pFilename[0] == '\0') // handle special null image without filename
417 g_pData->m_aImages[i].m_Id = IGraphics::CTextureHandle();
418 else
419 g_pData->m_aImages[i].m_Id = Graphics()->LoadTexture(pFilename: g_pData->m_aImages[i].m_pFilename, StorageType: IStorage::TYPE_ALL);
420 m_Menus.RenderLoading(pCaption: pLoadingDDNetCaption, pContent: pLoadingMessageAssets, IncreaseCounter: 1);
421 }
422
423 m_GameWorld.Init(pCollision: Collision(), pTuningList: m_aTuningList, pMapBugs: &m_MapBugs);
424 OnReset();
425
426 // Set free binds to DDRace binds if it's active
427 m_Binds.SetDDRaceBinds(true);
428
429 // Aggressively try to grab window again since some Windows users report
430 // window not being focused after starting client.
431 Graphics()->SetWindowGrab(true);
432
433 CChecksumData *pChecksum = Client()->ChecksumData();
434 pChecksum->m_SizeofGameClient = sizeof(*this);
435 pChecksum->m_NumComponents = m_vpAll.size();
436 for(size_t i = 0; i < m_vpAll.size(); i++)
437 {
438 if(i >= std::size(pChecksum->m_aComponentsChecksum))
439 {
440 break;
441 }
442 int Size = m_vpAll[i]->Sizeof();
443 pChecksum->m_aComponentsChecksum[i] = Size;
444 }
445
446 m_Menus.FinishLoading();
447 log_trace("gameclient", "initialization finished after %.2fms", (time_get() - OnInitStart) * 1000.0f / (float)time_freq());
448}
449
450void CGameClient::OnUpdate()
451{
452 HandleLanguageChanged();
453
454 CUIElementBase::Init(pUI: Ui()); // update static pointer because game and editor use separate UI
455
456 // handle mouse movement
457 float x = 0.0f, y = 0.0f;
458 IInput::ECursorType CursorType = Input()->CursorRelative(pX: &x, pY: &y);
459 if(CursorType != IInput::CURSOR_NONE)
460 {
461 for(auto &pComponent : m_vpInput)
462 {
463 if(pComponent->OnCursorMove(x, y, CursorType))
464 break;
465 }
466 }
467
468 // handle touch events
469 std::vector<IInput::CTouchFingerState> vTouchFingerStates = Input()->TouchFingerStates();
470 for(auto &pComponent : m_vpInput)
471 {
472 if(pComponent->OnTouchState(vTouchFingerStates))
473 {
474 Input()->ClearTouchDeltas();
475 }
476 }
477
478 std::fill(first: std::begin(arr&: m_Controls.m_aMouseOnAction), last: std::end(arr&: m_Controls.m_aMouseOnAction), value: false);
479
480 // handle key presses
481 Input()->ConsumeEvents(Consumer: [&](const IInput::CEvent &Event) {
482 OnInput(Event);
483 });
484
485 if(g_Config.m_ClSubTickAiming)
486 {
487 for(int Dummy = 0; Dummy < NUM_DUMMIES; Dummy++)
488 {
489 if(m_Controls.m_aMouseOnAction[Dummy])
490 m_Controls.m_aMousePosOnAction[Dummy] = m_Controls.m_aMousePos[Dummy];
491 }
492 }
493
494 for(auto &pComponent : m_vpAll)
495 {
496 pComponent->OnUpdate();
497 }
498
499 m_LocalServer.Update();
500}
501
502void CGameClient::OnInput(const IInput::CEvent &Event)
503{
504 for(auto &pComponent : m_vpInput)
505 {
506 // Events with flag `FLAG_RELEASE` must always be forwarded to all components so keys being
507 // released can be handled in all components also after some components have been disabled.
508 if(pComponent->OnInput(Event) && (Event.m_Flags & ~IInput::FLAG_RELEASE) != 0)
509 break;
510 }
511}
512
513void CGameClient::OnDummySwap()
514{
515 if(g_Config.m_ClDummyResetOnSwitch)
516 {
517 int PlayerOrDummy = (g_Config.m_ClDummyResetOnSwitch == 2) ? g_Config.m_ClDummy : (!g_Config.m_ClDummy);
518 m_Controls.ResetInput(Dummy: PlayerOrDummy);
519 m_Controls.m_aInputData[PlayerOrDummy].m_Hook = 0;
520 }
521 const int PrevDummyFire = m_DummyInput.m_Fire;
522 m_DummyInput = m_Controls.m_aInputData[!g_Config.m_ClDummy];
523 m_Controls.m_aInputData[g_Config.m_ClDummy].m_Fire = PrevDummyFire;
524 m_IsDummySwapping = 1;
525}
526
527int CGameClient::OnSnapInput(int *pData, bool Dummy, bool Force)
528{
529 if(!Dummy)
530 {
531 return m_Controls.SnapInput(pData);
532 }
533 if(m_aLocalIds[!g_Config.m_ClDummy] < 0)
534 {
535 return 0;
536 }
537
538 if(!g_Config.m_ClDummyHammer)
539 {
540 if(m_DummyFire != 0)
541 {
542 m_DummyInput.m_Fire = (m_HammerInput.m_Fire + 1) & ~1;
543 m_DummyFire = 0;
544 }
545
546 if(!Force && (!m_DummyInput.m_Direction && !m_DummyInput.m_Jump && !m_DummyInput.m_Hook))
547 {
548 return 0;
549 }
550
551 mem_copy(dest: pData, source: &m_DummyInput, size: sizeof(m_DummyInput));
552 return sizeof(m_DummyInput);
553 }
554 else
555 {
556 if(m_DummyFire % 25 != 0)
557 {
558 m_DummyFire++;
559 return 0;
560 }
561 m_DummyFire++;
562
563 m_HammerInput.m_Fire = (m_HammerInput.m_Fire + 1) | 1;
564 m_HammerInput.m_WantedWeapon = WEAPON_HAMMER + 1;
565 if(!g_Config.m_ClDummyRestoreWeapon)
566 {
567 m_DummyInput.m_WantedWeapon = WEAPON_HAMMER + 1;
568 }
569
570 const vec2 Dir = m_LocalCharacterPos - m_aClients[m_aLocalIds[!g_Config.m_ClDummy]].m_Predicted.m_Pos;
571 m_HammerInput.m_TargetX = (int)Dir.x;
572 m_HammerInput.m_TargetY = (int)Dir.y;
573
574 mem_copy(dest: pData, source: &m_HammerInput, size: sizeof(m_HammerInput));
575 return sizeof(m_HammerInput);
576 }
577}
578
579void CGameClient::OnConnected()
580{
581 const char *pConnectCaption = DemoPlayer()->IsPlaying() ? Localize(pStr: "Preparing demo playback") : Localize(pStr: "Connected");
582 const char *pLoadMapContent = Localize(pStr: "Initializing map logic");
583 // render loading before skip is calculated
584 m_Menus.RenderLoading(pCaption: pConnectCaption, pContent: pLoadMapContent, IncreaseCounter: 0);
585 m_Layers.Init(pMap: Map(), GameOnly: false, InitializeTilemapSkip: true);
586 m_Collision.Init(pLayers: Layers());
587 m_GameWorld.m_Core.InitSwitchers(HighestSwitchNumber: m_Collision.m_HighestSwitchNumber);
588 m_GameWorld.m_PredictedEvents.clear();
589 m_RaceHelper.Init(pGameClient: this);
590
591 // render loading before going through all components
592 m_Menus.RenderLoading(pCaption: pConnectCaption, pContent: pLoadMapContent, IncreaseCounter: 0);
593 for(auto &pComponent : m_vpAll)
594 {
595 pComponent->OnMapLoad();
596 pComponent->OnReset();
597 }
598 Ui()->OnReset();
599
600 ConfigManager()->ResetGameSettings();
601 LoadMapSettings();
602
603 if(Client()->State() != IClient::STATE_DEMOPLAYBACK)
604 {
605 Client()->SetLoadingStateDetail(IClient::ELoadingStateDetail::GETTING_READY);
606 m_Menus.RenderLoading(pCaption: pConnectCaption, pContent: Localize(pStr: "Sending initial client info"), IncreaseCounter: 0);
607
608 // send the initial info
609 SendInfo(Start: true);
610 // we should keep this in for now, because otherwise you can't spectate
611 // people at start as the other info 64 packet is only sent after the first
612 // snap
613 Client()->Rcon(pLine: "crashmeplx");
614
615 m_LocalServer.RconAuthIfPossible();
616 }
617}
618
619void CGameClient::OnReset()
620{
621 InvalidateSnapshot();
622
623 m_EditorMovementDelay = 5;
624
625 m_PredictedTick = -1;
626 std::fill(first: std::begin(arr&: m_aLastNewPredictedTick), last: std::end(arr&: m_aLastNewPredictedTick), value: -1);
627
628 m_LastRoundStartTick = -1;
629 m_LastRaceTick = -1;
630 m_LastFlagCarrierRed = -4;
631 m_LastFlagCarrierBlue = -4;
632
633 std::fill(first: std::begin(arr&: m_aCheckInfo), last: std::end(arr&: m_aCheckInfo), value: -1);
634
635 // m_aDDNetVersionStr is initialized once in OnInit
636
637 std::fill(first: std::begin(arr&: m_aLastPos), last: std::end(arr&: m_aLastPos), value: vec2(0.0f, 0.0f));
638 std::fill(first: std::begin(arr&: m_aLastActive), last: std::end(arr&: m_aLastActive), value: false);
639
640 m_GameOver = false;
641 m_GamePaused = false;
642
643 m_SuppressEvents = false;
644 m_NewTick = false;
645 m_NewPredictedTick = false;
646
647 m_aFlagDropTick[TEAM_RED] = 0;
648 m_aFlagDropTick[TEAM_BLUE] = 0;
649
650 m_ServerMode = SERVERMODE_PURE;
651 mem_zero(block: &m_GameInfo, size: sizeof(m_GameInfo));
652
653 m_DemoSpecId = SPEC_FOLLOW;
654 m_LocalCharacterPos = vec2(0.0f, 0.0f);
655
656 m_PredictedPrevChar.Reset();
657 m_PredictedChar.Reset();
658
659 // m_Snap was cleared in InvalidateSnapshot
660
661 std::fill(first: std::begin(arr&: m_aLocalTuneZone), last: std::end(arr&: m_aLocalTuneZone), value: -1);
662 std::fill(first: std::begin(arr&: m_aReceivedTuning), last: std::end(arr&: m_aReceivedTuning), value: false);
663 std::fill(first: std::begin(arr&: m_aExpectingTuningForZone), last: std::end(arr&: m_aExpectingTuningForZone), value: -1);
664 std::fill(first: std::begin(arr&: m_aExpectingTuningSince), last: std::end(arr&: m_aExpectingTuningSince), value: 0);
665 std::fill(first: std::begin(arr&: m_aTuning), last: std::end(arr&: m_aTuning), value: CTuningParams());
666
667 m_ActiveRecordings.reset();
668
669 for(auto &Client : m_aClients)
670 Client.Reset();
671
672 for(auto &Stats : m_aStats)
673 Stats.Reset();
674
675 std::fill(first: std::begin(arr&: m_aNextChangeInfo), last: std::end(arr&: m_aNextChangeInfo), value: -1);
676 std::fill(first: std::begin(arr&: m_aLocalIds), last: std::end(arr&: m_aLocalIds), value: -1);
677 m_DummyInput = {};
678 m_HammerInput = {};
679 m_DummyFire = 0;
680 m_ReceivedDDNetPlayer = false;
681 m_ReceivedDDNetPlayerFinishTimes = false;
682 m_ReceivedDDNetPlayerFinishTimesMillis = false;
683
684 m_Teams.Reset();
685 m_GameWorld.Clear();
686 m_GameWorld.m_WorldConfig.m_InfiniteAmmo = true;
687 m_PredictedWorld.CopyWorld(pFrom: &m_GameWorld);
688 m_PrevPredictedWorld.CopyWorld(pFrom: &m_PredictedWorld);
689
690 m_vSnapEntities.clear();
691
692 std::fill(first: std::begin(arr&: m_aDDRaceMsgSent), last: std::end(arr&: m_aDDRaceMsgSent), value: false);
693 std::fill(first: std::begin(arr&: m_aShowOthers), last: std::end(arr&: m_aShowOthers), value: SHOW_OTHERS_NOT_SET);
694 std::fill(first: std::begin(arr&: m_aEnableSpectatorCount), last: std::end(arr&: m_aEnableSpectatorCount), value: -1);
695 std::fill(first: std::begin(arr&: m_aLastUpdateTick), last: std::end(arr&: m_aLastUpdateTick), value: 0);
696
697 m_IsDummySwapping = false;
698 m_CharOrder.Reset();
699 std::fill(first: std::begin(arr&: m_aSwitchStateTeam), last: std::end(arr&: m_aSwitchStateTeam), value: -1);
700
701 m_MapBestTimeSeconds = FinishTime::UNSET;
702 m_MapBestTimeMillis = 0;
703 m_aMapDescription[0] = '\0';
704
705 // m_MapBugs and m_aTuningList are reset in LoadMapSettings
706
707 m_LastShowDistanceZoom = 0.0f;
708 m_LastZoom = 0.0f;
709 m_LastScreenAspect = 0.0f;
710 m_LastDeadzone = 0.0f;
711 m_LastFollowFactor = 0.0f;
712 m_LastDummyConnected = false;
713
714 m_CursorInfo.m_CursorOwnerId = -1;
715 m_CursorInfo.m_NumSamples = 0;
716
717 for(auto &pComponent : m_vpAll)
718 pComponent->OnReset();
719 Ui()->OnReset();
720
721 Editor()->ResetMentions();
722 Editor()->ResetIngameMoved();
723
724 Collision()->Unload();
725 Layers()->Unload();
726}
727
728void CGameClient::UpdatePositions()
729{
730 // local character position
731 if(!Predict() && m_Snap.m_pLocalCharacter && m_Snap.m_pLocalPrevCharacter)
732 {
733 m_LocalCharacterPos = mix(
734 a: vec2(m_Snap.m_pLocalPrevCharacter->m_X, m_Snap.m_pLocalPrevCharacter->m_Y),
735 b: vec2(m_Snap.m_pLocalCharacter->m_X, m_Snap.m_pLocalCharacter->m_Y), amount: Client()->IntraGameTick(Conn: g_Config.m_ClDummy));
736 }
737
738 // spectator position
739 if(m_Snap.m_SpecInfo.m_Active)
740 {
741 if(m_MultiView.IsActivated())
742 {
743 m_MultiView.UpdateView();
744 }
745 else if(Client()->State() == IClient::STATE_DEMOPLAYBACK && m_DemoSpecId != SPEC_FOLLOW && m_Snap.m_SpecInfo.m_SpectatorId != SPEC_FREEVIEW)
746 {
747 m_Snap.m_SpecInfo.m_Position = mix(
748 a: vec2(m_Snap.m_aCharacters[m_Snap.m_SpecInfo.m_SpectatorId].m_Prev.m_X, m_Snap.m_aCharacters[m_Snap.m_SpecInfo.m_SpectatorId].m_Prev.m_Y),
749 b: vec2(m_Snap.m_aCharacters[m_Snap.m_SpecInfo.m_SpectatorId].m_Cur.m_X, m_Snap.m_aCharacters[m_Snap.m_SpecInfo.m_SpectatorId].m_Cur.m_Y),
750 amount: Client()->IntraGameTick(Conn: g_Config.m_ClDummy));
751 m_Snap.m_SpecInfo.m_UsePosition = true;
752 }
753 else if(m_Snap.m_pSpectatorInfo && ((Client()->State() == IClient::STATE_DEMOPLAYBACK && m_DemoSpecId == SPEC_FOLLOW) || (Client()->State() != IClient::STATE_DEMOPLAYBACK && m_Snap.m_SpecInfo.m_SpectatorId != SPEC_FREEVIEW)))
754 {
755 if(m_Snap.m_pPrevSpectatorInfo && m_Snap.m_pPrevSpectatorInfo->m_SpectatorId == m_Snap.m_pSpectatorInfo->m_SpectatorId)
756 m_Snap.m_SpecInfo.m_Position = mix(a: vec2(m_Snap.m_pPrevSpectatorInfo->m_X, m_Snap.m_pPrevSpectatorInfo->m_Y),
757 b: vec2(m_Snap.m_pSpectatorInfo->m_X, m_Snap.m_pSpectatorInfo->m_Y), amount: Client()->IntraGameTick(Conn: g_Config.m_ClDummy));
758 else
759 m_Snap.m_SpecInfo.m_Position = vec2(m_Snap.m_pSpectatorInfo->m_X, m_Snap.m_pSpectatorInfo->m_Y);
760 m_Snap.m_SpecInfo.m_UsePosition = true;
761 }
762 }
763
764 m_MultiView.CheckReset();
765
766 UpdateRenderedCharacters();
767}
768
769void CGameClient::OnRender()
770{
771 const ColorRGBA ClearColor = color_cast<ColorRGBA>(hsl: ColorHSLA(g_Config.m_ClOverlayEntities ? g_Config.m_ClBackgroundEntitiesColor : g_Config.m_ClBackgroundColor));
772 Graphics()->Clear(r: ClearColor.r, g: ClearColor.g, b: ClearColor.b);
773
774 // check if multi view got activated
775 m_MultiView.UpdateActivation();
776
777 // update the local character and spectate position
778 UpdatePositions();
779
780 // display warnings
781 if(m_Menus.CanDisplayWarning())
782 {
783 std::optional<SWarning> Warning = Graphics()->CurrentWarning();
784 if(!Warning.has_value())
785 {
786 Warning = Client()->CurrentWarning();
787 }
788 if(Warning.has_value())
789 {
790 const SWarning &TheWarning = Warning.value();
791 m_Menus.PopupWarning(pTopic: TheWarning.m_aWarningTitle[0] == '\0' ? Localize(pStr: "Warning") : TheWarning.m_aWarningTitle, pBody: TheWarning.m_aWarningMsg, pButton: Localize(pStr: "Ok"), Duration: TheWarning.m_AutoHide ? 10s : 0s);
792 }
793 }
794
795 // update camera data prior to CControls::OnRender to allow CControls::m_aTargetPos to compensate using camera data
796 m_Camera.UpdateCamera();
797
798 UpdateSpectatorCursor();
799
800 // render all systems
801 for(auto &pComponent : m_vpAll)
802 pComponent->OnRender();
803 Ui()->OnRenderTooltip();
804
805 // clear all events/input for this frame
806 Input()->Clear();
807
808 CLineInput::RenderCandidates();
809
810 const bool WasNewTick = m_NewTick;
811
812 // clear new tick flags
813 m_NewTick = false;
814 m_NewPredictedTick = false;
815
816 if(g_Config.m_ClDummy && !Client()->DummyConnected())
817 g_Config.m_ClDummy = 0;
818
819 // resend player and dummy info if it was filtered by server
820 if(m_aLocalIds[0] >= 0 && Client()->State() == IClient::STATE_ONLINE && !m_Menus.IsActive() && WasNewTick)
821 {
822 if(m_aCheckInfo[0] == 0)
823 {
824 if(m_pClient->IsSixup())
825 {
826 if(!GotWantedSkin7(Dummy: false))
827 SendSkinChange7(Dummy: false);
828 else
829 m_aCheckInfo[0] = -1;
830 }
831 else
832 {
833 if(
834 str_comp(a: m_aClients[m_aLocalIds[0]].m_aName, b: Client()->PlayerName()) ||
835 str_comp(a: m_aClients[m_aLocalIds[0]].m_aClan, b: g_Config.m_PlayerClan) ||
836 m_aClients[m_aLocalIds[0]].m_Country != g_Config.m_PlayerCountry ||
837 str_comp(a: m_aClients[m_aLocalIds[0]].m_aSkinName, b: g_Config.m_ClPlayerSkin) ||
838 m_aClients[m_aLocalIds[0]].m_UseCustomColor != g_Config.m_ClPlayerUseCustomColor ||
839 m_aClients[m_aLocalIds[0]].m_ColorBody != (int)g_Config.m_ClPlayerColorBody ||
840 m_aClients[m_aLocalIds[0]].m_ColorFeet != (int)g_Config.m_ClPlayerColorFeet)
841 SendInfo(Start: false);
842 else
843 m_aCheckInfo[0] = -1;
844 }
845 }
846
847 if(m_aCheckInfo[0] > 0)
848 {
849 m_aCheckInfo[0] -= std::min(a: Client()->GameTick(Conn: 0) - Client()->PrevGameTick(Conn: 0), b: m_aCheckInfo[0]);
850 }
851
852 if(m_aLocalIds[1] >= 0)
853 {
854 if(m_aCheckInfo[1] == 0)
855 {
856 if(m_pClient->IsSixup())
857 {
858 if(!GotWantedSkin7(Dummy: true))
859 SendSkinChange7(Dummy: true);
860 else
861 m_aCheckInfo[1] = -1;
862 }
863 else
864 {
865 if(
866 str_comp(a: m_aClients[m_aLocalIds[1]].m_aName, b: Client()->DummyName()) ||
867 str_comp(a: m_aClients[m_aLocalIds[1]].m_aClan, b: g_Config.m_ClDummyClan) ||
868 m_aClients[m_aLocalIds[1]].m_Country != g_Config.m_ClDummyCountry ||
869 str_comp(a: m_aClients[m_aLocalIds[1]].m_aSkinName, b: g_Config.m_ClDummySkin) ||
870 m_aClients[m_aLocalIds[1]].m_UseCustomColor != g_Config.m_ClDummyUseCustomColor ||
871 m_aClients[m_aLocalIds[1]].m_ColorBody != (int)g_Config.m_ClDummyColorBody ||
872 m_aClients[m_aLocalIds[1]].m_ColorFeet != (int)g_Config.m_ClDummyColorFeet)
873 SendDummyInfo(Start: false);
874 else
875 m_aCheckInfo[1] = -1;
876 }
877 }
878
879 if(m_aCheckInfo[1] > 0)
880 {
881 m_aCheckInfo[1] -= std::min(a: Client()->GameTick(Conn: 1) - Client()->PrevGameTick(Conn: 1), b: m_aCheckInfo[1]);
882 }
883 }
884 }
885
886 UpdateManagedTeeRenderInfos();
887}
888
889void CGameClient::OnDummyDisconnect()
890{
891 m_aLocalIds[1] = -1;
892 m_aDDRaceMsgSent[1] = false;
893 m_aShowOthers[1] = SHOW_OTHERS_NOT_SET;
894 m_aEnableSpectatorCount[1] = -1;
895 m_aLastNewPredictedTick[1] = -1;
896}
897
898int CGameClient::LastRaceTick() const
899{
900 return m_LastRaceTick;
901}
902
903int CGameClient::CurrentRaceTime() const
904{
905 if(m_LastRaceTick < 0)
906 {
907 return 0;
908 }
909 return (Client()->GameTick(Conn: g_Config.m_ClDummy) - m_LastRaceTick) / Client()->GameTickSpeed();
910}
911
912bool CGameClient::IsTeamPlay() const
913{
914 return m_Snap.m_pGameInfoObj &&
915 (m_Snap.m_pGameInfoObj->m_GameFlags & GAMEFLAG_TEAMS) != 0;
916}
917
918int CGameClient::MinTeamSize() const
919{
920 // old servers only expose it if the map settings happen to contain it
921 return m_GameInfo.m_MinTeamSize != 0 ? m_GameInfo.m_MinTeamSize : Config()->m_SvMinTeamSize;
922}
923
924int CGameClient::MaxTeamSize() const
925{
926 // old servers only expose it if the map settings happen to contain it
927 return m_GameInfo.m_MaxTeamSize != 0 ? m_GameInfo.m_MaxTeamSize : Config()->m_SvMaxTeamSize;
928}
929
930bool CGameClient::IsWorldPaused() const
931{
932 return m_Snap.m_pGameInfoObj &&
933 (m_Snap.m_pGameInfoObj->m_GameStateFlags & (GAMESTATEFLAG_GAMEOVER | GAMESTATEFLAG_PAUSED)) != 0;
934}
935
936bool CGameClient::IsDemoPlaybackPaused() const
937{
938 return Client()->State() == IClient::STATE_DEMOPLAYBACK &&
939 DemoPlayer()->BaseInfo()->m_Paused;
940}
941
942float CGameClient::GetAnimationPlaybackSpeed() const
943{
944 if(IsWorldPaused() || IsDemoPlaybackPaused())
945 {
946 return 0.0f;
947 }
948 if(Client()->State() == IClient::STATE_DEMOPLAYBACK)
949 {
950 return DemoPlayer()->BaseInfo()->m_Speed;
951 }
952 return 1.0f;
953}
954
955int CGameClient::AntiPingPlayers() const
956{
957 if(g_Config.m_ClAntiPing &&
958 g_Config.m_ClAntiPingPlayers &&
959 !m_Snap.m_SpecInfo.m_Active &&
960 Client()->State() != IClient::STATE_DEMOPLAYBACK)
961 {
962 return g_Config.m_ClAntiPingPlayers;
963 }
964 return 0;
965}
966
967bool CGameClient::AntiPingGrenade() const
968{
969 return g_Config.m_ClAntiPing &&
970 g_Config.m_ClAntiPingGrenade &&
971 !m_Snap.m_SpecInfo.m_Active &&
972 Client()->State() != IClient::STATE_DEMOPLAYBACK;
973}
974
975bool CGameClient::AntiPingWeapons() const
976{
977 return g_Config.m_ClAntiPing &&
978 g_Config.m_ClAntiPingWeapons &&
979 !m_Snap.m_SpecInfo.m_Active &&
980 Client()->State() != IClient::STATE_DEMOPLAYBACK;
981}
982
983bool CGameClient::AntiPingGunfire() const
984{
985 return AntiPingGrenade() &&
986 AntiPingWeapons() &&
987 g_Config.m_ClAntiPingGunfire;
988}
989
990bool CGameClient::Predict() const
991{
992 return g_Config.m_ClPredict &&
993 !IsWorldPaused() &&
994 Client()->State() != IClient::STATE_DEMOPLAYBACK &&
995 !m_Snap.m_SpecInfo.m_Active &&
996 m_Snap.m_pLocalCharacter;
997}
998
999bool CGameClient::PredictDummy() const
1000{
1001 return g_Config.m_ClPredictDummy &&
1002 Client()->DummyConnected() &&
1003 m_Snap.m_LocalClientId >= 0 &&
1004 m_aLocalIds[!g_Config.m_ClDummy] >= 0 &&
1005 !m_aClients[m_aLocalIds[!g_Config.m_ClDummy]].m_Paused;
1006}
1007
1008ColorRGBA CGameClient::GetDDTeamColor(int DDTeam, float Lightness) const
1009{
1010 // Use golden angle to generate unique colors with distinct adjacent colors.
1011 // The first DDTeam (team 1) gets angle 0°, i.e. red hue.
1012 const float Hue = std::fmod(x: (DDTeam - 1) * normalized_golden_angle, y: 1.0f);
1013 return color_cast<ColorRGBA>(hsl: ColorHSLA(Hue, 1.0f, Lightness));
1014}
1015
1016void CGameClient::FormatClientId(int ClientId, char (&aClientId)[16], EClientIdFormat Format) const
1017{
1018 if(Format == EClientIdFormat::NO_INDENT)
1019 {
1020 str_format(buffer: aClientId, buffer_size: sizeof(aClientId), format: "%d", ClientId);
1021 }
1022 else
1023 {
1024 const int HighestClientId = Format == EClientIdFormat::INDENT_AUTO ? m_Snap.m_HighestClientId : 64;
1025 const char *pFigureSpace = " ";
1026 char aNumber[8];
1027 str_format(buffer: aNumber, buffer_size: sizeof(aNumber), format: "%d", ClientId);
1028 aClientId[0] = '\0';
1029 if(ClientId < 100 && HighestClientId >= 100)
1030 {
1031 str_append(dst&: aClientId, src: pFigureSpace);
1032 }
1033 if(ClientId < 10 && HighestClientId >= 10)
1034 {
1035 str_append(dst&: aClientId, src: pFigureSpace);
1036 }
1037 str_append(dst&: aClientId, src: aNumber);
1038 }
1039 str_append(dst&: aClientId, src: ": ");
1040}
1041
1042void CGameClient::OnRelease()
1043{
1044 // release all systems
1045 for(auto &pComponent : m_vpAll)
1046 pComponent->OnRelease();
1047}
1048
1049void CGameClient::OnMessage(int MsgId, CUnpacker *pUnpacker, int Conn, bool Dummy)
1050{
1051 // special messages
1052 static_assert((int)NETMSGTYPE_SV_TUNEPARAMS == (int)protocol7::NETMSGTYPE_SV_TUNEPARAMS, "0.6 and 0.7 tune message id do not match");
1053 if(MsgId == NETMSGTYPE_SV_TUNEPARAMS)
1054 {
1055 // unpack the new tuning
1056 CTuningParams NewTuning;
1057
1058 // No jetpack on DDNet incompatible servers,
1059 // jetpack strength will be received by tune params
1060 NewTuning.m_JetpackStrength = 0;
1061
1062 int *pParams = NewTuning.NetworkArray();
1063 for(int i = 0; i < CTuningParams::Num(); i++)
1064 {
1065 static_assert(offsetof(CTuningParams, m_LaserDamage) / sizeof(CTuneParam) == 30);
1066 if(i == 30 && Client()->IsSixup()) // laser_damage was removed in 0.7
1067 {
1068 continue;
1069 }
1070
1071 const int Value = pUnpacker->GetInt();
1072
1073 // check for unpacking errors
1074 if(pUnpacker->Error())
1075 break;
1076
1077 pParams[i] = Value;
1078 }
1079
1080 m_ServerMode = SERVERMODE_PURE;
1081
1082 m_aReceivedTuning[Conn] = true;
1083 // apply new tuning
1084 m_aTuning[Conn] = NewTuning;
1085 return;
1086 }
1087
1088 void *pRawMsg = TranslateGameMsg(pMsgId: &MsgId, pUnpacker, Conn);
1089
1090 if(!pRawMsg)
1091 {
1092 // the 0.7 version of this error message is printed on translation
1093 // in sixup/translate_game.cpp
1094 if(!Client()->IsSixup())
1095 {
1096 log_debug("client", "dropped weird message '%s' (%d), failed on '%s'",
1097 m_NetObjHandler.GetMsgName(MsgId), MsgId, m_NetObjHandler.FailedMsgOn());
1098 }
1099 return;
1100 }
1101
1102 if(MsgId == NETMSGTYPE_SV_CHANGEINFOCOOLDOWN)
1103 {
1104 CNetMsg_Sv_ChangeInfoCooldown *pMsg = (CNetMsg_Sv_ChangeInfoCooldown *)pRawMsg;
1105 m_aNextChangeInfo[Conn] = pMsg->m_WaitUntil;
1106 return;
1107 }
1108
1109 if(Dummy)
1110 {
1111 if(MsgId == NETMSGTYPE_SV_READYTOENTER)
1112 {
1113 Client()->EnterGame(Conn);
1114 }
1115 else if(MsgId == NETMSGTYPE_SV_CHAT && m_aLocalIds[0] >= 0 && m_aLocalIds[1] >= 0)
1116 {
1117 CNetMsg_Sv_Chat *pMsg = (CNetMsg_Sv_Chat *)pRawMsg;
1118
1119 if((pMsg->m_Team == 1 && (m_aClients[m_aLocalIds[0]].m_Team != m_aClients[m_aLocalIds[1]].m_Team || m_Teams.Team(ClientId: m_aLocalIds[0]) != m_Teams.Team(ClientId: m_aLocalIds[1]))) || pMsg->m_Team > 1)
1120 {
1121 m_Chat.OnMessage(MsgType: MsgId, pRawMsg);
1122 }
1123 }
1124 else if(MsgId == NETMSGTYPE_SV_MODERATORALERT)
1125 {
1126 m_ImportantAlert.OnMessage(MsgType: MsgId, pRawMsg);
1127 }
1128 return; // no need of all that stuff for the dummy
1129 }
1130
1131 // TODO: this should be done smarter
1132 for(auto &pComponent : m_vpAll)
1133 pComponent->OnMessage(Msg: MsgId, pRawMsg);
1134
1135 if(MsgId == NETMSGTYPE_SV_READYTOENTER)
1136 {
1137 Client()->EnterGame(Conn);
1138 }
1139 else if(MsgId == NETMSGTYPE_SV_EMOTICON)
1140 {
1141 CNetMsg_Sv_Emoticon *pMsg = (CNetMsg_Sv_Emoticon *)pRawMsg;
1142
1143 // apply
1144 m_aClients[pMsg->m_ClientId].m_Emoticon = pMsg->m_Emoticon;
1145 m_aClients[pMsg->m_ClientId].m_EmoticonStartTick = Client()->GameTick(Conn);
1146 m_aClients[pMsg->m_ClientId].m_EmoticonStartFraction = Client()->IntraGameTickSincePrev(Conn);
1147 }
1148 else if(MsgId == NETMSGTYPE_SV_SOUNDGLOBAL)
1149 {
1150 if(m_SuppressEvents)
1151 return;
1152
1153 // don't enqueue pseudo-global sounds from demos (created by PlayAndRecord)
1154 CNetMsg_Sv_SoundGlobal *pMsg = (CNetMsg_Sv_SoundGlobal *)pRawMsg;
1155 if(pMsg->m_SoundId == SOUND_CTF_DROP || pMsg->m_SoundId == SOUND_CTF_RETURN ||
1156 pMsg->m_SoundId == SOUND_CTF_CAPTURE || pMsg->m_SoundId == SOUND_CTF_GRAB_EN ||
1157 pMsg->m_SoundId == SOUND_CTF_GRAB_PL)
1158 {
1159 if(g_Config.m_SndGame)
1160 m_Sounds.Enqueue(Channel: CSounds::CHN_GLOBAL, SetId: pMsg->m_SoundId);
1161 }
1162 else
1163 {
1164 if(g_Config.m_SndGame)
1165 m_Sounds.Play(Channel: CSounds::CHN_GLOBAL, SetId: pMsg->m_SoundId, Volume: 1.0f);
1166 }
1167 }
1168 else if(MsgId == NETMSGTYPE_SV_TEAMSSTATE || MsgId == NETMSGTYPE_SV_TEAMSSTATELEGACY)
1169 {
1170 unsigned int i;
1171
1172 for(i = 0; i < MAX_CLIENTS; i++)
1173 {
1174 const int Team = pUnpacker->GetInt();
1175 if(!pUnpacker->Error() && Team >= TEAM_FLOCK && Team < NUM_DDRACE_TEAMS)
1176 {
1177 m_Teams.Team(ClientId: i, Team);
1178 }
1179 else
1180 {
1181 m_Teams.Team(ClientId: i, Team: 0);
1182 break;
1183 }
1184 }
1185
1186 if(i <= VANILLA_MAX_CLIENTS)
1187 m_Teams.m_NumDDRaceTeams = VANILLA_MAX_CLIENTS + 1;
1188
1189 m_Ghost.m_AllowRestart = true;
1190 m_RaceDemo.m_AllowRestart = true;
1191 }
1192 else if(MsgId == NETMSGTYPE_SV_KILLMSG)
1193 {
1194 CNetMsg_Sv_KillMsg *pMsg = (CNetMsg_Sv_KillMsg *)pRawMsg;
1195 // reset character prediction
1196 if(!(m_GameWorld.m_WorldConfig.m_IsFNG && pMsg->m_Weapon == WEAPON_LASER))
1197 {
1198 m_CharOrder.GiveWeak(c: pMsg->m_Victim);
1199 if(CCharacter *pChar = m_GameWorld.GetCharacterById(Id: pMsg->m_Victim))
1200 pChar->ResetPrediction();
1201 m_GameWorld.ReleaseHooked(ClientId: pMsg->m_Victim);
1202 }
1203 }
1204 else if(MsgId == NETMSGTYPE_SV_KILLMSGTEAM)
1205 {
1206 CNetMsg_Sv_KillMsgTeam *pMsg = (CNetMsg_Sv_KillMsgTeam *)pRawMsg;
1207
1208 // reset prediction
1209 std::vector<std::pair<int, int>> vStrongWeakSorted;
1210 for(int i = 0; i < MAX_CLIENTS; i++)
1211 {
1212 if(m_Teams.Team(ClientId: i) == pMsg->m_Team)
1213 {
1214 if(CCharacter *pChar = m_GameWorld.GetCharacterById(Id: i))
1215 {
1216 pChar->ResetPrediction();
1217 vStrongWeakSorted.emplace_back(args&: i, args: pMsg->m_First == i ? MAX_CLIENTS : (pChar ? pChar->GetStrongWeakId() : 0));
1218 }
1219 m_GameWorld.ReleaseHooked(ClientId: i);
1220 }
1221 }
1222 std::stable_sort(first: vStrongWeakSorted.begin(), last: vStrongWeakSorted.end(), comp: [](auto &Left, auto &Right) { return Left.second > Right.second; });
1223 for(auto Id : vStrongWeakSorted)
1224 {
1225 m_CharOrder.GiveWeak(c: Id.first);
1226 }
1227 }
1228 else if(MsgId == NETMSGTYPE_SV_MAPSOUNDGLOBAL)
1229 {
1230 if(m_SuppressEvents)
1231 return;
1232
1233 CNetMsg_Sv_MapSoundGlobal *pMsg = (CNetMsg_Sv_MapSoundGlobal *)pRawMsg;
1234 m_MapSounds.Play(Channel: CSounds::CHN_GLOBAL, SoundId: pMsg->m_SoundId);
1235 }
1236 else if(MsgId == NETMSGTYPE_SV_PREINPUT)
1237 {
1238 CNetMsg_Sv_PreInput *pMsg = (CNetMsg_Sv_PreInput *)pRawMsg;
1239 m_aClients[pMsg->m_Owner].m_aPreInputs[pMsg->m_IntendedTick % 200] = *pMsg;
1240 }
1241 else if(MsgId == NETMSGTYPE_SV_SAVECODE)
1242 {
1243 const CNetMsg_Sv_SaveCode *pMsg = (CNetMsg_Sv_SaveCode *)pRawMsg;
1244 OnSaveCodeNetMessage(pMsg);
1245 }
1246 else if(MsgId == NETMSGTYPE_SV_RECORD || MsgId == NETMSGTYPE_SV_RECORDLEGACY)
1247 {
1248 CNetMsg_Sv_Record *pMsg = static_cast<CNetMsg_Sv_Record *>(pRawMsg);
1249 if(pMsg->m_ServerTimeBest > 0)
1250 {
1251 m_MapBestTimeSeconds = pMsg->m_ServerTimeBest / 100;
1252 m_MapBestTimeMillis = (pMsg->m_ServerTimeBest % 100) * 10;
1253 }
1254 else if(m_MapBestTimeSeconds == FinishTime::UNSET)
1255 {
1256 // some PvP mods based on DDNet accidentally send a best time of 0, despite having no finished races
1257 }
1258 }
1259 else if(MsgId == NETMSGTYPE_SV_MAPINFO)
1260 {
1261 CNetMsg_Sv_MapInfo *pMsg = static_cast<CNetMsg_Sv_MapInfo *>(pRawMsg);
1262 str_copy(dst&: m_aMapDescription, src: pMsg->m_pDescription);
1263 }
1264}
1265
1266void CGameClient::OnStateChange(int NewState, int OldState)
1267{
1268 // reset everything when not already connected (to keep gathered stuff)
1269 if(NewState < IClient::STATE_ONLINE)
1270 OnReset();
1271
1272 // then change the state
1273 for(auto &pComponent : m_vpAll)
1274 pComponent->OnStateChange(NewState, OldState);
1275}
1276
1277void CGameClient::OnShutdown()
1278{
1279 for(auto &pComponent : m_vpAll)
1280 pComponent->OnShutdown();
1281
1282 m_LocalServer.KillServer();
1283}
1284
1285void CGameClient::OnEnterGame()
1286{
1287}
1288
1289void CGameClient::OnGameOver()
1290{
1291 if(Client()->State() != IClient::STATE_DEMOPLAYBACK && g_Config.m_ClEditor == 0)
1292 Client()->AutoScreenshot_Start();
1293}
1294
1295void CGameClient::OnStartGame()
1296{
1297 if(Client()->State() != IClient::STATE_DEMOPLAYBACK && !g_Config.m_ClAutoDemoOnConnect)
1298 Client()->DemoRecorder_HandleAutoStart();
1299 m_Statboard.OnReset();
1300}
1301
1302void CGameClient::OnStartRound()
1303{
1304 // In GamePaused or GameOver state RoundStartTick is updated on each tick
1305 // hence no need to reset stats until player leaves GameOver
1306 // and it would be a mistake to reset stats after or during the pause
1307 m_Statboard.OnReset();
1308
1309 // Restart automatic race demo recording
1310 m_RaceDemo.OnReset();
1311}
1312
1313void CGameClient::OnFlagGrab(int TeamId)
1314{
1315 if(TeamId == TEAM_RED)
1316 m_aStats[m_Snap.m_pGameDataObj->m_FlagCarrierRed].m_FlagGrabs++;
1317 else
1318 m_aStats[m_Snap.m_pGameDataObj->m_FlagCarrierBlue].m_FlagGrabs++;
1319}
1320
1321void CGameClient::OnWindowResize()
1322{
1323 for(auto &pComponent : m_vpAll)
1324 pComponent->OnWindowResize();
1325
1326 Ui()->OnWindowResize();
1327}
1328
1329void CGameClient::OnLanguageChange()
1330{
1331 // The actual language change is delayed because it
1332 // might require clearing the text render font atlas,
1333 // which would invalidate text that is currently drawn.
1334 m_LanguageChanged = true;
1335}
1336
1337void CGameClient::HandleLanguageChanged()
1338{
1339 if(!m_LanguageChanged)
1340 return;
1341 m_LanguageChanged = false;
1342
1343 g_Localization.Load(pFilename: g_Config.m_ClLanguagefile, pStorage: Storage(), pConsole: Console());
1344 TextRender()->SetFontLanguageVariant(g_Config.m_ClLanguagefile);
1345
1346 // Clear all text containers
1347 Client()->OnWindowResize();
1348}
1349
1350void CGameClient::RenderShutdownMessage()
1351{
1352 const char *pMessage = nullptr;
1353 if(Client()->State() == IClient::STATE_QUITTING)
1354 pMessage = Localize(pStr: "Quitting. Please wait…");
1355 else if(Client()->State() == IClient::STATE_RESTARTING)
1356 pMessage = Localize(pStr: "Restarting. Please wait…");
1357 else
1358 dbg_assert_failed("Invalid client state for quitting message");
1359
1360 // This function only gets called after the render loop has already terminated, so we have to call Swap manually.
1361 Graphics()->Clear(r: 0.0f, g: 0.0f, b: 0.0f);
1362 Ui()->MapScreen();
1363 TextRender()->TextColor(Color: TextRender()->DefaultTextColor());
1364 Ui()->DoLabel(pRect: Ui()->Screen(), pText: pMessage, Size: 16.0f, Align: TEXTALIGN_MC);
1365 Graphics()->Swap();
1366 Graphics()->Clear(r: 0.0f, g: 0.0f, b: 0.0f);
1367}
1368
1369void CGameClient::ProcessDemoSnapshot(CSnapshot *pSnap)
1370{
1371 for(int Index = 0; Index < pSnap->NumItems(); Index++)
1372 {
1373 const CSnapshotItem *pItem = pSnap->GetItem(Index);
1374 int ItemType = pSnap->GetItemType(Index);
1375
1376 if(ItemType == NETOBJTYPE_PROJECTILE)
1377 {
1378 // for antiping: if the projectile netobjects from the server contains extra data, this is removed and the original content restored before recording demo
1379 CNetObj_Projectile *pProj = (CNetObj_Projectile *)((void *)pItem->Data());
1380 DemoObjectRemoveExtraProjectileInfo(pProj);
1381 }
1382 else if(ItemType == NETOBJTYPE_DDNETSPECTATORINFO)
1383 {
1384 // always record local camera info as follow mode
1385 CNetObj_DDNetSpectatorInfo *pDDNetSpectatorInfo = (CNetObj_DDNetSpectatorInfo *)((void *)pItem->Data());
1386 pDDNetSpectatorInfo->m_HasCameraInfo = true;
1387 pDDNetSpectatorInfo->m_Zoom = (m_Camera.m_Zooming ? m_Camera.m_ZoomSmoothingTarget : m_Camera.m_Zoom) * 1000.0f;
1388 pDDNetSpectatorInfo->m_Deadzone = m_Camera.Deadzone();
1389 pDDNetSpectatorInfo->m_FollowFactor = m_Camera.FollowFactor();
1390 }
1391 }
1392}
1393
1394void CGameClient::OnRconType(bool UsernameReq)
1395{
1396 m_GameConsole.RequireUsername(UsernameReq);
1397}
1398
1399void CGameClient::OnRconLine(const char *pLine)
1400{
1401 m_GameConsole.PrintLine(Type: CGameConsole::CONSOLETYPE_REMOTE, pLine);
1402}
1403
1404void CGameClient::ProcessEvents()
1405{
1406 if(m_SuppressEvents)
1407 return;
1408
1409 int SnapType = IClient::SNAP_CURRENT;
1410 int Num = Client()->SnapNumItems(SnapId: SnapType);
1411 for(int Index = 0; Index < Num; Index++)
1412 {
1413 const IClient::CSnapItem Item = Client()->SnapGetItem(SnapId: SnapType, Index);
1414
1415 // TODO: We don't have enough info about us, others, to know a correct alpha or volume value.
1416 const float Alpha = 1.0f;
1417 const float Volume = 1.0f;
1418
1419 if(Item.m_Type == NETEVENTTYPE_DAMAGEIND)
1420 {
1421 const CNetEvent_DamageInd *pEvent = (const CNetEvent_DamageInd *)Item.m_pData;
1422
1423 vec2 DamageIndPos = vec2(pEvent->m_X, pEvent->m_Y);
1424 if(!m_PredictedWorld.CheckPredictedEventHandled(CheckEvent: CGameWorld::CPredictedEvent(Item.m_Type, DamageIndPos, -1, Client()->GameTick(Conn: g_Config.m_ClDummy), pEvent->m_Angle)))
1425 {
1426 m_Effects.DamageIndicator(Pos: vec2(pEvent->m_X, pEvent->m_Y), Dir: direction(angle: pEvent->m_Angle / 256.0f), Alpha);
1427 }
1428 }
1429 else if(Item.m_Type == NETEVENTTYPE_EXPLOSION)
1430 {
1431 const CNetEvent_Explosion *pEvent = (const CNetEvent_Explosion *)Item.m_pData;
1432
1433 vec2 ExplosionPos = vec2(pEvent->m_X, pEvent->m_Y);
1434 if(!m_PredictedWorld.CheckPredictedEventHandled(CheckEvent: CGameWorld::CPredictedEvent(Item.m_Type, ExplosionPos, -1, Client()->GameTick(Conn: g_Config.m_ClDummy))))
1435 {
1436 m_Effects.Explosion(Pos: ExplosionPos, Alpha);
1437 }
1438 }
1439 else if(Item.m_Type == NETEVENTTYPE_HAMMERHIT)
1440 {
1441 const CNetEvent_HammerHit *pEvent = (const CNetEvent_HammerHit *)Item.m_pData;
1442
1443 vec2 HammerHitPos = vec2(pEvent->m_X, pEvent->m_Y);
1444 if(!m_PredictedWorld.CheckPredictedEventHandled(CheckEvent: CGameWorld::CPredictedEvent(Item.m_Type, HammerHitPos, -1, Client()->GameTick(Conn: g_Config.m_ClDummy))))
1445 {
1446 m_Effects.HammerHit(Pos: HammerHitPos, Alpha, Volume);
1447 }
1448 }
1449 else if(Item.m_Type == NETEVENTTYPE_BIRTHDAY)
1450 {
1451 const CNetEvent_Birthday *pEvent = (const CNetEvent_Birthday *)Item.m_pData;
1452 m_Effects.Confetti(Pos: vec2(pEvent->m_X, pEvent->m_Y), Alpha);
1453 }
1454 else if(Item.m_Type == NETEVENTTYPE_FINISH)
1455 {
1456 const CNetEvent_Finish *pEvent = (const CNetEvent_Finish *)Item.m_pData;
1457 m_Effects.Confetti(Pos: vec2(pEvent->m_X, pEvent->m_Y), Alpha);
1458 }
1459 else if(Item.m_Type == NETEVENTTYPE_SPAWN)
1460 {
1461 const CNetEvent_Spawn *pEvent = (const CNetEvent_Spawn *)Item.m_pData;
1462 m_Effects.PlayerSpawn(Pos: vec2(pEvent->m_X, pEvent->m_Y), Alpha, Volume);
1463 }
1464 else if(Item.m_Type == NETEVENTTYPE_DEATH)
1465 {
1466 const CNetEvent_Death *pEvent = (const CNetEvent_Death *)Item.m_pData;
1467 m_Effects.PlayerDeath(Pos: vec2(pEvent->m_X, pEvent->m_Y), ClientId: pEvent->m_ClientId, Alpha);
1468 }
1469 else if(Item.m_Type == NETEVENTTYPE_SOUNDWORLD)
1470 {
1471 const CNetEvent_SoundWorld *pEvent = (const CNetEvent_SoundWorld *)Item.m_pData;
1472 if(!Config()->m_SndGame)
1473 continue;
1474
1475 if(m_GameInfo.m_RaceSounds && ((pEvent->m_SoundId == SOUND_GUN_FIRE && !g_Config.m_SndGun) || (pEvent->m_SoundId == SOUND_PLAYER_PAIN_LONG && !g_Config.m_SndLongPain)))
1476 continue;
1477
1478 vec2 SoundPos = vec2(pEvent->m_X, pEvent->m_Y);
1479 if(!m_PredictedWorld.CheckPredictedEventHandled(CheckEvent: CGameWorld::CPredictedEvent(Item.m_Type, SoundPos, -1, Client()->GameTick(Conn: g_Config.m_ClDummy), pEvent->m_SoundId)))
1480 {
1481 m_Sounds.PlayAt(Channel: CSounds::CHN_WORLD, SetId: pEvent->m_SoundId, Volume: 1.0f, Position: SoundPos);
1482 }
1483 }
1484 else if(Item.m_Type == NETEVENTTYPE_MAPSOUNDWORLD)
1485 {
1486 CNetEvent_MapSoundWorld *pEvent = (CNetEvent_MapSoundWorld *)Item.m_pData;
1487 m_MapSounds.PlayAt(Channel: CSounds::CHN_WORLD, SoundId: pEvent->m_SoundId, Position: vec2(pEvent->m_X, pEvent->m_Y));
1488 }
1489 }
1490}
1491
1492static CGameInfo GetGameInfo(const CNetObj_GameInfoEx *pInfoEx, int InfoExSize, const CServerInfo *pFallbackServerInfo)
1493{
1494 int Version = -1;
1495 if(InfoExSize >= 12)
1496 {
1497 Version = pInfoEx->m_Version;
1498 }
1499 else if(InfoExSize >= 8)
1500 {
1501 Version = std::min(a: pInfoEx->m_Version, b: 4);
1502 }
1503 else if(InfoExSize >= 4)
1504 {
1505 Version = 0;
1506 }
1507 int Flags = 0;
1508 if(Version >= 0)
1509 {
1510 Flags = pInfoEx->m_Flags;
1511 }
1512 int Flags2 = 0;
1513 if(Version >= 5)
1514 {
1515 Flags2 = pInfoEx->m_Flags2;
1516 }
1517 bool Race;
1518 bool FastCap;
1519 bool FNG;
1520 bool DDRace;
1521 bool DDNet;
1522 bool BlockWorlds;
1523 bool City;
1524 bool Vanilla;
1525 bool Plus;
1526 bool FDDrace;
1527 if(Version < 1)
1528 {
1529 // The game type is intentionally only available inside this
1530 // `if`. Game type sniffing should be avoided and ideally not
1531 // extended. Mods should set the relevant game flags instead.
1532 const char *pGameType = pFallbackServerInfo->m_aGameType;
1533 Race = str_find_nocase(haystack: pGameType, needle: "race") || str_find_nocase(haystack: pGameType, needle: "fastcap");
1534 FastCap = str_find_nocase(haystack: pGameType, needle: "fastcap");
1535 FNG = str_find_nocase(haystack: pGameType, needle: "fng");
1536 DDRace = str_find_nocase(haystack: pGameType, needle: "ddrace") || str_find_nocase(haystack: pGameType, needle: "mkrace");
1537 DDNet = str_find_nocase(haystack: pGameType, needle: "ddracenet") || str_find_nocase(haystack: pGameType, needle: "ddnet");
1538 BlockWorlds = str_startswith(str: pGameType, prefix: "bw ") || str_comp_nocase(a: pGameType, b: "bw") == 0;
1539 City = str_find_nocase(haystack: pGameType, needle: "city");
1540 Vanilla = str_comp(a: pGameType, b: "DM") == 0 || str_comp(a: pGameType, b: "TDM") == 0 || str_comp(a: pGameType, b: "CTF") == 0;
1541 Plus = str_find(haystack: pGameType, needle: "+");
1542 FDDrace = false;
1543 }
1544 else
1545 {
1546 Race = Flags & GAMEINFOFLAG_GAMETYPE_RACE;
1547 FastCap = Flags & GAMEINFOFLAG_GAMETYPE_FASTCAP;
1548 FNG = Flags & GAMEINFOFLAG_GAMETYPE_FNG;
1549 DDRace = Flags & GAMEINFOFLAG_GAMETYPE_DDRACE;
1550 DDNet = Flags & GAMEINFOFLAG_GAMETYPE_DDNET;
1551 BlockWorlds = Flags & GAMEINFOFLAG_GAMETYPE_BLOCK_WORLDS;
1552 Vanilla = Flags & GAMEINFOFLAG_GAMETYPE_VANILLA;
1553 Plus = Flags & GAMEINFOFLAG_GAMETYPE_PLUS;
1554 City = Version >= 5 && Flags2 & GAMEINFOFLAG2_GAMETYPE_CITY;
1555 FDDrace = Version >= 6 && Flags2 & GAMEINFOFLAG2_GAMETYPE_FDDRACE;
1556
1557 // Ensure invariants upheld by the server info parsing business.
1558 DDRace = DDRace || DDNet || FDDrace;
1559 Race = Race || FastCap || DDRace;
1560 }
1561
1562 CGameInfo Info;
1563 Info.m_FlagStartsRace = FastCap;
1564 Info.m_TimeScore = Race;
1565 Info.m_UnlimitedAmmo = Race;
1566 Info.m_DDRaceRecordMessage = DDRace && !DDNet;
1567 Info.m_RaceRecordMessage = DDNet || (Race && !DDRace);
1568 Info.m_RaceSounds = DDRace || FNG || BlockWorlds;
1569 Info.m_AllowEyeWheel = DDRace || BlockWorlds || City || Plus;
1570 Info.m_AllowHookColl = DDRace;
1571 Info.m_AllowZoom = Race || BlockWorlds || City;
1572 Info.m_BugDDRaceGhost = DDRace;
1573 Info.m_BugDDRaceInput = DDRace;
1574 Info.m_BugFNGLaserRange = FNG;
1575 Info.m_BugVanillaBounce = Vanilla;
1576 Info.m_PredictFNG = FNG;
1577 Info.m_PredictDDRace = DDRace;
1578 Info.m_PredictDDRaceTiles = DDRace && !BlockWorlds;
1579 Info.m_PredictVanilla = Vanilla || FastCap;
1580 Info.m_EntitiesDDNet = DDNet;
1581 Info.m_EntitiesDDRace = DDRace;
1582 Info.m_EntitiesRace = Race;
1583 Info.m_EntitiesFNG = FNG;
1584 Info.m_EntitiesVanilla = Vanilla;
1585 Info.m_EntitiesBW = BlockWorlds;
1586 Info.m_Race = Race;
1587 Info.m_Pvp = !Race;
1588 Info.m_DontMaskEntities = !DDNet;
1589 Info.m_AllowXSkins = false;
1590 Info.m_EntitiesFDDrace = FDDrace;
1591 Info.m_HudHealthArmor = true;
1592 Info.m_HudAmmo = true;
1593 Info.m_HudDDRace = false;
1594 Info.m_NoWeakHookAndBounce = false;
1595 Info.m_NoSkinChangeForFrozen = false;
1596 Info.m_DDRaceTeam = false;
1597 Info.m_PredictEvents = Vanilla;
1598 Info.m_MinTeamSize = 0;
1599 Info.m_MaxTeamSize = 0;
1600 Info.m_NumDDRaceTeams = 65; // `TEAM_SUPER + 1`, fallback for ddrace64 servers
1601 Info.m_OldLaser = false;
1602
1603 if(Version >= 0)
1604 {
1605 Info.m_TimeScore = Flags & GAMEINFOFLAG_TIMESCORE;
1606 }
1607 if(Version >= 2)
1608 {
1609 Info.m_FlagStartsRace = Flags & GAMEINFOFLAG_FLAG_STARTS_RACE;
1610 Info.m_UnlimitedAmmo = Flags & GAMEINFOFLAG_UNLIMITED_AMMO;
1611 Info.m_DDRaceRecordMessage = Flags & GAMEINFOFLAG_DDRACE_RECORD_MESSAGE;
1612 Info.m_RaceRecordMessage = Flags & GAMEINFOFLAG_RACE_RECORD_MESSAGE;
1613 Info.m_AllowEyeWheel = Flags & GAMEINFOFLAG_ALLOW_EYE_WHEEL;
1614 Info.m_AllowHookColl = Flags & GAMEINFOFLAG_ALLOW_HOOK_COLL;
1615 Info.m_AllowZoom = Flags & GAMEINFOFLAG_ALLOW_ZOOM;
1616 Info.m_BugDDRaceGhost = Flags & GAMEINFOFLAG_BUG_DDRACE_GHOST;
1617 Info.m_BugDDRaceInput = Flags & GAMEINFOFLAG_BUG_DDRACE_INPUT;
1618 Info.m_BugFNGLaserRange = Flags & GAMEINFOFLAG_BUG_FNG_LASER_RANGE;
1619 Info.m_BugVanillaBounce = Flags & GAMEINFOFLAG_BUG_VANILLA_BOUNCE;
1620 Info.m_PredictFNG = Flags & GAMEINFOFLAG_PREDICT_FNG;
1621 Info.m_PredictDDRace = Flags & GAMEINFOFLAG_PREDICT_DDRACE;
1622 Info.m_PredictDDRaceTiles = Flags & GAMEINFOFLAG_PREDICT_DDRACE_TILES;
1623 Info.m_PredictVanilla = Flags & GAMEINFOFLAG_PREDICT_VANILLA;
1624 Info.m_EntitiesDDNet = Flags & GAMEINFOFLAG_ENTITIES_DDNET;
1625 Info.m_EntitiesDDRace = Flags & GAMEINFOFLAG_ENTITIES_DDRACE;
1626 Info.m_EntitiesRace = Flags & GAMEINFOFLAG_ENTITIES_RACE;
1627 Info.m_EntitiesFNG = Flags & GAMEINFOFLAG_ENTITIES_FNG;
1628 Info.m_EntitiesVanilla = Flags & GAMEINFOFLAG_ENTITIES_VANILLA;
1629 }
1630 if(Version >= 3)
1631 {
1632 Info.m_Race = Flags & GAMEINFOFLAG_RACE;
1633 Info.m_DontMaskEntities = Flags & GAMEINFOFLAG_DONT_MASK_ENTITIES;
1634 }
1635 if(Version >= 4)
1636 {
1637 Info.m_EntitiesBW = Flags & GAMEINFOFLAG_ENTITIES_BW;
1638 }
1639 if(Version >= 5)
1640 {
1641 Info.m_AllowXSkins = Flags2 & GAMEINFOFLAG2_ALLOW_X_SKINS;
1642 }
1643 if(Version >= 6)
1644 {
1645 Info.m_EntitiesFDDrace = Flags2 & GAMEINFOFLAG2_ENTITIES_FDDRACE;
1646 }
1647 if(Version >= 7)
1648 {
1649 Info.m_HudHealthArmor = Flags2 & GAMEINFOFLAG2_HUD_HEALTH_ARMOR;
1650 Info.m_HudAmmo = Flags2 & GAMEINFOFLAG2_HUD_AMMO;
1651 Info.m_HudDDRace = Flags2 & GAMEINFOFLAG2_HUD_DDRACE;
1652 }
1653 if(Version >= 8)
1654 {
1655 Info.m_NoWeakHookAndBounce = Flags2 & GAMEINFOFLAG2_NO_WEAK_HOOK;
1656 }
1657 if(Version >= 9)
1658 {
1659 Info.m_NoSkinChangeForFrozen = Flags2 & GAMEINFOFLAG2_NO_SKIN_CHANGE_FOR_FROZEN;
1660 }
1661 if(Version >= 10)
1662 {
1663 Info.m_DDRaceTeam = Flags2 & GAMEINFOFLAG2_DDRACE_TEAM;
1664 }
1665 if(Version >= 11)
1666 {
1667 Info.m_PredictEvents = Flags2 & GAMEINFOFLAG2_PREDICT_EVENTS;
1668 }
1669 if(Version >= 12)
1670 {
1671 Info.m_MinTeamSize = pInfoEx->m_MinTeamSize;
1672 Info.m_MaxTeamSize = pInfoEx->m_MaxTeamSize;
1673 // Servers from before this field was added send 0, and this client cannot represent more
1674 // teams than it was compiled with. Fall back to our own count for anything out of range.
1675 const int NumDDRaceTeams = pInfoEx->m_NumDDRaceTeams;
1676 Info.m_NumDDRaceTeams = NumDDRaceTeams > TEAM_FLOCK + 1 && NumDDRaceTeams <= NUM_DDRACE_TEAMS ? NumDDRaceTeams : NUM_DDRACE_TEAMS;
1677 Info.m_OldLaser = Flags2 & GAMEINFOFLAG2_OLD_LASER;
1678 }
1679
1680 return Info;
1681}
1682
1683void CGameClient::InvalidateSnapshot()
1684{
1685 // clear all pointers
1686 mem_zero(block: &m_Snap, size: sizeof(m_Snap));
1687 m_Snap.m_SpecInfo.m_Zoom = 1.0f;
1688 m_Snap.m_LocalClientId = -1;
1689 SnapCollectEntities();
1690}
1691
1692void CGameClient::OnNewSnapshot(bool DummySwapped)
1693{
1694 auto &&Evolve = [this](CNetObj_Character *pCharacter, int Tick) {
1695 CWorldCore TempWorld;
1696 CCharacterCore TempCore = CCharacterCore();
1697 CTeamsCore TempTeams = CTeamsCore();
1698 TempCore.Init(pWorld: &TempWorld, pCollision: Collision(), pTeams: &TempTeams);
1699 TempCore.Read(pObjCore: pCharacter);
1700 TempCore.m_ActiveWeapon = pCharacter->m_Weapon;
1701
1702 while(pCharacter->m_Tick < Tick)
1703 {
1704 pCharacter->m_Tick++;
1705 TempCore.Tick(UseInput: false);
1706 TempCore.Move();
1707 TempCore.Quantize();
1708 }
1709
1710 TempCore.Write(pObjCore: pCharacter);
1711 };
1712
1713 InvalidateSnapshot();
1714
1715 m_NewTick = true;
1716
1717 ProcessEvents();
1718
1719 if(g_Config.m_DbgStress)
1720 {
1721 if((Client()->GameTick(Conn: g_Config.m_ClDummy) % 100) == 0)
1722 {
1723 char aMessage[64];
1724 int MsgLen = rand() % (sizeof(aMessage) - 1);
1725 for(int i = 0; i < MsgLen; i++)
1726 aMessage[i] = (char)('a' + (rand() % ('z' - 'a')));
1727 aMessage[MsgLen] = 0;
1728
1729 m_Chat.SendChat(Team: rand() & 1, pLine: aMessage);
1730 }
1731 }
1732
1733 const CServerInfo &ServerInfo = Client()->ServerInfo();
1734
1735 bool FoundGameInfoEx = false;
1736 bool GotSwitchStateTeam = false;
1737 bool HasUnsetDDNetFinishTimes = false;
1738 bool HasTrueMillisecondFinishTimes = false;
1739 m_aSwitchStateTeam[g_Config.m_ClDummy] = -1;
1740
1741 for(auto &Client : m_aClients)
1742 {
1743 Client.m_SpecCharPresent = false;
1744 }
1745
1746 // go through all the items in the snapshot and gather the info we want
1747 {
1748 m_Snap.m_aTeamSize[TEAM_RED] = m_Snap.m_aTeamSize[TEAM_BLUE] = 0;
1749
1750 int Num = Client()->SnapNumItems(SnapId: IClient::SNAP_CURRENT);
1751 for(int i = 0; i < Num; i++)
1752 {
1753 const IClient::CSnapItem Item = Client()->SnapGetItem(SnapId: IClient::SNAP_CURRENT, Index: i);
1754
1755 if(Item.m_Type == NETOBJTYPE_CLIENTINFO)
1756 {
1757 const CNetObj_ClientInfo *pInfo = (const CNetObj_ClientInfo *)Item.m_pData;
1758 int ClientId = Item.m_Id;
1759 if(ClientId < MAX_CLIENTS)
1760 {
1761 CClientData *pClient = &m_aClients[ClientId];
1762
1763 if(!IntsToStr(pInts: pInfo->m_aName, NumInts: std::size(pInfo->m_aName), pStr: pClient->m_aName, StrSize: std::size(pClient->m_aName)))
1764 {
1765 str_copy(dst&: pClient->m_aName, src: "nameless tee");
1766 }
1767 IntsToStr(pInts: pInfo->m_aClan, NumInts: std::size(pInfo->m_aClan), pStr: pClient->m_aClan, StrSize: std::size(pClient->m_aClan));
1768 pClient->m_Country = pInfo->m_Country;
1769 if(!in_range(a: pClient->m_Country, lower: CountryCode::MINIMUM, upper: CountryCode::MAXIMUM))
1770 {
1771 pClient->m_Country = CountryCode::DEFAULT;
1772 }
1773
1774 IntsToStr(pInts: pInfo->m_aSkin, NumInts: std::size(pInfo->m_aSkin), pStr: pClient->m_aSkinName, StrSize: std::size(pClient->m_aSkinName));
1775 if(!CSkin::IsValidName(pName: pClient->m_aSkinName) ||
1776 (!m_GameInfo.m_AllowXSkins && CSkins::IsSpecialSkin(pName: pClient->m_aSkinName)))
1777 {
1778 str_copy(dst&: pClient->m_aSkinName, src: "default");
1779 }
1780
1781 pClient->m_UseCustomColor = pInfo->m_UseCustomColor;
1782 pClient->m_ColorBody = pInfo->m_ColorBody;
1783 pClient->m_ColorFeet = pInfo->m_ColorFeet;
1784 }
1785 }
1786 else if(Item.m_Type == NETOBJTYPE_PLAYERINFO)
1787 {
1788 const CNetObj_PlayerInfo *pInfo = (const CNetObj_PlayerInfo *)Item.m_pData;
1789
1790 if(pInfo->m_ClientId < MAX_CLIENTS && pInfo->m_ClientId == Item.m_Id)
1791 {
1792 m_aClients[pInfo->m_ClientId].m_Team = pInfo->m_Team;
1793 m_aClients[pInfo->m_ClientId].m_Active = true;
1794 m_Snap.m_apPlayerInfos[pInfo->m_ClientId] = pInfo;
1795 m_Snap.m_apPrevPlayerInfos[pInfo->m_ClientId] = static_cast<const CNetObj_PlayerInfo *>(Client()->SnapFindItem(SnapId: IClient::SNAP_PREV, Type: Item.m_Type, Id: pInfo->m_ClientId));
1796 m_Snap.m_NumPlayers++;
1797
1798 if(pInfo->m_Local)
1799 {
1800 m_Snap.m_LocalClientId = pInfo->m_ClientId;
1801 m_Snap.m_pLocalInfo = pInfo;
1802
1803 if(pInfo->m_Team == TEAM_SPECTATORS)
1804 {
1805 m_Snap.m_SpecInfo.m_Active = true;
1806 }
1807 }
1808
1809 m_Snap.m_HighestClientId = std::max(a: m_Snap.m_HighestClientId, b: pInfo->m_ClientId);
1810
1811 // calculate team-balance
1812 if(pInfo->m_Team != TEAM_SPECTATORS)
1813 {
1814 m_Snap.m_aTeamSize[pInfo->m_Team]++;
1815 if(!m_aStats[pInfo->m_ClientId].IsActive())
1816 m_aStats[pInfo->m_ClientId].JoinGame(Tick: Client()->GameTick(Conn: g_Config.m_ClDummy));
1817 }
1818 else if(m_aStats[pInfo->m_ClientId].IsActive())
1819 {
1820 m_aStats[pInfo->m_ClientId].JoinSpec(Tick: Client()->GameTick(Conn: g_Config.m_ClDummy));
1821 }
1822 }
1823 }
1824 else if(Item.m_Type == NETOBJTYPE_DDNETPLAYER)
1825 {
1826 m_ReceivedDDNetPlayer = true;
1827 const CNetObj_DDNetPlayer *pInfo = (const CNetObj_DDNetPlayer *)Item.m_pData;
1828 if(Item.m_Id < MAX_CLIENTS)
1829 {
1830 m_aClients[Item.m_Id].m_AuthLevel = pInfo->m_AuthLevel;
1831 m_aClients[Item.m_Id].m_Afk = pInfo->m_Flags & EXPLAYERFLAG_AFK;
1832 m_aClients[Item.m_Id].m_Paused = pInfo->m_Flags & EXPLAYERFLAG_PAUSED;
1833 m_aClients[Item.m_Id].m_Spec = pInfo->m_Flags & EXPLAYERFLAG_SPEC;
1834 m_aClients[Item.m_Id].m_FinishTimeSeconds = pInfo->m_FinishTimeSeconds;
1835 m_aClients[Item.m_Id].m_FinishTimeMillis = pInfo->m_FinishTimeMillis;
1836
1837 if(m_aClients[Item.m_Id].m_FinishTimeSeconds == FinishTime::UNSET)
1838 HasUnsetDDNetFinishTimes = true;
1839 // Sub-second precision is only rendered for times under an hour in the scoreboard
1840 else if(m_aClients[Item.m_Id].m_FinishTimeSeconds < 60 * 60 && m_aClients[Item.m_Id].m_FinishTimeMillis % 10 != 0)
1841 HasTrueMillisecondFinishTimes = true;
1842
1843 if(Item.m_Id == m_Snap.m_LocalClientId && (m_aClients[Item.m_Id].m_Paused || m_aClients[Item.m_Id].m_Spec))
1844 {
1845 m_Snap.m_SpecInfo.m_Active = true;
1846 }
1847 }
1848 }
1849 else if(Item.m_Type == NETOBJTYPE_CHARACTER)
1850 {
1851 if(Item.m_Id < MAX_CLIENTS)
1852 {
1853 const void *pOld = Client()->SnapFindItem(SnapId: IClient::SNAP_PREV, Type: NETOBJTYPE_CHARACTER, Id: Item.m_Id);
1854 m_Snap.m_aCharacters[Item.m_Id].m_Cur = *((const CNetObj_Character *)Item.m_pData);
1855 if(pOld)
1856 {
1857 m_Snap.m_aCharacters[Item.m_Id].m_Active = true;
1858 m_Snap.m_aCharacters[Item.m_Id].m_Prev = *((const CNetObj_Character *)pOld);
1859
1860 // limit evolving to 3 seconds
1861 bool EvolvePrev = Client()->PrevGameTick(Conn: g_Config.m_ClDummy) - m_Snap.m_aCharacters[Item.m_Id].m_Prev.m_Tick <= 3 * Client()->GameTickSpeed();
1862 bool EvolveCur = Client()->GameTick(Conn: g_Config.m_ClDummy) - m_Snap.m_aCharacters[Item.m_Id].m_Cur.m_Tick <= 3 * Client()->GameTickSpeed();
1863
1864 // reuse the result from the previous evolve if the snapped character didn't change since the previous snapshot
1865 if(EvolveCur && m_aClients[Item.m_Id].m_Evolved.m_Tick == Client()->PrevGameTick(Conn: g_Config.m_ClDummy))
1866 {
1867 if(mem_comp(a: &m_Snap.m_aCharacters[Item.m_Id].m_Prev, b: &m_aClients[Item.m_Id].m_Snapped, size: sizeof(CNetObj_Character)) == 0)
1868 m_Snap.m_aCharacters[Item.m_Id].m_Prev = m_aClients[Item.m_Id].m_Evolved;
1869 if(mem_comp(a: &m_Snap.m_aCharacters[Item.m_Id].m_Cur, b: &m_aClients[Item.m_Id].m_Snapped, size: sizeof(CNetObj_Character)) == 0)
1870 m_Snap.m_aCharacters[Item.m_Id].m_Cur = m_aClients[Item.m_Id].m_Evolved;
1871 }
1872
1873 if(EvolvePrev && m_Snap.m_aCharacters[Item.m_Id].m_Prev.m_Tick)
1874 Evolve(&m_Snap.m_aCharacters[Item.m_Id].m_Prev, Client()->PrevGameTick(Conn: g_Config.m_ClDummy));
1875 if(EvolveCur && m_Snap.m_aCharacters[Item.m_Id].m_Cur.m_Tick)
1876 Evolve(&m_Snap.m_aCharacters[Item.m_Id].m_Cur, Client()->GameTick(Conn: g_Config.m_ClDummy));
1877
1878 m_aClients[Item.m_Id].m_Snapped = *((const CNetObj_Character *)Item.m_pData);
1879 m_aClients[Item.m_Id].m_Evolved = m_Snap.m_aCharacters[Item.m_Id].m_Cur;
1880 }
1881 else
1882 {
1883 m_aClients[Item.m_Id].m_Evolved.m_Tick = -1;
1884 }
1885 }
1886 }
1887 else if(Item.m_Type == NETOBJTYPE_DDNETCHARACTER)
1888 {
1889 const CNetObj_DDNetCharacter *pCharacterData = (const CNetObj_DDNetCharacter *)Item.m_pData;
1890
1891 if(Item.m_Id < MAX_CLIENTS)
1892 {
1893 m_Snap.m_aCharacters[Item.m_Id].m_ExtendedData = *pCharacterData;
1894 m_Snap.m_aCharacters[Item.m_Id].m_pPrevExtendedData = (const CNetObj_DDNetCharacter *)Client()->SnapFindItem(SnapId: IClient::SNAP_PREV, Type: NETOBJTYPE_DDNETCHARACTER, Id: Item.m_Id);
1895 m_Snap.m_aCharacters[Item.m_Id].m_HasExtendedData = true;
1896 m_Snap.m_aCharacters[Item.m_Id].m_HasExtendedDisplayInfo = false;
1897 if(pCharacterData->m_JumpedTotal != -1)
1898 {
1899 m_Snap.m_aCharacters[Item.m_Id].m_HasExtendedDisplayInfo = true;
1900 }
1901 CClientData *pClient = &m_aClients[Item.m_Id];
1902 // Collision
1903 pClient->m_Solo = pCharacterData->m_Flags & CHARACTERFLAG_SOLO;
1904 pClient->m_Jetpack = pCharacterData->m_Flags & CHARACTERFLAG_JETPACK;
1905 pClient->m_CollisionDisabled = pCharacterData->m_Flags & CHARACTERFLAG_COLLISION_DISABLED;
1906 pClient->m_HammerHitDisabled = pCharacterData->m_Flags & CHARACTERFLAG_HAMMER_HIT_DISABLED;
1907 pClient->m_GrenadeHitDisabled = pCharacterData->m_Flags & CHARACTERFLAG_GRENADE_HIT_DISABLED;
1908 pClient->m_LaserHitDisabled = pCharacterData->m_Flags & CHARACTERFLAG_LASER_HIT_DISABLED;
1909 pClient->m_ShotgunHitDisabled = pCharacterData->m_Flags & CHARACTERFLAG_SHOTGUN_HIT_DISABLED;
1910 pClient->m_HookHitDisabled = pCharacterData->m_Flags & CHARACTERFLAG_HOOK_HIT_DISABLED;
1911 pClient->m_Super = pCharacterData->m_Flags & CHARACTERFLAG_SUPER;
1912 pClient->m_Invincible = pCharacterData->m_Flags & CHARACTERFLAG_INVINCIBLE;
1913
1914 // Endless
1915 pClient->m_EndlessHook = pCharacterData->m_Flags & CHARACTERFLAG_ENDLESS_HOOK;
1916 pClient->m_EndlessJump = pCharacterData->m_Flags & CHARACTERFLAG_ENDLESS_JUMP;
1917
1918 // Freeze
1919 pClient->m_FreezeEnd = pCharacterData->m_FreezeEnd;
1920 pClient->m_DeepFrozen = pCharacterData->m_FreezeEnd == -1;
1921 pClient->m_LiveFrozen = (pCharacterData->m_Flags & CHARACTERFLAG_MOVEMENTS_DISABLED) != 0;
1922
1923 // Telegun
1924 pClient->m_HasTelegunGrenade = pCharacterData->m_Flags & CHARACTERFLAG_TELEGUN_GRENADE;
1925 pClient->m_HasTelegunGun = pCharacterData->m_Flags & CHARACTERFLAG_TELEGUN_GUN;
1926 pClient->m_HasTelegunLaser = pCharacterData->m_Flags & CHARACTERFLAG_TELEGUN_LASER;
1927
1928 pClient->m_Predicted.ReadDDNet(pObjDDNet: pCharacterData);
1929
1930 m_Teams.SetSolo(ClientId: Item.m_Id, Value: pClient->m_Solo);
1931 }
1932 }
1933 else if(Item.m_Type == NETOBJTYPE_SPECCHAR)
1934 {
1935 const CNetObj_SpecChar *pSpecCharData = (const CNetObj_SpecChar *)Item.m_pData;
1936
1937 if(Item.m_Id < MAX_CLIENTS)
1938 {
1939 CClientData *pClient = &m_aClients[Item.m_Id];
1940 pClient->m_SpecCharPresent = true;
1941 pClient->m_SpecChar.x = pSpecCharData->m_X;
1942 pClient->m_SpecChar.y = pSpecCharData->m_Y;
1943 }
1944 }
1945 else if(Item.m_Type == NETOBJTYPE_SPECTATORINFO)
1946 {
1947 m_Snap.m_pSpectatorInfo = (const CNetObj_SpectatorInfo *)Item.m_pData;
1948 m_Snap.m_pPrevSpectatorInfo = (const CNetObj_SpectatorInfo *)Client()->SnapFindItem(SnapId: IClient::SNAP_PREV, Type: NETOBJTYPE_SPECTATORINFO, Id: Item.m_Id);
1949
1950 // needed for 0.7 survival
1951 // to auto spec players when dead
1952 if(Client()->IsSixup())
1953 m_Snap.m_SpecInfo.m_Active = true;
1954 m_Snap.m_SpecInfo.m_SpectatorId = m_Snap.m_pSpectatorInfo->m_SpectatorId;
1955 }
1956 else if(Item.m_Type == NETOBJTYPE_DDNETSPECTATORINFO)
1957 {
1958 const CNetObj_DDNetSpectatorInfo *pDDNetSpecInfo = (const CNetObj_DDNetSpectatorInfo *)Item.m_pData;
1959 m_Snap.m_SpecInfo.m_HasCameraInfo = pDDNetSpecInfo->m_HasCameraInfo;
1960 m_Snap.m_SpecInfo.m_Zoom = pDDNetSpecInfo->m_Zoom / 1000.0f;
1961 m_Snap.m_SpecInfo.m_Deadzone = pDDNetSpecInfo->m_Deadzone;
1962 m_Snap.m_SpecInfo.m_FollowFactor = pDDNetSpecInfo->m_FollowFactor;
1963 }
1964 else if(Item.m_Type == NETOBJTYPE_SPECTATORCOUNT)
1965 {
1966 m_Snap.m_pSpectatorCount = (const CNetObj_SpectatorCount *)Item.m_pData;
1967 }
1968 else if(Item.m_Type == NETOBJTYPE_GAMEINFO)
1969 {
1970 m_Snap.m_pGameInfoObj = (const CNetObj_GameInfo *)Item.m_pData;
1971 const bool CurrentTickGameOver = (m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_GAMEOVER) != 0;
1972 const bool CurrentTickGamePaused = (m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_PAUSED) != 0;
1973 if(!m_GameOver && CurrentTickGameOver)
1974 OnGameOver();
1975 else if(m_GameOver && !CurrentTickGameOver)
1976 OnStartGame();
1977 // Handle case that a new round is started (RoundStartTick changed)
1978 // New round is usually started after `restart` on server
1979 if(m_Snap.m_pGameInfoObj->m_RoundStartTick != m_LastRoundStartTick && !(CurrentTickGameOver || CurrentTickGamePaused || m_GamePaused))
1980 OnStartRound();
1981 m_LastRoundStartTick = m_Snap.m_pGameInfoObj->m_RoundStartTick;
1982 m_GameOver = CurrentTickGameOver;
1983 m_GamePaused = CurrentTickGamePaused;
1984 }
1985 else if(Item.m_Type == NETOBJTYPE_GAMEINFOEX)
1986 {
1987 if(FoundGameInfoEx)
1988 {
1989 continue;
1990 }
1991 FoundGameInfoEx = true;
1992 m_GameInfo = GetGameInfo(pInfoEx: (const CNetObj_GameInfoEx *)Item.m_pData, InfoExSize: Item.m_DataSize, pFallbackServerInfo: &ServerInfo);
1993 }
1994 else if(Item.m_Type == NETOBJTYPE_GAMEDATA)
1995 {
1996 m_Snap.m_pGameDataObj = static_cast<const CNetObj_GameData *>(Item.m_pData);
1997 m_Snap.m_pPrevGameDataObj = static_cast<const CNetObj_GameData *>(Client()->SnapFindItem(SnapId: IClient::SNAP_PREV, Type: Item.m_Type, Id: Item.m_Id));
1998 if(m_Snap.m_pGameDataObj->m_FlagCarrierRed == FLAG_TAKEN)
1999 {
2000 if(m_aFlagDropTick[TEAM_RED] == 0)
2001 m_aFlagDropTick[TEAM_RED] = Client()->GameTick(Conn: g_Config.m_ClDummy);
2002 }
2003 else
2004 {
2005 m_aFlagDropTick[TEAM_RED] = 0;
2006 }
2007 if(m_Snap.m_pGameDataObj->m_FlagCarrierBlue == FLAG_TAKEN)
2008 {
2009 if(m_aFlagDropTick[TEAM_BLUE] == 0)
2010 m_aFlagDropTick[TEAM_BLUE] = Client()->GameTick(Conn: g_Config.m_ClDummy);
2011 }
2012 else
2013 {
2014 m_aFlagDropTick[TEAM_BLUE] = 0;
2015 }
2016 if(m_LastFlagCarrierRed == FLAG_ATSTAND && m_Snap.m_pGameDataObj->m_FlagCarrierRed >= 0)
2017 OnFlagGrab(TeamId: TEAM_RED);
2018 else if(m_LastFlagCarrierBlue == FLAG_ATSTAND && m_Snap.m_pGameDataObj->m_FlagCarrierBlue >= 0)
2019 OnFlagGrab(TeamId: TEAM_BLUE);
2020
2021 m_LastFlagCarrierRed = m_Snap.m_pGameDataObj->m_FlagCarrierRed;
2022 m_LastFlagCarrierBlue = m_Snap.m_pGameDataObj->m_FlagCarrierBlue;
2023 }
2024 else if(Item.m_Type == NETOBJTYPE_FLAG)
2025 {
2026 const CNetObj_Flag *pPrevFlag = static_cast<const CNetObj_Flag *>(Client()->SnapFindItem(SnapId: IClient::SNAP_PREV, Type: Item.m_Type, Id: Item.m_Id));
2027 if(pPrevFlag == nullptr)
2028 {
2029 continue;
2030 }
2031 m_Snap.m_apFlags[m_Snap.m_NumFlags] = static_cast<const CNetObj_Flag *>(Item.m_pData);
2032 m_Snap.m_apPrevFlags[m_Snap.m_NumFlags] = pPrevFlag;
2033 ++m_Snap.m_NumFlags;
2034 }
2035 else if(Item.m_Type == NETOBJTYPE_SWITCHSTATE)
2036 {
2037 if(Item.m_DataSize < 36)
2038 {
2039 continue;
2040 }
2041 const CNetObj_SwitchState *pSwitchStateData = (const CNetObj_SwitchState *)Item.m_pData;
2042 int Team = std::clamp(val: Item.m_Id, lo: (int)TEAM_FLOCK, hi: NUM_DDRACE_TEAMS - 1);
2043
2044 int HighestSwitchNumber = std::clamp(val: std::max(a: pSwitchStateData->m_HighestSwitchNumber, b: Collision()->m_HighestSwitchNumber), lo: 0, hi: 255);
2045 if(HighestSwitchNumber != std::max(a: 0, b: (int)Switchers().size() - 1))
2046 {
2047 m_GameWorld.m_Core.InitSwitchers(HighestSwitchNumber);
2048 Collision()->m_HighestSwitchNumber = HighestSwitchNumber;
2049 }
2050
2051 for(int j = 0; j < (int)Switchers().size(); j++)
2052 {
2053 Switchers()[j].m_aStatus[Team] = (pSwitchStateData->m_aStatus[j / 32] >> (j % 32)) & 1;
2054 }
2055
2056 if(Item.m_DataSize >= 68)
2057 {
2058 // update the endtick of up to four timed switchers
2059 for(int j = 0; j < (int)std::size(pSwitchStateData->m_aEndTicks); j++)
2060 {
2061 int SwitchNumber = pSwitchStateData->m_aSwitchNumbers[j];
2062 int EndTick = pSwitchStateData->m_aEndTicks[j];
2063 if(EndTick > 0 && SwitchNumber >= 0 && SwitchNumber < (int)Switchers().size())
2064 {
2065 Switchers()[SwitchNumber].m_aEndTick[Team] = EndTick;
2066 }
2067 }
2068 }
2069
2070 // update switch types
2071 for(auto &Switcher : Switchers())
2072 {
2073 if(Switcher.m_aStatus[Team])
2074 Switcher.m_aType[Team] = Switcher.m_aEndTick[Team] ? TILE_SWITCHTIMEDOPEN : TILE_SWITCHOPEN;
2075 else
2076 Switcher.m_aType[Team] = Switcher.m_aEndTick[Team] ? TILE_SWITCHTIMEDCLOSE : TILE_SWITCHCLOSE;
2077 }
2078
2079 if(!GotSwitchStateTeam)
2080 m_aSwitchStateTeam[g_Config.m_ClDummy] = Team;
2081 else
2082 m_aSwitchStateTeam[g_Config.m_ClDummy] = -1;
2083 GotSwitchStateTeam = true;
2084 }
2085 else if(Item.m_Type == NETOBJTYPE_MAPBESTTIME)
2086 {
2087 const CNetObj_MapBestTime *pMapBestTimeData = static_cast<const CNetObj_MapBestTime *>(Item.m_pData);
2088 m_MapBestTimeSeconds = pMapBestTimeData->m_MapBestTimeSeconds;
2089 m_MapBestTimeMillis = pMapBestTimeData->m_MapBestTimeMillis;
2090 }
2091 }
2092 }
2093
2094 if(!FoundGameInfoEx)
2095 {
2096 m_GameInfo = GetGameInfo(pInfoEx: nullptr, InfoExSize: 0, pFallbackServerInfo: &ServerInfo);
2097 }
2098
2099 // Sv_TeamsState can arrive before the first snapshot, so derive this here instead of in the message handler
2100 m_Teams.m_NumDDRaceTeams = m_GameInfo.m_NumDDRaceTeams;
2101
2102 for(CClientData &Client : m_aClients)
2103 {
2104 Client.UpdateSkinInfo();
2105 }
2106
2107 // setup local pointers
2108 if(m_Snap.m_LocalClientId >= 0)
2109 {
2110 m_aLocalIds[g_Config.m_ClDummy] = m_Snap.m_LocalClientId;
2111
2112 CSnapState::CCharacterInfo *pChr = &m_Snap.m_aCharacters[m_Snap.m_LocalClientId];
2113 if(pChr->m_Active)
2114 {
2115 if(!m_Snap.m_SpecInfo.m_Active)
2116 {
2117 m_Snap.m_pLocalCharacter = &pChr->m_Cur;
2118 m_Snap.m_pLocalPrevCharacter = &pChr->m_Prev;
2119 m_LocalCharacterPos = vec2(m_Snap.m_pLocalCharacter->m_X, m_Snap.m_pLocalCharacter->m_Y);
2120 }
2121 }
2122 else if(Client()->SnapFindItem(SnapId: IClient::SNAP_PREV, Type: NETOBJTYPE_CHARACTER, Id: m_Snap.m_LocalClientId))
2123 {
2124 // player died
2125 m_Controls.OnPlayerDeath();
2126 }
2127 }
2128 if(Client()->State() == IClient::STATE_DEMOPLAYBACK)
2129 {
2130 if(m_Snap.m_LocalClientId == -1 && m_DemoSpecId == SPEC_FOLLOW)
2131 {
2132 // TODO: can this be done in the translation layer?
2133 if(!Client()->IsSixup())
2134 m_DemoSpecId = SPEC_FREEVIEW;
2135 }
2136 if(m_DemoSpecId != SPEC_FOLLOW)
2137 {
2138 m_Snap.m_SpecInfo.m_Active = true;
2139 if(m_DemoSpecId > SPEC_FREEVIEW && m_Snap.m_aCharacters[m_DemoSpecId].m_Active)
2140 m_Snap.m_SpecInfo.m_SpectatorId = m_DemoSpecId;
2141 else
2142 m_Snap.m_SpecInfo.m_SpectatorId = SPEC_FREEVIEW;
2143 }
2144 }
2145
2146 // clear out unneeded client data
2147 for(int i = 0; i < MAX_CLIENTS; ++i)
2148 {
2149 if(!m_Snap.m_apPlayerInfos[i] && m_aClients[i].m_Active)
2150 {
2151 m_aClients[i].Reset();
2152 m_aStats[i].Reset();
2153 }
2154 }
2155
2156 if(Client()->State() == IClient::STATE_ONLINE)
2157 {
2158 m_pDiscord->UpdatePlayerCount(Count: m_Snap.m_NumPlayers);
2159 }
2160
2161 for(int i = 0; i < MAX_CLIENTS; ++i)
2162 {
2163 // update friend state
2164 m_aClients[i].m_Friend = !(i == m_Snap.m_LocalClientId || !m_Snap.m_apPlayerInfos[i] || !Friends()->IsFriend(pName: m_aClients[i].m_aName, pClan: m_aClients[i].m_aClan, PlayersOnly: true));
2165
2166 // update foe state
2167 m_aClients[i].m_Foe = !(i == m_Snap.m_LocalClientId || !m_Snap.m_apPlayerInfos[i] || !Foes()->IsFriend(pName: m_aClients[i].m_aName, pClan: m_aClients[i].m_aClan, PlayersOnly: true));
2168 }
2169
2170 // check if we received all finish times
2171 m_ReceivedDDNetPlayerFinishTimes = m_ReceivedDDNetPlayer && !HasUnsetDDNetFinishTimes;
2172 m_ReceivedDDNetPlayerFinishTimesMillis = m_ReceivedDDNetPlayer && HasTrueMillisecondFinishTimes;
2173
2174 // sort player infos by name
2175 mem_copy(dest: m_Snap.m_apInfoByName, source: m_Snap.m_apPlayerInfos, size: sizeof(m_Snap.m_apInfoByName));
2176 std::stable_sort(first: m_Snap.m_apInfoByName, last: m_Snap.m_apInfoByName + MAX_CLIENTS,
2177 comp: [this](const CNetObj_PlayerInfo *pPlayer1, const CNetObj_PlayerInfo *pPlayer2) -> bool {
2178 if(!pPlayer2)
2179 return static_cast<bool>(pPlayer1);
2180 if(!pPlayer1)
2181 return false;
2182 return str_comp_nocase(a: m_aClients[pPlayer1->m_ClientId].m_aName, b: m_aClients[pPlayer2->m_ClientId].m_aName) < 0;
2183 });
2184
2185 bool TimeScore = m_GameInfo.m_TimeScore;
2186 bool Race7 = Client()->IsSixup() && m_Snap.m_pGameInfoObj && m_Snap.m_pGameInfoObj->m_GameFlags & protocol7::GAMEFLAG_RACE;
2187
2188 // sort player infos by score
2189 mem_copy(dest: m_Snap.m_apInfoByScore, source: m_Snap.m_apInfoByName, size: sizeof(m_Snap.m_apInfoByScore));
2190 auto TimeComparator = CGameClient::GetScoreComparator(TimeScore, ReceivedMillisecondFinishTimes: m_ReceivedDDNetPlayerFinishTimes, Race7);
2191 auto SortByTimeScore = [TimeComparator, this](const CNetObj_PlayerInfo *pPlayer1, const CNetObj_PlayerInfo *pPlayer2) -> bool {
2192 if(!pPlayer2)
2193 return static_cast<bool>(pPlayer1);
2194 if(!pPlayer1)
2195 return false;
2196 if(m_ReceivedDDNetPlayerFinishTimes)
2197 return TimeComparator(m_aClients[pPlayer1->m_ClientId].m_FinishTimeSeconds, m_aClients[pPlayer2->m_ClientId].m_FinishTimeSeconds, m_aClients[pPlayer1->m_ClientId].m_FinishTimeMillis, m_aClients[pPlayer2->m_ClientId].m_FinishTimeMillis);
2198 return TimeComparator(pPlayer1->m_Score, pPlayer2->m_Score, 0, 0);
2199 };
2200 std::stable_sort(first: m_Snap.m_apInfoByScore, last: m_Snap.m_apInfoByScore + MAX_CLIENTS, comp: SortByTimeScore);
2201
2202 // sort player infos by DDRace Team (and score between)
2203 int Index = 0;
2204 for(int Team = TEAM_FLOCK; Team < NUM_DDRACE_TEAMS; ++Team)
2205 {
2206 for(int i = 0; i < MAX_CLIENTS && Index < MAX_CLIENTS; ++i)
2207 {
2208 if(m_Snap.m_apInfoByScore[i] && m_Teams.Team(ClientId: m_Snap.m_apInfoByScore[i]->m_ClientId) == Team)
2209 m_Snap.m_apInfoByDDTeamScore[Index++] = m_Snap.m_apInfoByScore[i];
2210 }
2211 }
2212
2213 // sort player infos by DDRace Team (and name between)
2214 Index = 0;
2215 for(int Team = TEAM_FLOCK; Team < NUM_DDRACE_TEAMS; ++Team)
2216 {
2217 for(int i = 0; i < MAX_CLIENTS && Index < MAX_CLIENTS; ++i)
2218 {
2219 if(m_Snap.m_apInfoByName[i] && m_Teams.Team(ClientId: m_Snap.m_apInfoByName[i]->m_ClientId) == Team)
2220 m_Snap.m_apInfoByDDTeamName[Index++] = m_Snap.m_apInfoByName[i];
2221 }
2222 }
2223
2224 if(ServerInfo.m_aGameType[0] != '0')
2225 {
2226 // Vanilla servers send laser_bounce_num 1, DDNet has laser_bounce_num 1000 since ~2014
2227 CTuningParams VanillaTuning;
2228 VanillaTuning.m_LaserBounceNum = 1;
2229 if(str_comp(a: ServerInfo.m_aGameType, b: "DM") != 0 && str_comp(a: ServerInfo.m_aGameType, b: "TDM") != 0 && str_comp(a: ServerInfo.m_aGameType, b: "CTF") != 0)
2230 m_ServerMode = SERVERMODE_MOD;
2231 else if(mem_comp(a: &VanillaTuning, b: &m_aTuning[g_Config.m_ClDummy], size: 33 * sizeof(CTuneParam)) == 0)
2232 m_ServerMode = SERVERMODE_PURE;
2233 else
2234 m_ServerMode = SERVERMODE_PUREMOD;
2235 }
2236
2237 // add tuning to demo when new recording was started, because server tune message was already received before
2238 std::bitset<RECORDER_MAX> CurrentRecordings;
2239 for(int i = 0; i < RECORDER_MAX; i++)
2240 {
2241 if(DemoRecorder(Recorder: i)->IsRecording())
2242 {
2243 CurrentRecordings.set(pos: i);
2244 }
2245 }
2246 const bool HasNewRecordings = (CurrentRecordings & ~m_ActiveRecordings).any();
2247 m_ActiveRecordings = CurrentRecordings;
2248 if(HasNewRecordings)
2249 {
2250 CMsgPacker Msg(NETMSGTYPE_SV_TUNEPARAMS);
2251 int *pParams = (int *)&m_aTuning[g_Config.m_ClDummy];
2252 for(unsigned i = 0; i < sizeof(m_aTuning[0]) / sizeof(int); i++)
2253 Msg.AddInt(i: pParams[i]);
2254 Client()->SendMsgActive(pMsg: &Msg, Flags: MSGFLAG_RECORD | MSGFLAG_NOSEND);
2255 }
2256
2257 for(int i = 0; i < 2; i++)
2258 {
2259 if(m_aDDRaceMsgSent[i] || !m_Snap.m_pLocalInfo)
2260 {
2261 continue;
2262 }
2263 if(i == IClient::CONN_DUMMY && !Client()->DummyConnected())
2264 {
2265 continue;
2266 }
2267 CMsgPacker Msg(NETMSGTYPE_CL_ISDDNETLEGACY, false);
2268 Msg.AddInt(i: DDNetVersion());
2269 Client()->SendMsg(Conn: i, pMsg: &Msg, Flags: MSGFLAG_VITAL);
2270 m_aDDRaceMsgSent[i] = true;
2271 }
2272
2273 if(m_Snap.m_SpecInfo.m_Active && m_MultiView.IsActivated())
2274 {
2275 // dont show other teams while spectating in multi view
2276 CNetMsg_Cl_ShowOthers Msg;
2277 Msg.m_Show = SHOW_OTHERS_ONLY_TEAM;
2278 Client()->SendPackMsgActive(pMsg: &Msg, Flags: MSGFLAG_VITAL);
2279
2280 // update state
2281 m_aShowOthers[g_Config.m_ClDummy] = SHOW_OTHERS_ONLY_TEAM;
2282 }
2283 else if(m_aShowOthers[g_Config.m_ClDummy] == SHOW_OTHERS_NOT_SET || m_aShowOthers[g_Config.m_ClDummy] != g_Config.m_ClShowOthers)
2284 {
2285 {
2286 CNetMsg_Cl_ShowOthers Msg;
2287 Msg.m_Show = g_Config.m_ClShowOthers;
2288 Client()->SendPackMsgActive(pMsg: &Msg, Flags: MSGFLAG_VITAL);
2289 }
2290
2291 // update state
2292 m_aShowOthers[g_Config.m_ClDummy] = g_Config.m_ClShowOthers;
2293 }
2294
2295 if(m_aEnableSpectatorCount[0] == -1 || m_aEnableSpectatorCount[0] != g_Config.m_ClShowhudSpectatorCount)
2296 {
2297 CNetMsg_Cl_EnableSpectatorCount Msg;
2298 Msg.m_Enable = g_Config.m_ClShowhudSpectatorCount;
2299 Client()->SendPackMsg(Conn: 0, pMsg: &Msg, Flags: MSGFLAG_VITAL);
2300 m_aEnableSpectatorCount[0] = g_Config.m_ClShowhudSpectatorCount;
2301 }
2302 if(Client()->DummyConnected() && (m_aEnableSpectatorCount[1] == -1 || m_aEnableSpectatorCount[1] != g_Config.m_ClShowhudSpectatorCount))
2303 {
2304 CNetMsg_Cl_EnableSpectatorCount Msg;
2305 Msg.m_Enable = g_Config.m_ClShowhudSpectatorCount;
2306 Client()->SendPackMsg(Conn: 1, pMsg: &Msg, Flags: MSGFLAG_VITAL);
2307 m_aEnableSpectatorCount[1] = g_Config.m_ClShowhudSpectatorCount;
2308 }
2309
2310 if(DummySwapped)
2311 m_Camera.UpdateCamera();
2312
2313 float ShowDistanceZoom = m_Camera.m_Zoom;
2314 float Zoom = m_Camera.m_Zoom;
2315 if(m_Camera.m_Zooming)
2316 {
2317 if(m_Camera.m_ZoomSmoothingTarget > m_Camera.m_Zoom) // Zooming out
2318 ShowDistanceZoom = m_Camera.m_ZoomSmoothingTarget;
2319 else if(m_Camera.m_ZoomSmoothingTarget < m_Camera.m_Zoom && m_LastShowDistanceZoom > 0) // Zooming in
2320 ShowDistanceZoom = m_LastShowDistanceZoom;
2321
2322 Zoom = m_Camera.m_ZoomSmoothingTarget;
2323 }
2324
2325 float Deadzone = m_Camera.Deadzone();
2326 float FollowFactor = m_Camera.FollowFactor();
2327
2328 if(m_Snap.m_SpecInfo.m_Active)
2329 {
2330 // don't send camera information when spectating
2331 Zoom = m_LastZoom;
2332 Deadzone = m_LastDeadzone;
2333 FollowFactor = m_LastFollowFactor;
2334 }
2335
2336 // initialize dummy vital when first connected
2337 if(Client()->DummyConnected() && !m_LastDummyConnected)
2338 {
2339 {
2340 CNetMsg_Cl_ShowDistance Msg;
2341 float x, y;
2342 Graphics()->CalcScreenParams(Aspect: Graphics()->ScreenAspect(), Zoom: ShowDistanceZoom, pWidth: &x, pHeight: &y);
2343 Msg.m_X = x;
2344 Msg.m_Y = y;
2345 CMsgPacker Packer(&Msg);
2346 Msg.Pack(pPacker: &Packer);
2347 Client()->SendMsg(Conn: IClient::CONN_DUMMY, pMsg: &Packer, Flags: MSGFLAG_VITAL);
2348 }
2349 {
2350 CNetMsg_Cl_CameraInfo Msg;
2351 Msg.m_Zoom = round_truncate(f: Zoom * 1000.f);
2352 Msg.m_Deadzone = Deadzone;
2353 Msg.m_FollowFactor = FollowFactor;
2354 CMsgPacker Packer(&Msg);
2355 Msg.Pack(pPacker: &Packer);
2356 Client()->SendMsg(Conn: IClient::CONN_DUMMY, pMsg: &Packer, Flags: MSGFLAG_VITAL);
2357 }
2358 }
2359
2360 // send show distance
2361 if(ShowDistanceZoom != m_LastShowDistanceZoom || Graphics()->ScreenAspect() != m_LastScreenAspect)
2362 {
2363 CNetMsg_Cl_ShowDistance Msg;
2364 float x, y;
2365 Graphics()->CalcScreenParams(Aspect: Graphics()->ScreenAspect(), Zoom: ShowDistanceZoom, pWidth: &x, pHeight: &y);
2366 Msg.m_X = x;
2367 Msg.m_Y = y;
2368 Client()->ChecksumData()->m_Zoom = ShowDistanceZoom;
2369 CMsgPacker Packer(&Msg);
2370 Msg.Pack(pPacker: &Packer);
2371
2372 Client()->SendMsg(Conn: IClient::CONN_MAIN, pMsg: &Packer, Flags: MSGFLAG_VITAL);
2373 if(Client()->DummyConnected() && m_LastDummyConnected)
2374 Client()->SendMsg(Conn: IClient::CONN_DUMMY, pMsg: &Packer, Flags: MSGFLAG_VITAL);
2375 }
2376
2377 // send camera info
2378 if(Zoom != m_LastZoom || Deadzone != m_LastDeadzone || FollowFactor != m_LastFollowFactor)
2379 {
2380 CNetMsg_Cl_CameraInfo Msg;
2381 Msg.m_Zoom = round_truncate(f: Zoom * 1000.f);
2382 Msg.m_Deadzone = Deadzone;
2383 Msg.m_FollowFactor = FollowFactor;
2384 CMsgPacker Packer(&Msg);
2385 Msg.Pack(pPacker: &Packer);
2386
2387 Client()->SendMsg(Conn: IClient::CONN_MAIN, pMsg: &Packer, Flags: MSGFLAG_VITAL);
2388 if(Client()->DummyConnected() && m_LastDummyConnected)
2389 Client()->SendMsg(Conn: IClient::CONN_DUMMY, pMsg: &Packer, Flags: MSGFLAG_VITAL);
2390 }
2391
2392 m_LastShowDistanceZoom = ShowDistanceZoom;
2393 m_LastZoom = Zoom;
2394 m_LastScreenAspect = Graphics()->ScreenAspect();
2395 m_LastDeadzone = Deadzone;
2396 m_LastFollowFactor = FollowFactor;
2397 m_LastDummyConnected = Client()->DummyConnected();
2398
2399 for(auto &pComponent : m_vpAll)
2400 pComponent->OnNewSnapshot();
2401
2402 // notify editor when local character moved
2403 UpdateEditorIngameMoved();
2404
2405 // detect air jump for other players
2406 for(int i = 0; i < MAX_CLIENTS; i++)
2407 {
2408 if(m_Snap.m_aCharacters[i].m_Active && (m_Snap.m_aCharacters[i].m_Cur.m_Jumped & 2) && !(m_Snap.m_aCharacters[i].m_Prev.m_Jumped & 2))
2409 {
2410 bool IsDummy = Client()->DummyConnected() && i == m_aLocalIds[!g_Config.m_ClDummy];
2411 bool IsLocalPlayer = i == m_Snap.m_LocalClientId;
2412
2413 if(!Predict() || (!IsLocalPlayer && !AntiPingPlayers()) || (!IsLocalPlayer && !IsDummy))
2414 {
2415 vec2 Pos = mix(a: vec2(m_Snap.m_aCharacters[i].m_Prev.m_X, m_Snap.m_aCharacters[i].m_Prev.m_Y),
2416 b: vec2(m_Snap.m_aCharacters[i].m_Cur.m_X, m_Snap.m_aCharacters[i].m_Cur.m_Y),
2417 amount: Client()->IntraGameTick(Conn: g_Config.m_ClDummy));
2418 float Alpha = 1.0f;
2419 if(IsOtherTeam(ClientId: i))
2420 Alpha = g_Config.m_ClShowOthersAlpha / 100.0f;
2421 const float Volume = 1.0f; // TODO snd_game_volume_others
2422
2423 const bool Grounded = Collision()->IsOnGround(Pos: vec2(m_Snap.m_aCharacters[i].m_Prev.m_X, m_Snap.m_aCharacters[i].m_Prev.m_Y), Size: CCharacterCore::PhysicalSize());
2424 if(!Grounded)
2425 {
2426 m_Effects.AirJump(Pos, Alpha, Volume);
2427 }
2428 }
2429 }
2430 }
2431
2432 if(g_Config.m_ClFreezeStars && !m_SuppressEvents)
2433 {
2434 for(auto &Character : m_Snap.m_aCharacters)
2435 {
2436 if(Character.m_Active && Character.m_HasExtendedData && Character.m_pPrevExtendedData)
2437 {
2438 int FreezeTimeNow = Character.m_ExtendedData.m_FreezeEnd - Client()->GameTick(Conn: g_Config.m_ClDummy);
2439 int FreezeTimePrev = Character.m_pPrevExtendedData->m_FreezeEnd - Client()->PrevGameTick(Conn: g_Config.m_ClDummy);
2440 vec2 Pos = vec2(Character.m_Cur.m_X, Character.m_Cur.m_Y);
2441 int StarsNow = (FreezeTimeNow + 1) / Client()->GameTickSpeed();
2442 int StarsPrev = (FreezeTimePrev + 1) / Client()->GameTickSpeed();
2443 if(StarsNow < StarsPrev || (StarsPrev == 0 && StarsNow > 0))
2444 {
2445 int Amount = StarsNow + 1;
2446 float Mid = 3 * pi / 2;
2447 float Min = Mid - pi / 3;
2448 float Max = Mid + pi / 3;
2449 for(int j = 0; j < Amount; j++)
2450 {
2451 float Angle = mix(a: Min, b: Max, amount: (j + 1) / (float)(Amount + 2));
2452 m_Effects.DamageIndicator(Pos, Dir: direction(angle: Angle), Alpha: 1.0f);
2453 }
2454 }
2455 }
2456 }
2457 }
2458
2459 // Record m_LastRaceTick for g_Config.m_ClConfirmDisconnect/QuitTime
2460 if(m_GameInfo.m_Race &&
2461 Client()->State() == IClient::STATE_ONLINE &&
2462 m_Snap.m_pGameInfoObj &&
2463 !m_Snap.m_SpecInfo.m_Active &&
2464 m_Snap.m_pLocalCharacter &&
2465 m_Snap.m_pLocalPrevCharacter)
2466 {
2467 const bool RaceFlag = m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_RACETIME;
2468 m_LastRaceTick = RaceFlag ? -m_Snap.m_pGameInfoObj->m_WarmupTimer : -1;
2469 }
2470
2471 SnapCollectEntities(); // creates a collection that associates EntityEx snap items with the entities they belong to
2472
2473 UpdateLocalTuning();
2474 m_IsDummySwapping = 0;
2475 if(Client()->State() != IClient::STATE_DEMOPLAYBACK)
2476 UpdatePrediction();
2477}
2478
2479std::function<bool(int, int, int, int)> CGameClient::GetScoreComparator(bool TimeScore, bool ReceivedMillisecondFinishTimes, bool Race7)
2480{
2481 // 0.7 race score
2482 if(Race7)
2483 {
2484 auto CompareTimeMillis07 = [](int TimeMillis1, int TimeMillis2, int, int) {
2485 TimeMillis1 = TimeMillis1 == protocol7::FinishTime::NOT_FINISHED ? std::numeric_limits<int>::max() : TimeMillis1;
2486 TimeMillis2 = TimeMillis2 == protocol7::FinishTime::NOT_FINISHED ? std::numeric_limits<int>::max() : TimeMillis2;
2487 return TimeMillis1 < TimeMillis2;
2488 };
2489 return CompareTimeMillis07;
2490 }
2491
2492 // normal scores (like points), biggest score is highest in scoreboard
2493 if(!TimeScore)
2494 {
2495 auto CompareScore = [](int Score1, int Score2, int, int) {
2496 return Score1 > Score2;
2497 };
2498 return CompareScore;
2499 }
2500
2501 // 'classical' times, times are send negative, so biggest value has shortest time
2502 if(!ReceivedMillisecondFinishTimes)
2503 {
2504 auto CompareTimeScore = [](int TimeScore1, int TimeScore2, int, int) {
2505 TimeScore1 = TimeScore1 == FinishTime::NOT_FINISHED_TIMESCORE ? std::numeric_limits<int>::min() : TimeScore1;
2506 TimeScore2 = TimeScore2 == FinishTime::NOT_FINISHED_TIMESCORE ? std::numeric_limits<int>::min() : TimeScore2;
2507 return TimeScore1 > TimeScore2;
2508 };
2509 return CompareTimeScore;
2510 }
2511
2512 // long precise times, smallest value first, subsorting by milliseconds
2513 auto CompareTimeMillis = [](int TimeSeconds1, int TimeSeconds2, int TimeMillis1, int TimeMillis2) {
2514 TimeSeconds1 = TimeSeconds1 == FinishTime::NOT_FINISHED_MILLIS ? std::numeric_limits<int>::max() : TimeSeconds1;
2515 TimeSeconds2 = TimeSeconds2 == FinishTime::NOT_FINISHED_MILLIS ? std::numeric_limits<int>::max() : TimeSeconds2;
2516 if(TimeSeconds1 == TimeSeconds2)
2517 return TimeMillis1 < TimeMillis2;
2518 return TimeSeconds1 < TimeSeconds2;
2519 };
2520 return CompareTimeMillis;
2521}
2522
2523void CGameClient::UpdateEditorIngameMoved()
2524{
2525 const bool LocalCharacterMoved = m_Snap.m_pLocalCharacter && m_Snap.m_pLocalPrevCharacter && (m_Snap.m_pLocalCharacter->m_X != m_Snap.m_pLocalPrevCharacter->m_X || m_Snap.m_pLocalCharacter->m_Y != m_Snap.m_pLocalPrevCharacter->m_Y);
2526 if(!g_Config.m_ClEditor)
2527 {
2528 m_EditorMovementDelay = 5;
2529 }
2530 else if(m_EditorMovementDelay > 0 && !LocalCharacterMoved)
2531 {
2532 --m_EditorMovementDelay;
2533 }
2534 if(m_EditorMovementDelay == 0 && LocalCharacterMoved)
2535 {
2536 Editor()->OnIngameMoved();
2537 }
2538}
2539
2540void CGameClient::ApplyPreInputs(int Tick, bool Direct, CGameWorld &GameWorld)
2541{
2542 if(!g_Config.m_ClAntiPingPreInput)
2543 return;
2544
2545 for(int ClientId = 0; ClientId < MAX_CLIENTS; ClientId++)
2546 {
2547 if(CCharacter *pChar = GameWorld.GetCharacterById(Id: ClientId))
2548 {
2549 if(ClientId == m_aLocalIds[0] || (Client()->DummyConnected() && ClientId == m_aLocalIds[1]))
2550 continue;
2551
2552 const CNetMsg_Sv_PreInput PreInput = m_aClients[ClientId].m_aPreInputs[Tick % 200];
2553 if(PreInput.m_IntendedTick != Tick)
2554 continue;
2555
2556 //convert preinput to input
2557 CNetObj_PlayerInput Input = {.m_Direction: 0};
2558 Input.m_Direction = PreInput.m_Direction;
2559 Input.m_TargetX = PreInput.m_TargetX;
2560 Input.m_TargetY = PreInput.m_TargetY;
2561 Input.m_Jump = PreInput.m_Jump;
2562 Input.m_Fire = PreInput.m_Fire;
2563 Input.m_Hook = PreInput.m_Hook;
2564 Input.m_WantedWeapon = PreInput.m_WantedWeapon;
2565 Input.m_NextWeapon = PreInput.m_NextWeapon;
2566 Input.m_PrevWeapon = PreInput.m_PrevWeapon;
2567
2568 if(Direct)
2569 {
2570 pChar->OnDirectInput(pNewInput: &Input);
2571 }
2572 else
2573 {
2574 pChar->OnPredictedInput(pNewInput: &Input);
2575 }
2576 }
2577 }
2578}
2579
2580void CGameClient::OnPredict()
2581{
2582 // store the previous values so we can detect prediction errors
2583 CCharacterCore BeforePrevChar = m_PredictedPrevChar;
2584 CCharacterCore BeforeChar = m_PredictedChar;
2585
2586 // we can't predict without our own id or own character
2587 if(m_Snap.m_LocalClientId == -1 || !m_Snap.m_aCharacters[m_Snap.m_LocalClientId].m_Active)
2588 return;
2589
2590 // don't predict anything if we are paused
2591 if(m_Snap.m_pGameInfoObj && m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_PAUSED)
2592 {
2593 if(m_Snap.m_pLocalCharacter)
2594 {
2595 m_PredictedChar.Read(pObjCore: m_Snap.m_pLocalCharacter);
2596 m_PredictedChar.m_ActiveWeapon = m_Snap.m_pLocalCharacter->m_Weapon;
2597 }
2598 if(m_Snap.m_pLocalPrevCharacter)
2599 {
2600 m_PredictedPrevChar.Read(pObjCore: m_Snap.m_pLocalPrevCharacter);
2601 m_PredictedPrevChar.m_ActiveWeapon = m_Snap.m_pLocalPrevCharacter->m_Weapon;
2602 }
2603 return;
2604 }
2605
2606 vec2 aBeforeRender[MAX_CLIENTS];
2607 for(int i = 0; i < MAX_CLIENTS; i++)
2608 aBeforeRender[i] = GetSmoothPos(ClientId: i);
2609
2610 // init
2611 bool Dummy = g_Config.m_ClDummy ^ m_IsDummySwapping;
2612
2613 // PredictedEvents are only handled in predicted world, so update them here
2614 m_GameWorld.m_PredictedEvents = m_PredictedWorld.m_PredictedEvents;
2615 m_PredictedWorld.CopyWorld(pFrom: &m_GameWorld);
2616
2617 // don't predict inactive players, or entities from other teams
2618 for(int i = 0; i < MAX_CLIENTS; i++)
2619 if(CCharacter *pChar = m_PredictedWorld.GetCharacterById(Id: i))
2620 if((!m_Snap.m_aCharacters[i].m_Active && pChar->m_SnapTicks > 10) || IsOtherTeam(ClientId: i))
2621 pChar->Destroy();
2622
2623 {
2624 CGameWorld::CEntityIterator Iterator(&m_PredictedWorld, CGameWorld::ENTTYPE_PROJECTILE);
2625 while(CProjectile *pProj = static_cast<CProjectile *>(Iterator.Next()))
2626 {
2627 if(IsOtherTeam(ClientId: pProj->GetOwner()))
2628 {
2629 pProj->Destroy();
2630 }
2631 }
2632 }
2633
2634 CCharacter *pLocalChar = m_PredictedWorld.GetCharacterById(Id: m_Snap.m_LocalClientId);
2635 if(!pLocalChar)
2636 return;
2637 CCharacter *pDummyChar = nullptr;
2638 if(PredictDummy())
2639 pDummyChar = m_PredictedWorld.GetCharacterById(Id: m_aLocalIds[!g_Config.m_ClDummy]);
2640
2641 int PredictionTick = Client()->GetPredictionTick();
2642 // predict
2643 for(int Tick = Client()->GameTick(Conn: g_Config.m_ClDummy) + 1; Tick <= Client()->PredGameTick(Conn: g_Config.m_ClDummy); Tick++)
2644 {
2645 // fetch the previous characters
2646 if(Tick == PredictionTick)
2647 {
2648 for(int i = 0; i < MAX_CLIENTS; i++)
2649 if(CCharacter *pChar = m_PredictedWorld.GetCharacterById(Id: i))
2650 m_aClients[i].m_PrevPredicted = pChar->GetCore();
2651 }
2652
2653 if(Tick == Client()->PredGameTick(Conn: g_Config.m_ClDummy))
2654 {
2655 m_PredictedPrevChar = pLocalChar->GetCore();
2656 m_aClients[m_Snap.m_LocalClientId].m_PrevPredicted = pLocalChar->GetCore();
2657
2658 if(pDummyChar)
2659 m_aClients[m_aLocalIds[!g_Config.m_ClDummy]].m_PrevPredicted = pDummyChar->GetCore();
2660 }
2661
2662 // optionally allow some movement in freeze by not predicting freeze the last one to two ticks
2663 if(g_Config.m_ClPredictFreeze == 2 && Client()->PredGameTick(Conn: g_Config.m_ClDummy) - 1 - Client()->PredGameTick(Conn: g_Config.m_ClDummy) % 2 <= Tick)
2664 pLocalChar->m_CanMoveInFreeze = true;
2665
2666 // apply inputs and tick
2667 CNetObj_PlayerInput *pInputData = (CNetObj_PlayerInput *)Client()->GetInput(Tick, IsDummy: m_IsDummySwapping);
2668 CNetObj_PlayerInput *pDummyInputData = !pDummyChar ? nullptr : (CNetObj_PlayerInput *)Client()->GetInput(Tick, IsDummy: m_IsDummySwapping ^ 1);
2669 bool DummyFirst = pInputData && pDummyInputData && pDummyChar->GetCid() < pLocalChar->GetCid();
2670
2671 if(DummyFirst)
2672 pDummyChar->OnDirectInput(pNewInput: pDummyInputData);
2673 if(pInputData)
2674 pLocalChar->OnDirectInput(pNewInput: pInputData);
2675 if(pDummyInputData && !DummyFirst)
2676 pDummyChar->OnDirectInput(pNewInput: pDummyInputData);
2677
2678 ApplyPreInputs(Tick, Direct: true, GameWorld&: m_PredictedWorld);
2679
2680 m_PredictedWorld.m_GameTick = Tick;
2681 if(pInputData)
2682 pLocalChar->OnPredictedInput(pNewInput: pInputData);
2683 if(pDummyInputData)
2684 pDummyChar->OnPredictedInput(pNewInput: pDummyInputData);
2685
2686 ApplyPreInputs(Tick, Direct: false, GameWorld&: m_PredictedWorld);
2687
2688 m_PredictedWorld.Tick();
2689
2690 // fetch the current characters
2691 if(Tick == PredictionTick)
2692 {
2693 m_PrevPredictedWorld.CopyWorld(pFrom: &m_PredictedWorld);
2694
2695 for(int i = 0; i < MAX_CLIENTS; i++)
2696 if(CCharacter *pChar = m_PredictedWorld.GetCharacterById(Id: i))
2697 m_aClients[i].m_Predicted = pChar->GetCore();
2698 }
2699
2700 if(Tick == Client()->PredGameTick(Conn: g_Config.m_ClDummy))
2701 {
2702 m_PredictedChar = pLocalChar->GetCore();
2703 m_aClients[m_Snap.m_LocalClientId].m_Predicted = pLocalChar->GetCore();
2704
2705 if(pDummyChar)
2706 m_aClients[m_aLocalIds[!g_Config.m_ClDummy]].m_Predicted = pDummyChar->GetCore();
2707 }
2708
2709 for(int i = 0; i < MAX_CLIENTS; i++)
2710 if(CCharacter *pChar = m_PredictedWorld.GetCharacterById(Id: i))
2711 {
2712 m_aClients[i].m_aPredPos[Tick % 200] = pChar->Core()->m_Pos;
2713 m_aClients[i].m_aPredTick[Tick % 200] = Tick;
2714 }
2715
2716 // check if we want to trigger effects
2717 if(Tick > m_aLastNewPredictedTick[Dummy])
2718 {
2719 m_aLastNewPredictedTick[Dummy] = Tick;
2720 m_NewPredictedTick = true;
2721 vec2 Pos = pLocalChar->Core()->m_Pos;
2722 int Events = pLocalChar->Core()->m_TriggeredEvents;
2723 if(g_Config.m_ClPredict && !m_SuppressEvents)
2724 if(Events & COREEVENT_AIR_JUMP)
2725 m_Effects.AirJump(Pos, Alpha: 1.0f, Volume: 1.0f);
2726 if(g_Config.m_SndGame && !m_SuppressEvents)
2727 {
2728 if(Events & COREEVENT_GROUND_JUMP)
2729 m_Sounds.PlayAndRecord(Channel: CSounds::CHN_WORLD, SetId: SOUND_PLAYER_JUMP, Volume: 1.0f, Position: Pos);
2730 if(Events & COREEVENT_HOOK_ATTACH_GROUND)
2731 m_Sounds.PlayAndRecord(Channel: CSounds::CHN_WORLD, SetId: SOUND_HOOK_ATTACH_GROUND, Volume: 1.0f, Position: Pos);
2732 if(Events & COREEVENT_HOOK_HIT_NOHOOK)
2733 m_Sounds.PlayAndRecord(Channel: CSounds::CHN_WORLD, SetId: SOUND_HOOK_NOATTACH, Volume: 1.0f, Position: Pos);
2734 if(Events & COREEVENT_HOOK_ATTACH_PLAYER)
2735 {
2736 m_PredictedWorld.CreatePredictedSound(Pos, SoundId: SOUND_HOOK_ATTACH_PLAYER, Id: pLocalChar->GetCid());
2737 }
2738 }
2739 }
2740
2741 // check if we want to trigger predicted airjump for dummy
2742 if(AntiPingPlayers() && pDummyChar && Tick > m_aLastNewPredictedTick[!Dummy])
2743 {
2744 m_aLastNewPredictedTick[!Dummy] = Tick;
2745 vec2 Pos = pDummyChar->Core()->m_Pos;
2746 int Events = pDummyChar->Core()->m_TriggeredEvents;
2747 if(g_Config.m_ClPredict && !m_SuppressEvents)
2748 if(Events & COREEVENT_AIR_JUMP)
2749 m_Effects.AirJump(Pos, Alpha: 1.0f, Volume: 1.0f);
2750 }
2751
2752 HandlePredictedEvents(Tick);
2753 }
2754
2755 // detect mispredictions of other players and make corrections smoother when possible
2756 if(g_Config.m_ClAntiPingSmooth && Predict() && AntiPingPlayers() && m_NewTick && m_PredictedTick >= MIN_TICK && absolute(a: m_PredictedTick - Client()->PredGameTick(Conn: g_Config.m_ClDummy)) <= 1 && absolute(a: Client()->GameTick(Conn: g_Config.m_ClDummy) - Client()->PrevGameTick(Conn: g_Config.m_ClDummy)) <= 2)
2757 {
2758 int PredTime = std::clamp(val: Client()->GetPredictionTime(), lo: 0, hi: 800);
2759 float SmoothPace = 4 - 1.5f * PredTime / 800.f; // smoothing pace (a lower value will make the smoothing quicker)
2760 int64_t Len = 1000 * PredTime * SmoothPace;
2761
2762 for(int i = 0; i < MAX_CLIENTS; i++)
2763 {
2764 if(!m_Snap.m_aCharacters[i].m_Active || i == m_Snap.m_LocalClientId || !m_aLastActive[i])
2765 continue;
2766 vec2 NewPos = (m_PredictedTick == Client()->PredGameTick(Conn: g_Config.m_ClDummy)) ? m_aClients[i].m_Predicted.m_Pos : m_aClients[i].m_PrevPredicted.m_Pos;
2767 vec2 PredErr = (m_aLastPos[i] - NewPos) / (float)std::min(a: Client()->GetPredictionTime(), b: 200);
2768 if(in_range(a: length(a: PredErr), lower: 0.05f, upper: 5.f))
2769 {
2770 vec2 PredPos = mix(a: m_aClients[i].m_PrevPredicted.m_Pos, b: m_aClients[i].m_Predicted.m_Pos, amount: Client()->PredIntraGameTick(Conn: g_Config.m_ClDummy));
2771 vec2 CurPos = mix(
2772 a: vec2(m_Snap.m_aCharacters[i].m_Prev.m_X, m_Snap.m_aCharacters[i].m_Prev.m_Y),
2773 b: vec2(m_Snap.m_aCharacters[i].m_Cur.m_X, m_Snap.m_aCharacters[i].m_Cur.m_Y),
2774 amount: Client()->IntraGameTick(Conn: g_Config.m_ClDummy));
2775 vec2 RenderDiff = PredPos - aBeforeRender[i];
2776 vec2 PredDiff = PredPos - CurPos;
2777
2778 float aMixAmount[2];
2779 for(int j = 0; j < 2; j++)
2780 {
2781 aMixAmount[j] = 1.0f;
2782 if(absolute(a: PredErr[j]) > 0.05f)
2783 {
2784 aMixAmount[j] = 0.0f;
2785 if(absolute(a: RenderDiff[j]) > 0.01f)
2786 {
2787 aMixAmount[j] = 1.f - std::clamp(val: RenderDiff[j] / PredDiff[j], lo: 0.f, hi: 1.f);
2788 aMixAmount[j] = 1.f - std::pow(x: 1.f - aMixAmount[j], y: 1 / 1.2f);
2789 }
2790 }
2791 int64_t TimePassed = time_get() - m_aClients[i].m_aSmoothStart[j];
2792 if(in_range(a: TimePassed, lower: (int64_t)0, upper: Len - 1))
2793 aMixAmount[j] = std::min(a: aMixAmount[j], b: (float)(TimePassed / (double)Len));
2794 }
2795 for(int j = 0; j < 2; j++)
2796 if(absolute(a: RenderDiff[j]) < 0.01f && absolute(a: PredDiff[j]) < 0.01f && absolute(a: m_aClients[i].m_PrevPredicted.m_Pos[j] - m_aClients[i].m_Predicted.m_Pos[j]) < 0.01f && aMixAmount[j] > aMixAmount[j ^ 1])
2797 aMixAmount[j] = aMixAmount[j ^ 1];
2798 for(int j = 0; j < 2; j++)
2799 {
2800 // don't smooth for longer than 700ms, or more than 300ms longer along one axis than the other axis
2801 int64_t Remaining = std::min(l: {
2802 (1.f - aMixAmount[j]) * Len,
2803 time_freq() * 0.700f,
2804 (1.f - aMixAmount[j ^ 1]) * Len + time_freq() * 0.300f,
2805 });
2806 int64_t Start = time_get() - (Len - Remaining);
2807 if(!in_range(a: Start + Len, lower: m_aClients[i].m_aSmoothStart[j], upper: m_aClients[i].m_aSmoothStart[j] + Len))
2808 {
2809 m_aClients[i].m_aSmoothStart[j] = Start;
2810 m_aClients[i].m_aSmoothLen[j] = Len;
2811 }
2812 }
2813 }
2814 }
2815 }
2816
2817 for(int i = 0; i < MAX_CLIENTS; i++)
2818 {
2819 if(m_Snap.m_aCharacters[i].m_Active)
2820 {
2821 m_aLastPos[i] = m_aClients[i].m_Predicted.m_Pos;
2822 m_aLastActive[i] = true;
2823 }
2824 else
2825 {
2826 m_aLastActive[i] = false;
2827 }
2828 }
2829
2830 if(g_Config.m_Debug && g_Config.m_ClPredict && m_PredictedTick == Client()->PredGameTick(Conn: g_Config.m_ClDummy))
2831 {
2832 CNetObj_CharacterCore Before = {.m_Tick: 0}, Now = {.m_Tick: 0}, BeforePrev = {.m_Tick: 0}, NowPrev = {.m_Tick: 0};
2833 BeforeChar.Write(pObjCore: &Before);
2834 BeforePrevChar.Write(pObjCore: &BeforePrev);
2835 m_PredictedChar.Write(pObjCore: &Now);
2836 m_PredictedPrevChar.Write(pObjCore: &NowPrev);
2837
2838 if(mem_comp(a: &Before, b: &Now, size: sizeof(CNetObj_CharacterCore)) != 0)
2839 {
2840 log_trace("client", "prediction error");
2841 for(unsigned i = 0; i < sizeof(CNetObj_CharacterCore) / sizeof(int); i++)
2842 {
2843 if(((int *)&Before)[i] != ((int *)&Now)[i])
2844 {
2845 log_trace("client", " %d %d %d (%d %d)", i, ((int *)&Before)[i], ((int *)&Now)[i], ((int *)&BeforePrev)[i], ((int *)&NowPrev)[i]);
2846 }
2847 }
2848 }
2849 }
2850
2851 m_PredictedTick = Client()->PredGameTick(Conn: g_Config.m_ClDummy);
2852
2853 if(m_NewPredictedTick)
2854 m_Ghost.OnNewPredictedSnapshot();
2855}
2856
2857void CGameClient::OnActivateEditor()
2858{
2859 OnRelease();
2860}
2861
2862CGameClient::CClientStats::CClientStats()
2863{
2864 Reset();
2865}
2866
2867void CGameClient::CClientStats::Reset()
2868{
2869 m_JoinTick = 0;
2870 m_IngameTicks = 0;
2871 m_Active = false;
2872
2873 std::fill(first: std::begin(arr&: m_aFragsWith), last: std::end(arr&: m_aFragsWith), value: 0);
2874 std::fill(first: std::begin(arr&: m_aDeathsFrom), last: std::end(arr&: m_aDeathsFrom), value: 0);
2875 m_Frags = 0;
2876 m_Deaths = 0;
2877 m_Suicides = 0;
2878 m_BestSpree = 0;
2879 m_CurrentSpree = 0;
2880
2881 m_FlagGrabs = 0;
2882 m_FlagCaptures = 0;
2883}
2884
2885void CGameClient::CClientData::UpdateSkinInfo()
2886{
2887 const CSkinDescriptor SkinDescriptor = ToSkinDescriptor();
2888 if(SkinDescriptor.m_Flags == 0)
2889 {
2890 return;
2891 }
2892
2893 const auto &&ApplySkinProperties = [&]() {
2894 if(SkinDescriptor.m_Flags & CSkinDescriptor::FLAG_SIX)
2895 {
2896 m_pSkinInfo->TeeRenderInfo().ApplyColors(CustomColoredSkin: m_UseCustomColor, ColorBody: m_ColorBody, ColorFeet: m_ColorFeet);
2897 }
2898 if(SkinDescriptor.m_Flags & CSkinDescriptor::FLAG_SEVEN)
2899 {
2900 for(int Dummy = 0; Dummy < NUM_DUMMIES; Dummy++)
2901 {
2902 const CClientData::CSixup &SixupData = m_aSixup[Dummy];
2903 CTeeRenderInfo::CSixup &SixupSkinInfo = m_pSkinInfo->TeeRenderInfo().m_aSixup[Dummy];
2904 for(int Part = 0; Part < protocol7::NUM_SKINPARTS; Part++)
2905 {
2906 m_pGameClient->m_Skins7.ApplyColorTo(SixupRenderInfo&: SixupSkinInfo, UseCustomColors: SixupData.m_aUseCustomColors[Part], Value: SixupData.m_aSkinPartColors[Part], Part);
2907 }
2908 UpdateSkin7HatSprite(Dummy);
2909 UpdateSkin7BotDecoration(Dummy);
2910 }
2911 }
2912 m_pSkinInfo->TeeRenderInfo().m_Size = 64.0f;
2913 };
2914
2915 if(m_pSkinInfo == nullptr)
2916 {
2917 CTeeRenderInfo TeeRenderInfo;
2918 m_pSkinInfo = m_pGameClient->CreateManagedTeeRenderInfo(TeeRenderInfo, SkinDescriptor);
2919 m_pSkinInfo->SetRefreshCallback([&]() { UpdateRenderInfo(); });
2920 ApplySkinProperties();
2921 m_pSkinInfo->m_RefreshCallback();
2922 }
2923 else if(m_pSkinInfo->SkinDescriptor() != SkinDescriptor)
2924 {
2925 m_pSkinInfo->m_SkinDescriptor = SkinDescriptor;
2926 m_pGameClient->RefreshSkin(pManagedTeeRenderInfo: m_pSkinInfo);
2927 ApplySkinProperties();
2928 }
2929 else
2930 {
2931 ApplySkinProperties();
2932 m_pSkinInfo->m_RefreshCallback();
2933 }
2934}
2935
2936void CGameClient::CClientData::UpdateRenderInfo()
2937{
2938 m_RenderInfo = m_pSkinInfo->TeeRenderInfo();
2939
2940 // force team colors
2941 if(m_pGameClient->IsTeamPlay())
2942 {
2943 m_RenderInfo.m_CustomColoredSkin = true;
2944 for(auto &Sixup : m_RenderInfo.m_aSixup)
2945 {
2946 std::fill(first: std::begin(arr&: Sixup.m_aUseCustomColors), last: std::end(arr&: Sixup.m_aUseCustomColors), value: true);
2947 }
2948
2949 if(m_Team >= TEAM_RED && m_Team <= TEAM_BLUE)
2950 {
2951 const int aTeamColors[2] = {65461, 10223541};
2952 m_RenderInfo.m_ColorBody = color_cast<ColorRGBA>(hsl: ColorHSLA(aTeamColors[m_Team]));
2953 m_RenderInfo.m_ColorFeet = color_cast<ColorRGBA>(hsl: ColorHSLA(aTeamColors[m_Team]));
2954
2955 // 0.7
2956 for(auto &Sixup : m_RenderInfo.m_aSixup)
2957 {
2958 const ColorRGBA aTeamColorsSixup[2] = {
2959 ColorRGBA(0.753f, 0.318f, 0.318f, 1.0f),
2960 ColorRGBA(0.318f, 0.471f, 0.753f, 1.0f)};
2961 const ColorRGBA aMarkingColorsSixup[2] = {
2962 ColorRGBA(0.824f, 0.345f, 0.345f, 1.0f),
2963 ColorRGBA(0.345f, 0.514f, 0.824f, 1.0f)};
2964 float MarkingAlpha = Sixup.m_aColors[protocol7::SKINPART_MARKING].a;
2965 for(auto &Color : Sixup.m_aColors)
2966 {
2967 Color = aTeamColorsSixup[m_Team];
2968 }
2969 if(MarkingAlpha > 0.1f)
2970 {
2971 Sixup.m_aColors[protocol7::SKINPART_MARKING] = aMarkingColorsSixup[m_Team];
2972 }
2973 }
2974 }
2975 else
2976 {
2977 m_RenderInfo.m_ColorBody = color_cast<ColorRGBA>(hsl: ColorHSLA(12829350));
2978 m_RenderInfo.m_ColorFeet = color_cast<ColorRGBA>(hsl: ColorHSLA(12829350));
2979 for(auto &Sixup : m_RenderInfo.m_aSixup)
2980 {
2981 for(auto &Color : Sixup.m_aColors)
2982 {
2983 Color = color_cast<ColorRGBA>(hsl: ColorHSLA(12829350));
2984 }
2985 }
2986 }
2987 }
2988}
2989
2990void CGameClient::CClientData::Reset()
2991{
2992 m_UseCustomColor = 0;
2993 m_ColorBody = 0;
2994 m_ColorFeet = 0;
2995
2996 m_aName[0] = '\0';
2997 m_aClan[0] = '\0';
2998 m_Country = CountryCode::DEFAULT;
2999 str_copy(dst&: m_aSkinName, src: "default");
3000
3001 m_Team = 0;
3002 m_Emoticon = 0;
3003 m_EmoticonStartFraction = 0;
3004 m_EmoticonStartTick = -1;
3005
3006 m_Solo = false;
3007 m_Jetpack = false;
3008 m_CollisionDisabled = false;
3009 m_EndlessHook = false;
3010 m_EndlessJump = false;
3011 m_HammerHitDisabled = false;
3012 m_GrenadeHitDisabled = false;
3013 m_LaserHitDisabled = false;
3014 m_ShotgunHitDisabled = false;
3015 m_HookHitDisabled = false;
3016 m_Super = false;
3017 m_Invincible = false;
3018 m_HasTelegunGun = false;
3019 m_HasTelegunGrenade = false;
3020 m_HasTelegunLaser = false;
3021 m_FreezeEnd = 0;
3022 m_DeepFrozen = false;
3023 m_LiveFrozen = false;
3024
3025 m_Predicted.Reset();
3026 m_PrevPredicted.Reset();
3027
3028 if(m_pSkinInfo != nullptr)
3029 {
3030 // Make sure other `shared_ptr`s to this skin info will not use the refresh callback that refers to this reset client data
3031 m_pSkinInfo->SetRefreshCallback(nullptr);
3032 m_pSkinInfo = nullptr;
3033 }
3034 m_RenderInfo.Reset();
3035
3036 m_Angle = 0.0f;
3037 m_Active = false;
3038 m_ChatIgnore = false;
3039 m_EmoticonIgnore = false;
3040 m_Friend = false;
3041 m_Foe = false;
3042
3043 m_AuthLevel = AUTHED_NO;
3044 m_Afk = false;
3045 m_Paused = false;
3046 m_Spec = false;
3047
3048 std::fill(first: std::begin(arr&: m_aSwitchStates), last: std::end(arr&: m_aSwitchStates), value: 0);
3049
3050 m_Snapped.m_Tick = -1;
3051 m_Evolved.m_Tick = -1;
3052
3053 for(auto &PreInput : m_aPreInputs)
3054 {
3055 PreInput.m_IntendedTick = -1;
3056 }
3057
3058 m_RenderCur.m_Tick = -1;
3059 m_RenderPrev.m_Tick = -1;
3060 m_RenderPos = vec2(0.0f, 0.0f);
3061 m_IsPredicted = false;
3062 m_IsPredictedLocal = false;
3063 std::fill(first: std::begin(arr&: m_aSmoothStart), last: std::end(arr&: m_aSmoothStart), value: 0);
3064 std::fill(first: std::begin(arr&: m_aSmoothLen), last: std::end(arr&: m_aSmoothLen), value: 0);
3065 std::fill(first: std::begin(arr&: m_aPredPos), last: std::end(arr&: m_aPredPos), value: vec2(0.0f, 0.0f));
3066 std::fill(first: std::begin(arr&: m_aPredTick), last: std::end(arr&: m_aPredTick), value: 0);
3067 m_SpecCharPresent = false;
3068 m_SpecChar = vec2(0.0f, 0.0f);
3069
3070 for(auto &Info : m_aSixup)
3071 Info.Reset();
3072}
3073
3074CSkinDescriptor CGameClient::CClientData::ToSkinDescriptor() const
3075{
3076 CSkinDescriptor SkinDescriptor;
3077
3078 CTranslationContext::CClientData &TranslatedClient = m_pGameClient->m_pClient->m_TranslationContext.m_aClients[ClientId()];
3079 if(m_Active && !TranslatedClient.m_Active)
3080 {
3081 SkinDescriptor.m_Flags |= CSkinDescriptor::FLAG_SIX;
3082 str_copy(dst&: SkinDescriptor.m_aSkinName, src: m_aSkinName);
3083 }
3084 else if(TranslatedClient.m_Active)
3085 {
3086 SkinDescriptor.m_Flags |= CSkinDescriptor::FLAG_SEVEN;
3087 for(int Dummy = 0; Dummy < NUM_DUMMIES; Dummy++)
3088 {
3089 for(int Part = 0; Part < protocol7::NUM_SKINPARTS; Part++)
3090 {
3091 str_copy(dst&: SkinDescriptor.m_aSixup[Dummy].m_aaSkinPartNames[Part], src: m_aSixup[Dummy].m_aaSkinPartNames[Part]);
3092 }
3093 SkinDescriptor.m_aSixup[Dummy].m_XmasHat = time_season() == ETimeSeason::XMAS;
3094 SkinDescriptor.m_aSixup[Dummy].m_BotDecoration = (TranslatedClient.m_PlayerFlags7 & protocol7::PLAYERFLAG_BOT) != 0;
3095 }
3096 }
3097
3098 return SkinDescriptor;
3099}
3100
3101void CGameClient::CClientData::CSixup::Reset()
3102{
3103 for(int i = 0; i < protocol7::NUM_SKINPARTS; ++i)
3104 {
3105 m_aaSkinPartNames[i][0] = '\0';
3106 m_aUseCustomColors[i] = 0;
3107 m_aSkinPartColors[i] = 0;
3108 }
3109}
3110
3111void CGameClient::SendSwitchTeam(int Team) const
3112{
3113 CNetMsg_Cl_SetTeam Msg;
3114 Msg.m_Team = Team;
3115 Client()->SendPackMsgActive(pMsg: &Msg, Flags: MSGFLAG_VITAL);
3116}
3117
3118void CGameClient::SendStartInfo7(bool Dummy)
3119{
3120 protocol7::CNetMsg_Cl_StartInfo Msg;
3121 Msg.m_pName = Dummy ? Client()->DummyName() : Client()->PlayerName();
3122 Msg.m_pClan = Dummy ? Config()->m_ClDummyClan : Config()->m_PlayerClan;
3123 Msg.m_Country = Dummy ? Config()->m_ClDummyCountry : Config()->m_PlayerCountry;
3124 for(int p = 0; p < protocol7::NUM_SKINPARTS; p++)
3125 {
3126 Msg.m_apSkinPartNames[p] = CSkins7::ms_apSkinVariables[(int)Dummy][p];
3127 Msg.m_aUseCustomColors[p] = *CSkins7::ms_apUCCVariables[(int)Dummy][p];
3128 Msg.m_aSkinPartColors[p] = *CSkins7::ms_apColorVariables[(int)Dummy][p];
3129 }
3130 CMsgPacker Packer(&Msg, false, true);
3131 if(Msg.Pack(pPacker: &Packer))
3132 return;
3133 Client()->SendMsg(Conn: (int)Dummy, pMsg: &Packer, Flags: MSGFLAG_VITAL | MSGFLAG_FLUSH);
3134 m_aCheckInfo[(int)Dummy] = -1;
3135}
3136
3137void CGameClient::SendSkinChange7(bool Dummy)
3138{
3139 protocol7::CNetMsg_Cl_SkinChange Msg;
3140 for(int p = 0; p < protocol7::NUM_SKINPARTS; p++)
3141 {
3142 Msg.m_apSkinPartNames[p] = CSkins7::ms_apSkinVariables[(int)Dummy][p];
3143 Msg.m_aUseCustomColors[p] = *CSkins7::ms_apUCCVariables[(int)Dummy][p];
3144 Msg.m_aSkinPartColors[p] = *CSkins7::ms_apColorVariables[(int)Dummy][p];
3145 }
3146 CMsgPacker Packer(&Msg, false, true);
3147 if(Msg.Pack(pPacker: &Packer))
3148 return;
3149 Client()->SendMsg(Conn: (int)Dummy, pMsg: &Packer, Flags: MSGFLAG_VITAL | MSGFLAG_FLUSH);
3150 m_aCheckInfo[(int)Dummy] = Client()->GameTickSpeed();
3151}
3152
3153bool CGameClient::GotWantedSkin7(bool Dummy)
3154{
3155 // validate the wanted skinparts before comparison
3156 // because the skin parts we compare against are also validated
3157 // otherwise it tries to resend the skin info when the eyes are set to "negative"
3158 // in team based modes
3159 char aSkinParts[protocol7::NUM_SKINPARTS][protocol7::MAX_SKIN_ARRAY_SIZE];
3160 char *apSkinPartsPtr[protocol7::NUM_SKINPARTS];
3161 int aUCCVars[protocol7::NUM_SKINPARTS];
3162 int aColorVars[protocol7::NUM_SKINPARTS];
3163 for(int SkinPart = 0; SkinPart < protocol7::NUM_SKINPARTS; SkinPart++)
3164 {
3165 str_copy(dst: aSkinParts[SkinPart], src: CSkins7::ms_apSkinVariables[(int)Dummy][SkinPart], dst_size: protocol7::MAX_SKIN_ARRAY_SIZE);
3166 apSkinPartsPtr[SkinPart] = aSkinParts[SkinPart];
3167 aUCCVars[SkinPart] = *CSkins7::ms_apUCCVariables[(int)Dummy][SkinPart];
3168 aColorVars[SkinPart] = *CSkins7::ms_apColorVariables[(int)Dummy][SkinPart];
3169 }
3170 m_Skins7.ValidateSkinParts(apPartNames: apSkinPartsPtr, pUseCustomColors: aUCCVars, pPartColors: aColorVars, GameFlags: m_pClient->m_TranslationContext.m_GameFlags);
3171
3172 for(int SkinPart = 0; SkinPart < protocol7::NUM_SKINPARTS; SkinPart++)
3173 {
3174 if(str_comp(a: m_aClients[m_aLocalIds[(int)Dummy]].m_aSixup[g_Config.m_ClDummy].m_aaSkinPartNames[SkinPart], b: apSkinPartsPtr[SkinPart]))
3175 return false;
3176 if(m_aClients[m_aLocalIds[(int)Dummy]].m_aSixup[g_Config.m_ClDummy].m_aUseCustomColors[SkinPart] != aUCCVars[SkinPart])
3177 return false;
3178 if(m_aClients[m_aLocalIds[(int)Dummy]].m_aSixup[g_Config.m_ClDummy].m_aSkinPartColors[SkinPart] != aColorVars[SkinPart])
3179 return false;
3180 }
3181
3182 // TODO: add name change ddnet extension to 0.7 protocol
3183 // if(str_comp(m_aClients[m_aLocalIds[(int)Dummy]].m_aName, Dummy ? Client()->DummyName() : Client()->PlayerName()))
3184 // return false;
3185 // if(str_comp(m_aClients[m_aLocalIds[(int)Dummy]].m_aClan, Dummy ? g_Config.m_ClDummyClan : g_Config.m_PlayerClan))
3186 // return false;
3187 // if(m_aClients[m_aLocalIds[(int)Dummy]].m_Country != (Dummy ? g_Config.m_ClDummyCountry : g_Config.m_PlayerCountry))
3188 // return false;
3189
3190 return true;
3191}
3192
3193void CGameClient::SendInfo(bool Start)
3194{
3195 if(m_pClient->IsSixup())
3196 {
3197 if(Start)
3198 SendStartInfo7(Dummy: false);
3199 else
3200 SendSkinChange7(Dummy: false);
3201 return;
3202 }
3203 if(Start)
3204 {
3205 CNetMsg_Cl_StartInfo Msg;
3206 Msg.m_pName = Client()->PlayerName();
3207 Msg.m_pClan = g_Config.m_PlayerClan;
3208 Msg.m_Country = g_Config.m_PlayerCountry;
3209 Msg.m_pSkin = g_Config.m_ClPlayerSkin;
3210 Msg.m_UseCustomColor = g_Config.m_ClPlayerUseCustomColor;
3211 Msg.m_ColorBody = g_Config.m_ClPlayerColorBody;
3212 Msg.m_ColorFeet = g_Config.m_ClPlayerColorFeet;
3213 CMsgPacker Packer(&Msg);
3214 Msg.Pack(pPacker: &Packer);
3215 Client()->SendMsg(Conn: IClient::CONN_MAIN, pMsg: &Packer, Flags: MSGFLAG_VITAL | MSGFLAG_FLUSH);
3216 m_aCheckInfo[0] = -1;
3217 }
3218 else
3219 {
3220 CNetMsg_Cl_ChangeInfo Msg;
3221 Msg.m_pName = Client()->PlayerName();
3222 Msg.m_pClan = g_Config.m_PlayerClan;
3223 Msg.m_Country = g_Config.m_PlayerCountry;
3224 Msg.m_pSkin = g_Config.m_ClPlayerSkin;
3225 Msg.m_UseCustomColor = g_Config.m_ClPlayerUseCustomColor;
3226 Msg.m_ColorBody = g_Config.m_ClPlayerColorBody;
3227 Msg.m_ColorFeet = g_Config.m_ClPlayerColorFeet;
3228 CMsgPacker Packer(&Msg);
3229 Msg.Pack(pPacker: &Packer);
3230 Client()->SendMsg(Conn: IClient::CONN_MAIN, pMsg: &Packer, Flags: MSGFLAG_VITAL);
3231 m_aCheckInfo[0] = Client()->GameTickSpeed();
3232 }
3233}
3234
3235void CGameClient::SendDummyInfo(bool Start)
3236{
3237 if(m_pClient->IsSixup())
3238 {
3239 if(Start)
3240 SendStartInfo7(Dummy: true);
3241 else
3242 SendSkinChange7(Dummy: true);
3243 return;
3244 }
3245 if(Start)
3246 {
3247 CNetMsg_Cl_StartInfo Msg;
3248 Msg.m_pName = Client()->DummyName();
3249 Msg.m_pClan = g_Config.m_ClDummyClan;
3250 Msg.m_Country = g_Config.m_ClDummyCountry;
3251 Msg.m_pSkin = g_Config.m_ClDummySkin;
3252 Msg.m_UseCustomColor = g_Config.m_ClDummyUseCustomColor;
3253 Msg.m_ColorBody = g_Config.m_ClDummyColorBody;
3254 Msg.m_ColorFeet = g_Config.m_ClDummyColorFeet;
3255 CMsgPacker Packer(&Msg);
3256 Msg.Pack(pPacker: &Packer);
3257 Client()->SendMsg(Conn: IClient::CONN_DUMMY, pMsg: &Packer, Flags: MSGFLAG_VITAL);
3258 m_aCheckInfo[1] = -1;
3259 }
3260 else
3261 {
3262 CNetMsg_Cl_ChangeInfo Msg;
3263 Msg.m_pName = Client()->DummyName();
3264 Msg.m_pClan = g_Config.m_ClDummyClan;
3265 Msg.m_Country = g_Config.m_ClDummyCountry;
3266 Msg.m_pSkin = g_Config.m_ClDummySkin;
3267 Msg.m_UseCustomColor = g_Config.m_ClDummyUseCustomColor;
3268 Msg.m_ColorBody = g_Config.m_ClDummyColorBody;
3269 Msg.m_ColorFeet = g_Config.m_ClDummyColorFeet;
3270 CMsgPacker Packer(&Msg);
3271 Msg.Pack(pPacker: &Packer);
3272 Client()->SendMsg(Conn: IClient::CONN_DUMMY, pMsg: &Packer, Flags: MSGFLAG_VITAL);
3273 m_aCheckInfo[1] = Client()->GameTickSpeed();
3274 }
3275}
3276
3277void CGameClient::SendKill() const
3278{
3279 CNetMsg_Cl_Kill Msg;
3280 Client()->SendPackMsgActive(pMsg: &Msg, Flags: MSGFLAG_VITAL);
3281
3282 if(g_Config.m_ClDummyCopyMoves)
3283 {
3284 CMsgPacker MsgP(NETMSGTYPE_CL_KILL, false);
3285 Client()->SendMsg(Conn: !g_Config.m_ClDummy, pMsg: &MsgP, Flags: MSGFLAG_VITAL);
3286 }
3287}
3288
3289void CGameClient::SendReadyChange7() // NOLINT(readability-make-member-function-const)
3290{
3291 if(!Client()->IsSixup())
3292 {
3293 log_error("client", "You have to be connected to a 0.7 server to use 'ready_change'");
3294 return;
3295 }
3296 protocol7::CNetMsg_Cl_ReadyChange Msg;
3297 Client()->SendPackMsgActive(pMsg: &Msg, Flags: MSGFLAG_VITAL, NoTranslate: true);
3298}
3299
3300void CGameClient::ConTeam(IConsole::IResult *pResult, void *pUserData)
3301{
3302 ((CGameClient *)pUserData)->SendSwitchTeam(Team: pResult->GetInteger(Index: 0));
3303}
3304
3305void CGameClient::ConKill(IConsole::IResult *pResult, void *pUserData)
3306{
3307 ((CGameClient *)pUserData)->SendKill();
3308}
3309
3310void CGameClient::ConReadyChange7(IConsole::IResult *pResult, void *pUserData)
3311{
3312 CGameClient *pClient = static_cast<CGameClient *>(pUserData);
3313 if(pClient->Client()->State() == IClient::STATE_ONLINE)
3314 pClient->SendReadyChange7();
3315}
3316
3317void CGameClient::ConchainLanguageUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
3318{
3319 CGameClient *pThis = static_cast<CGameClient *>(pUserData);
3320 const bool Changed = pThis->Client()->GlobalTime() && pResult->NumArguments() && str_comp(a: pResult->GetString(Index: 0), b: g_Config.m_ClLanguagefile) != 0;
3321 pfnCallback(pResult, pCallbackUserData);
3322 if(Changed)
3323 {
3324 pThis->OnLanguageChange();
3325 }
3326}
3327
3328void CGameClient::ConchainSpecialInfoupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
3329{
3330 pfnCallback(pResult, pCallbackUserData);
3331 if(pResult->NumArguments())
3332 ((CGameClient *)pUserData)->SendInfo(Start: false);
3333}
3334
3335void CGameClient::ConchainSpecialDummyInfoupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
3336{
3337 pfnCallback(pResult, pCallbackUserData);
3338 if(pResult->NumArguments())
3339 ((CGameClient *)pUserData)->SendDummyInfo(Start: false);
3340}
3341
3342void CGameClient::ConchainSpecialDummy(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
3343{
3344 pfnCallback(pResult, pCallbackUserData);
3345 if(pResult->NumArguments())
3346 {
3347 if(g_Config.m_ClDummy && !((CGameClient *)pUserData)->Client()->DummyConnected())
3348 g_Config.m_ClDummy = 0;
3349 }
3350}
3351
3352IGameClient *CreateGameClient()
3353{
3354 return new CGameClient();
3355}
3356
3357int CGameClient::IntersectCharacter(vec2 HookPos, vec2 NewPos, vec2 &NewPos2, int OwnId, vec2 *pPlayerPosition)
3358{
3359 float Distance = 0.0f;
3360 int ClosestId = -1;
3361
3362 const CClientData &OwnClientData = m_aClients[OwnId];
3363
3364 for(int i = 0; i < MAX_CLIENTS; i++)
3365 {
3366 if(i == OwnId)
3367 continue;
3368
3369 const CClientData &Data = m_aClients[i];
3370
3371 if(!Data.m_Active || !m_Snap.m_aCharacters[i].m_Active)
3372 continue;
3373
3374 CNetObj_Character Prev = m_Snap.m_aCharacters[i].m_Prev;
3375 CNetObj_Character Player = m_Snap.m_aCharacters[i].m_Cur;
3376
3377 vec2 Position = mix(a: vec2(Prev.m_X, Prev.m_Y), b: vec2(Player.m_X, Player.m_Y), amount: Client()->IntraGameTick(Conn: g_Config.m_ClDummy));
3378
3379 bool IsOneSuper = Data.m_Super || OwnClientData.m_Super;
3380 bool IsOneSolo = Data.m_Solo || OwnClientData.m_Solo;
3381
3382 if(!IsOneSuper && (!m_Teams.SameTeam(ClientId1: i, ClientId2: OwnId) || IsOneSolo || OwnClientData.m_HookHitDisabled))
3383 continue;
3384
3385 vec2 ClosestPoint;
3386 if(closest_point_on_line(line_pointA: HookPos, line_pointB: NewPos, target_point: Position, out_pos&: ClosestPoint))
3387 {
3388 if(distance(a: Position, b: ClosestPoint) < CCharacterCore::PhysicalSize() + 2.0f)
3389 {
3390 if(ClosestId == -1 || distance(a: HookPos, b: Position) < Distance)
3391 {
3392 NewPos2 = ClosestPoint;
3393 ClosestId = i;
3394 Distance = distance(a: HookPos, b: Position);
3395 if(pPlayerPosition)
3396 *pPlayerPosition = Position;
3397 }
3398 }
3399 }
3400 }
3401
3402 return ClosestId;
3403}
3404
3405ColorRGBA CalculateNameColor(ColorHSLA TextColorHSL)
3406{
3407 return color_cast<ColorRGBA>(hsl: ColorHSLA(TextColorHSL.h, TextColorHSL.s * 0.68f, TextColorHSL.l * 0.81f));
3408}
3409
3410void CGameClient::UpdateLocalTuning()
3411{
3412 m_GameWorld.m_WorldConfig.m_UseTuneZones = m_GameInfo.m_PredictDDRaceTiles;
3413
3414 // always update default tune zone, even without character
3415 if(!m_GameWorld.m_WorldConfig.m_UseTuneZones)
3416 m_GameWorld.TuningList()[0] = m_aTuning[g_Config.m_ClDummy];
3417
3418 if(!m_Snap.m_pLocalCharacter && !m_Snap.m_pSpectatorInfo)
3419 return;
3420
3421 vec2 LocalPos = m_Snap.m_pLocalCharacter ? vec2(m_Snap.m_pLocalCharacter->m_X, m_Snap.m_pLocalCharacter->m_Y) : vec2(m_Snap.m_pSpectatorInfo->m_X, m_Snap.m_pSpectatorInfo->m_Y);
3422
3423 // update the tuning at the local position with the latest tunings received before the new snapshot
3424 if(m_GameWorld.m_WorldConfig.m_UseTuneZones)
3425 {
3426 int TuneZone =
3427 m_Snap.m_aCharacters[m_Snap.m_LocalClientId].m_HasExtendedData &&
3428 m_Snap.m_aCharacters[m_Snap.m_LocalClientId].m_ExtendedData.m_TuneZoneOverride != TuneZone::OVERRIDE_NONE ?
3429 m_Snap.m_aCharacters[m_Snap.m_LocalClientId].m_ExtendedData.m_TuneZoneOverride :
3430 Collision()->IsTune(Index: Collision()->GetMapIndex(Pos: LocalPos));
3431
3432 if(TuneZone != m_aLocalTuneZone[g_Config.m_ClDummy])
3433 {
3434 // our tunezone changed, expecting tuning message
3435 m_aLocalTuneZone[g_Config.m_ClDummy] = m_aExpectingTuningForZone[g_Config.m_ClDummy] = TuneZone;
3436 m_aExpectingTuningSince[g_Config.m_ClDummy] = 0;
3437 }
3438
3439 // tunezone could have changed, send dummy tuning to demo
3440 if(m_ActiveRecordings.any() && m_IsDummySwapping && m_aLocalTuneZone[0] != m_aLocalTuneZone[1])
3441 {
3442 CMsgPacker Msg(NETMSGTYPE_SV_TUNEPARAMS);
3443 int *pParams = (int *)&m_aTuning[g_Config.m_ClDummy];
3444 for(unsigned i = 0; i < sizeof(m_aTuning[0]) / sizeof(int); i++)
3445 Msg.AddInt(i: pParams[i]);
3446 Client()->SendMsgActive(pMsg: &Msg, Flags: MSGFLAG_RECORD | MSGFLAG_NOSEND);
3447 }
3448
3449 if(m_aExpectingTuningForZone[g_Config.m_ClDummy] >= 0)
3450 {
3451 if(m_aReceivedTuning[g_Config.m_ClDummy])
3452 {
3453 TuningList()[m_aExpectingTuningForZone[g_Config.m_ClDummy]] = m_aTuning[g_Config.m_ClDummy];
3454 m_GameWorld.TuningList()[m_aExpectingTuningForZone[g_Config.m_ClDummy]] = m_aTuning[g_Config.m_ClDummy];
3455 m_aReceivedTuning[g_Config.m_ClDummy] = false;
3456 m_aExpectingTuningForZone[g_Config.m_ClDummy] = -1;
3457 }
3458 else if(m_aExpectingTuningSince[g_Config.m_ClDummy] >= 5)
3459 {
3460 // if we are expecting tuning for more than 10 snaps (less than a quarter of a second)
3461 // it is probably dropped or it was received out of order
3462 // or applied to another tunezone.
3463 // we need to fallback to current tuning to fix ourselves.
3464 m_aExpectingTuningForZone[g_Config.m_ClDummy] = -1;
3465 m_aExpectingTuningSince[g_Config.m_ClDummy] = 0;
3466 m_aReceivedTuning[g_Config.m_ClDummy] = false;
3467 log_debug("tunezone", "the tuning was missed");
3468 }
3469 else
3470 {
3471 // if we are expecting tuning and have not received one yet.
3472 // do not update any tuning, so we don't apply it to the wrong tunezone.
3473 log_debug("tunezone", "waiting for tuning for zone %d", m_aExpectingTuningForZone[g_Config.m_ClDummy]);
3474 m_aExpectingTuningSince[g_Config.m_ClDummy]++;
3475 }
3476 }
3477 else
3478 {
3479 // if we have processed what we need, and the tuning is still wrong due to out of order message
3480 // fix our tuning by using the current one
3481 m_GameWorld.TuningList()[TuneZone] = m_aTuning[g_Config.m_ClDummy];
3482 m_aExpectingTuningSince[g_Config.m_ClDummy] = 0;
3483 m_aReceivedTuning[g_Config.m_ClDummy] = false;
3484 }
3485 }
3486}
3487
3488void CGameClient::UpdatePrediction()
3489{
3490 m_GameWorld.m_WorldConfig.m_IsVanilla = m_GameInfo.m_PredictVanilla;
3491 m_GameWorld.m_WorldConfig.m_IsDDRace = m_GameInfo.m_PredictDDRace;
3492 m_GameWorld.m_WorldConfig.m_IsFNG = m_GameInfo.m_PredictFNG;
3493 m_GameWorld.m_WorldConfig.m_PredictDDRace = m_GameInfo.m_PredictDDRace;
3494 m_GameWorld.m_WorldConfig.m_PredictTiles = m_GameInfo.m_PredictDDRace && m_GameInfo.m_PredictDDRaceTiles;
3495 m_GameWorld.m_WorldConfig.m_PredictFreeze = g_Config.m_ClPredictFreeze;
3496 m_GameWorld.m_WorldConfig.m_PredictWeapons = AntiPingWeapons();
3497 m_GameWorld.m_WorldConfig.m_BugDDRaceInput = m_GameInfo.m_BugDDRaceInput;
3498 m_GameWorld.m_WorldConfig.m_NoWeakHookAndBounce = m_GameInfo.m_NoWeakHookAndBounce;
3499 m_GameWorld.m_WorldConfig.m_PredictEvents = m_GameInfo.m_PredictEvents;
3500 m_GameWorld.m_WorldConfig.m_OldLaser = m_GameInfo.m_OldLaser;
3501
3502 if(!m_Snap.m_pLocalCharacter)
3503 {
3504 if(CCharacter *pLocalChar = m_GameWorld.GetCharacterById(Id: m_Snap.m_LocalClientId))
3505 pLocalChar->Destroy();
3506 return;
3507 }
3508
3509 if(m_Snap.m_pLocalCharacter->m_AmmoCount > 0 && m_Snap.m_pLocalCharacter->m_Weapon != WEAPON_NINJA)
3510 m_GameWorld.m_WorldConfig.m_InfiniteAmmo = false;
3511 m_GameWorld.m_WorldConfig.m_IsSolo = !m_Snap.m_aCharacters[m_Snap.m_LocalClientId].m_HasExtendedData && !m_aTuning[g_Config.m_ClDummy].m_PlayerCollision && !m_aTuning[g_Config.m_ClDummy].m_PlayerHooking;
3512
3513 CCharacter *pLocalChar = m_GameWorld.GetCharacterById(Id: m_Snap.m_LocalClientId);
3514 CCharacter *pDummyChar = nullptr;
3515 if(PredictDummy())
3516 pDummyChar = m_GameWorld.GetCharacterById(Id: m_aLocalIds[!g_Config.m_ClDummy]);
3517
3518 // update strong and weak hook
3519 if(pLocalChar && !m_Snap.m_SpecInfo.m_Active && Client()->State() != IClient::STATE_DEMOPLAYBACK && (m_aTuning[g_Config.m_ClDummy].m_PlayerCollision || m_aTuning[g_Config.m_ClDummy].m_PlayerHooking))
3520 {
3521 if(m_Snap.m_aCharacters[m_Snap.m_LocalClientId].m_HasExtendedData)
3522 {
3523 int aIds[MAX_CLIENTS];
3524 std::fill(first: std::begin(arr&: aIds), last: std::end(arr&: aIds), value: -1);
3525 for(int i = 0; i < MAX_CLIENTS; i++)
3526 if(CCharacter *pChar = m_GameWorld.GetCharacterById(Id: i))
3527 aIds[pChar->GetStrongWeakId()] = i;
3528 for(int Id : aIds)
3529 if(Id >= 0)
3530 m_CharOrder.GiveStrong(c: Id);
3531 }
3532 else
3533 {
3534 // manual detection
3535 DetectStrongHook();
3536 }
3537 for(int i : m_CharOrder.m_Ids)
3538 {
3539 if(CCharacter *pChar = m_GameWorld.GetCharacterById(Id: i))
3540 {
3541 m_GameWorld.RemoveEntity(pEntity: pChar);
3542 m_GameWorld.InsertEntity(pEntity: pChar);
3543 }
3544 }
3545 }
3546
3547 // advance the gameworld to the current gametick
3548 if(pLocalChar && absolute(a: m_GameWorld.GameTick() - Client()->GameTick(Conn: g_Config.m_ClDummy)) < Client()->GameTickSpeed())
3549 {
3550 for(int Tick = m_GameWorld.GameTick() + 1; Tick <= Client()->GameTick(Conn: g_Config.m_ClDummy); Tick++)
3551 {
3552 CNetObj_PlayerInput *pInput = (CNetObj_PlayerInput *)Client()->GetInput(Tick);
3553 CNetObj_PlayerInput *pDummyInput = nullptr;
3554 if(pDummyChar)
3555 pDummyInput = (CNetObj_PlayerInput *)Client()->GetInput(Tick, IsDummy: 1);
3556 if(pInput)
3557 pLocalChar->OnDirectInput(pNewInput: pInput);
3558 if(pDummyInput)
3559 pDummyChar->OnDirectInput(pNewInput: pDummyInput);
3560
3561 ApplyPreInputs(Tick, Direct: true, GameWorld&: m_GameWorld);
3562
3563 m_GameWorld.m_GameTick = Tick;
3564 if(pInput)
3565 pLocalChar->OnPredictedInput(pNewInput: pInput);
3566 if(pDummyInput)
3567 pDummyChar->OnPredictedInput(pNewInput: pDummyInput);
3568
3569 ApplyPreInputs(Tick, Direct: false, GameWorld&: m_GameWorld);
3570
3571 m_GameWorld.Tick();
3572
3573 for(int i = 0; i < MAX_CLIENTS; i++)
3574 if(CCharacter *pChar = m_GameWorld.GetCharacterById(Id: i))
3575 {
3576 m_aClients[i].m_aPredPos[Tick % 200] = pChar->Core()->m_Pos;
3577 m_aClients[i].m_aPredTick[Tick % 200] = Tick;
3578 }
3579 }
3580 }
3581 else
3582 {
3583 // skip to current gametick
3584 m_GameWorld.m_GameTick = Client()->GameTick(Conn: g_Config.m_ClDummy);
3585 if(pLocalChar)
3586 if(CNetObj_PlayerInput *pInput = (CNetObj_PlayerInput *)Client()->GetInput(Tick: Client()->GameTick(Conn: g_Config.m_ClDummy)))
3587 pLocalChar->SetInput(pInput);
3588 if(pDummyChar)
3589 if(CNetObj_PlayerInput *pInput = (CNetObj_PlayerInput *)Client()->GetInput(Tick: Client()->GameTick(Conn: g_Config.m_ClDummy), IsDummy: 1))
3590 pDummyChar->SetInput(pInput);
3591 }
3592
3593 for(int i = 0; i < MAX_CLIENTS; i++)
3594 if(CCharacter *pChar = m_GameWorld.GetCharacterById(Id: i))
3595 {
3596 m_aClients[i].m_aPredPos[Client()->GameTick(Conn: g_Config.m_ClDummy) % 200] = pChar->Core()->m_Pos;
3597 m_aClients[i].m_aPredTick[Client()->GameTick(Conn: g_Config.m_ClDummy) % 200] = Client()->GameTick(Conn: g_Config.m_ClDummy);
3598 }
3599
3600 // update the local gameworld with the new snapshot
3601 m_GameWorld.NetObjBegin(Teams: m_Teams, LocalClientId: m_Snap.m_LocalClientId);
3602
3603 for(int i = 0; i < MAX_CLIENTS; i++)
3604 if(m_Snap.m_aCharacters[i].m_Active)
3605 {
3606 bool IsLocal = (i == m_Snap.m_LocalClientId || (PredictDummy() && i == m_aLocalIds[!g_Config.m_ClDummy]));
3607 int GameTeam = IsTeamPlay() ? m_aClients[i].m_Team : i;
3608 m_GameWorld.NetCharAdd(ObjId: i, pChar: &m_Snap.m_aCharacters[i].m_Cur,
3609 pExtended: m_Snap.m_aCharacters[i].m_HasExtendedData ? &m_Snap.m_aCharacters[i].m_ExtendedData : nullptr,
3610 GameTeam, IsLocal);
3611 }
3612
3613 for(const CSnapEntities &EntData : SnapEntities())
3614 m_GameWorld.NetObjAdd(ObjId: EntData.m_Item.m_Id, ObjType: EntData.m_Item.m_Type, pObjData: EntData.m_Item.m_pData, pDataEx: EntData.m_pDataEx);
3615
3616 m_GameWorld.NetObjEnd();
3617}
3618
3619void CGameClient::UpdateSpectatorCursor()
3620{
3621 int CursorOwnerId = m_Snap.m_LocalClientId;
3622 if(m_Snap.m_SpecInfo.m_Active)
3623 {
3624 CursorOwnerId = m_Snap.m_SpecInfo.m_SpectatorId;
3625 }
3626
3627 if(CursorOwnerId != m_CursorInfo.m_CursorOwnerId)
3628 {
3629 // reset cursor sample count upon changing spectating character
3630 m_CursorInfo.m_NumSamples = 0;
3631 m_CursorInfo.m_CursorOwnerId = CursorOwnerId;
3632 }
3633
3634 if(m_MultiView.IsActivated() || CursorOwnerId < 0 || CursorOwnerId >= MAX_CLIENTS)
3635 {
3636 // do not show spec cursor in multi-view
3637 m_CursorInfo.m_Available = false;
3638 m_CursorInfo.m_NumSamples = 0;
3639 return;
3640 }
3641
3642 const CSnapState::CCharacterInfo &CharInfo = m_Snap.m_aCharacters[CursorOwnerId];
3643 const CClientData &CursorOwnerClient = m_aClients[CursorOwnerId];
3644 if(!CharInfo.m_HasExtendedDisplayInfo || !CursorOwnerClient.m_Active || (!g_Config.m_Debug && CursorOwnerClient.m_Paused))
3645 {
3646 // hide cursor when the spectating player is paused
3647 m_CursorInfo.m_Available = false;
3648 m_CursorInfo.m_NumSamples = 0;
3649 return;
3650 }
3651
3652 m_CursorInfo.m_Available = true;
3653 m_CursorInfo.m_Position = CursorOwnerClient.m_RenderPos;
3654 m_CursorInfo.m_Weapon = CharInfo.m_Cur.m_Weapon;
3655
3656 const vec2 Target = vec2(CharInfo.m_ExtendedData.m_TargetX, CharInfo.m_ExtendedData.m_TargetY);
3657
3658 if(IsDemoPlaybackPaused())
3659 {
3660 m_CursorInfo.m_CursorOwnerId = -1;
3661 m_CursorInfo.m_NumSamples = 0;
3662 const vec2 TargetNew = vec2(CharInfo.m_ExtendedData.m_TargetX, CharInfo.m_ExtendedData.m_TargetY);
3663 if(CharInfo.m_pPrevExtendedData)
3664 {
3665 const vec2 TargetOld = vec2(CharInfo.m_pPrevExtendedData->m_TargetX, CharInfo.m_pPrevExtendedData->m_TargetY);
3666 m_CursorInfo.m_Target = mix(a: TargetOld, b: TargetNew, amount: Client()->IntraGameTick(Conn: g_Config.m_ClDummy));
3667 }
3668 else
3669 {
3670 m_CursorInfo.m_Target = TargetNew;
3671 }
3672 }
3673 else
3674 {
3675 // interpolate cursor positions
3676 const double Tick = Client()->GameTick(Conn: g_Config.m_ClDummy);
3677
3678 const bool HasSample = m_CursorInfo.m_NumSamples > 0;
3679 const vec2 LastInput = HasSample ? m_CursorInfo.m_aTargetSamplesData[m_CursorInfo.m_NumSamples - 1] : vec2(0.0f, 0.0f);
3680 const double LastTime = HasSample ? m_CursorInfo.m_aTargetSamplesTime[m_CursorInfo.m_NumSamples - 1] : 0.0;
3681 bool NewSample = LastInput != Target || LastTime + CCursorInfo::REST_THRESHOLD < Tick;
3682
3683 if(LastTime > Tick)
3684 {
3685 // clear samples when time flows backwards
3686 m_CursorInfo.m_NumSamples = 0;
3687 NewSample = true;
3688 }
3689
3690 if(m_CursorInfo.m_NumSamples == 0)
3691 {
3692 m_CursorInfo.m_aTargetSamplesTime[0] = Tick - CCursorInfo::INTERP_DELAY;
3693 m_CursorInfo.m_aTargetSamplesData[0] = Target;
3694 }
3695
3696 if(NewSample)
3697 {
3698 if(m_CursorInfo.m_NumSamples == CCursorInfo::CURSOR_SAMPLES)
3699 {
3700 m_CursorInfo.m_NumSamples--;
3701 mem_move(dest: m_CursorInfo.m_aTargetSamplesTime, source: m_CursorInfo.m_aTargetSamplesTime + 1, size: m_CursorInfo.m_NumSamples * sizeof(double));
3702 mem_move(dest: m_CursorInfo.m_aTargetSamplesData, source: m_CursorInfo.m_aTargetSamplesData + 1, size: m_CursorInfo.m_NumSamples * sizeof(vec2));
3703 }
3704 m_CursorInfo.m_aTargetSamplesTime[m_CursorInfo.m_NumSamples] = Tick;
3705 m_CursorInfo.m_aTargetSamplesData[m_CursorInfo.m_NumSamples] = Target;
3706 m_CursorInfo.m_NumSamples++;
3707 }
3708
3709 // using double to avoid precision loss when converting int tick to decimal type
3710 const double DisplayTime = Tick - CCursorInfo::INTERP_DELAY + double(Client()->IntraGameTickSincePrev(Conn: g_Config.m_ClDummy));
3711 double aTime[CCursorInfo::SAMPLE_FRAME_WINDOW];
3712 vec2 aData[CCursorInfo::SAMPLE_FRAME_WINDOW];
3713
3714 // find the available sample timing
3715 int Index = m_CursorInfo.m_NumSamples;
3716 for(int i = 0; i < m_CursorInfo.m_NumSamples; i++)
3717 {
3718 if(m_CursorInfo.m_aTargetSamplesTime[i] > DisplayTime)
3719 {
3720 Index = i;
3721 break;
3722 }
3723 }
3724
3725 for(int i = 0; i < CCursorInfo::SAMPLE_FRAME_WINDOW; i++)
3726 {
3727 const int Offset = i - CCursorInfo::SAMPLE_FRAME_OFFSET;
3728 const int SampleIndex = Index + Offset;
3729 if(SampleIndex < 0)
3730 {
3731 aTime[i] = m_CursorInfo.m_aTargetSamplesTime[0] + CCursorInfo::REST_THRESHOLD * Offset;
3732 aData[i] = m_CursorInfo.m_aTargetSamplesData[0];
3733 }
3734 else if(SampleIndex >= m_CursorInfo.m_NumSamples)
3735 {
3736 aTime[i] = m_CursorInfo.m_aTargetSamplesTime[m_CursorInfo.m_NumSamples - 1] + CCursorInfo::REST_THRESHOLD * (Offset + 1);
3737 aData[i] = m_CursorInfo.m_aTargetSamplesData[m_CursorInfo.m_NumSamples - 1];
3738 }
3739 else
3740 {
3741 aTime[i] = m_CursorInfo.m_aTargetSamplesTime[SampleIndex];
3742 aData[i] = m_CursorInfo.m_aTargetSamplesData[SampleIndex];
3743 }
3744 }
3745
3746 m_CursorInfo.m_Target = mix_polynomial(time: aTime, data: aData, samples: CCursorInfo::SAMPLE_FRAME_WINDOW, amount: DisplayTime, init: vec2(0.0f, 0.0f));
3747 }
3748
3749 vec2 TargetCameraOffset(0, 0);
3750 float l = length(a: m_CursorInfo.m_Target);
3751
3752 if(l > 0.0001f) // make sure that this isn't 0
3753 {
3754 float OffsetAmount = std::max(a: l - m_Snap.m_SpecInfo.m_Deadzone, b: 0.0f) * (m_Snap.m_SpecInfo.m_FollowFactor / 100.0f);
3755 TargetCameraOffset = normalize(v: m_CursorInfo.m_Target) * OffsetAmount;
3756 }
3757
3758 // if we are in auto spec mode, use camera zoom to smooth out cursor transitions
3759 const float Zoom = (m_Camera.m_Zooming && m_Camera.m_AutoSpecCameraZooming) ? m_Camera.m_Zoom : m_Snap.m_SpecInfo.m_Zoom;
3760 m_CursorInfo.m_WorldTarget = m_CursorInfo.m_Position + (m_CursorInfo.m_Target - TargetCameraOffset) * Zoom + TargetCameraOffset;
3761}
3762
3763void CGameClient::UpdateRenderedCharacters()
3764{
3765 for(int i = 0; i < MAX_CLIENTS; i++)
3766 {
3767 if(!m_Snap.m_aCharacters[i].m_Active)
3768 continue;
3769 m_aClients[i].m_RenderCur = m_Snap.m_aCharacters[i].m_Cur;
3770 m_aClients[i].m_RenderPrev = m_Snap.m_aCharacters[i].m_Prev;
3771 m_aClients[i].m_IsPredicted = false;
3772 m_aClients[i].m_IsPredictedLocal = false;
3773 vec2 UnpredPos = mix(
3774 a: vec2(m_Snap.m_aCharacters[i].m_Prev.m_X, m_Snap.m_aCharacters[i].m_Prev.m_Y),
3775 b: vec2(m_Snap.m_aCharacters[i].m_Cur.m_X, m_Snap.m_aCharacters[i].m_Cur.m_Y),
3776 amount: Client()->IntraGameTick(Conn: g_Config.m_ClDummy));
3777 vec2 Pos = UnpredPos;
3778
3779 CCharacter *pChar = m_PredictedWorld.GetCharacterById(Id: i);
3780 const bool IsDummy = PredictDummy() && i == m_aLocalIds[!g_Config.m_ClDummy];
3781 bool AntiPingPlayer = AntiPingPlayers() == 1 || (AntiPingPlayers() >= 2 && (IsDummy || (pChar && pChar->IsInterfering())));
3782 if(Predict() && (i == m_Snap.m_LocalClientId || (AntiPingPlayer && !IsOtherTeam(ClientId: i))) && pChar)
3783 {
3784 m_aClients[i].m_Predicted.Write(pObjCore: &m_aClients[i].m_RenderCur);
3785 m_aClients[i].m_PrevPredicted.Write(pObjCore: &m_aClients[i].m_RenderPrev);
3786
3787 m_aClients[i].m_IsPredicted = true;
3788
3789 Pos = mix(
3790 a: vec2(m_aClients[i].m_RenderPrev.m_X, m_aClients[i].m_RenderPrev.m_Y),
3791 b: vec2(m_aClients[i].m_RenderCur.m_X, m_aClients[i].m_RenderCur.m_Y),
3792 amount: m_aClients[i].m_IsPredicted ? Client()->PredIntraGameTick(Conn: g_Config.m_ClDummy) : Client()->IntraGameTick(Conn: g_Config.m_ClDummy));
3793
3794 if(i == m_Snap.m_LocalClientId || IsDummy)
3795 {
3796 m_aClients[i].m_IsPredictedLocal = true;
3797 if(AntiPingGunfire() && ((pChar->m_NinjaJetpack && pChar->m_FreezeTime == 0) || m_Snap.m_aCharacters[i].m_Cur.m_Weapon != WEAPON_NINJA || m_Snap.m_aCharacters[i].m_Cur.m_Weapon == m_aClients[i].m_Predicted.m_ActiveWeapon))
3798 {
3799 m_aClients[i].m_RenderCur.m_AttackTick = pChar->GetAttackTick();
3800 if(m_Snap.m_aCharacters[i].m_Cur.m_Weapon != WEAPON_NINJA && !(pChar->m_NinjaJetpack && pChar->Core()->m_ActiveWeapon == WEAPON_GUN))
3801 m_aClients[i].m_RenderCur.m_Weapon = m_aClients[i].m_Predicted.m_ActiveWeapon;
3802 }
3803 }
3804 else
3805 {
3806 // use unpredicted values for other players
3807 m_aClients[i].m_RenderPrev.m_Angle = m_Snap.m_aCharacters[i].m_Prev.m_Angle;
3808 m_aClients[i].m_RenderCur.m_Angle = m_Snap.m_aCharacters[i].m_Cur.m_Angle;
3809
3810 if(g_Config.m_ClAntiPingSmooth)
3811 Pos = GetSmoothPos(ClientId: i);
3812 }
3813 }
3814 m_aClients[i].m_RenderPos = Pos;
3815 if(Predict() && i == m_Snap.m_LocalClientId)
3816 m_LocalCharacterPos = Pos;
3817 }
3818}
3819
3820void CGameClient::HandlePredictedEvents(const int Tick)
3821{
3822 const float Alpha = 1.0f;
3823 const float Volume = 1.0f;
3824
3825 auto EventsIterator = m_PredictedWorld.m_PredictedEvents.begin();
3826 while(EventsIterator != m_PredictedWorld.m_PredictedEvents.end())
3827 {
3828 if(!EventsIterator->m_Handled && EventsIterator->m_Tick <= Tick)
3829 {
3830 if(EventsIterator->m_EventId == NETEVENTTYPE_SOUNDWORLD)
3831 {
3832 if(m_GameInfo.m_RaceSounds && ((EventsIterator->m_ExtraInfo == SOUND_GUN_FIRE && !g_Config.m_SndGun) || (EventsIterator->m_ExtraInfo == SOUND_PLAYER_PAIN_LONG && !g_Config.m_SndLongPain)))
3833 {
3834 EventsIterator = m_PredictedWorld.m_PredictedEvents.erase(position: EventsIterator);
3835 continue;
3836 }
3837 m_Sounds.PlayAt(Channel: CSounds::CHN_WORLD, SetId: EventsIterator->m_ExtraInfo, Volume: 1.0f, Position: EventsIterator->m_Pos);
3838 }
3839 else if(EventsIterator->m_EventId == NETEVENTTYPE_EXPLOSION)
3840 {
3841 m_Effects.Explosion(Pos: EventsIterator->m_Pos, Alpha);
3842 }
3843 else if(EventsIterator->m_EventId == NETEVENTTYPE_HAMMERHIT)
3844 {
3845 m_Effects.HammerHit(Pos: EventsIterator->m_Pos, Alpha, Volume);
3846 }
3847 else if(EventsIterator->m_EventId == NETEVENTTYPE_DAMAGEIND)
3848 {
3849 m_Effects.DamageIndicator(Pos: EventsIterator->m_Pos, Dir: direction(angle: EventsIterator->m_ExtraInfo / 256.0f), Alpha);
3850 }
3851
3852 EventsIterator->m_Handled = true;
3853 ++EventsIterator;
3854 continue;
3855 }
3856 else if(Tick - EventsIterator->m_Tick > 3 * Client()->GameTickSpeed()) // 3 seconds
3857 {
3858 // remove too old events
3859 EventsIterator = m_PredictedWorld.m_PredictedEvents.erase(position: EventsIterator);
3860 }
3861 else
3862 {
3863 ++EventsIterator;
3864 }
3865 }
3866}
3867
3868void CGameClient::DetectStrongHook()
3869{
3870 // attempt to detect strong/weak between players
3871 for(int FromPlayer = 0; FromPlayer < MAX_CLIENTS; FromPlayer++)
3872 {
3873 if(!m_Snap.m_aCharacters[FromPlayer].m_Active)
3874 continue;
3875 int ToPlayer = m_Snap.m_aCharacters[FromPlayer].m_Prev.m_HookedPlayer;
3876 if(ToPlayer < 0 || ToPlayer >= MAX_CLIENTS || !m_Snap.m_aCharacters[ToPlayer].m_Active || ToPlayer != m_Snap.m_aCharacters[FromPlayer].m_Cur.m_HookedPlayer)
3877 continue;
3878 if(absolute(a: std::min(a: m_aLastUpdateTick[ToPlayer], b: m_aLastUpdateTick[FromPlayer]) - Client()->GameTick(Conn: g_Config.m_ClDummy)) < Client()->GameTickSpeed() / 4)
3879 continue;
3880 if(m_Snap.m_aCharacters[FromPlayer].m_Prev.m_Direction != m_Snap.m_aCharacters[FromPlayer].m_Cur.m_Direction || m_Snap.m_aCharacters[ToPlayer].m_Prev.m_Direction != m_Snap.m_aCharacters[ToPlayer].m_Cur.m_Direction)
3881 continue;
3882
3883 CCharacter *pFromCharWorld = m_GameWorld.GetCharacterById(Id: FromPlayer);
3884 CCharacter *pToCharWorld = m_GameWorld.GetCharacterById(Id: ToPlayer);
3885 if(!pFromCharWorld || !pToCharWorld)
3886 continue;
3887
3888 m_aLastUpdateTick[ToPlayer] = m_aLastUpdateTick[FromPlayer] = Client()->GameTick(Conn: g_Config.m_ClDummy);
3889
3890 float aPredictErr[2];
3891 CCharacterCore ToCharCur;
3892 ToCharCur.Read(pObjCore: &m_Snap.m_aCharacters[ToPlayer].m_Cur);
3893
3894 CWorldCore World;
3895
3896 for(int Direction = 0; Direction < 2; Direction++)
3897 {
3898 CCharacterCore ToChar = pFromCharWorld->GetCore();
3899 ToChar.Init(pWorld: &World, pCollision: Collision(), pTeams: &m_Teams);
3900 World.m_apCharacters[ToPlayer] = &ToChar;
3901 ToChar.Read(pObjCore: &m_Snap.m_aCharacters[ToPlayer].m_Prev);
3902
3903 CCharacterCore FromChar = pFromCharWorld->GetCore();
3904 FromChar.Init(pWorld: &World, pCollision: Collision(), pTeams: &m_Teams);
3905 World.m_apCharacters[FromPlayer] = &FromChar;
3906 FromChar.Read(pObjCore: &m_Snap.m_aCharacters[FromPlayer].m_Prev);
3907
3908 for(int Tick = Client()->PrevGameTick(Conn: g_Config.m_ClDummy); Tick < Client()->GameTick(Conn: g_Config.m_ClDummy); Tick++)
3909 {
3910 if(Direction == 0)
3911 {
3912 FromChar.Tick(UseInput: false);
3913 ToChar.Tick(UseInput: false);
3914 }
3915 else
3916 {
3917 ToChar.Tick(UseInput: false);
3918 FromChar.Tick(UseInput: false);
3919 }
3920 FromChar.Move();
3921 FromChar.Quantize();
3922 ToChar.Move();
3923 ToChar.Quantize();
3924 }
3925 aPredictErr[Direction] = distance(a: ToChar.m_Vel, b: ToCharCur.m_Vel);
3926 }
3927 const float LOW = 0.0001f;
3928 const float HIGH = 0.07f;
3929 if(aPredictErr[1] < LOW && aPredictErr[0] > HIGH)
3930 {
3931 if(m_CharOrder.HasStrongAgainst(From: ToPlayer, To: FromPlayer))
3932 {
3933 if(ToPlayer != m_Snap.m_LocalClientId)
3934 m_CharOrder.GiveWeak(c: ToPlayer);
3935 else
3936 m_CharOrder.GiveStrong(c: FromPlayer);
3937 }
3938 }
3939 else if(aPredictErr[0] < LOW && aPredictErr[1] > HIGH)
3940 {
3941 if(m_CharOrder.HasStrongAgainst(From: FromPlayer, To: ToPlayer))
3942 {
3943 if(ToPlayer != m_Snap.m_LocalClientId)
3944 m_CharOrder.GiveStrong(c: ToPlayer);
3945 else
3946 m_CharOrder.GiveWeak(c: FromPlayer);
3947 }
3948 }
3949 }
3950}
3951
3952vec2 CGameClient::GetSmoothPos(int ClientId)
3953{
3954 vec2 Pos = mix(a: m_aClients[ClientId].m_PrevPredicted.m_Pos, b: m_aClients[ClientId].m_Predicted.m_Pos, amount: Client()->PredIntraGameTick(Conn: g_Config.m_ClDummy));
3955 int64_t Now = time_get();
3956 for(int i = 0; i < 2; i++)
3957 {
3958 int64_t Len = std::clamp(val: m_aClients[ClientId].m_aSmoothLen[i], lo: (int64_t)1, hi: time_freq());
3959 int64_t TimePassed = Now - m_aClients[ClientId].m_aSmoothStart[i];
3960 if(in_range(a: TimePassed, lower: (int64_t)0, upper: Len - 1))
3961 {
3962 float MixAmount = 1.f - std::pow(x: 1.f - TimePassed / (float)Len, y: 1.2f);
3963 int SmoothTick;
3964 float SmoothIntra;
3965 Client()->GetSmoothTick(pSmoothTick: &SmoothTick, pSmoothIntraTick: &SmoothIntra, MixAmount);
3966 if(SmoothTick > 0 && m_aClients[ClientId].m_aPredTick[(SmoothTick - 1) % 200] >= Client()->PrevGameTick(Conn: g_Config.m_ClDummy) && m_aClients[ClientId].m_aPredTick[SmoothTick % 200] <= Client()->PredGameTick(Conn: g_Config.m_ClDummy))
3967 Pos[i] = mix(a: m_aClients[ClientId].m_aPredPos[(SmoothTick - 1) % 200][i], b: m_aClients[ClientId].m_aPredPos[SmoothTick % 200][i], amount: SmoothIntra);
3968 }
3969 }
3970 return Pos;
3971}
3972
3973void CGameClient::Echo(const char *pString)
3974{
3975 m_Chat.Echo(pString);
3976}
3977
3978bool CGameClient::IsOtherTeam(int ClientId) const
3979{
3980 bool Local = m_Snap.m_LocalClientId == ClientId;
3981
3982 if(m_Snap.m_LocalClientId < 0)
3983 {
3984 return false;
3985 }
3986 else if((m_Snap.m_SpecInfo.m_Active && m_Snap.m_SpecInfo.m_SpectatorId == SPEC_FREEVIEW) || ClientId < 0)
3987 {
3988 return false;
3989 }
3990 else if(m_Snap.m_SpecInfo.m_Active && m_Snap.m_SpecInfo.m_SpectatorId != SPEC_FREEVIEW)
3991 {
3992 if(m_Teams.Team(ClientId) == m_Teams.TeamSuper() || m_Teams.Team(ClientId: m_Snap.m_SpecInfo.m_SpectatorId) == m_Teams.TeamSuper())
3993 return false;
3994 return m_Teams.Team(ClientId) != m_Teams.Team(ClientId: m_Snap.m_SpecInfo.m_SpectatorId);
3995 }
3996 else if((m_aClients[m_Snap.m_LocalClientId].m_Solo || m_aClients[ClientId].m_Solo) && !Local)
3997 {
3998 return true;
3999 }
4000
4001 if(m_Teams.Team(ClientId) == m_Teams.TeamSuper() || m_Teams.Team(ClientId: m_Snap.m_LocalClientId) == m_Teams.TeamSuper())
4002 return false;
4003
4004 return m_Teams.Team(ClientId) != m_Teams.Team(ClientId: m_Snap.m_LocalClientId);
4005}
4006
4007int CGameClient::SwitchStateTeam() const
4008{
4009 if(m_aSwitchStateTeam[g_Config.m_ClDummy] >= 0)
4010 return m_aSwitchStateTeam[g_Config.m_ClDummy];
4011 else if(m_Snap.m_LocalClientId < 0)
4012 return 0;
4013 else if(m_Snap.m_SpecInfo.m_Active && m_Snap.m_SpecInfo.m_SpectatorId != SPEC_FREEVIEW)
4014 return m_Teams.Team(ClientId: m_Snap.m_SpecInfo.m_SpectatorId);
4015 return m_Teams.Team(ClientId: m_Snap.m_LocalClientId);
4016}
4017
4018bool CGameClient::IsLocalCharSuper() const
4019{
4020 if(m_Snap.m_LocalClientId < 0)
4021 return false;
4022 return m_aClients[m_Snap.m_LocalClientId].m_Super;
4023}
4024
4025void CGameClient::RefreshSkin(const std::shared_ptr<CManagedTeeRenderInfo> &pManagedTeeRenderInfo)
4026{
4027 CTeeRenderInfo &TeeInfo = pManagedTeeRenderInfo->TeeRenderInfo();
4028 const CSkinDescriptor &SkinDescriptor = pManagedTeeRenderInfo->SkinDescriptor();
4029
4030 if(SkinDescriptor.m_Flags & CSkinDescriptor::FLAG_SIX)
4031 {
4032 TeeInfo.Apply(pSkin: m_Skins.Find(pName: SkinDescriptor.m_aSkinName));
4033 }
4034
4035 if(SkinDescriptor.m_Flags & CSkinDescriptor::FLAG_SEVEN)
4036 {
4037 for(int Dummy = 0; Dummy < NUM_DUMMIES; Dummy++)
4038 {
4039 for(int Part = 0; Part < protocol7::NUM_SKINPARTS; Part++)
4040 {
4041 m_Skins7.FindSkinPart(Part, pName: SkinDescriptor.m_aSixup[Dummy].m_aaSkinPartNames[Part], AllowSpecialPart: true)->ApplyTo(SixupRenderInfo&: TeeInfo.m_aSixup[Dummy]);
4042
4043 if(SkinDescriptor.m_aSixup[Dummy].m_XmasHat)
4044 {
4045 TeeInfo.m_aSixup[Dummy].m_HatTexture = m_Skins7.XmasHatTexture();
4046 }
4047 else
4048 {
4049 TeeInfo.m_aSixup[Dummy].m_HatTexture.Invalidate();
4050 }
4051
4052 if(SkinDescriptor.m_aSixup[Dummy].m_BotDecoration)
4053 {
4054 TeeInfo.m_aSixup[Dummy].m_BotTexture = m_Skins7.BotDecorationTexture();
4055 }
4056 else
4057 {
4058 TeeInfo.m_aSixup[Dummy].m_BotTexture.Invalidate();
4059 }
4060 }
4061 }
4062 }
4063
4064 if(SkinDescriptor.m_Flags != 0 && pManagedTeeRenderInfo->m_RefreshCallback)
4065 {
4066 pManagedTeeRenderInfo->m_RefreshCallback();
4067 }
4068}
4069
4070void CGameClient::RefreshSkins(int SkinDescriptorFlags)
4071{
4072 dbg_assert(SkinDescriptorFlags != 0, "SkinDescriptorFlags invalid");
4073
4074 const auto SkinStartLoadTime = time_get_nanoseconds();
4075 const auto &&ProgressCallback = [&]() {
4076 // if skin refreshing takes to long, swap to a loading screen
4077 if(time_get_nanoseconds() - SkinStartLoadTime > 500ms)
4078 {
4079 m_Menus.RenderLoading(pCaption: Localize(pStr: "Loading skin files"), pContent: "", IncreaseCounter: 0);
4080 }
4081 };
4082 if(SkinDescriptorFlags & CSkinDescriptor::FLAG_SIX)
4083 {
4084 m_Skins.Refresh(SkinLoadedCallback: ProgressCallback);
4085 }
4086 if(SkinDescriptorFlags & CSkinDescriptor::FLAG_SEVEN)
4087 {
4088 m_Skins7.Refresh(SkinLoadedCallback: ProgressCallback);
4089 }
4090
4091 for(std::shared_ptr<CManagedTeeRenderInfo> &pManagedTeeRenderInfo : m_vpManagedTeeRenderInfos)
4092 {
4093 if(!(pManagedTeeRenderInfo->SkinDescriptor().m_Flags & SkinDescriptorFlags))
4094 {
4095 continue;
4096 }
4097 RefreshSkin(pManagedTeeRenderInfo);
4098 }
4099}
4100
4101void CGameClient::OnSkinUpdate(const char *pSkinName)
4102{
4103 // If the refreshed skin's name starts with the current skin prefix, we also have to
4104 // refresh skins matching the unprefixed skin name, e.g. if "santa_cammo" is refreshed
4105 // with prefix "santa" we need to refresh both "santa_cammo" and "cammo".
4106 const char *pSkinPrefix = m_Skins.SkinPrefix();
4107 const int SkinPrefixLength = str_length(str: pSkinPrefix);
4108 char aSkinNameWithoutPrefix[MAX_SKIN_LENGTH];
4109 if(SkinPrefixLength > 0 &&
4110 str_comp_num(a: pSkinName, b: pSkinPrefix, num: SkinPrefixLength) == 0 &&
4111 pSkinName[SkinPrefixLength] == '_' &&
4112 pSkinName[SkinPrefixLength + 1] != '\0')
4113 {
4114 str_copy(dst&: aSkinNameWithoutPrefix, src: &pSkinName[SkinPrefixLength + 1]);
4115 }
4116 else
4117 {
4118 aSkinNameWithoutPrefix[0] = '\0';
4119 }
4120 const auto &&NameMatches = [&](const char *pCheckName) {
4121 if(str_comp(a: pCheckName, b: pSkinName) == 0)
4122 {
4123 return true;
4124 }
4125 if(aSkinNameWithoutPrefix[0] != '\0' &&
4126 str_comp(a: pCheckName, b: aSkinNameWithoutPrefix) == 0)
4127 {
4128 return true;
4129 }
4130 return false;
4131 };
4132
4133 for(std::shared_ptr<CManagedTeeRenderInfo> &pManagedTeeRenderInfo : m_vpManagedTeeRenderInfos)
4134 {
4135 if(!(pManagedTeeRenderInfo->SkinDescriptor().m_Flags & CSkinDescriptor::FLAG_SIX) ||
4136 !NameMatches(pManagedTeeRenderInfo->SkinDescriptor().m_aSkinName))
4137 {
4138 continue;
4139 }
4140 RefreshSkin(pManagedTeeRenderInfo);
4141 }
4142}
4143
4144std::shared_ptr<CManagedTeeRenderInfo> CGameClient::CreateManagedTeeRenderInfo(const CTeeRenderInfo &TeeRenderInfo, const CSkinDescriptor &SkinDescriptor)
4145{
4146 std::shared_ptr<CManagedTeeRenderInfo> pManagedTeeRenderInfo = std::make_shared<CManagedTeeRenderInfo>(args: TeeRenderInfo, args: SkinDescriptor);
4147 RefreshSkin(pManagedTeeRenderInfo);
4148 m_vpManagedTeeRenderInfos.emplace_back(args&: pManagedTeeRenderInfo);
4149 return pManagedTeeRenderInfo;
4150}
4151
4152std::shared_ptr<CManagedTeeRenderInfo> CGameClient::CreateManagedTeeRenderInfo(const CClientData &Client)
4153{
4154 return CreateManagedTeeRenderInfo(TeeRenderInfo: Client.m_RenderInfo, SkinDescriptor: Client.ToSkinDescriptor());
4155}
4156
4157void CGameClient::UpdateManagedTeeRenderInfos()
4158{
4159 while(!m_vpManagedTeeRenderInfos.empty())
4160 {
4161 auto UnusedInfo = std::find_if(first: m_vpManagedTeeRenderInfos.begin(), last: m_vpManagedTeeRenderInfos.end(), pred: [&](const auto &pItem) {
4162 return pItem.use_count() <= 1;
4163 });
4164 if(UnusedInfo == m_vpManagedTeeRenderInfos.end())
4165 {
4166 break;
4167 }
4168 m_vpManagedTeeRenderInfos.erase(position: UnusedInfo);
4169 }
4170}
4171
4172void CGameClient::CollectManagedTeeRenderInfos(const std::function<void(const char *pSkinName)> &ActiveSkinAcceptor)
4173{
4174 for(const std::shared_ptr<CManagedTeeRenderInfo> &pManagedTeeRenderInfo : m_vpManagedTeeRenderInfos)
4175 {
4176 if(pManagedTeeRenderInfo->m_SkinDescriptor.m_Flags & CSkinDescriptor::FLAG_SIX)
4177 {
4178 ActiveSkinAcceptor(pManagedTeeRenderInfo->m_SkinDescriptor.m_aSkinName);
4179 }
4180 }
4181}
4182
4183void CGameClient::ConchainRefreshSkins(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4184{
4185 CGameClient *pThis = static_cast<CGameClient *>(pUserData);
4186 pfnCallback(pResult, pCallbackUserData);
4187 if(pResult->NumArguments() && pThis->m_Menus.IsInit())
4188 {
4189 pThis->RefreshSkins(SkinDescriptorFlags: CSkinDescriptor::FLAG_SIX);
4190 }
4191}
4192
4193void CGameClient::ConchainRefreshEventSkins(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4194{
4195 CGameClient *pThis = static_cast<CGameClient *>(pUserData);
4196 pfnCallback(pResult, pCallbackUserData);
4197 if(pResult->NumArguments() && pThis->m_Menus.IsInit())
4198 {
4199 pThis->m_Skins.RefreshEventSkins();
4200 pThis->RefreshSkins(SkinDescriptorFlags: CSkinDescriptor::FLAG_SIX);
4201 }
4202}
4203
4204static bool UnknownMapSettingCallback(const char *pCommand, void *pUser)
4205{
4206 return true;
4207}
4208
4209void CGameClient::LoadMapSettings()
4210{
4211 m_MapBugs = CMapBugs::Create(pName: Map()->BaseName(), Size: Map()->Size(), Sha256: Map()->Sha256());
4212
4213 // Reset Tunezones
4214 for(int TuneZone = 0; TuneZone < TuneZone::NUM; TuneZone++)
4215 {
4216 TuningList()[TuneZone] = CTuningParams::DEFAULT;
4217 TuningList()[TuneZone].Set(pName: "gun_curvature", Value: 0);
4218 TuningList()[TuneZone].Set(pName: "gun_speed", Value: 1400);
4219 TuningList()[TuneZone].Set(pName: "shotgun_curvature", Value: 0);
4220 TuningList()[TuneZone].Set(pName: "shotgun_speed", Value: 500);
4221 TuningList()[TuneZone].Set(pName: "shotgun_speeddiff", Value: 0);
4222 }
4223
4224 // Load map tunings
4225 int Start, Num;
4226 Map()->GetType(Type: MAPITEMTYPE_INFO, pStart: &Start, pNum: &Num);
4227 for(int i = Start; i < Start + Num; i++)
4228 {
4229 int ItemId;
4230 CMapItemInfoSettings *pItem = (CMapItemInfoSettings *)Map()->GetItem(Index: i, pType: nullptr, pId: &ItemId);
4231 int ItemSize = Map()->GetItemSize(Index: i);
4232 if(!pItem || ItemId != 0)
4233 continue;
4234
4235 if(ItemSize < (int)sizeof(CMapItemInfoSettings))
4236 break;
4237 if(!(pItem->m_Settings > -1))
4238 break;
4239
4240 int Size = Map()->GetDataSize(Index: pItem->m_Settings);
4241 char *pSettings = (char *)Map()->GetData(Index: pItem->m_Settings);
4242 char *pNext = pSettings;
4243 Console()->SetUnknownCommandCallback(pfnCallback: UnknownMapSettingCallback, pUser: nullptr);
4244 while(pNext < pSettings + Size)
4245 {
4246 int StrSize = str_length(str: pNext) + 1;
4247 Console()->ExecuteLine(pStr: pNext, ClientId: IConsole::CLIENT_ID_GAME);
4248 pNext += StrSize;
4249 }
4250 Console()->SetUnknownCommandCallback(pfnCallback: IConsole::EmptyUnknownCommandCallback, pUser: nullptr);
4251 Map()->UnloadData(Index: pItem->m_Settings);
4252 break;
4253 }
4254}
4255
4256void CGameClient::ConTuneParam(IConsole::IResult *pResult, void *pUserData)
4257{
4258 CGameClient *pSelf = (CGameClient *)pUserData;
4259 const char *pParamName = pResult->GetString(Index: 0);
4260 if(pResult->NumArguments() == 2)
4261 {
4262 float NewValue = pResult->GetFloat(Index: 1);
4263 pSelf->TuningList()[0].Set(pName: pParamName, Value: NewValue);
4264 }
4265}
4266
4267void CGameClient::ConTuneZone(IConsole::IResult *pResult, void *pUserData)
4268{
4269 CGameClient *pSelf = (CGameClient *)pUserData;
4270 int List = pResult->GetInteger(Index: 0);
4271 const char *pParamName = pResult->GetString(Index: 1);
4272 float NewValue = pResult->GetFloat(Index: 2);
4273
4274 if(List >= 0 && List < TuneZone::NUM)
4275 pSelf->TuningList()[List].Set(pName: pParamName, Value: NewValue);
4276}
4277
4278void CGameClient::ConMapbug(IConsole::IResult *pResult, void *pUserData)
4279{
4280 CGameClient *pSelf = (CGameClient *)pUserData;
4281 const char *pMapBugName = pResult->GetString(Index: 0);
4282
4283 switch(pSelf->m_MapBugs.Update(pBug: pMapBugName))
4284 {
4285 case EMapBugUpdate::OK:
4286 break;
4287 case EMapBugUpdate::OVERRIDDEN:
4288 log_debug("mapbugs", "map-internal setting overridden by database");
4289 break;
4290 case EMapBugUpdate::NOTFOUND:
4291 log_debug("mapbugs", "unknown map bug '%s', ignoring", pMapBugName);
4292 break;
4293 default:
4294 dbg_assert_failed("unreachable");
4295 }
4296}
4297
4298void CGameClient::ConchainMenuMap(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4299{
4300 CGameClient *pSelf = (CGameClient *)pUserData;
4301 if(pResult->NumArguments())
4302 {
4303 if(str_comp(a: g_Config.m_ClMenuMap, b: pResult->GetString(Index: 0)) != 0)
4304 {
4305 str_copy(dst&: g_Config.m_ClMenuMap, src: pResult->GetString(Index: 0));
4306 pSelf->m_MenuBackground.LoadMenuBackground();
4307 }
4308 }
4309 else
4310 {
4311 pfnCallback(pResult, pCallbackUserData);
4312 }
4313}
4314
4315void CGameClient::DummyResetInput()
4316{
4317 if(!Client()->DummyConnected())
4318 return;
4319
4320 if((m_DummyInput.m_Fire & 1) != 0)
4321 m_DummyInput.m_Fire++;
4322
4323 m_Controls.ResetInput(Dummy: !g_Config.m_ClDummy);
4324 m_Controls.m_aInputData[!g_Config.m_ClDummy].m_Hook = 0;
4325 m_Controls.m_aInputData[!g_Config.m_ClDummy].m_Fire = m_DummyInput.m_Fire;
4326
4327 m_DummyInput = m_Controls.m_aInputData[!g_Config.m_ClDummy];
4328}
4329
4330bool CGameClient::CanDisplayWarning() const
4331{
4332 return m_Menus.CanDisplayWarning();
4333}
4334
4335CNetObjHandler *CGameClient::GetNetObjHandler()
4336{
4337 return &m_NetObjHandler;
4338}
4339
4340protocol7::CNetObjHandler *CGameClient::GetNetObjHandler7()
4341{
4342 return &m_NetObjHandler7;
4343}
4344
4345void CGameClient::SnapCollectEntities()
4346{
4347 int NumSnapItems = Client()->SnapNumItems(SnapId: IClient::SNAP_CURRENT);
4348
4349 std::vector<CSnapEntities> vItemData;
4350 std::vector<CSnapEntities> vItemEx;
4351
4352 for(int Index = 0; Index < NumSnapItems; Index++)
4353 {
4354 const IClient::CSnapItem Item = Client()->SnapGetItem(SnapId: IClient::SNAP_CURRENT, Index);
4355 if(Item.m_Type == NETOBJTYPE_ENTITYEX)
4356 vItemEx.push_back(x: {.m_Item: Item, .m_pDataEx: nullptr});
4357 else if(Item.m_Type == NETOBJTYPE_PICKUP || Item.m_Type == NETOBJTYPE_DDNETPICKUP || Item.m_Type == NETOBJTYPE_LASER || Item.m_Type == NETOBJTYPE_DDNETLASER || Item.m_Type == NETOBJTYPE_PROJECTILE || Item.m_Type == NETOBJTYPE_DDRACEPROJECTILE || Item.m_Type == NETOBJTYPE_DDNETPROJECTILE)
4358 vItemData.push_back(x: {.m_Item: Item, .m_pDataEx: nullptr});
4359 }
4360
4361 // sort by id
4362 class CEntComparer
4363 {
4364 public:
4365 bool operator()(const CSnapEntities &Lhs, const CSnapEntities &Rhs) const
4366 {
4367 return Lhs.m_Item.m_Id < Rhs.m_Item.m_Id;
4368 }
4369 };
4370
4371 std::sort(first: vItemData.begin(), last: vItemData.end(), comp: CEntComparer());
4372 std::sort(first: vItemEx.begin(), last: vItemEx.end(), comp: CEntComparer());
4373
4374 // merge extended items with items they belong to
4375 m_vSnapEntities.clear();
4376
4377 size_t IndexEx = 0;
4378 for(const CSnapEntities &Ent : vItemData)
4379 {
4380 while(IndexEx < vItemEx.size() && vItemEx[IndexEx].m_Item.m_Id < Ent.m_Item.m_Id)
4381 IndexEx++;
4382
4383 const CNetObj_EntityEx *pDataEx = nullptr;
4384 if(IndexEx < vItemEx.size() && vItemEx[IndexEx].m_Item.m_Id == Ent.m_Item.m_Id)
4385 pDataEx = (const CNetObj_EntityEx *)vItemEx[IndexEx].m_Item.m_pData;
4386
4387 m_vSnapEntities.push_back(x: {.m_Item: Ent.m_Item, .m_pDataEx: pDataEx});
4388 }
4389}
4390
4391void CGameClient::OnSaveCodeNetMessage(const CNetMsg_Sv_SaveCode *pMsg)
4392{
4393 char aBuf[512];
4394 if(pMsg->m_pError[0] != '\0')
4395 m_Chat.AddLine(ClientId: -1, Team: TEAM_ALL, pLine: pMsg->m_pError);
4396
4397 int State = pMsg->m_State;
4398 if(State == SAVESTATE_PENDING)
4399 {
4400 if(pMsg->m_pCode[0] == '\0')
4401 {
4402 str_format(buffer: aBuf, buffer_size: sizeof(aBuf),
4403 format: Localize(pStr: "Team save in progress. You'll be able to load with '/load %s'"),
4404 pMsg->m_pGeneratedCode);
4405 }
4406 else
4407 {
4408 str_format(buffer: aBuf, buffer_size: sizeof(aBuf),
4409 format: Localize(pStr: "Team save in progress. You'll be able to load with '/load %s' if save is successful or with '/load %s' if it fails"),
4410 pMsg->m_pCode,
4411 pMsg->m_pGeneratedCode);
4412 }
4413 m_Chat.AddLine(ClientId: -1, Team: TEAM_ALL, pLine: aBuf);
4414 }
4415 else if(State == SAVESTATE_DONE)
4416 {
4417 if(pMsg->m_pServerName[0] == '\0')
4418 {
4419 str_format(buffer: aBuf, buffer_size: sizeof(aBuf),
4420 format: "Team successfully saved by %s. Use '/load %s' to continue",
4421 pMsg->m_pSaveRequester,
4422 pMsg->m_pCode[0] ? pMsg->m_pCode : pMsg->m_pGeneratedCode);
4423 }
4424 else
4425 {
4426 str_format(buffer: aBuf, buffer_size: sizeof(aBuf),
4427 format: "Team successfully saved by %s. Use '/load %s' on %s to continue",
4428 pMsg->m_pSaveRequester,
4429 pMsg->m_pCode[0] ? pMsg->m_pCode : pMsg->m_pGeneratedCode,
4430 pMsg->m_pServerName);
4431 }
4432 m_Chat.AddLine(ClientId: -1, Team: TEAM_ALL, pLine: aBuf);
4433 }
4434 else if(State == SAVESTATE_FALLBACKFILE)
4435 {
4436 if(pMsg->m_pServerName[0] == '\0')
4437 {
4438 str_format(buffer: aBuf, buffer_size: sizeof(aBuf),
4439 format: Localize(pStr: "Team successfully saved by %s. The database connection failed, using generated save code instead to avoid collisions. Use '/load %s' to continue"),
4440 pMsg->m_pSaveRequester,
4441 pMsg->m_pGeneratedCode);
4442 }
4443 else
4444 {
4445 str_format(buffer: aBuf, buffer_size: sizeof(aBuf),
4446 format: Localize(pStr: "Team successfully saved by %s. The database connection failed, using generated save code instead to avoid collisions. Use '/load %s' on %s to continue"),
4447 pMsg->m_pSaveRequester,
4448 pMsg->m_pGeneratedCode,
4449 pMsg->m_pServerName);
4450 }
4451 m_Chat.AddLine(ClientId: -1, Team: TEAM_ALL, pLine: aBuf);
4452 }
4453 else if(State == SAVESTATE_ERROR)
4454 {
4455 m_Chat.AddLine(ClientId: -1, Team: TEAM_ALL, pLine: Localize(pStr: "Save failed!"));
4456 }
4457
4458 if(State != SAVESTATE_PENDING && State != SAVESTATE_ERROR && Client()->State() != IClient::STATE_DEMOPLAYBACK)
4459 {
4460 StoreSave(pTeamMembers: pMsg->m_pTeamMembers, pGeneratedCode: pMsg->m_pCode[0] ? pMsg->m_pCode : pMsg->m_pGeneratedCode);
4461 }
4462}
4463
4464void CGameClient::StoreSave(const char *pTeamMembers, const char *pGeneratedCode) const
4465{
4466 static constexpr const char *SAVES_HEADER[] = {
4467 "Time",
4468 "Players",
4469 "Map",
4470 "Code",
4471 };
4472
4473 char aTimestamp[20];
4474 str_timestamp_format(buffer: aTimestamp, buffer_size: sizeof(aTimestamp), format: TimestampFormat::SPACE);
4475
4476 const bool SavesFileExists = Storage()->FileExists(pFilename: SAVES_FILE, Type: IStorage::TYPE_SAVE);
4477 IOHANDLE File = Storage()->OpenFile(pFilename: SAVES_FILE, Flags: IOFLAG_APPEND, Type: IStorage::TYPE_SAVE);
4478 if(!File)
4479 {
4480 log_error("saves", "Failed to open the saves file '%s'", SAVES_FILE);
4481 return;
4482 }
4483
4484 const char *apColumns[std::size(SAVES_HEADER)] = {
4485 aTimestamp,
4486 pTeamMembers,
4487 Map()->BaseName(),
4488 pGeneratedCode,
4489 };
4490
4491 if(!SavesFileExists)
4492 {
4493 CsvWrite(File, NumColumns: std::size(SAVES_HEADER), ppColumns: SAVES_HEADER);
4494 }
4495 CsvWrite(File, NumColumns: std::size(SAVES_HEADER), ppColumns: apColumns);
4496 io_close(io: File);
4497}
4498