114 Commits

Author SHA1 Message Date
fd2288ac3c refactor xmake.lua 2022-09-03 16:55:36 +02:00
660952aed3 add example map 2022-07-18 12:12:53 +02:00
243b153309 remove unsed variable 2022-07-18 11:51:52 +02:00
73fa10d8d6 fixing log 2022-07-18 11:50:30 +02:00
0b8a7d8db7 hmmm 2022-07-14 18:42:46 +02:00
e2ec9d6a3b add player getter 2022-07-14 18:40:52 +02:00
eb5b3c8ce2 explicit cast zlib functions 2022-07-14 18:39:28 +02:00
ddbba7399d use of loge 2022-07-14 18:39:06 +02:00
9ce1f4a1a8 add loge 2022-07-14 18:35:11 +02:00
ea4349af4c fix log android 2022-07-14 18:34:26 +02:00
d6fbb58da8 using log calls 2022-07-14 18:32:32 +02:00
66376eaeda allow custom opengl loader 2022-07-14 18:04:13 +02:00
85eb9bbc32 add exp sync 2022-07-14 13:09:38 +02:00
bbb84c0061 add log 2022-07-14 13:08:20 +02:00
2f1161959b remove unused includes 2022-07-14 13:07:41 +02:00
f506307653 refactor databuffer write 2022-07-04 11:17:30 +02:00
40f0d50991 util format function 2022-07-04 11:13:26 +02:00
663ad60ee3 util player methods 2022-07-04 11:13:11 +02:00
3fbb6acac7 fix initial stats 2022-07-04 10:42:31 +02:00
377e98f583 fix warnings 2022-07-04 10:24:18 +02:00
ef9712629f remove use of loops in protocol 2022-06-29 12:42:21 +02:00
ed481de03e add databuffer helper functions 2022-06-29 12:35:36 +02:00
7d667d9c5e add buy packets 2022-06-29 12:13:58 +02:00
16006adc6e fix more warnings 2022-06-27 13:33:24 +02:00
19062b5c77 fix warnings 2022-06-27 13:12:39 +02:00
d3c6ff3988 fix MobSend size 2022-06-27 13:12:20 +02:00
31a0027bfc add namespace comments 2022-06-27 12:29:22 +02:00
d4b1805998 refactor: forgot this one 2022-04-27 19:46:41 +02:00
b84f1fd302 fix: remove useless warning flag 2022-04-27 19:46:09 +02:00
98f73f467d fix: change ChunkCoords hashing 2022-04-27 19:44:16 +02:00
dc8a4ce947 refactor: alpha sort methods 2022-04-27 19:41:03 +02:00
113a831f39 refactor: removed unused semicolon 2022-04-27 19:35:45 +02:00
f906aa1bf0 refactor: more casts 2022-04-27 19:34:45 +02:00
1bbf607b22 refactor: show override 2022-04-27 19:34:12 +02:00
d5b42caf39 refactor: cpp style casts 2022-04-27 19:25:36 +02:00
d3edc0cb6c refactor: spaces instead of tabs 2022-04-27 18:44:22 +02:00
87e4e65843 refactor: remove useless namespace 2022-04-27 18:38:10 +02:00
7509cc1bf2 feat: add player upgrades 2022-04-27 18:37:07 +02:00
6df59b1487 GIGA REFACTOR 2022-03-02 18:51:42 +01:00
553b2f6aad feat: show demo window on debug only 2022-02-17 19:39:07 +01:00
916fa0e7c0 format 2022-02-17 19:35:09 +01:00
bc271bc01e protocol rework + map packet ids removal 2022-02-17 19:35:02 +01:00
97a33e5517 BIG REFACTOR Part 2 2022-02-16 18:34:49 +01:00
bdebabb79e BIG REFACTOR 2022-02-16 17:54:33 +01:00
387cff36ad style: more space 2022-02-16 16:32:05 +01:00
790237a1b5 refactor: changed to PlayerID type 2022-02-16 16:31:18 +01:00
840d5edbe4 refactor: changed exp and money update 2022-02-16 16:18:25 +01:00
36a9e1921c refactor: use of const reference 2022-01-07 18:30:37 +01:00
784c558840 chore: bump version to "alpha-0.2.0" 2021-12-19 18:40:44 +01:00
5d366b6f6c feat: sync game 2021-12-19 18:40:14 +01:00
f70661694b chore: bump version to "alpha-0.1.2" 2021-12-19 11:58:36 +01:00
36a1ab0572 feat: close server when game finished 2021-12-19 11:57:47 +01:00
409268b604 refactor: use of GuiManager 2021-12-19 11:56:41 +01:00
174d144d26 refactor: add default server tps 2021-12-19 11:38:54 +01:00
360258e4cf feat: add end game disconnect 2021-12-13 20:05:20 +01:00
2148c0050c refactor: add game listener 2021-12-13 19:45:01 +01:00
61166023df feat: don't show tile select when tooltip 2021-12-12 16:59:57 +01:00
e7bf22cea6 feat: add pseudo end game 2021-12-12 16:59:35 +01:00
f09f79198d fix: windows build 2021-12-12 16:41:48 +01:00
8c19d3cc3c refactor: removed unused constant 2021-12-12 16:27:59 +01:00
208892d266 chore: update to alpha-0.1.1 2021-12-12 16:17:53 +01:00
4384806cf0 refactor: removed unused comment 2021-12-12 16:14:24 +01:00
1a091baeaf feat: add map background color 2021-12-12 16:13:05 +01:00
43f21ffd44 chore: bump verssion to alpha-0.1.0 2021-12-12 13:33:12 +01:00
24617c539f feat: add castle tooltip 2021-12-12 13:32:39 +01:00
4611a198c9 fix: add mob spawn border 2021-12-12 13:31:01 +01:00
d40ffe8f6c refactor: removed unused include 2021-12-12 11:36:56 +01:00
384b7ad51e chore: bump version to alpha-0.0.5 2021-12-11 20:07:26 +01:00
fd9b448fa4 feat: mob castle damage 2021-12-11 20:06:52 +01:00
c4a2b08416 feat: add mob spawn notification 2021-12-11 19:56:03 +01:00
a241d7691b refactor: mob die event 2021-12-11 19:51:45 +01:00
0af4cd506c refactor: moved mob functions 2021-12-11 19:30:31 +01:00
6b5c56b37d feat: notify when mob touches castle 2021-12-11 18:46:47 +01:00
1474220a77 refactor: separate mob ans world listener 2021-12-11 18:43:49 +01:00
a802b5cef5 fix: windows compilation 2021-12-08 17:24:29 +01:00
7e91b863da bump version to alpha-0.0.4 2021-12-08 15:39:26 +01:00
129bb47286 feat: debug library 2021-12-08 15:38:20 +01:00
e4a9c5f763 feat: remove tower 2021-12-08 15:34:20 +01:00
78cf2d0f18 Merge branch 'master' of 192.168.0.5:repos/Tower-Defense 2021-12-05 12:01:50 +01:00
00d2b5394f refactor: removed unused include 2021-12-05 12:01:17 +01:00
00414abe61 refactor: comment main 2021-12-04 19:09:26 +01:00
cb847d0edd refactor: removed unused declarations 2021-12-04 13:49:50 +01:00
2da0bd9b79 refactor: tower add event processing 2021-12-04 13:44:34 +01:00
cf9633c061 fix: mob spawning repartition 2021-12-03 18:47:55 +01:00
7a6fdc30b6 add fire arrow and fix world events 2021-12-03 18:30:45 +01:00
657fe761ab feat: bump version to alpha-0.0.3 2021-11-30 18:45:42 +01:00
687944bf51 fix: don't call onmobdamage with null damage 2021-11-30 18:45:09 +01:00
93e079ddb3 refactor: archer tower aoe damage 2021-11-30 18:38:40 +01:00
8171a91ed5 feat: add world notifier 2021-11-30 18:36:29 +01:00
0c1824e40b refactor: movd Updater 2021-11-30 18:07:25 +01:00
f91ab4bc83 fix: compilation error 2021-11-30 18:06:33 +01:00
1843fc6f4d feat: add archer tower aoe 2021-11-30 18:01:48 +01:00
6a51638b7e feat: add more shape distances 2021-11-30 18:01:07 +01:00
8351c5d09f refactor: add typo 2021-11-30 18:00:41 +01:00
ee94c811e1 feat: add archer tower damage 2021-11-30 18:00:19 +01:00
50a8269773 feat: add better mob pathing 2021-11-30 11:53:58 +01:00
2996c88d94 feat: add mob coords in tile coords space 2021-11-30 11:23:03 +01:00
55263fa582 fix: changed skel effect immunities 2021-11-29 16:39:29 +01:00
adeddee09d refactor: mob move lock (Castle) 2021-11-29 16:36:27 +01:00
f0115166c0 fix: compiler warning 2021-11-22 19:39:09 +01:00
c1affc36c0 chore: bump version to alpha-0.0.2 2021-11-22 19:36:14 +01:00
6c4ef25abd style: changed tower place popup size 2021-11-22 19:35:50 +01:00
fd0a5e5848 feat: mob stop in front of castle 2021-11-22 19:33:00 +01:00
7fb357e9c8 feat: add working shapes 2021-11-22 19:15:32 +01:00
1d7a8cc66b refactor: removed useless includePath 2021-11-22 18:00:55 +01:00
070749e685 feat: implement shapes for entities 2021-11-21 20:00:35 +01:00
a716e46c64 refactor(Team): moved include to source file 2021-11-21 19:44:20 +01:00
2e2aeb44b9 feat: add shapes 2021-11-21 18:51:54 +01:00
2df76248be chore: use c++17 2021-11-21 18:50:38 +01:00
36f1430ff2 refactor: changed cast type 2021-11-21 17:21:34 +01:00
2e14827f13 refactor: add mob size getter 2021-11-21 17:19:50 +01:00
c7d81de60e feat: add mob size 2021-11-21 17:18:45 +01:00
f48af51dc7 refactor: format project 2021-11-21 17:02:42 +01:00
0f328e6f81 fix: world tile pos calculation 2021-11-20 19:27:06 +01:00
114 changed files with 8056 additions and 2433 deletions

View File

@@ -12,42 +12,58 @@ enum class GameState : std::uint8_t {
Game, Game,
EndGame, EndGame,
Disconnected, Disconnected,
Closed
}; };
typedef std::map<std::uint8_t, Player> PlayerList; typedef std::map<std::uint8_t, Player> PlayerList;
class Game { class GameListener {
public:
virtual void OnPlayerJoin(PlayerID player) {}
virtual void OnPlayerLeave(PlayerID player) {}
virtual void OnGameStateUpdate(GameState newState) {}
virtual void OnGameBegin() {}
virtual void OnGameEnd() {}
virtual void OnGameClose() {}
};
typedef utils::ObjectNotifier<GameListener> GameNotifier;
class Game : public GameNotifier {
protected: protected:
World* m_World; World* m_World;
std::array<Team, 2> m_Teams = { Team{TeamColor::Red}, Team{TeamColor::Blue} }; TeamList m_Teams = { Team{TeamColor::Red}, Team{TeamColor::Blue} };
GameState m_GameState = GameState::Lobby; GameState m_GameState = GameState::Lobby;
PlayerList m_Players; PlayerList m_Players;
public: public:
Game(World* world); Game(World* world);
virtual ~Game(); virtual ~Game();
virtual void tick(std::uint64_t delta); virtual void Tick(std::uint64_t delta);
Team& getRedTeam() { return m_Teams[(std::uint8_t)TeamColor::Red]; } Team& GetRedTeam() { return m_Teams[static_cast<std::uint8_t>(TeamColor::Red)]; }
const Team& getRedTeam() const { return m_Teams[(std::uint8_t)TeamColor::Red]; } const Team& GetRedTeam() const { return m_Teams[static_cast<std::uint8_t>(TeamColor::Red)]; }
Team& getBlueTeam() { return m_Teams[(std::uint8_t)TeamColor::Blue]; } Team& GetBlueTeam() { return m_Teams[static_cast<std::uint8_t>(TeamColor::Blue)]; }
const Team& getBlueTeam() const { return m_Teams[(std::uint8_t)TeamColor::Blue]; } const Team& GetBlueTeam() const { return m_Teams[static_cast<std::uint8_t>(TeamColor::Red)]; }
Team& getTeam(TeamColor team) { return m_Teams[(std::uint8_t)team]; } Team& GetTeam(TeamColor team) { return m_Teams[static_cast<std::uint8_t>(team)]; }
const Team& getTeam(TeamColor team) const { return m_Teams[(std::uint8_t)team]; } const Team& GetTeam(TeamColor team) const { return m_Teams[static_cast<std::uint8_t>(team)]; }
GameState getGameState() const { return m_GameState; } GameState GetGameState() const { return m_GameState; }
void setGameState(GameState gameState) { m_GameState = gameState; }; void SetGameState(GameState gameState) { m_GameState = gameState; };
const World* getWorld() const { return m_World; } const World* GetWorld() const { return m_World; }
World* getWorld() { return m_World; } World* GetWorld() { return m_World; }
const PlayerList& getPlayers() const { return m_Players; } const PlayerList& GetPlayers() const { return m_Players; }
PlayerList& getPlayers() { return m_Players; } PlayerList& GetPlayers() { return m_Players; }
const Player& getPlayerById(PlayerID id) const { return m_Players.find(id)->second; } const Player* GetPlayerById(PlayerID id) const;
Player& getPlayerById(PlayerID id) { return m_Players.find(id)->second; } Player* GetPlayerById(PlayerID id);
const TeamList& GetTeams() const { return m_Teams; }
}; };

View File

@@ -20,14 +20,14 @@ public:
Connexion(protocol::PacketDispatcher* dispatcher, network::TCPSocket& socket); Connexion(protocol::PacketDispatcher* dispatcher, network::TCPSocket& socket);
virtual ~Connexion(); virtual ~Connexion();
virtual bool updateSocket(); virtual bool UpdateSocket();
void closeConnection(); void CloseConnection();
bool connect(const std::string& address, std::uint16_t port); bool Connect(const std::string& address, std::uint16_t port);
network::Socket::Status getSocketStatus() const { return m_Socket.GetStatus(); } network::Socket::Status GetSocketStatus() const { return m_Socket.GetStatus(); }
void sendPacket(const protocol::Packet* packet); void SendPacket(const protocol::Packet* packet);
REMOVE_COPY(Connexion); REMOVE_COPY(Connexion);
}; };

View File

@@ -10,12 +10,12 @@
namespace GameManager { namespace GameManager {
void render(); void Render();
void init(); void Init();
void destroy(); void Destroy();
void tick(); void Tick();
void startServer(); void StartServer();
} }

View File

@@ -2,13 +2,20 @@
#include "Towers.h" #include "Towers.h"
#include "Types.h" #include "Types.h"
#include "Team.h"
#include "misc/ObjectNotifier.h"
#include <vector> #include <vector>
#include <memory> #include <memory>
#include <glm/glm.hpp>
namespace td { namespace td {
namespace game { namespace game {
struct WalkableTile;
enum class EffectType : std::uint8_t { enum class EffectType : std::uint8_t {
Slowness = 0, Slowness = 0,
Stun, Stun,
@@ -41,37 +48,39 @@ class MobStats {
private: private:
float m_Damage; float m_Damage;
float m_Speed; float m_Speed;
glm::vec2 m_Size;
std::uint16_t m_MoneyCost; std::uint16_t m_MoneyCost;
std::uint16_t m_ExpCost; std::uint16_t m_ExpCost;
std::uint16_t m_MaxLife; std::uint16_t m_MaxLife;
std::uint16_t m_ExpReward; std::uint16_t m_ExpReward;
public: public:
MobStats(float damage, float speed, std::uint16_t moneyCost, MobStats(float damage, float speed, glm::vec2 size, std::uint16_t moneyCost,
std::uint16_t expCost, std::uint16_t expReward, std::uint16_t expCost, std::uint16_t expReward,
std::uint16_t maxLife) : m_Damage(damage), m_Speed(speed), std::uint16_t maxLife) : m_Damage(damage), m_Speed(speed),
m_MoneyCost(moneyCost), m_ExpCost(expCost), m_MaxLife(maxLife), m_Size(size), m_MoneyCost(moneyCost), m_ExpCost(expCost),
m_ExpReward(expReward) { m_MaxLife(maxLife), m_ExpReward(expReward) {
} }
float getDamage() const { return m_Damage; } float GetDamage() const { return m_Damage; }
float getMovementSpeed() const { return m_Speed; } float GetMovementSpeed() const { return m_Speed; }
std::uint16_t getMoneyCost() const { return m_MoneyCost; } const glm::vec2& GetSize() const { return m_Size; }
std::uint16_t getExpCost() const { return m_ExpCost; } std::uint16_t GetMoneyCost() const { return m_MoneyCost; }
std::uint16_t getExpReward() const { return m_ExpReward; } std::uint16_t GetExpCost() const { return m_ExpCost; }
std::uint16_t getMaxLife() const { return m_MaxLife; } std::uint16_t GetExpReward() const { return m_ExpReward; }
std::uint16_t GetMaxLife() const { return m_MaxLife; }
}; };
struct EffectDuration { struct EffectDuration {
EffectType type; EffectType type;
float duration; // in seconds float duration; // in seconds
const Tower* tower; // the tower that gived the effect Tower* tower; // the tower that gived the effect
}; };
const MobStats* getMobStats(MobType type, std::uint8_t level); const MobStats* GetMobStats(MobType type, std::uint8_t level);
const TowerImmunities& getMobTowerImmunities(MobType type, std::uint8_t level); const TowerImmunities& GetMobTowerImmunities(MobType type, std::uint8_t level);
const EffectImmunities& getMobEffectImmunities(MobType type, std::uint8_t level); const EffectImmunities& GetMobEffectImmunities(MobType type, std::uint8_t level);
class Mob { class Mob : public utils::shape::Rectangle {
protected: protected:
float m_Health; float m_Health;
private: private:
@@ -80,137 +89,163 @@ private:
MobLevel m_Level; MobLevel m_Level;
Direction m_Direction; Direction m_Direction;
std::vector<EffectDuration> m_Effects; std::vector<EffectDuration> m_Effects;
const Tower* m_LastDamage; // the tower that damaged the mob const Tower* m_LastDamage; // the last tower that damaged the mob
utils::Timer m_EffectFireTimer; utils::Timer m_EffectFireTimer;
utils::Timer m_EffectPoisonTimer; utils::Timer m_EffectPoisonTimer;
utils::Timer m_EffectHealTimer; utils::Timer m_EffectHealTimer;
float m_X = 0, m_Y = 0; TeamCastle* m_CastleTarget;
utils::CooldownTimer m_AttackTimer;
public: public:
Mob(MobID id, MobLevel level, PlayerID sender) : m_Sender(sender), m_Level(level), Mob(MobID id, MobLevel level, PlayerID sender) : m_Sender(sender), m_Level(level),
m_EffectFireTimer(1000), m_EffectPoisonTimer(1000), m_EffectHealTimer(1000) { m_EffectFireTimer(1000), m_EffectPoisonTimer(1000),
m_EffectHealTimer(1000), m_CastleTarget(nullptr), m_AttackTimer(1000) {
} }
virtual MobType getType() const = 0; virtual MobType GetType() const = 0;
virtual void tick(std::uint64_t delta); virtual void Tick(std::uint64_t delta, World* world);
virtual void OnDeath(World* world){} virtual bool OnDeath(World* world) { return true; }
const TowerImmunities& getTowerImmunities() const { return getMobTowerImmunities(getType(), m_Level); } MobID GetMobID() const { return m_ID; }
const EffectImmunities& getEffectImmunities() const { return getMobEffectImmunities(getType(), m_Level); } const TowerImmunities& GetTowerImmunities() const { return GetMobTowerImmunities(GetType(), m_Level); }
PlayerID getSender() const { return m_Sender; } const EffectImmunities& GetEffectImmunities() const { return GetMobEffectImmunities(GetType(), m_Level); }
MobLevel getLevel() const { return m_Level; } PlayerID GetSender() const { return m_Sender; }
const MobStats* getStats() const { return getMobStats(getType(), m_Level); } MobLevel GetLevel() const { return m_Level; }
float getHealth() const { return m_Health; } const MobStats* GetStats() const { return GetMobStats(GetType(), m_Level); }
bool isDead() const { return m_Health <= 0; } void SetHealth(float newHealth) { m_Health = newHealth; }
bool isAlive() const { return m_Health > 0; } float GetHealth() const { return m_Health; }
const Tower* getLastDamageTower() { return m_LastDamage; } bool IsDead() const { return m_Health <= 0; }
bool IsAlive() const { return m_Health > 0; }
const Tower* GetLastDamageTower() { return m_LastDamage; }
bool HasReachedEnemyCastle() { return m_CastleTarget != nullptr; }
void damage(float dmg, const Tower* damager) { m_Health = std::max(0.0f, m_Health - dmg); m_LastDamage = damager; } void Damage(float dmg, const Tower* damager) { m_Health = std::max(0.0f, m_Health - dmg); m_LastDamage = damager; }
void heal(float heal) { m_Health = std::min((float)getStats()->getMaxLife(), m_Health + heal); } void Heal(float heal) { m_Health = std::min(static_cast<float>(GetStats()->GetMaxLife()), m_Health + heal); }
void SetMobReachedCastle(TeamCastle* castle) { m_CastleTarget = castle; } // used when mob is in front of the castle
float getX() const { return m_X; } bool IsImmuneTo(TowerType type);
void setX(float x) { m_X = x; }
float getY() const { return m_Y; } bool IsImmuneTo(EffectType type);
void setY(float y) { m_Y = y; } void AddEffect(EffectType type, float durationSec, Tower* tower);
bool HasEffect(EffectType type);
bool isImmuneTo(TowerType type); float GetTileX() { return GetCenterX() - static_cast<float>(static_cast<std::int32_t>(GetCenterX())); } // returns a float between 0 and 1 excluded
float GetTileY() { return GetCenterY() - static_cast<float>(static_cast<std::int32_t>(GetCenterY())); } // returns a float between 0 and 1 excluded
bool isImmuneTo(EffectType type); Direction GetDirection() const { return m_Direction; }
void addEffect(EffectType type, float durationSec, const Tower* tower); void SetDirection(Direction dir) { m_Direction = dir; }
bool hasEffect(EffectType type);
Direction getDirection() const { return m_Direction; }
void setDirection(Direction dir) { m_Direction = dir; }
protected: protected:
void initHealth() { m_Health = (float)getStats()->getMaxLife(); } void InitMob() {
m_Health = static_cast<float>(GetStats()->GetMaxLife());
SetSize(GetStats()->GetSize().x, GetStats()->GetSize().y);
}
private: private:
void updateEffects(std::uint64_t delta); void UpdateEffects(std::uint64_t delta, World* world);
EffectDuration& getEffect(EffectType type); void AttackCastle(std::uint64_t delta, World* world);
void Move(std::uint64_t delta, World* world);
void Walk(std::uint64_t delta, World* world);
void MoveBack(const TeamCastle& castle, World* world);
void ChangeDirection(const WalkableTile& tile, World* world);
bool IsTouchingCastle(const TeamCastle& castle) const;
EffectDuration& GetEffect(EffectType type);
}; };
typedef std::shared_ptr<Mob> MobPtr; typedef std::shared_ptr<Mob> MobPtr;
class Zombie : public Mob { class Zombie : public Mob {
public: public:
Zombie(MobID id, std::uint8_t level, PlayerID sender) : Mob(id, level, sender) { initHealth(); } Zombie(MobID id, std::uint8_t level, PlayerID sender) : Mob(id, level, sender) { InitMob(); }
virtual MobType getType() const { return MobType::Zombie; } virtual MobType GetType() const { return MobType::Zombie; }
}; };
class Spider : public Mob { class Spider : public Mob {
public: public:
Spider(MobID id, std::uint8_t level, PlayerID sender) : Mob(id, level, sender) { initHealth(); } Spider(MobID id, std::uint8_t level, PlayerID sender) : Mob(id, level, sender) { InitMob(); }
virtual MobType getType() const { return MobType::Spider; } virtual MobType GetType() const { return MobType::Spider; }
}; };
class Skeleton : public Mob { class Skeleton : public Mob {
public: public:
Skeleton(MobID id, std::uint8_t level, PlayerID sender) : Mob(id, level, sender) { initHealth(); } Skeleton(MobID id, std::uint8_t level, PlayerID sender) : Mob(id, level, sender) { InitMob(); }
virtual MobType getType() const { return MobType::Skeleton; } virtual MobType GetType() const { return MobType::Skeleton; }
}; };
class PigMan : public Mob { class PigMan : public Mob {
public: public:
PigMan(MobID id, std::uint8_t level, PlayerID sender) : Mob(id, level, sender) { initHealth(); } PigMan(MobID id, std::uint8_t level, PlayerID sender) : Mob(id, level, sender) { InitMob(); }
virtual MobType getType() const { return MobType::Pigman; } virtual MobType GetType() const { return MobType::Pigman; }
}; };
class Creeper : public Mob { class Creeper : public Mob {
public: public:
Creeper(MobID id, std::uint8_t level, PlayerID sender) : Mob(id, level, sender) { initHealth(); } Creeper(MobID id, std::uint8_t level, PlayerID sender) : Mob(id, level, sender) { InitMob(); }
virtual MobType getType() const { return MobType::Creeper; } virtual MobType GetType() const { return MobType::Creeper; }
}; };
class Silverfish : public Mob { class Silverfish : public Mob {
public: public:
Silverfish(MobID id, std::uint8_t level, PlayerID sender) : Mob(id, level, sender) { initHealth(); } Silverfish(MobID id, std::uint8_t level, PlayerID sender) : Mob(id, level, sender) { InitMob(); }
virtual MobType getType() const { return MobType::Silverfish; } virtual MobType GetType() const { return MobType::Silverfish; }
}; };
class Blaze : public Mob { class Blaze : public Mob {
public: public:
Blaze(MobID id, std::uint8_t level, PlayerID sender) : Mob(id, level, sender) { initHealth(); } Blaze(MobID id, std::uint8_t level, PlayerID sender) : Mob(id, level, sender) { InitMob(); }
virtual MobType getType() const { return MobType::Blaze; } virtual MobType GetType() const { return MobType::Blaze; }
}; };
class Witch : public Mob { class Witch : public Mob {
public: public:
Witch(MobID id, std::uint8_t level, PlayerID sender) : Mob(id, level, sender) { initHealth(); } Witch(MobID id, std::uint8_t level, PlayerID sender) : Mob(id, level, sender) { InitMob(); }
virtual MobType getType() const { return MobType::Witch; } virtual MobType GetType() const { return MobType::Witch; }
}; };
class Slime : public Mob { class Slime : public Mob {
public: public:
Slime(MobID id, std::uint8_t level, PlayerID sender) : Mob(id, level, sender) { initHealth(); } Slime(MobID id, std::uint8_t level, PlayerID sender) : Mob(id, level, sender) { InitMob(); }
virtual MobType getType() const { return MobType::Slime; } virtual MobType GetType() const { return MobType::Slime; }
}; };
class Giant : public Mob { class Giant : public Mob {
public: public:
Giant(MobID id, std::uint8_t level, PlayerID sender) : Mob(id, level, sender) { initHealth(); } Giant(MobID id, std::uint8_t level, PlayerID sender) : Mob(id, level, sender) { InitMob(); }
virtual MobType getType() const { return MobType::Giant; } virtual MobType GetType() const { return MobType::Giant; }
}; };
namespace MobFactory { namespace MobFactory {
MobPtr createMob(MobID id, MobType type, std::uint8_t level, PlayerID sender);
std::string getMobName(MobType type); MobPtr CreateMob(MobID id, MobType type, std::uint8_t level, PlayerID sender);
std::string GetMobName(MobType type);
} }
class MobListener {
public:
virtual void OnMobSpawn(Mob* mob) {}
virtual void OnMobDie(Mob* mob) {}
virtual void OnMobDamage(Mob* target, float damage, Tower* damager) {}
virtual void OnMobTouchCastle(Mob* damager, TeamCastle* enemyCastle) {}
virtual void OnMobCastleDamage(Mob* damager, TeamCastle* enemyCastle, float damage) {}
};
typedef utils::ObjectNotifier<MobListener> MobNotifier;
} // namespace game } // namespace game
} // namespace td } // namespace td

View File

@@ -1,56 +1,50 @@
#pragma once #pragma once
#include <cstdint>
#include <string> #include <string>
#include "game/Team.h" #include "game/Team.h"
#include "game/PlayerUpgrades.h"
namespace td { namespace td {
namespace game { namespace game {
class Player { class Player {
private: private:
game::TeamColor m_TeamColor; TeamColor m_TeamColor;
PlayerUpgrades m_Upgrades;
std::uint32_t m_Gold; std::uint32_t m_Gold;
std::uint32_t m_Exp; std::uint32_t m_Exp;
std::string m_Name; std::string m_Name;
std::uint8_t m_ID; PlayerID m_ID;
std::uint8_t m_GoldPerSecond;
bool m_GoldChanged;
bool m_ExpChanged;
public: public:
Player(std::uint8_t id = 0) : m_TeamColor(game::TeamColor::None), m_Gold(0), m_Exp(0), m_ID(id), m_GoldPerSecond(5),
m_GoldChanged(false), m_ExpChanged(false) {}
const std::string& getName() const { return m_Name; } Player(std::uint8_t id = 0) : m_TeamColor(TeamColor::None), m_Gold(0), m_Exp(0), m_ID(id) {}
void setName(const std::string& name) { m_Name = name; }
game::TeamColor getTeamColor() const { return m_TeamColor; } const std::string& GetName() const { return m_Name; }
void setTeamColor(game::TeamColor teamColor) { m_TeamColor = teamColor; } void SetName(const std::string& name) { m_Name = name; }
std::uint8_t getGoldPerSecond() const { return m_GoldPerSecond; } TeamColor GetTeamColor() const { return m_TeamColor; }
void setGoldPerSecond(std::uint8_t goldPerSecond) { m_GoldPerSecond = goldPerSecond; } void SetTeamColor(TeamColor teamColor) { m_TeamColor = teamColor; }
std::uint32_t getGold() const { return m_Gold;} std::uint32_t GetGold() const { return m_Gold; }
void setGold(std::uint32_t gold) { m_GoldChanged = true; m_Gold = gold; } void SetGold(std::uint32_t gold) { m_Gold = gold; }
void addGold(std::uint32_t gold) { m_GoldChanged = true; m_Gold += gold; } void AddGold(std::uint32_t gold) { m_Gold += gold; }
void removeGold(std::uint32_t gold) { m_GoldChanged = true; m_Gold -= gold; } void RemoveGold(std::uint32_t gold) { m_Gold -= gold; }
std::uint32_t getExp() const { return m_Exp; } std::uint32_t GetExp() const { return m_Exp; }
void setExp(std::uint32_t exp) { m_ExpChanged = true; m_Exp = exp; } void SetExp(std::uint32_t exp) { m_Exp = exp; }
void addExp(std::uint32_t exp) { m_ExpChanged = true; m_Exp += exp; } void AddExp(std::uint32_t exp) { m_Exp += exp; }
void removeExp(std::uint32_t exp) { m_ExpChanged = true; m_Exp -= exp; } void RemoveExp(std::uint32_t exp) { m_Exp -= exp; }
bool hasGoldChanged() const { return m_GoldChanged; } const PlayerUpgrades& getUpgrades() const { return m_Upgrades; }
bool hasExpChanged() const { return m_ExpChanged; } PlayerUpgrades& getUpgrades() { return m_Upgrades; }
void updateGold() { m_GoldChanged = false; } bool HasEnoughGold(std::uint32_t gold) const { return m_Gold >= gold; }
void updateExp() { m_ExpChanged = false; } bool HasEnoughExp(std::uint32_t exp) const { return m_Exp >= exp; }
std::uint8_t getID() const { return m_ID; } PlayerID GetID() const { return m_ID; }
}; };
} // namespace game } // namespace game

View File

@@ -0,0 +1,34 @@
#pragma once
#include "Mobs.h"
namespace td {
namespace game {
class PlayerUpgrades {
private:
std::uint8_t m_ClickerLevel;
std::uint8_t m_GoldPerSecond;
std::array<std::uint8_t, static_cast<std::size_t>(MobType::MOB_COUNT)> m_MobsUpgradeLevel;
public:
static const int MAX_MOB_LEVEL = 5;
static const int MAX_CLICKER_LEVEL = 3;
PlayerUpgrades() : m_ClickerLevel(1), m_GoldPerSecond(5) {}
std::uint8_t GetClickerLevel() const { return m_ClickerLevel; }
std::uint8_t GetMobUpgradeLevel(MobType mob) const { return m_MobsUpgradeLevel.at(static_cast<std::size_t>(mob)); }
std::uint8_t GetGoldPerSecond() const { return m_GoldPerSecond; }
void UpgradeMob(MobType mob) {
std::uint8_t& mobLevel = m_MobsUpgradeLevel.at(static_cast<std::size_t>(mob));
mobLevel = std::min(mobLevel + 1, MAX_MOB_LEVEL);
}
void UpgradeClicker() { m_ClickerLevel = std::min(m_ClickerLevel + 1, MAX_CLICKER_LEVEL); }
void SetGoldPerSecond(std::uint8_t goldPerSecond) { m_GoldPerSecond = goldPerSecond; }
};
} // namespace game
} // namespace td

View File

@@ -2,9 +2,11 @@
#include "Types.h" #include "Types.h"
#include "misc/Shapes.h"
#include <vector> #include <vector>
#include <memory> #include <memory>
#include <algorithm> #include <cmath>
namespace td { namespace td {
namespace game { namespace game {
@@ -17,14 +19,48 @@ enum class TeamColor : std::int8_t {
Blue Blue
}; };
struct Spawn { class Spawn : public utils::shape::Rectangle {
Direction direction; private:
std::int32_t x, y; Direction m_Direction;
public:
Spawn() {
SetWidth(5);
SetHeight(5);
}
Direction GetDirection() const { return m_Direction; }
void SetDirection(Direction direction) { m_Direction = direction; }
}; };
struct TeamCastle { class Team;
std::int32_t x, y;
std::uint16_t life = 1000; class TeamCastle : public utils::shape::Rectangle {
private:
const Team* m_Team;
float m_Life;
public:
static constexpr int CastleMaxLife = 1000;
TeamCastle(const Team* team) : m_Team(team), m_Life(CastleMaxLife) {
SetWidth(5);
SetHeight(5);
}
TeamCastle() : TeamCastle(nullptr) {}
float GetLife() const { return m_Life; }
const Team* GetTeam() const { return m_Team; }
void SetTeam(const Team* team) { m_Team = team; }
void SetLife(float life) { m_Life = life; }
void Damage(float damage) { m_Life = std::max(0.0f, m_Life - damage); }
void SetShape(utils::shape::Rectangle rect) {
SetCenter(rect.GetCenter());
SetSize(rect.GetSize());
}
}; };
class Team { class Team {
@@ -36,19 +72,21 @@ private:
public: public:
Team(TeamColor color); Team(TeamColor color);
void addPlayer(Player* newPlayer); void AddPlayer(Player* newPlayer);
void removePlayer(const Player* player); void RemovePlayer(const Player* player);
TeamColor getColor() const; TeamColor GetColor() const;
const Spawn& getSpawn() const { return m_Spawn; } const Spawn& GetSpawn() const { return m_Spawn; }
Spawn& getSpawn() { return m_Spawn; } Spawn& GetSpawn() { return m_Spawn; }
const TeamCastle& getCastle() const { return m_TeamCastle; } const TeamCastle& GetCastle() const { return m_TeamCastle; }
TeamCastle& getCastle() { return m_TeamCastle; } TeamCastle& GetCastle() { return m_TeamCastle; }
std::uint8_t getPlayerCount() const; std::uint8_t GetPlayerCount() const;
}; };
typedef std::array<Team, 2> TeamList;
} // namespace game } // namespace game
} // namespace td } // namespace td

View File

@@ -1,10 +1,11 @@
#pragma once #pragma once
#include <cstdint>
#include <string> #include <string>
#include <memory> #include <memory>
#include "misc/Time.h" #include "misc/Time.h"
#include "misc/Shapes.h"
#include "game/Types.h" #include "game/Types.h"
namespace td { namespace td {
@@ -53,9 +54,9 @@ public:
m_Range(range) { m_Range(range) {
} }
float getDamageRate() const { return m_Rate; } float GetDamageRate() const { return m_Rate; }
float getDamage() const { return m_Damage; } float GetDamage() const { return m_Damage; }
std::uint8_t getRange() const { return m_Range; } std::uint8_t GetRange() const { return m_Range; }
}; };
class TowerLevel { class TowerLevel {
@@ -68,65 +69,63 @@ public:
TowerLevel() : m_Level(1), m_Path(TowerPath::Base) {} TowerLevel() : m_Level(1), m_Path(TowerPath::Base) {}
TowerLevel(std::uint8_t level, TowerPath path) : m_Level(level), m_Path(path) {} TowerLevel(std::uint8_t level, TowerPath path) : m_Level(level), m_Path(path) {}
std::uint8_t getLevel() const { return m_Level; } std::uint8_t GetLevel() const { return m_Level; }
TowerPath getPath() const { return m_Path; } TowerPath GetPath() const { return m_Path; }
void setLevel(std::uint8_t level) { m_Level = level; } void SetLevel(std::uint8_t level) { m_Level = level; }
void setPath(TowerPath path) { m_Path = path; } void SetPath(TowerPath path) { m_Path = path; }
// operator to sort maps // operator to sort maps
friend bool operator<(const TowerLevel& level, const TowerLevel& other) { friend bool operator<(const TowerLevel& level, const TowerLevel& other) {
return level.getLevel() + static_cast<std::uint8_t>(level.getPath()) * 4 < return level.GetLevel() + static_cast<std::uint8_t>(level.GetPath()) * 4 <
other.getLevel() + static_cast<std::uint8_t>(other.getPath()) * 4; other.GetLevel() + static_cast<std::uint8_t>(other.GetPath()) * 4;
} }
}; };
const TowerStats* getTowerStats(TowerType type, TowerLevel level); const TowerStats* GetTowerStats(TowerType type, TowerLevel level);
typedef std::uint16_t TowerID; typedef std::uint16_t TowerID;
class Tower { class Tower : public utils::shape::Circle {
private: private:
TowerID m_ID; TowerID m_ID;
TowerType m_Type; TowerType m_Type;
std::int32_t m_X, m_Y;
TowerLevel m_Level{}; TowerLevel m_Level{};
PlayerID m_Builder; PlayerID m_Builder;
protected: protected:
utils::CooldownTimer m_Timer; utils::CooldownTimer m_Timer;
public: public:
Tower(TowerID id, TowerType type, std::int32_t x, std::int32_t y, PlayerID builder) : m_ID(id), m_Type(type), m_X(x), m_Y(y), m_Builder(builder), Tower(TowerID id, TowerType type, std::int32_t x, std::int32_t y, PlayerID builder) : utils::shape::Circle(x + 0.5f, y + 0.5f, 0), m_ID(id), m_Type(type), m_Builder(builder),
m_Timer(getStats()->getDamageRate() * 1000) { // converting seconds to millis m_Timer(GetStats()->GetDamageRate() * 1000) { // converting seconds to millis
SetRadius(GetStats()->GetRange());
} }
virtual TowerType getType() const = 0; virtual TowerType GetType() const = 0;
virtual TowerSize getSize() const = 0; virtual TowerSize GetSize() const = 0;
virtual void tick(std::uint64_t delta, World* world) = 0; virtual void Tick(std::uint64_t delta, World* world) = 0;
void upgrade(std::uint8_t level, TowerPath path) { void Upgrade(std::uint8_t level, TowerPath path) {
m_Level.setLevel(level); m_Level.SetLevel(level);
m_Level.setPath(path); m_Level.SetPath(path);
m_Timer.setCooldown(getStats()->getDamageRate() * 1000); // converting seconds to millis m_Timer.SetCooldown(GetStats()->GetDamageRate() * 1000); // converting seconds to millis
m_Timer.reset(); m_Timer.Reset();
SetRadius(GetStats()->GetRange());
} }
std::uint16_t getID() const { return m_ID; } std::uint16_t GetID() const { return m_ID; }
std::int32_t getX() const { return m_X; } const TowerLevel& GetLevel() const { return m_Level; }
std::int32_t getY() const { return m_Y; } const TowerStats* GetStats() const { return GetTowerStats(m_Type, m_Level); }
const TowerLevel& getLevel() const { return m_Level; } PlayerID GetBuilder() const { return m_Builder; }
const TowerStats* getStats() const { return getTowerStats(m_Type, m_Level); }
PlayerID getBuilder() const { return m_Builder; }
bool isMobInRange(MobPtr mob); bool IsMobInRange(MobPtr mob);
}; };
typedef std::shared_ptr<Tower> TowerPtr; typedef std::shared_ptr<Tower> TowerPtr;
namespace TowerFactory { namespace TowerFactory {
TowerPtr createTower(TowerType type, TowerID id, std::int32_t x, std::int32_t y, PlayerID builder); TowerPtr CreateTower(TowerType type, TowerID id, std::int32_t x, std::int32_t y, PlayerID builder);
std::string getTowerName(TowerType type); std::string GetTowerName(TowerType type);
} // namespace TowerFactory } // namespace TowerFactory
@@ -139,13 +138,13 @@ public:
TowerInfo(std::string&& name, std::string&& description, bool big) : m_Name(std::move(name)), TowerInfo(std::string&& name, std::string&& description, bool big) : m_Name(std::move(name)),
m_Description(std::move(description)), m_IsBigTower(big) {} m_Description(std::move(description)), m_IsBigTower(big) {}
const std::string& getName() const { return m_Name; } const std::string& GetName() const { return m_Name; }
const std::string& getDescription() const { return m_Description; } const std::string& GetDescription() const { return m_Description; }
bool isBigTower() const { return m_IsBigTower; } bool IsBigTower() const { return m_IsBigTower; }
}; };
const TowerInfo& getTowerInfo(TowerType type); const TowerInfo& GetTowerInfo(TowerType type);
// ---------- Little Towers ---------- // ---------- Little Towers ----------
@@ -153,74 +152,77 @@ class LittleTower : public Tower {
public: public:
LittleTower(TowerID id, TowerType type, std::uint16_t x, std::uint16_t y, PlayerID builder) : Tower(id, type, x, y, builder) {} LittleTower(TowerID id, TowerType type, std::uint16_t x, std::uint16_t y, PlayerID builder) : Tower(id, type, x, y, builder) {}
virtual TowerSize getSize() const { return TowerSize::Little; } virtual TowerSize GetSize() const { return TowerSize::Little; }
virtual TowerType getType() const = 0; virtual TowerType GetType() const = 0;
virtual void tick(std::uint64_t delta, World* world) = 0; virtual void Tick(std::uint64_t delta, World* world) = 0;
}; };
class ArcherTower : public LittleTower { class ArcherTower : public LittleTower {
public: public:
ArcherTower(TowerID id, std::uint16_t x, std::uint16_t y, PlayerID builder) : LittleTower(id, getType(), x, y, builder) {} ArcherTower(TowerID id, std::uint16_t x, std::uint16_t y, PlayerID builder) : LittleTower(id, GetType(), x, y, builder) {}
virtual TowerType getType() const { return TowerType::Archer; } constexpr static float ExplosionRadius = 1.5f;
virtual void tick(std::uint64_t delta, World* world); constexpr static float FireDurationSec = 10.0f;
virtual TowerType GetType() const { return TowerType::Archer; }
virtual void Tick(std::uint64_t delta, World* world);
}; };
class IceTower : public LittleTower { class IceTower : public LittleTower {
public: public:
IceTower(TowerID id, std::uint16_t x, std::uint16_t y, PlayerID builder) : LittleTower(id, getType(), x, y, builder) {} IceTower(TowerID id, std::uint16_t x, std::uint16_t y, PlayerID builder) : LittleTower(id, GetType(), x, y, builder) {}
virtual TowerType getType() const { return TowerType::Ice; } virtual TowerType GetType() const { return TowerType::Ice; }
virtual void tick(std::uint64_t delta, World* world); virtual void Tick(std::uint64_t delta, World* world);
}; };
class MageTower : public LittleTower { class MageTower : public LittleTower {
public: public:
MageTower(TowerID id, std::uint16_t x, std::uint16_t y, PlayerID builder) : LittleTower(id, getType(), x, y, builder) {} MageTower(TowerID id, std::uint16_t x, std::uint16_t y, PlayerID builder) : LittleTower(id, GetType(), x, y, builder) {}
virtual TowerType getType() const { return TowerType::Mage; } virtual TowerType GetType() const { return TowerType::Mage; }
virtual void tick(std::uint64_t delta, World* world); virtual void Tick(std::uint64_t delta, World* world);
}; };
class PoisonTower : public LittleTower { class PoisonTower : public LittleTower {
public: public:
PoisonTower(TowerID id, std::uint16_t x, std::uint16_t y, PlayerID builder) : LittleTower(id, getType(), x, y, builder) {} PoisonTower(TowerID id, std::uint16_t x, std::uint16_t y, PlayerID builder) : LittleTower(id, GetType(), x, y, builder) {}
virtual TowerType getType() const { return TowerType::Poison; } virtual TowerType GetType() const { return TowerType::Poison; }
virtual void tick(std::uint64_t delta, World* world); virtual void Tick(std::uint64_t delta, World* world);
}; };
class QuakeTower : public LittleTower { class QuakeTower : public LittleTower {
public: public:
QuakeTower(TowerID id, std::uint16_t x, std::uint16_t y, PlayerID builder) : LittleTower(id, getType(), x, y, builder) {} QuakeTower(TowerID id, std::uint16_t x, std::uint16_t y, PlayerID builder) : LittleTower(id, GetType(), x, y, builder) {}
virtual TowerType getType() const { return TowerType::Quake; } virtual TowerType GetType() const { return TowerType::Quake; }
virtual void tick(std::uint64_t delta, World* world); virtual void Tick(std::uint64_t delta, World* world);
}; };
class ArtilleryTower : public LittleTower { class ArtilleryTower : public LittleTower {
public: public:
ArtilleryTower(TowerID id, std::uint16_t x, std::uint16_t y, PlayerID builder) : LittleTower(id, getType(), x, y, builder) {} ArtilleryTower(TowerID id, std::uint16_t x, std::uint16_t y, PlayerID builder) : LittleTower(id, GetType(), x, y, builder) {}
virtual TowerType getType() const { return TowerType::Artillery; } virtual TowerType GetType() const { return TowerType::Artillery; }
virtual void tick(std::uint64_t delta, World* world); virtual void Tick(std::uint64_t delta, World* world);
}; };
class SorcererTower : public LittleTower { class SorcererTower : public LittleTower {
public: public:
SorcererTower(TowerID id, std::uint16_t x, std::uint16_t y, PlayerID builder) : LittleTower(id, getType(), x, y, builder) {} SorcererTower(TowerID id, std::uint16_t x, std::uint16_t y, PlayerID builder) : LittleTower(id, GetType(), x, y, builder) {}
virtual TowerType getType() const { return TowerType::Sorcerer; } virtual TowerType GetType() const { return TowerType::Sorcerer; }
virtual void tick(std::uint64_t delta, World* world); virtual void Tick(std::uint64_t delta, World* world);
}; };
class ZeusTower : public LittleTower { class ZeusTower : public LittleTower {
public: public:
ZeusTower(TowerID id, std::uint16_t x, std::uint16_t y, PlayerID builder) : LittleTower(id, getType(), x, y, builder) {} ZeusTower(TowerID id, std::uint16_t x, std::uint16_t y, PlayerID builder) : LittleTower(id, GetType(), x, y, builder) {}
virtual TowerType getType() const { return TowerType::Zeus; } virtual TowerType GetType() const { return TowerType::Zeus; }
virtual void tick(std::uint64_t delta, World* world); virtual void Tick(std::uint64_t delta, World* world);
}; };
// ---------- Big Towers ---------- // ---------- Big Towers ----------
@@ -229,34 +231,34 @@ class BigTower : public Tower {
public: public:
BigTower(TowerID id, TowerType type, std::uint16_t x, std::uint16_t y, PlayerID builder) : Tower(id, type, x, y, builder) {} BigTower(TowerID id, TowerType type, std::uint16_t x, std::uint16_t y, PlayerID builder) : Tower(id, type, x, y, builder) {}
virtual TowerSize getSize() const { return TowerSize::Big; } virtual TowerSize GetSize() const { return TowerSize::Big; }
virtual TowerType getType() const = 0; virtual TowerType GetType() const = 0;
virtual void tick(std::uint64_t delta, World* world) = 0; virtual void Tick(std::uint64_t delta, World* world) = 0;
}; };
class TurretTower : public BigTower { class TurretTower : public BigTower {
public: public:
TurretTower(TowerID id, std::uint16_t x, std::uint16_t y, PlayerID builder) : BigTower(id, getType(), x, y, builder) {} TurretTower(TowerID id, std::uint16_t x, std::uint16_t y, PlayerID builder) : BigTower(id, GetType(), x, y, builder) {}
virtual TowerType getType() const { return TowerType::Turret; } virtual TowerType GetType() const { return TowerType::Turret; }
virtual void tick(std::uint64_t delta, World* world); virtual void Tick(std::uint64_t delta, World* world);
}; };
class NecromancerTower : public BigTower { class NecromancerTower : public BigTower {
public: public:
NecromancerTower(TowerID id, std::uint16_t x, std::uint16_t y, PlayerID builder) : BigTower(id, getType(), x, y, builder) {} NecromancerTower(TowerID id, std::uint16_t x, std::uint16_t y, PlayerID builder) : BigTower(id, GetType(), x, y, builder) {}
virtual TowerType getType() const { return TowerType::Necromancer; } virtual TowerType GetType() const { return TowerType::Necromancer; }
virtual void tick(std::uint64_t delta, World* world); virtual void Tick(std::uint64_t delta, World* world);
}; };
class LeachTower : public BigTower { class LeachTower : public BigTower {
public: public:
LeachTower(TowerID id, std::uint16_t x, std::uint16_t y, PlayerID builder) : BigTower(id, getType(), x, y, builder) {} LeachTower(TowerID id, std::uint16_t x, std::uint16_t y, PlayerID builder) : BigTower(id, GetType(), x, y, builder) {}
virtual TowerType getType() const { return TowerType::Leach; } virtual TowerType GetType() const { return TowerType::Leach; }
virtual void tick(std::uint64_t delta, World* world); virtual void Tick(std::uint64_t delta, World* world);
}; };
} // namespace game } // namespace game

View File

@@ -2,6 +2,9 @@
#include <cstdint> #include <cstdint>
// include Log for every files
#include "misc/Log.h"
namespace td { namespace td {
namespace game { namespace game {

View File

@@ -12,23 +12,30 @@
namespace td { namespace td {
namespace game { namespace game {
typedef std::pair<std::int16_t, std::int16_t> ChunkCoord;
struct ChunkCoord {
std::int16_t x, y;
friend bool operator==(const td::game::ChunkCoord& first, const td::game::ChunkCoord& other) {
return first.x == other.x && first.y == other.y;
}
};
} }
} }
namespace std { namespace std {
template <> template <>
struct hash<td::game::ChunkCoord> { struct hash<td::game::ChunkCoord> {
std::size_t operator()(const td::game::ChunkCoord& key) const { std::size_t operator()(const td::game::ChunkCoord& key) const noexcept{
// Compute individual hash values for first, return std::hash<std::int16_t>()(key.x << 16 | key.y);
// second and third and combine them using XOR
// and bit shifting:
return ((std::hash<std::int16_t>()(key.first) ^ (std::hash<std::int16_t>()(key.second) << 1)) >> 1);
} }
}; };
} }
namespace td { namespace td {
namespace protocol { namespace protocol {
class WorldBeginDataPacket; class WorldBeginDataPacket;
@@ -56,27 +63,34 @@ struct Color {
std::uint8_t r, g, b; std::uint8_t r, g, b;
}; };
static constexpr Color BLACK{ 0, 0, 0 };
static constexpr Color WHITE{ 255, 255, 255 };
static constexpr Color RED{ 255, 0, 0 };
static constexpr Color GREEN{ 0, 255, 0 };
static constexpr Color BLUE{ 0, 0, 255 };
struct Tile { struct Tile {
virtual TileType getType() const = 0; virtual TileType GetType() const = 0;
}; };
struct TowerTile : Tile { struct TowerTile : Tile {
std::uint8_t color_palette_ref; std::uint8_t color_palette_ref;
TeamColor team_owner; TeamColor team_owner;
virtual TileType getType() const { return TileType::Tower; } virtual TileType GetType() const { return TileType::Tower; }
}; };
struct WalkableTile : Tile { struct WalkableTile : Tile {
Direction direction; Direction direction;
virtual TileType getType() const { return TileType::Walk; } virtual TileType GetType() const { return TileType::Walk; }
}; };
struct DecorationTile : Tile { struct DecorationTile : Tile {
std::uint16_t color_palette_ref; std::uint16_t color_palette_ref;
virtual TileType getType() const { return TileType::Decoration; } virtual TileType GetType() const { return TileType::Decoration; }
}; };
typedef std::shared_ptr<Tile> TilePtr; typedef std::shared_ptr<Tile> TilePtr;
@@ -84,17 +98,18 @@ typedef std::vector<std::uint16_t> ChunkPalette;
typedef std::shared_ptr<WalkableTile> WalkableTilePtr; typedef std::shared_ptr<WalkableTile> WalkableTilePtr;
typedef std::array<std::uint16_t, 32 * 32> ChunkData;
typedef std::uint32_t TileIndex; typedef std::uint32_t TileIndex;
//32 x 32 area //32 x 32 area
struct Chunk { struct Chunk {
enum { ChunkWidth = 32, ChunkHeight = 32, ChunkSize = ChunkWidth * ChunkHeight }; enum { ChunkWidth = 32, ChunkHeight = 32, ChunkSize = ChunkWidth * ChunkHeight };
typedef std::array<std::uint16_t, ChunkSize> ChunkData;
// stores index of tile palette // stores index of tile palette
ChunkData tiles{ 0 }; ChunkData tiles{ 0 };
ChunkPalette palette; ChunkPalette palette;
TileIndex getTileIndex(std::uint16_t tileNumber) const { TileIndex GetTileIndex(std::uint16_t tileNumber) const {
TileIndex chunkPaletteIndex = tiles.at(tileNumber); TileIndex chunkPaletteIndex = tiles.at(tileNumber);
if (chunkPaletteIndex == 0) // index 0 means empty tile index 1 = first tile if (chunkPaletteIndex == 0) // index 0 means empty tile index 1 = first tile
return 0; return 0;
@@ -114,11 +129,27 @@ typedef std::array<Color, 2> SpawnColorPalette;
typedef std::vector<TowerPtr> TowerList; typedef std::vector<TowerPtr> TowerList;
class World { class WorldListener {
public:
WorldListener() {}
virtual void OnTowerAdd(TowerPtr tower) {}
virtual void OnTowerRemove(TowerPtr tower) {}
virtual void OnArcherTowerShot(MobPtr target, ArcherTower* shooter) {}
virtual void OnArrowShot(MobPtr target, bool fire, Tower* shooter) {}
virtual void OnExplosion(utils::shape::Circle explosion, float centerDamage, Tower* shooter) {}
};
typedef utils::ObjectNotifier<WorldListener> WorldNotifier;
class World : public WorldListener, public MobListener {
protected: protected:
TowerTileColorPalette m_TowerPlacePalette; TowerTileColorPalette m_TowerPlacePalette;
Color m_WalkablePalette; Color m_WalkablePalette;
std::vector<Color> m_DecorationPalette; std::vector<Color> m_DecorationPalette;
Color m_Background;
std::unordered_map<ChunkCoord, ChunkPtr> m_Chunks; std::unordered_map<ChunkCoord, ChunkPtr> m_Chunks;
@@ -131,30 +162,35 @@ protected:
TowerList m_Towers; TowerList m_Towers;
Game* m_Game; Game* m_Game;
WorldNotifier m_WorldNotifier;
MobNotifier m_MobNotifier;
public: public:
World(Game* game); World(Game* game);
bool loadMap(const protocol::WorldBeginDataPacket* worldHeader); bool LoadMap(const protocol::WorldBeginDataPacket* worldHeader);
bool loadMap(const protocol::WorldDataPacket* worldData); bool LoadMap(const protocol::WorldDataPacket* worldData);
bool loadMapFromFile(const std::string& fileName); bool LoadMapFromFile(const std::string& fileName);
bool saveMap(const std::string& fileName) const; bool SaveMap(const std::string& fileName) const;
void tick(std::uint64_t delta); void Tick(std::uint64_t delta);
void spawnMobAt(MobID id, MobType type, std::uint8_t level, PlayerID sender, float x, float y, Direction dir); void SpawnMobAt(MobID id, MobType type, std::uint8_t level, PlayerID sender, float x, float y, Direction dir);
TowerPtr placeTowerAt(TowerID id, TowerType type, std::int32_t x, std::int32_t y, PlayerID builder); TowerPtr PlaceTowerAt(TowerID id, TowerType type, std::int32_t x, std::int32_t y, PlayerID builder);
TowerPtr RemoveTower(TowerID id);
TilePtr getTile(std::int32_t x, std::int32_t y) const; TilePtr GetTile(std::int32_t x, std::int32_t y) const;
const TowerTileColorPalette& getTowerTileColorPalette() const { return m_TowerPlacePalette; } const TowerTileColorPalette& GetTowerTileColorPalette() const { return m_TowerPlacePalette; }
const Color& getWalkableTileColor() const { return m_WalkablePalette; } const Color& GetWalkableTileColor() const { return m_WalkablePalette; }
const std::vector<Color>& getDecorationPalette() const { return m_DecorationPalette; } const std::vector<Color>& GetDecorationPalette() const { return m_DecorationPalette; }
const Color& GetBackgroundColor() const { return m_Background; }
const TilePalette& getTilePalette() const { return m_TilePalette; } const TilePalette& GetTilePalette() const { return m_TilePalette; }
TilePtr getTilePtr(TileIndex index) const { TilePtr GetTilePtr(TileIndex index) const {
if (index == 0) if (index == 0)
return nullptr; return nullptr;
return m_TilePalette.at(index - 1); return m_TilePalette.at(index - 1);
@@ -163,36 +199,51 @@ public:
bool CanPlaceLittleTower(const glm::vec2& worldPos, PlayerID player) const; bool CanPlaceLittleTower(const glm::vec2& worldPos, PlayerID player) const;
bool CanPlaceBigTower(const glm::vec2& worldPos, PlayerID player) const; bool CanPlaceBigTower(const glm::vec2& worldPos, PlayerID player) const;
TowerPtr getTower(const glm::vec2& position) const; // returns null if no tower is here TowerPtr GetTower(const glm::vec2& position) const; // returns null if no tower is here
const std::unordered_map<ChunkCoord, ChunkPtr>& getChunks() const { return m_Chunks; } const std::unordered_map<ChunkCoord, ChunkPtr>& GetChunks() const { return m_Chunks; }
const Color& getSpawnColor(TeamColor color) const { return m_SpawnColorPalette[(std::size_t)color]; } const Color& GetSpawnColor(TeamColor color) const { return m_SpawnColorPalette[static_cast<std::size_t>(color)]; }
const SpawnColorPalette& getSpawnColors() const { return m_SpawnColorPalette; } const SpawnColorPalette& GetSpawnColors() const { return m_SpawnColorPalette; }
const MobList& getMobList() const { return m_Mobs; } const MobList& GetMobList() const { return m_Mobs; }
MobList& getMobList() { return m_Mobs; } MobList& GetMobList() { return m_Mobs; }
const Color* getTileColor(TilePtr tile) const; const Color* GetTileColor(TilePtr tile) const;
Team& getRedTeam(); Team& GetRedTeam();
const Team& getRedTeam() const; const Team& GetRedTeam() const;
Team& getBlueTeam(); Team& GetBlueTeam();
const Team& getBlueTeam() const; const Team& GetBlueTeam() const;
Team& getTeam(TeamColor team); Team& GetTeam(TeamColor team);
const Team& getTeam(TeamColor team) const; const Team& GetTeam(TeamColor team) const;
const TowerList& getTowers() const { return m_Towers; }; const TeamList& GetTeams() const;
TowerPtr getTowerById(TowerID tower);
const TowerList& GetTowers() const { return m_Towers; }
TowerPtr GetTowerById(TowerID tower);
const Player* GetPlayerById(PlayerID id) const;
WorldNotifier& GetWorldNotifier() { return m_WorldNotifier; }
MobNotifier& GetMobNotifier() { return m_MobNotifier; }
// WorldListener
virtual void OnArcherTowerShot(MobPtr target, ArcherTower* shooter) override;
virtual void OnArrowShot(MobPtr target, bool fire, Tower* shooter) override;
virtual void OnExplosion(utils::shape::Circle explosion, float centerDamage, Tower* shooter) override;
// MobListener
virtual void OnMobDamage(Mob* target, float damage, Tower* source) override;
virtual void OnMobCastleDamage(Mob* damager, TeamCastle* enemyCastle, float damage) override;
// Archer Tower
virtual void OnArrowShot(MobPtr target, Tower* shooter);
private: private:
void moveMobs(std::uint64_t delta); void TickMobs(std::uint64_t delta);
void tickMobs(std::uint64_t delta); void CleanDeadMobs();
void cleanDeadMobs();
}; };
} // namespace game } // namespace game

View File

@@ -19,31 +19,36 @@ class Client {
private: private:
render::Renderer* m_Renderer; render::Renderer* m_Renderer;
ClientConnexion m_Connexion; ClientConnexion m_Connexion;
ClientGame m_Game; std::unique_ptr<ClientGame> m_Game;
bool m_Connected; bool m_Connected;
public: public:
Client(render::Renderer* renderer) : m_Renderer(renderer), m_Game(this), m_Connected(false) {} Client(render::Renderer* renderer) : m_Renderer(renderer), m_Game(std::make_unique<ClientGame>(this)), m_Connected(false) {}
const ClientGame& getGame() const { return m_Game; } const ClientGame& GetGame() const { return *m_Game; }
const ClientConnexion& getConnexion() const { return m_Connexion; } const ClientConnexion& GetConnexion() const { return m_Connexion; }
render::Renderer* getRenderer() const { return m_Renderer; } render::Renderer* GetRenderer() const { return m_Renderer; }
ClientGame& getGame() { return m_Game; } ClientGame& GetGame() { return *m_Game; }
ClientConnexion& getConnexion() { return m_Connexion; } ClientConnexion& GetConnexion() { return m_Connexion; }
void tick(std::uint64_t delta); const game::Player* GetPlayer() { return m_Game->GetPlayer(); }
void render(); void Tick(std::uint64_t delta);
bool connect(const network::IPAddresses& addresses, std::uint16_t port); void Render();
void closeConnection();
bool isConnected() const { return m_Connexion.getSocketStatus() == network::Socket::Connected; } bool Connect(const network::IPAddresses& addresses, std::uint16_t port);
void CloseConnection();
void selectTeam(game::TeamColor team); bool IsConnected() const { return m_Connexion.GetSocketStatus() == network::Socket::Connected; }
void sendMobs(const std::vector<protocol::MobSend>& mobSends);
void placeTower(game::TowerType type, const glm::vec2& position); void SelectTeam(game::TeamColor team);
void upgradeTower(game::TowerID tower, game::TowerLevel level); void SendMobs(const std::vector<protocol::MobSend>& mobSends);
void PlaceTower(game::TowerType type, const glm::vec2& position);
void UpgradeTower(game::TowerID tower, game::TowerLevel level);
void RemoveTower(game::TowerID tower);
private:
void Reset();
}; };
} // namespace client } // namespace client

View File

@@ -16,21 +16,21 @@ private:
public: public:
ClientConnexion(); ClientConnexion();
virtual bool updateSocket(); virtual bool UpdateSocket();
virtual void HandlePacket(const protocol::KeepAlivePacket* packet); virtual void HandlePacket(const protocol::KeepAlivePacket* packet) override;
virtual void HandlePacket(const protocol::ConnexionInfoPacket* packet); virtual void HandlePacket(const protocol::ConnexionInfoPacket* packet) override;
virtual void HandlePacket(const protocol::DisconnectPacket* packet); virtual void HandlePacket(const protocol::DisconnectPacket* packet) override;
virtual void HandlePacket(const protocol::ServerTpsPacket* packet); virtual void HandlePacket(const protocol::ServerTpsPacket* packet) override;
const std::string& getDisconnectReason() const { return m_DisconnectReason; } const std::string& GetDisconnectReason() const { return m_DisconnectReason; }
float getServerTPS() const { return m_ServerTPS; } float GetServerTPS() const { return m_ServerTPS; }
int getServerPing() const { return m_Ping; } int GetServerPing() const { return m_Ping; }
REMOVE_COPY(ClientConnexion); REMOVE_COPY(ClientConnexion);
private: private:
void registerHandlers(); void RegisterHandlers();
void login(); void Login();
}; };
} // namespace client } // namespace client

View File

@@ -27,28 +27,30 @@ public:
ClientGame(Client* client); ClientGame(Client* client);
virtual ~ClientGame(); virtual ~ClientGame();
virtual void tick(std::uint64_t delta); virtual void Tick(std::uint64_t delta);
void renderWorld(); void RenderWorld();
std::uint32_t getLobbyTime() const { return m_LobbyTime; } std::uint32_t GetLobbyTime() const { return m_LobbyTime; }
const game::Player* getPlayer() const { return m_Player; } const game::Player* GetPlayer() const { return m_Player; }
const WorldClient& getWorld() const { return m_WorldClient; } const WorldClient& GetWorld() const { return m_WorldClient; }
Client* getClient() const { return m_Client; } Client* GetClient() const { return m_Client; }
render::Renderer* getRenderer() const { return m_Renderer; } render::Renderer* GetRenderer() const { return m_Renderer; }
WorldClient& GetWorldClient() { return m_WorldClient; }
virtual void HandlePacket(const protocol::ConnexionInfoPacket* packet) override;
virtual void HandlePacket(const protocol::PlayerJoinPacket* packet) override;
virtual void HandlePacket(const protocol::PlayerLeavePacket* packet) override;
virtual void HandlePacket(const protocol::PlayerListPacket* packet) override;
virtual void HandlePacket(const protocol::UpdatePlayerTeamPacket* packet) override;
virtual void HandlePacket(const protocol::UpdateGameStatePacket* packet) override;
virtual void HandlePacket(const protocol::UpdateLobbyTimePacket* packet) override;
virtual void HandlePacket(const protocol::UpdateMoneyPacket* packet) override;
virtual void HandlePacket(const protocol::UpdateExpPacket* packet) override;
virtual void HandlePacket(const protocol::DisconnectPacket* packet) override;
virtual void HandlePacket(const protocol::WorldDataPacket* packet) override;
virtual void HandlePacket(const protocol::ConnexionInfoPacket* packet);
virtual void HandlePacket(const protocol::PlayerJoinPacket* packet);
virtual void HandlePacket(const protocol::PlayerLeavePacket* packet);
virtual void HandlePacket(const protocol::PlayerListPacket* packet);
virtual void HandlePacket(const protocol::UpdatePlayerTeamPacket* packet);
virtual void HandlePacket(const protocol::UpdateGameStatePacket* packet);
virtual void HandlePacket(const protocol::UpdateLobbyTimePacket* packet);
virtual void HandlePacket(const protocol::UpdateMoneyPacket* packet);
virtual void HandlePacket(const protocol::DisconnectPacket* packet);
virtual void HandlePacket(const protocol::WorldDataPacket* packet);
virtual void HandlePacket(const protocol::WorldAddTowerPacket* packet);
}; };
} // namespace client } // namespace client

View File

@@ -18,8 +18,11 @@ public:
virtual void HandlePacket(const protocol::WorldDataPacket* packet) override; virtual void HandlePacket(const protocol::WorldDataPacket* packet) override;
virtual void HandlePacket(const protocol::SpawnMobPacket* packet) override; virtual void HandlePacket(const protocol::SpawnMobPacket* packet) override;
virtual void HandlePacket(const protocol::UpgradeTowerPacket* packet) override; virtual void HandlePacket(const protocol::UpgradeTowerPacket* packet) override;
virtual void HandlePacket(const protocol::WorldAddTowerPacket* packet) override;
virtual void HandlePacket(const protocol::RemoveTowerPacket* packet) override;
virtual void HandlePacket(const protocol::UpdateMobStatesPacket* packet) override;
virtual void HandlePacket(const protocol::UpdateCastleLifePacket* packet) override;
virtual void OnArrowShot(game::MobPtr target, game::Tower* shooter) override;
}; };
} // namespace client } // namespace client

View File

@@ -22,9 +22,9 @@ public:
void OnPlayerJoin(std::uint8_t playerID); void OnPlayerJoin(std::uint8_t playerID);
void OnPlayerLeave(std::uint8_t playerID); void OnPlayerLeave(std::uint8_t playerID);
void sendTimeRemaining(); void SendTimeRemaining();
void tick(); void Tick();
//static constexpr int LobbyWaitingTime = 2 * 60 * 1000; // in millis //static constexpr int LobbyWaitingTime = 2 * 60 * 1000; // in millis
static constexpr int LobbyWaitingTime = 5 * 1000; // in millis static constexpr int LobbyWaitingTime = 5 * 1000; // in millis

View File

@@ -1,6 +1,5 @@
#pragma once #pragma once
#include <cstdint>
#include <map> #include <map>
#include <thread> #include <thread>
@@ -28,25 +27,25 @@ private:
public: public:
TickCounter() {} TickCounter() {}
void reset() { void Reset() {
m_TPS = SERVER_TPS; m_TPS = SERVER_TPS;
m_LastTPSTime = utils::getTime(); m_LastTPSTime = utils::GetTime();
m_TickCount = 0; m_TickCount = 0;
} }
bool update() { // return true when tps is updated bool Update() { // return true when tps is updated
m_TickCount++; m_TickCount++;
if (m_TickCount >= SERVER_TPS) { if (m_TickCount >= SERVER_TPS) {
std::uint64_t timeElapsedSinceLast20Ticks = td::utils::getTime() - m_LastTPSTime; std::uint64_t timeElapsedSinceLast20Ticks = td::utils::GetTime() - m_LastTPSTime;
m_TPS = (float)SERVER_TPS / (float)(timeElapsedSinceLast20Ticks / 1000.0f); m_TPS = static_cast<float>(SERVER_TPS) / static_cast<float>(timeElapsedSinceLast20Ticks / 1000.0f);
m_TickCount = 0; m_TickCount = 0;
m_LastTPSTime = td::utils::getTime(); m_LastTPSTime = td::utils::GetTime();
return true; return true;
} }
return false; return false;
} }
float getTPS() const { return m_TPS; } float GetTPS() const { return m_TPS; }
}; };
class Server { class Server {
@@ -61,36 +60,38 @@ private:
bool m_ServerRunning; bool m_ServerRunning;
public: public:
Server(const std::string& worldFilePath); Server(const std::string& worldFilePath);
virtual ~Server() {} virtual ~Server();
bool start(std::uint16_t port); bool Start(std::uint16_t port);
void stop(); void Stop(); // force the server to stop
void Close(); // at the end of a game
void lauchGame(); void RemoveConnexion(std::uint8_t connexionID);
void removeConnexion(std::uint8_t connexionID); void BroadcastPacket(const protocol::Packet* packet);
void broadcastPacket(const protocol::Packet* packet); float GetTPS() const { return m_TickCounter.GetTPS(); }
float getTPS() const { return m_TickCounter.getTPS(); } bool IsRunning() { return m_ServerRunning; }
const ServerGame& getGame() const { return m_Game; } const ServerGame& GetGame() const { return m_Game; }
ServerGame& getGame() { return m_Game; } ServerGame& GetGame() { return m_Game; }
const Lobby& getLobby() const { return m_Lobby; } const Lobby& GetLobby() const { return m_Lobby; }
const ConnexionMap& getConnexions() const { return m_Connections; } const ConnexionMap& GetConnexions() const { return m_Connections; }
ConnexionMap& getConnexions() { return m_Connections; } ConnexionMap& GetConnexions() { return m_Connections; }
const game::PlayerList& getPlayers() const { return m_Game.getPlayers(); } const game::PlayerList& GetPlayers() const { return m_Game.GetPlayers(); }
game::PlayerList& getPlayers() { return m_Game.getPlayers(); } game::PlayerList& GetPlayers() { return m_Game.GetPlayers(); }
private: private:
void accept(); void Accept();
void updateSockets(); void UpdateSockets();
void startThread(); void Clean();
void stopThread(); void StartThread();
void tick(std::uint64_t delta); void StopThread();
void Tick(std::uint64_t delta);
void OnPlayerJoin(std::uint8_t id); void OnPlayerJoin(std::uint8_t id);
void OnPlayerLeave(std::uint8_t id); void OnPlayerLeave(std::uint8_t id);

View File

@@ -31,28 +31,29 @@ public:
ServerConnexion(ServerConnexion&& move); ServerConnexion(ServerConnexion&& move);
virtual ~ServerConnexion(); virtual ~ServerConnexion();
void setServer(Server* server); void SetServer(Server* server);
virtual void HandlePacket(const protocol::PlayerLoginPacket* packet); virtual void HandlePacket(const protocol::PlayerLoginPacket* packet) override;
virtual void HandlePacket(const protocol::KeepAlivePacket* packet); virtual void HandlePacket(const protocol::KeepAlivePacket* packet) override;
virtual void HandlePacket(const protocol::SelectTeamPacket* packet); virtual void HandlePacket(const protocol::SelectTeamPacket* packet) override;
virtual void HandlePacket(const protocol::DisconnectPacket* packet); virtual void HandlePacket(const protocol::DisconnectPacket* packet) override;
virtual void HandlePacket(const protocol::PlaceTowerPacket* packet); virtual void HandlePacket(const protocol::PlaceTowerPacket* packet) override;
virtual void HandlePacket(const protocol::SendMobsPacket* packet); virtual void HandlePacket(const protocol::SendMobsPacket* packet) override;
virtual void HandlePacket(const protocol::UpgradeTowerPacket* packet); virtual void HandlePacket(const protocol::UpgradeTowerPacket* packet) override;
virtual void HandlePacket(const protocol::RemoveTowerPacket* packet) override;
std::uint8_t getID() const { return m_ID; } std::uint8_t GetID() const { return m_ID; }
const game::Player* getPlayer() const { return m_Player; } const game::Player* GetPlayer() const { return m_Player; }
game::Player* getPlayer() { return m_Player; } game::Player* GetPlayer() { return m_Player; }
virtual bool updateSocket(); virtual bool UpdateSocket();
REMOVE_COPY(ServerConnexion); REMOVE_COPY(ServerConnexion);
private: private:
void registerHandlers(); void RegisterHandlers();
void checkKeepAlive(); void CheckKeepAlive();
void sendKeepAlive(); void SendKeepAlive();
void initConnection(); void InitConnection();
}; };
} // namespace server } // namespace server

View File

@@ -9,23 +9,34 @@ namespace server {
class Server; class Server;
class ServerGame : public game::Game { class ServerGame : public game::Game, public game::GameListener {
private: private:
Server* m_Server; Server* m_Server;
ServerWorld m_ServerWorld; ServerWorld m_ServerWorld;
utils::AutoTimer m_GoldMineTimer{ 1000, std::bind(&ServerGame::updateGoldMines, this) }; utils::AutoTimer m_GoldMineTimer;
utils::AutoTimer m_MobStatesTimer;
utils::CooldownTimer m_EndGameCooldown;
public: public:
ServerGame(Server* server); ServerGame(Server* server);
~ServerGame() {} ~ServerGame() {}
ServerWorld* getServerWorld() { return &m_ServerWorld; } ServerWorld* GetServerWorld() { return &m_ServerWorld; }
virtual void tick(std::uint64_t delta); virtual void Tick(std::uint64_t delta);
void startGame(); void StartGame();
// GameListener
virtual void OnGameStateUpdate(game::GameState newState) override;
virtual void OnGameBegin() override;
virtual void OnGameEnd() override;
virtual void OnGameClose() override;
private: private:
void balanceTeams(); void BalanceTeams();
void updateGoldMines(); void InitPlayerStats();
void updatePlayerStats(); void UpdateMobStates();
void UpdateGoldMines();
void UpdatePlayerStats();
}; };
} // namespace game } // namespace game

View File

@@ -14,12 +14,16 @@ private:
game::TowerID m_CurrentTowerID; game::TowerID m_CurrentTowerID;
Server* m_Server; Server* m_Server;
public: public:
static constexpr float MobSpawnBorder = 0.01f;
ServerWorld(Server* server, ServerGame* game); ServerWorld(Server* server, ServerGame* game);
void spawnMobs(game::MobType type, std::uint8_t level, game::PlayerID sender, std::uint8_t count); void SpawnMobs(game::MobType type, std::uint8_t level, game::PlayerID sender, std::uint8_t count);
game::TowerPtr placeTowerAt(game::TowerType type, std::int32_t x, std::int32_t y, game::PlayerID builder); game::TowerPtr PlaceTowerAt(game::TowerType type, std::int32_t x, std::int32_t y, game::PlayerID builder);
virtual void OnMobDie(game::Mob* mob) override;
virtual void OnMobCastleDamage(game::Mob* damager, game::TeamCastle* enemyCastle, float damage) override;
virtual void OnArrowShot(game::MobPtr target, game::Tower* shooter) override;
}; };
} // namespace server } // namespace server

4465
include/misc/Backward.hpp Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +1,14 @@
#pragma once #pragma once
#include <cstdint> #include <cstdint>
#include "misc/DataBuffer.h" #include "DataBuffer.h"
namespace td { namespace td {
namespace utils { namespace utils {
std::uint64_t Inflate(const std::string& source, std::string& dest);
std::uint64_t Deflate(const std::string& source, std::string& dest);
DataBuffer Compress(const DataBuffer& buffer); DataBuffer Compress(const DataBuffer& buffer);
DataBuffer Decompress(DataBuffer& buffer); DataBuffer Decompress(DataBuffer& buffer);
DataBuffer Decompress(DataBuffer& buffer, std::uint64_t packetLength); DataBuffer Decompress(DataBuffer& buffer, std::uint64_t packetLength);

View File

@@ -1,5 +1,4 @@
#ifndef MCLIB_COMMON_DATA_BUFFER_H_ #pragma once
#define MCLIB_COMMON_DATA_BUFFER_H_
#include <vector> #include <vector>
#include <algorithm> #include <algorithm>
@@ -13,7 +12,7 @@ class DataBuffer {
private: private:
typedef std::vector<std::uint8_t> Data; typedef std::vector<std::uint8_t> Data;
Data m_Buffer; Data m_Buffer;
std::size_t m_ReadOffset = 0; std::size_t m_ReadOffset;
public: public:
typedef Data::iterator iterator; typedef Data::iterator iterator;
@@ -23,7 +22,7 @@ public:
DataBuffer(); DataBuffer();
DataBuffer(const DataBuffer& other); DataBuffer(const DataBuffer& other);
DataBuffer(const DataBuffer& other, std::size_t offset); DataBuffer(const DataBuffer& other, Data::difference_type offset);
DataBuffer(DataBuffer&& other); DataBuffer(DataBuffer&& other);
DataBuffer(const std::string& str); DataBuffer(const std::string& str);
@@ -64,7 +63,7 @@ public:
template <typename T> template <typename T>
DataBuffer& operator>>(T& data) { DataBuffer& operator>>(T& data) {
assert(m_ReadOffset + sizeof(T) <= GetSize()); assert(m_ReadOffset + sizeof(T) <= GetSize());
data = *(T*)&m_Buffer[m_ReadOffset]; data = *(reinterpret_cast<T*>(&m_Buffer[m_ReadOffset]));
//std::reverse((std::uint8_t*)&data, (std::uint8_t*)&data + sizeof(T)); //std::reverse((std::uint8_t*)&data, (std::uint8_t*)&data + sizeof(T));
m_ReadOffset += sizeof(T); m_ReadOffset += sizeof(T);
return *this; return *this;
@@ -72,42 +71,55 @@ public:
DataBuffer& operator>>(DataBuffer& data) { DataBuffer& operator>>(DataBuffer& data) {
data.Resize(GetSize() - m_ReadOffset); data.Resize(GetSize() - m_ReadOffset);
std::copy(m_Buffer.begin() + m_ReadOffset, m_Buffer.end(), data.begin()); std::copy(m_Buffer.begin() + static_cast<Data::difference_type>(m_ReadOffset), m_Buffer.end(), data.begin());
m_ReadOffset = m_Buffer.size(); m_ReadOffset = m_Buffer.size();
return *this; return *this;
} }
DataBuffer& operator>>(std::string& str) { DataBuffer& operator>>(std::string& str) {
std::size_t stringSize = strlen((const char*)m_Buffer.data() + m_ReadOffset) + 1; // including null character std::size_t stringSize = strlen(reinterpret_cast<const char*>(m_Buffer.data()) + m_ReadOffset) + 1; // including null character
str.resize(stringSize); str.resize(stringSize);
std::copy(m_Buffer.begin() + m_ReadOffset, m_Buffer.begin() + m_ReadOffset + stringSize, str.begin()); std::copy(m_Buffer.begin() + static_cast<Data::difference_type>(m_ReadOffset),
m_Buffer.begin() + static_cast<Data::difference_type>(m_ReadOffset + stringSize), str.begin());
m_ReadOffset += stringSize; m_ReadOffset += stringSize;
return *this; return *this;
} }
void WriteSome(const char* buffer, std::size_t amount) {
std::size_t end_pos = m_Buffer.size();
m_Buffer.resize(m_Buffer.size() + amount);
memcpy(m_Buffer.data() + end_pos, buffer, amount);
}
void WriteSome(const std::uint8_t* buffer, std::size_t amount) {
std::size_t end_pos = m_Buffer.size();
m_Buffer.resize(m_Buffer.size() + amount);
memcpy(m_Buffer.data() + end_pos, buffer, amount);
}
void ReadSome(char* buffer, std::size_t amount) { void ReadSome(char* buffer, std::size_t amount) {
assert(m_ReadOffset + amount <= GetSize()); assert(m_ReadOffset + amount <= GetSize());
std::copy_n(m_Buffer.begin() + m_ReadOffset, amount, buffer); std::copy_n(m_Buffer.begin() + static_cast<Data::difference_type>(m_ReadOffset), amount, buffer);
m_ReadOffset += amount; m_ReadOffset += amount;
} }
void ReadSome(std::uint8_t* buffer, std::size_t amount) { void ReadSome(std::uint8_t* buffer, std::size_t amount) {
assert(m_ReadOffset + amount <= GetSize()); assert(m_ReadOffset + amount <= GetSize());
std::copy_n(m_Buffer.begin() + m_ReadOffset, amount, buffer); std::copy_n(m_Buffer.begin() + static_cast<Data::difference_type>(m_ReadOffset), amount, buffer);
m_ReadOffset += amount; m_ReadOffset += amount;
} }
void ReadSome(DataBuffer& buffer, std::size_t amount) { void ReadSome(DataBuffer& buffer, std::size_t amount) {
assert(m_ReadOffset + amount <= GetSize()); assert(m_ReadOffset + amount <= GetSize());
buffer.Resize(amount); buffer.Resize(amount);
std::copy_n(m_Buffer.begin() + m_ReadOffset, amount, buffer.begin()); std::copy_n(m_Buffer.begin() + static_cast<Data::difference_type>(m_ReadOffset), amount, buffer.begin());
m_ReadOffset += amount; m_ReadOffset += amount;
} }
void ReadSome(std::string& buffer, std::size_t amount) { void ReadSome(std::string& buffer, std::size_t amount) {
assert(m_ReadOffset + amount <= GetSize()); assert(m_ReadOffset + amount <= GetSize());
buffer.resize(amount); buffer.resize(amount);
std::copy_n(m_Buffer.begin() + m_ReadOffset, amount, buffer.begin()); std::copy_n(m_Buffer.begin() + static_cast<Data::difference_type>(m_ReadOffset), amount, buffer.begin());
m_ReadOffset += amount; m_ReadOffset += amount;
} }
@@ -163,5 +175,3 @@ public:
std::ostream& operator<<(std::ostream& os, const DataBuffer& buffer); std::ostream& operator<<(std::ostream& os, const DataBuffer& buffer);
} // ns td } // ns td
#endif

View File

@@ -7,63 +7,63 @@ constexpr float PI = 3.14159274101257324219;
/* Sine functions */ /* Sine functions */
float easeInSine(float x); float EaseInSine(float x);
float easeOutSine(float x); float EaseOutSine(float x);
float easeInOutSine(float x); float EaseInOutSine(float x);
/* Cubic functions */ /* Cubic functions */
float easeInCubic(float x); float EaseInCubic(float x);
float easeOutCubic(float x); float EaseOutCubic(float x);
float easeInOutCubic(float x); float EaseInOutCubic(float x);
/* Quint functions */ /* Quint functions */
float easeInQuint(float x); float EaseInQuint(float x);
float easeOutQuint(float x); float EaseOutQuint(float x);
float easeInOutQuint(float x); float EaseInOutQuint(float x);
/* Circ functions */ /* Circ functions */
float easeInCirc(float x); float EaseInCirc(float x);
float easeOutCirc(float x); float EaseOutCirc(float x);
float easeInOutCirc(float x); float EaseInOutCirc(float x);
/* Elastic functions */ /* Elastic functions */
float easeInElastic(float x); float EaseInElastic(float x);
float easeOutElastic(float x); float EaseOutElastic(float x);
float easeInOutElastic(float x); float EaseInOutElastic(float x);
/* Quad functions */ /* Quad functions */
float easeInQuad(float x); float EaseInQuad(float x);
float easeOutQuad(float x); float EaseOutQuad(float x);
float easeInOutQuad(float x); float EaseInOutQuad(float x);
/* Quart functions */ /* Quart functions */
float easeInQuart(float x); float EaseInQuart(float x);
float easeOutQuart(float x); float EaseOutQuart(float x);
float easeInOutQuart(float x); float EaseInOutQuart(float x);
/* Expo functions */ /* Expo functions */
float easeInExpo(float x); float EaseInExpo(float x);
float easeOutExpo(float x); float EaseOutExpo(float x);
float easeInOutExpo(float x); float EaseInOutExpo(float x);
/* Back functions */ /* Back functions */
float easeInBack(float x); float EaseInBack(float x);
float easeOutBack(float x); float EaseOutBack(float x);
float easeInOutBack(float x); float EaseInOutBack(float x);
/* Bounce functions */ /* Bounce functions */
float easeInBounce(float x); float EaseInBounce(float x);
float easeOutBounce(float x); float EaseOutBounce(float x);
float easeInOutBounce(float x); float EaseInOutBounce(float x);
} // namespace utils } // namespace utils
} // namespace td } // namespace td

23
include/misc/Format.h Normal file
View File

@@ -0,0 +1,23 @@
#pragma once
#include <string>
#include <memory>
#include <stdexcept>
namespace td {
namespace utils {
template <typename... Args>
std::string format(const std::string& format, Args... args){
int size = snprintf(nullptr, 0, format.c_str(), args...) + 1; // Extra space for '\0'
if (size <= 0){
throw std::runtime_error("Error during formatting.");
}
std::unique_ptr<char[]> buf(new char[size]);
snprintf(buf.get(), size, format.c_str(), args...);
return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside
}
} // namespace utils
} // namespace td

13
include/misc/Log.h Normal file
View File

@@ -0,0 +1,13 @@
#pragma once
#include <string>
namespace td {
namespace utils {
void LOG(const std::string& msg);
void LOGD(const std::string& msg);
void LOGE(const std::string& err);
} // namespace utils
} // namespace td

View File

@@ -0,0 +1,36 @@
#pragma once
#include <algorithm>
#include <functional>
#include <vector>
namespace td {
namespace utils {
template <typename Listener>
class ObjectNotifier {
protected:
std::vector<Listener*> m_Listeners;
public:
void BindListener(Listener* listener) {
m_Listeners.push_back(listener);
}
void UnbindListener(Listener* listener) {
auto iter = std::find(m_Listeners.begin(), m_Listeners.end(), listener);
if (iter == m_Listeners.end()) return;
m_Listeners.erase(iter);
}
template <typename Func, typename... Args>
void NotifyListeners(Func function, Args... args) {
for (Listener* listener : m_Listeners)
std::bind(function, listener, args...)();
}
};
} // namespace utils
} // namespace td

View File

@@ -18,7 +18,7 @@ enum class Architecture {
Unknown, Unknown,
}; };
inline Os getSystemOs(){ inline Os GetSystemOs() {
#if defined(_WIN32) || defined(_WIN64) #if defined(_WIN32) || defined(_WIN64)
return Os::Windows; return Os::Windows;
#elif defined(__ANDROID__) #elif defined(__ANDROID__)
@@ -31,7 +31,7 @@ inline Os getSystemOs(){
#endif #endif
} }
inline Architecture getSystemArchitecture(){ inline Architecture GetSystemArchitecture() {
#if defined(_WIN64) #if defined(_WIN64)
return Architecture::x86_64; return Architecture::x86_64;
#elif defined(_WIN32) #elif defined(_WIN32)

View File

@@ -6,7 +6,7 @@ namespace td {
namespace utils { namespace utils {
template<typename NumberType> template<typename NumberType>
NumberType getRandomInt(NumberType min, NumberType max){ NumberType GetRandomInt(NumberType min, NumberType max) {
std::random_device randomDevice; std::random_device randomDevice;
std::mt19937 generator(randomDevice()); std::mt19937 generator(randomDevice());
std::uniform_int_distribution<NumberType> distrib(min, max); std::uniform_int_distribution<NumberType> distrib(min, max);
@@ -14,7 +14,7 @@ NumberType getRandomInt(NumberType min, NumberType max){
} }
template<typename NumberType> template<typename NumberType>
NumberType getRandomReal(NumberType min, NumberType max){ NumberType GetRandomReal(NumberType min, NumberType max) {
std::random_device randomDevice; std::random_device randomDevice;
std::mt19937 generator(randomDevice()); std::mt19937 generator(randomDevice());
std::uniform_real_distribution<NumberType> distrib(min, max); std::uniform_real_distribution<NumberType> distrib(min, max);

96
include/misc/Shapes.h Normal file
View File

@@ -0,0 +1,96 @@
#pragma once
#include <cstdint>
namespace td {
namespace utils {
namespace shape {
class Point {
private:
float m_X, m_Y;
public:
Point() : m_X(0), m_Y(0) {}
Point(float x, float y) : m_X(x), m_Y(y) {}
float GetX() const { return m_X; }
float GetY() const { return m_Y; }
void SetX(float x) { m_X = x; }
void SetY(float y) { m_Y = y; }
float Distance(const Point& point) const;
float DistanceSquared(const Point& point) const;
};
class Circle;
class Rectangle {
private:
Point m_Center;
float m_Width, m_Height;
public:
Rectangle() {}
const Point& GetCenter() const { return m_Center; }
float GetCenterX() const { return m_Center.GetX(); }
float GetCenterY() const { return m_Center.GetY(); }
float GetWidth() const { return m_Width; }
float GetHeight() const { return m_Height; }
Point GetTopLeft() const { return { m_Center.GetX() - (m_Width / 2.0f), m_Center.GetY() - (m_Height / 2.0f) }; }
Point GetBottomRight() const { return { m_Center.GetX() + (m_Width / 2.0f), m_Center.GetY() + (m_Height / 2.0f) }; }
void SetCenter(const Point& center) { m_Center = center; }
void SetCenterX(float x) { m_Center.SetX(x); }
void SetCenterY(float y) { m_Center.SetY(y); }
void SetSize(float width, float height) { SetWidth(width); SetHeight(height); }
void SetSize(Point size) { SetSize(size.GetX(), size.GetY()); }
Point GetSize() { return { m_Width, m_Height }; }
void SetWidth(float width) { m_Width = width; }
void SetHeight(float height) { m_Height = height; }
bool CollidesWith(const Point& point) const;
bool CollidesWith(const Rectangle& rect) const;
bool CollidesWith(const Circle& circle) const;
// distance from the closest side of the rectangle
float Distance(const Circle& circle) const;
float DistanceSquared(const Circle& circle) const;
};
class Circle {
private:
Point m_Center;
float m_Radius;
public:
Circle(float x, float y, float radius) : m_Center(x, y), m_Radius(radius) {}
Circle() : m_Radius(0) {}
const Point& GetCenter() const { return m_Center; }
float GetCenterX() const { return m_Center.GetX(); }
float GetCenterY() const { return m_Center.GetY(); }
float GetRadius() const { return m_Radius; }
void SetCenter(const Point& center) { m_Center = center; }
void SetCenterX(float x) { m_Center.SetX(x); }
void SetCenterY(float y) { m_Center.SetY(y); }
void SetRadius(float radius) { m_Radius = radius; }
bool CollidesWith(const Point& point) const;
bool CollidesWith(const Rectangle& rect) const;
bool CollidesWith(const Circle& circle) const;
// distance from the closest side of the rectangle
float Distance(const Rectangle& rect) const;
float DistanceSquared(const Rectangle& rect) const;
};
} // namespace shape
} // namespace utils
} // namespace td

View File

@@ -6,7 +6,7 @@
namespace td { namespace td {
namespace utils { namespace utils {
std::uint64_t getTime(); std::uint64_t GetTime();
typedef std::function<void()> TimerExecFunction; typedef std::function<void()> TimerExecFunction;
@@ -17,59 +17,59 @@ private:
std::uint64_t m_Interval; std::uint64_t m_Interval;
TimerExecFunction m_Function; TimerExecFunction m_Function;
std::uint64_t m_LastTime = getTime(); std::uint64_t m_LastTime = GetTime();
std::uint64_t m_InternalTime = 0; std::uint64_t m_InternalTime = 0;
public: public:
AutoTimer() : m_Interval(0), m_Function(nullptr) {} AutoTimer() : m_Interval(0), m_Function(nullptr) {}
AutoTimer(std::uint64_t interval) : m_Interval(interval), m_Function(nullptr) {} AutoTimer(std::uint64_t interval) : m_Interval(interval), m_Function(nullptr) {}
AutoTimer(std::uint64_t interval, TimerExecFunction callback) : m_Interval(interval), m_Function(callback) {} AutoTimer(std::uint64_t interval, TimerExecFunction callback) : m_Interval(interval), m_Function(callback) {}
void update(); void Update();
void update(std::uint64_t delta); void Update(std::uint64_t delta);
void reset(); void Reset();
void setInterval(std::uint64_t newInterval) { m_Interval = newInterval; } void SetInterval(std::uint64_t newInterval) { m_Interval = newInterval; }
std::uint64_t getInterval() const { return m_Interval; } std::uint64_t GetInterval() const { return m_Interval; }
void setCallbackFunction(TimerExecFunction newCallback) { m_Function = newCallback; } void SetCallbackFunction(TimerExecFunction newCallback) { m_Function = newCallback; }
TimerExecFunction getCallbackFunction() const { return m_Function; } TimerExecFunction GetCallbackFunction() const { return m_Function; }
}; };
// utililty class to call function at regular period of time // utililty class to call function at regular period of time
class Timer { class Timer {
private: private:
std::uint64_t m_Interval; std::uint64_t m_Interval; // in millis
std::uint64_t m_InternalTime = 0; std::uint64_t m_InternalTime = 0;
public: public:
Timer() : m_Interval(0) {} Timer() : m_Interval(0) {}
Timer(std::uint64_t interval) : m_Interval(interval) {} Timer(std::uint64_t interval) : m_Interval(interval) {}
bool update(std::uint64_t delta); bool Update(std::uint64_t delta);
void reset(); void Reset();
void setInterval(std::uint64_t newInterval) { m_Interval = newInterval; } void SetInterval(std::uint64_t newInterval) { m_Interval = newInterval; }
std::uint64_t getInterval() const { return m_Interval; } std::uint64_t GetInterval() const { return m_Interval; }
}; };
// utililty class to call function at regular period of time with a cooldown (used for towers) // utililty class to call function at regular period of time with a cooldown (used for towers and mobs )
class CooldownTimer { class CooldownTimer {
private: private:
std::uint64_t m_Cooldown; std::uint64_t m_Cooldown; // in millis
std::uint64_t m_CooldownTime; std::uint64_t m_CooldownTime;
public: public:
CooldownTimer() : m_Cooldown(0), m_CooldownTime(0) {} CooldownTimer() : m_Cooldown(0), m_CooldownTime(0) {}
CooldownTimer(std::uint64_t cooldown) : m_Cooldown(0), m_CooldownTime(cooldown) {} CooldownTimer(std::uint64_t cooldown) : m_Cooldown(0), m_CooldownTime(cooldown) {}
bool update(std::uint64_t delta); bool Update(std::uint64_t delta);
void applyCooldown(); void ApplyCooldown();
void reset(); void Reset();
void setCooldown(std::uint64_t newCooldown) { m_CooldownTime = newCooldown; } void SetCooldown(std::uint64_t newCooldown) { m_CooldownTime = newCooldown; }
std::uint64_t getCooldown() const { return m_CooldownTime; } std::uint64_t GetCooldown() const { return m_CooldownTime; }
}; };
} // namespace utils } // namespace utils

View File

@@ -1,46 +0,0 @@
#pragma once
#include "misc/DataBuffer.h"
#include <ctime>
#define TD_VERSION "alpha-0.0.1"
namespace td {
namespace utils {
class Updater {
private:
float m_Progress;
bool m_DownloadComplete;
bool m_FileWrited;
bool m_CancelDownload;
DataBuffer m_FileBuffer;
std::string m_LastVersion;
public:
Updater() : m_Progress(0), m_DownloadComplete(false), m_FileWrited(false), m_CancelDownload(false) {}
bool checkUpdate();
void downloadUpdate();
void cancelDownload() { m_CancelDownload = true; m_Progress = 0.0f; m_DownloadComplete = false; }
bool writeFile();
void clearCache() { m_FileBuffer.Clear(); }
float getDownloadProgress() { return m_Progress; }
bool isDownloadComplete() { return m_DownloadComplete; }
bool isFileWrited() { return m_FileWrited; }
static std::string getLocalFilePath();
static void removeOldFile();
static std::string getCurrentVersion(){ return TD_VERSION; }
std::string getLastVersion() { return m_LastVersion; }
bool canUpdate();
private:
std::string getDownloadFileURL();
};
} // namespace utils
} // namespace td

View File

@@ -13,17 +13,18 @@ public:
TCPListener(); TCPListener();
~TCPListener(); ~TCPListener();
bool listen(std::uint16_t port, int maxConnections); bool Listen(std::uint16_t port, int maxConnections);
bool accept(TCPSocket& newSocket); bool Accept(TCPSocket& newSocket);
void destroy(); void Destroy();
bool close(); bool Close();
bool setBlocking(bool blocking); bool SetBlocking(bool blocking);
std::uint16_t getListeningPort() const { std::uint16_t GetListeningPort() const {
return m_Port; return m_Port;
} }
int getMaximumConnections() const {
int GetMaximumConnections() const {
return m_MaxConnections; return m_MaxConnections;
} }

View File

@@ -15,7 +15,7 @@ class TCPSocket : public Socket {
private: private:
IPAddress m_RemoteIP; IPAddress m_RemoteIP;
uint16_t m_Port; uint16_t m_Port;
sockaddr_in m_RemoteAddr; sockaddr m_RemoteAddr;
public: public:
TCPSocket(); TCPSocket();

View File

@@ -20,7 +20,9 @@ public:
bool Connect(const IPAddress& address, std::uint16_t port); bool Connect(const IPAddress& address, std::uint16_t port);
std::size_t Send(const std::uint8_t* data, std::size_t size); std::size_t Send(const std::uint8_t* data, std::size_t size);
DataBuffer Receive(std::size_t amount);
virtual DataBuffer Receive(std::size_t amount);
virtual std::size_t Receive(DataBuffer& buffer, std::size_t amount);
}; };
} // ns network } // ns network

View File

@@ -6,7 +6,7 @@ namespace td {
namespace protocol { namespace protocol {
namespace PacketFactory { namespace PacketFactory {
PacketPtr createPacket(PacketType type, DataBuffer& buffer); PacketPtr CreatePacket(PacketType type, DataBuffer& buffer);
} }
} // namespace protocol } // namespace protocol

View File

@@ -16,28 +16,32 @@ public:
PacketDispatcher* GetDispatcher() { return m_Dispatcher; } PacketDispatcher* GetDispatcher() { return m_Dispatcher; }
virtual void HandlePacket(const PlayerLoginPacket* packet) {} virtual void HandlePacket(const ConnexionInfoPacket* packet) {}
virtual void HandlePacket(const WorldBeginDataPacket* packet) {} virtual void HandlePacket(const DisconnectPacket* packet) {}
virtual void HandlePacket(const WorldDataPacket* packet) {}
virtual void HandlePacket(const KeepAlivePacket* packet) {} virtual void HandlePacket(const KeepAlivePacket* packet) {}
virtual void HandlePacket(const UpdateMoneyPacket* packet) {} virtual void HandlePacket(const PlaceTowerPacket* packet) {}
virtual void HandlePacket(const UpdateExpPacket* packet) {} virtual void HandlePacket(const PlayerBuyItemPacket* packet) {}
virtual void HandlePacket(const UpdateLobbyTimePacket* packet) {} virtual void HandlePacket(const PlayerBuyMobUpgradePacket* packet) {}
virtual void HandlePacket(const UpdateGameStatePacket* packet) {}
virtual void HandlePacket(const PlayerListPacket* packet) {}
virtual void HandlePacket(const PlayerJoinPacket* packet) {} virtual void HandlePacket(const PlayerJoinPacket* packet) {}
virtual void HandlePacket(const PlayerLeavePacket* packet) {} virtual void HandlePacket(const PlayerLeavePacket* packet) {}
virtual void HandlePacket(const ConnexionInfoPacket* packet) {} virtual void HandlePacket(const PlayerListPacket* packet) {}
virtual void HandlePacket(const PlayerLoginPacket* packet) {}
virtual void HandlePacket(const RemoveTowerPacket* packet) {}
virtual void HandlePacket(const SelectTeamPacket* packet) {} virtual void HandlePacket(const SelectTeamPacket* packet) {}
virtual void HandlePacket(const UpdatePlayerTeamPacket* packet) {} virtual void HandlePacket(const SendMobsPacket* packet) {}
virtual void HandlePacket(const DisconnectPacket* packet) {}
virtual void HandlePacket(const ServerTpsPacket* packet) {} virtual void HandlePacket(const ServerTpsPacket* packet) {}
virtual void HandlePacket(const SpawnMobPacket* packet) {} virtual void HandlePacket(const SpawnMobPacket* packet) {}
virtual void HandlePacket(const PlaceTowerPacket* packet) {} virtual void HandlePacket(const UpdateCastleLifePacket* packet) {}
virtual void HandlePacket(const WorldAddTowerPacket* packet) {} virtual void HandlePacket(const UpdateExpPacket* packet) {}
virtual void HandlePacket(const WorldRemoveTowerPacket* packet) {} virtual void HandlePacket(const UpdateGameStatePacket* packet) {}
virtual void HandlePacket(const SendMobsPacket* packet) {} virtual void HandlePacket(const UpdateLobbyTimePacket* packet) {}
virtual void HandlePacket(const UpdateMobStatesPacket* packet) {}
virtual void HandlePacket(const UpdateMoneyPacket* packet) {}
virtual void HandlePacket(const UpdatePlayerTeamPacket* packet) {}
virtual void HandlePacket(const UpgradeTowerPacket* packet) {} virtual void HandlePacket(const UpgradeTowerPacket* packet) {}
virtual void HandlePacket(const WorldAddTowerPacket* packet) {}
virtual void HandlePacket(const WorldBeginDataPacket* packet) {}
virtual void HandlePacket(const WorldDataPacket* packet) {}
}; };
} // namespace protocol } // namespace protocol

View File

@@ -33,18 +33,25 @@ enum class PacketType : std::uint8_t {
UpdatePlayerTeam, UpdatePlayerTeam,
ServerTps, ServerTps,
WorldAddTower, WorldAddTower,
WorldRemoveTower, UpdateMobStates,
UpdateCastleLife,
// client <--> server // client <--> server
KeepAlive, KeepAlive,
Disconnect, Disconnect,
UpgradeTower, UpgradeTower,
RemoveTower,
PlayerBuyItem,
PlayerBuyMobUpgrade,
PACKET_COUNT
}; };
struct WorldHeader { struct WorldHeader {
game::TowerTileColorPalette m_TowerPlacePalette; game::TowerTileColorPalette m_TowerPlacePalette;
game::Color m_WalkablePalette; game::Color m_WalkablePalette;
std::vector<game::Color> m_DecorationPalette; std::vector<game::Color> m_DecorationPalette;
game::Color m_Background;
game::SpawnColorPalette m_SpawnColorPalette; game::SpawnColorPalette m_SpawnColorPalette;
@@ -65,12 +72,14 @@ public:
Packet() {} Packet() {}
virtual ~Packet() {} virtual ~Packet() {}
virtual DataBuffer Serialize() const = 0; virtual DataBuffer Serialize(bool packetID = true) const = 0;
virtual void Deserialize(DataBuffer& data) = 0; virtual void Deserialize(DataBuffer& data) = 0;
virtual void Dispatch(PacketHandler* handler) const = 0; virtual void Dispatch(PacketHandler* handler) const = 0;
virtual PacketType getType() const = 0; void WritePacketID(DataBuffer& data, bool packetID) const;
std::uint8_t getID() const { return (std::uint8_t)getType(); }
virtual PacketType GetType() const = 0;
std::uint8_t GetID() const { return static_cast<std::uint8_t>(GetType()); }
}; };
typedef std::unique_ptr<Packet> PacketPtr; typedef std::unique_ptr<Packet> PacketPtr;
@@ -83,13 +92,13 @@ public:
KeepAlivePacket(std::uint64_t aliveID) : m_AliveID(aliveID) {} KeepAlivePacket(std::uint64_t aliveID) : m_AliveID(aliveID) {}
virtual ~KeepAlivePacket() {} virtual ~KeepAlivePacket() {}
virtual DataBuffer Serialize() const; virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
std::uint64_t getAliveID() const { return m_AliveID; } std::uint64_t GetAliveID() const { return m_AliveID; }
virtual PacketType getType() const { return PacketType::KeepAlive; } virtual PacketType GetType() const { return PacketType::KeepAlive; }
}; };
class PlayerLoginPacket : public Packet { class PlayerLoginPacket : public Packet {
@@ -100,13 +109,13 @@ public:
PlayerLoginPacket(std::string playerName) : m_PlayerName(playerName) {} PlayerLoginPacket(std::string playerName) : m_PlayerName(playerName) {}
virtual ~PlayerLoginPacket() {} virtual ~PlayerLoginPacket() {}
virtual DataBuffer Serialize() const; virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
virtual PacketType getType() const { return PacketType::PlayerLogin; } virtual PacketType GetType() const { return PacketType::PlayerLogin; }
const std::string& getPlayerName() const { return m_PlayerName; } const std::string& GetPlayerName() const { return m_PlayerName; }
}; };
class WorldBeginDataPacket : public Packet { class WorldBeginDataPacket : public Packet {
@@ -119,27 +128,27 @@ public:
} }
virtual ~WorldBeginDataPacket() {} virtual ~WorldBeginDataPacket() {}
virtual DataBuffer Serialize() const; virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
virtual PacketType getType() const { return PacketType::WorldBeginData; } virtual PacketType GetType() const { return PacketType::WorldBeginData; }
const game::TowerTileColorPalette& getTowerTilePalette() const { return m_Header.m_TowerPlacePalette; } const game::TowerTileColorPalette& GetTowerTilePalette() const { return m_Header.m_TowerPlacePalette; }
const game::Color& getWalkableTileColor() const { return m_Header.m_WalkablePalette; } const game::Color& GetWalkableTileColor() const { return m_Header.m_WalkablePalette; }
const std::vector<game::Color>& getDecorationPalette() const { return m_Header.m_DecorationPalette; } const std::vector<game::Color>& GetDecorationPalette() const { return m_Header.m_DecorationPalette; }
const game::Color& GetBackgroundColor() const { return m_Header.m_Background; }
const game::Spawn& getRedSpawn() const { return m_Header.m_RedSpawn; } const game::Spawn& GetRedSpawn() const { return m_Header.m_RedSpawn; }
const game::Spawn& getBlueSpawn() const { return m_Header.m_BlueSpawn; } const game::Spawn& GetBlueSpawn() const { return m_Header.m_BlueSpawn; }
const game::SpawnColorPalette& getSpawnPalette() const { return m_Header.m_SpawnColorPalette; } const game::SpawnColorPalette& GetSpawnPalette() const { return m_Header.m_SpawnColorPalette; }
const game::TeamCastle& getRedCastle() const { return m_Header.m_RedCastle; } const game::TeamCastle& GetRedCastle() const { return m_Header.m_RedCastle; }
const game::TeamCastle& getBlueCastle() const { return m_Header.m_BlueCastle; } const game::TeamCastle& GetBlueCastle() const { return m_Header.m_BlueCastle; }
const game::TilePalette getTilePalette() const { return m_Header.m_TilePalette; } const game::TilePalette GetTilePalette() const { return m_Header.m_TilePalette; }
DataBuffer SerializeCustom() const; // allow serialisation with invalid World member
void setWorldHeader(const WorldHeader& header) { m_Header = header; } void setWorldHeader(const WorldHeader& header) { m_Header = header; }
}; };
@@ -153,16 +162,16 @@ public:
WorldDataPacket(const game::World* world) : m_World(world) {} WorldDataPacket(const game::World* world) : m_World(world) {}
virtual ~WorldDataPacket() {} virtual ~WorldDataPacket() {}
virtual DataBuffer Serialize() const; virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
virtual PacketType getType() const { return PacketType::WorldData; } virtual PacketType GetType() const { return PacketType::WorldData; }
const std::unordered_map<game::ChunkCoord, game::ChunkPtr>& getChunks() const { return m_WorldData.m_Chunks; } const std::unordered_map<game::ChunkCoord, game::ChunkPtr>& GetChunks() const { return m_WorldData.m_Chunks; }
DataBuffer SerializeCustom() const; // allow serialisation with invalid World member DataBuffer SerializeCustom() const; // allow serialisation with invalid World member
void setWorldData(const WorldData& worldData) { m_WorldData = worldData; } void SetWorldData(const WorldData& worldData) { m_WorldData = worldData; }
}; };
class UpdateMoneyPacket : public Packet { class UpdateMoneyPacket : public Packet {
@@ -173,13 +182,13 @@ public:
UpdateMoneyPacket(std::uint32_t newAmount) : m_NewAmount(newAmount) {} UpdateMoneyPacket(std::uint32_t newAmount) : m_NewAmount(newAmount) {}
virtual ~UpdateMoneyPacket() {} virtual ~UpdateMoneyPacket() {}
std::uint32_t getGold() const { return m_NewAmount; } std::uint32_t GetGold() const { return m_NewAmount; }
virtual DataBuffer Serialize() const; virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
virtual PacketType getType() const { return PacketType::UpdateMoney; } virtual PacketType GetType() const { return PacketType::UpdateMoney; }
}; };
class UpdateExpPacket : public Packet { class UpdateExpPacket : public Packet {
@@ -190,11 +199,13 @@ public:
UpdateExpPacket(std::uint32_t newAmount) : m_NewAmount(newAmount) {} UpdateExpPacket(std::uint32_t newAmount) : m_NewAmount(newAmount) {}
virtual ~UpdateExpPacket() {} virtual ~UpdateExpPacket() {}
virtual DataBuffer Serialize() const; std::uint32_t GetExp() const { return m_NewAmount; }
virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
virtual PacketType getType() const { return PacketType::UpdateEXP; } virtual PacketType GetType() const { return PacketType::UpdateEXP; }
}; };
class UpdateLobbyTimePacket : public Packet { class UpdateLobbyTimePacket : public Packet {
@@ -205,13 +216,13 @@ public:
UpdateLobbyTimePacket(std::uint32_t remainingTime) : m_RemainingTime(remainingTime) {} UpdateLobbyTimePacket(std::uint32_t remainingTime) : m_RemainingTime(remainingTime) {}
virtual ~UpdateLobbyTimePacket() {} virtual ~UpdateLobbyTimePacket() {}
virtual DataBuffer Serialize() const; virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
std::uint32_t getRemainingTime() const { return m_RemainingTime; } std::uint32_t GetRemainingTime() const { return m_RemainingTime; }
virtual PacketType getType() const { return PacketType::UpdateLobbyTime; } virtual PacketType GetType() const { return PacketType::UpdateLobbyTime; }
}; };
class UpdateGameStatePacket : public Packet { class UpdateGameStatePacket : public Packet {
@@ -222,13 +233,13 @@ public:
UpdateGameStatePacket(game::GameState gameState) : m_GameState(gameState) {} UpdateGameStatePacket(game::GameState gameState) : m_GameState(gameState) {}
virtual ~UpdateGameStatePacket() {} virtual ~UpdateGameStatePacket() {}
virtual DataBuffer Serialize() const; virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
game::GameState getGameState() const { return m_GameState; } game::GameState GetGameState() const { return m_GameState; }
virtual PacketType getType() const { return PacketType::UpdateGameState; } virtual PacketType GetType() const { return PacketType::UpdateGameState; }
}; };
struct PlayerInfo { struct PlayerInfo {
@@ -244,13 +255,13 @@ public:
PlayerListPacket(std::map<std::uint8_t, PlayerInfo> players) : m_Players(players) {} PlayerListPacket(std::map<std::uint8_t, PlayerInfo> players) : m_Players(players) {}
virtual ~PlayerListPacket() {} virtual ~PlayerListPacket() {}
virtual DataBuffer Serialize() const; virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
const std::map<std::uint8_t, PlayerInfo>& getPlayers() const { return m_Players; } const std::map<std::uint8_t, PlayerInfo>& GetPlayers() const { return m_Players; }
virtual PacketType getType() const { return PacketType::PlayerList; } virtual PacketType GetType() const { return PacketType::PlayerList; }
}; };
class PlayerJoinPacket : public Packet { class PlayerJoinPacket : public Packet {
@@ -262,14 +273,14 @@ public:
PlayerJoinPacket(std::uint8_t playerID, const std::string& playerName) : m_PlayerID(playerID), m_PlayerName(playerName) {} PlayerJoinPacket(std::uint8_t playerID, const std::string& playerName) : m_PlayerID(playerID), m_PlayerName(playerName) {}
virtual ~PlayerJoinPacket() {} virtual ~PlayerJoinPacket() {}
virtual DataBuffer Serialize() const; virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
std::uint8_t getPlayerID() const { return m_PlayerID; } std::uint8_t GetPlayerID() const { return m_PlayerID; }
const std::string& getPlayerName() const { return m_PlayerName; } const std::string& GetPlayerName() const { return m_PlayerName; }
virtual PacketType getType() const { return PacketType::PlayerJoin; } virtual PacketType GetType() const { return PacketType::PlayerJoin; }
}; };
class PlayerLeavePacket : public Packet { class PlayerLeavePacket : public Packet {
@@ -280,13 +291,13 @@ public:
PlayerLeavePacket(std::uint8_t playerID) : m_PlayerID(playerID) {} PlayerLeavePacket(std::uint8_t playerID) : m_PlayerID(playerID) {}
virtual ~PlayerLeavePacket() {} virtual ~PlayerLeavePacket() {}
virtual DataBuffer Serialize() const; virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
std::uint8_t getPlayerID() const { return m_PlayerID; } std::uint8_t GetPlayerID() const { return m_PlayerID; }
virtual PacketType getType() const { return PacketType::PlayerLeave; } virtual PacketType GetType() const { return PacketType::PlayerLeave; }
}; };
class ConnexionInfoPacket : public Packet { class ConnexionInfoPacket : public Packet {
@@ -297,13 +308,13 @@ public:
ConnexionInfoPacket(std::uint8_t connectionID) : m_ConnectionID(connectionID) {} ConnexionInfoPacket(std::uint8_t connectionID) : m_ConnectionID(connectionID) {}
virtual ~ConnexionInfoPacket() {} virtual ~ConnexionInfoPacket() {}
virtual DataBuffer Serialize() const; virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
std::uint8_t getConnectionID() const { return m_ConnectionID; } std::uint8_t GetConnectionID() const { return m_ConnectionID; }
virtual PacketType getType() const { return PacketType::ConnectionInfo; } virtual PacketType GetType() const { return PacketType::ConnectionInfo; }
}; };
class SelectTeamPacket : public Packet { class SelectTeamPacket : public Packet {
@@ -314,13 +325,13 @@ public:
SelectTeamPacket(game::TeamColor selectedTeam) : m_SelectedTeam(selectedTeam) {} SelectTeamPacket(game::TeamColor selectedTeam) : m_SelectedTeam(selectedTeam) {}
virtual ~SelectTeamPacket() {} virtual ~SelectTeamPacket() {}
virtual DataBuffer Serialize() const; virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
game::TeamColor getSelectedTeam() const { return m_SelectedTeam; } game::TeamColor GetSelectedTeam() const { return m_SelectedTeam; }
virtual PacketType getType() const { return PacketType::SelectTeam; } virtual PacketType GetType() const { return PacketType::SelectTeam; }
}; };
class UpdatePlayerTeamPacket : public Packet { class UpdatePlayerTeamPacket : public Packet {
@@ -332,14 +343,14 @@ public:
UpdatePlayerTeamPacket(std::uint8_t playerID, game::TeamColor selectedTeam) : m_PlayerID(playerID), m_SelectedTeam(selectedTeam) {} UpdatePlayerTeamPacket(std::uint8_t playerID, game::TeamColor selectedTeam) : m_PlayerID(playerID), m_SelectedTeam(selectedTeam) {}
virtual ~UpdatePlayerTeamPacket() {} virtual ~UpdatePlayerTeamPacket() {}
virtual DataBuffer Serialize() const; virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
game::TeamColor getSelectedTeam() const { return m_SelectedTeam; } game::TeamColor GetSelectedTeam() const { return m_SelectedTeam; }
std::uint8_t getPlayerID() const { return m_PlayerID; } std::uint8_t GetPlayerID() const { return m_PlayerID; }
virtual PacketType getType() const { return PacketType::UpdatePlayerTeam; } virtual PacketType GetType() const { return PacketType::UpdatePlayerTeam; }
}; };
class DisconnectPacket : public Packet { class DisconnectPacket : public Packet {
@@ -350,13 +361,13 @@ public:
DisconnectPacket(std::string reason) : m_Reason(reason) {} DisconnectPacket(std::string reason) : m_Reason(reason) {}
virtual ~DisconnectPacket() {} virtual ~DisconnectPacket() {}
virtual DataBuffer Serialize() const; virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
const std::string& getReason() const { return m_Reason; } const std::string& GetReason() const { return m_Reason; }
virtual PacketType getType() const { return PacketType::Disconnect; } virtual PacketType GetType() const { return PacketType::Disconnect; }
}; };
class ServerTpsPacket : public Packet { class ServerTpsPacket : public Packet {
@@ -368,19 +379,19 @@ public:
ServerTpsPacket(float tps, std::uint64_t sendTime) : m_TPS(tps), m_PacketSendTime(sendTime) {} ServerTpsPacket(float tps, std::uint64_t sendTime) : m_TPS(tps), m_PacketSendTime(sendTime) {}
virtual ~ServerTpsPacket() {} virtual ~ServerTpsPacket() {}
virtual DataBuffer Serialize() const; virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
float getTPS() const { return m_TPS; } float GetTPS() const { return m_TPS; }
std::uint64_t getPacketSendTime() const { return m_PacketSendTime; } std::uint64_t GetPacketSendTime() const { return m_PacketSendTime; }
virtual PacketType getType() const { return PacketType::ServerTps; } virtual PacketType GetType() const { return PacketType::ServerTps; }
}; };
struct MobSend { // represents a mob send struct MobSend { // represents a mob send
game::MobType mobType; game::MobType mobType : 4;
game::MobLevel mobLevel; game::MobLevel mobLevel : 4;
std::uint8_t mobCount; // the max is 12 std::uint8_t mobCount; // the max is 12
}; };
@@ -392,13 +403,13 @@ public:
SendMobsPacket(const std::vector<MobSend>& mobSends) : m_MobSends(mobSends) {} SendMobsPacket(const std::vector<MobSend>& mobSends) : m_MobSends(mobSends) {}
virtual ~SendMobsPacket() {} virtual ~SendMobsPacket() {}
virtual DataBuffer Serialize() const; virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
const std::vector<MobSend>& getMobSends() const { return m_MobSends; } const std::vector<MobSend>& GetMobSends() const { return m_MobSends; }
virtual PacketType getType() const { return PacketType::SendMobs; } virtual PacketType GetType() const { return PacketType::SendMobs; }
}; };
class SpawnMobPacket : public Packet { class SpawnMobPacket : public Packet {
@@ -416,19 +427,19 @@ public:
m_MobDirection(dir), m_Sender(sender), m_MobX(x), m_MobY(y) {} m_MobDirection(dir), m_Sender(sender), m_MobX(x), m_MobY(y) {}
virtual ~SpawnMobPacket() {} virtual ~SpawnMobPacket() {}
virtual DataBuffer Serialize() const; virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
game::MobID getMobID() const { return m_MobID; } game::MobID GetMobID() const { return m_MobID; }
game::MobType getMobType() const { return m_MobType; } game::MobType GetMobType() const { return m_MobType; }
game::MobLevel getMobLevel() const { return m_MobLevel; } game::MobLevel GetMobLevel() const { return m_MobLevel; }
game::Direction getMobDirection() const { return m_MobDirection; } game::Direction GetMobDirection() const { return m_MobDirection; }
game::PlayerID getSender() const { return m_Sender; } game::PlayerID GetSender() const { return m_Sender; }
float getMobX() const { return m_MobX; } float GetMobX() const { return m_MobX; }
float getMobY() const { return m_MobY; } float GetMobY() const { return m_MobY; }
virtual PacketType getType() const { return PacketType::SpawnMob; } virtual PacketType GetType() const { return PacketType::SpawnMob; }
}; };
class PlaceTowerPacket : public Packet { class PlaceTowerPacket : public Packet {
@@ -441,15 +452,15 @@ public:
m_TowerX(x), m_TowerY(y), m_TowerType(type) {} m_TowerX(x), m_TowerY(y), m_TowerType(type) {}
virtual ~PlaceTowerPacket() {} virtual ~PlaceTowerPacket() {}
virtual DataBuffer Serialize() const; virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
std::int32_t getTowerX() const { return m_TowerX; } std::int32_t GetTowerX() const { return m_TowerX; }
std::int32_t getTowerY() const { return m_TowerY; } std::int32_t GetTowerY() const { return m_TowerY; }
game::TowerType getTowerType() const { return m_TowerType; } game::TowerType GetTowerType() const { return m_TowerType; }
virtual PacketType getType() const { return PacketType::PlaceTower; } virtual PacketType GetType() const { return PacketType::PlaceTower; }
}; };
class WorldAddTowerPacket : public Packet { class WorldAddTowerPacket : public Packet {
@@ -464,34 +475,34 @@ public:
m_TowerID(id), m_TowerX(x), m_TowerY(y), m_TowerType(type), m_Builder(player) {} m_TowerID(id), m_TowerX(x), m_TowerY(y), m_TowerType(type), m_Builder(player) {}
virtual ~WorldAddTowerPacket() {} virtual ~WorldAddTowerPacket() {}
virtual DataBuffer Serialize() const; virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
game::TowerID getTowerID() const { return m_TowerID; } game::TowerID GetTowerID() const { return m_TowerID; }
std::int32_t getTowerX() const { return m_TowerX; } std::int32_t GetTowerX() const { return m_TowerX; }
std::int32_t getTowerY() const { return m_TowerY; } std::int32_t GetTowerY() const { return m_TowerY; }
game::TowerType getTowerType() const { return m_TowerType; } game::TowerType GetTowerType() const { return m_TowerType; }
game::PlayerID getBuilder() const { return m_Builder; } game::PlayerID GetBuilder() const { return m_Builder; }
virtual PacketType getType() const { return PacketType::WorldAddTower; } virtual PacketType GetType() const { return PacketType::WorldAddTower; }
}; };
class WorldRemoveTowerPacket : public Packet { class RemoveTowerPacket : public Packet {
private: private:
game::TowerID m_TowerID; game::TowerID m_TowerID;
public: public:
WorldRemoveTowerPacket() {} RemoveTowerPacket() {}
WorldRemoveTowerPacket(game::TowerID id) : m_TowerID(id) {} RemoveTowerPacket(game::TowerID id) : m_TowerID(id) {}
virtual ~WorldRemoveTowerPacket() {} virtual ~RemoveTowerPacket() {}
virtual DataBuffer Serialize() const; virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
game::TowerID getTowerID() const { return m_TowerID; } game::TowerID GetTowerID() const { return m_TowerID; }
virtual PacketType getType() const { return PacketType::WorldRemoveTower; } virtual PacketType GetType() const { return PacketType::RemoveTower; }
}; };
class UpgradeTowerPacket : public Packet { class UpgradeTowerPacket : public Packet {
@@ -503,15 +514,120 @@ public:
UpgradeTowerPacket(game::TowerID tower, game::TowerLevel level) : m_TowerID(tower), m_TowerLevel(level) {} UpgradeTowerPacket(game::TowerID tower, game::TowerLevel level) : m_TowerID(tower), m_TowerLevel(level) {}
virtual ~UpgradeTowerPacket() {} virtual ~UpgradeTowerPacket() {}
virtual DataBuffer Serialize() const; virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data); virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const; virtual void Dispatch(PacketHandler* handler) const;
game::TowerID getTowerID() const { return m_TowerID; } game::TowerID GetTowerID() const { return m_TowerID; }
game::TowerLevel getTowerLevel() const { return m_TowerLevel; } game::TowerLevel GetTowerLevel() const { return m_TowerLevel; }
virtual PacketType getType() const { return PacketType::UpgradeTower; } virtual PacketType GetType() const { return PacketType::UpgradeTower; }
}; };
} class MobState {
} using Point = utils::shape::Point;
private:
game::MobID m_MobID;
Point m_MobPosition;
float m_MobLife;
game::Direction m_MobDirection;
public:
MobState() {}
MobState(game::MobID id, const Point& position, float life, game::Direction direction) :
m_MobID(id), m_MobPosition(position), m_MobLife(life), m_MobDirection(direction) {}
game::MobID GetMobId() const { return m_MobID; }
Point GetMobPosition() const { return m_MobPosition; }
float GetMobLife() const { return m_MobLife; }
game::Direction GetMobDirection() const { return m_MobDirection; }
};
class UpdateMobStatesPacket : public Packet {
private:
std::vector<MobState> m_MobStates;
public:
UpdateMobStatesPacket() {}
virtual ~UpdateMobStatesPacket() {}
virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const;
void addMobState(MobState mobState) { m_MobStates.push_back(mobState); }
const std::vector<MobState>& GetMobStates() const { return m_MobStates; }
virtual PacketType GetType() const { return PacketType::UpdateMobStates; }
};
class UpdateCastleLifePacket : public Packet {
private:
std::uint16_t m_CastleLife;
game::TeamColor m_Team;
public:
UpdateCastleLifePacket() {}
UpdateCastleLifePacket(std::uint16_t life, game::TeamColor team) : m_CastleLife(life), m_Team(team) {}
virtual ~UpdateCastleLifePacket() {}
virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const;
std::uint16_t GetCastleLife() const { return m_CastleLife; }
game::TeamColor GetTeamColor() const { return m_Team; }
virtual PacketType GetType() const { return PacketType::UpdateCastleLife; }
};
enum class ItemType : std::uint8_t {
// Upgrades
ClickerUpgrade,
GoldPerSecUpgrade,
// Items
};
/** Packet used by the client to buy items or upgrades
Packet used by the server to confirm transaction */
class PlayerBuyItemPacket : public Packet {
private:
ItemType m_ItemType;
std::uint8_t m_Count;
public:
PlayerBuyItemPacket() {}
PlayerBuyItemPacket(ItemType itemType, std::uint8_t count) : m_ItemType(itemType), m_Count(count) {}
virtual ~PlayerBuyItemPacket() {}
virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const;
ItemType GetItemType() const { return m_ItemType; }
std::uint8_t GetCount() const { return m_Count; }
virtual PacketType GetType() const { return PacketType::PlayerBuyItem; }
};
/** Packet used by the client to buy mob upgrades
Packet used by the server to confirm transaction */
class PlayerBuyMobUpgradePacket : public Packet {
private:
game::MobType m_MobType;
std::uint8_t m_MobLevel;
public:
PlayerBuyMobUpgradePacket() {}
PlayerBuyMobUpgradePacket(game::MobType mobType, std::uint8_t level) : m_MobType(mobType), m_MobLevel(level) {}
virtual ~PlayerBuyMobUpgradePacket() {}
virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const;
game::MobType GetMobType() const { return m_MobType; }
std::uint8_t GetLevel() const { return m_MobLevel; }
virtual PacketType GetType() const { return PacketType::PlayerBuyMobUpgrade; }
};
} // namespace protocol
} // namespace td

View File

@@ -1,8 +1,62 @@
#pragma once #pragma once
#ifdef __ANDROID__ #if !defined(TD_IMPL_OPENGL_ES2) \
#include <GLES3/gl3.h> && !defined(TD_IMPL_OPENGL_ES3) \
&& !defined(TD_IMPL_OPENGL_LOADER_GL3W) \
&& !defined(TD_IMPL_OPENGL_LOADER_GLEW) \
&& !defined(TD_IMPL_OPENGL_LOADER_GLAD) \
&& !defined(TD_IMPL_OPENGL_LOADER_GLBINDING2) \
&& !defined(TD_IMPL_OPENGL_LOADER_GLBINDING3) \
&& !defined(TD_IMPL_OPENGL_LOADER_CUSTOM) \
&& !defined(__ANDROID__)
#if defined(__has_include)
#if __has_include(<GL/glew.h>)
#define TD_IMPL_OPENGL_LOADER_GLEW
#elif __has_include(<glad/glad.h>)
#define TD_IMPL_OPENGL_LOADER_GLAD
#elif __has_include(<GL/gl3w.h>)
#define TD_IMPL_OPENGL_LOADER_GL3W
#elif __has_include(<glbinding/glbinding.h>)
#define TD_IMPL_OPENGL_LOADER_GLBINDING3
#elif __has_include(<glbinding/Binding.h>)
#define TD_IMPL_OPENGL_LOADER_GLBINDING2
#else #else
#include "glbinding/gl/gl.h" #error "Cannot detect OpenGL loader!"
using namespace gl; #endif
#else
#error "Cannot detect loader with include detection !"
#endif
#endif
// Include correct files
#if defined(__ANDROID__)
#include <GLES3/gl3.h>
#elif defined(TD_IMPL_OPENGL_LOADER_GL3W)
#include <GL/gl3w.h> // Needs to be initialized with gl3wInit() in user's code
#elif defined(TD_IMPL_OPENGL_LOADER_GLEW)
#include <GL/glew.h> // Needs to be initialized with glewInit() in user's code.
#elif defined(TD_IMPL_OPENGL_LOADER_GLAD)
#include <glad/glad.h> // Needs to be initialized with gladLoadGL() in user's code.
#elif defined(TD_IMPL_OPENGL_LOADER_GLBINDING2)
#ifndef GLFW_INCLUDE_NONE
#define GLFW_INCLUDE_NONE // GLFW including OpenGL headers causes ambiguity or multiple definition errors.
#endif
#include <glbinding/Binding.h> // Needs to be initialized with glbinding::Binding::initialize() in user's code.
#include <glbinding/gl/gl.h>
using namespace gl;
#elif defined(TD_IMPL_OPENGL_LOADER_GLBINDING3)
#ifndef GLFW_INCLUDE_NONE
#define GLFW_INCLUDE_NONE // GLFW including OpenGL headers causes ambiguity or multiple definition errors.
#endif
#include <glbinding/glbinding.h>// Needs to be initialized with glbinding::initialize() in user's code.
#include <glbinding/gl/gl.h>
using namespace gl;
#else
#include TD_IMPL_OPENGL_LOADER_CUSTOM
#endif #endif

View File

@@ -1,12 +1,4 @@
/* #pragma once
* Renderer.h
*
* Created on: 4 nov. 2020
* Author: simon
*/
#ifndef RENDER_RENDERER_H_
#define RENDER_RENDERER_H_
#include <glm/glm.hpp> #include <glm/glm.hpp>
#include <memory> #include <memory>
@@ -26,8 +18,10 @@ public:
glm::vec2 positon; glm::vec2 positon;
}; };
private: private:
std::unique_ptr<WorldShader> m_WorldShader; std::unique_ptr<shader::WorldShader> m_WorldShader;
std::unique_ptr<EntityShader> m_EntityShader; std::unique_ptr<shader::EntityShader> m_EntityShader;
glm::vec3 m_BackgroundColor;
bool m_IsometricView = true; bool m_IsometricView = true;
float m_IsometricShade = m_IsometricView; float m_IsometricShade = m_IsometricView;
@@ -36,27 +30,27 @@ public:
Renderer(); Renderer();
~Renderer(); ~Renderer();
bool init(); bool Init();
void prepare(); void Prepare();
void resize(const int width, const int height); void Resize(const int width, const int height);
void renderVAO(const GL::VertexArray& vao); void RenderVAO(const GL::VertexArray& vao);
void renderModel(const Model& model); void RenderModel(const Model& model);
void setZoom(float zoom); void SetZoom(float zoom);
void setCamMovement(const glm::vec2& mov); void SetCamMovement(const glm::vec2& mov);
void setCamPos(const glm::vec2& newPos); void SetCamPos(const glm::vec2& newPos);
void setIsometricView(bool isometric); // false = 2D true = Isometric void SetIsometricView(bool isometric); // false = 2D true = Isometric
glm::vec2 getCursorWorldPos(const glm::vec2& cursorPos, float aspectRatio, float zoom, float windowWidth, float windowHeight); void SetBackgroundColor(const glm::vec3& color) { m_BackgroundColor = color; }
glm::vec2 GetCursorWorldPos(const glm::vec2& cursorPos, float aspectRatio, float zoom, float windowWidth, float windowHeight);
private: private:
void updateIsometricView(); void UpdateIsometricView();
void updateIsometricFade(); void UpdateIsometricFade();
void initShader(); void InitShaders();
}; };
} // namespace render } // namespace render
} // namespace td } // namespace td
#endif /* RENDER_RENDERER_H_ */

View File

@@ -12,22 +12,26 @@ namespace render {
class VertexCache { class VertexCache {
typedef std::vector<float> Vector; typedef std::vector<float> Vector;
typedef std::pair<Vector::iterator, Vector::iterator> ElementsIndex;
typedef std::pair<ElementsIndex, ElementsIndex> DataIndex; struct DataIndex {
Vector position;
Vector color;
};
private: private:
Vector m_Positions; std::size_t m_VertexCount;
Vector m_Colors;
std::unordered_map<std::uint64_t, DataIndex> m_Indexes; std::unordered_map<std::uint64_t, DataIndex> m_Indexes;
std::unique_ptr<GL::VertexArray> m_VertexArray; std::unique_ptr<GL::VertexArray> m_VertexArray;
public: public:
void addData(std::uint64_t index, std::vector<float> positions, std::vector<float> colors); VertexCache() : m_VertexCount(0) {}
void removeData(std::uint64_t index);
void clear();
void updateVertexArray();
const GL::VertexArray& getVertexArray() const { return *m_VertexArray; } void AddData(std::uint64_t index, std::vector<float> positions, std::vector<float> colors);
bool isEmpty() const { return m_VertexArray == nullptr; } void RemoveData(std::uint64_t index);
void Clear();
void UpdateVertexArray();
const GL::VertexArray& GetVertexArray() const { return *m_VertexArray; }
bool IsEmpty() const { return m_VertexArray == nullptr; }
}; };
} // namespace render } // namespace render

View File

@@ -7,6 +7,7 @@
#include "render/gui/TowerPlacePopup.h" #include "render/gui/TowerPlacePopup.h"
#include "render/gui/MobTooltip.h" #include "render/gui/MobTooltip.h"
#include "render/gui/CastleTooltip.h"
#include "render/gui/imgui/imgui.h" #include "render/gui/imgui/imgui.h"
@@ -23,7 +24,7 @@ class ClientGame;
namespace render { namespace render {
class WorldRenderer { class WorldRenderer : public game::WorldListener {
private: private:
client::ClientGame* m_Client; client::ClientGame* m_Client;
Renderer* m_Renderer; Renderer* m_Renderer;
@@ -40,39 +41,46 @@ private:
std::unique_ptr<gui::TowerPlacePopup> m_TowerPlacePopup; std::unique_ptr<gui::TowerPlacePopup> m_TowerPlacePopup;
std::unique_ptr<gui::MobTooltip> m_MobTooltip; std::unique_ptr<gui::MobTooltip> m_MobTooltip;
std::unique_ptr<gui::CastleTooltip> m_CastleTooltip;
public: public:
WorldRenderer(game::World* world, client::ClientGame* client); WorldRenderer(game::World* world, client::ClientGame* client);
~WorldRenderer(); ~WorldRenderer();
void loadModels(); void LoadModels();
void addTower(game::TowerPtr tower); static ImVec4 GetImGuiTeamColor(game::TeamColor color);
void removeTower(game::TowerPtr tower);
static ImVec4 getImGuiTeamColor(game::TeamColor color); void Update();
void Render();
void update(); void SetCamPos(float camX, float camY);
void render();
void setCamPos(float camX, float camY); void MoveCam(float relativeX, float relativeY, float aspectRatio);
void ChangeZoom(float zoom);
void moveCam(float relativeX, float relativeY, float aspectRatio); // WorldListener
void changeZoom(float zoom);
virtual void OnTowerAdd(game::TowerPtr tower);
virtual void OnTowerRemove(game::TowerPtr tower);
private: private:
void click(); void Click();
void renderWorld() const; void RenderWorld() const;
void renderTowers() const; void RenderTowers() const;
void renderMobs() const; void RenderMobs() const;
void renderTileSelect() const; void RenderTileSelect() const;
void renderPopups(); void RenderPopups();
void renderTowerUpgradePopup(); void RenderTowerUpgradePopup();
void renderMobTooltip() const; void RenderMobTooltip() const;
void detectClick(); void RenderCastleTooltip() const;
void detectMobHovering() const; void DetectClick();
glm::vec2 getCursorWorldPos() const; void DetectMobHovering() const;
glm::vec2 getClickWorldPos() const; void DetectCastleHovering() const;
void RenderTooltips() const;
void RemoveTower();
glm::vec2 GetCursorWorldPos() const;
glm::vec2 GetClickWorldPos() const;
void updateCursorPos(); void UpdateCursorPos();
}; };
} // namespace render } // namespace render

View File

@@ -0,0 +1,28 @@
#pragma once
#include "GuiWidget.h"
namespace td {
namespace game {
class TeamCastle;
} // namespace game
namespace gui {
class CastleTooltip : public GuiWidget {
private:
const game::TeamCastle* m_Castle;
public:
CastleTooltip(client::Client* client);
virtual void Render();
void SetCastle(const game::TeamCastle* castle) { m_Castle = castle; }
bool IsShown() { return m_Castle != nullptr; }
};
} // namespace gui
} // namespace td

View File

@@ -13,7 +13,7 @@ private:
public: public:
FrameMenu(client::Client* client); FrameMenu(client::Client* client);
virtual void render(); virtual void Render();
}; };
} // namespace gui } // namespace gui

View File

@@ -11,13 +11,13 @@ private:
public: public:
GameMenu(client::Client* client); GameMenu(client::Client* client);
virtual void render(); virtual void Render();
private: private:
void showTPS(); void ShowTPS();
void showStats(); void ShowStats();
void showPlayers(); void ShowPlayers();
void showLobbyProgress(); void ShowLobbyProgress();
void showTeamSelection(); void ShowTeamSelection();
}; };
} // namespace gui } // namespace gui

View File

@@ -10,15 +10,17 @@ namespace gui {
class GuiManager { class GuiManager {
private: private:
std::vector<std::shared_ptr<GuiWidget>> m_Widgets; std::vector<std::unique_ptr<GuiWidget>> m_Widgets;
public: public:
void renderWidgets(){ GuiManager() {}
for(auto widget : m_Widgets){
widget->render(); void RenderWidgets() {
for (auto& widget : m_Widgets) {
widget->Render();
} }
} }
void addWidgets(const std::shared_ptr<GuiWidget>& widget){ void AddWidget(std::unique_ptr<GuiWidget>&& widget) {
m_Widgets.push_back(std::move(widget)); m_Widgets.push_back(std::move(widget));
} }
}; };

View File

@@ -14,9 +14,9 @@ protected:
public: public:
GuiWidget(client::Client* client) : m_Client(client) {} GuiWidget(client::Client* client) : m_Client(client) {}
client::Client* getClient() { return m_Client; } client::Client* GetClient() { return m_Client; }
virtual void render() = 0; virtual void Render() = 0;
}; };
} // namespace gui } // namespace gui

View File

@@ -26,11 +26,11 @@ public:
MainMenu(client::Client* client); MainMenu(client::Client* client);
~MainMenu(); ~MainMenu();
virtual void render(); virtual void Render();
const server::Server* getServer() const { return m_Server.get(); } const server::Server* GetServer() const { return m_Server.get(); }
private: private:
bool startServer(); bool StartServer();
}; };
} // namespace gui } // namespace gui

View File

@@ -18,9 +18,10 @@ private:
public: public:
MobTooltip(client::Client* client); MobTooltip(client::Client* client);
virtual void render(); virtual void Render();
void setMob(const game::Mob* mob) { m_Mob = mob; } void SetMob(const game::Mob* mob) { m_Mob = mob; }
bool IsShown() { return m_Mob != nullptr; }
}; };
} // namespace gui } // namespace gui

View File

@@ -17,9 +17,9 @@ private:
public: public:
SummonMenu(client::Client* client); SummonMenu(client::Client* client);
virtual void render(); virtual void Render();
private: private:
void setSummonMax(int valueIndex); void SetSummonMax(int valueIndex);
}; };
} // namespace gui } // namespace gui

View File

@@ -9,6 +9,8 @@
#include <memory> #include <memory>
#include "render/gui/GuiManager.h"
struct SDL_Window; struct SDL_Window;
typedef void* SDL_GLContext; typedef void* SDL_GLContext;
@@ -20,15 +22,6 @@ class Client;
} // namespace client } // namespace client
namespace gui {
class MainMenu;
class GameMenu;
class FrameMenu;
class UpdateMenu;
} // namespace gui
namespace render { namespace render {
class Renderer; class Renderer;
@@ -38,21 +31,18 @@ private:
SDL_Window* m_Window; SDL_Window* m_Window;
SDL_GLContext m_GlContext; SDL_GLContext m_GlContext;
td::render::Renderer* m_Renderer; td::render::Renderer* m_Renderer;
td::gui::GuiManager m_GuiManager;
std::unique_ptr<td::client::Client> m_Client; std::unique_ptr<td::client::Client> m_Client;
std::unique_ptr<td::gui::MainMenu> m_MainMenu;
std::unique_ptr<td::gui::GameMenu> m_GameMenu;
std::unique_ptr<td::gui::FrameMenu> m_FrameMenu;
std::unique_ptr<td::gui::UpdateMenu> m_UpdateMenu;
public: public:
TowerGui(SDL_Window* wndow, SDL_GLContext glContext, td::render::Renderer* renderer); TowerGui(SDL_Window* wndow, SDL_GLContext glContext, td::render::Renderer* renderer);
~TowerGui(); ~TowerGui();
void render(); void Render();
private: private:
void initWidgets(); void InitWidgets();
void tick(); void Tick();
void beginFrame(); void BeginFrame();
void endFrame(); void EndFrame();
}; };
} // namespace render } // namespace render

View File

@@ -13,15 +13,15 @@ private:
public: public:
TowerPlacePopup(client::Client* client); TowerPlacePopup(client::Client* client);
virtual void render(); virtual void Render();
void setClickPos(const glm::vec2& worldPos); void SetClickPos(const glm::vec2& worldPos);
private: private:
static constexpr float m_TowerPopupTileWidth = 250.0f; static constexpr float m_TowerPopupTileWidth = 200.0f;
static constexpr float m_TowerPopupTileHeight = 250.0f; static constexpr float m_TowerPopupTileHeight = 200.0f;
static constexpr float m_PlaceTowerButtonWidth = 200.0f; static constexpr float m_PlaceTowerButtonWidth = 150.0f;
static constexpr float m_PlaceTowerButtonHeight = 45.0f; static constexpr float m_PlaceTowerButtonHeight = 35.0f;
}; };
} // namespace gui } // namespace gui

View File

@@ -2,7 +2,7 @@
#include "GuiWidget.h" #include "GuiWidget.h"
#include "misc/Updater.h" #include "updater/Updater.h"
#include <future> #include <future>
@@ -18,11 +18,11 @@ private:
public: public:
UpdateMenu(client::Client* client); UpdateMenu(client::Client* client);
virtual void render(); virtual void Render();
private: private:
void checkUpdates(); void CheckUpdates();
bool isUpdateChecked(); bool IsUpdateChecked();
void renderErrorPopup(); void RenderErrorPopup();
}; };
} // namespace gui } // namespace gui

View File

@@ -107,8 +107,20 @@ namespace ImGui
} }
*/ */
#ifdef __ANDROID__ #include "render/GL.h"
#define IMGUI_IMPL_OPENGL_ES3
#else #if defined(__ANDROID__)
#define IMGUI_IMPL_OPENGL_LOADER_ES3
#elif defined(TD_IMPL_OPENGL_LOADER_GL3W)
#define IMGUI_IMPL_OPENGL_LOADER_GL3W
#elif defined(TD_IMPL_OPENGL_LOADER_GLEW)
#define IMGUI_IMPL_OPENGL_LOADER_GLEW
#elif defined(TD_IMPL_OPENGL_LOADER_GLAD)
#define IMGUI_IMPL_OPENGL_LOADER_GLAD
#elif defined(TD_IMPL_OPENGL_LOADER_GLBINDING2)
#define IMGUI_IMPL_OPENGL_LOADER_GLBINDING2 #define IMGUI_IMPL_OPENGL_LOADER_GLBINDING2
#elif defined(TD_IMPL_OPENGL_LOADER_GLBINDING3)
#define IMGUI_IMPL_OPENGL_LOADER_GLBINDING3
#else
#define IMGUI_IMPL_OPENGL_LOADER_CUSTOM
#endif #endif

View File

@@ -17,8 +17,9 @@
namespace GL { namespace GL {
struct VertexAttribPointer { struct VertexAttribPointer {
unsigned int m_Index, m_Size; unsigned int m_Index;
int m_Offset; unsigned int m_Size;
unsigned int m_Offset;
}; };
class VertexBuffer { class VertexBuffer {
@@ -27,6 +28,7 @@ private:
std::vector<VertexAttribPointer> m_VertexAttribs; std::vector<VertexAttribPointer> m_VertexAttribs;
public: public:
REMOVE_COPY(VertexBuffer); REMOVE_COPY(VertexBuffer);
VertexBuffer(VertexBuffer&& other) { VertexBuffer(VertexBuffer&& other) {
m_VertexAttribs = std::move(other.m_VertexAttribs); m_VertexAttribs = std::move(other.m_VertexAttribs);
m_ID = other.m_ID; m_ID = other.m_ID;
@@ -34,12 +36,14 @@ public:
other.m_ID = 0; other.m_ID = 0;
other.m_DataStride = 0; other.m_DataStride = 0;
} }
VertexBuffer(const std::vector<float>& data, unsigned int stride); VertexBuffer(const std::vector<float>& data, unsigned int stride);
~VertexBuffer(); ~VertexBuffer();
void bind() const;
void unbind() const; void Bind() const;
void addVertexAttribPointer(unsigned int index, unsigned int coordinateSize, unsigned int offset); void Unbind() const;
void bindVertexAttribs() const; void AddVertexAttribPointer(unsigned int index, unsigned int coordinateSize, unsigned int offset);
void BindVertexAttribs() const;
}; };
class VertexArray { class VertexArray {
@@ -48,6 +52,7 @@ private:
std::vector<VertexBuffer> m_VertexBuffers; //use to destroy vbos when become unused std::vector<VertexBuffer> m_VertexBuffers; //use to destroy vbos when become unused
public: public:
REMOVE_COPY(VertexArray); REMOVE_COPY(VertexArray);
VertexArray(VertexArray&& other) { VertexArray(VertexArray&& other) {
m_ID = other.m_ID; m_ID = other.m_ID;
m_VertexCount = other.m_VertexCount; m_VertexCount = other.m_VertexCount;
@@ -55,12 +60,14 @@ public:
other.m_VertexCount = 0; other.m_VertexCount = 0;
other.m_ID = 0; other.m_ID = 0;
} }
VertexArray(unsigned int vertexCount); VertexArray(unsigned int vertexCount);
~VertexArray(); ~VertexArray();
unsigned int getVertexCount() const { return m_VertexCount; }
void bindVertexBuffer(VertexBuffer& vbo); unsigned int GetVertexCount() const { return m_VertexCount; }
void bind() const; void BindVertexBuffer(VertexBuffer& vbo);
void unbind() const; void Bind() const;
void Unbind() const;
}; };
} }

View File

@@ -9,7 +9,9 @@
#define RENDER_LOADER_TEXTURELOADER_H_ #define RENDER_LOADER_TEXTURELOADER_H_
namespace TextureLoader { namespace TextureLoader {
const unsigned int loadGLTexture(const char* fileName);
unsigned int LoadGLTexture(const char* fileName);
} }

View File

@@ -13,10 +13,10 @@ struct RenderData {
std::vector<float> colors; std::vector<float> colors;
}; };
GL::VertexArray loadMobModel(); GL::VertexArray LoadMobModel();
GL::VertexArray loadWorldModel(const td::game::World* world); GL::VertexArray LoadWorldModel(const td::game::World* world);
GL::VertexArray loadTileSelectModel(); GL::VertexArray LoadTileSelectModel();
RenderData loadTowerModel(game::TowerPtr tower); RenderData LoadTowerModel(game::TowerPtr tower);
} // namespace WorldLoader } // namespace WorldLoader

View File

@@ -2,17 +2,29 @@
#include "ShaderProgram.h" #include "ShaderProgram.h"
namespace td {
namespace shader {
class EntityShader : public ShaderProgram { class EntityShader : public ShaderProgram {
private: private:
unsigned int location_cam = 0, location_zoom = 0, location_aspect_ratio = 0, location_translation = 0, location_viewtype = 0; unsigned int m_LocationCam = 0;
unsigned int m_LocationZoom = 0;
unsigned int m_LocationAspectRatio = 0;
unsigned int m_LocationTranslation = 0;
unsigned int m_LocationViewtype = 0;
protected: protected:
void getAllUniformLocation(); virtual void GetAllUniformLocation();
public: public:
EntityShader(); EntityShader();
void loadShader();
void setCamPos(const glm::vec2& camPos); void LoadShader();
void setZoom(float zoom); void SetCamPos(const glm::vec2& camPos);
void setAspectRatio(float aspectRatio); void SetZoom(float zoom);
void setModelPos(const glm::vec2& modelPos); void SetAspectRatio(float aspectRatio);
void setIsometricView(float isometric); void SetModelPos(const glm::vec2& modelPos);
void SetIsometricView(float isometric);
}; };
} // namespace shader
} // namespace td

View File

@@ -1,44 +1,44 @@
/* #pragma once
* ShaderProgram.h
*
* Created on: 31 janv. 2020
* Author: simon
*/
#ifndef RENDER_SHADERS_SHADERPROGRAM_H_
#define RENDER_SHADERS_SHADERPROGRAM_H_
#include <string> #include <string>
#include <glm/glm.hpp> #include <glm/glm.hpp>
#include "render/GL.h" #include "render/GL.h"
namespace td {
namespace shader {
class ShaderProgram { class ShaderProgram {
public: public:
ShaderProgram(); ShaderProgram();
virtual ~ShaderProgram(); virtual ~ShaderProgram();
void start() const;
void stop() const; void Start() const;
void loadProgramFile(const std::string& vertexFile, const std::string& fragmentFile); void Stop() const;
void loadProgram(const std::string& vertexSource, const std::string& fragmentSource);
void LoadProgramFile(const std::string& vertexFile, const std::string& fragmentFile);
void LoadProgram(const std::string& vertexSource, const std::string& fragmentSource);
protected: protected:
virtual void getAllUniformLocation() = 0; virtual void GetAllUniformLocation() = 0;
int getUniformLocation(const std::string& uniformName)const; int GetUniformLocation(const std::string& uniformName) const;
void loadFloat(const int location, const float value)const;
void loadInt(const int& location, const int& value)const; void LoadFloat(unsigned int location, float value) const;
void loadVector(const int& location, const glm::vec2& vector)const; void LoadInt(unsigned int location, int value) const;
void loadVector(const int& location, const glm::vec3& vector)const; void LoadVector(unsigned int location, const glm::vec2& vector) const;
void loadVector(const int& location, const glm::vec4& vector)const; void LoadVector(unsigned int location, const glm::vec3& vector) const;
void loadBoolean(const int& location, const bool& value)const; void LoadVector(unsigned int location, const glm::vec4& vector) const;
void loadMatrix(const int& location, const glm::mat4& matrix); void LoadBoolean(unsigned int location, bool value) const;
void cleanUp() const; void LoadMatrix(unsigned int location, const glm::mat4& matrix) const;
void CleanUp() const;
private: private:
unsigned int programID; unsigned int m_ProgramID;
unsigned int vertexShaderID; unsigned int m_VertexShaderID;
unsigned int fragmentShaderID; unsigned int m_FragmentShaderID;
int loadShaderFromFile(const std::string& file, GLenum type);
int loadShader(const std::string& source, GLenum type); unsigned int LoadShaderFromFile(const std::string& file, GLenum type);
unsigned int LoadShader(const std::string& source, GLenum type);
}; };
#endif /* RENDER_SHADERS_SHADERPROGRAM_H_ */ } // namespace shader
} // namespace td

View File

@@ -1,27 +1,23 @@
/* #pragma once
* GameShader.h
*
* Created on: 4 nov. 2020
* Author: simon
*/
#ifndef RENDER_SHADERS_GAMESHADER_H_
#define RENDER_SHADERS_GAMESHADER_H_
#include "ShaderProgram.h" #include "ShaderProgram.h"
namespace td {
namespace shader {
class WorldShader : public ShaderProgram { class WorldShader : public ShaderProgram {
private: private:
unsigned int location_cam = 0, location_zoom = 0, location_aspect_ratio = 0, location_viewtype = 0; unsigned int m_LocationCam = 0, m_LocationZoom = 0, m_LocationAspectRatio = 0, m_LocationViewtype = 0;
protected: protected:
void getAllUniformLocation(); void GetAllUniformLocation();
public: public:
WorldShader(); WorldShader();
void loadShader(); void LoadShader();
void setCamPos(const glm::vec2& camPos); void SetCamPos(const glm::vec2& camPos);
void setZoom(float zoom); void SetZoom(float zoom);
void setAspectRatio(float aspectRatio); void SetAspectRatio(float aspectRatio);
void setIsometricView(float isometric); void SetIsometricView(float isometric);
}; };
#endif /* RENDER_SHADERS_GAMESHADER_H_ */ } // namespace shader
} // namespace td

44
include/updater/Updater.h Normal file
View File

@@ -0,0 +1,44 @@
#pragma once
#include "misc/DataBuffer.h"
#define TD_VERSION "alpha-0.2.0"
namespace td {
namespace utils {
class Updater {
private:
float m_Progress;
bool m_DownloadComplete;
bool m_FileWrited;
bool m_CancelDownload;
DataBuffer m_FileBuffer;
std::string m_LastVersion;
public:
Updater() : m_Progress(0), m_DownloadComplete(false), m_FileWrited(false), m_CancelDownload(false) {}
bool CheckUpdate();
void DownloadUpdate();
void CancelDownload() { m_CancelDownload = true; m_Progress = 0.0f; m_DownloadComplete = false; }
bool WriteFile();
void ClearCache() { m_FileBuffer.Clear(); }
float GetDownloadProgress() { return m_Progress; }
bool IsDownloadComplete() { return m_DownloadComplete; }
bool IsFileWrited() { return m_FileWrited; }
static std::string GetLocalFilePath();
static void RemoveOldFile();
static std::string GetCurrentVersion() { return TD_VERSION; }
std::string GetLastVersion() { return m_LastVersion; }
bool CanUpdate();
private:
std::string GetDownloadFileURL();
};
} // namespace utils
} // namespace td

View File

@@ -11,19 +11,19 @@
namespace Display { namespace Display {
bool create(); bool Create();
void render(); void Render();
void update(); void Update();
void destroy(); void Destroy();
void pollEvents(); void PollEvents();
bool isCloseRequested(); bool IsCloseRequested();
bool isMouseDown(int button); bool IsMouseDown(int button);
float getAspectRatio(); float GetAspectRatio();
int getWindowWidth(); int GetWindowWidth();
int getWindowHeight(); int GetWindowHeight();
} }

View File

@@ -6,22 +6,34 @@
// Description : Hello World in C++, Ansi-style // Description : Hello World in C++, Ansi-style
//============================================================================ //============================================================================
#if !defined(NDEBUG) && !defined(_WIN32)
#define BACKWARD_HAS_UNWIND 1
#define BACKWARD_HAS_DW 1
#endif
#include "window/Display.h" #include "window/Display.h"
#include "misc/Updater.h" #include "updater/Updater.h"
#include "misc/Backward.hpp"
#ifdef __ANDROID__ #ifdef __ANDROID__
extern "C" extern "C"
#endif #endif
int main(int argc, const char* args[]) { int main(int argc, const char* args[]) {
td::utils::Updater::removeOldFile(); #if !defined(NDEBUG)
// setup signal handling
backward::SignalHandling sh;
#endif
Display::create(); // remove the outdated binary
while (!Display::isCloseRequested()) { td::utils::Updater::RemoveOldFile();
Display::pollEvents();
Display::render(); Display::Create();
Display::update(); while (!Display::IsCloseRequested()) {
Display::PollEvents();
Display::Render();
Display::Update();
} }
Display::destroy(); Display::Destroy();
return 0; return 0;
} }

View File

@@ -11,11 +11,27 @@ Game::~Game() {
} }
void Game::tick(std::uint64_t delta) { void Game::Tick(std::uint64_t delta) {
if (m_GameState == GameState::Game) { if (m_GameState == GameState::Game) {
m_World->tick(delta); m_World->Tick(delta);
} }
} }
Player* Game::GetPlayerById(PlayerID id) {
auto it = m_Players.find(id);
if (it == m_Players.end()) return nullptr;
return &it->second;
}
const Player* Game::GetPlayerById(PlayerID id) const {
auto it = m_Players.find(id);
if (it == m_Players.end()) return nullptr;
return &it->second;
}
} // namespace game } // namespace game
} // namespace td } // namespace td

View File

@@ -28,7 +28,7 @@ Connexion::Connexion(protocol::PacketDispatcher* dispatcher, network::TCPSocket&
} }
bool Connexion::updateSocket() { bool Connexion::UpdateSocket() {
if (m_Socket.GetStatus() != network::Socket::Connected) if (m_Socket.GetStatus() != network::Socket::Connected)
return false; return false;
@@ -47,13 +47,13 @@ bool Connexion::updateSocket() {
protocol::PacketType packetType; protocol::PacketType packetType;
decompressed >> packetType; decompressed >> packetType;
PacketPtr packet = protocol::PacketFactory::createPacket(packetType, decompressed); PacketPtr packet = protocol::PacketFactory::CreatePacket(packetType, decompressed);
GetDispatcher()->Dispatch(packet); GetDispatcher()->Dispatch(packet);
} }
return true; return true;
} }
bool Connexion::connect(const std::string& address, std::uint16_t port) { bool Connexion::Connect(const std::string& address, std::uint16_t port) {
if (!m_Socket.Connect(address, port)) { if (!m_Socket.Connect(address, port)) {
return false; return false;
} }
@@ -61,11 +61,11 @@ bool Connexion::connect(const std::string& address, std::uint16_t port) {
return true; return true;
} }
void Connexion::sendPacket(const protocol::Packet* packet) { void Connexion::SendPacket(const protocol::Packet* packet) {
network::SendPacket(packet->Serialize(), m_Socket); network::SendPacket(packet->Serialize(), m_Socket);
} }
void Connexion::closeConnection() { void Connexion::CloseConnection() {
m_Socket.Disconnect(); m_Socket.Disconnect();
} }

View File

@@ -1,4 +1,6 @@
#include "game/Mobs.h" #include "game/Mobs.h"
#include "game/Player.h"
#include "game/World.h"
#include <map> #include <map>
#include <algorithm> #include <algorithm>
@@ -6,54 +8,226 @@
namespace td { namespace td {
namespace game { namespace game {
bool Mob::isImmuneTo(TowerType type) { bool Mob::IsImmuneTo(TowerType type) {
return std::find(getTowerImmunities().begin(), getTowerImmunities().end(), type) != getTowerImmunities().end(); return std::find(GetTowerImmunities().begin(), GetTowerImmunities().end(), type) != GetTowerImmunities().end();
} }
bool Mob::isImmuneTo(EffectType type) { bool Mob::IsImmuneTo(EffectType type) {
return std::find(getEffectImmunities().begin(), getEffectImmunities().end(), type) != getEffectImmunities().end(); return std::find(GetEffectImmunities().begin(), GetEffectImmunities().end(), type) != GetEffectImmunities().end();
} }
EffectDuration& Mob::getEffect(EffectType effectType){ EffectDuration& Mob::GetEffect(EffectType effectType) {
return *std::find_if(m_Effects.begin(), m_Effects.end(), [&effectType](EffectDuration effect) { return effect.type == effectType;}); return *std::find_if(m_Effects.begin(), m_Effects.end(), [&effectType](EffectDuration effect) { return effect.type == effectType;});
} }
void Mob::addEffect(EffectType effectType, float durationSec, const Tower* tower) { void Mob::AddEffect(EffectType effectType, float durationSec, Tower* tower) {
if (isImmuneTo(effectType)) if (IsImmuneTo(effectType))
return; return;
if (hasEffect(effectType)) { if (HasEffect(effectType)) {
EffectDuration& effect = getEffect(effectType); EffectDuration& effect = GetEffect(effectType);
if (effect.duration < durationSec) if (effect.duration < durationSec)
effect.duration = durationSec; // setting new duration if it's greater then the actual effect.duration = durationSec; // Setting new duration if it's greater then the actual
} else { } else {
m_Effects.push_back({ effectType, durationSec, tower }); m_Effects.push_back({ effectType, durationSec, tower });
} }
} }
void Mob::tick(std::uint64_t delta) { void Mob::AttackCastle(std::uint64_t delta, World* world) {
updateEffects(delta); if (!HasReachedEnemyCastle()) return;
if (m_AttackTimer.Update(delta)) {
world->GetMobNotifier().NotifyListeners(&MobListener::OnMobCastleDamage, this, m_CastleTarget, GetStats()->GetDamage());
m_AttackTimer.ApplyCooldown();
}
} }
void Mob::updateEffects(std::uint64_t delta) { void Mob::Walk(std::uint64_t delta, World* world) {
float deltaSec = (float)delta / 1000.0f; float mobWalkSpeed = GetStats()->GetMovementSpeed();
float walkAmount = mobWalkSpeed * (static_cast<float>(delta) / 1000.0f);
if (HasEffect(EffectType::Slowness))
walkAmount *= 0.70; // walk 30% slower
switch (GetDirection()) {
case Direction::NegativeX: {
SetCenterX(GetCenterX() - walkAmount);
break;
}
case Direction::PositiveX: {
SetCenterX(GetCenterX() + walkAmount);
break;
}
case Direction::NegativeY: {
SetCenterY(GetCenterY() - walkAmount);
break;
}
case Direction::PositiveY: {
SetCenterY(GetCenterY() + walkAmount);
break;
}
default:
break;
}
}
void Mob::Move(std::uint64_t delta, World* world) {
TilePtr tile = world->GetTile(GetCenter().GetX(), GetCenter().GetY());
if (tile != nullptr && tile->GetType() == TileType::Walk) {
WalkableTilePtr walkTile = std::static_pointer_cast<WalkableTile>(tile);
ChangeDirection(*walkTile, world);
}
if (HasReachedEnemyCastle()) return;
Walk(delta, world);
TeamColor mobTeam = world->GetPlayerById(GetSender())->GetTeamColor();
TeamCastle* enemyCastle = nullptr;
if (mobTeam == TeamColor::Red) {
enemyCastle = &world->GetBlueTeam().GetCastle();
} else if (mobTeam == TeamColor::Blue) {
enemyCastle = &world->GetRedTeam().GetCastle();
}
if (IsTouchingCastle(*enemyCastle)) {
MoveBack(*enemyCastle, world);
SetMobReachedCastle(enemyCastle);
world->GetMobNotifier().NotifyListeners(&MobListener::OnMobTouchCastle, this, enemyCastle);
}
}
void Mob::MoveBack(const TeamCastle& enemyCastle, World* world) {
switch (GetDirection()) {
case Direction::NegativeX: {
SetCenterX(enemyCastle.GetBottomRight().GetX() + GetWidth() / 2.0f);
break;
}
case Direction::PositiveX: {
SetCenterX(enemyCastle.GetTopLeft().GetX() - GetWidth() / 2.0f);
break;
}
case Direction::NegativeY: {
SetCenterY(enemyCastle.GetBottomRight().GetY() + GetHeight() / 2.0f);
break;
}
case Direction::PositiveY: {
SetCenterY(enemyCastle.GetTopLeft().GetY() - GetHeight() / 2.0f);
break;
}
default:
break;
}
}
void Mob::ChangeDirection(const WalkableTile& tile, World* world) {
if (GetDirection() == tile.direction) return;
float tileX = static_cast<float>(static_cast<std::int32_t>(GetCenterX()));
float tileY = static_cast<float>(static_cast<std::int32_t>(GetCenterY()));
switch (GetDirection()) {
case Direction::PositiveY: {
if (tile.direction == Direction::NegativeX) {
if (GetTileY() > GetTileX()) {
SetCenterY(tileY + GetTileX());
SetDirection(tile.direction);
}
} else { // tile->direction = Direction::PositiveX
if (GetTileY() > 1 - GetTileX()) {
SetCenterY(tileY + (1 - GetTileX()));
SetDirection(tile.direction);
}
}
return;
}
case Direction::NegativeY: {
if (tile.direction == Direction::PositiveX) {
if (GetTileY() < GetTileX()) {
SetCenterY(tileY + GetTileX());
SetDirection(tile.direction);
}
} else { // tile.direction = Direction::NegativeX
if (GetTileY() < 1 - GetTileX()) {
SetCenterY(tileY + (1 - GetTileX()));
SetDirection(tile.direction);
}
}
return;
}
case Direction::PositiveX: {
if (tile.direction == Direction::NegativeY) {
if (GetTileX() > GetTileY()) {
SetCenterX(tileX + GetTileY());
SetDirection(tile.direction);
}
} else { // tile.direction = Direction::PositiveY
if (GetTileX() > 1 - GetTileY()) {
SetCenterX(tileX + (1 - GetTileY()));
SetDirection(tile.direction);
}
}
return;
}
case Direction::NegativeX: {
if (tile.direction == Direction::PositiveY) {
if (GetTileX() < GetTileY()) {
SetCenterX(tileX + GetTileY());
SetDirection(tile.direction);
}
} else { // tile.direction = Direction::NegativeY
if (GetTileX() < 1 - GetTileY()) {
SetCenterX(tileX + (1 - GetTileY()));
SetDirection(tile.direction);
}
}
return;
}
default:
break;
}
}
bool Mob::IsTouchingCastle(const TeamCastle& enemyCastle) const {
return enemyCastle.CollidesWith(*this);
}
void Mob::Tick(std::uint64_t delta, World* world) {
UpdateEffects(delta, world);
Move(delta, world);
AttackCastle(delta, world);
}
void Mob::UpdateEffects(std::uint64_t delta, World* world) {
float deltaSec = static_cast<float>(delta / 1000.0f);
for (std::size_t i = 0; i < m_Effects.size(); i++) { for (std::size_t i = 0; i < m_Effects.size(); i++) {
EffectDuration& effect = m_Effects[i]; EffectDuration& effect = m_Effects[i];
effect.duration -= deltaSec; effect.duration -= deltaSec;
if (effect.duration < 0) { // effect has gone if (effect.duration < 0) { // effect has gone
m_Effects.erase(m_Effects.begin() + i); m_Effects.erase(m_Effects.begin() + static_cast<int>(i));
switch (effect.type) { switch (effect.type) {
case EffectType::Fire: { case EffectType::Fire: {
m_EffectFireTimer.reset(); m_EffectFireTimer.Reset();
break; break;
} }
case EffectType::Poison: { case EffectType::Poison: {
m_EffectPoisonTimer.reset(); m_EffectPoisonTimer.Reset();
break; break;
} }
case EffectType::Heal: { case EffectType::Heal: {
m_EffectHealTimer.reset(); m_EffectHealTimer.Reset();
} }
default: default:
@@ -61,24 +235,24 @@ void Mob::updateEffects(std::uint64_t delta) {
} }
} }
} }
if(hasEffect(EffectType::Fire)){ if (HasEffect(EffectType::Fire)) {
if(m_EffectFireTimer.update(delta)){ if (m_EffectFireTimer.Update(delta)) {
damage(3, getEffect(EffectType::Fire).tower); world->GetMobNotifier().NotifyListeners(&MobListener::OnMobDamage, this, 3.0f, GetEffect(EffectType::Fire).tower);
} }
} }
if(hasEffect(EffectType::Poison)){ if (HasEffect(EffectType::Poison)) {
if(m_EffectPoisonTimer.update(delta)){ if (m_EffectPoisonTimer.Update(delta)) {
damage(1, getEffect(EffectType::Poison).tower); world->GetMobNotifier().NotifyListeners(&MobListener::OnMobDamage, this, 1.0f, GetEffect(EffectType::Poison).tower);
} }
} }
if(hasEffect(EffectType::Heal)){ if (HasEffect(EffectType::Heal)) {
if(m_EffectFireTimer.update(delta)){ if (m_EffectFireTimer.Update(delta)) {
heal(10); Heal(10);
} }
} }
} }
bool Mob::hasEffect(EffectType type) { bool Mob::HasEffect(EffectType type) {
return std::find_if(m_Effects.begin(), m_Effects.end(), [&type](EffectDuration effect) { return effect.type == type;}) != m_Effects.end(); return std::find_if(m_Effects.begin(), m_Effects.end(), [&type](EffectDuration effect) { return effect.type == type;}) != m_Effects.end();
} }
@@ -87,74 +261,74 @@ bool Mob::hasEffect(EffectType type) {
typedef std::pair<MobType, std::uint8_t> MobKey; typedef std::pair<MobType, std::uint8_t> MobKey;
const std::map<MobKey, MobStats> MobConstants = { static const std::map<MobKey, MobStats> MobConstants = {
// damage speed money_cost exp_cost exp_reward max_health // damage speed size money_cost exp_cost exp_reward max_health
{{MobType::Zombie, 1},{MobStats{1, 1.6, 15, 0, 7, 40}}}, {{MobType::Zombie, 1},{MobStats{1, 1.6, {1, 1}, 15, 0, 7, 40}}},
{{MobType::Zombie, 2},{MobStats{1, 1.6, 18, 88, 9, 56}}}, {{MobType::Zombie, 2},{MobStats{1, 1.6, {1, 1}, 18, 88, 9, 56}}},
{{MobType::Zombie, 3},{MobStats{1, 1.6, 22, 153, 10, 78}}}, {{MobType::Zombie, 3},{MobStats{1, 1.6, {1, 1}, 22, 153, 10, 78}}},
{{MobType::Zombie, 4},{MobStats{1.5, 1.6, 26, 268, 13, 110}}}, {{MobType::Zombie, 4},{MobStats{1.5, 1.6, {1, 1}, 26, 268, 13, 110}}},
{{MobType::Zombie, 5},{MobStats{2, 1.6, 31, 469, 15, 154}}}, {{MobType::Zombie, 5},{MobStats{2, 1.6, {1, 1}, 31, 469, 15, 154}}},
{{MobType::Spider, 1},{MobStats{1, 1.6, 25, 100, 15, 80}}}, {{MobType::Spider, 1},{MobStats{1, 1.6, {1, 1}, 25, 100, 15, 80}}},
{{MobType::Spider, 2},{MobStats{1, 2, 30, 175, 16, 112}}}, {{MobType::Spider, 2},{MobStats{1, 2, {1, 1}, 30, 175, 16, 112}}},
{{MobType::Spider, 3},{MobStats{1.5, 2, 36, 306, 18, 157}}}, {{MobType::Spider, 3},{MobStats{1.5, 2, {1, 1}, 36, 306, 18, 157}}},
{{MobType::Spider, 4},{MobStats{2.5, 2, 43, 536, 19, 222}}}, {{MobType::Spider, 4},{MobStats{2.5, 2, {1, 1}, 43, 536, 19, 222}}},
{{MobType::Spider, 5},{MobStats{1.5, 2.5, 52, 938, 22, 307}}}, {{MobType::Spider, 5},{MobStats{1.5, 2.5, {1, 1}, 52, 938, 22, 307}}},
{{MobType::Skeleton, 1},{MobStats{1, 1.6, 120, 200, 30, 350}}}, {{MobType::Skeleton, 1},{MobStats{1, 1.6, {1, 1}, 120, 200, 30, 350}}},
{{MobType::Skeleton, 2},{MobStats{1, 1.6, 144, 350, 33, 490}}}, {{MobType::Skeleton, 2},{MobStats{1, 1.6, {1, 1}, 144, 350, 33, 490}}},
{{MobType::Skeleton, 3},{MobStats{1, 1.6, 173, 613, 36, 686}}}, {{MobType::Skeleton, 3},{MobStats{1, 1.6, {1, 1}, 173, 613, 36, 686}}},
{{MobType::Skeleton, 4},{MobStats{1.5, 1.6, 225, 1072, 40, 960}}}, {{MobType::Skeleton, 4},{MobStats{1.5, 1.6, {1, 1}, 225, 1072, 40, 960}}},
{{MobType::Skeleton, 5},{MobStats{2, 1.6, 255, 1876, 43, 1345}}}, {{MobType::Skeleton, 5},{MobStats{2, 1.6, {1, 1}, 255, 1876, 43, 1345}}},
{{MobType::Pigman, 1},{MobStats{1, 2, 100, 150, 22, 150}}}, {{MobType::Pigman, 1},{MobStats{1, 2, {1, 1}, 100, 150, 22, 150}}},
{{MobType::Pigman, 2},{MobStats{1, 2, 120, 263, 24, 210}}}, {{MobType::Pigman, 2},{MobStats{1, 2, {1, 1}, 120, 263, 24, 210}}},
{{MobType::Pigman, 3},{MobStats{1, 2, 144, 459, 25, 297}}}, {{MobType::Pigman, 3},{MobStats{1, 2, {1, 1}, 144, 459, 25, 297}}},
{{MobType::Pigman, 4},{MobStats{1, 2, 173, 804, 25, 412}}}, {{MobType::Pigman, 4},{MobStats{1, 2, {1, 1}, 173, 804, 25, 412}}},
{{MobType::Pigman, 5},{MobStats{1.5, 2, 207, 1407, 27, 576}}}, {{MobType::Pigman, 5},{MobStats{1.5, 2, {1, 1}, 207, 1407, 27, 576}}},
{{MobType::Creeper, 1},{MobStats{1, 2, 250, 325, 46, 350}}}, {{MobType::Creeper, 1},{MobStats{1, 2, {1, 1}, 250, 325, 46, 350}}},
{{MobType::Creeper, 2},{MobStats{1, 2, 290, 550, 49, 460}}}, {{MobType::Creeper, 2},{MobStats{1, 2, {1, 1}, 290, 550, 49, 460}}},
{{MobType::Creeper, 3},{MobStats{2, 2, 350, 800, 55, 630}}}, {{MobType::Creeper, 3},{MobStats{2, 2, {1, 1}, 350, 800, 55, 630}}},
{{MobType::Creeper, 4},{MobStats{3, 2, 420, 1300, 61, 900}}}, {{MobType::Creeper, 4},{MobStats{3, 2, {1, 1}, 420, 1300, 61, 900}}},
{{MobType::Creeper, 5},{MobStats{4, 2, 510, 1850, 67, 1250}}}, {{MobType::Creeper, 5},{MobStats{4, 2, {1, 1}, 510, 1850, 67, 1250}}},
{{MobType::Silverfish, 1},{MobStats{1, 1.6, 38, 125, 18, 120}}}, {{MobType::Silverfish, 1},{MobStats{1, 1.6, {1, 1}, 38, 125, 18, 120}}},
{{MobType::Silverfish, 2},{MobStats{1, 1.6, 50, 230, 19, 170}}}, {{MobType::Silverfish, 2},{MobStats{1, 1.6, {1, 1}, 50, 230, 19, 170}}},
{{MobType::Silverfish, 3},{MobStats{1, 1.6, 75, 340, 25, 225}}}, {{MobType::Silverfish, 3},{MobStats{1, 1.6, {1, 1}, 75, 340, 25, 225}}},
{{MobType::Silverfish, 4},{MobStats{1.5, 1.6, 170, 700, 33, 310}}}, {{MobType::Silverfish, 4},{MobStats{1.5, 1.6, {1, 1}, 170, 700, 33, 310}}},
{{MobType::Silverfish, 5},{MobStats{1.5, 1.6, 200, 1800, 36, 390}}}, {{MobType::Silverfish, 5},{MobStats{1.5, 1.6, {1, 1}, 200, 1800, 36, 390}}},
{{MobType::Blaze, 1},{MobStats{1, 1.6, 500, 500, 105, 410}}}, {{MobType::Blaze, 1},{MobStats{1, 1.6, {1, 1}, 500, 500, 105, 410}}},
{{MobType::Blaze, 2},{MobStats{1, 1.6, 600, 875, 111, 574}}}, {{MobType::Blaze, 2},{MobStats{1, 1.6, {1, 1}, 600, 875, 111, 574}}},
{{MobType::Blaze, 3},{MobStats{1, 1.6, 720, 1531, 115, 804}}}, {{MobType::Blaze, 3},{MobStats{1, 1.6, {1, 1}, 720, 1531, 115, 804}}},
{{MobType::Blaze, 4},{MobStats{1.5, 1.6, 864, 2680, 121, 1125}}}, {{MobType::Blaze, 4},{MobStats{1.5, 1.6, {1, 1}, 864, 2680, 121, 1125}}},
{{MobType::Blaze, 5},{MobStats{2, 1.6, 1037, 4689, 127, 1575}}}, {{MobType::Blaze, 5},{MobStats{2, 1.6, {1, 1}, 1037, 4689, 127, 1575}}},
{{MobType::Witch, 1},{MobStats{1, 1.6, 150, 300, 37, 300}}}, {{MobType::Witch, 1},{MobStats{1, 1.6, {1, 1}, 150, 300, 37, 300}}},
{{MobType::Witch, 2},{MobStats{1, 1.6, 165, 525, 39, 405}}}, {{MobType::Witch, 2},{MobStats{1, 1.6, {1, 1}, 165, 525, 39, 405}}},
{{MobType::Witch, 3},{MobStats{1, 1.6, 182, 918, 42, 547}}}, {{MobType::Witch, 3},{MobStats{1, 1.6, {1, 1}, 182, 918, 42, 547}}},
{{MobType::Witch, 4},{MobStats{1.5, 1.6, 200, 1606, 43, 738}}}, {{MobType::Witch, 4},{MobStats{1.5, 1.6, {1, 1}, 200, 1606, 43, 738}}},
{{MobType::Witch, 5},{MobStats{2, 1.6, 220, 2810, 45, 996}}}, {{MobType::Witch, 5},{MobStats{2, 1.6, {1, 1}, 220, 2810, 45, 996}}},
{{MobType::Slime, 1},{MobStats{1, 0.8, 1500, 1000, 300, 800}}}, {{MobType::Slime, 1},{MobStats{1, 0.8, {1, 1}, 1500, 1000, 300, 800}}},
{{MobType::Slime, 2},{MobStats{1.5, 0.8, 1800, 1750, 314, 880}}}, {{MobType::Slime, 2},{MobStats{1.5, 0.8, {1, 1}, 1800, 1750, 314, 880}}},
{{MobType::Slime, 3},{MobStats{2, 0.8, 2160, 3063, 330, 968}}}, {{MobType::Slime, 3},{MobStats{2, 0.8, {1, 1}, 2160, 3063, 330, 968}}},
{{MobType::Slime, 4},{MobStats{2.5, 0.8, 2592, 5359, 348, 1065}}}, {{MobType::Slime, 4},{MobStats{2.5, 0.8, {1, 1}, 2592, 5359, 348, 1065}}},
{{MobType::Slime, 5},{MobStats{3, 0.8, 3110, 9379, 366, 1171}}}, {{MobType::Slime, 5},{MobStats{3, 0.8, {1, 1}, 3110, 9379, 366, 1171}}},
{{MobType::Giant, 1},{MobStats{10, 0.8, 4000, 2250, 600, 6250}}}, {{MobType::Giant, 1},{MobStats{10, 0.8, {1, 1}, 4000, 2250, 600, 6250}}},
{{MobType::Giant, 2},{MobStats{20, 0.8, 4500, 4000, 612, 9375}}}, {{MobType::Giant, 2},{MobStats{20, 0.8, {1, 1}, 4500, 4000, 612, 9375}}},
{{MobType::Giant, 3},{MobStats{30, 0.8, 5062, 7250, 624, 14062}}}, {{MobType::Giant, 3},{MobStats{30, 0.8, {1, 1}, 5062, 7250, 624, 14062}}},
{{MobType::Giant, 4},{MobStats{40, 0.8, 5695, 12500, 636, 21093}}}, {{MobType::Giant, 4},{MobStats{40, 0.8, {1, 1}, 5695, 12500, 636, 21093}}},
{{MobType::Giant, 5},{MobStats{50, 0.8, 6407, 22000, 648, 31640}}}, {{MobType::Giant, 5},{MobStats{50, 0.8, {1, 1}, 6407, 22000, 648, 31640}}},
}; };
const MobStats* getMobStats(MobType type, std::uint8_t level) { const MobStats* GetMobStats(MobType type, std::uint8_t level) {
return &MobConstants.at(MobKey{ type, level }); return &MobConstants.at(MobKey{ type, level });
} }
const std::map<MobKey, TowerImmunities> MobsTowerImmunities = { static const std::map<MobKey, TowerImmunities> MobsTowerImmunities = {
{{MobType::Zombie, 1},{}}, {{MobType::Zombie, 1},{}},
{{MobType::Zombie, 2},{}}, {{MobType::Zombie, 2},{}},
{{MobType::Zombie, 3},{}}, {{MobType::Zombie, 3},{}},
@@ -216,11 +390,11 @@ const std::map<MobKey, TowerImmunities> MobsTowerImmunities = {
{{MobType::Giant, 5},{}}, {{MobType::Giant, 5},{}},
}; };
const TowerImmunities& getMobTowerImmunities(MobType type, std::uint8_t level) { const TowerImmunities& GetMobTowerImmunities(MobType type, std::uint8_t level) {
return MobsTowerImmunities.at({ type, level }); return MobsTowerImmunities.at({ type, level });
} }
const std::map<MobKey, EffectImmunities> MobsEffectImmunities = { static const std::map<MobKey, EffectImmunities> MobsEffectImmunities = {
{{MobType::Zombie, 1},{}}, {{MobType::Zombie, 1},{}},
{{MobType::Zombie, 2},{}}, {{MobType::Zombie, 2},{}},
{{MobType::Zombie, 3},{}}, {{MobType::Zombie, 3},{}},
@@ -235,7 +409,7 @@ const std::map<MobKey, EffectImmunities> MobsEffectImmunities = {
{{MobType::Skeleton, 1},{}}, {{MobType::Skeleton, 1},{}},
{{MobType::Skeleton, 2},{}}, {{MobType::Skeleton, 2},{}},
{{MobType::Skeleton, 3},{EffectType::Fire}}, {{MobType::Skeleton, 3},{}},
{{MobType::Skeleton, 4},{EffectType::Fire}}, {{MobType::Skeleton, 4},{EffectType::Fire}},
{{MobType::Skeleton, 5},{EffectType::Fire}}, {{MobType::Skeleton, 5},{EffectType::Fire}},
@@ -282,14 +456,14 @@ const std::map<MobKey, EffectImmunities> MobsEffectImmunities = {
{{MobType::Giant, 5},{EffectType::Stun}}, {{MobType::Giant, 5},{EffectType::Stun}},
}; };
const EffectImmunities& getMobEffectImmunities(MobType type, std::uint8_t level) { const EffectImmunities& GetMobEffectImmunities(MobType type, std::uint8_t level) {
return MobsEffectImmunities.at({ type, level }); return MobsEffectImmunities.at({ type, level });
} }
MobPtr MobFactory::createMob(MobID id, MobType type, std::uint8_t level, PlayerID sender) { MobPtr MobFactory::CreateMob(MobID mobId, MobType mobType, std::uint8_t mobLevel, PlayerID mobSender) {
using MobCreator = std::function<std::shared_ptr<Mob>(MobID, std::uint8_t, PlayerID)>; using MobCreator = std::function<std::shared_ptr<Mob>(MobID, std::uint8_t, PlayerID)>;
static std::map<MobType, MobCreator> mobFactory = { static const std::map<MobType, MobCreator> mobFactory = {
{MobType::Zombie, [](MobID id, std::uint8_t level, PlayerID sender) -> MobPtr {return std::make_shared<Zombie>(id, level, sender);} }, {MobType::Zombie, [](MobID id, std::uint8_t level, PlayerID sender) -> MobPtr {return std::make_shared<Zombie>(id, level, sender);} },
{MobType::Spider, [](MobID id, std::uint8_t level, PlayerID sender) -> MobPtr {return std::make_shared<Spider>(id, level, sender);} }, {MobType::Spider, [](MobID id, std::uint8_t level, PlayerID sender) -> MobPtr {return std::make_shared<Spider>(id, level, sender);} },
{MobType::Skeleton, [](MobID id, std::uint8_t level, PlayerID sender) -> MobPtr {return std::make_shared<Skeleton>(id, level, sender);} }, {MobType::Skeleton, [](MobID id, std::uint8_t level, PlayerID sender) -> MobPtr {return std::make_shared<Skeleton>(id, level, sender);} },
@@ -302,10 +476,10 @@ MobPtr MobFactory::createMob(MobID id, MobType type, std::uint8_t level, PlayerI
{MobType::Giant, [](MobID id, std::uint8_t level, PlayerID sender) -> MobPtr {return std::make_shared<Giant>(id, level, sender);} }, {MobType::Giant, [](MobID id, std::uint8_t level, PlayerID sender) -> MobPtr {return std::make_shared<Giant>(id, level, sender);} },
}; };
return mobFactory[type](id, level, sender); return mobFactory.at(mobType)(mobId, mobLevel, mobSender);
} }
std::string MobFactory::getMobName(MobType type){ std::string MobFactory::GetMobName(MobType type) {
switch (type) { switch (type) {
case MobType::Zombie: case MobType::Zombie:
return "Zombie"; return "Zombie";

View File

@@ -1,23 +1,25 @@
#include "game/Player.h" #include "game/Player.h"
#include <algorithm>
namespace td { namespace td {
namespace game { namespace game {
Team::Team(TeamColor color) : m_Color(color) {} Team::Team(TeamColor color) : m_Color(color), m_TeamCastle(this) {}
void Team::addPlayer(Player* newPlayer) { void Team::AddPlayer(Player* newPlayer) {
m_Players.push_back(newPlayer); m_Players.push_back(newPlayer);
} }
void Team::removePlayer(const Player* player) { void Team::RemovePlayer(const Player* player) {
m_Players.erase(std::find(m_Players.begin(), m_Players.end(), player)); m_Players.erase(std::find(m_Players.begin(), m_Players.end(), player));
} }
TeamColor Team::getColor() const { TeamColor Team::GetColor() const {
return m_Color; return m_Color;
} }
std::uint8_t Team::getPlayerCount() const { std::uint8_t Team::GetPlayerCount() const {
return m_Players.size(); return m_Players.size();
} }

View File

@@ -6,10 +6,10 @@
namespace td { namespace td {
namespace game { namespace game {
bool Tower::isMobInRange(MobPtr mob) { bool Tower::IsMobInRange(MobPtr mob) {
if (mob->isDead()) if (mob->IsDead())
return false; return false;
return (m_X - mob->getX()) * (m_X - mob->getX()) + (m_Y - mob->getY()) * (m_Y - mob->getY()) < (getStats()->getRange() * getStats()->getRange()); return mob->CollidesWith(*this);
} }
const std::map<std::pair<TowerType, TowerLevel>, TowerStats> TowerConstants = { const std::map<std::pair<TowerType, TowerLevel>, TowerStats> TowerConstants = {
@@ -21,8 +21,8 @@ const std::map<std::pair<TowerType, TowerLevel>, TowerStats> TowerConstants = {
{{TowerType::Archer, {4, TowerPath::Top}}, {0.8, 0, 15}}, {{TowerType::Archer, {4, TowerPath::Top}}, {0.8, 0, 15}},
{{TowerType::Archer, {2, TowerPath::Bottom}}, {2, 10, 12}}, {{TowerType::Archer, {2, TowerPath::Bottom}}, {2, 10, 12}},
{{TowerType::Archer, {3, TowerPath::Bottom}}, {2, 0, 13}}, {{TowerType::Archer, {3, TowerPath::Bottom}}, {2, 10, 13}},
{{TowerType::Archer, {4, TowerPath::Bottom}}, {2, 0, 15}}, {{TowerType::Archer, {4, TowerPath::Bottom}}, {2, 10, 15}},
//----------------------------------------------------------------- //-----------------------------------------------------------------
@@ -115,7 +115,7 @@ const std::map<std::pair<TowerType, TowerLevel>, TowerStats> TowerConstants = {
{{TowerType::Necromancer, {3, TowerPath::Bottom}}, {0, 30, 0}}, {{TowerType::Necromancer, {3, TowerPath::Bottom}}, {0, 30, 0}},
}; };
const TowerStats* getTowerStats(TowerType type, TowerLevel level) { const TowerStats* GetTowerStats(TowerType type, TowerLevel level) {
auto it = TowerConstants.find({ type, level }); auto it = TowerConstants.find({ type, level });
if (it == TowerConstants.end()) return nullptr; if (it == TowerConstants.end()) return nullptr;
return &it->second; return &it->second;
@@ -139,7 +139,7 @@ static const std::map<TowerType, TowerInfo> TowerInfoConstants = {
{TowerType::Zeus, {"Zeus", "Strike lightning", false}}, {TowerType::Zeus, {"Zeus", "Strike lightning", false}},
}; };
const TowerInfo& getTowerInfo(TowerType type) { const TowerInfo& GetTowerInfo(TowerType type) {
return TowerInfoConstants.at(type); return TowerInfoConstants.at(type);
} }
@@ -165,11 +165,11 @@ static const std::map<TowerType, TowerCreator> towerFactory = {
{TowerType::Turret, [](TowerID id, std::int32_t x, std::int32_t y, PlayerID builder) -> TowerPtr {return std::make_shared<TurretTower>(id, x, y , builder);} }, {TowerType::Turret, [](TowerID id, std::int32_t x, std::int32_t y, PlayerID builder) -> TowerPtr {return std::make_shared<TurretTower>(id, x, y , builder);} },
}; };
TowerPtr createTower(TowerType type, TowerID id, std::int32_t x, std::int32_t y, PlayerID builder) { TowerPtr CreateTower(TowerType type, TowerID id, std::int32_t x, std::int32_t y, PlayerID builder) {
return towerFactory.at(type)(id, x, y, builder); return towerFactory.at(type)(id, x, y, builder);
} }
std::string getTowerName(TowerType type) { std::string GetTowerName(TowerType type) {
switch (type) { switch (type) {
case TowerType::Archer: case TowerType::Archer:
@@ -206,56 +206,57 @@ std::string getTowerName(TowerType type) {
void ArcherTower::tick(std::uint64_t delta, World* world) { void ArcherTower::Tick(std::uint64_t delta, World* world) {
if (m_Timer.update(delta)) { if (m_Timer.Update(delta)) {
std::uint8_t arrowsShot = 0; std::uint8_t arrowsShot = 0;
bool explosiveArrows = getLevel().getPath() == TowerPath::Bottom; bool explosiveArrows = GetLevel().GetPath() == TowerPath::Bottom;
std::uint8_t arrows = explosiveArrows ? 2 : getLevel().getLevel(); std::uint8_t arrows = explosiveArrows ? 2 : GetLevel().GetLevel();
for (MobPtr mob : world->getMobList()) { for (MobPtr mob : world->GetMobList()) {
if (isMobInRange(mob)) { if (IsMobInRange(mob)) {
world->OnArrowShot(mob, this); world->GetWorldNotifier().NotifyListeners(&WorldListener::OnArcherTowerShot, mob, this);
m_Timer.ApplyCooldown();
arrowsShot++; arrowsShot++;
if (arrowsShot >= arrows) if (arrowsShot >= arrows)
break; break;
m_Timer.applyCooldown();
} }
} }
} }
} }
void IceTower::tick(std::uint64_t delta, World* world) { void IceTower::Tick(std::uint64_t delta, World* world) {
if (m_Timer.update(delta)) { if (m_Timer.Update(delta)) {
float damage = getStats()->getDamage(); float damage = GetStats()->GetDamage();
for (MobPtr mob : world->getMobList()) { for (MobPtr mob : world->GetMobList()) {
if (isMobInRange(mob)) { if (IsMobInRange(mob)) {
mob->addEffect(EffectType::Slowness, 1, this); // slowness for 1s every second mob->AddEffect(EffectType::Slowness, 1, this); // slowness for 1s every second
mob->damage(damage, this); if (damage > 0)
m_Timer.applyCooldown(); world->GetMobNotifier().NotifyListeners(&MobListener::OnMobDamage, mob.get(), damage, this);
m_Timer.ApplyCooldown();
} }
} }
} }
} }
void MageTower::tick(std::uint64_t delta, World* world) { void MageTower::Tick(std::uint64_t delta, World* world) {
if (m_Timer.update(delta)) { if (m_Timer.Update(delta)) {
for (MobPtr mob : world->getMobList()) { for (MobPtr mob : world->GetMobList()) {
if (isMobInRange(mob)) { if (IsMobInRange(mob)) {
mob->addEffect(EffectType::Fire, getLevel().getLevel() * 3, this); mob->AddEffect(EffectType::Fire, GetLevel().GetLevel() * 3, this);
m_Timer.applyCooldown(); m_Timer.ApplyCooldown();
} }
} }
} }
} }
void PoisonTower::tick(std::uint64_t delta, World* world) { void PoisonTower::Tick(std::uint64_t delta, World* world) {
if (m_Timer.update(delta)) { if (m_Timer.Update(delta)) {
for (MobPtr mob : world->getMobList()) { for (MobPtr mob : world->GetMobList()) {
if (isMobInRange(mob)) { if (IsMobInRange(mob)) {
if(getLevel().getPath() == TowerPath::Bottom){ if (GetLevel().GetPath() == TowerPath::Bottom) {
mob->damage(getStats()->getDamage(), this); world->GetMobNotifier().NotifyListeners(&MobListener::OnMobDamage, mob.get(), GetStats()->GetDamage(), this);
} else { } else {
float durationSec; float durationSec;
switch(getLevel().getLevel()){ switch (GetLevel().GetLevel()) {
case 1: case 1:
durationSec = 5; durationSec = 5;
break; break;
@@ -276,41 +277,41 @@ void PoisonTower::tick(std::uint64_t delta, World* world) {
durationSec = 0; // how did we get there ? durationSec = 0; // how did we get there ?
break; break;
} }
mob->addEffect(EffectType::Poison, durationSec, this); mob->AddEffect(EffectType::Poison, durationSec, this);
} }
m_Timer.applyCooldown(); m_Timer.ApplyCooldown();
} }
} }
} }
} }
void QuakeTower::tick(std::uint64_t delta, World* world) { void QuakeTower::Tick(std::uint64_t delta, World* world) {
} }
void ZeusTower::tick(std::uint64_t delta, World* world) { void ZeusTower::Tick(std::uint64_t delta, World* world) {
} }
void ArtilleryTower::tick(std::uint64_t delta, World* world) { void ArtilleryTower::Tick(std::uint64_t delta, World* world) {
} }
void SorcererTower::tick(std::uint64_t delta, World* world) { void SorcererTower::Tick(std::uint64_t delta, World* world) {
} }
void LeachTower::tick(std::uint64_t delta, World* world) { void LeachTower::Tick(std::uint64_t delta, World* world) {
} }
void TurretTower::tick(std::uint64_t delta, World* world) { void TurretTower::Tick(std::uint64_t delta, World* world) {
} }
void NecromancerTower::tick(std::uint64_t delta, World* world) { void NecromancerTower::Tick(std::uint64_t delta, World* world) {
} }

View File

@@ -3,25 +3,25 @@
#include "protocol/Protocol.h" #include "protocol/Protocol.h"
#include "game/BaseGame.h" #include "game/BaseGame.h"
#include "misc/Random.h" #include "misc/Random.h"
#include "misc/Compression.h"
#include "misc/Format.h"
#include <cmath> #include <cmath>
#include "misc/Compression.h"
#include <iostream>
namespace td { namespace td {
namespace game { namespace game {
World::World(Game* game) : m_Game(game) { World::World(Game* game) : m_Game(game) {
GetWorldNotifier().BindListener(this);
GetMobNotifier().BindListener(this);
} }
TilePtr World::getTile(std::int32_t x, std::int32_t y) const { TilePtr World::GetTile(std::int32_t x, std::int32_t y) const {
std::int16_t chunkX = x / Chunk::ChunkWidth; std::int16_t chunkX = x / Chunk::ChunkWidth;
std::int16_t chunkY = y / Chunk::ChunkHeight; std::int16_t chunkY = y / Chunk::ChunkHeight;
std::uint16_t subChunkX = x % Chunk::ChunkWidth; std::uint16_t subChunkX = std::abs(x % Chunk::ChunkWidth);
std::uint16_t subChunkY = y % Chunk::ChunkHeight; std::uint16_t subChunkY = std::abs(y % Chunk::ChunkHeight);
auto chunkIt = m_Chunks.find({ chunkX, chunkY }); auto chunkIt = m_Chunks.find({ chunkX, chunkY });
if (chunkIt == m_Chunks.end()) if (chunkIt == m_Chunks.end())
@@ -29,158 +29,131 @@ TilePtr World::getTile(std::int32_t x, std::int32_t y) const {
ChunkPtr chunk = chunkIt->second; ChunkPtr chunk = chunkIt->second;
return getTilePtr(chunk->getTileIndex(subChunkY * Chunk::ChunkWidth + subChunkX)); return GetTilePtr(chunk->GetTileIndex(subChunkY * Chunk::ChunkWidth + subChunkX));
} }
bool World::loadMap(const protocol::WorldBeginDataPacket* worldHeader) { bool World::LoadMap(const protocol::WorldBeginDataPacket* worldHeader) {
m_TowerPlacePalette = worldHeader->getTowerTilePalette(); m_TowerPlacePalette = worldHeader->GetTowerTilePalette();
m_WalkablePalette = worldHeader->getWalkableTileColor(); m_WalkablePalette = worldHeader->GetWalkableTileColor();
m_DecorationPalette = worldHeader->getDecorationPalette(); m_DecorationPalette = worldHeader->GetDecorationPalette();
m_Background = worldHeader->GetBackgroundColor();
getRedTeam().getSpawn() = worldHeader->getRedSpawn(); GetRedTeam().GetSpawn() = worldHeader->GetRedSpawn();
getBlueTeam().getSpawn() = worldHeader->getBlueSpawn(); GetBlueTeam().GetSpawn() = worldHeader->GetBlueSpawn();
m_SpawnColorPalette = worldHeader->getSpawnPalette(); m_SpawnColorPalette = worldHeader->GetSpawnPalette();
getRedTeam().getCastle() = worldHeader->getRedCastle(); GetRedTeam().GetCastle() = worldHeader->GetRedCastle();
getBlueTeam().getCastle() = worldHeader->getBlueCastle(); GetRedTeam().GetCastle().SetTeam(&GetRedTeam());
m_TilePalette = worldHeader->getTilePalette(); GetBlueTeam().GetCastle() = worldHeader->GetBlueCastle();
GetBlueTeam().GetCastle().SetTeam(&GetBlueTeam());
m_TilePalette = worldHeader->GetTilePalette();
return true; return true;
} }
bool World::loadMap(const protocol::WorldDataPacket* worldData) { bool World::LoadMap(const protocol::WorldDataPacket* worldData) {
m_Chunks = worldData->getChunks(); m_Chunks = worldData->GetChunks();
return true; return true;
} }
bool World::loadMapFromFile(const std::string& fileName) { bool World::LoadMapFromFile(const std::string& fileName) {
DataBuffer buffer; DataBuffer buffer;
if (!buffer.ReadFile(fileName)) { if (!buffer.ReadFile(fileName)) {
std::cerr << "Failed to load map from file " << fileName << " !\n"; utils::LOGE(utils::format("Failed to load map from file %s", fileName.c_str()));
return false; return false;
} }
std::cout << "Read file : " << fileName << " (File size : " << buffer.GetSize() << ")" << std::endl; utils::LOG(utils::format("Read file : %s (File size : %u)", fileName.c_str(), buffer.GetSize()));
DataBuffer mapHeaderPacketBuffer = utils::Decompress(buffer); DataBuffer mapHeaderPacketBuffer = utils::Decompress(buffer);
DataBuffer mapDataPacketBuffer = utils::Decompress(buffer); DataBuffer mapDataPacketBuffer = utils::Decompress(buffer);
protocol::PacketType packetType;
mapHeaderPacketBuffer >> packetType;
protocol::WorldBeginDataPacket headerPacket; protocol::WorldBeginDataPacket headerPacket;
headerPacket.Deserialize(mapHeaderPacketBuffer); headerPacket.Deserialize(mapHeaderPacketBuffer);
mapDataPacketBuffer >> packetType;
protocol::WorldDataPacket dataPacket; protocol::WorldDataPacket dataPacket;
dataPacket.Deserialize(mapDataPacketBuffer); dataPacket.Deserialize(mapDataPacketBuffer);
loadMap(&headerPacket); LoadMap(&headerPacket);
loadMap(&dataPacket); LoadMap(&dataPacket);
return true; return true;
} }
bool World::saveMap(const std::string& fileName) const { bool World::SaveMap(const std::string& fileName) const {
protocol::WorldBeginDataPacket headerPacket(this); protocol::WorldBeginDataPacket headerPacket(this);
protocol::WorldDataPacket dataPacket(this); protocol::WorldDataPacket dataPacket(this);
DataBuffer mapHeaderCompressed = utils::Compress(headerPacket.Serialize()); DataBuffer mapHeaderCompressed = utils::Compress(headerPacket.Serialize(false));
DataBuffer mapDataCompressed = utils::Compress(dataPacket.Serialize()); DataBuffer mapDataCompressed = utils::Compress(dataPacket.Serialize(false));
std::cout << "Header Packet Size : " << mapHeaderCompressed.GetSize() << std::endl; utils::LOG(utils::format("Header Packet Size : %u", mapHeaderCompressed.GetSize()));
std::cout << "World Data Packet Size : " << mapDataCompressed.GetSize() << std::endl; utils::LOG(utils::format("World Data Packet Size : %u", mapDataCompressed.GetSize()));
DataBuffer buffer = mapHeaderCompressed << mapDataCompressed; DataBuffer buffer = mapHeaderCompressed << mapDataCompressed;
std::cout << "Total Size : " << buffer.GetSize() << std::endl; utils::LOG(utils::format("Total Size : %u", buffer.GetSize()));
return buffer.WriteFile(fileName); return buffer.WriteFile(fileName);
} }
void World::tick(std::uint64_t delta) { void World::Tick(std::uint64_t delta) {
moveMobs(delta); if (m_Game->GetGameState() != GameState::Game) return;
tickMobs(delta);
TickMobs(delta);
for (TowerPtr tower : m_Towers) { for (TowerPtr tower : m_Towers) {
tower->tick(delta, this); tower->Tick(delta, this);
} }
cleanDeadMobs(); CleanDeadMobs();
} }
void World::spawnMobAt(MobID id, MobType type, std::uint8_t level, PlayerID sender, float x, float y, Direction dir) { void World::SpawnMobAt(MobID id, MobType type, std::uint8_t level, PlayerID sender, float x, float y, Direction dir) {
MobPtr mob = MobFactory::createMob(id, type, level, sender); MobPtr mob = MobFactory::CreateMob(id, type, level, sender);
mob->setX(x); mob->SetCenter({ x, y });
mob->setY(y); mob->SetDirection(dir);
mob->setDirection(dir);
m_Mobs.push_back(mob); m_Mobs.push_back(mob);
GetMobNotifier().NotifyListeners(&MobListener::OnMobSpawn, mob.get());
} }
TowerPtr World::placeTowerAt(TowerID id, TowerType type, std::int32_t x, std::int32_t y, PlayerID builder) { TowerPtr World::PlaceTowerAt(TowerID id, TowerType type, std::int32_t x, std::int32_t y, PlayerID builder) {
TowerPtr tower = TowerFactory::createTower(type, id, x, y, builder); TowerPtr tower = TowerFactory::CreateTower(type, id, x, y, builder);
m_Towers.push_back(tower); m_Towers.push_back(tower);
return tower; return tower;
} }
void World::tickMobs(std::uint64_t delta) { TowerPtr World::RemoveTower(TowerID towerId) {
auto it = std::find_if(m_Towers.begin(), m_Towers.end(), [towerId](TowerPtr tower) { return tower->GetID() == towerId;});
if (it == m_Towers.end()) return nullptr;
TowerPtr tower = *it;
m_Towers.erase(it);
return tower;
}
void World::TickMobs(std::uint64_t delta) {
for (MobPtr mob : m_Mobs) { for (MobPtr mob : m_Mobs) {
mob->tick(delta); mob->Tick(delta, this);
} }
} }
void World::moveMobs(std::uint64_t delta) { const Color* World::GetTileColor(TilePtr tile) const {
for (MobPtr mob : m_Mobs) { switch (tile->GetType()) {
TilePtr tile = getTile(mob->getX(), mob->getY());
if (tile != nullptr && tile->getType() == TileType::Walk) {
WalkableTile* walkTile = dynamic_cast<WalkableTile*>(tile.get());
mob->setDirection(walkTile->direction);
}
float mobWalkSpeed = mob->getStats()->getMovementSpeed();
float walkAmount = mobWalkSpeed * ((float)delta / 1000.0f);
if (mob->hasEffect(EffectType::Slowness))
walkAmount *= 0.70;
switch (mob->getDirection()) {
case Direction::NegativeX: {
mob->setX(mob->getX() - walkAmount);
break;
}
case Direction::PositiveX: {
mob->setX(mob->getX() + walkAmount);
break;
}
case Direction::NegativeY: {
mob->setY(mob->getY() - walkAmount);
break;
}
case Direction::PositiveY: {
mob->setY(mob->getY() + walkAmount);
break;
}
}
}
}
const Color* World::getTileColor(TilePtr tile) const {
switch (tile->getType()) {
case TileType::Tower: { case TileType::Tower: {
TowerTile* towerTile = (TowerTile*)tile.get(); TowerTile* towerTile = dynamic_cast<TowerTile*>(tile.get());
return &m_TowerPlacePalette[towerTile->color_palette_ref]; return &m_TowerPlacePalette[towerTile->color_palette_ref];
} }
case TileType::Walk: { case TileType::Walk: {
return &m_WalkablePalette; return &m_WalkablePalette;
} }
case TileType::Decoration: { case TileType::Decoration: {
DecorationTile* towerTile = (DecorationTile*)tile.get(); DecorationTile* towerTile = dynamic_cast<DecorationTile*>(tile.get());
return &m_DecorationPalette[towerTile->color_palette_ref]; return &m_DecorationPalette[towerTile->color_palette_ref];
break; break;
} }
case TileType::None: { default: {
return nullptr; return nullptr;
} }
} }
@@ -188,21 +161,21 @@ const Color* World::getTileColor(TilePtr tile) const {
} }
bool World::CanPlaceLittleTower(const glm::vec2& worldPos, PlayerID playerID) const { bool World::CanPlaceLittleTower(const glm::vec2& worldPos, PlayerID playerID) const {
TilePtr tile = getTile(worldPos.x, worldPos.y); TilePtr tile = GetTile(worldPos.x, worldPos.y);
const Player& player = m_Game->getPlayers()[playerID]; const Player& player = m_Game->GetPlayers()[playerID];
if (tile == nullptr) { if (tile == nullptr) {
return false; return false;
} }
if (tile->getType() == game::TileType::Tower) { if (tile->GetType() == game::TileType::Tower) {
const TowerTile* towerTile = (const TowerTile*)tile.get(); const TowerTile* towerTile = dynamic_cast<TowerTile*>(tile.get());
if (towerTile->team_owner != player.getTeamColor()) if (towerTile->team_owner != player.GetTeamColor())
return false; return false;
for (int x = -1; x < 2; x++) { for (int x = -1; x < 2; x++) {
for (int y = -1; y < 2; y++) { for (int y = -1; y < 2; y++) {
game::TilePtr adjacentTile = getTile(worldPos.x + x, worldPos.y + y); game::TilePtr adjacentTile = GetTile(worldPos.x + x, worldPos.y + y);
if (adjacentTile == nullptr || adjacentTile->getType() != game::TileType::Tower || getTower({ worldPos.x + x, worldPos.y + y }) != nullptr) { if (adjacentTile == nullptr || adjacentTile->GetType() != game::TileType::Tower || GetTower({ worldPos.x + x, worldPos.y + y }) != nullptr) {
return false; return false;
} }
} }
@@ -216,21 +189,21 @@ bool World::CanPlaceLittleTower(const glm::vec2& worldPos, PlayerID playerID) co
bool World::CanPlaceBigTower(const glm::vec2& worldPos, PlayerID playerID) const { bool World::CanPlaceBigTower(const glm::vec2& worldPos, PlayerID playerID) const {
if (!CanPlaceLittleTower(worldPos, playerID)) return false; if (!CanPlaceLittleTower(worldPos, playerID)) return false;
TilePtr tile = getTile(worldPos.x, worldPos.y); TilePtr tile = GetTile(worldPos.x, worldPos.y);
const Player& player = m_Game->getPlayers()[playerID]; const Player& player = m_Game->GetPlayers()[playerID];
if (tile == nullptr) { if (tile == nullptr) {
return false; return false;
} }
if (tile->getType() == game::TileType::Tower) { if (tile->GetType() == game::TileType::Tower) {
const TowerTile* towerTile = (const TowerTile*)tile.get(); const TowerTile* towerTile = dynamic_cast<const TowerTile*>(tile.get());
if (towerTile->team_owner != player.getTeamColor()) if (towerTile->team_owner != player.GetTeamColor())
return false; return false;
for (int x = -2; x < 3; x++) { for (int x = -2; x < 3; x++) {
for (int y = -2; y < 3; y++) { for (int y = -2; y < 3; y++) {
game::TilePtr adjacentTile = getTile(worldPos.x + x, worldPos.y + y); game::TilePtr adjacentTile = GetTile(worldPos.x + x, worldPos.y + y);
if (adjacentTile == nullptr || adjacentTile->getType() != game::TileType::Tower || getTower({ worldPos.x + x, worldPos.y + y }) != nullptr) { if (adjacentTile == nullptr || adjacentTile->GetType() != game::TileType::Tower || GetTower({ worldPos.x + x, worldPos.y + y }) != nullptr) {
return false; return false;
} }
} }
@@ -241,34 +214,26 @@ bool World::CanPlaceBigTower(const glm::vec2& worldPos, PlayerID playerID) const
return false; return false;
} }
void World::cleanDeadMobs() { void World::CleanDeadMobs() {
// safely remove mobs when unused
for (std::size_t i = 0; i < m_Mobs.size(); i++) { for (std::size_t i = 0; i < m_Mobs.size(); i++) {
MobPtr mob = m_Mobs[i]; MobPtr mob = m_Mobs[i];
if (mob->isDead()) { if (mob->IsDead()) {
mob->OnDeath(this); m_Mobs.erase(m_Mobs.begin() + static_cast<int>(i));
//reward players
Player& sender = m_Game->getPlayerById(mob->getSender());
sender.addExp(mob->getStats()->getExpReward());
Player& killer = m_Game->getPlayerById(mob->getLastDamageTower()->getBuilder());
killer.addGold(mob->getStats()->getMoneyCost());
m_Mobs.erase(m_Mobs.begin() + i);
} }
} }
} }
TowerPtr World::getTower(const glm::vec2& position) const { TowerPtr World::GetTower(const glm::vec2& position) const {
for (TowerPtr tower : m_Towers) { for (TowerPtr tower : m_Towers) {
if (tower->getSize() == TowerSize::Big) { if (tower->GetSize() == TowerSize::Big) {
if (tower->getX() - 2 <= static_cast<std::int32_t>(position.x) && tower->getX() + 2 >= static_cast<std::int32_t>(position.x) && if (tower->GetCenterX() - 2.5f < position.x && tower->GetCenterX() + 2.5f > position.x &&
tower->getY() - 2 <= static_cast<std::int32_t>(position.y) && tower->getY() + 2 >= static_cast<std::int32_t>(position.y)) { tower->GetCenterY() - 2.5f < position.y && tower->GetCenterY() + 2.5f > position.y) {
return tower; return tower;
} }
} else { } else { // little tower
if (tower->getX() - 1 <= static_cast<std::int32_t>(position.x) && tower->getX() + 1 >= static_cast<std::int32_t>(position.x) && if (tower->GetCenterX() - 1.5f < position.x && tower->GetCenterX() + 1.5f > position.x &&
tower->getY() - 1 <= static_cast<std::int32_t>(position.y) && tower->getY() + 1 >= static_cast<std::int32_t>(position.y)) { tower->GetCenterY() - 1.5f < position.y && tower->GetCenterY() + 1.5f > position.y) {
return tower; return tower;
} }
} }
@@ -276,43 +241,83 @@ TowerPtr World::getTower(const glm::vec2& position) const {
return nullptr; return nullptr;
} }
TowerPtr World::getTowerById(TowerID towerID) { TowerPtr World::GetTowerById(TowerID towerID) {
auto it = std::find_if(m_Towers.begin(), m_Towers.end(), [towerID](TowerPtr tower) { return tower->getID() == towerID;}); auto it = std::find_if(m_Towers.begin(), m_Towers.end(), [towerID](TowerPtr tower) { return tower->GetID() == towerID;});
if (it == m_Towers.end()) return nullptr; if (it == m_Towers.end()) return nullptr;
return *it; return *it;
} }
void World::OnArrowShot(MobPtr target, Tower* shooter) { void World::OnArcherTowerShot(MobPtr tarGet, ArcherTower* shooter) {
bool explosiveArrows = shooter->getLevel().getPath() == TowerPath::Bottom; bool fireArrows = shooter->GetLevel().GetPath() == TowerPath::Bottom;
bool explosiveArrows = shooter->GetLevel().GetLevel() == 4 && fireArrows;
GetWorldNotifier().NotifyListeners(&WorldListener::OnArrowShot, tarGet, fireArrows, shooter);
if (explosiveArrows) { if (explosiveArrows) {
// aoe damage GetWorldNotifier().NotifyListeners(&WorldListener::OnExplosion, utils::shape::Circle{ tarGet->GetCenterX(), tarGet->GetCenterY(), ArcherTower::ExplosionRadius }, shooter->GetStats()->GetDamage(), shooter);
} else {
target->damage(shooter->getStats()->getDamage(), shooter);
} }
} }
Team& World::getRedTeam() { void World::OnArrowShot(MobPtr tarGet, bool fireArrow, Tower* shooter) {
return m_Game->getRedTeam(); GetMobNotifier().NotifyListeners(&MobListener::OnMobDamage, tarGet.get(), shooter->GetStats()->GetDamage(), shooter);
if (fireArrow) {
tarGet->AddEffect(EffectType::Fire, ArcherTower::FireDurationSec, shooter);
}
} }
const Team& World::getRedTeam() const { void World::OnExplosion(utils::shape::Circle explosion, float centerDamage, Tower* shooter) {
return m_Game->getRedTeam(); for (MobPtr mob : m_Mobs) {
if (mob->IsAlive() && mob->CollidesWith(explosion)) {
// linear distance damage reduction
float explosionDamage = mob->Distance(explosion) / explosion.GetRadius() * centerDamage;
GetMobNotifier().NotifyListeners(&MobListener::OnMobDamage, mob.get(), explosionDamage, shooter);
}
}
} }
Team& World::getBlueTeam() { void World::OnMobCastleDamage(Mob* damager, TeamCastle* enemyCastle, float damage) {
return m_Game->getBlueTeam(); enemyCastle->Damage(damage);
if (enemyCastle->GetLife() <= 0) {
m_Game->NotifyListeners(&GameListener::OnGameEnd);
}
} }
const Team& World::getBlueTeam() const { void World::OnMobDamage(Mob* tarGet, float damage, Tower* source) {
return m_Game->getBlueTeam(); tarGet->Damage(damage, source);
if (tarGet->IsDead()) {
GetMobNotifier().NotifyListeners(&MobListener::OnMobDie, tarGet);
}
} }
Team& World::getTeam(TeamColor team) { Team& World::GetRedTeam() {
return m_Game->getTeam(team); return m_Game->GetRedTeam();
} }
const Team& World::getTeam(TeamColor team) const { const Team& World::GetRedTeam() const {
return m_Game->getTeam(team); return m_Game->GetRedTeam();
}
Team& World::GetBlueTeam() {
return m_Game->GetBlueTeam();
}
const Team& World::GetBlueTeam() const {
return m_Game->GetBlueTeam();
}
Team& World::GetTeam(TeamColor team) {
return m_Game->GetTeam(team);
}
const Team& World::GetTeam(TeamColor team) const {
return m_Game->GetTeam(team);
}
const Player* World::GetPlayerById(PlayerID id) const {
return m_Game->GetPlayerById(id);
}
const TeamList& World::GetTeams() const {
return m_Game->GetTeams();
} }
} // namespace game } // namespace game

View File

@@ -1,67 +1,77 @@
#include "game/client/Client.h" #include "game/client/Client.h"
#include "misc/Format.h"
#include <iostream>
namespace td { namespace td {
namespace client { namespace client {
bool Client::connect(const network::IPAddresses& addresses, std::uint16_t port) { bool Client::Connect(const network::IPAddresses& addresses, std::uint16_t port) {
for (const network::IPAddress& address : addresses) { for (const network::IPAddress& address : addresses) {
if (address.IsValid() && m_Connexion.connect(address.ToString(), port)) { if (address.IsValid() && m_Connexion.Connect(address.ToString(), port)) {
m_Connected = true; m_Connected = true;
return true; return true;
} }
} }
std::cout << "Failed to connect !\n"; utils::LOGE("Failed to connect !");
return false; return false;
} }
void Client::selectTeam(game::TeamColor team) { void Client::SelectTeam(game::TeamColor team) {
if (!m_Connected) if (!m_Connected)
return; return;
protocol::SelectTeamPacket packet(team); protocol::SelectTeamPacket packet(team);
m_Connexion.sendPacket(&packet); m_Connexion.SendPacket(&packet);
} }
void Client::closeConnection() { void Client::CloseConnection() {
if (!m_Connected) if (!m_Connected)
return; return;
m_Connected = false; m_Connected = false;
protocol::DisconnectPacket packet; protocol::DisconnectPacket packet;
m_Connexion.sendPacket(&packet); m_Connexion.SendPacket(&packet);
} }
void Client::tick(std::uint64_t delta) { void Client::Tick(std::uint64_t delta) {
if (!m_Connected) if (!m_Connected)
return; return;
m_Connected = m_Connexion.updateSocket(); m_Connected = m_Connexion.UpdateSocket();
if (!m_Connected) { if (!m_Connected) {
std::cout << "Disconnected ! (Reason : " << m_Connexion.getDisconnectReason() << ")\n"; utils::LOG(utils::format("Disconnected ! (Reason : %s)", m_Connexion.GetDisconnectReason().c_str()));
Reset();
} else { } else {
m_Game.tick(delta); m_Game->Tick(delta);
} }
} }
void Client::render() { void Client::Render() {
m_Game.renderWorld(); m_Game->RenderWorld();
} }
void Client::sendMobs(const std::vector<protocol::MobSend>& mobSends){ void Client::Reset() {
m_Game.reset(0);
m_Game = std::make_unique<ClientGame>(this);
}
void Client::SendMobs(const std::vector<protocol::MobSend>& mobSends) {
protocol::SendMobsPacket packet(mobSends); protocol::SendMobsPacket packet(mobSends);
m_Connexion.sendPacket(&packet); m_Connexion.SendPacket(&packet);
} }
void Client::placeTower(game::TowerType type, const glm::vec2& position) { void Client::PlaceTower(game::TowerType type, const glm::vec2& position) {
protocol::PlaceTowerPacket packet(position.x, position.y, type); protocol::PlaceTowerPacket packet(position.x, position.y, type);
m_Connexion.sendPacket(&packet); m_Connexion.SendPacket(&packet);
} }
void Client::upgradeTower(game::TowerID tower, game::TowerLevel level){ void Client::UpgradeTower(game::TowerID tower, game::TowerLevel level) {
protocol::UpgradeTowerPacket packet(tower, level); protocol::UpgradeTowerPacket packet(tower, level);
m_Connexion.sendPacket(&packet); m_Connexion.SendPacket(&packet);
}
void Client::RemoveTower(game::TowerID tower) {
protocol::RemoveTowerPacket packet(tower);
m_Connexion.SendPacket(&packet);
} }
} // namespace client } // namespace client

View File

@@ -4,11 +4,11 @@
namespace td { namespace td {
namespace client { namespace client {
ClientConnexion::ClientConnexion() : Connexion(&m_Dispatcher) { ClientConnexion::ClientConnexion() : Connexion(&m_Dispatcher), m_ServerTPS(0) {
registerHandlers(); RegisterHandlers();
} }
void ClientConnexion::registerHandlers() { void ClientConnexion::RegisterHandlers() {
GetDispatcher()->RegisterHandler(protocol::PacketType::KeepAlive, this); GetDispatcher()->RegisterHandler(protocol::PacketType::KeepAlive, this);
GetDispatcher()->RegisterHandler(protocol::PacketType::ConnectionInfo, this); GetDispatcher()->RegisterHandler(protocol::PacketType::ConnectionInfo, this);
GetDispatcher()->RegisterHandler(protocol::PacketType::Disconnect, this); GetDispatcher()->RegisterHandler(protocol::PacketType::Disconnect, this);
@@ -16,32 +16,32 @@ void ClientConnexion::registerHandlers() {
} }
void ClientConnexion::HandlePacket(const protocol::KeepAlivePacket* packet) { void ClientConnexion::HandlePacket(const protocol::KeepAlivePacket* packet) {
protocol::KeepAlivePacket keepAlivePacket(packet->getAliveID()); protocol::KeepAlivePacket keepAlivePacket(packet->GetAliveID());
sendPacket(&keepAlivePacket); SendPacket(&keepAlivePacket);
} }
void ClientConnexion::HandlePacket(const protocol::ConnexionInfoPacket* packet) { void ClientConnexion::HandlePacket(const protocol::ConnexionInfoPacket* packet) {
m_ConnectionID = packet->getConnectionID(); m_ConnectionID = packet->GetConnectionID();
login(); Login();
} }
void ClientConnexion::HandlePacket(const protocol::ServerTpsPacket* packet) { void ClientConnexion::HandlePacket(const protocol::ServerTpsPacket* packet) {
m_ServerTPS = packet->getTPS(); m_ServerTPS = packet->GetTPS();
m_Ping = utils::getTime() - packet->getPacketSendTime(); m_Ping = utils::GetTime() - packet->GetPacketSendTime();
} }
void ClientConnexion::login() { void ClientConnexion::Login() {
td::protocol::PlayerLoginPacket loginPacket("Persson" + std::to_string(m_ConnectionID)); td::protocol::PlayerLoginPacket loginPacket("Persson" + std::to_string(m_ConnectionID));
sendPacket(&loginPacket); SendPacket(&loginPacket);
} }
bool ClientConnexion::updateSocket() { bool ClientConnexion::UpdateSocket() {
return Connexion::updateSocket(); return Connexion::UpdateSocket();
} }
void ClientConnexion::HandlePacket(const protocol::DisconnectPacket* packet) { void ClientConnexion::HandlePacket(const protocol::DisconnectPacket* packet) {
m_DisconnectReason = packet->getReason(); m_DisconnectReason = packet->GetReason();
closeConnection(); CloseConnection();
} }
} // namespace client } // namespace client

View File

@@ -1,15 +1,12 @@
#include "game/client/ClientGame.h" #include "game/client/ClientGame.h"
#include "protocol/PacketDispatcher.h" #include "protocol/PacketDispatcher.h"
//#include "game/Team.h"
#include "game/client/Client.h" #include "game/client/Client.h"
#include <iostream>
namespace td { namespace td {
namespace client { namespace client {
ClientGame::ClientGame(Client* client) : protocol::PacketHandler(client->getConnexion().GetDispatcher()), ClientGame::ClientGame(Client* client) : protocol::PacketHandler(client->GetConnexion().GetDispatcher()),
game::Game(&m_WorldClient), m_Client(client), m_Renderer(client->getRenderer()), m_WorldClient(this), game::Game(&m_WorldClient), m_Client(client), m_Renderer(client->GetRenderer()), m_WorldClient(this),
m_WorldRenderer(&m_WorldClient, this) { m_WorldRenderer(&m_WorldClient, this) {
GetDispatcher()->RegisterHandler(protocol::PacketType::ConnectionInfo, this); GetDispatcher()->RegisterHandler(protocol::PacketType::ConnectionInfo, this);
GetDispatcher()->RegisterHandler(protocol::PacketType::PlayerJoin, this); GetDispatcher()->RegisterHandler(protocol::PacketType::PlayerJoin, this);
@@ -19,102 +16,103 @@ m_WorldRenderer(&m_WorldClient, this) {
GetDispatcher()->RegisterHandler(protocol::PacketType::UpdateLobbyTime, this); GetDispatcher()->RegisterHandler(protocol::PacketType::UpdateLobbyTime, this);
GetDispatcher()->RegisterHandler(protocol::PacketType::UpdateGameState, this); GetDispatcher()->RegisterHandler(protocol::PacketType::UpdateGameState, this);
GetDispatcher()->RegisterHandler(protocol::PacketType::UpdateMoney, this); GetDispatcher()->RegisterHandler(protocol::PacketType::UpdateMoney, this);
GetDispatcher()->RegisterHandler(protocol::PacketType::UpdateEXP, this);
GetDispatcher()->RegisterHandler(protocol::PacketType::Disconnect, this); GetDispatcher()->RegisterHandler(protocol::PacketType::Disconnect, this);
GetDispatcher()->RegisterHandler(protocol::PacketType::WorldData, this); GetDispatcher()->RegisterHandler(protocol::PacketType::WorldData, this);
GetDispatcher()->RegisterHandler(protocol::PacketType::WorldAddTower, this);
} }
ClientGame::~ClientGame() { ClientGame::~ClientGame() {
GetDispatcher()->UnregisterHandler(this); GetDispatcher()->UnregisterHandler(this);
} }
void ClientGame::tick(std::uint64_t delta) { void ClientGame::Tick(std::uint64_t delta) {
game::Game::tick(delta); game::Game::Tick(delta);
m_WorldRenderer.update(); m_WorldRenderer.Update();
if (m_GameState == game::GameState::Lobby && m_LobbyTime > 0) { if (m_GameState == game::GameState::Lobby && m_LobbyTime > 0) {
m_LobbyTime -= delta; m_LobbyTime -= delta;
} }
} }
void ClientGame::HandlePacket(const protocol::PlayerJoinPacket* packet) { void ClientGame::HandlePacket(const protocol::PlayerJoinPacket* packet) {
game::Player player(packet->getPlayerID()); game::Player player(packet->GetPlayerID());
player.setName(packet->getPlayerName()); player.SetName(packet->GetPlayerName());
m_Players.insert({ player.getID(), player }); m_Players.insert({ player.GetID(), player });
} }
void ClientGame::HandlePacket(const protocol::PlayerLeavePacket* packet) { void ClientGame::HandlePacket(const protocol::PlayerLeavePacket* packet) {
game::Player* player = &m_Players[packet->getPlayerID()]; game::Player* player = &m_Players[packet->GetPlayerID()];
if (player->getTeamColor() != game::TeamColor::None) { if (player->GetTeamColor() != game::TeamColor::None) {
m_Teams[(std::size_t)player->getTeamColor()].removePlayer(player); m_Teams[(std::size_t)player->GetTeamColor()].RemovePlayer(player);
} }
m_Players.erase(player->getID()); m_Players.erase(player->GetID());
} }
void ClientGame::HandlePacket(const protocol::PlayerListPacket* packet) { void ClientGame::HandlePacket(const protocol::PlayerListPacket* packet) {
for (auto pair : packet->getPlayers()) { for (auto pair : packet->GetPlayers()) {
std::uint8_t playerID = pair.first; std::uint8_t playerID = pair.first;
protocol::PlayerInfo playerInfo = pair.second; protocol::PlayerInfo playerInfo = pair.second;
game::Player player(playerID); game::Player player(playerID);
player.setName(playerInfo.name); player.SetName(playerInfo.name);
player.setTeamColor(playerInfo.team); player.SetTeamColor(playerInfo.team);
m_Players.insert({ playerID, player }); m_Players.insert({ playerID, player });
if (player.getTeamColor() != game::TeamColor::None) { if (player.GetTeamColor() != game::TeamColor::None) {
m_Teams[(std::size_t)player.getTeamColor()].addPlayer(&m_Players[playerID]); m_Teams[(std::size_t)player.GetTeamColor()].AddPlayer(&m_Players[playerID]);
} }
} }
m_Player = &m_Players[m_ConnexionID]; m_Player = &m_Players[m_ConnexionID];
} }
void ClientGame::HandlePacket(const protocol::UpdatePlayerTeamPacket* packet) { void ClientGame::HandlePacket(const protocol::UpdatePlayerTeamPacket* packet) {
game::Player* player = &m_Players[packet->getPlayerID()]; game::Player* player = &m_Players[packet->GetPlayerID()];
if (player->getTeamColor() == game::TeamColor::None) { //join a team if (player->GetTeamColor() == game::TeamColor::None) { //join a team
getTeam(packet->getSelectedTeam()).addPlayer(player); GetTeam(packet->GetSelectedTeam()).AddPlayer(player);
} else if (packet->getSelectedTeam() == game::TeamColor::None) { // leave a team } else if (packet->GetSelectedTeam() == game::TeamColor::None) { // leave a team
getTeam(player->getTeamColor()).removePlayer(player); GetTeam(player->GetTeamColor()).RemovePlayer(player);
} else { // change team } else { // change team
getTeam(player->getTeamColor()).removePlayer(player); GetTeam(player->GetTeamColor()).RemovePlayer(player);
getTeam(packet->getSelectedTeam()).addPlayer(player); GetTeam(packet->GetSelectedTeam()).AddPlayer(player);
} }
player->setTeamColor(packet->getSelectedTeam()); player->SetTeamColor(packet->GetSelectedTeam());
} }
void ClientGame::HandlePacket(const protocol::UpdateGameStatePacket* packet) { void ClientGame::HandlePacket(const protocol::UpdateGameStatePacket* packet) {
setGameState(packet->getGameState()); SetGameState(packet->GetGameState());
} }
void ClientGame::HandlePacket(const protocol::ConnexionInfoPacket* packet) { void ClientGame::HandlePacket(const protocol::ConnexionInfoPacket* packet) {
m_ConnexionID = packet->getConnectionID(); m_ConnexionID = packet->GetConnectionID();
} }
void ClientGame::HandlePacket(const protocol::UpdateLobbyTimePacket* packet) { void ClientGame::HandlePacket(const protocol::UpdateLobbyTimePacket* packet) {
m_LobbyTime = packet->getRemainingTime(); m_LobbyTime = packet->GetRemainingTime();
} }
void ClientGame::HandlePacket(const protocol::UpdateMoneyPacket* packet) { void ClientGame::HandlePacket(const protocol::UpdateMoneyPacket* packet) {
m_Player->setGold(packet->getGold()); m_Player->SetGold(packet->GetGold());
}
void ClientGame::HandlePacket(const protocol::UpdateExpPacket* packet) {
m_Player->SetExp(packet->GetExp());
} }
void ClientGame::HandlePacket(const protocol::DisconnectPacket* packet) { void ClientGame::HandlePacket(const protocol::DisconnectPacket* packet) {
m_GameState = game::GameState::Disconnected; m_GameState = game::GameState::Disconnected;
m_Renderer->SetBackgroundColor({ 0, 0, 0 });
} }
void ClientGame::HandlePacket(const protocol::WorldDataPacket* packet) { void ClientGame::HandlePacket(const protocol::WorldDataPacket* packet) {
m_WorldRenderer.loadModels(); m_WorldRenderer.LoadModels();
// set cam pos to player spawn // set cam pos to player spawn
const game::Spawn& spawn = m_World->getTeam(m_Player->getTeamColor()).getSpawn(); const game::Spawn& spawn = m_World->GetTeam(m_Player->GetTeamColor()).GetSpawn();
m_WorldRenderer.setCamPos(spawn.x + 0.5, spawn.y + 0.5); m_WorldRenderer.SetCamPos(spawn.GetCenterX(), spawn.GetCenterY());
} }
void ClientGame::renderWorld() { void ClientGame::RenderWorld() {
if (m_GameState == game::GameState::Game || m_GameState == game::GameState::EndGame) { if (m_GameState == game::GameState::Game || m_GameState == game::GameState::EndGame) {
m_WorldRenderer.render(); m_WorldRenderer.Render();
} }
} }
void ClientGame::HandlePacket(const protocol::WorldAddTowerPacket* packet) {
m_WorldRenderer.addTower(m_WorldClient.placeTowerAt(packet->getTowerID(), packet->getTowerType(), packet->getTowerX(), packet->getTowerY(), packet->getBuilder()));
}
} // namespace client } // namespace client
} // namespace td } // namespace td

View File

@@ -7,33 +7,69 @@ namespace td {
namespace client { namespace client {
WorldClient::WorldClient(ClientGame* game) : game::World(game), protocol::PacketHandler(game->GetDispatcher()), m_Game(game) { WorldClient::WorldClient(ClientGame* game) : game::World(game), protocol::PacketHandler(game->GetDispatcher()), m_Game(game) {
GetDispatcher()->RegisterHandler(protocol::PacketType::WorldAddTower, this);
GetDispatcher()->RegisterHandler(protocol::PacketType::WorldBeginData, this); GetDispatcher()->RegisterHandler(protocol::PacketType::WorldBeginData, this);
GetDispatcher()->RegisterHandler(protocol::PacketType::WorldData, this); GetDispatcher()->RegisterHandler(protocol::PacketType::WorldData, this);
GetDispatcher()->RegisterHandler(protocol::PacketType::SpawnMob, this); GetDispatcher()->RegisterHandler(protocol::PacketType::SpawnMob, this);
GetDispatcher()->RegisterHandler(protocol::PacketType::UpgradeTower, this); GetDispatcher()->RegisterHandler(protocol::PacketType::UpgradeTower, this);
GetDispatcher()->RegisterHandler(protocol::PacketType::RemoveTower, this);
GetDispatcher()->RegisterHandler(protocol::PacketType::UpdateCastleLife, this);
GetDispatcher()->RegisterHandler(protocol::PacketType::UpdateMobStates, this);
} }
void WorldClient::HandlePacket(const protocol::WorldBeginDataPacket* packet) { void WorldClient::HandlePacket(const protocol::WorldBeginDataPacket* packet) {
loadMap(packet); LoadMap(packet);
if (m_Game->GetGameState() == game::GameState::Game) {
const game::Color& backgroundColor = GetBackgroundColor();
m_Game->GetRenderer()->SetBackgroundColor({ static_cast<float>(backgroundColor.r / 255.0f), static_cast<float>(backgroundColor.g / 255.0f),
static_cast<float>(backgroundColor.b / 255.0f) });
}
} }
void WorldClient::HandlePacket(const protocol::WorldDataPacket* packet) { void WorldClient::HandlePacket(const protocol::WorldDataPacket* packet) {
loadMap(packet); LoadMap(packet);
} }
void WorldClient::HandlePacket(const protocol::SpawnMobPacket* packet) { void WorldClient::HandlePacket(const protocol::SpawnMobPacket* packet) {
spawnMobAt(packet->getMobID(), packet->getMobType(), packet->getMobLevel(), packet->getSender(), SpawnMobAt(packet->GetMobID(), packet->GetMobType(), packet->GetMobLevel(), packet->GetSender(),
packet->getMobX(), packet->getMobY(), packet->getMobDirection()); packet->GetMobX(), packet->GetMobY(), packet->GetMobDirection());
} }
void WorldClient::HandlePacket(const protocol::UpgradeTowerPacket* packet) { void WorldClient::HandlePacket(const protocol::UpgradeTowerPacket* packet) {
game::TowerPtr tower = getTowerById(packet->getTowerID()); game::TowerPtr tower = GetTowerById(packet->GetTowerID());
if (tower == nullptr) return; // this should not happen but who knows ? if (tower == nullptr) return; // this should not happen but who knows ?
tower->upgrade(packet->getTowerLevel().getLevel(), packet->getTowerLevel().getPath()); tower->Upgrade(packet->GetTowerLevel().GetLevel(), packet->GetTowerLevel().GetPath());
} }
void WorldClient::OnArrowShot(game::MobPtr target, game::Tower* tower) { void WorldClient::HandlePacket(const protocol::WorldAddTowerPacket* packet) {
World::OnArrowShot(target, tower); game::TowerPtr newTower = PlaceTowerAt(packet->GetTowerID(), packet->GetTowerType(), packet->GetTowerX(), packet->GetTowerY(), packet->GetBuilder());
GetWorldNotifier().NotifyListeners(&WorldListener::OnTowerAdd, newTower);
}
void WorldClient::HandlePacket(const protocol::RemoveTowerPacket* packet) {
game::TowerPtr tower = RemoveTower(packet->GetTowerID());
if (tower != nullptr) {
GetWorldNotifier().NotifyListeners(&WorldListener::OnTowerRemove, tower);
}
}
void WorldClient::HandlePacket(const protocol::UpdateMobStatesPacket* packet) {
for (auto mobState : packet->GetMobStates()) {
game::MobID mobId = mobState.GetMobId();
auto it = std::find_if(GetMobList().begin(), GetMobList().end(), [mobId](game::MobPtr mob) { return mob->GetMobID() == mobId; });
if (it != GetMobList().end()) {
game::MobPtr& mob = *it;
mob->SetCenter(mobState.GetMobPosition());
mob->SetDirection(mobState.GetMobDirection());
mob->SetHealth(mobState.GetMobLife());
}
}
}
void WorldClient::HandlePacket(const protocol::UpdateCastleLifePacket* packet) {
GetTeam(packet->GetTeamColor()).GetCastle().SetLife(packet->GetCastleLife());
} }
} // namespace client } // namespace client

View File

@@ -3,8 +3,6 @@
#include "misc/Time.h" #include "misc/Time.h"
#include <iostream>
#ifdef NDEBUG #ifdef NDEBUG
#define MIN_PLAYER_WAITING 2 #define MIN_PLAYER_WAITING 2
#else #else
@@ -28,53 +26,53 @@ namespace server {
1, // 1 s 1, // 1 s
};*/ };*/
Lobby::Lobby(Server* server) : m_Server(server), m_Timer(1000, std::bind(&Lobby::sendTimeRemaining, this)) { Lobby::Lobby(Server* server) : m_Server(server), m_Timer(1000, std::bind(&Lobby::SendTimeRemaining, this)) {
} }
void Lobby::tick() { void Lobby::Tick() {
if (m_GameStarted || m_StartTimerTime == 0) if (m_GameStarted || m_StartTimerTime == 0)
return; return;
if (utils::getTime() - m_StartTimerTime >= LobbyWaitingTime) { if (utils::GetTime() - m_StartTimerTime >= LobbyWaitingTime) {
protocol::UpdateGameStatePacket packet(game::GameState::Game); m_Server->GetGame().NotifyListeners(&game::GameListener::OnGameBegin);
m_Server->broadcastPacket(&packet);
m_GameStarted = true; m_GameStarted = true;
m_Server->lauchGame();
return; return;
} }
m_Timer.update(); m_Timer.Update();
} }
void Lobby::sendTimeRemaining() { void Lobby::SendTimeRemaining() {
protocol::UpdateLobbyTimePacket packet(LobbyWaitingTime - (utils::getTime() - m_StartTimerTime)); // converting second to millis protocol::UpdateLobbyTimePacket packet(LobbyWaitingTime - (utils::GetTime() - m_StartTimerTime)); // converting second to millis
m_Server->broadcastPacket(&packet); m_Server->BroadcastPacket(&packet);
} }
void Lobby::OnPlayerJoin(std::uint8_t playerID) { void Lobby::OnPlayerJoin(std::uint8_t playerID) {
if (m_GameStarted) if (m_GameStarted)
return; return;
std::cout << "(Server) Player Joined Lobby !\n"; utils::LOG("(Server) Player Joined Lobby !");
m_Players.push_back(playerID); m_Players.push_back(playerID);
if (m_Players.size() == MIN_PLAYER_WAITING) { // start timer if a second player join the match if (m_Players.size() == MIN_PLAYER_WAITING) { // start timer if a second player join the match
m_StartTimerTime = utils::getTime(); m_StartTimerTime = utils::GetTime();
m_Timer.reset(); m_Timer.Reset();
sendTimeRemaining(); SendTimeRemaining();
} }
} }
void Lobby::OnPlayerLeave(std::uint8_t playerID) { void Lobby::OnPlayerLeave(std::uint8_t playerID) {
if (m_GameStarted) if (m_GameStarted)
return; return;
std::cout << "(Server) Player Leaved Lobby !\n"; utils::LOG("(Server) Player Leaved Lobby !");
auto it = std::find(m_Players.begin(), m_Players.end(), playerID); auto it = std::find(m_Players.begin(), m_Players.end(), playerID);
if (it == m_Players.end()) if (it == m_Players.end())
return; return;
m_Players.erase(it); m_Players.erase(it);
if (m_Players.size() == 1) { if (m_Players.size() == 1) {
protocol::UpdateLobbyTimePacket packet(0); protocol::UpdateLobbyTimePacket packet(0);
m_Server->broadcastPacket(&packet); m_Server->BroadcastPacket(&packet);
m_StartTimerTime = 0; // reset timer if there is only one player left m_StartTimerTime = 0; // reset timer if there is only one player left
} }
} }

View File

@@ -1,121 +1,131 @@
#include "game/server/Server.h" #include "game/server/Server.h"
#include <iostream>
#include "protocol/PacketFactory.h" #include "protocol/PacketFactory.h"
#include "misc/Format.h"
namespace td { namespace td {
namespace server { namespace server {
Server::Server(const std::string& worldFilePath) : m_ServerRunning(false) { Server::Server(const std::string& worldFilePath) : m_ServerRunning(false) {
m_Game.getWorld()->loadMapFromFile(worldFilePath); m_Game.GetWorld()->LoadMapFromFile(worldFilePath);
} }
void Server::lauchGame() { Server::~Server() {
m_Game.startGame(); if (m_Thread.joinable())
m_Thread.join();
} }
void Server::startThread() { void Server::StartThread() {
m_Thread = std::thread([this]() { m_Thread = std::thread([this]() {
std::uint64_t lastTime = td::utils::getTime(); std::uint64_t lastTime = td::utils::GetTime();
while (m_ServerRunning) { while (m_ServerRunning) {
std::uint64_t time = td::utils::getTime(); std::uint64_t time = td::utils::GetTime();
std::uint64_t delta = time - lastTime; std::uint64_t delta = time - lastTime;
if (delta >= SERVER_TICK) { if (delta >= SERVER_TICK) {
tick(delta); Tick(delta);
lastTime = td::utils::getTime(); lastTime = td::utils::GetTime();
std::uint64_t sleepTime = SERVER_TICK - (delta - SERVER_TICK); std::uint64_t sleepTime = SERVER_TICK - (delta - SERVER_TICK);
std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime)); std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime));
} }
} }
Clean();
}); });
} }
void Server::stopThread(){ void Server::Close() {
m_ServerRunning = false; StopThread();
if(m_Thread.joinable())
m_Thread.join();
} }
bool Server::start(std::uint16_t port) { void Server::StopThread() {
if (!m_Listener.listen(port, 10)) { m_ServerRunning = false;
std::cout << "Failed to bind port " << port << " !\n"; }
bool Server::Start(std::uint16_t port) {
if (!m_Listener.Listen(port, 10)) {
utils::LOGE(utils::format("Failed to bind port %u !", port));
return false; return false;
} }
if (!m_Listener.setBlocking(false)) { if (!m_Listener.SetBlocking(false)) {
std::cout << "Failed to block server socket !\n"; utils::LOGE("Failed to block server socket !");
return false; return false;
} }
std::cout << "Server started at port " << port << " !\n"; utils::LOG(utils::format("Server started at port %u !", port));
m_TickCounter.reset(); m_TickCounter.Reset();
m_ServerRunning = true; m_ServerRunning = true;
startThread(); StartThread();
return true; return true;
} }
void Server::stop() { void Server::Clean() {
if(!m_ServerRunning) m_Listener.Close();
return; m_Listener.Destroy();
stopThread();
protocol::DisconnectPacket packet("Server closed");
broadcastPacket(&packet);
m_Listener.close();
m_Listener.destroy();
m_Connections.clear(); m_Connections.clear();
getPlayers().clear(); GetPlayers().clear();
utils::LOG("Server successfully stopped !");
} }
void Server::tick(std::uint64_t delta) { void Server::Stop() {
accept(); if (!m_ServerRunning)
updateSockets(); return;
m_Lobby.tick();
m_Game.tick(delta); protocol::DisconnectPacket packet("Server closed");
if (m_TickCounter.update()) { BroadcastPacket(&packet);
protocol::ServerTpsPacket packet(m_TickCounter.getTPS(), utils::getTime());
broadcastPacket(&packet); StopThread();
}
void Server::Tick(std::uint64_t delta) {
Accept();
UpdateSockets();
m_Lobby.Tick();
m_Game.Tick(delta);
if (m_TickCounter.Update()) {
protocol::ServerTpsPacket packet(m_TickCounter.GetTPS(), utils::GetTime());
BroadcastPacket(&packet);
} }
} }
void Server::accept() { void Server::Accept() {
static std::uint8_t newPlayerID = 0; static std::uint8_t newPlayerID = 0;
network::TCPSocket newSocket; network::TCPSocket newSocket;
if (m_Listener.accept(newSocket)) { if (m_Listener.Accept(newSocket)) {
ServerConnexion con(newSocket, newPlayerID); ServerConnexion con(newSocket, newPlayerID);
m_Connections.insert(std::move(ConnexionMap::value_type{ newPlayerID, std::move(con) })); m_Connections.insert(std::move(ConnexionMap::value_type{ newPlayerID, std::move(con) }));
OnPlayerJoin(newPlayerID); OnPlayerJoin(newPlayerID);
m_Connections[newPlayerID].setServer(this); m_Connections[newPlayerID].SetServer(this);
newPlayerID++; newPlayerID++;
} }
} }
void Server::updateSockets() { void Server::UpdateSockets() {
std::int16_t closedConnexionID = -1; std::int16_t closedConnexionID = -1;
for (auto& connection : m_Connections) { for (auto& connection : m_Connections) {
ServerConnexion& con = connection.second; ServerConnexion& con = connection.second;
if (con.getSocketStatus() != network::Socket::Status::Connected) { if (con.GetSocketStatus() != network::Socket::Status::Connected) {
closedConnexionID = connection.first; closedConnexionID = connection.first;
} else { } else {
con.updateSocket(); con.UpdateSocket();
} }
} }
if (closedConnexionID != -1) { if (closedConnexionID != -1) {
removeConnexion(closedConnexionID); RemoveConnexion(closedConnexionID);
} }
} }
void Server::broadcastPacket(const protocol::Packet* packet) { void Server::BroadcastPacket(const protocol::Packet* packet) {
for (auto& connection : m_Connections) { for (auto& connection : m_Connections) {
ServerConnexion& con = connection.second; ServerConnexion& con = connection.second;
con.sendPacket(packet); con.SendPacket(packet);
} }
} }
void Server::removeConnexion(std::uint8_t connexionID) { void Server::RemoveConnexion(std::uint8_t connexionID) {
getPlayers().erase(getPlayers().find(connexionID)); GetPlayers().erase(GetPlayers().find(connexionID));
m_Connections.erase(connexionID); m_Connections.erase(connexionID);
m_Lobby.OnPlayerLeave(connexionID); m_Lobby.OnPlayerLeave(connexionID);
OnPlayerLeave(connexionID); OnPlayerLeave(connexionID);
@@ -124,12 +134,12 @@ void Server::removeConnexion(std::uint8_t connexionID) {
void Server::OnPlayerJoin(std::uint8_t id) { void Server::OnPlayerJoin(std::uint8_t id) {
m_Lobby.OnPlayerJoin(id); m_Lobby.OnPlayerJoin(id);
getPlayers().insert({ id, game::Player{id} }); GetPlayers().insert({ id, game::Player{id} });
} }
void Server::OnPlayerLeave(std::uint8_t id) { void Server::OnPlayerLeave(std::uint8_t id) {
protocol::PlayerLeavePacket packet(id); protocol::PlayerLeavePacket packet(id);
broadcastPacket(&packet); BroadcastPacket(&packet);
} }
} // namespace server } // namespace server

View File

@@ -23,17 +23,17 @@ ServerConnexion::ServerConnexion() : m_Player(0) {
} }
ServerConnexion::ServerConnexion(network::TCPSocket& socket, std::uint8_t id) : Connexion::Connexion(&m_Dispatcher, socket), m_ID(id), m_Player(0) { ServerConnexion::ServerConnexion(network::TCPSocket& socket, std::uint8_t id) : Connexion::Connexion(&m_Dispatcher, socket), m_ID(id), m_Player(0) {
Connexion::updateSocket(); Connexion::UpdateSocket();
} }
ServerConnexion::ServerConnexion(ServerConnexion&& move) : Connexion::Connexion(std::move(move)), m_Server(move.m_Server), ServerConnexion::ServerConnexion(ServerConnexion&& move) : Connexion::Connexion(std::move(move)), m_Server(move.m_Server),
m_ID(move.m_ID), m_KeepAlive(move.m_KeepAlive), m_Player(move.m_Player) { m_ID(move.m_ID), m_KeepAlive(move.m_KeepAlive), m_Player(move.m_Player) {
move.m_Server = nullptr; move.m_Server = nullptr;
registerHandlers(); RegisterHandlers();
} }
void ServerConnexion::registerHandlers() { void ServerConnexion::RegisterHandlers() {
GetDispatcher()->RegisterHandler(protocol::PacketType::PlayerLogin, this); GetDispatcher()->RegisterHandler(protocol::PacketType::PlayerLogin, this);
GetDispatcher()->RegisterHandler(protocol::PacketType::KeepAlive, this); GetDispatcher()->RegisterHandler(protocol::PacketType::KeepAlive, this);
GetDispatcher()->RegisterHandler(protocol::PacketType::SelectTeam, this); GetDispatcher()->RegisterHandler(protocol::PacketType::SelectTeam, this);
@@ -41,142 +41,151 @@ void ServerConnexion::registerHandlers() {
GetDispatcher()->RegisterHandler(protocol::PacketType::PlaceTower, this); GetDispatcher()->RegisterHandler(protocol::PacketType::PlaceTower, this);
GetDispatcher()->RegisterHandler(protocol::PacketType::SendMobs, this); GetDispatcher()->RegisterHandler(protocol::PacketType::SendMobs, this);
GetDispatcher()->RegisterHandler(protocol::PacketType::UpgradeTower, this); GetDispatcher()->RegisterHandler(protocol::PacketType::UpgradeTower, this);
GetDispatcher()->RegisterHandler(protocol::PacketType::RemoveTower, this);
} }
bool ServerConnexion::updateSocket() { bool ServerConnexion::UpdateSocket() {
checkKeepAlive(); CheckKeepAlive();
return Connexion::updateSocket(); return Connexion::UpdateSocket();
} }
void ServerConnexion::checkKeepAlive() { void ServerConnexion::CheckKeepAlive() {
std::uint64_t time = utils::getTime(); std::uint64_t time = utils::GetTime();
if (time - m_KeepAlive.sendTime > KEEP_ALIVE_TIMEOUT) { if (time - m_KeepAlive.sendTime > KEEP_ALIVE_TIMEOUT) {
if (m_KeepAlive.recievedResponse) { if (m_KeepAlive.recievedResponse) {
sendKeepAlive(); SendKeepAlive();
} else { } else {
protocol::DisconnectPacket packet("Time out"); protocol::DisconnectPacket packet("Time out");
sendPacket(&packet); SendPacket(&packet);
closeConnection(); CloseConnection();
} }
} }
} }
void ServerConnexion::sendKeepAlive() { void ServerConnexion::SendKeepAlive() {
m_KeepAlive.keepAliveID = utils::getRandomInt<std::uint64_t>(0, RAND_MAX); m_KeepAlive.keepAliveID = utils::GetRandomInt<std::uint64_t>(0, RAND_MAX);
m_KeepAlive.recievedResponse = false; m_KeepAlive.recievedResponse = false;
protocol::KeepAlivePacket keepAlivePacket(m_KeepAlive.keepAliveID); protocol::KeepAlivePacket keepAlivePacket(m_KeepAlive.keepAliveID);
sendPacket(&keepAlivePacket); SendPacket(&keepAlivePacket);
std::uint64_t time = utils::getTime(); std::uint64_t time = utils::GetTime();
m_KeepAlive.sendTime = time; m_KeepAlive.sendTime = time;
} }
void ServerConnexion::HandlePacket(const protocol::PlayerLoginPacket* packet) { void ServerConnexion::HandlePacket(const protocol::PlayerLoginPacket* packet) {
if (m_Player->getName().empty() && !packet->getPlayerName().empty()) { if (m_Player->GetName().empty() && !packet->GetPlayerName().empty()) {
m_Player->setName(packet->getPlayerName()); m_Player->SetName(packet->GetPlayerName());
protocol::PlayerJoinPacket joinPacket(m_ID, m_Player->getName()); protocol::PlayerJoinPacket joinPacket(m_ID, m_Player->GetName());
m_Server->broadcastPacket(&joinPacket); m_Server->BroadcastPacket(&joinPacket);
std::map<std::uint8_t, protocol::PlayerInfo> playerNames; std::map<std::uint8_t, protocol::PlayerInfo> playerNames;
for (const auto& pair : m_Server->getPlayers()) { for (const auto& pair : m_Server->GetPlayers()) {
const game::Player& player = pair.second; const game::Player& player = pair.second;
if (!player.getName().empty()) { if (!player.GetName().empty()) {
protocol::PlayerInfo playerInfo; protocol::PlayerInfo playerInfo;
playerInfo.name = player.getName(); playerInfo.name = player.GetName();
playerInfo.team = player.getTeamColor(); playerInfo.team = player.GetTeamColor();
playerNames.insert({ player.getID(), playerInfo }); playerNames.insert({ player.GetID(), playerInfo });
} }
} }
protocol::PlayerListPacket listPacket(playerNames); protocol::PlayerListPacket listPacket(playerNames);
sendPacket(&listPacket); SendPacket(&listPacket);
} }
} }
void ServerConnexion::HandlePacket(const protocol::SelectTeamPacket* packet) { void ServerConnexion::HandlePacket(const protocol::SelectTeamPacket* packet) {
if (m_Server->getGame().getGameState() != game::GameState::Lobby) if (m_Server->GetGame().GetGameState() != game::GameState::Lobby)
return; return;
if ((std::int8_t)packet->getSelectedTeam() >= -1 || (std::int8_t)packet->getSelectedTeam() <= 1) { if (static_cast<std::int8_t>(packet->GetSelectedTeam()) >= -1 || static_cast<std::int8_t>(packet->GetSelectedTeam()) <= 1) {
if (m_Player->getTeamColor() == game::TeamColor::None) { // join a team if (m_Player->GetTeamColor() == game::TeamColor::None) { // join a team
m_Server->getGame().getTeam(packet->getSelectedTeam()).addPlayer(m_Player); m_Server->GetGame().GetTeam(packet->GetSelectedTeam()).AddPlayer(m_Player);
} else if (packet->getSelectedTeam() == game::TeamColor::None) { // leave a team } else if (packet->GetSelectedTeam() == game::TeamColor::None) { // leave a team
m_Server->getGame().getTeam(m_Player->getTeamColor()).removePlayer(m_Player); m_Server->GetGame().GetTeam(m_Player->GetTeamColor()).RemovePlayer(m_Player);
m_Player->setTeamColor(game::TeamColor::None); m_Player->SetTeamColor(game::TeamColor::None);
} else { // change team } else { // change team
m_Server->getGame().getTeam(m_Player->getTeamColor()).removePlayer(m_Player); m_Server->GetGame().GetTeam(m_Player->GetTeamColor()).RemovePlayer(m_Player);
m_Server->getGame().getTeam(packet->getSelectedTeam()).addPlayer(m_Player); m_Server->GetGame().GetTeam(packet->GetSelectedTeam()).AddPlayer(m_Player);
} }
m_Player->setTeamColor(packet->getSelectedTeam()); m_Player->SetTeamColor(packet->GetSelectedTeam());
protocol::UpdatePlayerTeamPacket updateTeamPacket(m_ID, packet->getSelectedTeam()); protocol::UpdatePlayerTeamPacket updateTeamPacket(m_ID, packet->GetSelectedTeam());
m_Server->broadcastPacket(&updateTeamPacket); m_Server->BroadcastPacket(&updateTeamPacket);
} }
} }
void ServerConnexion::HandlePacket(const protocol::KeepAlivePacket* packet) { void ServerConnexion::HandlePacket(const protocol::KeepAlivePacket* packet) {
if (packet->getAliveID() == m_KeepAlive.keepAliveID) if (packet->GetAliveID() == m_KeepAlive.keepAliveID)
m_KeepAlive.recievedResponse = true; m_KeepAlive.recievedResponse = true;
} }
void ServerConnexion::HandlePacket(const protocol::DisconnectPacket* packet) { void ServerConnexion::HandlePacket(const protocol::DisconnectPacket* packet) {
closeConnection(); CloseConnection();
} }
void ServerConnexion::setServer(Server* server) { void ServerConnexion::SetServer(Server* server) {
m_Server = server; m_Server = server;
m_Player = &m_Server->getPlayers().at(m_ID); m_Player = &m_Server->GetPlayers().at(m_ID);
initConnection(); InitConnection();
sendKeepAlive(); SendKeepAlive();
} }
void ServerConnexion::initConnection() { void ServerConnexion::InitConnection() {
protocol::UpdateGameStatePacket statePacket(m_Server->getGame().getGameState()); protocol::UpdateGameStatePacket statePacket(m_Server->GetGame().GetGameState());
sendPacket(&statePacket); SendPacket(&statePacket);
protocol::ConnexionInfoPacket conPacket(m_ID); protocol::ConnexionInfoPacket conPacket(m_ID);
sendPacket(&conPacket); SendPacket(&conPacket);
if (m_Server->getGame().getGameState() == game::GameState::Game) { if (m_Server->GetGame().GetGameState() == game::GameState::Game) {
protocol::WorldBeginDataPacket headerDataPacket(m_Server->getGame().getWorld()); protocol::WorldBeginDataPacket headerDataPacket(m_Server->GetGame().GetWorld());
protocol::WorldBeginDataPacket dataPacket(m_Server->getGame().getWorld()); protocol::WorldBeginDataPacket dataPacket(m_Server->GetGame().GetWorld());
sendPacket(&headerDataPacket); SendPacket(&headerDataPacket);
sendPacket(&dataPacket); SendPacket(&dataPacket);
} }
} }
void ServerConnexion::HandlePacket(const protocol::PlaceTowerPacket* packet) { void ServerConnexion::HandlePacket(const protocol::PlaceTowerPacket* packet) {
game::TowerType towerType = packet->getTowerType(); game::TowerType towerType = packet->GetTowerType();
const game::TowerInfo& towerInfo = game::getTowerInfo(towerType); const game::TowerInfo& towerInfo = game::GetTowerInfo(towerType);
server::ServerWorld* world = m_Server->getGame().getServerWorld(); server::ServerWorld* world = m_Server->GetGame().GetServerWorld();
if (!world->CanPlaceLittleTower({ packet->getTowerX(), packet->getTowerY() }, m_ID)) if (!world->CanPlaceLittleTower({ packet->GetTowerX(), packet->GetTowerY() }, m_ID))
return; return;
if (towerInfo.isBigTower()) if (towerInfo.IsBigTower())
if (!world->CanPlaceBigTower({ packet->getTowerX(), packet->getTowerY() }, m_ID)) if (!world->CanPlaceBigTower({ packet->GetTowerX(), packet->GetTowerY() }, m_ID))
return; return;
game::TowerPtr tower = world->placeTowerAt(towerType, packet->getTowerX(), packet->getTowerY(), m_ID); game::TowerPtr tower = world->PlaceTowerAt(towerType, packet->GetTowerX(), packet->GetTowerY(), m_ID);
protocol::WorldAddTowerPacket addTowerPacket(tower->getID(), packet->getTowerX(), packet->getTowerY(), packet->getTowerType(), m_ID); world->GetWorldNotifier().NotifyListeners(&game::WorldListener::OnTowerAdd, tower);
m_Server->broadcastPacket(&addTowerPacket);
protocol::WorldAddTowerPacket addTowerPacket(tower->GetID(), packet->GetTowerX(), packet->GetTowerY(), packet->GetTowerType(), m_ID);
m_Server->BroadcastPacket(&addTowerPacket);
} }
void ServerConnexion::HandlePacket(const protocol::SendMobsPacket* packet) { void ServerConnexion::HandlePacket(const protocol::SendMobsPacket* packet) {
const std::vector<protocol::MobSend>& mobSent = packet->getMobSends(); const std::vector<protocol::MobSend>& mobSent = packet->GetMobSends();
//TODO: verify the packet //TODO: verify the packet
for (protocol::MobSend mobSend : mobSent) { for (protocol::MobSend mobSend : mobSent) {
m_Server->getGame().getServerWorld()->spawnMobs(mobSend.mobType, mobSend.mobLevel, m_ID, mobSend.mobCount); m_Server->GetGame().GetServerWorld()->SpawnMobs(mobSend.mobType, mobSend.mobLevel, m_ID, mobSend.mobCount);
} }
} }
void ServerConnexion::HandlePacket(const protocol::UpgradeTowerPacket* packet) { void ServerConnexion::HandlePacket(const protocol::UpgradeTowerPacket* packet) {
//TODO: verify the packet //TODO: verify the packet
m_Server->broadcastPacket(packet); m_Server->BroadcastPacket(packet);
}
void ServerConnexion::HandlePacket(const protocol::RemoveTowerPacket* packet) {
//TODO: verify the packet
m_Server->BroadcastPacket(packet);
} }
ServerConnexion::~ServerConnexion() { ServerConnexion::~ServerConnexion() {

View File

@@ -4,71 +4,118 @@
namespace td { namespace td {
namespace server { namespace server {
ServerGame::ServerGame(server::Server* server) : game::Game(&m_ServerWorld), m_Server(server), m_ServerWorld(server, this) { ServerGame::ServerGame(server::Server* server) : game::Game(&m_ServerWorld), m_Server(server), m_ServerWorld(server, this),
m_GoldMineTimer{ 1000, std::bind(&ServerGame::UpdateGoldMines, this) },
m_MobStatesTimer{ 5000, std::bind(&ServerGame::UpdateMobStates, this) },
m_EndGameCooldown{ 1000 * 10 } {
BindListener(this);
} }
void ServerGame::tick(std::uint64_t delta) { void ServerGame::Tick(std::uint64_t delta) {
if (m_GameState == game::GameState::Game) { if (m_GameState == game::GameState::Game) {
Game::tick(delta); Game::Tick(delta);
updatePlayerStats(); m_MobStatesTimer.Update(delta);
UpdatePlayerStats();
} else if (m_GameState == game::GameState::EndGame) {
if (m_EndGameCooldown.Update(delta)) {
NotifyListeners(&game::GameListener::OnGameClose);
}
} }
} }
void ServerGame::startGame() { void ServerGame::StartGame() {
balanceTeams(); BalanceTeams();
protocol::WorldBeginDataPacket headerMapData(m_World); protocol::WorldBeginDataPacket headerMapData(m_World);
m_Server->broadcastPacket(&headerMapData); m_Server->BroadcastPacket(&headerMapData);
protocol::WorldDataPacket mapData(m_World); protocol::WorldDataPacket mapData(m_World);
m_Server->broadcastPacket(&mapData); m_Server->BroadcastPacket(&mapData);
InitPlayerStats();
m_GameState = game::GameState::Game; m_GameState = game::GameState::Game;
} }
void ServerGame::updatePlayerStats(){ void ServerGame::InitPlayerStats() {
m_GoldMineTimer.update(); static const unsigned int START_GOLD = 100;
for (auto& pair : m_Server->getPlayers()) { static const unsigned int START_EXP = 0;
game::Player& player = pair.second; for (auto& [id, player] : m_Server->GetPlayers()) {
if(player.hasGoldChanged()){ player.SetGold(START_GOLD);
protocol::UpdateMoneyPacket packet(player.getGold()); player.SetExp(START_EXP);
m_Server->getConnexions()[player.getID()].sendPacket(&packet); player.getUpgrades().SetGoldPerSecond(5);
player.updateGold();
}
if(player.hasExpChanged()){
protocol::UpdateExpPacket packet(player.getExp());
m_Server->getConnexions()[player.getID()].sendPacket(&packet);
player.updateExp();
}
}
}
void ServerGame::updateGoldMines() {
for (auto& pair : m_Server->getPlayers()) {
game::Player* player = &pair.second;
player->addGold(player->getGoldPerSecond());
} }
} }
void ServerGame::balanceTeams() { void ServerGame::UpdatePlayerStats() {
m_GoldMineTimer.Update();
}
void ServerGame::UpdateGoldMines() {
for (auto& [id, player] : m_Server->GetPlayers()) {
player.AddGold(player.getUpgrades().GetGoldPerSecond());
// Update player money and exp every second
protocol::UpdateMoneyPacket moneyPacket(player.GetGold());
m_Server->GetConnexions()[player.GetID()].SendPacket(&moneyPacket);
protocol::UpdateExpPacket expPacket(player.GetExp());
m_Server->GetConnexions()[player.GetID()].SendPacket(&expPacket);
}
}
void ServerGame::UpdateMobStates() {
protocol::UpdateMobStatesPacket packet;
for (auto mob : m_World->GetMobList()) {
packet.addMobState({ mob->GetMobID(), mob->GetCenter(), mob->GetHealth(), mob->GetDirection() });
}
m_Server->BroadcastPacket(&packet);
}
void ServerGame::BalanceTeams() {
for (auto& playerInfo : Game::m_Players) { for (auto& playerInfo : Game::m_Players) {
game::Player& player = playerInfo.second; game::Player& player = playerInfo.second;
if (player.getTeamColor() == game::TeamColor::None) { if (player.GetTeamColor() == game::TeamColor::None) {
game::Team& redTeam = getRedTeam(); game::Team& redTeam = GetRedTeam();
game::Team& blueTeam = getBlueTeam(); game::Team& blueTeam = GetBlueTeam();
if (blueTeam.getPlayerCount() > redTeam.getPlayerCount()) { if (blueTeam.GetPlayerCount() > redTeam.GetPlayerCount()) {
player.setTeamColor(game::TeamColor::Red); player.SetTeamColor(game::TeamColor::Red);
redTeam.addPlayer(&player); redTeam.AddPlayer(&player);
} else { } else {
player.setTeamColor(game::TeamColor::Blue); player.SetTeamColor(game::TeamColor::Blue);
blueTeam.addPlayer(&player); blueTeam.AddPlayer(&player);
} }
protocol::UpdatePlayerTeamPacket packet(player.getID(), player.getTeamColor()); protocol::UpdatePlayerTeamPacket packet(player.GetID(), player.GetTeamColor());
m_Server->broadcastPacket(&packet); m_Server->BroadcastPacket(&packet);
} }
} }
} }
void ServerGame::OnGameStateUpdate(game::GameState newState) {
SetGameState(newState);
protocol::UpdateGameStatePacket packet(newState);
m_Server->BroadcastPacket(&packet);
}
void ServerGame::OnGameBegin() {
NotifyListeners(&game::GameListener::OnGameStateUpdate, game::GameState::Game);
StartGame();
}
void ServerGame::OnGameEnd() {
NotifyListeners(&game::GameListener::OnGameStateUpdate, game::GameState::EndGame);
m_EndGameCooldown.ApplyCooldown();
}
void ServerGame::OnGameClose() {
NotifyListeners(&game::GameListener::OnGameStateUpdate, game::GameState::Closed);
// Disconnect clients
protocol::DisconnectPacket packet("Game finished");
m_Server->BroadcastPacket(&packet);
// Closing server
m_Server->Close();
}
} // namespace game } // namespace game
} // namespace td } // namespace td

View File

@@ -11,46 +11,67 @@ ServerWorld::ServerWorld(Server* server, ServerGame* game) : game::World(game),
} }
void ServerWorld::spawnMobs(game::MobType type, std::uint8_t level, game::PlayerID sender, std::uint8_t count) { void ServerWorld::SpawnMobs(game::MobType type, std::uint8_t level, game::PlayerID sender, std::uint8_t count) {
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
game::TeamColor senderTeam = m_Game->getPlayers().at(sender).getTeamColor(); game::TeamColor senderTeam = m_Game->GetPlayers().at(sender).GetTeamColor();
game::Spawn* enemyMobSpawn; game::Spawn* enemyMobSpawn;
if (senderTeam == game::TeamColor::Red) { if (senderTeam == game::TeamColor::Red) {
enemyMobSpawn = &getTeam(game::TeamColor::Blue).getSpawn(); enemyMobSpawn = &GetTeam(game::TeamColor::Blue).GetSpawn();
} else { } else {
enemyMobSpawn = &getTeam(game::TeamColor::Red).getSpawn(); enemyMobSpawn = &GetTeam(game::TeamColor::Red).GetSpawn();
} }
std::int32_t spawnCenterX = enemyMobSpawn->x; float spawnWidth = enemyMobSpawn->GetWidth();
std::int32_t spawnCenterY = enemyMobSpawn->y; float spawnHeight = enemyMobSpawn->GetHeight();
std::int32_t minSpawnY = spawnCenterY - 2; float spawnCenterX = enemyMobSpawn->GetCenterX();
std::int32_t maxSpawnY = spawnCenterY + 2; float spawnCenterY = enemyMobSpawn->GetCenterY();
std::int32_t minSpawnX = spawnCenterX - 2; auto mobStats = GetMobStats(type, level);
std::int32_t maxSpawnX = spawnCenterX + 2; auto mobSize = mobStats->GetSize();
float mobX = utils::getRandomReal<float>(minSpawnX, maxSpawnX); float minSpawnX = spawnCenterX - spawnWidth / 2.0f + mobSize.x / 2.0f;
float mobY = utils::getRandomReal<float>(minSpawnY, maxSpawnY); float maxSpawnX = spawnCenterX + spawnWidth / 2.0f - mobSize.x / 2.0f;
spawnMobAt(m_CurrentMobID, type, level, sender, mobX, mobY, enemyMobSpawn->direction); float minSpawnY = spawnCenterY - spawnHeight / 2.0f + mobSize.y / 2.0f;
float maxSpawnY = spawnCenterY + spawnHeight / 2.0f - mobSize.y / 2.0f;
protocol::SpawnMobPacket packet(m_CurrentMobID, type, level, sender, mobX, mobY, enemyMobSpawn->direction); float mobX = utils::GetRandomReal<float>(minSpawnX + MobSpawnBorder, maxSpawnX - MobSpawnBorder);
m_Server->broadcastPacket(&packet); float mobY = utils::GetRandomReal<float>(minSpawnY + MobSpawnBorder, maxSpawnY - MobSpawnBorder);
SpawnMobAt(m_CurrentMobID, type, level, sender, mobX, mobY, enemyMobSpawn->GetDirection());
protocol::SpawnMobPacket packet(m_CurrentMobID, type, level, sender, mobX, mobY, enemyMobSpawn->GetDirection());
m_Server->BroadcastPacket(&packet);
m_CurrentMobID++; m_CurrentMobID++;
} }
} }
game::TowerPtr ServerWorld::placeTowerAt(game::TowerType type, std::int32_t x, std::int32_t y, game::PlayerID builder) { game::TowerPtr ServerWorld::PlaceTowerAt(game::TowerType type, std::int32_t x, std::int32_t y, game::PlayerID builder) {
game::TowerPtr tower = World::placeTowerAt(m_CurrentTowerID, type, x, y, builder); game::TowerPtr tower = World::PlaceTowerAt(m_CurrentTowerID, type, x, y, builder);
m_CurrentTowerID++; m_CurrentTowerID++;
return tower; return tower;
} }
void ServerWorld::OnArrowShot(game::MobPtr target, game::Tower* shooter) { void ServerWorld::OnMobDie(game::Mob* mob) {
World::OnArrowShot(target, shooter); if (mob->OnDeath(this)) { // check if the mob is actually dead (slimes ...)
//reward players
game::Player* sender = m_Game->GetPlayerById(mob->GetSender());
sender->AddExp(mob->GetStats()->GetExpReward());
game::Player* killer = m_Game->GetPlayerById(mob->GetLastDamageTower()->GetBuilder());
killer->AddGold(mob->GetStats()->GetMoneyCost());
}
}
void ServerWorld::OnMobCastleDamage(game::Mob* damager, game::TeamCastle* enemyCastle, float damage) {
// calling base class event
World::OnMobCastleDamage(damager, enemyCastle, damage);
protocol::UpdateCastleLifePacket packet(enemyCastle->GetLife(), enemyCastle->GetTeam()->GetColor());
m_Server->BroadcastPacket(&packet);
} }
} // namespace server } // namespace server

View File

@@ -8,18 +8,17 @@
namespace td { namespace td {
namespace utils { namespace utils {
unsigned long inflate(const std::string& source, std::string& dest) { std::uint64_t Inflate(const std::string& source, std::string& dest) {
unsigned long size = dest.size(); std::size_t size;
uncompress((Bytef*)&dest[0], &size, (const Bytef*)source.c_str(), source.length()); uncompress(reinterpret_cast<Bytef*>(dest.data()), reinterpret_cast<uLongf*>(&size), reinterpret_cast<const Bytef*>(source.c_str()), source.length());
return size; return size;
} }
unsigned long deflate(const std::string& source, std::string& dest) { std::uint64_t Deflate(const std::string& source, std::string& dest) {
unsigned long size = source.length(); std::size_t size;
dest.resize(size); dest.resize(source.size()); // Resize for the compressed data to fit into
compress(reinterpret_cast<Bytef*>(dest.data()), reinterpret_cast<uLongf*>(&size), reinterpret_cast<const Bytef*>(source.c_str()), source.length());
compress((Bytef*)&dest[0], &size, (const Bytef*)source.c_str(), source.length()); dest.resize(size); // Resize to cut useless data
dest.resize(size);
return size; return size;
} }
@@ -38,7 +37,7 @@ DataBuffer Compress(const DataBuffer& buffer) {
return packet; return packet;
} }
deflate(buffer.ToString(), compressedData); Deflate(buffer.ToString(), compressedData);
std::uint64_t dataLength = buffer.GetSize(); std::uint64_t dataLength = buffer.GetSize();
std::uint64_t packetLength = compressedData.length() + sizeof(dataLength); std::uint64_t packetLength = compressedData.length() + sizeof(dataLength);
@@ -71,7 +70,7 @@ DataBuffer Decompress(DataBuffer& buffer, std::uint64_t packetLength) {
std::string inflated; std::string inflated;
inflated.resize(uncompressedLength); inflated.resize(uncompressedLength);
inflate(deflatedData, inflated); Inflate(deflatedData, inflated);
assert(inflated.length() == uncompressedLength); assert(inflated.length() == uncompressedLength);
return DataBuffer(inflated); return DataBuffer(inflated);

View File

@@ -7,12 +7,13 @@
namespace td { namespace td {
DataBuffer::DataBuffer() { } DataBuffer::DataBuffer() : m_ReadOffset(0) { }
DataBuffer::DataBuffer(const DataBuffer& other) : m_Buffer(other.m_Buffer), m_ReadOffset(other.m_ReadOffset) { } DataBuffer::DataBuffer(const DataBuffer& other) : m_Buffer(other.m_Buffer), m_ReadOffset(other.m_ReadOffset) { }
DataBuffer::DataBuffer(DataBuffer&& other) : m_Buffer(std::move(other.m_Buffer)), m_ReadOffset(std::move(other.m_ReadOffset)) { } DataBuffer::DataBuffer(DataBuffer&& other) : m_Buffer(std::move(other.m_Buffer)), m_ReadOffset(std::move(other.m_ReadOffset)) { }
DataBuffer::DataBuffer(const std::string& str) : m_Buffer(str.begin(), str.end()) { } DataBuffer::DataBuffer(const std::string& str) : m_Buffer(str.begin(), str.end()), m_ReadOffset(0) { }
DataBuffer::DataBuffer(const DataBuffer& other, std::size_t offset) {
m_Buffer.reserve(other.GetSize() - offset); DataBuffer::DataBuffer(const DataBuffer& other, Data::difference_type offset) : m_ReadOffset(0) {
m_Buffer.reserve(other.GetSize() - static_cast<std::size_t>(offset));
std::copy(other.m_Buffer.begin() + offset, other.m_Buffer.end(), std::back_inserter(m_Buffer)); std::copy(other.m_Buffer.begin() + offset, other.m_Buffer.end(), std::back_inserter(m_Buffer));
} }
@@ -58,7 +59,7 @@ DataBuffer::const_iterator DataBuffer::end() const {
std::ostream& operator<<(std::ostream& os, const DataBuffer& buffer) { std::ostream& operator<<(std::ostream& os, const DataBuffer& buffer) {
for (unsigned char u : buffer) for (unsigned char u : buffer)
os << std::hex << std::setfill('0') << std::setw(2) << (int)u << " "; os << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(u) << " ";
os << std::dec; os << std::dec;
return os; return os;
} }
@@ -81,7 +82,7 @@ bool DataBuffer::ReadFile(const std::string& fileName) {
bool DataBuffer::WriteFile(const std::string& fileName) { bool DataBuffer::WriteFile(const std::string& fileName) {
try { try {
std::ofstream file(fileName, std::ostream::binary); std::ofstream file(fileName, std::ostream::binary);
file.write((const char*)m_Buffer.data(), m_Buffer.size()); file.write(reinterpret_cast<const char*>(m_Buffer.data()), static_cast<std::streamsize>(m_Buffer.size()));
file.flush(); file.flush();
} catch (std::exception& e) { } catch (std::exception& e) {
std::cerr << "Failed to write file \"" << fileName << "\" reason : " << e.what() << std::endl; std::cerr << "Failed to write file \"" << fileName << "\" reason : " << e.what() << std::endl;

View File

@@ -5,59 +5,61 @@
namespace td { namespace td {
namespace utils { namespace utils {
// Found at https://easings.net/
/* Sine functions */ /* Sine functions */
float easeInSine(float x) { float EaseInSine(float x) {
return 1.0f - std::cos((x * PI) / 2.0f); return 1.0f - std::cos((x * PI) / 2.0f);
} }
float easeOutSine(float x) { float EaseOutSine(float x) {
return std::sin((x * PI) / 2.0f); return std::sin((x * PI) / 2.0f);
} }
float easeInOutSine(float x) { float EaseInOutSine(float x) {
return -(std::cos(PI * x) - 1.0f) / 2.0f; return -(std::cos(PI * x) - 1.0f) / 2.0f;
} }
/* Cubic functions */ /* Cubic functions */
float easeInCubic(float x) { float EaseInCubic(float x) {
return x * easeInQuad(x); return x * EaseInQuad(x);
} }
float easeOutCubic(float x) { float EaseOutCubic(float x) {
return 1 - std::pow(1 - x, 3); return 1 - std::pow(1 - x, 3);
} }
float easeInOutCubic(float x) { float EaseInOutCubic(float x) {
return x < 0.5 ? 4 * easeInCubic(x) : 1 - std::pow(-2 * x + 2, 3) / 2.0f; return x < 0.5 ? 4 * EaseInCubic(x) : 1 - std::pow(-2 * x + 2, 3) / 2.0f;
} }
/* Quint functions */ /* Quint functions */
float easeInQuint(float x) { float EaseInQuint(float x) {
return x * easeInQuart(x); return x * EaseInQuart(x);
} }
float easeOutQuint(float x) { float EaseOutQuint(float x) {
return 1 - std::pow(1 - x, 5); return 1 - std::pow(1 - x, 5);
} }
float easeInOutQuint(float x) { float EaseInOutQuint(float x) {
return x < 0.5 ? 16 * easeInQuint(x) : 1 - std::pow(-2 * x + 2, 5) / 2.0f; return x < 0.5 ? 16 * EaseInQuint(x) : 1 - std::pow(-2 * x + 2, 5) / 2.0f;
} }
/* Circ functions */ /* Circ functions */
float easeInCirc(float x) { float EaseInCirc(float x) {
return 1 - std::sqrt(1 - std::pow(x, 2)); return 1 - std::sqrt(1 - std::pow(x, 2));
} }
float easeOutCirc(float x) { float EaseOutCirc(float x) {
return std::sqrt(1 - std::pow(x - 1, 2)); return std::sqrt(1 - std::pow(x - 1, 2));
} }
float easeInOutCirc(float x) { float EaseInOutCirc(float x) {
return x < 0.5 return x < 0.5
? (1 - std::sqrt(1 - std::pow(2 * x, 2))) / 2.0f ? (1 - std::sqrt(1 - std::pow(2 * x, 2))) / 2.0f
: (std::sqrt(1 - std::pow(-2 * x + 2, 2)) + 1) / 2.0f; : (std::sqrt(1 - std::pow(-2 * x + 2, 2)) + 1) / 2.0f;
@@ -65,7 +67,7 @@ float easeInOutCirc(float x) {
/* Elastic functions */ /* Elastic functions */
float easeInElastic(float x) { float EaseInElastic(float x) {
const float c4 = (2 * PI) / 3.0f; const float c4 = (2 * PI) / 3.0f;
return x == 0 return x == 0
@@ -75,7 +77,7 @@ float easeInElastic(float x) {
: -std::pow(2, 10 * x - 10) * std::sin((x * 10 - 10.75) * c4); : -std::pow(2, 10 * x - 10) * std::sin((x * 10 - 10.75) * c4);
} }
float easeOutElastic(float x) { float EaseOutElastic(float x) {
const float c4 = (2 * PI) / 3.0f; const float c4 = (2 * PI) / 3.0f;
return x == 0 return x == 0
@@ -85,7 +87,7 @@ float easeOutElastic(float x) {
: std::pow(2, -10 * x) * std::sin((x * 10 - 0.75) * c4) + 1; : std::pow(2, -10 * x) * std::sin((x * 10 - 0.75) * c4) + 1;
} }
float easeInOutElastic(float x) { float EaseInOutElastic(float x) {
const float c5 = (2 * PI) / 4.5; const float c5 = (2 * PI) / 4.5;
return x == 0 return x == 0
@@ -99,43 +101,43 @@ float easeInOutElastic(float x) {
/* Quad functions */ /* Quad functions */
float easeInQuad(float x) { float EaseInQuad(float x) {
return x * x; return x * x;
} }
float easeOutQuad(float x) { float EaseOutQuad(float x) {
return 1 - (1 - x) * (1 - x); return 1 - (1 - x) * (1 - x);
} }
float easeInOutQuad(float x) { float EaseInOutQuad(float x) {
return x < 0.5 ? 2 * x * x : 1 - std::pow(-2 * x + 2, 2) / 2.0f; return x < 0.5 ? 2 * x * x : 1 - std::pow(-2 * x + 2, 2) / 2.0f;
} }
/* Quart functions */ /* Quart functions */
float easeInQuart(float x) { float EaseInQuart(float x) {
return x * easeInCubic(x); return x * EaseInCubic(x);
} }
float easeOutQuart(float x) { float EaseOutQuart(float x) {
return 1 - std::pow(1 - x, 4); return 1 - std::pow(1 - x, 4);
} }
float easeInOutQuart(float x) { float EaseInOutQuart(float x) {
return x < 0.5 ? 8 * easeInQuart(x) : 1 - std::pow(-2 * x + 2, 4) / 2.0f; return x < 0.5 ? 8 * EaseInQuart(x) : 1 - std::pow(-2 * x + 2, 4) / 2.0f;
} }
/* Expo functions */ /* Expo functions */
float easeInExpo(float x) { float EaseInExpo(float x) {
return x == 0 ? 0 : std::pow(2, 10 * x - 10); return x == 0 ? 0 : std::pow(2, 10 * x - 10);
} }
float easeOutExpo(float x) { float EaseOutExpo(float x) {
return x == 1 ? 1 : 1 - std::pow(2, -10 * x); return x == 1 ? 1 : 1 - std::pow(2, -10 * x);
} }
float easeInOutExpo(float x) { float EaseInOutExpo(float x) {
return x == 0 return x == 0
? 0 ? 0
: x == 1 : x == 1
@@ -146,21 +148,21 @@ float easeInOutExpo(float x) {
/* Back functions */ /* Back functions */
float easeInBack(float x) { float EaseInBack(float x) {
const float c1 = 1.70158; const float c1 = 1.70158;
const float c3 = c1 + 1; const float c3 = c1 + 1;
return c3 * easeInCubic(x) - c1 * easeInQuad(x); return c3 * EaseInCubic(x) - c1 * EaseInQuad(x);
} }
float easeOutBack(float x) { float EaseOutBack(float x) {
const float c1 = 1.70158; const float c1 = 1.70158;
const float c3 = c1 + 1; const float c3 = c1 + 1;
return 1 + c3 * std::pow(x - 1, 3) + c1 * std::pow(x - 1, 2); return 1 + c3 * std::pow(x - 1, 3) + c1 * std::pow(x - 1, 2);
} }
float easeInOutBack(float x) { float EaseInOutBack(float x) {
const float c1 = 1.70158; const float c1 = 1.70158;
const float c2 = c1 * 1.525; const float c2 = c1 * 1.525;
@@ -171,16 +173,16 @@ float easeInOutBack(float x) {
/* Bounce functions */ /* Bounce functions */
float easeInBounce(float x) { float EaseInBounce(float x) {
return 1 - easeOutBounce(1 - x); return 1 - EaseOutBounce(1 - x);
} }
float easeOutBounce(float x) { float EaseOutBounce(float x) {
const float n1 = 7.5625; const float n1 = 7.5625;
const float d1 = 2.75; const float d1 = 2.75;
if (x < 1 / d1) { if (x < 1 / d1) {
return n1 * easeInQuad(x); return n1 * EaseInQuad(x);
} else if (x < 2 / d1) { } else if (x < 2 / d1) {
x -= 1.5; x -= 1.5;
return n1 * (x / d1) * x + 0.75; return n1 * (x / d1) * x + 0.75;
@@ -193,10 +195,10 @@ float easeOutBounce(float x) {
} }
} }
float easeInOutBounce(float x) { float EaseInOutBounce(float x) {
return x < 0.5 return x < 0.5
? (1 - easeOutBounce(1 - 2 * x)) / 2.0f ? (1 - EaseOutBounce(1 - 2 * x)) / 2.0f
: (1 + easeOutBounce(2 * x - 1)) / 2.0f; : (1 + EaseOutBounce(2 * x - 1)) / 2.0f;
} }
} // namespace utils } // namespace utils

35
src/misc/Log.cpp Normal file
View File

@@ -0,0 +1,35 @@
#include "misc/Log.h"
#ifdef __ANDROID__
#include <android/log.h>
#else
#include <iostream>
#endif
namespace td {
namespace utils {
void LOG(const std::string& msg) {
#ifdef __ANDROID__
__android_log_print(ANDROID_LOG_INFO, "TRACKERS", "%s", msg.c_str());
#else
std::cout << msg << "\n";
#endif
}
void LOGD(const std::string& msg) {
#if !defined(NDEBUG)
LOG(msg);
#endif
}
void LOGE(const std::string& err) {
#ifdef __ANDROID__
__android_log_print(ANDROID_LOG_ERROR, "TRACKERS", "%s", err.c_str());
#else
std::cerr << err << "\n";
#endif
}
}
} // namespace td

85
src/misc/Shapes.cpp Normal file
View File

@@ -0,0 +1,85 @@
#include "misc/Shapes.h"
#include <algorithm>
#include <cmath>
namespace td {
namespace utils {
namespace shape {
float Point::Distance(const Point& point) const {
return std::sqrt(DistanceSquared(point));
}
float Point::DistanceSquared(const Point& point) const {
return (m_X - point.GetX()) * (m_X - point.GetX()) + (m_Y - point.GetY()) * (m_Y - point.GetY());
}
bool Rectangle::CollidesWith(const Point& point) const {
return point.GetX() > GetTopLeft().GetX() && point.GetX() < GetBottomRight().GetX() &&
point.GetY() > GetTopLeft().GetY() && point.GetY() < GetBottomRight().GetY();
}
bool Rectangle::CollidesWith(const Rectangle& rect) const {
Point point1{ rect.GetTopLeft().GetX(), rect.GetTopLeft().GetY() };
Point point2{ rect.GetTopLeft().GetX(), rect.GetBottomRight().GetY() };
Point point3{ rect.GetBottomRight().GetX(), rect.GetTopLeft().GetY() };
Point point4{ rect.GetBottomRight().GetX(), rect.GetBottomRight().GetY() };
if (CollidesWith(point1)) return true;
if (CollidesWith(point2)) return true;
if (CollidesWith(point3)) return true;
if (CollidesWith(point4)) return true;
return false;
}
bool Rectangle::CollidesWith(const Circle& circle) const {
return circle.CollidesWith(*this);
}
float Rectangle::Distance(const Circle& circle) const {
return circle.Distance(*this);
}
float Rectangle::DistanceSquared(const Circle& circle) const {
return circle.DistanceSquared(*this);
}
bool Circle::CollidesWith(const Point& point) const {
return m_Radius * m_Radius > m_Center.DistanceSquared(point);
}
bool Circle::CollidesWith(const Rectangle& rect) const {
float DistanceSquared_ = DistanceSquared(rect);
return DistanceSquared_ < m_Radius* m_Radius;
}
bool Circle::CollidesWith(const Circle& circle) const {
return m_Radius + circle.GetRadius() > m_Center.DistanceSquared(circle.GetCenter());
}
float Circle::Distance(const Rectangle& rect) const {
return std::sqrt(DistanceSquared(rect));
}
float Circle::DistanceSquared(const Rectangle& rect) const {
float closestX = std::clamp(m_Center.GetX(), rect.GetTopLeft().GetX(), rect.GetBottomRight().GetX());
float closestY = std::clamp(m_Center.GetY(), rect.GetTopLeft().GetY(), rect.GetBottomRight().GetY());
float DistanceX = m_Center.GetX() - closestX;
float DistanceY = m_Center.GetY() - closestY;
return (DistanceX * DistanceX) + (DistanceY * DistanceY);
}
} // namespace shape
} // namespace utils
} // namespace td

View File

@@ -6,32 +6,32 @@
namespace td { namespace td {
namespace utils { namespace utils {
void AutoTimer::update() { void AutoTimer::Update() {
m_InternalTime += getTime() - m_LastTime; m_InternalTime += GetTime() - m_LastTime;
if (m_InternalTime >= m_Interval) { if (m_InternalTime >= m_Interval) {
if (m_Function != nullptr) if (m_Function != nullptr)
m_Function(); m_Function();
m_InternalTime %= m_Interval; m_InternalTime %= m_Interval;
} }
m_LastTime = getTime(); m_LastTime = GetTime();
} }
void AutoTimer::update(std::uint64_t delta) { void AutoTimer::Update(std::uint64_t delta) {
m_InternalTime += delta; m_InternalTime += delta;
if (m_InternalTime >= m_Interval) { if (m_InternalTime >= m_Interval) {
if (m_Function != nullptr) if (m_Function != nullptr)
m_Function(); m_Function();
m_InternalTime %= m_Interval; m_InternalTime %= m_Interval;
} }
m_LastTime = getTime(); m_LastTime = GetTime();
} }
void AutoTimer::reset() { void AutoTimer::Reset() {
m_InternalTime = 0; m_InternalTime = 0;
m_LastTime = getTime(); m_LastTime = GetTime();
} }
bool Timer::update(std::uint64_t delta) { bool Timer::Update(std::uint64_t delta) {
m_InternalTime += delta; m_InternalTime += delta;
if (m_InternalTime >= m_Interval) { if (m_InternalTime >= m_Interval) {
m_InternalTime %= m_Interval; m_InternalTime %= m_Interval;
@@ -40,27 +40,27 @@ bool Timer::update(std::uint64_t delta) {
return false; return false;
} }
void Timer::reset() { void Timer::Reset() {
m_InternalTime = 0; // let the timer active once at the beginning m_InternalTime = 0; // let the timer active once at the beginning
} }
bool CooldownTimer::update(std::uint64_t delta) { bool CooldownTimer::Update(std::uint64_t delta) {
if (m_Cooldown > 0) { if (m_Cooldown > 0) {
m_Cooldown = std::max(static_cast<std::int64_t>(0), static_cast<std::int64_t>(m_Cooldown - delta)); m_Cooldown = static_cast<std::uint64_t>(std::max(static_cast<std::int64_t>(0), static_cast<std::int64_t>(m_Cooldown - delta)));
} }
return m_Cooldown == 0; return m_Cooldown == 0;
} }
void CooldownTimer::reset() { void CooldownTimer::Reset() {
m_Cooldown = 0; // let the timer active once at the beginning m_Cooldown = 0; // let the timer active once at the beginning
} }
void CooldownTimer::applyCooldown(){ void CooldownTimer::ApplyCooldown() {
m_Cooldown = m_CooldownTime; m_Cooldown = m_CooldownTime;
} }
std::uint64_t getTime() { std::uint64_t GetTime() {
return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock().now().time_since_epoch()).count(); return static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock().now().time_since_epoch()).count());
} }
} // namespace utils } // namespace utils

View File

@@ -36,7 +36,7 @@ IPAddress::IPAddress(const std::string& ip)
std::uint8_t octet3 = std::stoul(std::string(match[3])); std::uint8_t octet3 = std::stoul(std::string(match[3]));
std::uint8_t octet4 = std::stoul(std::string(match[4])); std::uint8_t octet4 = std::stoul(std::string(match[4]));
m_Address = (octet1 << 24) | (octet2 << 16) | (octet3 << 8) | octet4; m_Address = static_cast<std::uint32_t>((octet1 << 24) | (octet2 << 16) | (octet3 << 8) | octet4);
m_Valid = true; m_Valid = true;
} }
@@ -55,14 +55,14 @@ IPAddress::IPAddress(const std::wstring& ip)
std::uint8_t octet3 = std::stoul(match[3]); std::uint8_t octet3 = std::stoul(match[3]);
std::uint8_t octet4 = std::stoul(match[4]); std::uint8_t octet4 = std::stoul(match[4]);
m_Address = (octet1 << 24) | (octet2 << 16) | (octet3 << 8) | octet4; m_Address = static_cast<std::uint32_t>((octet1 << 24) | (octet2 << 16) | (octet3 << 8) | octet4);
m_Valid = true; m_Valid = true;
} }
/* Initialize by octets */ /* Initialize by octets */
IPAddress::IPAddress(uint8_t octet1, uint8_t octet2, uint8_t octet3, uint8_t octet4) noexcept IPAddress::IPAddress(uint8_t octet1, uint8_t octet2, uint8_t octet3, uint8_t octet4) noexcept
: m_Valid(true) { : m_Valid(true) {
m_Address = (octet1 << 24) | (octet2 << 16) | (octet3 << 8) | octet4; m_Address = static_cast<std::uint32_t>((octet1 << 24) | (octet2 << 16) | (octet3 << 8) | octet4);
} }
/* Get the specific octet */ /* Get the specific octet */
@@ -82,7 +82,7 @@ void IPAddress::SetOctet(uint8_t num, uint8_t value) {
octets[num - 1] = value; octets[num - 1] = value;
m_Address = (octets[0] << 24) | (octets[1] << 16) | (octets[2] << 8) | octets[3]; m_Address = static_cast<std::uint32_t>((octets[0] << 24) | (octets[1] << 16) | (octets[2] << 8) | octets[3]);
} }
IPAddress IPAddress::LocalAddress() { IPAddress IPAddress::LocalAddress() {

View File

@@ -33,7 +33,8 @@ NetworkInitializer initializer;
IPAddresses Dns::Resolve(const std::string& host) { IPAddresses Dns::Resolve(const std::string& host) {
IPAddresses list; IPAddresses list;
addrinfo hints = { 0 }, * addresses; addrinfo hints{};
addrinfo* addresses = nullptr;
//hints.ai_family = AF_UNSPEC; //hints.ai_family = AF_UNSPEC;
hints.ai_family = AF_INET; hints.ai_family = AF_INET;
@@ -54,7 +55,7 @@ IPAddresses Dns::Resolve(const std::string& host) {
#else #else
char straddr[512]; char straddr[512];
inet_ntop(p->ai_family, &((sockaddr_in*)p->ai_addr)->sin_addr, straddr, sizeof(straddr)); inet_ntop(p->ai_family, &(reinterpret_cast<sockaddr_in*>(p->ai_addr))->sin_addr, straddr, sizeof(straddr));
#endif #endif
list.push_back(IPAddress(straddr)); list.push_back(IPAddress(straddr));

View File

@@ -16,7 +16,7 @@ Socket::Socket(Type type)
: m_Blocking(false), : m_Blocking(false),
m_Type(type), m_Type(type),
m_Status(Disconnected), m_Status(Disconnected),
m_Handle((SocketHandle)INVALID_SOCKET) m_Handle(static_cast<SocketHandle>(INVALID_SOCKET))
{ {
} }

View File

@@ -14,10 +14,10 @@ namespace network {
TCPListener::TCPListener() {} TCPListener::TCPListener() {}
TCPListener::~TCPListener() { TCPListener::~TCPListener() {
destroy(); Destroy();
} }
bool TCPListener::listen(uint16_t port, int maxConnections) { bool TCPListener::Listen(uint16_t port, int maxConnections) {
if ((m_Handle = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) if ((m_Handle = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
return false; return false;
@@ -38,7 +38,7 @@ bool TCPListener::listen(uint16_t port, int maxConnections) {
return true; return true;
} }
bool TCPListener::accept(TCPSocket& newSocket) { bool TCPListener::Accept(TCPSocket& newSocket) {
int addrlen = sizeof(newSocket.m_RemoteAddr); int addrlen = sizeof(newSocket.m_RemoteAddr);
if ((newSocket.m_Handle = ::accept(m_Handle, reinterpret_cast<sockaddr*>(&newSocket.m_RemoteAddr), if ((newSocket.m_Handle = ::accept(m_Handle, reinterpret_cast<sockaddr*>(&newSocket.m_RemoteAddr),
reinterpret_cast<socklen_t*>(&addrlen))) < 0) reinterpret_cast<socklen_t*>(&addrlen))) < 0)
@@ -48,21 +48,21 @@ bool TCPListener::accept(TCPSocket& newSocket) {
return true; return true;
} }
void TCPListener::destroy() { void TCPListener::Destroy() {
if (m_Handle < 0) if (m_Handle < 0)
::closesocket(m_Handle); ::closesocket(m_Handle);
} }
bool TCPListener::close() { bool TCPListener::Close() {
if (::shutdown(m_Handle, SD_BOTH) == 0) if (::shutdown(m_Handle, SD_BOTH) == 0)
return true; return true;
return false; return false;
} }
bool TCPListener::setBlocking(bool blocking) { bool TCPListener::SetBlocking(bool blocking) {
unsigned long mode = blocking ? 0 : 1; unsigned long mode = blocking ? 0 : 1;
if (ioctlsocket(m_Handle, FIONBIO, &mode) < 0) { if (::ioctlsocket(m_Handle, FIONBIO, &mode) < 0) {
return false; return false;
} }
return true; return true;

View File

@@ -13,10 +13,8 @@
namespace td { namespace td {
namespace network { namespace network {
TCPSocket::TCPSocket() TCPSocket::TCPSocket() : Socket(Socket::TCP), m_Port(0) {
: Socket(Socket::TCP), m_Port(0) m_Handle = static_cast<SocketHandle>(INVALID_SOCKET);
{
m_Handle = (SocketHandle)INVALID_SOCKET;
} }
bool TCPSocket::Connect(const IPAddress& address, unsigned short port) { bool TCPSocket::Connect(const IPAddress& address, unsigned short port) {
@@ -32,7 +30,7 @@ bool TCPSocket::Connect(const IPAddress& address, unsigned short port) {
hints.ai_socktype = SOCK_STREAM; hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP; hints.ai_protocol = IPPROTO_TCP;
if (::getaddrinfo(address.ToString().c_str(), std::to_string(port).c_str(), &hints, &result) != 0) { if (::getaddrinfo(address.ToString().c_str(), std::to_string(static_cast<int>(port)).c_str(), &hints, &result) != 0) {
std::cerr << "Failed to get address info !\n"; std::cerr << "Failed to get address info !\n";
return false; return false;
} }
@@ -44,8 +42,8 @@ bool TCPSocket::Connect(const IPAddress& address, unsigned short port) {
struct addrinfo* ptr = nullptr; struct addrinfo* ptr = nullptr;
for (ptr = result; ptr != nullptr; ptr = ptr->ai_next) { for (ptr = result; ptr != nullptr; ptr = ptr->ai_next) {
struct sockaddr_in* sockaddr = (struct sockaddr_in*)ptr->ai_addr; struct sockaddr* sockaddr = ptr->ai_addr;
if (::connect(m_Handle, (struct sockaddr*)sockaddr, sizeof(struct sockaddr_in)) != 0) { if (::connect(m_Handle, sockaddr, sizeof(sockaddr_in)) != 0) {
std::cerr << "Failed to connect with this address !\n"; std::cerr << "Failed to connect with this address !\n";
continue; continue;
} }
@@ -78,7 +76,7 @@ size_t TCPSocket::Send(const unsigned char* data, size_t size) {
Disconnect(); Disconnect();
return 0; return 0;
} }
sent += cur; sent += static_cast<std::size_t>(cur);
} }
return sent; return sent;
@@ -88,7 +86,7 @@ std::size_t TCPSocket::Receive(DataBuffer& buffer, std::size_t amount) {
buffer.Resize(amount); buffer.Resize(amount);
buffer.SetReadOffset(0); buffer.SetReadOffset(0);
int recvAmount = ::recv(m_Handle, (char*)&buffer[0], amount, 0); int recvAmount = ::recv(m_Handle, reinterpret_cast<char*>(buffer.data()), amount, 0);
if (recvAmount <= 0) { if (recvAmount <= 0) {
#if defined(_WIN32) || defined(WIN32) #if defined(_WIN32) || defined(WIN32)
int err = WSAGetLastError(); int err = WSAGetLastError();
@@ -104,8 +102,8 @@ std::size_t TCPSocket::Receive(DataBuffer& buffer, std::size_t amount) {
buffer.Clear(); buffer.Clear();
return 0; return 0;
} }
buffer.Resize(recvAmount); buffer.Resize(static_cast<std::size_t>(recvAmount));
return recvAmount; return static_cast<std::size_t>(recvAmount);
} }
DataBuffer TCPSocket::Receive(std::size_t amount) { DataBuffer TCPSocket::Receive(std::size_t amount) {
@@ -126,7 +124,7 @@ DataBuffer TCPSocket::Receive(std::size_t amount) {
return DataBuffer(); return DataBuffer();
} }
return DataBuffer(std::string(buf.get(), received)); return DataBuffer(std::string(buf.get(), static_cast<std::size_t>(received)));
} }
TCPSocket::TCPSocket(TCPSocket&& other) : Socket(TCP) { TCPSocket::TCPSocket(TCPSocket&& other) : Socket(TCP) {
@@ -136,12 +134,12 @@ TCPSocket::TCPSocket(TCPSocket&& other) : Socket(TCP) {
m_RemoteIP = other.m_RemoteIP; m_RemoteIP = other.m_RemoteIP;
SetStatus(other.GetStatus()); SetStatus(other.GetStatus());
SetBlocking(other.IsBlocking()); SetBlocking(other.IsBlocking());
other.m_Handle = (SocketHandle)INVALID_SOCKET; other.m_Handle = static_cast<SocketHandle>(INVALID_SOCKET);
} }
void SendPacket(const DataBuffer& data, network::TCPSocket& socket) { void SendPacket(const DataBuffer& data, network::TCPSocket& socket) {
DataBuffer compressed = utils::Compress(data); DataBuffer compressed = utils::Compress(data);
socket.Send((const std::uint8_t*)compressed.ToString().data(), compressed.GetSize()); socket.Send(reinterpret_cast<const std::uint8_t*>(compressed.ToString().data()), compressed.GetSize());
} }

View File

@@ -14,7 +14,7 @@ namespace network {
UDPSocket::UDPSocket() UDPSocket::UDPSocket()
: Socket(Socket::UDP), m_Port(0) : Socket(Socket::UDP), m_Port(0)
{ {
m_Handle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); m_Handle = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
} }
bool UDPSocket::Connect(const IPAddress& address, unsigned short port) { bool UDPSocket::Connect(const IPAddress& address, unsigned short port) {
@@ -31,20 +31,20 @@ bool UDPSocket::Connect(const IPAddress& address, unsigned short port) {
return true; return true;
} }
size_t UDPSocket::Send(const unsigned char* data, size_t size) { std::size_t UDPSocket::Send(const unsigned char* data, std::size_t size) {
size_t sent = 0; std::size_t sent = 0;
if (this->GetStatus() != Connected) if (this->GetStatus() != Connected)
return 0; return 0;
while (sent < size) { while (sent < size) {
int cur = sendto(m_Handle, reinterpret_cast<const char*>(data + sent), size - sent, 0, int cur = ::sendto(m_Handle, reinterpret_cast<const char*>(data + sent), size - sent, 0,
reinterpret_cast<sockaddr*>(&m_RemoteAddr), sizeof(sockaddr_in)); reinterpret_cast<sockaddr*>(&m_RemoteAddr), sizeof(sockaddr_in));
if (cur <= 0) { if (cur <= 0) {
Disconnect(); Disconnect();
return 0; return 0;
} }
sent += cur; sent += static_cast<std::size_t>(cur);
} }
return sent; return sent;
@@ -54,7 +54,7 @@ DataBuffer UDPSocket::Receive(std::size_t amount) {
std::unique_ptr<char[]> buf(new char[amount]); std::unique_ptr<char[]> buf(new char[amount]);
socklen_t slen = sizeof(sockaddr_in); socklen_t slen = sizeof(sockaddr_in);
int received = recvfrom(m_Handle, buf.get(), amount, 0, int received = ::recvfrom(m_Handle, buf.get(), amount, 0,
reinterpret_cast<sockaddr*>(&m_RemoteAddr), &slen); reinterpret_cast<sockaddr*>(&m_RemoteAddr), &slen);
if (received <= 0) { if (received <= 0) {
@@ -64,13 +64,40 @@ DataBuffer UDPSocket::Receive(std::size_t amount) {
int err = errno; int err = errno;
#endif #endif
if (err == WOULDBLOCK) if (err == WOULDBLOCK)
return DataBuffer(std::string(buf.get(), received)); return DataBuffer(std::string(buf.get(), static_cast<std::size_t>(received)));
Disconnect(); Disconnect();
return DataBuffer(); return DataBuffer();
} }
return DataBuffer(std::string(buf.get(), received)); return DataBuffer(std::string(buf.get(), static_cast<std::size_t>(received)));
}
std::size_t UDPSocket::Receive(DataBuffer& buffer, std::size_t amount) {
buffer.Resize(amount);
buffer.SetReadOffset(0);
socklen_t slen = sizeof(sockaddr_in);
int recvAmount = ::recvfrom(m_Handle, reinterpret_cast<char*>(buffer.data()), amount, 0,
reinterpret_cast<sockaddr*>(&m_RemoteAddr), &slen);
if (recvAmount <= 0) {
#if defined(_WIN32) || defined(WIN32)
int err = WSAGetLastError();
#else
int err = errno;
#endif
if (err == WOULDBLOCK) {
buffer.Clear();
return 0;
}
Disconnect();
buffer.Clear();
return 0;
}
buffer.Resize(static_cast<std::size_t>(recvAmount));
return static_cast<std::size_t>(recvAmount);
} }
} // ns network } // ns network

View File

@@ -28,7 +28,7 @@ void PacketDispatcher::UnregisterHandler(PacketHandler* handler) {
void PacketDispatcher::Dispatch(const PacketPtr& packet) { void PacketDispatcher::Dispatch(const PacketPtr& packet) {
if (!packet) return; if (!packet) return;
PacketType type = packet->getType(); PacketType type = packet->GetType();
for (PacketHandler* handler : m_Handlers[type]) for (PacketHandler* handler : m_Handlers[type])
packet->Dispatch(handler); packet->Dispatch(handler);
} }

View File

@@ -28,12 +28,16 @@ static std::map<PacketType, PacketCreator> packets = {
{PacketType::SpawnMob, []() -> PacketPtr {return std::make_unique<SpawnMobPacket>(); } }, {PacketType::SpawnMob, []() -> PacketPtr {return std::make_unique<SpawnMobPacket>(); } },
{PacketType::PlaceTower, []() -> PacketPtr {return std::make_unique<PlaceTowerPacket>(); } }, {PacketType::PlaceTower, []() -> PacketPtr {return std::make_unique<PlaceTowerPacket>(); } },
{PacketType::WorldAddTower, []() -> PacketPtr {return std::make_unique<WorldAddTowerPacket>(); } }, {PacketType::WorldAddTower, []() -> PacketPtr {return std::make_unique<WorldAddTowerPacket>(); } },
{PacketType::WorldRemoveTower, []() -> PacketPtr {return std::make_unique<WorldRemoveTowerPacket>(); } }, {PacketType::RemoveTower, []() -> PacketPtr {return std::make_unique<RemoveTowerPacket>(); } },
{PacketType::SendMobs, []() -> PacketPtr {return std::make_unique<SendMobsPacket>(); } }, {PacketType::SendMobs, []() -> PacketPtr {return std::make_unique<SendMobsPacket>(); } },
{PacketType::UpgradeTower, []() -> PacketPtr {return std::make_unique<UpgradeTowerPacket>(); } }, {PacketType::UpgradeTower, []() -> PacketPtr {return std::make_unique<UpgradeTowerPacket>(); } },
{PacketType::UpdateCastleLife, []() -> PacketPtr {return std::make_unique<UpdateCastleLifePacket>(); } },
{PacketType::UpdateMobStates, []() -> PacketPtr {return std::make_unique<UpdateMobStatesPacket>(); } },
{PacketType::PlayerBuyItem, []() -> PacketPtr {return std::make_unique<PlayerBuyItemPacket>(); } },
{PacketType::PlayerBuyMobUpgrade, []() -> PacketPtr {return std::make_unique<PlayerBuyMobUpgradePacket>(); } },
}; };
PacketPtr createPacket(PacketType type, DataBuffer& buffer) { PacketPtr CreatePacket(PacketType type, DataBuffer& buffer) {
PacketPtr packet = packets[type](); PacketPtr packet = packets[type]();
packet->Deserialize(buffer); packet->Deserialize(buffer);
return packet; return packet;

View File

@@ -1,7 +1,10 @@
#include "protocol/PacketHandler.h" #include "protocol/PacketHandler.h"
#include <cmath> #include <cmath>
#define REGISTER_DISPATCH_CLASS(className) void className::Dispatch(PacketHandler* handler) const {handler->HandlePacket(this);} #define REGISTER_DISPATCH_CLASS(className) void className::Dispatch(PacketHandler* handler) const { \
handler->HandlePacket(this);\
}
namespace td { namespace td {
namespace protocol { namespace protocol {
@@ -9,54 +12,65 @@ namespace protocol {
const int BITS_IN_BYTE = 8; const int BITS_IN_BYTE = 8;
const int BITS_IN_LONG = BITS_IN_BYTE * sizeof(std::uint64_t); const int BITS_IN_LONG = BITS_IN_BYTE * sizeof(std::uint64_t);
unsigned int countBits(unsigned int number) { static unsigned int countBits(unsigned int number) {
// log function in base 2 // log function in base 2
// take only integer part // take only integer part
return (int)std::log2(number) + 1; return static_cast<unsigned int>(std::log2(number) + 1);
} }
DataBuffer& operator<<(DataBuffer& buffer, game::TilePtr tile) { void Packet::WritePacketID(DataBuffer& data, bool packetID) const {
buffer << tile->getType(); if (packetID)
switch (tile->getType()) { data << GetID();
}
static DataBuffer& operator<<(DataBuffer& buffer, game::TilePtr tile) {
buffer << tile->GetType();
switch (tile->GetType()) {
case game::TileType::Tower: { case game::TileType::Tower: {
const game::TowerTile* towerTile = (const game::TowerTile*)tile.get(); const game::TowerTile* towerTile = dynamic_cast<const game::TowerTile*>(tile.get());
buffer << towerTile->color_palette_ref << towerTile->team_owner; buffer << towerTile->color_palette_ref << towerTile->team_owner;
break; break;
} }
case game::TileType::Walk: { case game::TileType::Walk: {
const game::WalkableTile* walkTile = (const game::WalkableTile*)tile.get(); const game::WalkableTile* walkTile = dynamic_cast<const game::WalkableTile*>(tile.get());
buffer << walkTile->direction; buffer << walkTile->direction;
break; break;
} }
case game::TileType::Decoration: { case game::TileType::Decoration: {
const game::DecorationTile* decoTile = (const game::DecorationTile*)tile.get(); const game::DecorationTile* decoTile = dynamic_cast<const game::DecorationTile*>(tile.get());
buffer << decoTile->color_palette_ref; buffer << decoTile->color_palette_ref;
break; break;
} }
default: default:
break; break;
} }
return buffer; return buffer;
} }
DataBuffer& operator>>(DataBuffer& buffer, game::TilePtr& tile) { static DataBuffer& operator>>(DataBuffer& buffer, game::TilePtr& tile) {
game::TileType tileType; game::TileType tileType;
buffer >> tileType; buffer >> tileType;
switch (tileType) { switch (tileType) {
case game::TileType::Tower: { case game::TileType::Tower: {
std::shared_ptr<game::TowerTile> tilePtr = std::make_shared<game::TowerTile>(); auto tilePtr = std::make_shared<game::TowerTile>();
buffer >> tilePtr->color_palette_ref >> tilePtr->team_owner; buffer >> tilePtr->color_palette_ref >> tilePtr->team_owner;
tile = tilePtr; tile = tilePtr;
break; break;
} }
case game::TileType::Walk: { case game::TileType::Walk: {
std::shared_ptr<game::WalkableTile> tilePtr = std::make_shared<game::WalkableTile>(); auto tilePtr = std::make_shared<game::WalkableTile>();
buffer >> tilePtr->direction; buffer >> tilePtr->direction;
tile = tilePtr; tile = tilePtr;
break; break;
} }
case game::TileType::Decoration: { case game::TileType::Decoration: {
std::shared_ptr<game::DecorationTile> tilePtr = std::make_shared<game::DecorationTile>(); auto tilePtr = std::make_shared<game::DecorationTile>();
buffer >> tilePtr->color_palette_ref; buffer >> tilePtr->color_palette_ref;
tile = tilePtr; tile = tilePtr;
break; break;
@@ -67,9 +81,11 @@ DataBuffer& operator>>(DataBuffer& buffer, game::TilePtr& tile) {
return buffer; return buffer;
} }
DataBuffer PlayerLoginPacket::Serialize() const { DataBuffer PlayerLoginPacket::Serialize(bool packetID) const {
DataBuffer data; DataBuffer data;
data << getID() << m_PlayerName;
WritePacketID(data, packetID);
data << m_PlayerName;
return data; return data;
} }
@@ -77,66 +93,38 @@ void PlayerLoginPacket::Deserialize(DataBuffer& data) {
data >> m_PlayerName; data >> m_PlayerName;
} }
DataBuffer WorldBeginDataPacket::SerializeCustom() const { DataBuffer WorldBeginDataPacket::Serialize(bool packetID) const {
DataBuffer data; DataBuffer data;
const game::TowerTileColorPalette towerTilePalette = m_Header.m_TowerPlacePalette; const game::TowerTileColorPalette& towerTilePalette = m_Header.m_World->GetTowerTileColorPalette();
const std::vector<game::Color>& decoTilePalette = m_Header.m_DecorationPalette; const std::vector<game::Color>& decoTilePalette = m_Header.m_World->GetDecorationPalette();
data << getID() << towerTilePalette << m_Header.m_WalkablePalette WritePacketID(data, packetID);
<< (std::uint16_t)decoTilePalette.size();
data << towerTilePalette << m_Header.m_World->GetWalkableTileColor()
<< static_cast<std::uint16_t>(decoTilePalette.size());
// deco color palette // deco color palette
std::size_t bufferSize = data.GetSize(); std::size_t bufferSize = data.GetSize();
data.Resize(bufferSize + decoTilePalette.size() * sizeof(game::Color)); data.Resize(bufferSize + decoTilePalette.size() * sizeof(game::Color));
memcpy((std::uint8_t*)data.data() + bufferSize, decoTilePalette.data(), decoTilePalette.size() * sizeof(game::Color)); memcpy(reinterpret_cast<std::uint8_t*>(data.data()) + bufferSize, decoTilePalette.data(), decoTilePalette.size() * sizeof(game::Color));
const game::Spawn& redSpawn = m_Header.m_RedSpawn, blueSpawn = m_Header.m_BlueSpawn; data << m_Header.m_World->GetBackgroundColor();
const game::TeamCastle& redCastle = m_Header.m_RedCastle, blueCastle = m_Header.m_BlueCastle;
data << redSpawn << redCastle; const game::Spawn& redSpawn = m_Header.m_World->GetRedTeam().GetSpawn(), blueSpawn = m_Header.m_World->GetBlueTeam().GetSpawn();
data << blueSpawn << blueCastle; const game::TeamCastle& redCastle = m_Header.m_World->GetRedTeam().GetCastle(), blueCastle = m_Header.m_World->GetBlueTeam().GetCastle();
data << redSpawn << static_cast<utils::shape::Rectangle>(redCastle);
data << blueSpawn << static_cast<utils::shape::Rectangle>(blueCastle);
// tile palette // tile palette
data << m_Header.m_TilePalette.size(); data << static_cast<std::uint64_t>(m_Header.m_World->GetTilePalette().size());
for (game::TilePtr tile : m_Header.m_TilePalette) { for (game::TilePtr tile : m_Header.m_World->GetTilePalette()) {
data << tile; data << tile;
} }
data << m_Header.m_SpawnColorPalette; data << m_Header.m_World->GetSpawnColors();
return data;
}
DataBuffer WorldBeginDataPacket::Serialize() const {
DataBuffer data;
const game::TowerTileColorPalette towerTilePalette = m_Header.m_World->getTowerTileColorPalette();
const std::vector<game::Color>& decoTilePalette = m_Header.m_World->getDecorationPalette();
data << getID() << towerTilePalette << m_Header.m_World->getWalkableTileColor()
<< (std::uint16_t)decoTilePalette.size();
// deco color palette
std::size_t bufferSize = data.GetSize();
data.Resize(bufferSize + decoTilePalette.size() * sizeof(game::Color));
memcpy((std::uint8_t*)data.data() + bufferSize, decoTilePalette.data(), decoTilePalette.size() * sizeof(game::Color));
const game::Spawn& redSpawn = m_Header.m_World->getRedTeam().getSpawn(), blueSpawn = m_Header.m_World->getBlueTeam().getSpawn();
const game::TeamCastle& redCastle = m_Header.m_World->getRedTeam().getCastle(), blueCastle = m_Header.m_World->getBlueTeam().getCastle();
data << redSpawn << redCastle;
data << blueSpawn << blueCastle;
// tile palette
data << m_Header.m_World->getTilePalette().size();
for (game::TilePtr tile : m_Header.m_World->getTilePalette()) {
data << tile;
}
data << m_Header.m_World->getSpawnColors();
return data; return data;
} }
@@ -151,12 +139,19 @@ void WorldBeginDataPacket::Deserialize(DataBuffer& data) {
m_Header.m_DecorationPalette.resize(decoPaletteSize); m_Header.m_DecorationPalette.resize(decoPaletteSize);
memcpy((std::uint8_t*)m_Header.m_DecorationPalette.data(), data.data() + data.GetReadOffset(), decoPalletteSizeByte); memcpy(reinterpret_cast<std::uint8_t*>(m_Header.m_DecorationPalette.data()), data.data() + data.GetReadOffset(), decoPalletteSizeByte);
data.SetReadOffset(data.GetReadOffset() + decoPalletteSizeByte); data.SetReadOffset(data.GetReadOffset() + decoPalletteSizeByte);
data >> m_Header.m_RedSpawn >> m_Header.m_RedCastle; data >> m_Header.m_Background;
data >> m_Header.m_BlueSpawn >> m_Header.m_BlueCastle;
utils::shape::Rectangle redCastle, blueCastle;
data >> m_Header.m_RedSpawn >> redCastle;
data >> m_Header.m_BlueSpawn >> blueCastle;
m_Header.m_RedCastle.SetShape(redCastle);
m_Header.m_BlueCastle.SetShape(blueCastle);
std::uint64_t tilePaletteSize; std::uint64_t tilePaletteSize;
data >> tilePaletteSize; data >> tilePaletteSize;
@@ -174,35 +169,37 @@ void WorldBeginDataPacket::Deserialize(DataBuffer& data) {
typedef std::vector<uint64_t> ChunkPackedData; typedef std::vector<uint64_t> ChunkPackedData;
DataBuffer WorldDataPacket::SerializeCustom() const { DataBuffer WorldDataPacket::Serialize(bool packetID) const {
DataBuffer data; DataBuffer data;
data << getID() << m_WorldData.m_Chunks.size();
for (const auto& pair : m_WorldData.m_Chunks) { WritePacketID(data, packetID);
data << m_World->GetChunks().size();
for (const auto& pair : m_World->GetChunks()) {
game::ChunkCoord coords = pair.first; game::ChunkCoord coords = pair.first;
game::ChunkPtr chunk = pair.second; game::ChunkPtr chunk = pair.second;
data << coords.first << coords.second << (std::uint64_t)chunk->palette.size(); data << coords.x << coords.y << static_cast<std::uint64_t>(chunk->palette.size());
std::size_t bufferSize = data.GetSize(); std::size_t bufferSize = data.GetSize();
data.Resize(data.GetSize() + chunk->palette.size() * sizeof(game::ChunkPalette::value_type)); data.Resize(data.GetSize() + chunk->palette.size() * sizeof(game::ChunkPalette::value_type));
memcpy((std::uint8_t*)data.data() + bufferSize, chunk->palette.data(), chunk->palette.size() * sizeof(game::ChunkPalette::value_type)); memcpy(reinterpret_cast<std::uint8_t*>(data.data()) + bufferSize, chunk->palette.data(), chunk->palette.size() * sizeof(game::ChunkPalette::value_type));
std::uint8_t bitsPerTile = countBits(chunk->palette.size()); std::uint8_t bitsPerTile = countBits(chunk->palette.size());
game::ChunkData::value_type individualValueMask = ((1 << bitsPerTile) - 1); game::Chunk::ChunkData::value_type individualValueMask = ((1 << bitsPerTile) - 1);
ChunkPackedData chunkData(game::Chunk::ChunkSize / (BITS_IN_BYTE * sizeof(ChunkPackedData::value_type) / bitsPerTile), 0); ChunkPackedData chunkData(game::Chunk::ChunkSize / (BITS_IN_BYTE * sizeof(ChunkPackedData::value_type) / bitsPerTile), 0);
for (int tileNumber = 0; tileNumber < game::Chunk::ChunkSize; tileNumber++) { for (unsigned int tileNumber = 0; tileNumber < game::Chunk::ChunkSize; tileNumber++) {
int startLong = (tileNumber * bitsPerTile) / BITS_IN_LONG; std::size_t startLong = static_cast<std::size_t>((tileNumber * bitsPerTile) / BITS_IN_LONG);
int startOffset = (tileNumber * bitsPerTile) % BITS_IN_LONG; std::size_t startOffset = static_cast<std::size_t>((tileNumber * bitsPerTile) % BITS_IN_LONG);
int endLong = ((tileNumber + 1) * bitsPerTile - 1) / BITS_IN_LONG; std::size_t endLong = static_cast<std::size_t>(((tileNumber + 1) * bitsPerTile - 1) / BITS_IN_LONG);
std::uint64_t value = chunk->tiles[tileNumber]; std::uint64_t value = static_cast<std::uint64_t>(chunk->tiles[tileNumber]);
value &= individualValueMask; value &= individualValueMask;
chunkData[startLong] |= (value << startOffset); chunkData[startLong] |= (value << startOffset);
if (startLong != endLong) { if (startLong != endLong) {
@@ -212,50 +209,7 @@ DataBuffer WorldDataPacket::SerializeCustom() const {
bufferSize = data.GetSize(); bufferSize = data.GetSize();
data.Resize(data.GetSize() + chunkData.size() * sizeof(ChunkPackedData::value_type)); data.Resize(data.GetSize() + chunkData.size() * sizeof(ChunkPackedData::value_type));
memcpy((std::uint8_t*)data.data() + bufferSize, chunkData.data(), chunkData.size() * sizeof(ChunkPackedData::value_type)); memcpy(reinterpret_cast<std::uint8_t*>(data.data()) + bufferSize, chunkData.data(), chunkData.size() * sizeof(ChunkPackedData::value_type));
}
return data;
}
DataBuffer WorldDataPacket::Serialize() const {
DataBuffer data;
data << getID() << m_World->getChunks().size();
for (const auto& pair : m_World->getChunks()) {
game::ChunkCoord coords = pair.first;
game::ChunkPtr chunk = pair.second;
data << coords.first << coords.second << (std::uint64_t)chunk->palette.size();
std::size_t bufferSize = data.GetSize();
data.Resize(data.GetSize() + chunk->palette.size() * sizeof(game::ChunkPalette::value_type));
memcpy((std::uint8_t*)data.data() + bufferSize, chunk->palette.data(), chunk->palette.size() * sizeof(game::ChunkPalette::value_type));
std::uint8_t bitsPerTile = countBits(chunk->palette.size());
game::ChunkData::value_type individualValueMask = ((1 << bitsPerTile) - 1);
ChunkPackedData chunkData(game::Chunk::ChunkSize / (BITS_IN_BYTE * sizeof(ChunkPackedData::value_type) / bitsPerTile), 0);
for (int tileNumber = 0; tileNumber < game::Chunk::ChunkSize; tileNumber++) {
int startLong = (tileNumber * bitsPerTile) / BITS_IN_LONG;
int startOffset = (tileNumber * bitsPerTile) % BITS_IN_LONG;
int endLong = ((tileNumber + 1) * bitsPerTile - 1) / BITS_IN_LONG;
std::uint64_t value = chunk->tiles[tileNumber];
value &= individualValueMask;
chunkData[startLong] |= (value << startOffset);
if (startLong != endLong) {
chunkData[endLong] = (value >> (BITS_IN_LONG - startOffset));
}
}
bufferSize = data.GetSize();
data.Resize(data.GetSize() + chunkData.size() * sizeof(ChunkPackedData::value_type));
memcpy((std::uint8_t*)data.data() + bufferSize, chunkData.data(), chunkData.size() * sizeof(ChunkPackedData::value_type));
} }
return data; return data;
} }
@@ -267,7 +221,7 @@ void WorldDataPacket::Deserialize(DataBuffer& data) {
for (std::uint64_t chunkNumber = 0; chunkNumber < chunkCount; chunkNumber++) { for (std::uint64_t chunkNumber = 0; chunkNumber < chunkCount; chunkNumber++) {
game::ChunkPtr chunk = std::make_shared<game::Chunk>(); game::ChunkPtr chunk = std::make_shared<game::Chunk>();
game::ChunkCoord::first_type chunkX, chunkY; decltype(game::ChunkCoord::x) chunkX, chunkY;
data >> chunkX >> chunkY; data >> chunkX >> chunkY;
std::uint64_t chunkPaletteSize; std::uint64_t chunkPaletteSize;
@@ -275,7 +229,7 @@ void WorldDataPacket::Deserialize(DataBuffer& data) {
game::ChunkPalette chunkPalette(chunkPaletteSize); game::ChunkPalette chunkPalette(chunkPaletteSize);
memcpy((void*)chunkPalette.data(), data.data() + data.GetReadOffset(), chunkPaletteSize * sizeof(game::ChunkPalette::value_type)); memcpy(reinterpret_cast<void*>(chunkPalette.data()), data.data() + data.GetReadOffset(), chunkPaletteSize * sizeof(game::ChunkPalette::value_type));
data.SetReadOffset(data.GetReadOffset() + chunkPaletteSize * sizeof(game::ChunkPalette::value_type)); data.SetReadOffset(data.GetReadOffset() + chunkPaletteSize * sizeof(game::ChunkPalette::value_type));
chunk->palette = chunkPalette; chunk->palette = chunkPalette;
@@ -283,19 +237,19 @@ void WorldDataPacket::Deserialize(DataBuffer& data) {
std::uint8_t bitsPerTile = countBits(chunkPaletteSize); std::uint8_t bitsPerTile = countBits(chunkPaletteSize);
// A bitmask that contains bitsPerTile set bits // A bitmask that contains bitsPerTile set bits
game::ChunkData::value_type individualValueMask = ((1 << bitsPerTile) - 1); game::Chunk::ChunkData::value_type individualValueMask = ((1 << bitsPerTile) - 1);
ChunkPackedData chunkData(game::Chunk::ChunkSize / (BITS_IN_BYTE * sizeof(ChunkPackedData::value_type) / bitsPerTile), 0); ChunkPackedData chunkData(game::Chunk::ChunkSize / (BITS_IN_BYTE * sizeof(ChunkPackedData::value_type) / bitsPerTile), 0);
memcpy((void*)chunkData.data(), data.data() + data.GetReadOffset(), chunkData.size() * sizeof(ChunkPackedData::value_type)); memcpy(reinterpret_cast<void*>(chunkData.data()), data.data() + data.GetReadOffset(), chunkData.size() * sizeof(ChunkPackedData::value_type));
data.SetReadOffset(data.GetReadOffset() + chunkData.size() * sizeof(ChunkPackedData::value_type)); data.SetReadOffset(data.GetReadOffset() + chunkData.size() * sizeof(ChunkPackedData::value_type));
for (int tileNumber = 0; tileNumber < game::Chunk::ChunkSize; tileNumber++) { for (unsigned int tileNumber = 0; tileNumber < game::Chunk::ChunkSize; tileNumber++) {
int startLong = (tileNumber * bitsPerTile) / BITS_IN_LONG; std::size_t startLong = (tileNumber * bitsPerTile) / BITS_IN_LONG;
int startOffset = (tileNumber * bitsPerTile) % BITS_IN_LONG; std::size_t startOffset = (tileNumber * bitsPerTile) % BITS_IN_LONG;
int endLong = ((tileNumber + 1) * bitsPerTile - 1) / BITS_IN_LONG; std::size_t endLong = ((tileNumber + 1) * bitsPerTile - 1) / BITS_IN_LONG;
game::ChunkData::value_type value; game::Chunk::ChunkData::value_type value;
if (startLong == endLong) { if (startLong == endLong) {
value = (chunkData[startLong] >> startOffset); value = (chunkData[startLong] >> startOffset);
} else { } else {
@@ -312,9 +266,11 @@ void WorldDataPacket::Deserialize(DataBuffer& data) {
} }
} }
DataBuffer KeepAlivePacket::Serialize() const { DataBuffer KeepAlivePacket::Serialize(bool packetID) const {
DataBuffer data; DataBuffer data;
data << getID() << m_AliveID;
WritePacketID(data, packetID);
data << m_AliveID;
return data; return data;
} }
@@ -322,9 +278,11 @@ void KeepAlivePacket::Deserialize(DataBuffer& data) {
data >> m_AliveID; data >> m_AliveID;
} }
DataBuffer UpdateMoneyPacket::Serialize() const { DataBuffer UpdateMoneyPacket::Serialize(bool packetID) const {
DataBuffer data; DataBuffer data;
data << getID() << m_NewAmount;
WritePacketID(data, packetID);
data << m_NewAmount;
return data; return data;
} }
@@ -332,9 +290,11 @@ void UpdateMoneyPacket::Deserialize(DataBuffer& data) {
data >> m_NewAmount; data >> m_NewAmount;
} }
DataBuffer UpdateExpPacket::Serialize() const { DataBuffer UpdateExpPacket::Serialize(bool packetID) const {
DataBuffer data; DataBuffer data;
data << getID() << m_NewAmount;
WritePacketID(data, packetID);
data << m_NewAmount;
return data; return data;
} }
@@ -342,9 +302,11 @@ void UpdateExpPacket::Deserialize(DataBuffer& data) {
data >> m_NewAmount; data >> m_NewAmount;
} }
DataBuffer UpdateLobbyTimePacket::Serialize() const { DataBuffer UpdateLobbyTimePacket::Serialize(bool packetID) const {
DataBuffer data; DataBuffer data;
data << getID() << m_RemainingTime;
WritePacketID(data, packetID);
data << m_RemainingTime;
return data; return data;
} }
@@ -352,9 +314,11 @@ void UpdateLobbyTimePacket::Deserialize(DataBuffer& data) {
data >> m_RemainingTime; data >> m_RemainingTime;
} }
DataBuffer UpdateGameStatePacket::Serialize() const { DataBuffer UpdateGameStatePacket::Serialize(bool packetID) const {
DataBuffer data; DataBuffer data;
data << getID() << m_GameState;
WritePacketID(data, packetID);
data << m_GameState;
return data; return data;
} }
@@ -362,11 +326,13 @@ void UpdateGameStatePacket::Deserialize(DataBuffer& data) {
data >> m_GameState; data >> m_GameState;
} }
DataBuffer PlayerListPacket::Serialize() const { DataBuffer PlayerListPacket::Serialize(bool packetID) const {
DataBuffer data; DataBuffer data;
data << getID() << (std::uint8_t)m_Players.size();
for (auto pair : m_Players) { WritePacketID(data, packetID);
data << pair.first << pair.second.name << pair.second.team; data << static_cast<std::uint8_t>(m_Players.size());
for (auto [playerID, playerInfo] : m_Players) {
data << playerID << playerInfo.name << playerInfo.team;
} }
return data; return data;
} }
@@ -383,9 +349,11 @@ void PlayerListPacket::Deserialize(DataBuffer& data) {
} }
} }
DataBuffer PlayerJoinPacket::Serialize() const { DataBuffer PlayerJoinPacket::Serialize(bool packetID) const {
DataBuffer data; DataBuffer data;
data << getID() << m_PlayerID << m_PlayerName;
WritePacketID(data, packetID);
data << m_PlayerID << m_PlayerName;
return data; return data;
} }
@@ -393,9 +361,11 @@ void PlayerJoinPacket::Deserialize(DataBuffer& data) {
data >> m_PlayerID >> m_PlayerName; data >> m_PlayerID >> m_PlayerName;
} }
DataBuffer PlayerLeavePacket::Serialize() const { DataBuffer PlayerLeavePacket::Serialize(bool packetID) const {
DataBuffer data; DataBuffer data;
data << getID() << m_PlayerID;
WritePacketID(data, packetID);
data << m_PlayerID;
return data; return data;
} }
@@ -403,9 +373,11 @@ void PlayerLeavePacket::Deserialize(DataBuffer& data) {
data >> m_PlayerID; data >> m_PlayerID;
} }
DataBuffer ConnexionInfoPacket::Serialize() const { DataBuffer ConnexionInfoPacket::Serialize(bool packetID) const {
DataBuffer data; DataBuffer data;
data << getID() << m_ConnectionID;
WritePacketID(data, packetID);
data << m_ConnectionID;
return data; return data;
} }
@@ -413,9 +385,11 @@ void ConnexionInfoPacket::Deserialize(DataBuffer& data) {
data >> m_ConnectionID; data >> m_ConnectionID;
} }
DataBuffer SelectTeamPacket::Serialize() const { DataBuffer SelectTeamPacket::Serialize(bool packetID) const {
DataBuffer data; DataBuffer data;
data << getID() << m_SelectedTeam;
WritePacketID(data, packetID);
data << m_SelectedTeam;
return data; return data;
} }
@@ -423,9 +397,11 @@ void SelectTeamPacket::Deserialize(DataBuffer& data) {
data >> m_SelectedTeam; data >> m_SelectedTeam;
} }
DataBuffer UpdatePlayerTeamPacket::Serialize() const { DataBuffer UpdatePlayerTeamPacket::Serialize(bool packetID) const {
DataBuffer data; DataBuffer data;
data << getID() << m_PlayerID << m_SelectedTeam;
WritePacketID(data, packetID);
data << m_PlayerID << m_SelectedTeam;
return data; return data;
} }
@@ -433,9 +409,11 @@ void UpdatePlayerTeamPacket::Deserialize(DataBuffer& data) {
data >> m_PlayerID >> m_SelectedTeam; data >> m_PlayerID >> m_SelectedTeam;
} }
DataBuffer DisconnectPacket::Serialize() const { DataBuffer DisconnectPacket::Serialize(bool packetID) const {
DataBuffer data; DataBuffer data;
data << getID() << m_Reason;
WritePacketID(data, packetID);
data << m_Reason;
return data; return data;
} }
@@ -443,9 +421,11 @@ void DisconnectPacket::Deserialize(DataBuffer& data) {
data >> m_Reason; data >> m_Reason;
} }
DataBuffer ServerTpsPacket::Serialize() const { DataBuffer ServerTpsPacket::Serialize(bool packetID) const {
DataBuffer data; DataBuffer data;
data << getID() << m_TPS << m_PacketSendTime;
WritePacketID(data, packetID);
data << m_TPS << m_PacketSendTime;
return data; return data;
} }
@@ -453,9 +433,11 @@ void ServerTpsPacket::Deserialize(DataBuffer& data) {
data >> m_TPS >> m_PacketSendTime; data >> m_TPS >> m_PacketSendTime;
} }
DataBuffer SpawnMobPacket::Serialize() const { DataBuffer SpawnMobPacket::Serialize(bool packetID) const {
DataBuffer data; DataBuffer data;
data << getID() << m_MobID << m_MobType << m_MobLevel << m_MobDirection
WritePacketID(data, packetID);
data << m_MobID << m_MobType << m_MobLevel << m_MobDirection
<< m_Sender << m_MobX << m_MobY; << m_Sender << m_MobX << m_MobY;
return data; return data;
} }
@@ -465,9 +447,11 @@ void SpawnMobPacket::Deserialize(DataBuffer& data) {
>> m_Sender >> m_MobX >> m_MobY; >> m_Sender >> m_MobX >> m_MobY;
} }
DataBuffer PlaceTowerPacket::Serialize() const { DataBuffer PlaceTowerPacket::Serialize(bool packetID) const {
DataBuffer data; DataBuffer data;
data << getID() << m_TowerX << m_TowerY << m_TowerType;
WritePacketID(data, packetID);
data << m_TowerX << m_TowerY << m_TowerType;
return data; return data;
} }
@@ -475,9 +459,11 @@ void PlaceTowerPacket::Deserialize(DataBuffer& data) {
data >> m_TowerX >> m_TowerY >> m_TowerType; data >> m_TowerX >> m_TowerY >> m_TowerType;
} }
DataBuffer WorldAddTowerPacket::Serialize() const { DataBuffer WorldAddTowerPacket::Serialize(bool packetID) const {
DataBuffer data; DataBuffer data;
data << getID() << m_TowerID << m_TowerX << m_TowerY << m_TowerType << m_Builder;
WritePacketID(data, packetID);
data << m_TowerID << m_TowerX << m_TowerY << m_TowerType << m_Builder;
return data; return data;
} }
@@ -485,38 +471,42 @@ void WorldAddTowerPacket::Deserialize(DataBuffer& data) {
data >> m_TowerID >> m_TowerX >> m_TowerY >> m_TowerType >> m_Builder; data >> m_TowerID >> m_TowerX >> m_TowerY >> m_TowerType >> m_Builder;
} }
DataBuffer WorldRemoveTowerPacket::Serialize() const { DataBuffer RemoveTowerPacket::Serialize(bool packetID) const {
DataBuffer data; DataBuffer data;
data << getID() << m_TowerID;
WritePacketID(data, packetID);
data << m_TowerID;
return data; return data;
} }
void WorldRemoveTowerPacket::Deserialize(DataBuffer& data) { void RemoveTowerPacket::Deserialize(DataBuffer& data) {
data >> m_TowerID; data >> m_TowerID;
} }
DataBuffer SendMobsPacket::Serialize() const { DataBuffer SendMobsPacket::Serialize(bool packetID) const {
DataBuffer data; DataBuffer data;
data << getID() << static_cast<std::uint8_t>(m_MobSends.size());
for(const MobSend& mobSend : m_MobSends){ WritePacketID(data, packetID);
data << mobSend; data << static_cast<std::uint8_t>(m_MobSends.size());
}
data.WriteSome(reinterpret_cast<const std::uint8_t*>(m_MobSends.data()), m_MobSends.size() * sizeof(m_MobSends));
return data; return data;
} }
void SendMobsPacket::Deserialize(DataBuffer& data) { void SendMobsPacket::Deserialize(DataBuffer& data) {
std::uint8_t mobSendCount; std::uint8_t mobSendCount;
data >> mobSendCount; data >> mobSendCount;
protocol::MobSend mobSend;
for(int i = 0; i < mobSendCount; i++){ m_MobSends.resize(mobSendCount);
data >> mobSend; data.ReadSome(reinterpret_cast<std::uint8_t*>(m_MobSends.data()), mobSendCount * sizeof(MobSend));
m_MobSends.push_back(mobSend);
}
} }
DataBuffer UpgradeTowerPacket::Serialize() const { DataBuffer UpgradeTowerPacket::Serialize(bool packetID) const {
DataBuffer data; DataBuffer data;
data << getID() << m_TowerID << m_TowerLevel;
WritePacketID(data, packetID);
data << m_TowerID << m_TowerLevel;
return data; return data;
} }
@@ -524,28 +514,86 @@ void UpgradeTowerPacket::Deserialize(DataBuffer& data) {
data >> m_TowerID >> m_TowerLevel; data >> m_TowerID >> m_TowerLevel;
} }
REGISTER_DISPATCH_CLASS(PlayerLoginPacket); DataBuffer UpdateCastleLifePacket::Serialize(bool packetID) const {
REGISTER_DISPATCH_CLASS(WorldBeginDataPacket); DataBuffer data;
REGISTER_DISPATCH_CLASS(WorldDataPacket);
REGISTER_DISPATCH_CLASS(KeepAlivePacket); WritePacketID(data, packetID);
REGISTER_DISPATCH_CLASS(UpdateExpPacket); data << m_CastleLife << m_Team;
REGISTER_DISPATCH_CLASS(UpdateMoneyPacket); return data;
REGISTER_DISPATCH_CLASS(UpdateLobbyTimePacket); }
REGISTER_DISPATCH_CLASS(UpdateGameStatePacket);
REGISTER_DISPATCH_CLASS(PlayerListPacket); void UpdateCastleLifePacket::Deserialize(DataBuffer& data) {
REGISTER_DISPATCH_CLASS(PlayerJoinPacket); data >> m_CastleLife >> m_Team;
REGISTER_DISPATCH_CLASS(PlayerLeavePacket); }
REGISTER_DISPATCH_CLASS(ConnexionInfoPacket);
REGISTER_DISPATCH_CLASS(SelectTeamPacket); DataBuffer UpdateMobStatesPacket::Serialize(bool packetID) const {
REGISTER_DISPATCH_CLASS(UpdatePlayerTeamPacket); DataBuffer data;
REGISTER_DISPATCH_CLASS(DisconnectPacket);
REGISTER_DISPATCH_CLASS(ServerTpsPacket); WritePacketID(data, packetID);
REGISTER_DISPATCH_CLASS(SpawnMobPacket); data << static_cast<std::uint64_t>(m_MobStates.size());
REGISTER_DISPATCH_CLASS(PlaceTowerPacket);
REGISTER_DISPATCH_CLASS(WorldAddTowerPacket); data.WriteSome(reinterpret_cast<const std::uint8_t*>(m_MobStates.data()), m_MobStates.size() * sizeof(MobState));
REGISTER_DISPATCH_CLASS(WorldRemoveTowerPacket); return data;
REGISTER_DISPATCH_CLASS(SendMobsPacket); }
REGISTER_DISPATCH_CLASS(UpgradeTowerPacket);
void UpdateMobStatesPacket::Deserialize(DataBuffer& data) {
std::uint64_t mobCount;
data >> mobCount;
m_MobStates.resize(mobCount);
data.ReadSome(reinterpret_cast<std::uint8_t*>(m_MobStates.data()), mobCount * sizeof(MobState));
}
DataBuffer PlayerBuyItemPacket::Serialize(bool packetID) const {
DataBuffer data;
WritePacketID(data, packetID);
data << m_ItemType << m_Count;
return data;
}
void PlayerBuyItemPacket::Deserialize(DataBuffer& data) {
data >> m_ItemType >> m_Count;
}
DataBuffer PlayerBuyMobUpgradePacket::Serialize(bool packetID) const {
DataBuffer data;
WritePacketID(data, packetID);
data << m_MobType << m_MobLevel;
return data;
}
void PlayerBuyMobUpgradePacket::Deserialize(DataBuffer& data) {
data >> m_MobType >> m_MobLevel;
}
REGISTER_DISPATCH_CLASS(PlayerLoginPacket)
REGISTER_DISPATCH_CLASS(WorldBeginDataPacket)
REGISTER_DISPATCH_CLASS(WorldDataPacket)
REGISTER_DISPATCH_CLASS(KeepAlivePacket)
REGISTER_DISPATCH_CLASS(UpdateExpPacket)
REGISTER_DISPATCH_CLASS(UpdateMoneyPacket)
REGISTER_DISPATCH_CLASS(UpdateLobbyTimePacket)
REGISTER_DISPATCH_CLASS(UpdateGameStatePacket)
REGISTER_DISPATCH_CLASS(PlayerListPacket)
REGISTER_DISPATCH_CLASS(PlayerJoinPacket)
REGISTER_DISPATCH_CLASS(PlayerLeavePacket)
REGISTER_DISPATCH_CLASS(ConnexionInfoPacket)
REGISTER_DISPATCH_CLASS(SelectTeamPacket)
REGISTER_DISPATCH_CLASS(UpdatePlayerTeamPacket)
REGISTER_DISPATCH_CLASS(DisconnectPacket)
REGISTER_DISPATCH_CLASS(ServerTpsPacket)
REGISTER_DISPATCH_CLASS(SpawnMobPacket)
REGISTER_DISPATCH_CLASS(PlaceTowerPacket)
REGISTER_DISPATCH_CLASS(WorldAddTowerPacket)
REGISTER_DISPATCH_CLASS(RemoveTowerPacket)
REGISTER_DISPATCH_CLASS(SendMobsPacket)
REGISTER_DISPATCH_CLASS(UpgradeTowerPacket)
REGISTER_DISPATCH_CLASS(UpdateCastleLifePacket)
REGISTER_DISPATCH_CLASS(UpdateMobStatesPacket)
REGISTER_DISPATCH_CLASS(PlayerBuyItemPacket)
REGISTER_DISPATCH_CLASS(PlayerBuyMobUpgradePacket)
} // namespace protocol } // namespace protocol
} // namespace td } // namespace td

View File

@@ -5,9 +5,6 @@
* Author: simon * Author: simon
*/ */
#ifndef ANDROID
#include <glbinding/Binding.h>
#endif
#include "render/Renderer.h" #include "render/Renderer.h"
#include "render/GL.h" #include "render/GL.h"
#include <stdio.h> #include <stdio.h>
@@ -17,7 +14,7 @@
namespace td { namespace td {
namespace render { namespace render {
Renderer::Renderer() { Renderer::Renderer() : m_BackgroundColor(0, 0, 0) {
} }
@@ -25,53 +22,61 @@ Renderer::~Renderer() {
} }
void Renderer::updateIsometricView() { void Renderer::UpdateIsometricView() {
float isometricEased = utils::easeInOutExpo(m_IsometricShade); float isometricEased = utils::EaseInOutExpo(m_IsometricShade);
m_WorldShader->start(); m_WorldShader->Start();
m_WorldShader->setIsometricView(isometricEased); m_WorldShader->SetIsometricView(isometricEased);
m_EntityShader->start(); m_EntityShader->Start();
m_EntityShader->setIsometricView(isometricEased); m_EntityShader->SetIsometricView(isometricEased);
} }
void Renderer::initShader() { void Renderer::InitShaders() {
m_WorldShader = std::make_unique<WorldShader>(); m_WorldShader = std::make_unique<shader::WorldShader>();
m_WorldShader->loadShader(); m_WorldShader->LoadShader();
m_EntityShader = std::make_unique<EntityShader>(); m_EntityShader = std::make_unique<shader::EntityShader>();
m_EntityShader->loadShader(); m_EntityShader->LoadShader();
setIsometricView(true); SetIsometricView(true);
updateIsometricView(); UpdateIsometricView();
} }
bool Renderer::init() { bool Renderer::Init() {
#ifndef ANDROID #if __has_include(<glbinding/glbinding.h>)
glbinding::initialize();
#elif __has_include(<GL/glew.h>)
glewInit();
#elif __has_include(<glad/glad.h>)
gladLoadGL();
#elif __has_include(<GL/gl3w.h>)
gl3wInit();
#elif __has_include(<glbinding/Binding.h>)
glbinding::Binding::initialize(); glbinding::Binding::initialize();
#endif #endif
glEnable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND); glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
initShader(); InitShaders();
return true; return true;
} }
void Renderer::renderVAO(const GL::VertexArray& vao) { void Renderer::RenderVAO(const GL::VertexArray& vao) {
m_WorldShader->start(); m_WorldShader->Start();
vao.bind(); vao.Bind();
glDrawArrays(GL_TRIANGLES, 0, vao.getVertexCount()); glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(vao.GetVertexCount()));
vao.unbind(); vao.Unbind();
} }
void Renderer::renderModel(const Model& model) { void Renderer::RenderModel(const Model& model) {
m_EntityShader->start(); m_EntityShader->Start();
m_EntityShader->setModelPos(model.positon); m_EntityShader->SetModelPos(model.positon);
model.vao->bind(); model.vao->Bind();
glDrawArrays(GL_TRIANGLES, 0, model.vao->getVertexCount()); glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(model.vao->GetVertexCount()));
model.vao->unbind(); model.vao->Unbind();
} }
void Renderer::updateIsometricFade() { void Renderer::UpdateIsometricFade() {
static std::uint64_t lastTime = utils::getTime(); static std::uint64_t lastTime = utils::GetTime();
if (m_IsometricShade != (float)m_IsometricView) { if (m_IsometricShade != static_cast<float>(m_IsometricView)) {
float step = (float)(utils::getTime() - lastTime) / 1000.0f * m_AnimationSpeed; float step = static_cast<float>(utils::GetTime() - lastTime) / 1000.0f * m_AnimationSpeed;
if (m_IsometricShade < m_IsometricView) { if (m_IsometricShade < m_IsometricView) {
m_IsometricShade += step; m_IsometricShade += step;
} else { } else {
@@ -79,52 +84,52 @@ void Renderer::updateIsometricFade() {
} }
m_IsometricShade = std::min(m_IsometricShade, 1.0f); m_IsometricShade = std::min(m_IsometricShade, 1.0f);
m_IsometricShade = std::max(m_IsometricShade, 0.0f); m_IsometricShade = std::max(m_IsometricShade, 0.0f);
updateIsometricView(); UpdateIsometricView();
} }
lastTime = utils::getTime(); lastTime = utils::GetTime();
} }
void Renderer::prepare() { void Renderer::Prepare() {
glClear(GL_COLOR_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT);
glClearColor(0, 0, 0, 0); glClearColor(m_BackgroundColor.r, m_BackgroundColor.g, m_BackgroundColor.b, 0);
updateIsometricFade(); UpdateIsometricFade();
} }
void Renderer::resize(int width, int height) { void Renderer::Resize(int width, int height) {
m_WorldShader->start(); m_WorldShader->Start();
m_WorldShader->setAspectRatio((float)width / height); m_WorldShader->SetAspectRatio(static_cast<float>(width) / height);
m_EntityShader->start(); m_EntityShader->Start();
m_EntityShader->setAspectRatio((float)width / height); m_EntityShader->SetAspectRatio(static_cast<float>(width) / height);
glViewport(0, 0, width, height); glViewport(0, 0, width, height);
} }
void Renderer::setZoom(float zoom) { void Renderer::SetZoom(float zoom) {
m_WorldShader->start(); m_WorldShader->Start();
m_WorldShader->setZoom(zoom); m_WorldShader->SetZoom(zoom);
m_EntityShader->start(); m_EntityShader->Start();
m_EntityShader->setZoom(zoom); m_EntityShader->SetZoom(zoom);
} }
void Renderer::setCamMovement(const glm::vec2& mov) { void Renderer::SetCamMovement(const glm::vec2& mov) {
m_CamPos.x += mov.x * (1 - m_IsometricView) + (0.5 * mov.x - mov.y) * m_IsometricView; m_CamPos.x += mov.x * (1 - m_IsometricView) + (0.5 * mov.x - mov.y) * m_IsometricView;
m_CamPos.y += -mov.y * (1 - m_IsometricView) + (-0.5 * mov.x - mov.y) * m_IsometricView; m_CamPos.y += -mov.y * (1 - m_IsometricView) + (-0.5 * mov.x - mov.y) * m_IsometricView;
setCamPos(m_CamPos); SetCamPos(m_CamPos);
} }
void Renderer::setCamPos(const glm::vec2& newPos) { void Renderer::SetCamPos(const glm::vec2& newPos) {
m_CamPos = newPos; m_CamPos = newPos;
m_WorldShader->start(); m_WorldShader->Start();
m_WorldShader->setCamPos(newPos); m_WorldShader->SetCamPos(newPos);
m_EntityShader->start(); m_EntityShader->Start();
m_EntityShader->setCamPos(newPos); m_EntityShader->SetCamPos(newPos);
} }
void Renderer::setIsometricView(bool isometric) { void Renderer::SetIsometricView(bool isometric) {
m_IsometricView = isometric; m_IsometricView = isometric;
} }
glm::vec2 Renderer::getCursorWorldPos(const glm::vec2& cursorPos, float aspectRatio, float zoom, float windowWidth, float windowHeight) { glm::vec2 Renderer::GetCursorWorldPos(const glm::vec2& cursorPos, float aspectRatio, float zoom, float windowWidth, float windowHeight) {
float isometricEased = utils::easeInOutExpo(m_IsometricShade); float isometricEased = utils::EaseInOutExpo(m_IsometricShade);
float relativeX = (cursorPos.x / windowWidth * 2) - 1; float relativeX = (cursorPos.x / windowWidth * 2) - 1;
float relativeY = (cursorPos.y / windowHeight * 2) - 1; float relativeY = (cursorPos.y / windowHeight * 2) - 1;

View File

@@ -4,53 +4,50 @@
namespace td { namespace td {
namespace render { namespace render {
void VertexCache::addData(std::uint64_t index, std::vector<float> positions, std::vector<float> colors) { void VertexCache::AddData(std::uint64_t index, std::vector<float> positions, std::vector<float> colors) {
ElementsIndex positionsIndexes; m_Indexes.insert({ index, {positions, colors} });
positionsIndexes.first = m_Positions.end(); m_VertexCount += colors.size(); // one color per vertex
m_Positions.insert(m_Positions.end(), positions.begin(), positions.end());
positionsIndexes.second = m_Positions.end() - 1;
ElementsIndex colorsIndexes;
colorsIndexes.first = m_Colors.end();
m_Colors.insert(m_Colors.end(), colors.begin(), colors.end());
colorsIndexes.second = m_Colors.end() - 1;
m_Indexes.insert({ index, {positionsIndexes, colorsIndexes} });
} }
void VertexCache::removeData(std::uint64_t index) { void VertexCache::RemoveData(std::uint64_t index) {
auto it = m_Indexes.find(index); auto it = m_Indexes.find(index);
if (it != m_Indexes.end()) { if (it != m_Indexes.end()) {
DataIndex indexes = it->second;
ElementsIndex positionsIndexes = indexes.first;
ElementsIndex colorsIndexes = indexes.second;
m_Positions.erase(positionsIndexes.first, positionsIndexes.second);
m_Colors.erase(colorsIndexes.first, colorsIndexes.second);
m_Indexes.erase(it); m_Indexes.erase(it);
m_VertexCount -= it->second.color.size(); // one color per vertex
} }
} }
void VertexCache::clear() { void VertexCache::Clear() {
m_Positions.clear();
m_Colors.clear();
m_Indexes.clear(); m_Indexes.clear();
m_VertexCount = 0;
} }
void VertexCache::updateVertexArray() { void VertexCache::UpdateVertexArray() {
m_VertexArray = std::make_unique<GL::VertexArray>(m_Colors.size()); // one color per vertex m_VertexArray = std::make_unique<GL::VertexArray>(m_VertexCount); // one color per vertex
GL::VertexBuffer positionsBuffer(m_Positions, 2); Vector positions;
positionsBuffer.addVertexAttribPointer(0, 2, 0); positions.reserve(m_VertexCount * 2);
GL::VertexBuffer colorsBuffer(m_Colors, 1); Vector colors;
colorsBuffer.addVertexAttribPointer(1, 1, 0); colors.reserve(m_VertexCount);
m_VertexArray->bind(); for (auto it = m_Indexes.begin(); it != m_Indexes.end(); it++) {
m_VertexArray->bindVertexBuffer(positionsBuffer); const DataIndex& data = it->second;
m_VertexArray->bindVertexBuffer(colorsBuffer);
m_VertexArray->unbind(); positions.insert(positions.end(), data.position.begin(), data.position.end());
colors.insert(colors.end(), data.color.begin(), data.color.end());
}
GL::VertexBuffer positionsBuffer(positions, 2);
positionsBuffer.AddVertexAttribPointer(0, 2, 0);
GL::VertexBuffer colorsBuffer(colors, 1);
colorsBuffer.AddVertexAttribPointer(1, 1, 0);
m_VertexArray->Bind();
m_VertexArray->BindVertexBuffer(positionsBuffer);
m_VertexArray->BindVertexBuffer(colorsBuffer);
m_VertexArray->Unbind();
} }
} // namespace render } // namespace render

View File

@@ -6,13 +6,12 @@
#include "window/Display.h" #include "window/Display.h"
#include "game/client/ClientGame.h" #include "game/client/ClientGame.h"
#include "game/client/Client.h" #include "game/client/Client.h"
#include "misc/Format.h"
#include <iostream>
namespace td { namespace td {
namespace render { namespace render {
ImVec4 WorldRenderer::getImGuiTeamColor(game::TeamColor color) { ImVec4 WorldRenderer::GetImGuiTeamColor(game::TeamColor color) {
switch (color) { switch (color) {
case td::game::TeamColor::None: case td::game::TeamColor::None:
break; break;
@@ -24,39 +23,41 @@ ImVec4 WorldRenderer::getImGuiTeamColor(game::TeamColor color) {
return ImVec4(1, 1, 1, 1); return ImVec4(1, 1, 1, 1);
} }
void WorldRenderer::loadModels() { void WorldRenderer::LoadModels() {
std::cout << "World Created !\n"; utils::LOGD("World Created !");
m_WorldVao = std::make_unique<GL::VertexArray>(std::move(WorldLoader::loadWorldModel(m_World))); m_WorldVao = std::make_unique<GL::VertexArray>(std::move(WorldLoader::LoadWorldModel(m_World)));
m_MobVao = std::make_unique<GL::VertexArray>(std::move(WorldLoader::loadMobModel())); m_MobVao = std::make_unique<GL::VertexArray>(std::move(WorldLoader::LoadMobModel()));
m_SelectTileVao = std::make_unique<GL::VertexArray>(std::move(WorldLoader::loadTileSelectModel())); m_SelectTileVao = std::make_unique<GL::VertexArray>(std::move(WorldLoader::LoadTileSelectModel()));
std::cout << "Vertex Count : " << m_WorldVao->getVertexCount() << std::endl; utils::LOGD(utils::format("Vertex Count : %u", m_WorldVao->GetVertexCount()));
} }
WorldRenderer::WorldRenderer(game::World* world, client::ClientGame* client) : m_Client(client), m_Renderer(m_Client->getRenderer()), m_World(world), m_Zoom(0.1) { WorldRenderer::WorldRenderer(game::World* world, client::ClientGame* client) : m_Client(client), m_Renderer(m_Client->GetRenderer()), m_World(world), m_Zoom(0.1) {
m_Renderer->setZoom(m_Zoom); m_Renderer->SetZoom(m_Zoom);
m_Renderer->setCamMovement({}); m_Renderer->SetCamMovement({});
m_TowerPlacePopup = std::make_unique<gui::TowerPlacePopup>(m_Client->getClient()); m_TowerPlacePopup = std::make_unique<gui::TowerPlacePopup>(m_Client->GetClient());
m_MobTooltip = std::make_unique<gui::MobTooltip>(m_Client->getClient()); m_MobTooltip = std::make_unique<gui::MobTooltip>(m_Client->GetClient());
m_CastleTooltip = std::make_unique<gui::CastleTooltip>(m_Client->GetClient());
m_Client->GetWorldClient().GetWorldNotifier().BindListener(this);
} }
void WorldRenderer::updateCursorPos() { void WorldRenderer::UpdateCursorPos() {
m_CursorPos = getCursorWorldPos(); m_CursorPos = GetCursorWorldPos();
} }
void WorldRenderer::update() { void WorldRenderer::Update() {
if (m_WorldVao == nullptr) if (m_WorldVao == nullptr)
return; return;
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
if (io.MouseDown[0] && !ImGui::IsAnyItemActive()) { if (io.MouseDown[0] && !ImGui::IsAnyItemActive()) {
ImVec2 mouseDelta = ImGui::GetIO().MouseDelta; ImVec2 mouseDelta = ImGui::GetIO().MouseDelta;
const float relativeX = mouseDelta.x / (float)Display::getWindowWidth() * 2; const float relativeX = mouseDelta.x / (float)Display::GetWindowWidth() * 2;
const float relativeY = mouseDelta.y / (float)Display::getWindowHeight() * 2; const float relativeY = mouseDelta.y / (float)Display::GetWindowHeight() * 2;
moveCam(relativeX, relativeY, Display::getAspectRatio()); MoveCam(relativeX, relativeY, Display::GetAspectRatio());
} }
if (io.MouseWheel != 0) { if (io.MouseWheel != 0) {
changeZoom(io.MouseWheel); ChangeZoom(io.MouseWheel);
} }
updateCursorPos(); UpdateCursorPos();
if (ImGui::IsMouseClicked(0)) { if (ImGui::IsMouseClicked(0)) {
if (!m_PopupOpened) { if (!m_PopupOpened) {
m_HoldCursorPos = { io.MousePos.x, io.MousePos.y }; m_HoldCursorPos = { io.MousePos.x, io.MousePos.y };
@@ -64,66 +65,85 @@ void WorldRenderer::update() {
m_PopupOpened = false; m_PopupOpened = false;
} }
} }
if (ImGui::IsMouseDoubleClicked(1)) RemoveTower();
} }
void WorldRenderer::renderWorld() const { void WorldRenderer::RemoveTower() {
m_Renderer->renderVAO(*m_WorldVao); glm::vec2 cursorPos = GetCursorWorldPos();
game::TowerPtr clickedTower = m_World->GetTower(cursorPos);
if (clickedTower != nullptr) {
m_Client->GetClient()->RemoveTower(clickedTower->GetID());
}
} }
void WorldRenderer::renderMobs() const { void WorldRenderer::RenderWorld() const {
for (game::MobPtr mob : m_World->getMobList()) { m_Renderer->RenderVAO(*m_WorldVao);
}
void WorldRenderer::RenderMobs() const {
for (game::MobPtr mob : m_World->GetMobList()) {
Renderer::Model model; Renderer::Model model;
model.vao = m_MobVao.get(); model.vao = m_MobVao.get();
model.positon = { mob->getX(), mob->getY() }; model.positon = { mob->GetCenterX(), mob->GetCenterY() };
m_Renderer->renderModel(model); m_Renderer->RenderModel(model);
} }
} }
void WorldRenderer::renderTowers() const { void WorldRenderer::RenderTowers() const {
if (!m_TowersCache.isEmpty()) if (!m_TowersCache.IsEmpty())
m_Renderer->renderVAO(m_TowersCache.getVertexArray()); m_Renderer->RenderVAO(m_TowersCache.GetVertexArray());
} }
void WorldRenderer::renderTileSelect() const { void WorldRenderer::RenderTileSelect() const {
if (ImGui::IsAnyItemHovered()) return; if (ImGui::IsAnyItemHovered()) return;
if (m_MobTooltip->IsShown() || m_CastleTooltip->IsShown()) return;
Renderer::Model tileSelectModel; Renderer::Model tileSelectModel;
tileSelectModel.vao = m_SelectTileVao.get(); tileSelectModel.vao = m_SelectTileVao.get();
tileSelectModel.positon = { (int)m_CursorPos.x, (int)m_CursorPos.y }; tileSelectModel.positon = { (int)m_CursorPos.x, (int)m_CursorPos.y };
m_Renderer->renderModel(tileSelectModel); m_Renderer->RenderModel(tileSelectModel);
} }
void WorldRenderer::renderPopups() { void WorldRenderer::RenderPopups() {
m_TowerPlacePopup->render(); m_TowerPlacePopup->Render();
renderTowerUpgradePopup(); RenderTowerUpgradePopup();
} }
void WorldRenderer::render() { void WorldRenderer::Render() {
if (m_WorldVao == nullptr) if (m_WorldVao == nullptr)
return; return;
renderWorld(); RenderWorld();
renderMobs(); RenderMobs();
renderTowers(); RenderTowers();
renderTileSelect(); RenderTileSelect();
renderMobTooltip(); RenderTooltips();
renderPopups(); RenderPopups();
detectClick(); DetectClick();
} }
WorldRenderer::~WorldRenderer() { WorldRenderer::~WorldRenderer() {
} }
void WorldRenderer::moveCam(float relativeX, float relativeY, float aspectRatio) { void WorldRenderer::RenderTooltips() const {
RenderMobTooltip();
RenderCastleTooltip();
}
void WorldRenderer::MoveCam(float relativeX, float relativeY, float aspectRatio) {
if (m_WorldVao == nullptr) if (m_WorldVao == nullptr)
return; return;
float movementX = -relativeX / m_Zoom * aspectRatio; float movementX = -relativeX / m_Zoom * aspectRatio;
float movementY = relativeY / m_Zoom; float movementY = relativeY / m_Zoom;
m_Renderer->setCamMovement({ movementX, movementY }); m_Renderer->SetCamMovement({ movementX, movementY });
} }
void WorldRenderer::changeZoom(float zoomStep) { void WorldRenderer::ChangeZoom(float zoomStep) {
if (m_WorldVao == nullptr) if (m_WorldVao == nullptr)
return; return;
static float sensibility = 1.5f; static float sensibility = 1.5f;
@@ -132,34 +152,34 @@ void WorldRenderer::changeZoom(float zoomStep) {
} else { } else {
m_Zoom *= zoomStep * sensibility; m_Zoom *= zoomStep * sensibility;
} }
m_Renderer->setZoom(m_Zoom); m_Renderer->SetZoom(m_Zoom);
m_Renderer->setCamMovement({}); m_Renderer->SetCamMovement({});
} }
void WorldRenderer::click() { void WorldRenderer::Click() {
const game::TowerPtr tower = m_Client->getWorld().getTower(getClickWorldPos()); const game::TowerPtr tower = m_Client->GetWorld().GetTower(GetClickWorldPos());
m_TowerPlacePopup->setClickPos(getClickWorldPos()); m_TowerPlacePopup->SetClickPos(GetClickWorldPos());
if (tower != nullptr) { // there is a tower here if (tower != nullptr) { // there is a tower here
ImGui::OpenPopup("TowerUpgrade"); ImGui::OpenPopup("TowerUpgrade");
} else if (m_Client->getWorld().CanPlaceLittleTower(getClickWorldPos(), m_Client->getPlayer()->getID())) { } else if (m_Client->GetWorld().CanPlaceLittleTower(GetClickWorldPos(), m_Client->GetPlayer()->GetID())) {
ImGui::OpenPopup("TowerPlace"); ImGui::OpenPopup("TowerPlace");
} }
} }
void WorldRenderer::setCamPos(float camX, float camY) { void WorldRenderer::SetCamPos(float camX, float camY) {
m_CamPos = { camX, camY }; m_CamPos = { camX, camY };
m_Renderer->setCamPos(m_CamPos); m_Renderer->SetCamPos(m_CamPos);
} }
void WorldRenderer::renderTowerUpgradePopup() { void WorldRenderer::RenderTowerUpgradePopup() {
if (ImGui::BeginPopup("TowerUpgrade")) { if (ImGui::BeginPopup("TowerUpgrade")) {
m_PopupOpened = true; m_PopupOpened = true;
game::TowerPtr tower = m_Client->getWorld().getTower(getClickWorldPos()); game::TowerPtr tower = m_Client->GetWorld().GetTower(GetClickWorldPos());
if (tower == nullptr) { if (tower == nullptr) {
ImGui::EndPopup(); ImGui::EndPopup();
return; return;
} }
ImGui::Text("Tower : %s", game::TowerFactory::getTowerName(tower->getType()).c_str()); ImGui::Text("Tower : %s", game::TowerFactory::GetTowerName(tower->GetType()).c_str());
for (int y = 0; y < 3; y++) { // path: 0 -> top 1 -> middle 2 -> bottom for (int y = 0; y < 3; y++) { // path: 0 -> top 1 -> middle 2 -> bottom
for (int x = 0; x < 4; x++) { // level: 1, 2, 3, 4 for (int x = 0; x < 4; x++) { // level: 1, 2, 3, 4
@@ -170,12 +190,12 @@ void WorldRenderer::renderTowerUpgradePopup() {
std::uint8_t currentLevel = x + 1; std::uint8_t currentLevel = x + 1;
game::TowerPath currentPath = game::TowerPath(y); game::TowerPath currentPath = game::TowerPath(y);
const game::TowerStats* towerStats = game::getTowerStats(tower->getType(), { currentLevel, currentPath }); const game::TowerStats* towerStats = game::GetTowerStats(tower->GetType(), { currentLevel, currentPath });
game::TowerPath towerPath = tower->getLevel().getPath(); game::TowerPath towerPath = tower->GetLevel().GetPath();
bool disabled = towerStats == nullptr; bool disabled = towerStats == nullptr;
int towerLevel = tower->getLevel().getLevel(); int towerLevel = tower->GetLevel().GetLevel();
bool alreadyUpgraded = currentLevel <= towerLevel; bool alreadyUpgraded = currentLevel <= towerLevel;
bool canUpgrade = (towerLevel + 1) == currentLevel; bool canUpgrade = (towerLevel + 1) == currentLevel;
@@ -199,7 +219,7 @@ void WorldRenderer::renderTowerUpgradePopup() {
ImGui::EndDisabled(); ImGui::EndDisabled();
} else if (canUpgrade) { } else if (canUpgrade) {
if (ImGui::Button("Upgrade", ImVec2(100, 100))) { if (ImGui::Button("Upgrade", ImVec2(100, 100))) {
m_Client->getClient()->upgradeTower(tower->getID(), {currentLevel, currentPath}); m_Client->GetClient()->UpgradeTower(tower->GetID(), { currentLevel, currentPath });
} }
} else { } else {
ImGui::BeginDisabled(); ImGui::BeginDisabled();
@@ -214,57 +234,71 @@ void WorldRenderer::renderTowerUpgradePopup() {
} }
} }
void WorldRenderer::detectClick() { void WorldRenderer::DetectClick() {
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
if (ImGui::IsMouseReleased(0) && !ImGui::IsAnyItemHovered() && !ImGui::IsAnyItemFocused()) { if (ImGui::IsMouseReleased(0) && !ImGui::IsAnyItemHovered() && !ImGui::IsAnyItemFocused()) {
glm::vec2 cursorPos = { io.MousePos.x, io.MousePos.y }; glm::vec2 cursorPos = { io.MousePos.x, io.MousePos.y };
if (cursorPos == m_HoldCursorPos) { if (cursorPos == m_HoldCursorPos) {
m_LastClicked = m_HoldCursorPos; m_LastClicked = m_HoldCursorPos;
click(); Click();
} }
} }
} }
void WorldRenderer::renderMobTooltip() const { void WorldRenderer::RenderMobTooltip() const {
if (ImGui::IsAnyItemHovered()) return; if (ImGui::IsAnyItemHovered()) return;
detectMobHovering(); DetectMobHovering();
m_MobTooltip->render(); m_MobTooltip->Render();
} }
void WorldRenderer::detectMobHovering() const { void WorldRenderer::RenderCastleTooltip() const {
glm::vec2 cursorWorldPos = getCursorWorldPos(); if (ImGui::IsAnyItemHovered()) return;
for (game::MobPtr mob : m_World->getMobList()) {
// mob size is currently 1x1 for all mobs DetectCastleHovering();
float mobCenterX = mob->getX(); m_CastleTooltip->Render();
float mobCenterY = mob->getY(); }
if (cursorWorldPos.x > mobCenterX - 0.5f && cursorWorldPos.x < mobCenterX + 0.5f
&& cursorWorldPos.y > mobCenterY - 0.5f && cursorWorldPos.y < mobCenterY + 0.5f) { void WorldRenderer::DetectMobHovering() const {
m_MobTooltip->setMob(mob.get()); glm::vec2 cursorWorldPos = GetCursorWorldPos();
for (game::MobPtr mob : m_World->GetMobList()) {
if (mob->CollidesWith({ cursorWorldPos.x, cursorWorldPos.y })) {
m_MobTooltip->SetMob(mob.get());
return; return;
} }
} }
m_MobTooltip->setMob(nullptr); m_MobTooltip->SetMob(nullptr);
} }
void WorldRenderer::addTower(game::TowerPtr tower) { void WorldRenderer::DetectCastleHovering() const {
const WorldLoader::RenderData& renderData = WorldLoader::loadTowerModel(tower); glm::vec2 cursorWorldPos = GetCursorWorldPos();
m_TowersCache.addData(tower->getID(), renderData.positions, renderData.colors); for (const game::Team& team : m_World->GetTeams()) {
m_TowersCache.updateVertexArray(); if (team.GetCastle().CollidesWith({ cursorWorldPos.x, cursorWorldPos.y })) {
m_CastleTooltip->SetCastle(&team.GetCastle());
return;
}
}
m_CastleTooltip->SetCastle(nullptr);
} }
void WorldRenderer::removeTower(game::TowerPtr tower) { void WorldRenderer::OnTowerAdd(game::TowerPtr tower) {
m_TowersCache.removeData(tower->getID()); WorldLoader::RenderData RenderData = WorldLoader::LoadTowerModel(tower);
m_TowersCache.updateVertexArray(); m_TowersCache.AddData(tower->GetID(), RenderData.positions, RenderData.colors);
m_TowersCache.UpdateVertexArray();
} }
glm::vec2 WorldRenderer::getCursorWorldPos() const { void WorldRenderer::OnTowerRemove(game::TowerPtr tower) {
m_TowersCache.RemoveData(tower->GetID());
m_TowersCache.UpdateVertexArray();
}
glm::vec2 WorldRenderer::GetCursorWorldPos() const {
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
return m_Renderer->getCursorWorldPos({ io.MousePos.x, io.MousePos.y }, Display::getAspectRatio(), m_Zoom, Display::getWindowWidth(), Display::getWindowHeight()); return m_Renderer->GetCursorWorldPos({ io.MousePos.x, io.MousePos.y }, Display::GetAspectRatio(), m_Zoom, Display::GetWindowWidth(), Display::GetWindowHeight());
} }
glm::vec2 WorldRenderer::getClickWorldPos() const { glm::vec2 WorldRenderer::GetClickWorldPos() const {
return m_Renderer->getCursorWorldPos(m_LastClicked, Display::getAspectRatio(), m_Zoom, Display::getWindowWidth(), Display::getWindowHeight()); return m_Renderer->GetCursorWorldPos(m_LastClicked, Display::GetAspectRatio(), m_Zoom, Display::GetWindowWidth(), Display::GetWindowHeight());
} }
} // namespace render } // namespace render

View File

@@ -0,0 +1,27 @@
#include "render/gui/CastleTooltip.h"
#include "render/gui/imgui/imgui.h"
#include "render/WorldRenderer.h"
#include "game/client/Client.h"
namespace td {
namespace gui {
CastleTooltip::CastleTooltip(client::Client* client) : GuiWidget(client) {
}
void CastleTooltip::Render() {
if (m_Castle == nullptr) return;
ImGui::BeginTooltip();
ImGui::PushStyleColor(ImGuiCol_Text, render::WorldRenderer::GetImGuiTeamColor(m_Castle->GetTeam()->GetColor()));
ImGui::Text("Castle : ");
ImGui::PopStyleColor();
ImGui::Text("\tCastle HP : %i/%i", static_cast<int>(m_Castle->GetLife()), game::TeamCastle::CastleMaxLife);
ImGui::EndTooltip();
}
} // namespace gui
} // namespace td

View File

@@ -12,20 +12,28 @@ FrameMenu::FrameMenu(client::Client* client) : GuiWidget(client), m_VSync(true),
} }
void FrameMenu::render() { void FrameMenu::Render() {
ImGui::Begin("FPS Counter"); ImGui::Begin("FPS Counter");
ImGui::Text("FPS : %i", (int)ImGui::GetIO().Framerate); ImGui::Text("FPS : %i", (int)ImGui::GetIO().Framerate);
if (ImGui::Checkbox("V-Sync", &m_VSync)) { if (ImGui::Checkbox("V-Sync", &m_VSync)) {
SDL_GL_SetSwapInterval(m_VSync); SDL_GL_SetSwapInterval(m_VSync);
} }
if (ImGui::Checkbox("Vue Isometrique ?", &m_IsometricView)) { if (ImGui::Checkbox("Vue Isometrique ?", &m_IsometricView)) {
getClient()->getRenderer()->setIsometricView(m_IsometricView); GetClient()->GetRenderer()->SetIsometricView(m_IsometricView);
} }
#if !defined(NDEBUG)
ImGui::Checkbox("Demo Window", &m_ShowDemoWindow); ImGui::Checkbox("Demo Window", &m_ShowDemoWindow);
#endif
ImGui::End(); ImGui::End();
#if !defined(NDEBUG)
if (m_ShowDemoWindow) if (m_ShowDemoWindow)
ImGui::ShowDemoWindow(&m_ShowDemoWindow); ImGui::ShowDemoWindow(&m_ShowDemoWindow);
#endif
} }
} // namespace gui } // namespace gui

View File

@@ -13,67 +13,69 @@ GameMenu::GameMenu(client::Client* client) : GuiWidget(client), m_SummonMenu(std
} }
void GameMenu::render(){ void GameMenu::Render() {
if (getClient()->getGame().getGameState() == td::game::GameState::Lobby) { if (!m_Client->IsConnected()) return;
if (GetClient()->GetGame().GetGameState() == td::game::GameState::Lobby) {
ImGui::Begin("Lobby"); ImGui::Begin("Lobby");
showTPS(); ShowTPS();
showPlayers(); ShowPlayers();
showLobbyProgress(); ShowLobbyProgress();
showTeamSelection(); ShowTeamSelection();
ImGui::End(); ImGui::End();
} }
if (getClient()->getGame().getGameState() == td::game::GameState::Game) { if (GetClient()->GetGame().GetGameState() == td::game::GameState::Game) {
ImGui::Begin("Game"); ImGui::Begin("Game");
showTPS(); ShowTPS();
showStats(); ShowStats();
showPlayers(); ShowPlayers();
ImGui::End(); ImGui::End();
m_SummonMenu->render(); m_SummonMenu->Render();
} }
} }
void GameMenu::showPlayers() { void GameMenu::ShowPlayers() {
if (ImGui::TreeNode(std::string("Players (" + std::to_string(getClient()->getGame().getPlayers().size()) + ")##player_list").c_str())) { if (ImGui::TreeNode(std::string("Players (" + std::to_string(GetClient()->GetGame().GetPlayers().size()) + ")##player_list").c_str())) {
for (auto pair : getClient()->getGame().getPlayers()) { for (auto pair : GetClient()->GetGame().GetPlayers()) {
const td::game::Player& player = pair.second; const td::game::Player& player = pair.second;
ImGui::PushStyleColor(ImGuiCol_Text, render::WorldRenderer::getImGuiTeamColor(player.getTeamColor())); ImGui::PushStyleColor(ImGuiCol_Text, render::WorldRenderer::GetImGuiTeamColor(player.GetTeamColor()));
ImGui::Text("%s", player.getName().c_str()); ImGui::Text("%s", player.GetName().c_str());
ImGui::PopStyleColor(); ImGui::PopStyleColor();
} }
ImGui::TreePop(); ImGui::TreePop();
} }
} }
void GameMenu::showTeamSelection() { void GameMenu::ShowTeamSelection() {
if (getClient()->getGame().getPlayer() == nullptr) if (GetClient()->GetGame().GetPlayer() == nullptr)
return; return;
td::game::TeamColor playerTeam = getClient()->getGame().getPlayer()->getTeamColor(); td::game::TeamColor playerTeam = GetClient()->GetGame().GetPlayer()->GetTeamColor();
if (ImGui::Button(std::string((playerTeam == td::game::TeamColor::Red ? "Leave" : "Join") + std::string(" Red Team")).c_str())) { if (ImGui::Button(std::string((playerTeam == td::game::TeamColor::Red ? "Leave" : "Join") + std::string(" Red Team")).c_str())) {
if (playerTeam == td::game::TeamColor::Red) if (playerTeam == td::game::TeamColor::Red)
getClient()->selectTeam(td::game::TeamColor::None); GetClient()->SelectTeam(td::game::TeamColor::None);
else else
getClient()->selectTeam(td::game::TeamColor::Red); GetClient()->SelectTeam(td::game::TeamColor::Red);
} }
ImGui::SameLine(); ImGui::SameLine();
if (ImGui::Button(std::string((playerTeam == td::game::TeamColor::Blue ? "Leave" : "Join") + std::string(" Blue Team")).c_str())) { if (ImGui::Button(std::string((playerTeam == td::game::TeamColor::Blue ? "Leave" : "Join") + std::string(" Blue Team")).c_str())) {
if (playerTeam == td::game::TeamColor::Blue) if (playerTeam == td::game::TeamColor::Blue)
getClient()->selectTeam(td::game::TeamColor::None); GetClient()->SelectTeam(td::game::TeamColor::None);
else else
getClient()->selectTeam(td::game::TeamColor::Blue); GetClient()->SelectTeam(td::game::TeamColor::Blue);
} }
} }
void GameMenu::showLobbyProgress() { void GameMenu::ShowLobbyProgress() {
const int timePassed = server::Lobby::LobbyWaitingTime - getClient()->getGame().getLobbyTime(); const int timePassed = server::Lobby::LobbyWaitingTime - GetClient()->GetGame().GetLobbyTime();
const float progress = (float)timePassed / (float)(server::Lobby::LobbyWaitingTime); const float progress = (float)timePassed / (float)(server::Lobby::LobbyWaitingTime);
if (progress > 0 && progress < 1) { if (progress > 0 && progress < 1) {
ImGui::ProgressBar(progress, ImVec2(0.0f, 0.0f), std::string(std::to_string(getClient()->getGame().getLobbyTime() / 1000) + "s").c_str()); ImGui::ProgressBar(progress, ImVec2(0.0f, 0.0f), std::string(std::to_string(GetClient()->GetGame().GetLobbyTime() / 1000) + "s").c_str());
ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x);
ImGui::Text("Time Remaining"); ImGui::Text("Time Remaining");
} else { } else {
@@ -81,14 +83,14 @@ void GameMenu::showLobbyProgress() {
} }
} }
void GameMenu::showTPS() { void GameMenu::ShowTPS() {
ImGui::Text("Server TPS : %.1f", getClient()->getConnexion().getServerTPS()); ImGui::Text("Server TPS : %.1f", GetClient()->GetConnexion().GetServerTPS());
ImGui::Text("Server Ping : %i", getClient()->getConnexion().getServerPing()); ImGui::Text("Server Ping : %i", GetClient()->GetConnexion().GetServerPing());
} }
void GameMenu::showStats() { void GameMenu::ShowStats() {
ImGui::Text("Gold : %i", getClient()->getGame().getPlayer()->getGold()); ImGui::Text("Gold : %i", GetClient()->GetGame().GetPlayer()->GetGold());
ImGui::Text("EXP: %i", getClient()->getGame().getPlayer()->getExp()); ImGui::Text("EXP: %i", GetClient()->GetGame().GetPlayer()->GetExp());
} }
} // namespace gui } // namespace gui

View File

@@ -14,10 +14,16 @@ MainMenu::MainMenu(client::Client* client) : GuiWidget(client), m_ConnectPort(25
MainMenu::~MainMenu() { MainMenu::~MainMenu() {
if (m_Server != nullptr) if (m_Server != nullptr)
m_Server->stop(); m_Server->Stop();
} }
void MainMenu::render() { void MainMenu::Render() {
if (m_Server != nullptr && !m_Server->IsRunning()) {
m_Server.reset(0); // destroying server if it stoped
}
if (m_Client->IsConnected()) return;
ImGui::Begin("Main Menu"); ImGui::Begin("Main Menu");
if (ImGui::Button("Rejoindre une partie##join")) { if (ImGui::Button("Rejoindre une partie##join")) {
ImGui::OpenPopup("Rejoindre une partie##join_popup"); ImGui::OpenPopup("Rejoindre une partie##join_popup");
@@ -33,7 +39,7 @@ void MainMenu::render() {
ImGui::InputText("Server Adress", &m_ConnectAddress.front(), m_ConnectAddress.capacity()); ImGui::InputText("Server Adress", &m_ConnectAddress.front(), m_ConnectAddress.capacity());
ImGui::InputInt("Port", &m_ConnectPort, -1); ImGui::InputInt("Port", &m_ConnectPort, -1);
if (ImGui::Button("Rejoindre")) { if (ImGui::Button("Rejoindre")) {
getClient()->connect(td::network::Dns::Resolve(m_ConnectAddress), m_ConnectPort); GetClient()->Connect(td::network::Dns::Resolve(m_ConnectAddress), m_ConnectPort);
m_TriedToConnect = true; m_TriedToConnect = true;
} }
if (m_TriedToConnect) { if (m_TriedToConnect) {
@@ -55,10 +61,10 @@ void MainMenu::render() {
m_WorldFilePath = m_FileDialog.selected_path; m_WorldFilePath = m_FileDialog.selected_path;
} }
if (ImGui::Button("Créer")) { if (ImGui::Button("Créer")) {
if (!startServer()) { if (!StartServer()) {
m_TriedToCreate = true; m_TriedToCreate = true;
} else { } else {
getClient()->connect(td::network::Dns::Resolve("localhost"), m_ServerPort); GetClient()->Connect(td::network::Dns::Resolve("localhost"), m_ServerPort);
} }
} }
if (m_TriedToCreate) if (m_TriedToCreate)
@@ -71,11 +77,11 @@ void MainMenu::render() {
ImGui::End(); ImGui::End();
} }
bool MainMenu::startServer(){ bool MainMenu::StartServer() {
if (m_WorldFilePath.empty()) if (m_WorldFilePath.empty())
return false; return false;
m_Server = std::make_unique<td::server::Server>(m_WorldFilePath); m_Server = std::make_unique<td::server::Server>(m_WorldFilePath);
if (!m_Server->start(m_ServerPort)) { if (!m_Server->Start(m_ServerPort)) {
return false; return false;
} }
return true; return true;

View File

@@ -14,27 +14,29 @@ MobTooltip::MobTooltip(client::Client* client) : GuiWidget(client) {
} }
void MobTooltip::render() { void MobTooltip::Render() {
if (m_Mob == nullptr) return; if (m_Mob == nullptr) return;
const game::Player& sender = getClient()->getGame().getPlayerById(m_Mob->getSender()); // TODO: add sender null check
const game::Player* sender = GetClient()->GetGame().GetPlayerById(m_Mob->GetSender());
ImGui::BeginTooltip(); ImGui::BeginTooltip();
ImGui::Text("Sender :"); ImGui::Text("Sender :");
ImGui::SameLine(); ImGui::SameLine();
ImGui::PushStyleColor(ImGuiCol_Text, render::WorldRenderer::getImGuiTeamColor(sender.getTeamColor())); ImGui::PushStyleColor(ImGuiCol_Text, render::WorldRenderer::GetImGuiTeamColor(sender->GetTeamColor()));
ImGui::Text("%s", sender.getName().c_str()); ImGui::Text("%s", sender->GetName().c_str());
ImGui::PopStyleColor(); ImGui::PopStyleColor();
ImGui::Text("Mob HP : %.1f/%i", m_Mob->getHealth(), m_Mob->getStats()->getMaxLife()); ImGui::Text("Mob HP : %.1f/%i", m_Mob->GetHealth(), m_Mob->GetStats()->GetMaxLife());
ImGui::Text("Mob Type : %s", game::MobFactory::getMobName(m_Mob->getType()).c_str()); ImGui::Text("Mob Type : %s", game::MobFactory::GetMobName(m_Mob->GetType()).c_str());
ImGui::Text("Mob Level : %i", m_Mob->getLevel()); ImGui::Text("Mob Level : %i", m_Mob->GetLevel());
ImGui::NewLine(); ImGui::NewLine();
ImGui::Text("Mob Stats :"); ImGui::Text("Mob Stats :");
ImGui::Text("\tMax health : %i", m_Mob->getStats()->getMaxLife()); ImGui::Text("\tMax health : %i", m_Mob->GetStats()->GetMaxLife());
ImGui::Text("\tSpeed : %.1f", m_Mob->getStats()->getMovementSpeed()); ImGui::Text("\tSpeed : %.1f", m_Mob->GetStats()->GetMovementSpeed());
ImGui::Text("\tDamage : %.1f", m_Mob->getStats()->getDamage()); ImGui::Text("\tDamage : %.1f", m_Mob->GetStats()->GetDamage());
ImGui::Text("\tMoney cost : %i", m_Mob->getStats()->getMoneyCost()); ImGui::Text("\tMoney cost : %i", m_Mob->GetStats()->GetMoneyCost());
ImGui::Text("\tEXP cost : %i", m_Mob->getStats()->getExpCost()); ImGui::Text("\tEXP cost : %i", m_Mob->GetStats()->GetExpCost());
ImGui::Text("\tEXP reward : %i", m_Mob->getStats()->getExpReward()); ImGui::Text("\tEXP reward : %i", m_Mob->GetStats()->GetExpReward());
ImGui::EndTooltip(); ImGui::EndTooltip();
} }

Some files were not shown because too many files have changed in this diff Show More