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 "gameworld.h"
5
6#include "entities/character.h"
7#include "entities/door.h"
8#include "entities/dragger.h"
9#include "entities/laser.h"
10#include "entities/pickup.h"
11#include "entities/plasma.h"
12#include "entities/projectile.h"
13#include "entity.h"
14
15#include <engine/shared/config.h>
16
17#include <game/client/laser_data.h>
18#include <game/client/pickup_data.h>
19#include <game/client/projectile_data.h>
20#include <game/collision.h>
21#include <game/mapbugs.h>
22#include <game/mapitems.h>
23
24#include <algorithm>
25#include <utility>
26
27//////////////////////////////////////////////////
28// game world
29//////////////////////////////////////////////////
30
31CGameWorld::CEntityIterator::CEntityIterator(CGameWorld *pWorld, CEntity *pFirstEntity) :
32 m_pWorld(pWorld),
33 m_pNext(pFirstEntity)
34{
35 m_pWorld->m_vpEntityIterators.push_back(x: this);
36}
37
38CGameWorld::CEntityIterator::CEntityIterator(CGameWorld *pWorld, int EntityType) :
39 m_pWorld(pWorld)
40{
41 dbg_assert(EntityType >= 0 && EntityType < NUM_ENTTYPES, "Invalid EntityType: %d", EntityType);
42 m_pNext = m_pWorld->m_apFirstEntityTypes[EntityType];
43 m_pWorld->m_vpEntityIterators.push_back(x: this);
44}
45
46CGameWorld::CEntityIterator::~CEntityIterator()
47{
48 dbg_assert(m_pWorld->m_vpEntityIterators.back() == this, "Inconsistent entity iterator removal");
49 m_pWorld->m_vpEntityIterators.pop_back();
50}
51
52void CGameWorld::CEntityIterator::AllowEntityRemoval()
53{
54 m_AllowEntityRemoval = true;
55}
56
57CEntity *CGameWorld::CEntityIterator::Next()
58{
59 CEntity *pResult = m_pNext;
60 if(m_pNext != nullptr)
61 {
62 m_pNext = m_pNext->m_pNextTypeEntity;
63 }
64 return pResult;
65}
66
67CGameWorld::CGameWorld()
68{
69 std::fill(first: std::begin(arr&: m_apFirstEntityTypes), last: std::end(arr&: m_apFirstEntityTypes), value: nullptr);
70 std::fill(first: std::begin(arr&: m_apCharacters), last: std::end(arr&: m_apCharacters), value: nullptr);
71 m_pCollision = nullptr;
72 m_GameTick = 0;
73 m_pParent = nullptr;
74 m_pChild = nullptr;
75}
76
77CGameWorld::~CGameWorld()
78{
79 Clear();
80 if(m_pChild && m_pChild->m_pParent == this)
81 {
82 OnModified();
83 m_pChild->m_pParent = nullptr;
84 }
85 if(m_pParent && m_pParent->m_pChild == this)
86 m_pParent->m_pChild = nullptr;
87}
88
89void CGameWorld::Init(CCollision *pCollision, CTuningParams *pTuningList, const CMapBugs *pMapBugs)
90{
91 m_pCollision = pCollision;
92 m_pTuningList = pTuningList;
93 m_pMapBugs = pMapBugs;
94}
95
96int CGameWorld::FindEntities(vec2 Pos, float Radius, CEntity **ppEnts, int Max, int Type)
97{
98 int Num = 0;
99 CEntityIterator Iterator(this, Type);
100 while(CEntity *pEnt = Iterator.Next())
101 {
102 if(distance(a: pEnt->m_Pos, b: Pos) < Radius + pEnt->m_ProximityRadius)
103 {
104 if(ppEnts)
105 ppEnts[Num] = pEnt;
106 Num++;
107 if(Num == Max)
108 break;
109 }
110 }
111
112 return Num;
113}
114
115void CGameWorld::InsertEntity(CEntity *pEnt, bool Last)
116{
117 pEnt->m_pGameWorld = this;
118 pEnt->m_pNextTypeEntity = nullptr;
119 pEnt->m_pPrevTypeEntity = nullptr;
120
121 // insert it
122 if(!Last)
123 {
124 if(m_apFirstEntityTypes[pEnt->m_ObjType])
125 m_apFirstEntityTypes[pEnt->m_ObjType]->m_pPrevTypeEntity = pEnt;
126 pEnt->m_pNextTypeEntity = m_apFirstEntityTypes[pEnt->m_ObjType];
127 pEnt->m_pPrevTypeEntity = nullptr;
128 m_apFirstEntityTypes[pEnt->m_ObjType] = pEnt;
129 }
130 else
131 {
132 // insert it at the end of the list
133 CEntity *pLast = m_apFirstEntityTypes[pEnt->m_ObjType];
134 if(pLast)
135 {
136 while(pLast->m_pNextTypeEntity)
137 pLast = pLast->m_pNextTypeEntity;
138 pLast->m_pNextTypeEntity = pEnt;
139 }
140 else
141 {
142 m_apFirstEntityTypes[pEnt->m_ObjType] = pEnt;
143 }
144 pEnt->m_pPrevTypeEntity = pLast;
145 pEnt->m_pNextTypeEntity = nullptr;
146 }
147
148 if(pEnt->m_ObjType == ENTTYPE_CHARACTER)
149 {
150 auto *pChar = (CCharacter *)pEnt;
151 int Id = pChar->GetCid();
152 if(Id >= 0 && Id < MAX_CLIENTS)
153 {
154 m_apCharacters[Id] = pChar;
155 m_Core.m_apCharacters[Id] = &pChar->m_Core;
156 }
157 pChar->SetCoreWorld(this);
158 }
159}
160
161void CGameWorld::RemoveEntity(CEntity *pEnt)
162{
163 // not in the list
164 if(!pEnt->m_pNextTypeEntity && !pEnt->m_pPrevTypeEntity && m_apFirstEntityTypes[pEnt->m_ObjType] != pEnt)
165 return;
166
167 for(CEntityIterator *pEntityIterator : m_vpEntityIterators)
168 {
169 dbg_assert(pEntityIterator->m_AllowEntityRemoval, "Removing entities not allowed with current iterator");
170 }
171
172 // remove
173 if(pEnt->m_pPrevTypeEntity)
174 pEnt->m_pPrevTypeEntity->m_pNextTypeEntity = pEnt->m_pNextTypeEntity;
175 else
176 m_apFirstEntityTypes[pEnt->m_ObjType] = pEnt->m_pNextTypeEntity;
177 if(pEnt->m_pNextTypeEntity)
178 pEnt->m_pNextTypeEntity->m_pPrevTypeEntity = pEnt->m_pPrevTypeEntity;
179
180 // keep list traversing valid
181 for(CEntityIterator *pEntityIterator : m_vpEntityIterators)
182 {
183 if(pEntityIterator->m_pNext == pEnt)
184 {
185 pEntityIterator->m_pNext = pEnt->m_pNextTypeEntity;
186 }
187 }
188
189 pEnt->m_pNextTypeEntity = nullptr;
190 pEnt->m_pPrevTypeEntity = nullptr;
191
192 if(pEnt->m_pParent)
193 {
194 if(m_IsValidCopy && m_pParent && m_pParent->m_pChild == this)
195 pEnt->m_pParent->m_DestroyTick = GameTick();
196 pEnt->m_pParent->m_pChild = nullptr;
197 pEnt->m_pParent = nullptr;
198 }
199 if(pEnt->m_pChild)
200 {
201 pEnt->m_pChild->m_pParent = nullptr;
202 pEnt->m_pChild = nullptr;
203 }
204}
205
206void CGameWorld::RemoveCharacter(CCharacter *pChar)
207{
208 int Id = pChar->GetCid();
209 if(Id >= 0 && Id < MAX_CLIENTS)
210 {
211 m_apCharacters[Id] = nullptr;
212 m_Core.m_apCharacters[Id] = nullptr;
213 }
214}
215
216void CGameWorld::RemoveEntities()
217{
218 // destroy objects marked for destruction
219 for(CEntity *pFirstEntity : m_apFirstEntityTypes)
220 {
221 CEntityIterator Iterator(this, pFirstEntity);
222 Iterator.AllowEntityRemoval();
223 while(CEntity *pEnt = Iterator.Next())
224 {
225 if(pEnt->m_MarkedForDestroy)
226 {
227 pEnt->Destroy();
228 }
229 }
230 }
231}
232
233void CGameWorld::Tick()
234{
235 // update all objects
236 for(int i = 0; i < NUM_ENTTYPES; i++)
237 {
238 // It's important to call PreTick() and Tick() after each other.
239 // If we call PreTick() before, and Tick() after other entities have been processed, it causes physics changes such as a stronger shotgun or grenade.
240 if(m_WorldConfig.m_NoWeakHookAndBounce && i == ENTTYPE_CHARACTER)
241 {
242 CEntityIterator Iterator(this, m_apFirstEntityTypes[ENTTYPE_CHARACTER]);
243 Iterator.AllowEntityRemoval();
244 while(CCharacter *pCharacter = static_cast<CCharacter *>(Iterator.Next()))
245 {
246 pCharacter->PreTick();
247 }
248 }
249
250 CEntityIterator Iterator(this, m_apFirstEntityTypes[i]);
251 Iterator.AllowEntityRemoval();
252 while(CEntity *pEnt = Iterator.Next())
253 {
254 pEnt->Tick();
255 }
256 }
257
258 for(CEntity *pFirstEntity : m_apFirstEntityTypes)
259 {
260 CEntityIterator Iterator(this, pFirstEntity);
261 Iterator.AllowEntityRemoval();
262 while(CEntity *pEnt = Iterator.Next())
263 {
264 pEnt->TickDeferred();
265 pEnt->m_SnapTicks++;
266 }
267 }
268
269 RemoveEntities();
270
271 // update switch state
272 for(auto &Switcher : Switchers())
273 {
274 for(int j = 0; j < NUM_DDRACE_TEAMS; ++j)
275 {
276 if(Switcher.m_aEndTick[j] <= GameTick() && Switcher.m_aType[j] == TILE_SWITCHTIMEDOPEN)
277 {
278 Switcher.m_aStatus[j] = false;
279 Switcher.m_aEndTick[j] = 0;
280 Switcher.m_aType[j] = TILE_SWITCHCLOSE;
281 }
282 else if(Switcher.m_aEndTick[j] <= GameTick() && Switcher.m_aType[j] == TILE_SWITCHTIMEDCLOSE)
283 {
284 Switcher.m_aStatus[j] = true;
285 Switcher.m_aEndTick[j] = 0;
286 Switcher.m_aType[j] = TILE_SWITCHOPEN;
287 }
288 }
289 }
290
291 OnModified();
292}
293
294CCharacter *CGameWorld::IntersectCharacter(vec2 Pos0, vec2 Pos1, float Radius, vec2 &NewPos, const CCharacter *pNotThis, int CollideWith, const CCharacter *pThisOnly)
295{
296 return (CCharacter *)IntersectEntity(Pos0, Pos1, Radius, Type: ENTTYPE_CHARACTER, NewPos, pNotThis, CollideWith, pThisOnly);
297}
298
299CEntity *CGameWorld::IntersectEntity(vec2 Pos0, vec2 Pos1, float Radius, int Type, vec2 &NewPos, const CEntity *pNotThis, int CollideWith, const CEntity *pThisOnly)
300{
301 float ClosestLen = distance(a: Pos0, b: Pos1) * 100.0f;
302 CEntity *pClosest = nullptr;
303
304 CEntityIterator Iterator(this, Type);
305 while(CEntity *pEntity = Iterator.Next())
306 {
307 if(pEntity == pNotThis)
308 continue;
309
310 if(pThisOnly && pEntity != pThisOnly)
311 continue;
312
313 if(CollideWith != -1 && !pEntity->CanCollide(ClientId: CollideWith))
314 continue;
315
316 vec2 IntersectPos;
317 if(closest_point_on_line(line_pointA: Pos0, line_pointB: Pos1, target_point: pEntity->m_Pos, out_pos&: IntersectPos))
318 {
319 float Len = distance(a: pEntity->m_Pos, b: IntersectPos);
320 if(Len < pEntity->m_ProximityRadius + Radius)
321 {
322 Len = distance(a: Pos0, b: IntersectPos);
323 if(Len < ClosestLen)
324 {
325 NewPos = IntersectPos;
326 ClosestLen = Len;
327 pClosest = pEntity;
328 }
329 }
330 }
331 }
332
333 return pClosest;
334}
335
336std::vector<CCharacter *> CGameWorld::IntersectedCharacters(vec2 Pos0, vec2 Pos1, float Radius, const CEntity *pNotThis)
337{
338 std::vector<CCharacter *> vpCharacters;
339 CEntityIterator Iterator(this, m_apFirstEntityTypes[ENTTYPE_CHARACTER]);
340 while(CCharacter *pChr = static_cast<CCharacter *>(Iterator.Next()))
341 {
342 if(pChr == pNotThis)
343 continue;
344
345 vec2 IntersectPos;
346 if(closest_point_on_line(line_pointA: Pos0, line_pointB: Pos1, target_point: pChr->m_Pos, out_pos&: IntersectPos))
347 {
348 float Len = distance(a: pChr->m_Pos, b: IntersectPos);
349 if(Len < pChr->m_ProximityRadius + Radius)
350 {
351 vpCharacters.push_back(x: pChr);
352 }
353 }
354 }
355 return vpCharacters;
356}
357
358void CGameWorld::ReleaseHooked(int ClientId)
359{
360 CEntityIterator Iterator(this, m_apFirstEntityTypes[ENTTYPE_CHARACTER]);
361 while(CCharacter *pChr = static_cast<CCharacter *>(Iterator.Next()))
362 {
363 if(pChr->Core()->HookedPlayer() == ClientId && !pChr->IsSuper())
364 {
365 pChr->ReleaseHook();
366 }
367 }
368}
369
370CEntity *CGameWorld::GetEntity(int Id, int EntityType)
371{
372 CEntityIterator Iterator(this, EntityType);
373 while(CEntity *pEnt = Iterator.Next())
374 if(pEnt->m_Id == Id)
375 return pEnt;
376 return nullptr;
377}
378
379void CGameWorld::CreateExplosion(vec2 Pos, int Owner, int Weapon, bool NoDamage, int ActivatedTeam, CClientMask Mask, int Id)
380{
381 if(Owner < 0 && m_WorldConfig.m_IsSolo && !(Weapon == WEAPON_SHOTGUN && m_WorldConfig.m_IsDDRace))
382 return;
383
384 if(m_WorldConfig.m_IsDDRace && m_WorldConfig.m_PredictDDRace)
385 {
386 // vanilla has different projectile physics
387 CreatePredictedExplosionEvent(Pos, Id);
388 }
389
390 // deal damage
391 CEntity *apEnts[MAX_CLIENTS];
392 float Radius = 135.0f;
393 float InnerRadius = 48.0f;
394 int Num = FindEntities(Pos, Radius, ppEnts: apEnts, Max: MAX_CLIENTS, Type: CGameWorld::ENTTYPE_CHARACTER);
395 for(int i = 0; i < Num; i++)
396 {
397 auto *pChar = static_cast<CCharacter *>(apEnts[i]);
398 vec2 Diff = pChar->m_Pos - Pos;
399 vec2 ForceDir(0, 1);
400 float l = length(a: Diff);
401 if(l)
402 ForceDir = normalize(v: Diff);
403 l = 1 - std::clamp(val: (l - InnerRadius) / (Radius - InnerRadius), lo: 0.0f, hi: 1.0f);
404 float Strength;
405 CCharacter *pOwnerChar = GetCharacterById(Id: Owner);
406 if(Owner == -1 || !pOwnerChar)
407 Strength = GlobalTuning()->m_ExplosionStrength;
408 else
409 Strength = pOwnerChar->GetTuning(i: pOwnerChar->GetOverriddenTuneZone())->m_ExplosionStrength;
410
411 float Dmg = Strength * l;
412 if((int)Dmg)
413 if((pOwnerChar ? !pOwnerChar->GrenadeHitDisabled() : g_Config.m_SvHit || NoDamage) || Owner == pChar->GetCid())
414 {
415 if(Owner != -1 && !pChar->CanCollide(ClientId: Owner))
416 continue;
417 if(Owner == -1 && ActivatedTeam != -1 && pChar->Team() != ActivatedTeam)
418 continue;
419 pChar->TakeDamage(Force: ForceDir * Dmg * 2, Dmg: (int)Dmg, From: Owner, Weapon);
420 if(pOwnerChar)
421 {
422 pOwnerChar->AntiPingInterference(ClientId: pChar->GetCid());
423 }
424 if(pOwnerChar ? pOwnerChar->GrenadeHitDisabled() : !g_Config.m_SvHit || NoDamage)
425 break;
426 }
427 }
428}
429
430bool CGameWorld::IsLocalTeam(int OwnerId) const
431{
432 return OwnerId < 0 || m_Teams.CanCollide(ClientId1: m_LocalClientId, ClientId2: OwnerId);
433}
434
435void CGameWorld::NetObjBegin(CTeamsCore Teams, int LocalClientId)
436{
437 m_Teams = Teams;
438 m_LocalClientId = LocalClientId;
439
440 for(int i = 0; i < NUM_ENTTYPES; i++)
441 {
442 CEntityIterator Iterator(this, m_apFirstEntityTypes[i]);
443 while(CEntity *pEnt = Iterator.Next())
444 {
445 pEnt->m_MarkedForDestroy = true;
446 if(i == ENTTYPE_CHARACTER)
447 ((CCharacter *)pEnt)->m_KeepHooked = false;
448 }
449 }
450 OnModified();
451}
452
453void CGameWorld::NetCharAdd(int ObjId, CNetObj_Character *pCharObj, CNetObj_DDNetCharacter *pExtended, int GameTeam, bool IsLocal)
454{
455 if(IsLocalTeam(OwnerId: ObjId))
456 {
457 CCharacter *pChar;
458 if((pChar = (CCharacter *)GetEntity(Id: ObjId, EntityType: ENTTYPE_CHARACTER)))
459 {
460 pChar->Read(pChar: pCharObj, pExtended, IsLocal);
461 pChar->Keep();
462 }
463 else
464 {
465 pChar = new CCharacter(this, ObjId, pCharObj, pExtended);
466 InsertEntity(pEnt: pChar);
467 }
468
469 if(pChar)
470 pChar->m_GameTeam = GameTeam;
471 }
472}
473
474void CGameWorld::NetObjAdd(int ObjId, int ObjType, const void *pObjData, const CNetObj_EntityEx *pDataEx)
475{
476 if((ObjType == NETOBJTYPE_PROJECTILE || ObjType == NETOBJTYPE_DDRACEPROJECTILE || ObjType == NETOBJTYPE_DDNETPROJECTILE) && m_WorldConfig.m_PredictWeapons)
477 {
478 CProjectileData Data = ExtractProjectileInfo(NetObjType: ObjType, pData: pObjData, pGameWorld: this, pEntEx: pDataEx);
479 if(!IsLocalTeam(OwnerId: Data.m_Owner))
480 return;
481
482 CProjectile NetProj = CProjectile(this, ObjId, &Data);
483
484 if(NetProj.m_Type != WEAPON_SHOTGUN && absolute(a: length(a: NetProj.m_Direction) - 1.f) > 0.02f) // workaround to skip grenades on ball mod
485 return;
486
487 if(CProjectile *pProj = (CProjectile *)GetEntity(Id: ObjId, EntityType: ENTTYPE_PROJECTILE))
488 {
489 if(NetProj.Match(pProj))
490 {
491 pProj->Keep();
492 if(pProj->m_Type == WEAPON_SHOTGUN && m_WorldConfig.m_IsDDRace)
493 pProj->m_LifeSpan = 20 * GameTickSpeed() - (GameTick() - pProj->m_StartTick);
494 return;
495 }
496 }
497 if(!Data.m_ExtraInfo)
498 {
499 // try to match the newly received (unrecognized) projectile with a locally fired one
500 {
501 CEntityIterator Iterator(this, m_apFirstEntityTypes[ENTTYPE_PROJECTILE]);
502 while(CProjectile *pProj = static_cast<CProjectile *>(Iterator.Next()))
503 {
504 if(pProj->m_Id == -1 && NetProj.Match(pProj))
505 {
506 pProj->m_Id = ObjId;
507 pProj->Keep();
508 return;
509 }
510 }
511 }
512 // otherwise try to determine its owner by checking if there is only one player nearby
513 if(NetProj.m_StartTick >= GameTick() - 4)
514 {
515 const vec2 NetPos = NetProj.m_Pos - normalize(v: NetProj.m_Direction) * CCharacterCore::PhysicalSize() * 0.75;
516 const bool Prev = (GameTick() - NetProj.m_StartTick) > 1;
517 float First = 200.0f, Second = 200.0f;
518 CCharacter *pClosest = nullptr;
519 CEntityIterator Iterator(this, m_apFirstEntityTypes[ENTTYPE_CHARACTER]);
520 while(CCharacter *pChar = static_cast<CCharacter *>(Iterator.Next()))
521 {
522 float Dist = distance(a: Prev ? pChar->m_PrevPrevPos : pChar->m_PrevPos, b: NetPos);
523 if(Dist < First)
524 {
525 Second = First;
526 pClosest = pChar;
527 First = Dist;
528 }
529 else if(Dist < Second)
530 {
531 Second = Dist;
532 }
533 }
534 if(pClosest && std::max(a: First, b: 2.0f) * 1.2f < Second)
535 NetProj.m_Owner = pClosest->m_Id;
536 }
537 }
538 CProjectile *pProj = new CProjectile(NetProj);
539 InsertEntity(pEnt: pProj);
540 }
541 else if((ObjType == NETOBJTYPE_PICKUP || ObjType == NETOBJTYPE_DDNETPICKUP) && m_WorldConfig.m_PredictWeapons)
542 {
543 CPickupData Data = ExtractPickupInfo(NetObjType: ObjType, pData: pObjData, pEntEx: pDataEx);
544 if(Data.m_Flags & PICKUPFLAG_NO_PREDICT)
545 return;
546 CPickup NetPickup = CPickup(this, ObjId, &Data);
547 if(CPickup *pPickup = (CPickup *)GetEntity(Id: ObjId, EntityType: ENTTYPE_PICKUP))
548 {
549 if(NetPickup.Match(pPickup))
550 {
551 pPickup->m_Pos = NetPickup.m_Pos;
552 pPickup->Keep();
553 return;
554 }
555 }
556 CEntity *pEnt = new CPickup(NetPickup);
557 InsertEntity(pEnt, Last: true);
558 }
559 else if(ObjType == NETOBJTYPE_LASER || ObjType == NETOBJTYPE_DDNETLASER)
560 {
561 CLaserData Data = ExtractLaserInfo(NetObjType: ObjType, pData: pObjData, pGameWorld: this, pEntEx: pDataEx);
562 if(!IsLocalTeam(OwnerId: Data.m_Owner) || !Data.m_Predict)
563 {
564 return;
565 }
566
567 // Doors are static world geometry that only ever adds move restrictions to tiles,
568 // so they follow the tile physics config rather than the weapon prediction config.
569 if(!(Data.m_Type == LASERTYPE_DOOR ? m_WorldConfig.m_PredictTiles : m_WorldConfig.m_PredictWeapons))
570 {
571 return;
572 }
573
574 if(Data.m_Type == LASERTYPE_RIFLE || Data.m_Type == LASERTYPE_SHOTGUN || Data.m_Type < 0)
575 {
576 CLaser NetLaser = CLaser(this, ObjId, &Data);
577 CLaser *pMatching = nullptr;
578 if(CLaser *pLaser = static_cast<CLaser *>(GetEntity(Id: ObjId, EntityType: ENTTYPE_LASER)))
579 if(NetLaser.Match(pLaser))
580 pMatching = pLaser;
581 if(!pMatching)
582 {
583 CEntityIterator Iterator(this, m_apFirstEntityTypes[ENTTYPE_LASER]);
584 while(CLaser *pLaser = static_cast<CLaser *>(Iterator.Next()))
585 {
586 if(pLaser->m_Id == -1 && NetLaser.Match(pLaser))
587 {
588 pMatching = pLaser;
589 pMatching->m_Id = ObjId;
590 break;
591 }
592 }
593 }
594 if(pMatching)
595 {
596 pMatching->Keep();
597 if(distance(a: NetLaser.m_From, b: NetLaser.m_Pos) < distance(a: pMatching->m_From, b: pMatching->m_Pos) - 2.f)
598 {
599 // if the laser stopped earlier than predicted, set the energy to 0
600 pMatching->m_Energy = 0.f;
601 pMatching->m_Pos = NetLaser.m_Pos;
602 }
603 }
604 }
605 else if(Data.m_Type == LASERTYPE_DRAGGER)
606 {
607 CDragger NetDragger = CDragger(this, ObjId, &Data);
608 if(NetDragger.GetStrength() > 0)
609 {
610 auto *pDragger = static_cast<CDragger *>(GetEntity(Id: ObjId, EntityType: ENTTYPE_DRAGGER));
611 if(pDragger && NetDragger.Match(pDragger))
612 {
613 pDragger->Keep();
614 pDragger->Read(pData: &Data);
615 return;
616 }
617 CEntity *pEnt = new CDragger(NetDragger);
618 InsertEntity(pEnt);
619 }
620 }
621 else if(Data.m_Type == LASERTYPE_DOOR)
622 {
623 CDoor NetDoor = CDoor(this, ObjId, &Data);
624 auto *pDoor = static_cast<CDoor *>(GetEntity(Id: ObjId, EntityType: ENTTYPE_DOOR));
625 if(pDoor && NetDoor.Match(pDoor))
626 {
627 pDoor->Keep();
628 pDoor->Read(pData: &Data);
629 return;
630 }
631 CDoor *pEnt = new CDoor(NetDoor);
632 InsertEntity(pEnt);
633 }
634 else if(Data.m_Type == LASERTYPE_PLASMA)
635 {
636 CPlasma NetPlasma = CPlasma(this, ObjId, &Data);
637 auto *pPlasma = static_cast<CPlasma *>(GetEntity(Id: ObjId, EntityType: ENTTYPE_PLASMA));
638 if(pPlasma && NetPlasma.Match(pPlasma))
639 {
640 pPlasma->Keep();
641 pPlasma->Read(pData: &Data);
642 return;
643 }
644 CPlasma *pEnt = new CPlasma(NetPlasma);
645 InsertEntity(pEnt);
646 }
647 }
648}
649
650void CGameWorld::ResetDoorCollision()
651{
652 // Doors add their move restrictions to the collision grid shared by the whole client
653 // rather than keeping them on the entity, so the grid is rebuilt after every snapshot:
654 // a destroyed door clears its entire span, including tiles another door still occupies.
655 // Doors are applied in map order, the order the server creates them in, so intersecting
656 // doors resolve to the same tile on both sides. Two doors originating on the same tile
657 // share a map index; the server creates the game/front-layer door before the switch-layer
658 // one, so the switch door (m_Number > 0) stamps the shared origin tile last and wins.
659 std::vector<CDoor *> vpDoors;
660 CEntityIterator Iterator(this, m_apFirstEntityTypes[ENTTYPE_DOOR]);
661 while(CDoor *pDoor = static_cast<CDoor *>(Iterator.Next()))
662 vpDoors.push_back(x: pDoor);
663 std::stable_sort(first: vpDoors.begin(), last: vpDoors.end(), comp: [this](const CDoor *pLeft, const CDoor *pRight) {
664 const int LeftIndex = Collision()->GetPureMapIndex(Pos: pLeft->m_Pos);
665 const int RightIndex = Collision()->GetPureMapIndex(Pos: pRight->m_Pos);
666 if(LeftIndex != RightIndex)
667 return LeftIndex < RightIndex;
668 return (pLeft->m_Number > 0) < (pRight->m_Number > 0);
669 });
670 for(CDoor *pDoor : vpDoors)
671 pDoor->ResetCollision();
672}
673
674void CGameWorld::NetObjEnd()
675{
676 // keep predicting hooked characters, based on hook position
677 for(int i = 0; i < MAX_CLIENTS; i++)
678 if(CCharacter *pChar = GetCharacterById(Id: i))
679 if(!pChar->m_MarkedForDestroy)
680 if(CCharacter *pHookedChar = GetCharacterById(Id: pChar->m_Core.HookedPlayer()))
681 if(pHookedChar->m_MarkedForDestroy)
682 {
683 pHookedChar->m_Pos = pHookedChar->m_Core.m_Pos = pChar->m_Core.m_HookPos;
684 pHookedChar->ResetVelocity();
685 mem_zero(block: &pHookedChar->m_SavedInput, size: sizeof(pHookedChar->m_SavedInput));
686 pHookedChar->m_SavedInput.m_TargetY = -1;
687 pHookedChar->m_KeepHooked = true;
688 pHookedChar->m_MarkedForDestroy = false;
689 }
690 RemoveEntities();
691 ResetDoorCollision();
692
693 // Update character IDs and pointers
694 for(int i = 0; i < MAX_CLIENTS; i++)
695 {
696 m_apCharacters[i] = nullptr;
697 m_Core.m_apCharacters[i] = nullptr;
698 }
699 CEntityIterator Iterator(this, m_apFirstEntityTypes[ENTTYPE_CHARACTER]);
700 while(CCharacter *pChar = static_cast<CCharacter *>(Iterator.Next()))
701 {
702 int Id = pChar->GetCid();
703 if(Id >= 0 && Id < MAX_CLIENTS)
704 {
705 m_apCharacters[Id] = pChar;
706 m_Core.m_apCharacters[Id] = &pChar->m_Core;
707 }
708 }
709}
710
711void CGameWorld::CopyWorld(CGameWorld *pFrom)
712{
713 if(pFrom == this || !pFrom)
714 return;
715 m_IsValidCopy = false;
716 m_pParent = pFrom;
717 if(m_pParent->m_pChild && m_pParent->m_pChild != this)
718 m_pParent->m_pChild->m_IsValidCopy = false;
719 pFrom->m_pChild = this;
720
721 m_GameTick = pFrom->m_GameTick;
722 m_pCollision = pFrom->m_pCollision;
723 m_WorldConfig = pFrom->m_WorldConfig;
724 m_pTuningList = pFrom->m_pTuningList;
725 m_pMapBugs = pFrom->m_pMapBugs;
726 m_Teams = pFrom->m_Teams;
727 m_Core.m_vSwitchers = pFrom->m_Core.m_vSwitchers;
728 m_PredictedEvents = pFrom->m_PredictedEvents;
729 // delete the previous entities
730 Clear();
731 for(int i = 0; i < MAX_CLIENTS; i++)
732 {
733 m_apCharacters[i] = nullptr;
734 m_Core.m_apCharacters[i] = nullptr;
735 }
736 // copy and add the new entities
737 for(int Type = 0; Type < NUM_ENTTYPES; Type++)
738 {
739 CEntity *pLast = pFrom->m_apFirstEntityTypes[Type];
740 if(pLast)
741 {
742 while(pLast->m_pNextTypeEntity)
743 {
744 pLast = pLast->m_pNextTypeEntity;
745 }
746 }
747 for(CEntity *pEnt = pLast; pEnt; pEnt = pEnt->m_pPrevTypeEntity)
748 {
749 CEntity *pCopy = nullptr;
750 if(Type == ENTTYPE_PROJECTILE)
751 pCopy = new CProjectile(*((CProjectile *)pEnt));
752 else if(Type == ENTTYPE_LASER)
753 pCopy = new CLaser(*((CLaser *)pEnt));
754 else if(Type == ENTTYPE_DRAGGER)
755 pCopy = new CDragger(*((CDragger *)pEnt));
756 else if(Type == ENTTYPE_CHARACTER)
757 pCopy = new CCharacter(*((CCharacter *)pEnt));
758 else if(Type == ENTTYPE_PICKUP)
759 pCopy = new CPickup(*((CPickup *)pEnt));
760 else if(Type == ENTTYPE_PLASMA)
761 pCopy = new CPlasma(*((CPlasma *)pEnt));
762 if(pCopy)
763 {
764 pCopy->m_pParent = pEnt;
765 pEnt->m_pChild = pCopy;
766 this->InsertEntity(pEnt: pCopy);
767 }
768 }
769 }
770 m_IsValidCopy = true;
771}
772
773CEntity *CGameWorld::FindMatch(int ObjId, int ObjType, const void *pObjData)
774{
775 switch(ObjType)
776 {
777 case NETOBJTYPE_CHARACTER:
778 {
779 CCharacter *pEnt = (CCharacter *)GetEntity(Id: ObjId, EntityType: ENTTYPE_CHARACTER);
780 if(pEnt && CCharacter(this, ObjId, (CNetObj_Character *)pObjData).Match(pChar: pEnt))
781 {
782 return pEnt;
783 }
784 return nullptr;
785 }
786 case NETOBJTYPE_PROJECTILE:
787 case NETOBJTYPE_DDRACEPROJECTILE:
788 case NETOBJTYPE_DDNETPROJECTILE:
789 {
790 CProjectileData Data = ExtractProjectileInfo(NetObjType: ObjType, pData: pObjData, pGameWorld: this, pEntEx: nullptr);
791 CProjectile *pEnt = (CProjectile *)GetEntity(Id: ObjId, EntityType: ENTTYPE_PROJECTILE);
792 if(pEnt && CProjectile(this, ObjId, &Data).Match(pProj: pEnt))
793 {
794 return pEnt;
795 }
796 return nullptr;
797 }
798 case NETOBJTYPE_LASER:
799 case NETOBJTYPE_DDNETLASER:
800 {
801 CLaserData Data = ExtractLaserInfo(NetObjType: ObjType, pData: pObjData, pGameWorld: this, pEntEx: nullptr);
802 if(Data.m_Type == LASERTYPE_RIFLE || Data.m_Type == LASERTYPE_SHOTGUN)
803 {
804 CLaser *pEnt = (CLaser *)GetEntity(Id: ObjId, EntityType: ENTTYPE_LASER);
805 if(pEnt && CLaser(this, ObjId, &Data).Match(pLaser: pEnt))
806 {
807 return pEnt;
808 }
809 }
810 else if(Data.m_Type == LASERTYPE_DRAGGER)
811 {
812 CDragger *pEnt = (CDragger *)GetEntity(Id: ObjId, EntityType: ENTTYPE_DRAGGER);
813 if(pEnt && CDragger(this, ObjId, &Data).Match(pDragger: pEnt))
814 {
815 return pEnt;
816 }
817 }
818 else if(Data.m_Type == LASERTYPE_DOOR)
819 {
820 CDoor *pEnt = (CDoor *)GetEntity(Id: ObjId, EntityType: ENTTYPE_DOOR);
821 if(pEnt && CDoor(this, ObjId, &Data).Match(pDoor: pEnt))
822 {
823 return pEnt;
824 }
825 }
826 else if(Data.m_Type == LASERTYPE_PLASMA)
827 {
828 CPlasma *pEnt = (CPlasma *)GetEntity(Id: ObjId, EntityType: ENTTYPE_PLASMA);
829 if(pEnt && CPlasma(this, ObjId, &Data).Match(pPlasma: pEnt))
830 {
831 return pEnt;
832 }
833 }
834 return nullptr;
835 }
836 case NETOBJTYPE_PICKUP:
837 case NETOBJTYPE_DDNETPICKUP:
838 {
839 CPickupData Data = ExtractPickupInfo(NetObjType: ObjType, pData: pObjData, pEntEx: nullptr);
840 CPickup *pEnt = (CPickup *)GetEntity(Id: ObjId, EntityType: ENTTYPE_PICKUP);
841 if(pEnt && CPickup(this, ObjId, &Data).Match(pPickup: pEnt))
842 {
843 return pEnt;
844 }
845 return nullptr;
846 }
847 }
848 return nullptr;
849}
850
851void CGameWorld::OnModified() const
852{
853 if(m_pChild)
854 m_pChild->m_IsValidCopy = false;
855}
856
857void CGameWorld::Clear()
858{
859 // delete all entities
860 for(auto &pFirstEntityType : m_apFirstEntityTypes)
861 while(pFirstEntityType)
862 delete pFirstEntityType; // NOLINT(clang-analyzer-cplusplus.NewDelete)
863}
864
865bool CGameWorld::EmulateBug(int Bug) const
866{
867 return m_pMapBugs->Contains(Bug);
868}
869
870void CGameWorld::CreatePredictedEvent(const CPredictedEvent &NewEvent)
871{
872 if(!g_Config.m_ClPredictEvents || !m_WorldConfig.m_PredictEvents)
873 return;
874
875 // prediction is ran multiple times per tick, check if event already exists
876 const auto It = std::find_if(
877 first: m_PredictedEvents.begin(),
878 last: m_PredictedEvents.end(),
879 pred: [NewEvent](const CPredictedEvent &Event) {
880 return Event.m_EventId == NewEvent.m_EventId && Event.m_ExtraInfo == NewEvent.m_ExtraInfo &&
881 Event.m_Pos == NewEvent.m_Pos && Event.m_Id == NewEvent.m_Id && Event.m_Tick == NewEvent.m_Tick;
882 });
883
884 if(It == m_PredictedEvents.end())
885 {
886 m_PredictedEvents.push_back(x: NewEvent);
887 }
888}
889
890bool CGameWorld::CheckPredictedEventHandled(const CPredictedEvent &CheckEvent)
891{
892 // events could be delayed by ping, so don't check for exact tick match
893 // also received events don't have Id
894 auto It = std::find_if(
895 first: m_PredictedEvents.begin(),
896 last: m_PredictedEvents.end(),
897 pred: [CheckEvent](const CPredictedEvent &Event) {
898 return Event.m_Handled == true && Event.m_EventId == CheckEvent.m_EventId &&
899 Event.m_Pos == CheckEvent.m_Pos && Event.m_Tick <= CheckEvent.m_Tick && Event.m_ExtraInfo == CheckEvent.m_ExtraInfo;
900 });
901
902 if(It == m_PredictedEvents.end())
903 {
904 return false;
905 }
906
907 // remove the event after it has been confirmed played
908 m_PredictedEvents.erase(position: It);
909 return true;
910}
911
912void CGameWorld::CreatePredictedSound(vec2 Pos, int SoundId, int Id)
913{
914 if(!g_Config.m_SndEnable)
915 return;
916
917 CPredictedEvent Event(NETEVENTTYPE_SOUNDWORLD, Pos, Id, GameTick(), SoundId);
918 CreatePredictedEvent(NewEvent: Event);
919}
920
921void CGameWorld::CreatePredictedExplosionEvent(vec2 Pos, int Id)
922{
923 CPredictedEvent Event(NETEVENTTYPE_EXPLOSION, Pos, Id, GameTick());
924 CreatePredictedEvent(NewEvent: Event);
925}
926
927void CGameWorld::CreatePredictedHammerHitEvent(vec2 Pos, int Id)
928{
929 CPredictedEvent Event(NETEVENTTYPE_HAMMERHIT, Pos, Id, GameTick());
930 CreatePredictedEvent(NewEvent: Event);
931}
932
933void CGameWorld::CreatePredictedDamageIndEvent(vec2 Pos, float Angle, int Amount, int Id)
934{
935 float a = 3 * pi / 2 + Angle;
936 float s = a - pi / 3;
937 float e = a + pi / 3;
938 for(int i = 0; i < Amount; i++)
939 {
940 float f = mix(a: s, b: e, amount: (i + 1) / (float)(Amount + 1));
941
942 CPredictedEvent Event(NETEVENTTYPE_DAMAGEIND, Pos, Id, GameTick(), (int)(f * 256.0f));
943 CreatePredictedEvent(NewEvent: Event);
944 }
945}
946