diff --git a/assets b/assets index 1e7adc74..10a61165 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 1e7adc749e02144615a20a82c847d3c8df46ee3d +Subproject commit 10a611659ddaadfea6a560e707d395834855a979 diff --git a/include/Engine/Collision/CollisionSystem.h b/include/Engine/Collision/CollisionSystem.h index 9cd2fe63..19adea35 100644 --- a/include/Engine/Collision/CollisionSystem.h +++ b/include/Engine/Collision/CollisionSystem.h @@ -24,6 +24,7 @@ public: private: Octree* m_Octree; std::vector m_OctreeResult; + std::unordered_map m_PrevPositions; }; #endif \ No newline at end of file diff --git a/include/Engine/Core/EntityWrapper.h b/include/Engine/Core/EntityWrapper.h index b0e65d9e..8ece8e59 100644 --- a/include/Engine/Core/EntityWrapper.h +++ b/include/Engine/Core/EntityWrapper.h @@ -29,16 +29,22 @@ struct EntityWrapper EntityWrapper Parent(); EntityWrapper FirstChildByName(const std::string& name); EntityWrapper FirstParentWithComponent(const std::string& componentType); + EntityWrapper Clone(EntityWrapper parent = EntityWrapper::Invalid); + std::vector ChildrenWithComponent(const std::string& componentType); + void DeleteChildren(); bool IsChildOf(EntityWrapper potentialParent); bool Valid() const; ComponentWrapper operator[](const char* componentName); + ComponentWrapper operator[](const std::string& componentName); bool operator==(const EntityWrapper& e) const; bool operator!=(const EntityWrapper& e) const; explicit operator EntityID() const; private: EntityWrapper firstChildByNameRecursive(const std::string& name, EntityID parent); + EntityWrapper cloneRecursive(EntityWrapper entity, EntityWrapper parent); + void childrenWithComponentRecursive(const std::string& componentType, EntityWrapper& entity, std::vector& childrenWithComponent); }; namespace std diff --git a/include/Engine/Core/System.h b/include/Engine/Core/System.h index 1a387855..23d5f9a5 100644 --- a/include/Engine/Core/System.h +++ b/include/Engine/Core/System.h @@ -68,7 +68,7 @@ protected: const std::string m_ComponentType; - virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cPlayer, double dt) = 0; + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) = 0; }; class ImpureSystem : public virtual System diff --git a/include/Engine/Core/World.h b/include/Engine/Core/World.h index 1604df37..c9f738ce 100644 --- a/include/Engine/Core/World.h +++ b/include/Engine/Core/World.h @@ -40,7 +40,7 @@ public: // Change the parent of an entity void SetParent(EntityID entity, EntityID parent); // Get children of an entity - const std::pair::const_iterator, std::unordered_multimap::const_iterator> GetChildren(EntityID entity); + const std::pair::const_iterator, std::unordered_multimap::const_iterator> GetDirectChildren(EntityID entity); // Get all component pools const std::unordered_map& GetComponentPools() const { return m_ComponentPools; } // Get the entity children map diff --git a/include/Engine/Editor/EditorGUI.h b/include/Engine/Editor/EditorGUI.h index 7a0289c6..57574e66 100644 --- a/include/Engine/Editor/EditorGUI.h +++ b/include/Engine/Editor/EditorGUI.h @@ -73,6 +73,12 @@ public: // Called when the user means to rename an entity. typedef std::function OnEntityChangeName_t; void SetEntityChangeNameCallback(OnEntityChangeName_t f) { m_OnEntityChangeName = f; } + // Called when the user pastes an entity previously "copied" + // @param EntityWrapper The entity to copy + // @param EntityWrapper The entity to parent the new copy to + // @return The new copy of the entity + typedef std::function OnEntityPaste_t; + void SetEntityPasteCallback(OnEntityPaste_t f) { m_OnEntityPaste = f; } // Called when the user means to attach a new component to an entity. typedef std::function OnComponentAttach_t; void SetComponentAttachCallback(OnComponentAttach_t f) { m_OnComponentAttach = f; } @@ -111,6 +117,7 @@ private: std::string m_DroppedFile = ""; bool m_Paused = false; bool m_MouseLocked = false; + EntityWrapper m_CopyTarget = EntityWrapper::Invalid; // Callbacks OnEntitySelectedCallback_t m_OnEntitySelected = nullptr; @@ -124,6 +131,7 @@ private: OnComponentDelete_t m_OnComponentDelete = nullptr; OnWidgetMode_t m_OnWidgetMode = nullptr; OnWidgetSpace_t m_OnWidgetSpace = nullptr; + OnEntityPaste_t m_OnEntityPaste = nullptr; // Events EventRelay m_EKeyDown; diff --git a/include/Engine/Editor/EditorSystem.h b/include/Engine/Editor/EditorSystem.h index fcaa2e47..06ee53b6 100644 --- a/include/Engine/Editor/EditorSystem.h +++ b/include/Engine/Editor/EditorSystem.h @@ -56,6 +56,7 @@ private: void OnEntityDelete(EntityWrapper entity); void OnEntityChangeParent(EntityWrapper entity, EntityWrapper parent); void OnEntityChangeName(EntityWrapper entity, const std::string& name); + EntityWrapper OnEntityPaste(EntityWrapper entityToCopy, EntityWrapper parent); void OnComponentAttach(EntityWrapper entity, const std::string& componentType); void OnComponentDelete(EntityWrapper entity, const std::string& componentType); void OnWidgetSpace(EditorGUI::WidgetSpace widgetSpace); diff --git a/include/Engine/Network/Client.h b/include/Engine/Network/Client.h index 978c9b65..be76e265 100644 --- a/include/Engine/Network/Client.h +++ b/include/Engine/Network/Client.h @@ -19,11 +19,26 @@ #include "Core/World.h" #include "Core/EventBroker.h" #include "Core/ConfigFile.h" +#include "Core/EPlayerDeath.h" #include "Input/EInputCommand.h" #include "Core/EPlayerDamage.h" +#include "../Game/Events/EDoubleJump.h" #include "Network/EInterpolate.h" #include "Network/SnapshotFilter.h" #include "Core/EPlayerSpawned.h" +#include "Network/ESearchForServers.h" + +struct ServerInfo +{ + ServerInfo(std::string a, int b, std::string c, int d) + { + Address = a; Port = b; Name = c; PlayersConnected = d; + } + std::string Address = ""; + int Port = 0; + std::string Name = ""; + int PlayersConnected = 0; +}; class Client : public Network { @@ -34,7 +49,9 @@ public: void Connect(std::string address, int port); void Update() override; - +private: + UDPClient m_Unreliable; + TCPClient m_Reliable; std::vector m_PlayerSpawnEvents; void parseSpawnEvents(); // Save for children @@ -82,10 +99,13 @@ public: void parseTCPConnect(Packet& packet); void parsePlayerConnected(Packet& packet); void parsePing(); + void parseServerlist(Packet& packet); void parseKick(); void parsePlayersSpawned(Packet& packet); void parseEntityDeletion(Packet& packet); + void parsePlayerDamage(Packet& packet); void parseComponentDeletion(Packet& packet); + void parseDoubleJump(Packet& packet); void InterpolateFields(Packet & packet, const ComponentInfo & componentInfo, const EntityID & entityID, const std::string & componentType); void parseSnapshot(Packet& packet); void identifyPacketLoss(); @@ -94,6 +114,7 @@ public: void sendInputCommands(); void sendLocalPlayerTransform(); void becomePlayer(); + void displayServerlist(); // Mapping Logic // Returns if local EntityID exist in map bool clientServerMapsHasEntity(EntityID clientEntityID); @@ -109,10 +130,15 @@ public: bool OnPlayerDamage(const Events::PlayerDamage& e); EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(const Events::PlayerSpawned& e); - void parsePlayerDamage(Packet& packet); -private: - UDPClient m_Unreliable; - TCPClient m_Reliable; + EventRelay< Client, Events::SearchForServers> m_ESearchForServers; + EventRelay m_EDoubleJump; + bool OnDoubleJump(Events::DoubleJump & e); + bool OnSearchForServers(const Events::SearchForServers& e); + UDPClient m_ServerlistRequest; + std::vector m_Serverlist; + bool m_SearchingForServers = false; + std::clock_t m_StartSearchTime; + double m_SearchingTime = 2000; // Config I guess }; #endif diff --git a/include/Engine/Network/ESearchForServers.h b/include/Engine/Network/ESearchForServers.h new file mode 100644 index 00000000..1b08a8f3 --- /dev/null +++ b/include/Engine/Network/ESearchForServers.h @@ -0,0 +1,12 @@ +#ifndef Events_SearchForServers_h__ +#define Events_SearchForServers_h__ + +#include "Core/Event.h" + +namespace Events +{ + +struct SearchForServers : public Event { }; + +} +#endif diff --git a/include/Engine/Network/HybridClient.h b/include/Engine/Network/HybridClient.h deleted file mode 100644 index 8d96bf6e..00000000 --- a/include/Engine/Network/HybridClient.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef HybridClient_h__ -#define HybridClient_h__ - -class HybridClient -{ -public: - HybridClient(); - ~HybridClient(); -private: - -}; - -#endif \ No newline at end of file diff --git a/include/Engine/Network/HybridServer.h b/include/Engine/Network/HybridServer.h deleted file mode 100644 index 48d6fe63..00000000 --- a/include/Engine/Network/HybridServer.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef HybridServer_h__ -#define HybridServer_h__ - -class HybridServer -{ -public: - HybridServer(); - ~HybridServer(); -private: -}; - -#endif \ No newline at end of file diff --git a/include/Engine/Network/MessageType.h b/include/Engine/Network/MessageType.h index a72f054e..00a2a91f 100644 --- a/include/Engine/Network/MessageType.h +++ b/include/Engine/Network/MessageType.h @@ -19,6 +19,8 @@ enum class MessageType EntityDeleted, ComponentDeleted, PlayerTransform, + OnDoubleJump, + ServerlistRequest, Invalid }; diff --git a/include/Engine/Network/NetworkClient.h b/include/Engine/Network/NetworkClient.h index d0339d84..4adc68f5 100644 --- a/include/Engine/Network/NetworkClient.h +++ b/include/Engine/Network/NetworkClient.h @@ -9,13 +9,16 @@ typedef unsigned int PacketID; class NetworkClient { public: + NetworkClient(); + virtual ~NetworkClient(); virtual void Connect(std::string playerName, std::string address, int port) = 0; virtual void Disconnect() = 0; virtual void Receive(Packet& packet) = 0; virtual void Send(Packet & packet) = 0; virtual bool IsSocketAvailable() = 0; protected: - char m_ReadBuffer[BUFFERSIZE] = { 0 }; + char* m_ReadBuffer; + unsigned int m_BufferSize = BUFFERSIZE; }; #endif \ No newline at end of file diff --git a/include/Engine/Network/NetworkServer.h b/include/Engine/Network/NetworkServer.h index ccec82cc..296c8762 100644 --- a/include/Engine/Network/NetworkServer.h +++ b/include/Engine/Network/NetworkServer.h @@ -10,12 +10,15 @@ typedef unsigned int PacketID; class NetworkServer { public: + NetworkServer(); + virtual ~NetworkServer(); virtual void AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers) = 0; virtual void Receive(Packet & packet, PlayerDefinition & playerDefinition) = 0; virtual void Send(Packet & packet, PlayerDefinition & playerDefinition) = 0; virtual void Send(Packet & packet) = 0; protected: - char m_ReadBuffer[BUFFERSIZE] = { 0 }; + char* m_ReadBuffer; + unsigned int m_BufferSize = BUFFERSIZE; }; #endif \ No newline at end of file diff --git a/include/Engine/Network/Server.h b/include/Engine/Network/Server.h index b37bffab..aac4e4c8 100644 --- a/include/Engine/Network/Server.h +++ b/include/Engine/Network/Server.h @@ -17,6 +17,7 @@ #include "Core/EPlayerDamage.h" #include "Network/EPlayerDisconnected.h" #include "Core/EPlayerSpawned.h" +#include "../Game/Events/EDoubleJump.h" #include "Core/EEntityDeleted.h" #include "Core/EComponentDeleted.h" @@ -32,6 +33,7 @@ private: // Network channels TCPServer m_Reliable; UDPServer m_Unreliable; + UDPServer m_ServerlistRequest; // dont forget to set these in the childrens receive logic boost::asio::ip::address m_Address; int m_Port = 27666; @@ -54,7 +56,7 @@ private: std::vector m_InputCommandsToBroadcast; //Timers std::clock_t m_StartPingTime; - + // Packet loss logic PacketID m_PacketID = 0; PacketID m_PreviousPacketID = 0; @@ -64,6 +66,7 @@ private: void reliableBroadcast(Packet& packet); void unreliableBroadcast(Packet& packet); void sendSnapshot(); + void addPlayersToPacket(Packet& packet, EntityID entityID); void addChildrenToPacket(Packet& packet, EntityID entityID); void addInputCommandsToPacket(Packet& packet); void sendPing(); @@ -77,10 +80,12 @@ private: void parsePlayerTransform(Packet& packet); void parseOnInputCommand(Packet& packet); void parseClientPing(); - void parsePing(); - void parseUDPConnect(Packet & packet); - void parseTCPConnect(Packet & packet); + void parsePing(); + bool parseDoubleJump(Packet& packet); + void parseUDPConnect(Packet& packet); + void parseTCPConnect(Packet& packet); void parseDisconnect(); + void parseServerlistRequest(boost::asio::ip::udp::endpoint endpoint); bool shouldSendToClient(EntityWrapper childEntity); // Debug event diff --git a/include/Engine/Network/TCPClient.h b/include/Engine/Network/TCPClient.h index a666cbbe..2108fa3d 100644 --- a/include/Engine/Network/TCPClient.h +++ b/include/Engine/Network/TCPClient.h @@ -20,7 +20,7 @@ private: boost::asio::ip::tcp::endpoint m_Endpoint; boost::asio::io_service m_IOService; std::unique_ptr m_Socket; - size_t readBuffer(char* data); + size_t readBuffer(); PacketID m_SendPacketID = 0; bool m_IsConnected = false; }; diff --git a/include/Engine/Network/TCPServer.h b/include/Engine/Network/TCPServer.h index 9cc7646a..55631a22 100644 --- a/include/Engine/Network/TCPServer.h +++ b/include/Engine/Network/TCPServer.h @@ -16,16 +16,22 @@ public: void Send(Packet & packet, PlayerDefinition & playerDefinition); void Send(Packet & packet); void Disconnect(); + int Port() { return m_Port; } + std::string Address() { return m_Address; } + private: // TCP logic boost::asio::io_service m_IOService; std::unique_ptr acceptor; boost::shared_ptr lastReceivedSocket; - void handle_accept(boost::shared_ptr socket, - int& nextPlayerID, std::map& connectedPlayers, - const boost::system::error_code& error); - int readBuffer(char* data, PlayerDefinition& playerDefinition); + int readBuffer(PlayerDefinition& playerDefinition); + PlayerID getPlayerIDFromEndpoint(const std::map& connectedPlayers, + boost::asio::ip::address address, unsigned short port); + int GetPort(); + std::string GetAddress(); + int m_Port = 0; + std::string m_Address = ""; }; #endif \ No newline at end of file diff --git a/include/Engine/Network/UDPClient.h b/include/Engine/Network/UDPClient.h index 3a458d3e..42c27783 100644 --- a/include/Engine/Network/UDPClient.h +++ b/include/Engine/Network/UDPClient.h @@ -14,13 +14,14 @@ public: void Disconnect(); void Receive(Packet& packet); void Send(Packet & packet); + void Broadcast(Packet& packet, int port); bool IsSocketAvailable(); private: // Assio UDP logic boost::asio::io_service m_IOService; boost::asio::ip::udp::endpoint m_ReceiverEndpoint; boost::shared_ptr m_Socket; - int readBuffer(char* data); + int readBuffer(); PacketID m_SendPacketID = 0; }; diff --git a/include/Engine/Network/UDPServer.h b/include/Engine/Network/UDPServer.h index 246fb333..54f4e327 100644 --- a/include/Engine/Network/UDPServer.h +++ b/include/Engine/Network/UDPServer.h @@ -8,18 +8,21 @@ class UDPServer : public NetworkServer { public: UDPServer(); + UDPServer(int port); ~UDPServer(); void AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers); void Receive(Packet & packet, PlayerDefinition & playerDefinition); void Send(Packet & packet, PlayerDefinition & playerDefinition); - void Send(Packet & packet); + void Send(Packet & packet); + void Send(Packet & packet, boost::asio::ip::udp::endpoint endpoint); + void Broadcast(Packet & packet, int port); bool IsSocketAvailable(); private: // UDP logic boost::asio::io_service m_IOService; boost::asio::ip::udp::endpoint m_ReceiverEndpoint; std::unique_ptr m_Socket; - int readBuffer(char* data); + int readBuffer(); }; #endif \ No newline at end of file diff --git a/include/Engine/Rendering/CubeMapPass.h b/include/Engine/Rendering/CubeMapPass.h new file mode 100644 index 00000000..3cda8cad --- /dev/null +++ b/include/Engine/Rendering/CubeMapPass.h @@ -0,0 +1,27 @@ +#ifndef CubeMapPass_h__ +#define CubeMapPass_h__ + +#include "IRenderer.h" +#include "ShaderProgram.h" + +class CubeMapPass +{ +public: + CubeMapPass(IRenderer* renderer); + ~CubeMapPass() { } + + void LoadTextures(std::string input); + void FillCubeMap(glm::vec3 originPosition); + void GenerateCubeMapTexture(); + + //GLuint CubeMapTexture() const { return m_CubeMapTexture; } + GLuint m_CubeMapTexture = -1; + +private: + IRenderer* m_Renderer; + std::string m_PreviusCubeMapTexture; + + std::vector m_CubeMapTextures; +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index e3389471..1800c90e 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -4,6 +4,7 @@ #include "IRenderer.h" #include "DrawFinalPassState.h" #include "LightCullingPass.h" +#include "CubeMapPass.h" #include "FrameBuffer.h" #include "ShaderProgram.h" #include "Util/UnorderedMapVec2.h" @@ -13,7 +14,7 @@ class DrawFinalPass { public: - DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass); + DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass, CubeMapPass* cubeMapPass); ~DrawFinalPass() { } void InitializeTextures(); void InitializeFrameBuffers(); @@ -62,12 +63,14 @@ private: GLuint m_SceneTextureLowRes; GLuint m_DepthBuffer; GLuint m_DepthBufferLowRes; + GLuint m_CubeMapTexture; //maqke this component based i guess? GLuint m_ShieldPixelRate = 16; const IRenderer* m_Renderer; const LightCullingPass* m_LightCullingPass; + const CubeMapPass* m_CubeMapPass; ShaderProgram* m_ForwardPlusProgram; ShaderProgram* m_ExplosionEffectProgram; diff --git a/include/Engine/Rendering/ModelJob.h b/include/Engine/Rendering/ModelJob.h index 8801d2eb..c2a469d2 100644 --- a/include/Engine/Rendering/ModelJob.h +++ b/include/Engine/Rendering/ModelJob.h @@ -184,7 +184,7 @@ struct ModelJob : RenderJob void CalculateHash() override { - Hash = TextureID + ModelID << 10 + ShaderID << 20; + Hash = ShaderID << 20 + ModelID << 10 + TextureID; } }; diff --git a/include/Engine/Rendering/Renderer.h b/include/Engine/Rendering/Renderer.h index aa87536b..f3a6bf31 100644 --- a/include/Engine/Rendering/Renderer.h +++ b/include/Engine/Rendering/Renderer.h @@ -17,6 +17,7 @@ #include "DrawBloomPass.h" #include "DrawColorCorrectionPass.h" #include "SSAOPass.h" +#include "CubeMapPass.h" #include "../Core/EventBroker.h" #include "ImGuiRenderPass.h" #include "Camera.h" @@ -58,6 +59,7 @@ private: Model* m_UnitSphere; int m_DebugTextureToDraw = 0; + int m_CubeMapTexture = 0; bool m_ResizeWindow = false; float m_SSAO_Radius = 1.0f; float m_SSAO_Bias = 0.05f; @@ -74,6 +76,7 @@ private: DrawBloomPass* m_DrawBloomPass; DrawColorCorrectionPass* m_DrawColorCorrectionPass; SSAOPass* m_SSAOPass; + CubeMapPass* m_CubeMapPass; //----------------------Functions----------------------// void InitializeWindow(); diff --git a/include/Engine/Rendering/SSAOPass.h b/include/Engine/Rendering/SSAOPass.h index f15e20d3..792d1d82 100644 --- a/include/Engine/Rendering/SSAOPass.h +++ b/include/Engine/Rendering/SSAOPass.h @@ -14,11 +14,14 @@ class SSAOPass { public: SSAOPass(IRenderer* rendere); - ~SSAOPass() { }; + ~SSAOPass() { + delete m_DrawBloomPass; + }; void Draw(GLuint depthBuffer, Camera* camera); void Setting(float radius, float bias, float contrast, float intensityScale, int numOfSamples, int NumOfTurns); void ClearBuffer(); + void OnWindowResize(); //Return the SSAO of the texture sent to Draw GLuint SSAOTexture() const { return m_DrawBloomPass->GaussianTexture(); } @@ -31,7 +34,6 @@ private: void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const; - void ComputeAO(GLuint depthBuffer, Camera* camera); //void blurHorizontal(GLuint depthBuffer); //void blurVertical(GLuint depthBuffer); diff --git a/include/Engine/Rendering/SpriteJob.h b/include/Engine/Rendering/SpriteJob.h index 4fe19dca..25c2d5cb 100644 --- a/include/Engine/Rendering/SpriteJob.h +++ b/include/Engine/Rendering/SpriteJob.h @@ -17,7 +17,7 @@ struct SpriteJob : RenderJob { - SpriteJob(ComponentWrapper cSprite, Camera* camera, glm::mat4 matrix, World* world, glm::vec4 fillColor, float fillPercentage, bool depthSorted) + SpriteJob(ComponentWrapper cSprite, Camera* camera, glm::mat4 matrix, World* world, glm::vec4 fillColor, float fillPercentage, bool depthSorted, bool isIndicator) : RenderJob() { Model = ResourceManager::Load<::Model>("Models/Core/UnitQuad.mesh"); @@ -30,7 +30,7 @@ struct SpriteJob : RenderJob StartIndex = matProp.material->StartIndex; EndIndex = matProp.material->EndIndex; - Matrix = matrix; + Matrix = matrix; Color = cSprite["Color"]; Entity = cSprite.EntityID; Position = Transform::AbsolutePosition(world, cSprite.EntityID); @@ -41,7 +41,8 @@ struct SpriteJob : RenderJob } World = world; Pickable = world->HasComponent(cSprite.EntityID, "Button"); - + IsIndicator = isIndicator; + FillColor = fillColor; FillPercentage = fillPercentage; }; @@ -61,7 +62,9 @@ struct SpriteJob : RenderJob unsigned int StartIndex = 0; unsigned int EndIndex = 0; World* World; + bool Pickable; + bool IsIndicator = false; glm::vec4 FillColor = glm::vec4(0); float FillPercentage = 0.0; diff --git a/include/Engine/Rendering/Texture.h b/include/Engine/Rendering/Texture.h index 0fe650b3..d159e636 100644 --- a/include/Engine/Rendering/Texture.h +++ b/include/Engine/Rendering/Texture.h @@ -18,6 +18,7 @@ public: void Bind(GLenum textureUnit = GL_TEXTURE0); GLuint m_Texture = 0; + unsigned char* Data = nullptr; }; diff --git a/include/Game/Events/EDoubleJump.h b/include/Game/Events/EDoubleJump.h index 767d5b39..f5cad1fd 100644 --- a/include/Game/Events/EDoubleJump.h +++ b/include/Game/Events/EDoubleJump.h @@ -8,7 +8,7 @@ namespace Events struct DoubleJump : public Event { - + EntityID entityID; }; } diff --git a/include/Game/Systems/AmmoPickupSystem.h b/include/Game/Systems/AmmoPickupSystem.h index a54b8495..0fbd9e08 100644 --- a/include/Game/Systems/AmmoPickupSystem.h +++ b/include/Game/Systems/AmmoPickupSystem.h @@ -26,6 +26,7 @@ private: double AmmoGain; double RespawnTimer; double DecreaseThisRespawnTimer; + EntityID parentID; }; std::vector m_ETriggerTouchVector; }; diff --git a/include/Game/Systems/DamageIndicatorSystem.h b/include/Game/Systems/DamageIndicatorSystem.h index 053b196b..ae9ba195 100644 --- a/include/Game/Systems/DamageIndicatorSystem.h +++ b/include/Game/Systems/DamageIndicatorSystem.h @@ -14,11 +14,13 @@ #include #include "Rendering/Util/CommonFunctions.h" +//#define INDICATOR_TEST -class DamageIndicatorSystem : public System +class DamageIndicatorSystem : public ImpureSystem { public: DamageIndicatorSystem(SystemParams params); + virtual void Update(double dt) override; private: EventRelay m_EPlayerDamage; @@ -28,6 +30,20 @@ private: bool OnSetCamera(const Events::SetCamera& e); EntityID m_CurrentCamera = -1; + struct DamageIndicatorStruct { + EntityWrapper spriteEntity; + glm::vec3 enemyPosition; + DamageIndicatorStruct(EntityWrapper sprite, glm::vec3 pos) + : spriteEntity(sprite) + , enemyPosition(pos) {} + }; + std::vector updateDamageIndicatorVector; + float CalculateAngle(EntityWrapper player, glm::vec3 enemyPos); + //for tests +#ifdef INDICATOR_TEST + glm::vec3 DamageIndicatorTest(EntityWrapper player); + int m_TestVar = 0; +#endif }; #endif diff --git a/include/Game/Systems/PickupSpawnSystem.h b/include/Game/Systems/PickupSpawnSystem.h index f912e8ff..66c5f630 100644 --- a/include/Game/Systems/PickupSpawnSystem.h +++ b/include/Game/Systems/PickupSpawnSystem.h @@ -27,6 +27,7 @@ private: double HealthGain; double RespawnTimer; double DecreaseThisRespawnTimer; + EntityID parentID; }; std::vector m_ETriggerTouchVector; }; diff --git a/include/Game/Systems/PlayerMovementSystem.h b/include/Game/Systems/PlayerMovementSystem.h index 2bcae866..92aa1915 100644 --- a/include/Game/Systems/PlayerMovementSystem.h +++ b/include/Game/Systems/PlayerMovementSystem.h @@ -34,10 +34,14 @@ private: glm::vec3 m_LastPosition = glm::vec3(); // The logic for making the sound play when player is moving void playerStep(double dt); + // Spawn a hexagon at origin of an Entity + void spawnHexagon(EntityWrapper target); EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(Events::PlayerSpawned& e); + EventRelay m_EDoubleJump; + bool PlayerMovementSystem::OnDoubleJump(Events::DoubleJump & e); void updateMovementControllers(double dt); - void updateVelocity(double dt); + void updateVelocity(EntityWrapper player, double dt); }; \ No newline at end of file diff --git a/include/Game/Systems/PlayerSpawnSystem.h b/include/Game/Systems/PlayerSpawnSystem.h index bf87bef8..70f94807 100644 --- a/include/Game/Systems/PlayerSpawnSystem.h +++ b/include/Game/Systems/PlayerSpawnSystem.h @@ -13,8 +13,6 @@ public: PlayerSpawnSystem(SystemParams params); virtual void Update(double dt) override; - - static void SetRespawnTime(float respawnTime) { m_RespawnTime = respawnTime; }; private: struct SpawnRequest @@ -31,8 +29,8 @@ private: //EntityWrapper ID -> Player ID. std::map m_PlayerIDs; - static float m_RespawnTime; - float m_Timer; + float m_ForcedRespawnTime; + bool m_DbgConfigForceRespawn; EventRelay m_OnInputCommand; bool OnInputCommand(Events::InputCommand& e); diff --git a/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h b/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h index 7bd9c175..993dd060 100644 --- a/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h +++ b/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h @@ -1,37 +1,33 @@ +#ifndef AssaultWeaponBehaviour_h__ +#define AssaultWeaponBehaviour_h__ + #include "Sound/EPlaySoundOnEntity.h" #include "Collision/Collision.h" -#include "Rendering/AnimationSystem.h" #include "Core/ConfigFile.h" #include "WeaponBehaviour.h" #include "../SpawnerSystem.h" #include "Core/EPlayerDamage.h" #include "Core/EShoot.h" - -class AssaultWeaponBehaviour : public WeaponBehaviour +class AssaultWeaponBehaviour : public WeaponBehaviour { public: - AssaultWeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree, EntityWrapper weaponEntity); - - virtual void Fire() override; - virtual void CeaseFire() override; - virtual void Reload() override; + AssaultWeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree) + : WeaponBehaviour(systemParams, "AssaultWeapon", renderer, collisionOctree) + { } - virtual void Update(double dt) override; +protected: + virtual void OnPrimaryFire(WeaponInfo& wi) override; + virtual void OnCeasePrimaryFire(WeaponInfo& wi) override; + virtual void OnReload(WeaponInfo& wi) override; private: - EntityWrapper m_FirstPersonModel; - EntityWrapper m_ThirdPersonModel; // State bool m_Firing = false; bool m_Reloading = false; double m_ReloadTimer = 0.0; - EntityWrapper m_FirstPersonReloadImpersonator; - EntityWrapper m_ThirdPersonReloadImpersonator; double m_TimeSinceLastFire = 0.0; - - EventRelay m_EAnimationComplete; - bool OnAnimationComplete(Events::AnimationComplete& e); + EntityWrapper m_FirstPersonReloadImpostor; bool hasAmmo(); void fireRound(); @@ -47,3 +43,5 @@ private: bool shoot(double damage); void showHitMarker(); }; + +#endif \ No newline at end of file diff --git a/include/Game/Systems/Weapon/DefenderWeaponBehaviour.h b/include/Game/Systems/Weapon/DefenderWeaponBehaviour.h new file mode 100644 index 00000000..5ca13d3e --- /dev/null +++ b/include/Game/Systems/Weapon/DefenderWeaponBehaviour.h @@ -0,0 +1,38 @@ +#include "WeaponBehaviour.h" +#include "Collision/Collision.h" +#include "Core/EPlayerDamage.h" +#include "Rendering/ESetCamera.h" + +class DefenderWeaponBehaviour : public WeaponBehaviour +{ +public: + DefenderWeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree) + : System(systemParams) + , WeaponBehaviour(systemParams, "DefenderWeapon", renderer, collisionOctree) + , m_RandomEngine(m_RandomDevice()) + { + EVENT_SUBSCRIBE_MEMBER(m_ESetCamera, &DefenderWeaponBehaviour::OnSetCamera); + } + + void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cWeapon, double dt) override; + void UpdateWeapon(WeaponInfo& wi, double dt) override; + void OnPrimaryFire(WeaponInfo& wi) override; + void OnCeasePrimaryFire(WeaponInfo& wi) override; + bool OnInputCommand(WeaponInfo& wi, const Events::InputCommand& e) override; + +private: + std::random_device m_RandomDevice; + std::mt19937 m_RandomEngine; + EntityWrapper m_CurrentCamera; + + EventRelay m_ESetCamera; + bool OnSetCamera(const Events::SetCamera& e); + + // Weapon functions + void fireShell(WeaponInfo& wi); + void dealDamage(WeaponInfo& wi, glm::vec3 direction, double damage); + + // Utility + float traceRayDistance(glm::vec3 origin, glm::vec3 direction); + Camera cameraFromEntity(EntityWrapper camera); +}; \ No newline at end of file diff --git a/include/Game/Systems/Weapon/WeaponBehaviour.h b/include/Game/Systems/Weapon/WeaponBehaviour.h index 7a0b4626..f23269df 100644 --- a/include/Game/Systems/Weapon/WeaponBehaviour.h +++ b/include/Game/Systems/Weapon/WeaponBehaviour.h @@ -5,30 +5,177 @@ #include "Rendering/IRenderer.h" #include "Core/Octree.h" #include "Collision/EntityAABB.h" +#include "Input/EInputCommand.h" +#include "Systems/SpawnerSystem.h" -class WeaponBehaviour : public System +template +class WeaponBehaviour : public PureSystem { + friend class WeaponSystem; + public: - WeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree, EntityWrapper player) - : System(systemParams) + WeaponBehaviour(SystemParams params, std::string componentType, IRenderer* renderer, Octree* collisionOctree) + : System(params) + , PureSystem(componentType) , m_Renderer(renderer) , m_CollisionOctree(collisionOctree) - , m_Player(player) - { } + { + EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &WeaponBehaviour::_OnInputCommand) + } virtual ~WeaponBehaviour() = default; - WeaponBehaviour(const WeaponBehaviour&) = delete; - WeaponBehaviour& operator=(const WeaponBehaviour &) = delete; - - virtual void Fire() = 0; - virtual void CeaseFire() { } - virtual void Reload() { } - virtual void Update(double dt) { } + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override + { + auto weapon = getActiveWeapon(entity); + if (!weapon) { + return; + } else { + UpdateWeapon(*weapon, dt); + } + } protected: + struct WeaponInfo + { + std::string WeaponComponent; + EntityWrapper Player; + EntityWrapper WeaponEntity; + EntityWrapper FirstPersonEntity; + EntityWrapper ThirdPersonEntity; + ComponentWrapper GetComponent() { return WeaponEntity[WeaponComponent]; } + }; + IRenderer* m_Renderer; Octree* m_CollisionOctree; - EntityWrapper m_Player; + std::unordered_map m_ActiveWeapons; + + virtual void UpdateWeapon(WeaponInfo& wi, double dt) { } + virtual void OnPrimaryFire(WeaponInfo& wi) { } + virtual void OnCeasePrimaryFire(WeaponInfo& wi) { } + virtual void OnReload(WeaponInfo& wi) { } + virtual bool OnInputCommand(WeaponInfo& wi, const Events::InputCommand& e) { return false; } + +private: + EventRelay m_EInputCommand; + bool _OnInputCommand(const Events::InputCommand& e) + { + EntityWrapper player = e.Player; + if (e.PlayerID == -1) { + player = LocalPlayer; + } + + // Make sure the player is alive + if (!player.Valid()) { + return false; + } + + // Make sure the player has this weapon + auto weapon = getWeaponComponent(player); + if (!weapon) { + return false; + } + + // Weapon selection + if (e.Command == "SelectWeapon") { + if (static_cast(e.Value) == static_cast((*weapon)["Slot"])) { + selectWeapon(player); + } + } + + // Only handle weapon actions if the weapon is active + auto activeWeapon = getActiveWeapon(player); + if (!activeWeapon) { + return false; + } + + // Fire + if (e.Command == "PrimaryFire") { + if (e.Value > 0) { + OnPrimaryFire(*activeWeapon); + } else { + OnCeasePrimaryFire(*activeWeapon); + } + } + + // Reload + if (e.Command == "Reload" && e.Value != 0) { + OnReload(*activeWeapon); + } + + return OnInputCommand(*activeWeapon, e); + } + + boost::optional getWeaponComponent(EntityWrapper player) + { + if (!player.HasComponent(m_ComponentType)) { + return boost::none; + } + + return player[m_ComponentType]; + } + + boost::optional getActiveWeapon(EntityWrapper player) + { + auto it = m_ActiveWeapons.find(player); + if (it == m_ActiveWeapons.end()) { + return boost::none; + } + WeaponInfo& activeWeapon = it->second; + + if (!activeWeapon.FirstPersonEntity.Valid() && !activeWeapon.ThirdPersonEntity.Valid()) { + return boost::none; + } + + return activeWeapon; + } + + void selectWeapon(EntityWrapper player) + { + // Find the weapon attachments matching the weapon type + std::vector weaponAttachments = player.ChildrenWithComponent("WeaponAttachment"); + EntityWrapper firstPersonAttachment; + EntityWrapper thirdPersonAttachment; + for (auto& attachment : weaponAttachments) { + ComponentWrapper cWeaponAttachment = attachment["WeaponAttachment"]; + if ((std::string&)cWeaponAttachment["Weapon"] == m_ComponentType) { + ComponentWrapper::SubscriptProxy person = cWeaponAttachment["Person"]; + if ((ComponentInfo::EnumType)person == person.Enum("FirstPerson")) { + firstPersonAttachment = attachment; + } else if ((ComponentInfo::EnumType)person == person.Enum("ThirdPerson")) { + thirdPersonAttachment = attachment; + } + } + } + + if (!firstPersonAttachment.Valid() && !thirdPersonAttachment.Valid()) { + LOG_WARNING("No weapon attachment found for %s of player #%i", m_ComponentType.c_str(), player.ID); + return; + } + + // Purge other weapon entities + for (auto& attachment : weaponAttachments) { + //if (attachment == firstPersonAttachment || attachment == thirdPersonAttachment) { + // continue; + //} + attachment.DeleteChildren(); + } + + // Spawn the weapon(s) + EntityWrapper firstPersonWeapon; + EntityWrapper thirdPersonWeapon; + if (firstPersonAttachment.Valid()) { + firstPersonWeapon = SpawnerSystem::Spawn(firstPersonAttachment, firstPersonAttachment); + } + if (thirdPersonAttachment.Valid()) { + thirdPersonWeapon = SpawnerSystem::Spawn(thirdPersonAttachment, thirdPersonAttachment); + } + + m_ActiveWeapons[player].WeaponComponent = m_ComponentType; + m_ActiveWeapons[player].Player = player; + m_ActiveWeapons[player].WeaponEntity = player; + m_ActiveWeapons[player].FirstPersonEntity = firstPersonWeapon; + m_ActiveWeapons[player].ThirdPersonEntity = thirdPersonWeapon; + } }; #endif diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index 74423f56..eb41ed6a 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -44,5 +44,10 @@ + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/AssaultWeapon.xml b/resources/Schema/Components/AssaultWeapon.xml index 6c645624..c835217b 100755 --- a/resources/Schema/Components/AssaultWeapon.xml +++ b/resources/Schema/Components/AssaultWeapon.xml @@ -8,4 +8,5 @@ 120 0.01 2 + \ No newline at end of file diff --git a/resources/Schema/Components/AssaultWeapon.xsd b/resources/Schema/Components/AssaultWeapon.xsd index 95df64b7..7e9854a2 100755 --- a/resources/Schema/Components/AssaultWeapon.xsd +++ b/resources/Schema/Components/AssaultWeapon.xsd @@ -2,6 +2,7 @@ + @@ -28,6 +29,7 @@ Time it takes to reload the weapon in seconds + diff --git a/resources/Schema/Components/CapturePointGameMode.xml b/resources/Schema/Components/CapturePointGameMode.xml new file mode 100644 index 00000000..3104e71f --- /dev/null +++ b/resources/Schema/Components/CapturePointGameMode.xml @@ -0,0 +1,5 @@ + + + 0.0 + 8.0 + \ No newline at end of file diff --git a/resources/Schema/Components/CapturePointGameMode.xsd b/resources/Schema/Components/CapturePointGameMode.xsd new file mode 100644 index 00000000..8b81d67a --- /dev/null +++ b/resources/Schema/Components/CapturePointGameMode.xsd @@ -0,0 +1,18 @@ + + + + + + + + + + The time since the last respawn wave. Players will be spawned when this reaches MaxRespawnTime. + + + Players will be spawned when RespawnTime reaches this. + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/DefenderWeapon.xml b/resources/Schema/Components/DefenderWeapon.xml new file mode 100755 index 00000000..998f3bde --- /dev/null +++ b/resources/Schema/Components/DefenderWeapon.xml @@ -0,0 +1,16 @@ + + + 8 + 8 + 64 + 64 + 90 + 0.174533 + 10 + 120 + 0.01 + 0.5 + + false + 0 + \ No newline at end of file diff --git a/resources/Schema/Components/DefenderWeapon.xsd b/resources/Schema/Components/DefenderWeapon.xsd new file mode 100755 index 00000000..3fe5a64a --- /dev/null +++ b/resources/Schema/Components/DefenderWeapon.xsd @@ -0,0 +1,44 @@ + + + + + + + + + + + Ammo currently loaded into the magazine + + + Max number of rounds in a magazine + + + Current ammo carried + + + Maximum ammo able to be carried + + + Damage dealt if all shotgun pellets hit + + + Spread angle in radians + + + + Rate of fire in rounds per minute + + + View punch in radians for each shell fired + + + Time it takes to load ONE SHELL into the weapon in seconds + + + + + + + + diff --git a/resources/Schema/Components/DoubleJump.xml b/resources/Schema/Components/DoubleJump.xml new file mode 100644 index 00000000..bb0d3bc7 --- /dev/null +++ b/resources/Schema/Components/DoubleJump.xml @@ -0,0 +1,4 @@ + + + 4.0 + \ No newline at end of file diff --git a/resources/Schema/Components/DoubleJump.xsd b/resources/Schema/Components/DoubleJump.xsd new file mode 100644 index 00000000..65ff0419 --- /dev/null +++ b/resources/Schema/Components/DoubleJump.xsd @@ -0,0 +1,16 @@ + + + + + + + Enables a Player to double jump. + + + + Vertical velocity set on double jump. + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/Physics.xml b/resources/Schema/Components/Physics.xml index 84b6aba3..6cb73c75 100644 --- a/resources/Schema/Components/Physics.xml +++ b/resources/Schema/Components/Physics.xml @@ -2,7 +2,6 @@ true - false 0.33 diff --git a/resources/Schema/Components/Physics.xsd b/resources/Schema/Components/Physics.xsd index 206e2a23..7fed1fb5 100644 --- a/resources/Schema/Components/Physics.xsd +++ b/resources/Schema/Components/Physics.xsd @@ -13,7 +13,6 @@ m/s^2 - The largest height of a "stair-step" that can be walked over diff --git a/resources/Schema/Components/Player.xml b/resources/Schema/Components/Player.xml index 00cff257..b50274ac 100644 --- a/resources/Schema/Components/Player.xml +++ b/resources/Schema/Components/Player.xml @@ -2,5 +2,7 @@ 3 1.5 + 4.0 + \ No newline at end of file diff --git a/resources/Schema/Components/Player.xsd b/resources/Schema/Components/Player.xsd index 1b33d222..006ae9d7 100644 --- a/resources/Schema/Components/Player.xsd +++ b/resources/Schema/Components/Player.xsd @@ -11,7 +11,11 @@ + + Vertical velocity set when jumping. + + diff --git a/resources/Schema/Components/SpriteIndicator.xml b/resources/Schema/Components/SpriteIndicator.xml new file mode 100644 index 00000000..cbed22f0 --- /dev/null +++ b/resources/Schema/Components/SpriteIndicator.xml @@ -0,0 +1,5 @@ + + + 10 + false + \ No newline at end of file diff --git a/resources/Schema/Components/SpriteIndicator.xsd b/resources/Schema/Components/SpriteIndicator.xsd new file mode 100644 index 00000000..bd8c1038 --- /dev/null +++ b/resources/Schema/Components/SpriteIndicator.xsd @@ -0,0 +1,19 @@ + + + + + + + + Billbord a Sprite around global Y axis + + + + + + Add a Team component to this Entity or Parent to make it visible only for that team + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/Weapon.xml b/resources/Schema/Components/Weapon.xml deleted file mode 100644 index 38c6fce9..00000000 --- a/resources/Schema/Components/Weapon.xml +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/resources/Schema/Components/Weapon.xsd b/resources/Schema/Components/Weapon.xsd deleted file mode 100644 index 8bddd8a9..00000000 --- a/resources/Schema/Components/Weapon.xsd +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/resources/Schema/Components/WeaponAttachment.xml b/resources/Schema/Components/WeaponAttachment.xml new file mode 100644 index 00000000..8867b2b7 --- /dev/null +++ b/resources/Schema/Components/WeaponAttachment.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/WeaponAttachment.xsd b/resources/Schema/Components/WeaponAttachment.xsd new file mode 100644 index 00000000..3b1291ae --- /dev/null +++ b/resources/Schema/Components/WeaponAttachment.xsd @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + Combine with a spawner to define a weapon attachment point + + + + The weapon component type this attachment refers to + + + + + + \ No newline at end of file diff --git a/resources/Schema/Entities/AmmoPickup.xml b/resources/Schema/Entities/AmmoPickup.xml index 1d1435f7..bebde467 100644 --- a/resources/Schema/Entities/AmmoPickup.xml +++ b/resources/Schema/Entities/AmmoPickup.xml @@ -2,18 +2,18 @@ - Models/Props/PickUps/AmmoPickUp.mesh - 0.1 - + 8 + - - + + + diff --git a/resources/Schema/Entities/AssaultWeaponView.xml b/resources/Schema/Entities/AssaultWeaponView.xml new file mode 100755 index 00000000..4b985fbb --- /dev/null +++ b/resources/Schema/Entities/AssaultWeaponView.xml @@ -0,0 +1,99 @@ + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + Schema/Entities/ReloadEffectView.xml + + + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + + + + + 32 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/AssaultWeaponWorld.xml b/resources/Schema/Entities/AssaultWeaponWorld.xml new file mode 100755 index 00000000..6fcb97b3 --- /dev/null +++ b/resources/Schema/Entities/AssaultWeaponWorld.xml @@ -0,0 +1,40 @@ + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + Schema/Entities/ReloadEffectWorld.xml + + + + + + + + diff --git a/resources/Schema/Entities/DefenderShield.xml b/resources/Schema/Entities/DefenderShield.xml new file mode 100755 index 00000000..da760e72 --- /dev/null +++ b/resources/Schema/Entities/DefenderShield.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + Models/Core/UnitPlane.mesh + + + + + + + + + + + + + + Models/Core/UnitHexagon.mesh + + true + + + + + + + + + + + + diff --git a/resources/Schema/Entities/DefenderWeaponView.xml b/resources/Schema/Entities/DefenderWeaponView.xml new file mode 100755 index 00000000..f6b6e89d --- /dev/null +++ b/resources/Schema/Entities/DefenderWeaponView.xml @@ -0,0 +1,99 @@ + + + + + + R_Arm_Weapon_Joint + + + + Models/Weapons/Blue/DefenderGunBlue.mesh + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + Schema/Entities/ReloadEffectView.xml + + + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + + + + + 32 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/DefenderWeaponViewRed.xml b/resources/Schema/Entities/DefenderWeaponViewRed.xml new file mode 100755 index 00000000..b5b1c322 --- /dev/null +++ b/resources/Schema/Entities/DefenderWeaponViewRed.xml @@ -0,0 +1,99 @@ + + + + + + R_Arm_Weapon_Joint + + + + Models/Weapons/Red/DefenderGunRed.mesh + + + + + + + + + + + Schema/Entities/RayRed.xml + + + + + + + + + + + Schema/Entities/ReloadEffectView.xml + + + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + + + + + 32 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/DefenderWeaponWorld.xml b/resources/Schema/Entities/DefenderWeaponWorld.xml new file mode 100755 index 00000000..826301b4 --- /dev/null +++ b/resources/Schema/Entities/DefenderWeaponWorld.xml @@ -0,0 +1,41 @@ + + + + + + R_Arm_Weapon_Joint + + + + Models/Weapons/Blue/DefenderGunBlue.mesh + + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + Schema/Entities/ReloadEffectWorld.xml + + + + + + + + diff --git a/resources/Schema/Entities/DefenderWeaponWorldRed.xml b/resources/Schema/Entities/DefenderWeaponWorldRed.xml new file mode 100755 index 00000000..7f697304 --- /dev/null +++ b/resources/Schema/Entities/DefenderWeaponWorldRed.xml @@ -0,0 +1,41 @@ + + + + + + R_Arm_Weapon_Joint + + + + Models/Weapons/Red/DefenderGunRed.mesh + + + + + + + + + + + + Schema/Entities/RayRed.xml + + + + + + + + + + + Schema/Entities/ReloadEffectWorld.xml + + + + + + + + diff --git a/resources/Schema/Entities/HealthPickup.xml b/resources/Schema/Entities/HealthPickup.xml index c6fbc4f4..b4b83392 100644 --- a/resources/Schema/Entities/HealthPickup.xml +++ b/resources/Schema/Entities/HealthPickup.xml @@ -2,18 +2,18 @@ - Models/Props/PickUps/HealthPickUp.mesh - 0.1 - + 8 + - - + + + diff --git a/resources/Schema/Entities/MovementTest.xml b/resources/Schema/Entities/MovementTest.xml index 84aaa03a..41474568 100644 --- a/resources/Schema/Entities/MovementTest.xml +++ b/resources/Schema/Entities/MovementTest.xml @@ -10,7 +10,7 @@ - Schema/Entities/Player.xml + Schema/Entities/PlayerRed.xml @@ -118,257 +118,6 @@ - - - - - - - - 600 - - - - - - - - - 5 - - - - - - - - - - - - - - - - - - - - - - - Fonts/DroidSans.ttf,100 - - - - - - - - - - - - - - Models/Widgets/Camera.mesh - false - - - - - - - - - - - - - - - - - - - 1 - - - - - Models/Core/UnitHexagon.mesh - - - - - - - - - - - - - - Textures/Weapons/Crosshair/SmallThickHoleDot.png - false - - - - - - - - - - - - - - Idle - 1.9569972344146196 - 1 - - - Models/Characters/Assault/FirstPerson.mesh - true - - - - - - - - R_Arm_Weapon_Joint - - - Models/Weapons/Blue/AssaultWeaponBlue.mesh - true - - - - - - - - - - - Schema/Entities/RayBlue.xml - - - - - - - - - - - - - Schema/Entities/WeaponReloadEffect.xml - - - - - - - - - - - - - - Models/Widgets/Camera.mesh - false - - - - - - - - - - - - Idle - 1.8055945618467364 - 1 - - - AimRifle - - - - - Models/Characters/Assault/AssaultAnimations.mesh - - - - - - - - - R_Arm_Weapon_Joint - - - Models/Weapons/Blue/AssaultWeaponBlue.mesh - false - - - - - - - - - - - Schema/Entities/RayBlue.xml - - - - - - - - - - - - - - - Models/Core/UnitCube.mesh - - false - - - - - - - - - - - - Models/Core/UnitCube.mesh - - false - - - - - - - - - diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index d4485112..88f153ae 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -7,23 +7,31 @@ - 600 + + + - + + 1.6944730461160304 + + 5 + - + + + @@ -60,6 +68,7 @@ Textures/Weapons/Crosshair/SmallThickHoleDot.png false + @@ -110,6 +119,7 @@ Textures/HealthHUD3.png + @@ -135,6 +145,7 @@ Textures/Core/UnitHexagon.png + @@ -152,6 +163,7 @@ Textures/Core/UnitHexagon_Rotated.png + @@ -167,6 +179,7 @@ Textures/Core/UnitHexagon.png + @@ -185,6 +198,7 @@ Textures/Core/UnitHexagon_Rotated.png + @@ -200,6 +214,7 @@ Textures/Core/UnitHexagon.png + @@ -217,6 +232,7 @@ Textures/Core/UnitHexagon_Rotated.png + @@ -232,6 +248,7 @@ Textures/Core/UnitHexagon.png + @@ -249,6 +266,7 @@ Textures/Core/UnitHexagon_Rotated.png + @@ -264,6 +282,7 @@ Textures/Core/UnitHexagon.png + @@ -279,6 +298,7 @@ Textures/Core/UnitHexagon_Rotated.png + @@ -304,6 +324,7 @@ + Fonts/DroidSans.ttf,64 @@ -316,6 +337,7 @@ + Fonts/DroidSans.ttf,64 @@ -330,6 +352,7 @@ + Fonts/DroidSans.ttf,64 @@ -349,8 +372,10 @@ Idle - 1.8314163732853146 + 0.67172915251515519 1 + + Models/Characters/Assault/FirstPerson.mesh @@ -359,99 +384,29 @@ - + - - R_Arm_Weapon_Joint - - - Models/Weapons/Blue/AssaultWeaponBlue.mesh - - - - - + + Schema/Entities/DefenderWeaponView.xml + + + + DefenderWeapon + - - - - - Schema/Entities/RayBlue.xml - - - - - - - - - - - Schema/Entities/ReloadEffectView.xml - - - - - - - - - - - - - - - - - - Textures/Core/UnitHexagon.png - - - - - - - - - - - - - - - - - - 32 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - 360 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - + + + + + + Schema/Entities/AssaultWeaponView.xml + + + + AssaultWeapon + + + @@ -475,13 +430,15 @@ Idle - 0.16333512901638159 1 + + AimRifle + Models/Characters/Assault/AssaultAnimations.mesh @@ -490,41 +447,35 @@ - + - - R_Arm_Weapon_Joint - - - Models/Weapons/Blue/AssaultWeaponBlue.mesh - - - - - + + Schema/Entities/DefenderWeaponWorld.xml + + + + DefenderWeapon + + + + - - - - - Schema/Entities/RayBlue.xml - - - - - - - - - - - Schema/Entities/ReloadEffectWorld.xml - - - - - - + + + + + + Schema/Entities/AssaultWeaponWorld.xml + + + + AssaultWeapon + + + + + + @@ -570,6 +521,37 @@ + + + + Textures/Icons/Arrow.png + false + + + + + + 50 + true + + + + + + + + + + + + Schema/Entities/DefenderShield.xml + + + + + + + diff --git a/resources/Schema/Entities/PlayerRed.xml b/resources/Schema/Entities/PlayerRed.xml index 4be8fc26..3cf17558 100644 --- a/resources/Schema/Entities/PlayerRed.xml +++ b/resources/Schema/Entities/PlayerRed.xml @@ -7,23 +7,31 @@ - 600 + + + - + + 1.6944730461160304 + + 5 + - + + + @@ -60,6 +68,7 @@ Textures/Weapons/Crosshair/SmallThickHoleDot.png false + @@ -110,6 +119,7 @@ Textures/HealthHUD3.png + @@ -135,6 +145,7 @@ Textures/Core/UnitHexagon.png + @@ -152,6 +163,7 @@ Textures/Core/UnitHexagon_Rotated.png + @@ -167,6 +179,7 @@ Textures/Core/UnitHexagon.png + @@ -185,6 +198,7 @@ Textures/Core/UnitHexagon_Rotated.png + @@ -200,6 +214,7 @@ Textures/Core/UnitHexagon.png + @@ -217,6 +232,7 @@ Textures/Core/UnitHexagon_Rotated.png + @@ -232,6 +248,7 @@ Textures/Core/UnitHexagon.png + @@ -249,6 +266,7 @@ Textures/Core/UnitHexagon_Rotated.png + @@ -264,6 +282,7 @@ Textures/Core/UnitHexagon.png + @@ -279,6 +298,7 @@ Textures/Core/UnitHexagon_Rotated.png + @@ -304,6 +324,7 @@ + Fonts/DroidSans.ttf,64 @@ -316,6 +337,7 @@ + Fonts/DroidSans.ttf,64 @@ -330,6 +352,7 @@ + Fonts/DroidSans.ttf,64 @@ -349,8 +372,10 @@ Idle - 0.018170670865885086 + 0.67172915251515519 1 + + Models/Characters/Assault/FirstPerson.mesh @@ -359,99 +384,29 @@ - + - - R_Arm_Weapon_Joint - - - Models/Weapons/Red/AssaultWeaponRed.mesh - - - - - + + Schema/Entities/DefenderWeaponViewRed.xml + + + + DefenderWeapon + - - - - - Schema/Entities/RayRed.xml - - - - - - - - - - - Schema/Entities/ReloadEffectViewRed.xml - - - - - - - - - - - - - - - - - - Textures/Core/UnitHexagon.png - - - - - - - - - - - - - - - - - - 32 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - 360 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - + + + + + + Schema/Entities/AssaultWeaponView.xml + + + + AssaultWeapon + + + @@ -475,13 +430,15 @@ Idle - 0.11675631578762591 1 + + AimRifle + Models/Characters/Assault/AssaultAnimations.mesh @@ -490,41 +447,35 @@ - + - - R_Arm_Weapon_Joint - - - Models/Weapons/Red/AssaultWeaponRed.mesh - - - - - + + Schema/Entities/DefenderWeaponWorldRed.xml + + + + DefenderWeapon + + + + - - - - - Schema/Entities/RayRed.xml - - - - - - - - - - - Schema/Entities/ReloadEffectWorldRed.xml - - - - - - + + + + + + Schema/Entities/AssaultWeaponWorld.xml + + + + AssaultWeapon + + + + + + @@ -563,13 +514,44 @@ - + + + + + Textures/Icons/Arrow.png + false + + + + + + 50 + true + + + + + + + + + + + + Schema/Entities/DefenderShield.xml + + + + + + + diff --git a/resources/Schema/Types/Entity.xsd b/resources/Schema/Types/Entity.xsd index a9c5f641..0965ef89 100644 --- a/resources/Schema/Types/Entity.xsd +++ b/resources/Schema/Types/Entity.xsd @@ -50,6 +50,8 @@ + + diff --git a/resources/Schema/Types/WeaponSlotEnum.xsd b/resources/Schema/Types/WeaponSlotEnum.xsd new file mode 100644 index 00000000..6713ca9d --- /dev/null +++ b/resources/Schema/Types/WeaponSlotEnum.xsd @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/resources/Shaders/ForwardPlus.frag.glsl b/resources/Shaders/ForwardPlus.frag.glsl index 47da7480..d88154ef 100644 --- a/resources/Shaders/ForwardPlus.frag.glsl +++ b/resources/Shaders/ForwardPlus.frag.glsl @@ -12,6 +12,7 @@ uniform vec4 FillColor; uniform vec4 AmbientColor; uniform float FillPercentage; uniform float GlowIntensity = 10; +uniform vec3 CameraPosition; uniform vec2 DiffuseUVRepeat; uniform vec2 NormalUVRepeat; @@ -22,6 +23,7 @@ layout (binding = 1) uniform sampler2D DiffuseTexture; layout (binding = 2) uniform sampler2D NormalMapTexture; layout (binding = 3) uniform sampler2D SpecularMapTexture; layout (binding = 4) uniform sampler2D GlowMapTexture; +layout (binding = 5) uniform samplerCube CubeMap; #define TILE_SIZE 16 @@ -76,7 +78,7 @@ struct LightResult { }; float CalcAttenuation(float radius, float dist, float falloff) { - return 1.0 - smoothstep(radius * 0.3, radius, dist); + return 1.0 - smoothstep(radius * falloff, radius, dist); } vec4 CalcSpecular(vec4 lightColor, vec4 viewVec, vec4 lightVec, vec4 normal) { @@ -132,7 +134,11 @@ void main() vec4 normal = V * CalcNormalMappedValue(Input.Normal, Input.Tangent, Input.BiTangent, Input.TextureCoordinate * NormalUVRepeat, NormalMapTexture); normal = normalize(normal); //vec4 normal = normalize(V * vec4(Input.Normal, 0.0)); - vec4 viewVec = normalize(-position); + vec4 viewVec = normalize(-position); + vec3 I = normalize(vec3(M * vec4(Input.Position, 1.0)) - CameraPosition); + vec3 R = reflect(-I, Input.Normal); + //R = vec3(P * vec4(R, 1.0)); + vec4 reflectionColor = texture(CubeMap, R); vec2 tilePos; tilePos.x = int(gl_FragCoord.x/TILE_SIZE); @@ -163,6 +169,9 @@ void main() vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); color_result = color_result * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)); + float specularResult = (specularTexel.r + specularTexel.g + specularTexel.b)/3.0; + vec4 reflectionTotal = reflectionColor * (1-specularTexel.a) * color_result.a; + color_result = color_result * clamp(1/specularTexel.a, 0, 1) + reflectionTotal; //vec4 color_result = (DiffuseColor + Input.ExplosionColor) * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)) * diffuseTexel * Color; @@ -172,9 +181,10 @@ void main() color_result += FillColor; } sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); - color_result += glowTexel*GlowIntensity; + //sceneColor = vec4(reflectionColor.xyz, 1); + color_result.xyz += glowTexel.xyz*GlowIntensity; - bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), 1.0); + bloomColor = vec4(max(color_result.xyz - 1.0, 0.0), clamp(color_result.a, 0, 1)); //Tiled Debug Code /* diff --git a/resources/Shaders/ForwardPlus.vert.glsl b/resources/Shaders/ForwardPlus.vert.glsl index d475d825..26686222 100644 --- a/resources/Shaders/ForwardPlus.vert.glsl +++ b/resources/Shaders/ForwardPlus.vert.glsl @@ -23,12 +23,12 @@ out VertexData{ void main() { gl_Position = P*V*M * vec4(Position, 1.0); - + mat4 TIM = transpose(inverse(M)); Output.Position = Position; Output.TextureCoordinate = TextureCoords; - Output.Normal = vec3(M * vec4(Normal, 0.0)); - Output.Tangent = vec3(M * vec4(Tangent, 0.0)); - Output.BiTangent = vec3(M * vec4(BiTangent, 0.0)); + Output.Normal = vec3(TIM * vec4(Normal, 0.0)); + Output.Tangent = vec3(TIM * vec4(Tangent, 0.0)); + Output.BiTangent = vec3(TIM * vec4(BiTangent, 0.0)); Output.ExplosionColor = vec4(1.0); Output.ExplosionPercentageElapsed = 0.0; } \ No newline at end of file diff --git a/src/Engine/Collision/CollisionSystem.cpp b/src/Engine/Collision/CollisionSystem.cpp index fcc3665f..95609ea6 100644 --- a/src/Engine/Collision/CollisionSystem.cpp +++ b/src/Engine/Collision/CollisionSystem.cpp @@ -12,55 +12,56 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c if (!boundingBox) { return; } + ComponentWrapper& cTransform = entity["Transform"]; EntityAABB& boxA = *boundingBox; bool everHitTheGround = false; - glm::vec3 size = boxA.Size(); - float diameter = std::min(size.x, size.z); - glm::vec3 prevOrigin = (glm::vec3)cPhysics["PrevOrigin"]; - glm::vec3 toCurrentPos = boxA.Origin() - prevOrigin; - float rayLength = glm::length(toCurrentPos) + 0.5f*diameter; - //If the entity has moved farther than the size of its box, we need to handle it specially. - bool traceCollision = rayLength > diameter; - //hack solution: If prevOrigin is less than -9000 in all dimensions, - //then it means it is not set, i.e. this is the first collision check for the entity. - if (traceCollision && glm::any(glm::greaterThan((glm::vec3)cPhysics["PrevOrigin"], glm::vec3(-9000.f)))) { - Ray ray(prevOrigin, toCurrentPos); - m_OctreeResult.clear(); - m_Octree->ObjectsPossiblyHitByRay(ray, m_OctreeResult); - for (auto& boxB : m_OctreeResult) { - if (boxA.Entity == boxB.Entity) { - continue; - } - bool hit; - float dist; - if (boxB.Entity.HasComponent("Model")) { - RawModel* model; - std::string res = (std::string)boxB.Entity["Model"]["Resource"]; - try { - model = ResourceManager::Load(res); - } catch (const std::exception&) { + auto prevPosIt = m_PrevPositions.find(entity); + if (prevPosIt != m_PrevPositions.end()) { + glm::vec3 size = boxA.Size(); + float diameter = std::min(size.x, size.z); + glm::vec3 prevOrigin = prevPosIt->second; + glm::vec3 toCurrentPos = boxA.Origin() - prevOrigin; + float rayLength = glm::length(toCurrentPos) + 0.5f*diameter; + //If the entity has moved farther than the size of its box, we need to handle it specially. + if (rayLength > diameter) { + Ray ray(prevOrigin, toCurrentPos); + m_OctreeResult.clear(); + m_Octree->ObjectsPossiblyHitByRay(ray, m_OctreeResult); + for (auto& boxB : m_OctreeResult) { + if (boxA.Entity == boxB.Entity) { continue; } - float u, v; - hit = Collision::RayVsModel(ray, model->Vertices(), model->m_Indices, Transform::ModelMatrix(boxB.Entity), dist, u, v); - } else { - hit = Collision::RayVsAABB(ray, boxB, dist); - } - if (hit && dist < rayLength) { - //Set the entity to where it was colliding, minus the maximum box size. - //TODO: Perhaps this should be done slightly more properly. - glm::vec3 newOriginPos = ray.Origin() + (dist - 0.707107f*diameter) * ray.Direction(); - glm::vec3 resolve = newOriginPos - boxA.Origin(); - (glm::vec3&)cTransform["Position"] += resolve; - boxA = *Collision::EntityAbsoluteAABB(entity); - if (resolve.y > 0) { - everHitTheGround = true; - (bool)cPhysics["IsOnGround"] = true; - ((glm::vec3&)cPhysics["Velocity"]).y = 0.f; + bool hit; + float dist; + if (boxB.Entity.HasComponent("Model")) { + RawModel* model; + std::string res = (std::string)boxB.Entity["Model"]["Resource"]; + try { + model = ResourceManager::Load(res); + } catch (const std::exception&) { + continue; + } + float u, v; + hit = Collision::RayVsModel(ray, model->Vertices(), model->m_Indices, Transform::ModelMatrix(boxB.Entity), dist, u, v); + } else { + hit = Collision::RayVsAABB(ray, boxB, dist); + } + if (hit && dist < rayLength) { + //Set the entity to where it was colliding, minus the maximum box size. + //TODO: Perhaps this should be done slightly more properly. + glm::vec3 newOriginPos = ray.Origin() + (dist - 0.707107f*diameter) * ray.Direction(); + glm::vec3 resolve = newOriginPos - boxA.Origin(); + (glm::vec3&)cTransform["Position"] += resolve; + boxA = *Collision::EntityAbsoluteAABB(entity); + if (resolve.y > 0) { + everHitTheGround = true; + (bool)cPhysics["IsOnGround"] = true; + ((glm::vec3&)cPhysics["Velocity"]).y = 0.f; + } + break; } - break; } } } @@ -86,10 +87,13 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c glm::mat4 modelMatrix = Transform::ModelMatrix(boxB.Entity); glm::vec3 inOutVelocity = (glm::vec3)cPhysics["Velocity"]; + bool notMovingxz = glm::all(glm::lessThan(glm::abs(glm::vec2(inOutVelocity.x, inOutVelocity.z)), glm::vec2(0.01f))) && prevPosIt != m_PrevPositions.end(); bool isOnGround = (bool)cPhysics["IsOnGround"]; float verticalStepHeight = (float)(double)cPhysics["VerticalStepHeight"]; if (Collision::AABBvsTriangles(boxA, model->Vertices(), model->m_Indices, modelMatrix, inOutVelocity, verticalStepHeight, isOnGround, resolutionVector)) { - (glm::vec3&)cTransform["Position"] += resolutionVector; + //Move the position to previous position if it is not moving in the xz-plane, else resolve with the resolution vector. + (glm::vec3&)cTransform["Position"] += notMovingxz ? prevPosIt->second - boxA.Origin() : resolutionVector; + boxA = *Collision::EntityAbsoluteAABB(entity); cPhysics["Velocity"] = inOutVelocity; if (isOnGround) { everHitTheGround = true; @@ -99,6 +103,7 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c } else if (Collision::AABBVsAABB(boxA, boxB, resolutionVector)) { //Enter here if boxB has no Model. (glm::vec3&)cTransform["Position"] += resolutionVector; + boxA = *Collision::EntityAbsoluteAABB(entity); if (resolutionVector.y > 0) { everHitTheGround = true; (bool)cPhysics["IsOnGround"] = true; @@ -112,5 +117,5 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c (bool)cPhysics["IsOnGround"] = false; } - (glm::vec3&)cPhysics["PrevOrigin"] = boxA.Origin(); + m_PrevPositions[entity] = boxA.Origin(); } diff --git a/src/Engine/Core/EntityWrapper.cpp b/src/Engine/Core/EntityWrapper.cpp index 4b45b8d0..b3bef55a 100644 --- a/src/Engine/Core/EntityWrapper.cpp +++ b/src/Engine/Core/EntityWrapper.cpp @@ -51,6 +51,40 @@ EntityWrapper EntityWrapper::FirstParentWithComponent(const std::string& compone return EntityWrapper::Invalid; } +EntityWrapper EntityWrapper::Clone(EntityWrapper parent /*= Invalid*/) +{ + if (!Valid()) { + return EntityWrapper::Invalid; + } + + EntityWrapper clone = cloneRecursive(*this, EntityWrapper::Invalid); + this->World->SetParent(clone.ID, parent.ID); + return clone; +} + +std::vector EntityWrapper::ChildrenWithComponent(const std::string& componentType) +{ + std::vector childrenWithComponent; + childrenWithComponentRecursive(componentType, *this, childrenWithComponent); + return childrenWithComponent; +} + +void EntityWrapper::DeleteChildren() +{ + auto itPair = this->World->GetDirectChildren(this->ID); + if (itPair.first == itPair.second) { + return; + } + + std::vector entitiesToDelete; + for (auto it = itPair.first; it != itPair.second; it++) { + entitiesToDelete.push_back(it->second); + } + for (auto& e : entitiesToDelete) { + this->World->DeleteEntity(e); + } +} + bool EntityWrapper::IsChildOf(EntityWrapper potentialParent) { EntityWrapper entity = *this; @@ -90,6 +124,11 @@ ComponentWrapper EntityWrapper::operator[](const char* componentName) } } +ComponentWrapper EntityWrapper::operator[](const std::string& componentName) +{ + return this->operator[](componentName.c_str()); +} + bool EntityWrapper::operator==(const EntityWrapper& e) const { return (this->ID == e.ID) && (this->World == e.World); @@ -111,7 +150,7 @@ EntityWrapper EntityWrapper::firstChildByNameRecursive(const std::string& name, return EntityWrapper::Invalid; } - auto itPair = this->World->GetChildren(parent); + auto itPair = this->World->GetDirectChildren(parent); if (itPair.first == itPair.second) { return EntityWrapper::Invalid; } @@ -131,3 +170,42 @@ EntityWrapper EntityWrapper::firstChildByNameRecursive(const std::string& name, return EntityWrapper::Invalid; } +EntityWrapper EntityWrapper::cloneRecursive(EntityWrapper entity, EntityWrapper parent) +{ + EntityWrapper clone = EntityWrapper(entity.World, entity.World->CreateEntity(parent.ID)); + entity.World->SetName(clone.ID, entity.Name()); + + // Clone components + for (auto& kv : entity.World->GetComponentPools()) { + if (kv.second->KnowsEntity(entity.ID)) { + ComponentWrapper c1 = kv.second->GetByEntity(entity.ID); + ComponentWrapper c2 = entity.World->AttachComponent(clone.ID, kv.first); + c1.Copy(c2); + } + } + + // Clone children + auto children = entity.World->GetDirectChildren(entity.ID); + for (auto it = children.first; it != children.second; ++it) { + EntityWrapper child(entity.World, it->second); + cloneRecursive(child, clone); + } + + return clone; +} + +void EntityWrapper::childrenWithComponentRecursive(const std::string& componentType, EntityWrapper& entity, std::vector& childrenWithComponent) +{ + auto itPair = this->World->GetDirectChildren(entity.ID); + if (itPair.first == itPair.second) { + return; + } + + for (auto it = itPair.first; it != itPair.second; ++it) { + EntityWrapper child = EntityWrapper(entity.World, it->second); + if (child.HasComponent(componentType)) { + childrenWithComponent.push_back(child); + } + childrenWithComponentRecursive(componentType, child, childrenWithComponent); + } +} diff --git a/src/Engine/Core/Util/Logging.cpp b/src/Engine/Core/Util/Logging.cpp index 63a6f380..c7612fd8 100644 --- a/src/Engine/Core/Util/Logging.cpp +++ b/src/Engine/Core/Util/Logging.cpp @@ -33,8 +33,8 @@ void _LOG(_LOG_LEVEL logLevel, const char* file, const char* func, unsigned int va_end(args); if (logLevel == LOG_LEVEL_ERROR) { - std::cerr << file << ":" << line << " " << func << std::endl; - std::cerr << _LOG_LEVEL_PREFIX[logLevel] << message << std::endl; + //std::cerr << file << ":" << line << " " << func << std::endl; + //std::cerr << _LOG_LEVEL_PREFIX[logLevel] << message << std::endl; } else { std::cout << _LOG_LEVEL_PREFIX[logLevel] << message << std::endl; } diff --git a/src/Engine/Core/World.cpp b/src/Engine/Core/World.cpp index 8788a92e..9b323ff4 100644 --- a/src/Engine/Core/World.cpp +++ b/src/Engine/Core/World.cpp @@ -127,7 +127,7 @@ void World::SetParent(EntityID entity, EntityID parent) m_EntityChildren.insert(std::make_pair(parent, entity)); } -const std::pair::const_iterator, std::unordered_multimap::const_iterator> World::GetChildren(EntityID entity) +const std::pair::const_iterator, std::unordered_multimap::const_iterator> World::GetDirectChildren(EntityID entity) { return m_EntityChildren.equal_range(entity); } diff --git a/src/Engine/Editor/EditorGUI.cpp b/src/Engine/Editor/EditorGUI.cpp index 70775a2b..f2690f13 100644 --- a/src/Engine/Editor/EditorGUI.cpp +++ b/src/Engine/Editor/EditorGUI.cpp @@ -598,6 +598,19 @@ bool EditorGUI::OnKeyDown(const Events::KeyDown& e) entityImport(m_World); } + if (e.ModCtrl && e.KeyCode == GLFW_KEY_C) { + m_CopyTarget = m_CurrentSelection; + } + + if (e.ModCtrl && e.KeyCode == GLFW_KEY_V) { + if (m_OnEntityPaste != nullptr) { + EntityWrapper copy = m_OnEntityPaste(m_CopyTarget, m_CurrentSelection); + if (copy != EntityWrapper::Invalid) { + SelectEntity(copy); + } + } + } + if (e.KeyCode == GLFW_KEY_DELETE) { if (m_CurrentSelection.Valid()) { entityDelete(m_CurrentSelection); diff --git a/src/Engine/Editor/EditorSystem.cpp b/src/Engine/Editor/EditorSystem.cpp index 97ea9d53..4bee1427 100644 --- a/src/Engine/Editor/EditorSystem.cpp +++ b/src/Engine/Editor/EditorSystem.cpp @@ -28,6 +28,7 @@ EditorSystem::EditorSystem(SystemParams params, IRenderer* renderer, RenderFrame m_EditorGUI->SetEntityDeleteCallback(std::bind(&EditorSystem::OnEntityDelete, this, std::placeholders::_1)); m_EditorGUI->SetEntityChangeParentCallback(std::bind(&EditorSystem::OnEntityChangeParent, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetEntityChangeNameCallback(std::bind(&EditorSystem::OnEntityChangeName, this, std::placeholders::_1, std::placeholders::_2)); + m_EditorGUI->SetEntityPasteCallback(std::bind(&EditorSystem::OnEntityPaste, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetComponentAttachCallback(std::bind(&EditorSystem::OnComponentAttach, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetComponentDeleteCallback(std::bind(&EditorSystem::OnComponentDelete, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetWidgetModeCallback(std::bind(&EditorSystem::setWidgetMode, this, std::placeholders::_1)); @@ -160,6 +161,11 @@ void EditorSystem::OnEntityChangeName(EntityWrapper entity, const std::string& n } } +EntityWrapper EditorSystem::OnEntityPaste(EntityWrapper entityToCopy, EntityWrapper parent) +{ + return entityToCopy.Clone(parent); +} + void EditorSystem::OnComponentAttach(EntityWrapper entity, const std::string& componentType) { if (entity.Valid()) { diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index a2f52adb..d8da7e16 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -1,7 +1,7 @@ #include "Network/Client.h" using namespace boost::asio::ip; -Client::Client(World* world, EventBroker* eventBroker) +Client::Client(World* world, EventBroker* eventBroker) : Network(world, eventBroker) { // Asumes root node is EntityID_Invalid @@ -13,6 +13,8 @@ Client::Client(World* world, EventBroker* eventBroker) m_PlayerName = config->Get("Networking.Name", "Raptorcopter"); m_SendInputIntervalMs = config->Get("Networking.SendInputIntervalMs", 33); LOG_INFO("Client initialized"); + + m_ServerlistRequest.Connect(m_PlayerName, "192.168.1.255", 32554); } Client::Client(World* world, EventBroker* eventBroker, std::unique_ptr snapshotFilter) @@ -30,6 +32,8 @@ void Client::Connect(std::string address, int port) EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &Client::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &Client::OnPlayerDamage); EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &Client::OnPlayerSpawned); + EVENT_SUBSCRIBE_MEMBER(m_EDoubleJump, &Client::OnDoubleJump); + EVENT_SUBSCRIBE_MEMBER(m_ESearchForServers, &Client::OnSearchForServers); auto config = ResourceManager::Load("Config.ini"); m_Address = address; if (address.empty()) { @@ -66,6 +70,21 @@ void Client::Update() } + while (m_ServerlistRequest.IsSocketAvailable()) { + Packet packet(MessageType::Invalid); + m_ServerlistRequest.Receive(packet); + if (packet.GetMessageType() == MessageType::ServerlistRequest) { + parseServerlist(packet); + } + } + + if (m_SearchingForServers) { + if (m_SearchingTime < (1000* (std::clock() - m_StartSearchTime) / (double)CLOCKS_PER_SEC)) { + m_SearchingForServers = false; + displayServerlist(); + } + } + if (m_IsConnected) { // Don't send 1 input in 1 packet, bunch em up. if (m_SendInputIntervalMs < (1000 * (std::clock() - m_TimeSinceSentInputs) / (double)CLOCKS_PER_SEC)) { @@ -122,6 +141,9 @@ void Client::parseMessageType(Packet& packet) case MessageType::OnPlayerDamage: parsePlayerDamage(packet); break; + case MessageType::OnDoubleJump: + parseDoubleJump(packet); + break; default: break; } @@ -173,6 +195,22 @@ void Client::parsePing() m_Reliable.Send(packet); } + +void Client::parseServerlist(Packet& packet) +{ + // Pop size, message type, and ID + packet.ReadPrimitive(); + packet.ReadPrimitive(); + packet.ReadPrimitive(); + std::string address = packet.ReadString(); + int port = packet.ReadPrimitive(); + std::string serverName = packet.ReadString(); + int playersConnected = packet.ReadPrimitive(); + //TODO: This should not happen when a client is connected to a server + + m_Serverlist.push_back({ address, port, serverName, playersConnected }); +} + void Client::parseKick() { LOG_WARNING("You have been kicked from the server."); @@ -190,12 +228,12 @@ void Client::parseSpawnEvents() } e.Player = EntityWrapper(m_World, m_ServerIDToClientID.at(m_PlayerSpawnEvents.at(i).Player.ID)); //e.Spawner = EntityWrapper(m_World, m_ServerIDToClientID.at(m_PlayerSpawnEvents.at(i).Spawner.ID)); - e.PlayerID = -1; + e.PlayerID = -1; e.PlayerName = m_PlayerSpawnEvents.at(i).PlayerName; m_EventBroker->Publish(e); } m_PlayerSpawnEvents = tempSpawn; - // m_PlayerSpawnEvents.clear(); + // m_PlayerSpawnEvents.clear(); } void Client::parsePlayersSpawned(Packet& packet) @@ -223,8 +261,14 @@ void Client::parseEntityDeletion(Packet & packet) if (m_ServerIDToClientID.find(entityToDelete) != m_ServerIDToClientID.end()) { EntityID localEntity = m_ServerIDToClientID.at(entityToDelete); if (m_World->ValidEntity(localEntity)) { - m_World->DeleteEntity(localEntity); - deleteFromServerClientMaps(entityToDelete, localEntity); + if (m_World->HasComponent(localEntity,"Player")) { + Events::PlayerDeath e; + e.Player = EntityWrapper(m_World, localEntity); + m_EventBroker->Publish(e); + } else { + m_World->DeleteEntity(localEntity); + deleteFromServerClientMaps(entityToDelete, localEntity); + } } } } @@ -238,6 +282,20 @@ void Client::parseComponentDeletion(Packet & packet) } } +void Client::parseDoubleJump(Packet & packet) +{ + EntityID serverID = packet.ReadPrimitive(); + if (!serverClientMapsHasEntity(serverID)) { + return; + } + Events::DoubleJump e; + e.entityID = m_ServerIDToClientID.at(serverID); + // If player is local player do not publish to prevent infinite feedback loop + if (e.entityID != m_LocalPlayer.ID) { + m_EventBroker->Publish(e); + } +} + void Client::updateFields(Packet& packet, const ComponentInfo& componentInfo, const EntityID& entityID) { for (auto field : componentInfo.FieldsInOrder) { @@ -312,19 +370,20 @@ void Client::parseSnapshot(Packet& packet) if (serverClientMapsHasEntity(serverEntityID)) { EntityID localEntityID = m_ServerIDToClientID.at(serverEntityID); EntityWrapper localEntity(m_World, localEntityID); - // Update entity if (m_World->HasComponent(localEntityID, componentType)) { + // TODO Fix memory leak here SharedComponentWrapper newComponent = createSharedComponent(packet, localEntityID, componentInfo); bool shouldApply = true; // Apply potential filter function if (m_SnapshotFilter != nullptr) { shouldApply = m_SnapshotFilter->FilterComponent(localEntity, newComponent); } - if (shouldApply) { + if (shouldApply) { ComponentWrapper currentComponent = m_World->GetComponent(localEntityID, componentType); memcpy(currentComponent.Data, newComponent.Data, componentInfo.Stride); } + //if (localEntity != m_LocalPlayer && !localEntity.IsChildOf(m_LocalPlayer)) { // updateFields(packet, componentInfo, localEntityID); //} else { @@ -341,7 +400,11 @@ void Client::parseSnapshot(Packet& packet) if (serverParentID == EntityID_Invalid) { newLocalEntityID = m_World->CreateEntity(EntityID_Invalid); } else { - newLocalEntityID = m_World->CreateEntity(m_ServerIDToClientID.at(serverParentID)); + if (serverClientMapsHasEntity(serverParentID)) { + newLocalEntityID = m_World->CreateEntity(m_ServerIDToClientID.at(serverParentID)); + } else { + newLocalEntityID = m_World->CreateEntity(EntityID_Invalid); + } } m_World->SetName(newLocalEntityID, serverEntityName); insertIntoServerClientMaps(serverEntityID, newLocalEntityID); @@ -351,9 +414,11 @@ void Client::parseSnapshot(Packet& packet) } // Parent logic // This should be enough beacause we know that the entities arives in pre-order (there will always be a parent) - if (serverParentID != EntityID_Invalid) { + if (serverParentID != EntityID_Invalid && serverClientMapsHasEntity(serverParentID)) { EntityID localEntityID = m_ServerIDToClientID.at(serverEntityID); - m_World->SetParent(localEntityID, m_ServerIDToClientID.at(serverParentID)); + if (m_World->GetParent(localEntityID) != m_ServerIDToClientID.at(serverParentID)) { + m_World->SetParent(localEntityID, m_ServerIDToClientID.at(serverParentID)); + } } } parseSpawnEvents(); @@ -371,6 +436,12 @@ void Client::disconnect() bool Client::OnInputCommand(const Events::InputCommand & e) { + // TEMP + if (e.Command == "SearchForServers" && e.Value > 0) { + Events::SearchForServers e; + m_EventBroker->Publish(e); + } + if (e.PlayerID != -1) { return false; } @@ -415,6 +486,11 @@ bool Client::OnPlayerDamage(const Events::PlayerDamage & e) if (e.Inflictor != m_LocalPlayer) { return false; } + // Could this happen? + //if (!clientServerMapsHasEntity(e.Inflictor.ID) + // || !clientServerMapsHasEntity(e.Victim.ID)) { + // return; + //} Packet packet(MessageType::OnPlayerDamage, m_SendPacketID); packet.WritePrimitive(m_ClientIDToServerID.at(e.Inflictor.ID)); @@ -433,12 +509,23 @@ bool Client::OnPlayerSpawned(const Events::PlayerSpawned& e) return true; } +bool Client::OnSearchForServers(const Events::SearchForServers& e) +{ + m_SearchingForServers = true; + m_StartSearchTime = std::clock(); + m_Serverlist.clear(); + LOG_INFO("Searching for LAN servers...\n"); + Packet packet(MessageType::ServerlistRequest); + m_ServerlistRequest.Broadcast(packet, 13); // TODO: Config + return true; +} + void Client::parsePlayerDamage(Packet& packet) { Events::PlayerDamage e; PlayerID victimID = packet.ReadPrimitive(); PlayerID inflictorID = packet.ReadPrimitive(); - if(!serverClientMapsHasEntity(victimID) || !serverClientMapsHasEntity(inflictorID)){ + if (!serverClientMapsHasEntity(victimID) || !serverClientMapsHasEntity(inflictorID)) { return; } e.Inflictor = EntityWrapper(m_World, m_ServerIDToClientID.at(victimID)); @@ -450,6 +537,17 @@ void Client::parsePlayerDamage(Packet& packet) } } +bool Client::OnDoubleJump(Events::DoubleJump & e) +{ + if (!clientServerMapsHasEntity(e.entityID) || e.entityID != m_LocalPlayer.ID) { + return false; + } + Packet packet(MessageType::OnDoubleJump); + packet.WritePrimitive(m_ClientIDToServerID.at(e.entityID)); + m_Reliable.Send(packet); + return true; +} + void Client::sendLocalPlayerTransform() { if (!m_LocalPlayer.Valid()) { @@ -467,7 +565,7 @@ void Client::sendLocalPlayerTransform() packet.WritePrimitive(orientation.x); packet.WritePrimitive(orientation.y); packet.WritePrimitive(orientation.z); - + bool hasAssaultWeapon = m_LocalPlayer.HasComponent("AssaultWeapon"); packet.WritePrimitive(hasAssaultWeapon); if (hasAssaultWeapon) { @@ -475,7 +573,7 @@ void Client::sendLocalPlayerTransform() packet.WritePrimitive((int)cAssaultWeapon["MagazineAmmo"]); packet.WritePrimitive((int)cAssaultWeapon["Ammo"]); } - + m_Unreliable.Send(packet); } @@ -528,6 +626,16 @@ void Client::becomePlayer() m_Reliable.Send(packet); } + +void Client::displayServerlist() +{ + LOG_INFO("This is a serverlist:\n"); + for (int i = 0; i < m_Serverlist.size(); i++) { + ServerInfo si = m_Serverlist[i]; + LOG_INFO("%s:%i\t%s\t%i\n", si.Address.c_str(), si.Port, si.Name.c_str(), si.PlayersConnected); + } +} + bool Client::clientServerMapsHasEntity(EntityID clientEntityID) { if (m_ClientIDToServerID.find(clientEntityID) != m_ClientIDToServerID.end()) { diff --git a/src/Engine/Network/HybridClient.cpp b/src/Engine/Network/HybridClient.cpp deleted file mode 100644 index 4200e8e3..00000000 --- a/src/Engine/Network/HybridClient.cpp +++ /dev/null @@ -1,10 +0,0 @@ -#include "Network/HybridClient.h" - - -HybridClient::HybridClient() -{ -} - -HybridClient::~HybridClient() -{ -} \ No newline at end of file diff --git a/src/Engine/Network/HybridServer.cpp b/src/Engine/Network/HybridServer.cpp deleted file mode 100644 index bfcdaee0..00000000 --- a/src/Engine/Network/HybridServer.cpp +++ /dev/null @@ -1,9 +0,0 @@ -#include "Network/HybridServer.h" - -HybridServer::HybridServer() -{ -} - -HybridServer::~HybridServer() -{ -} \ No newline at end of file diff --git a/src/Engine/Network/NetworkClient.cpp b/src/Engine/Network/NetworkClient.cpp index e69de29b..7a61d5f3 100644 --- a/src/Engine/Network/NetworkClient.cpp +++ b/src/Engine/Network/NetworkClient.cpp @@ -0,0 +1,11 @@ +#include "Network/NetworkClient.h" + +NetworkClient::NetworkClient() +{ + m_ReadBuffer = new char[m_BufferSize]; +} + +NetworkClient::~NetworkClient() +{ + delete[] m_ReadBuffer; +} diff --git a/src/Engine/Network/NetworkServer.cpp b/src/Engine/Network/NetworkServer.cpp new file mode 100644 index 00000000..1412621d --- /dev/null +++ b/src/Engine/Network/NetworkServer.cpp @@ -0,0 +1,11 @@ +#include "Network/NetworkServer.h" + +NetworkServer::NetworkServer() +{ + m_ReadBuffer = new char[m_BufferSize]; +} + +NetworkServer::~NetworkServer() +{ + delete[] m_ReadBuffer; +} diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index aa66433b..7c614cee 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -1,7 +1,8 @@ #include "Network/Server.h" -Server::Server(World* world, EventBroker* eventBroker, int port) +Server::Server(World* world, EventBroker* eventBroker, int port) : Network(world, eventBroker) + , m_ServerlistRequest(13) { ConfigFile* config = ResourceManager::Load("Config.ini"); snapshotInterval = 1000 * config->Get("Networking.SnapshotInterval", 0.05f); @@ -13,7 +14,7 @@ Server::Server(World* world, EventBroker* eventBroker, int port) EVENT_SUBSCRIBE_MEMBER(m_EComponentDeleted, &Server::OnComponentDeleted); EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &Server::OnPlayerDamage); - // Bind + // BindWW if (port == 0) { port = config->Get("Networking.Port", 27666); } @@ -28,9 +29,8 @@ Server::~Server() void Server::Update() { - PlayerDefinition pd; - m_Reliable.AcceptNewConnections(m_NextPlayerID, m_ConnectedPlayers); + for (auto& kv : m_ConnectedPlayers) { while (kv.second.TCPSocket->available()) { // Packet will get real data in receive @@ -46,6 +46,7 @@ void Server::Update() } } + PlayerDefinition pd; while (m_Unreliable.IsSocketAvailable()) { // Packet will get real data in receive Packet packet(MessageType::Invalid); @@ -58,6 +59,22 @@ void Server::Update() parseMessageType(packet); } } + + while (m_ServerlistRequest.IsSocketAvailable()) { + Packet packet(MessageType::Invalid); + PlayerDefinition localArea; + localArea.Endpoint = boost::asio::ip::udp::endpoint(); + m_ServerlistRequest.Receive(packet, localArea); + if (packet.GetMessageType() == MessageType::ServerlistRequest) { + packet.ReadPrimitive(); // Pop size + packet.ReadPrimitive(); // Pop MsgType + packet.ReadPrimitive(); // Pop packet ID + int port = packet.ReadPrimitive(); + std::string address = localArea.Endpoint.address().to_string(); + parseServerlistRequest(boost::asio::ip::udp::endpoint(boost::asio::ip::address().from_string(address), port)); + } + } + // Check if players have disconnected for (int i = 0; i < m_PlayersToDisconnect.size(); i++) { disconnect(m_PlayersToDisconnect.at(i)); @@ -75,6 +92,7 @@ void Server::Update() sendPing(); previousePingMessage = currentTime; } + // Time out logic if (checkTimeOutInterval < (1000 * (currentTime - timOutTimer) / (double)CLOCKS_PER_SEC)) { checkForTimeOuts(); @@ -120,6 +138,9 @@ void Server::parseMessageType(Packet& packet) case MessageType::PlayerTransform: parsePlayerTransform(packet); break; + case MessageType::OnDoubleJump: + parseDoubleJump(packet); + break; default: break; } @@ -146,7 +167,7 @@ void Server::sendSnapshot() { Packet packet(MessageType::Snapshot); addInputCommandsToPacket(packet); - addChildrenToPacket(packet, EntityID_Invalid); + addPlayersToPacket(packet, EntityID_Invalid); unreliableBroadcast(packet); } @@ -163,19 +184,61 @@ void Server::addInputCommandsToPacket(Packet& packet) m_InputCommandsToBroadcast.clear(); } -void Server::addChildrenToPacket(Packet & packet, EntityID entityID) +void Server::addPlayersToPacket(Packet & packet, EntityID entityID) { - auto itPair = m_World->GetChildren(entityID); + auto itPair = m_World->GetDirectChildren(entityID); std::unordered_map worldComponentPools = m_World->GetComponentPools(); // Loop through every child for (auto it = itPair.first; it != itPair.second; it++) { EntityID childEntityID = it->second; // HACK: Only sync players for now, since the map turned out to be TOO LARGE to send in one snapshot and Simon's computer shits itself + // HACK: Also checked CapturePointHUD for now. (this would get out of sync); EntityWrapper childEntity(m_World, childEntityID); - if (!shouldSendToClient(childEntity)) { - continue; + if (shouldSendToClient(childEntity)) { + // Write EntityID and parentsID and Entity name + packet.WritePrimitive(childEntityID); + packet.WritePrimitive(entityID); + packet.WriteString(m_World->GetName(childEntityID)); + // Write components to child + int numberOfComponents = 0; + for (auto& i : worldComponentPools) { + if (i.second->KnowsEntity(childEntityID)) { + numberOfComponents++; + } + } + // Write how many components should be read + packet.WritePrimitive(numberOfComponents); + for (auto& i : worldComponentPools) { + // If the entity exist in the pool + if (i.second->KnowsEntity(childEntityID)) { + ComponentWrapper componentWrapper = i.second->GetByEntity(childEntityID); + // ComponentType + packet.WriteString(componentWrapper.Info.Name); + // Loop through fields + for (auto& componentField : componentWrapper.Info.FieldsInOrder) { + ComponentInfo::Field_t fieldInfo = componentWrapper.Info.Fields.at(componentField); + if (fieldInfo.Type == "string") { + std::string& value = componentWrapper[componentField]; + packet.WriteString(value); + } else { + packet.WriteData(componentWrapper.Data + fieldInfo.Offset, fieldInfo.Stride); + } + } + } + } } + // Go to to your children + addPlayersToPacket(packet, childEntityID); + } +} +void Server::addChildrenToPacket(Packet & packet, EntityID entityID) +{ + auto itPair = m_World->GetDirectChildren(entityID); + std::unordered_map worldComponentPools = m_World->GetComponentPools(); + // Loop through every child + for (auto it = itPair.first; it != itPair.second; it++) { + EntityID childEntityID = it->second; // Write EntityID and parentsID and Entity name packet.WritePrimitive(childEntityID); packet.WritePrimitive(entityID); @@ -230,6 +293,8 @@ void Server::sendPing() reliableBroadcast(packet); } + + void Server::checkForTimeOuts() { double startPing = 1000 * m_StartPingTime @@ -279,7 +344,7 @@ void Server::parseTCPConnect(Packet & packet) // Read packet ID m_PreviousPacketID = m_PacketID; // Set previous packet id m_PacketID = packet.ReadPrimitive(); //Read new packet id - + LOG_INFO("Parsing connections"); // Check if player is already connected // Ska vara till lagd i TCPServer receive @@ -304,6 +369,11 @@ void Server::parseTCPConnect(Packet & packet) connnectPacket.WritePrimitive(playerID); m_Reliable.Send(connnectPacket); + Packet firstSnapshot(MessageType::Snapshot); + addInputCommandsToPacket(firstSnapshot); + addChildrenToPacket(firstSnapshot, EntityID_Invalid); + m_Reliable.Send(firstSnapshot); + // Send notification that a player has connected //Packet notificationPacket(MessageType::PlayerConnected); //broadcast(notificationPacket); @@ -322,6 +392,17 @@ void Server::parseDisconnect() } } + +void Server::parseServerlistRequest(boost::asio::ip::udp::endpoint endpoint) +{ + Packet packet(MessageType::ServerlistRequest); + packet.WriteString(m_Reliable.Address()); + packet.WritePrimitive(m_Reliable.Port()); + packet.WriteString("SERVERNAME"); + packet.WritePrimitive(m_ConnectedPlayers.size()); + m_ServerlistRequest.Send(packet); +} + void Server::disconnect(PlayerID playerID) { //broadcast("A player disconnected"); @@ -346,6 +427,7 @@ void Server::parseOnPlayerDamage(Packet & packet) e.Victim = EntityWrapper(m_World, packet.ReadPrimitive()); e.Damage = packet.ReadPrimitive(); m_EventBroker->Publish(e); + //LOG_DEBUG("Server::parseOnPlayerDamage: Command is %s. Value is %f. PlayerID is %i.", e.DamageAmount, e.PlayerDamagedID, e.TypeOfDamage.c_str()); } @@ -374,8 +456,7 @@ bool Server::OnInputCommand(const Events::InputCommand & e) } isReadingData = !isReadingData; m_SaveDataTimer = std::clock(); - } - if (e.Command == "KickPlayer" && e.Value > 0) { + } else if (e.Command == "KickPlayer" && e.Value > 0) { kick(0); } @@ -426,7 +507,7 @@ bool Server::OnPlayerDamage(const Events::PlayerDamage& e) packet.WritePrimitive(e.Damage); reliableBroadcast(packet); - return false; + return true; } void Server::parseClientPing() @@ -446,13 +527,21 @@ void Server::parsePing() { for (auto& kv : m_ConnectedPlayers) { if (kv.second.TCPAddress == m_Address && - kv.second.TCPPort == m_Port) { + kv.second.TCPPort == m_Port + || (kv.second.Endpoint.address() == m_Address + && kv.second.Endpoint.port() == m_Port)) { kv.second.StopTime = std::clock(); break; } } } +bool Server::parseDoubleJump(Packet & packet) +{ + reliableBroadcast(packet); + return true; +} + void Server::parseOnInputCommand(Packet& packet) { PlayerID player = -1; @@ -512,7 +601,15 @@ void Server::parsePlayerTransform(Packet& packet) bool Server::shouldSendToClient(EntityWrapper childEntity) { - return childEntity.HasComponent("Player") || childEntity.FirstParentWithComponent("Player").Valid(); + auto children = m_World->GetDirectChildren(childEntity.ID); + for (auto it = children.first; it != children.second; it++) { + EntityWrapper child(m_World, it->second); + if(child.HasComponent("CapturePoint")) { + return true; + } + } + return childEntity.HasComponent("Player") || childEntity.FirstParentWithComponent("Player").Valid() + || childEntity.HasComponent("CapturePoint"); } PlayerID Server::GetPlayerIDFromEndpoint() diff --git a/src/Engine/Network/TCPClient.cpp b/src/Engine/Network/TCPClient.cpp index df4f3826..f3394d3d 100644 --- a/src/Engine/Network/TCPClient.cpp +++ b/src/Engine/Network/TCPClient.cpp @@ -56,32 +56,42 @@ void TCPClient::Disconnect() void TCPClient::Receive(Packet& packet) { - size_t bytesRead = readBuffer(m_ReadBuffer); + size_t bytesRead = readBuffer(); if (bytesRead > 0) { packet.ReconstructFromData(m_ReadBuffer, bytesRead); } } -size_t TCPClient::readBuffer(char* data) +size_t TCPClient::readBuffer() { if (!m_Socket) { return 0; } boost::system::error_code error; // Read size of packet - size_t bytesReceived = m_Socket->read_some(boost - ::asio::buffer((void*)data, sizeof(int)), - error); - int sizeOfPacket = 0; - memcpy(&sizeOfPacket, data, sizeof(int)); + m_Socket->receive(boost + ::asio::buffer((void*)m_ReadBuffer, sizeof(int)), + boost::asio::ip::tcp::socket::message_peek, error); + unsigned int sizeOfPacket = 0; + memcpy(&sizeOfPacket, m_ReadBuffer, sizeof(int)); + // if the buffer is to small increase the size of it + // TODO if message is huge 1 time the buffer will not decrease. + if (sizeOfPacket > m_BufferSize) { + delete[] m_ReadBuffer; + m_ReadBuffer = new char[sizeOfPacket]; + m_BufferSize = sizeOfPacket; + } // Read the rest of the message - bytesReceived += m_Socket->read_some(boost - ::asio::buffer((void*)(data + bytesReceived), sizeOfPacket - bytesReceived), + size_t bytesReceived = m_Socket->read_some(boost + ::asio::buffer((void*)(m_ReadBuffer), sizeOfPacket), error); if (error) { //LOG_ERROR("receive: %s", error.message().c_str()); } + if (sizeOfPacket > 1000000) + LOG_WARNING("The packets received are bigger than 1MB"); + return bytesReceived; } diff --git a/src/Engine/Network/TCPServer.cpp b/src/Engine/Network/TCPServer.cpp index a449e684..acd3d6d0 100644 --- a/src/Engine/Network/TCPServer.cpp +++ b/src/Engine/Network/TCPServer.cpp @@ -1,25 +1,38 @@ #include "Network/TCPServer.h" using namespace boost::asio::ip; -TCPServer::TCPServer() +TCPServer::TCPServer() { acceptor = std::unique_ptr(new tcp::acceptor(m_IOService, tcp::endpoint(tcp::v4(), 27666))); + // Make the acceptor non-blocking so we wont get stuck in AcceptNewConnections(). + acceptor->non_blocking(true); + m_Port = GetPort(); + m_Address = GetAddress(); } TCPServer::~TCPServer() -{ -} +{ } void TCPServer::AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers) { + boost::system::error_code error; boost::shared_ptr newSocket = boost::shared_ptr(new tcp::socket(m_IOService)); - m_IOService.poll(); - acceptor->async_accept(*newSocket, - boost::bind(&TCPServer::handle_accept, this, newSocket, boost::ref(nextPlayerID), boost::ref(connectedPlayers), - boost::asio::placeholders::error)); + acceptor->accept(*newSocket, error); + // If no error occured add new tcp connection + if (!error) { + // Add tcp socket to connections + boost::asio::ip::tcp::no_delay option(true); + newSocket->set_option(option); + PlayerDefinition pd; + pd.StopTime = std::clock(); + pd.TCPSocket = newSocket; + pd.TCPAddress = newSocket.get()->remote_endpoint().address(); + pd.TCPPort = newSocket.get()->remote_endpoint().port(); + connectedPlayers[nextPlayerID++] = pd; + } } -PlayerID GetPlayerIDFromEndpoint(const std::map& connectedPlayers, +PlayerID TCPServer::getPlayerIDFromEndpoint(const std::map& connectedPlayers, boost::asio::ip::address address, unsigned short port) { for (auto& kv : connectedPlayers) { @@ -31,28 +44,10 @@ PlayerID GetPlayerIDFromEndpoint(const std::map& con return -1; } -void TCPServer::handle_accept(boost::shared_ptr socket, - int& nextPlayerID, std::map& connectedPlayers, - const boost::system::error_code& error) -{ - if (!error && GetPlayerIDFromEndpoint(connectedPlayers, socket->remote_endpoint().address(), - socket->remote_endpoint().port()) == -1) { - // Add tcp socket to connections - boost::asio::ip::tcp::no_delay option(true); - socket->set_option(option); - PlayerDefinition pd; - pd.StopTime = std::clock(); - pd.TCPSocket = socket; - pd.TCPAddress = socket.get()->remote_endpoint().address(); - pd.TCPPort = socket.get()->remote_endpoint().port(); - connectedPlayers[nextPlayerID++] = pd; - } -} - void TCPServer::Send(Packet & packet, PlayerDefinition & playerDefinition) { + packet.UpdateSize(); try { - packet.UpdateSize(); int bytesSent = playerDefinition.TCPSocket->send( boost::asio::buffer(packet.Data(), packet.Size()), 0); @@ -73,38 +68,60 @@ void TCPServer::Send(Packet & packet) } void TCPServer::Disconnect() -{ +{ +} +int TCPServer::GetPort() +{ + return acceptor->local_endpoint().port(); +} + +std::string TCPServer::GetAddress() +{ + boost::asio::ip::tcp::resolver resolver(m_IOService); + boost::asio::ip::tcp::resolver::query query(boost::asio::ip::tcp::v4(), boost::asio::ip::host_name(), ""); + boost::asio::ip::tcp::resolver::iterator it = resolver.resolve(query); + boost::asio::ip::tcp::endpoint endpoint = *it; + return endpoint.address().to_string().c_str(); } void TCPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition) { - int bytesRead = readBuffer(m_ReadBuffer, playerDefinition); + int bytesRead = readBuffer(playerDefinition); if (bytesRead > 0) { packet.ReconstructFromData(m_ReadBuffer, bytesRead); } lastReceivedSocket = playerDefinition.TCPSocket; } -int TCPServer::readBuffer(char* data, PlayerDefinition & playerDefinition) +int TCPServer::readBuffer(PlayerDefinition & playerDefinition) { if (!playerDefinition.TCPSocket) { return 0; } boost::system::error_code error; // Read size of packet - size_t bytesReceived = playerDefinition.TCPSocket->read_some(boost - ::asio::buffer((void*)data, sizeof(int)), - error); - int sizeOfPacket = 0; - memcpy(&sizeOfPacket, data, sizeof(int)); + playerDefinition.TCPSocket->receive(boost + ::asio::buffer((void*)m_ReadBuffer, sizeof(int)), + boost::asio::ip::tcp::socket::message_peek, error); + unsigned int sizeOfPacket = 0; + memcpy(&sizeOfPacket, m_ReadBuffer, sizeof(int)); + // if the buffer is to small increase the size of it + if (sizeOfPacket > m_BufferSize) { + delete[] m_ReadBuffer; + m_ReadBuffer = new char[sizeOfPacket]; + m_BufferSize = sizeOfPacket; + } // Read the rest of the message - bytesReceived += playerDefinition.TCPSocket->read_some(boost - ::asio::buffer((void*)(data + bytesReceived), sizeOfPacket - bytesReceived), + size_t bytesReceived = playerDefinition.TCPSocket->read_some(boost + ::asio::buffer((void*)(m_ReadBuffer), sizeOfPacket), error); if (error) { //LOG_ERROR("receive: %s", error.message().c_str()); } + if (sizeOfPacket > 1000000) + LOG_WARNING("The packets received are bigger than 1MB"); + return bytesReceived; } \ No newline at end of file diff --git a/src/Engine/Network/UDPClient.cpp b/src/Engine/Network/UDPClient.cpp index c76de084..51c29920 100644 --- a/src/Engine/Network/UDPClient.cpp +++ b/src/Engine/Network/UDPClient.cpp @@ -15,9 +15,9 @@ void UDPClient::Connect(std::string playerName, std::string address, int port) if (m_Socket) { return; } - m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address::from_string(address), port); + m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address().from_string(address), port); m_Socket = boost::shared_ptr(new boost::asio::ip::udp::socket(m_IOService)); - m_Socket->connect(m_ReceiverEndpoint); + m_Socket->open(boost::asio::ip::udp::v4()); } void UDPClient::Disconnect() @@ -27,34 +27,66 @@ void UDPClient::Disconnect() void UDPClient::Receive(Packet& packet) { - int bytesRead = readBuffer(m_ReadBuffer); + int bytesRead = readBuffer(); if (bytesRead > 0) { packet.ReconstructFromData(m_ReadBuffer, bytesRead); } } -int UDPClient::readBuffer(char* data) +int UDPClient::readBuffer() { if (!m_Socket) { return 0; } boost::system::error_code error; - int bytesReceived = m_Socket->receive_from(boost - ::asio::buffer((void*)data, BUFFERSIZE), - m_ReceiverEndpoint, - 0, error); + // Read size of packet + m_Socket->receive(boost + ::asio::buffer((void*)m_ReadBuffer, sizeof(int)), + boost::asio::ip::udp::socket::message_peek, error); + int sizeOfPacket = 0; + memcpy(&sizeOfPacket, m_ReadBuffer, sizeof(int)); + + // if the buffer is to small increase the size of it + if (sizeOfPacket > m_BufferSize) { + delete[] m_ReadBuffer; + m_ReadBuffer = new char[sizeOfPacket]; + m_BufferSize = sizeOfPacket; + } + + size_t availableData = m_Socket->available(); + // Read the rest of the message + size_t bytesReceived = m_Socket->receive_from(boost + ::asio::buffer((void*)(m_ReadBuffer), + sizeOfPacket), + m_ReceiverEndpoint, 0, error); if (error) { //LOG_ERROR("receive: %s", error.message().c_str()); } + if (sizeOfPacket > 1000000) + LOG_WARNING("The packets received are bigger than 1MB"); + return bytesReceived; } void UDPClient::Send(Packet& packet) { + packet.UpdateSize(); m_Socket->send_to(boost::asio::buffer( packet.Data(), packet.Size()), m_ReceiverEndpoint, 0); +} + +void UDPClient::Broadcast(Packet& packet, int port) +{ + packet.UpdateSize(); + m_Socket->set_option(boost::asio::socket_base::broadcast(true)); + m_Socket->send_to(boost::asio::buffer( + packet.Data(), + packet.Size()), + udp::endpoint(boost::asio::ip::address_v4().broadcast(), port) + , 0); + m_Socket->set_option(boost::asio::socket_base::broadcast(false)); } bool UDPClient::IsSocketAvailable() diff --git a/src/Engine/Network/UDPServer.cpp b/src/Engine/Network/UDPServer.cpp index 4b0a08ba..635ebd4d 100644 --- a/src/Engine/Network/UDPServer.cpp +++ b/src/Engine/Network/UDPServer.cpp @@ -5,11 +5,17 @@ UDPServer::UDPServer() m_Socket = std::unique_ptr(new boost::asio::ip::udp::socket(m_IOService, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 27666))); } +UDPServer::UDPServer(int port) +{ + m_Socket = std::unique_ptr(new boost::asio::ip::udp::socket(m_IOService, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), port))); +} + UDPServer::~UDPServer() { } void UDPServer::Send(Packet& packet, PlayerDefinition & playerDefinition) { + packet.UpdateSize(); try { int bytesSent = m_Socket->send_to( boost::asio::buffer(packet.Data(), packet.Size()), @@ -23,6 +29,7 @@ void UDPServer::Send(Packet& packet, PlayerDefinition & playerDefinition) // Send back to endpoint of received packet void UDPServer::Send(Packet & packet) { + packet.UpdateSize(); m_Socket->send_to( boost::asio::buffer( packet.Data(), @@ -31,9 +38,35 @@ void UDPServer::Send(Packet & packet) 0); } +// Broadcasting respond specific logic +void UDPServer::Send(Packet & packet, boost::asio::ip::udp::endpoint endpoint) +{ + packet.UpdateSize(); + m_Socket->send_to( + boost::asio::buffer( + packet.Data(), + packet.Size()), + endpoint, + 0); +} + +// Broadcasting +void UDPServer::Broadcast(Packet & packet, int port) +{ + packet.UpdateSize(); + m_Socket->set_option(boost::asio::socket_base::broadcast(true)); + m_Socket->send_to( + boost::asio::buffer( + packet.Data(), + packet.Size()), + boost::asio::ip::udp::endpoint(boost::asio::ip::address_v4().broadcast(),port), + 0); + m_Socket->set_option(boost::asio::socket_base::broadcast(false)); +} + void UDPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition) { - int bytesRead = readBuffer(m_ReadBuffer); + int bytesRead = readBuffer(); if (bytesRead > 0) { packet.ReconstructFromData(m_ReadBuffer, bytesRead); } @@ -45,17 +78,39 @@ bool UDPServer::IsSocketAvailable() return m_Socket->available(); } -int UDPServer::readBuffer(char* data) +int UDPServer::readBuffer() { - boost::system::error_code error = boost::asio::error::host_not_found; - unsigned int length = m_Socket->receive_from( - boost::asio::buffer((void*)data - , BUFFERSIZE) - , m_ReceiverEndpoint, 0, error); - if (error) { - LOG_WARNING(error.message().c_str()); + if (!m_Socket) { + return 0; } - return length; + int addasdasd = m_Socket->available(); + boost::system::error_code error; + // Read size of packet + m_Socket->receive_from(boost + ::asio::buffer((void*)m_ReadBuffer, sizeof(int)), + m_ReceiverEndpoint, boost::asio::ip::udp::socket::message_peek, error); + unsigned int sizeOfPacket = 0; + memcpy(&sizeOfPacket, m_ReadBuffer, sizeof(int)); + + // if the buffer is to small increase the size of it + if (sizeOfPacket > m_BufferSize) { + delete[] m_ReadBuffer; + m_ReadBuffer = new char[sizeOfPacket]; + m_BufferSize = sizeOfPacket; + } + + // Read the rest of the message + size_t bytesReceived = m_Socket->receive_from(boost + ::asio::buffer((void*)(m_ReadBuffer), + sizeOfPacket), + m_ReceiverEndpoint, 0, error); + if (error) { + //LOG_ERROR("receive: %s", error.message().c_str()); + } + if (sizeOfPacket > 1000000) + LOG_WARNING("The packets received are bigger than 1MB"); + + return bytesReceived; } void UDPServer::AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers) diff --git a/src/Engine/Rendering/CubeMapPass.cpp b/src/Engine/Rendering/CubeMapPass.cpp new file mode 100644 index 00000000..e2a55b74 --- /dev/null +++ b/src/Engine/Rendering/CubeMapPass.cpp @@ -0,0 +1,41 @@ +#include "Rendering/CubeMapPass.h" + +CubeMapPass::CubeMapPass(IRenderer* renderer) + :m_Renderer(renderer) +{ + LoadTextures("Nevada"); +} + +void CubeMapPass::LoadTextures(std::string input) +{ + if (m_PreviusCubeMapTexture != input) { + m_CubeMapTextures.clear(); + for (int i = 0; i < 6; i++) { + std::string str; + str = "Textures/Test/CubeMap/" + input + "/CubeMapTest0" + std::to_string(i) + ".png"; + Texture* img = ResourceManager::Load(str); + m_CubeMapTextures.push_back(img); + } + GenerateCubeMapTexture(); + m_PreviusCubeMapTexture = input; + } +} + +void CubeMapPass::GenerateCubeMapTexture() +{ + if (m_CubeMapTexture == -1) { + glGenTextures(1, &m_CubeMapTexture); + } + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapTexture); + + for (int i = 0; i < 6; i++) { + glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA32F, m_CubeMapTextures[0]->Width, m_CubeMapTextures[0]->Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_CubeMapTextures[i]->Data); + } + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); + GLERROR("Generate Cubemap"); +} + diff --git a/src/Engine/Rendering/DrawBloomPass.cpp b/src/Engine/Rendering/DrawBloomPass.cpp index 6bfb58eb..e8ad4cd5 100644 --- a/src/Engine/Rendering/DrawBloomPass.cpp +++ b/src/Engine/Rendering/DrawBloomPass.cpp @@ -52,6 +52,7 @@ void DrawBloomPass::InitializeBuffers() void DrawBloomPass::ClearBuffer() { + GLERROR("PRE"); m_GaussianFrameBuffer_horiz.Bind(); glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); @@ -60,6 +61,7 @@ void DrawBloomPass::ClearBuffer() glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_GaussianFrameBuffer_vert.Unbind(); + GLERROR("END"); } void DrawBloomPass::Draw(GLuint texture) diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index a12c52b1..d084b919 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -1,10 +1,11 @@ #include "Rendering/DrawFinalPass.h" -DrawFinalPass::DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass) +DrawFinalPass::DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass, CubeMapPass* cubeMapPass) + : m_Renderer(renderer) + , m_LightCullingPass(lightCullingPass) + , m_CubeMapPass(cubeMapPass) { //TODO: Make sure that uniforms are not sent into shader if not needed. - m_Renderer = renderer; - m_LightCullingPass = lightCullingPass; m_ShieldPixelRate = 8; InitializeTextures(); InitializeShaderPrograms(); @@ -192,8 +193,12 @@ void DrawFinalPass::Draw(RenderScene& scene, GLuint SSAOTexture) state->StencilMask(0x00); DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene, SSAOTexture); GLERROR("OpaqueObjects"); + //state->BlendFunc(GL_ONE, GL_ONE); + state->BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene, SSAOTexture); GLERROR("TransparentObjects"); + //state->BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); DrawSprites(scene.Jobs.SpriteJob, scene); GLERROR("SpriteJobs"); @@ -259,20 +264,35 @@ void DrawFinalPass::Draw(RenderScene& scene, GLuint SSAOTexture) void DrawFinalPass::ClearBuffer() { + GLERROR("PRE"); m_FinalPassFrameBufferLowRes.Bind(); + GLERROR("Bind LowRes"); + glViewport(0, 0, m_Renderer->GetViewportSize().Width/m_ShieldPixelRate, m_Renderer->GetViewportSize().Height/m_ShieldPixelRate); glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + GLERROR("ViewPort,Scissor LowRes"); + glClearColor(0.f, 0.f, 0.f, 0.f); + GLERROR("1"); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + GLERROR("2"); + glDisable(GL_SCISSOR_TEST); + GLERROR("3"); + m_FinalPassFrameBufferLowRes.Unbind(); + GLERROR("prebind HighRes"); m_FinalPassFrameBuffer.Bind(); + GLERROR("Bind HighRes"); glViewport(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + GLERROR("ViewPort,Scissor LowRes"); glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_FinalPassFrameBuffer.Unbind(); + GLERROR("END"); } @@ -356,12 +376,17 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& case RawModel::MaterialType::SingleTextures: { if (explosionEffectJob->Model->IsSkinned()) { + m_ExplosionEffectSkinnedProgram->Bind(); GLERROR("Bind ExplosionEffectSkinned program"); //bind uniforms BindExplosionUniforms(explosionSkinnedHandle, explosionEffectJob, scene); //bind textures BindExplosionTextures(explosionSkinnedHandle, explosionEffectJob); + glActiveTexture(GL_TEXTURE5); + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); + glUniform3fv(glGetUniformLocation(forwardHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); + std::vector frameBones; if (explosionEffectJob->AnimationOffset.animation != nullptr) { frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); @@ -376,6 +401,10 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& BindExplosionUniforms(explosionHandle, explosionEffectJob, scene); //bind textures BindExplosionTextures(explosionHandle, explosionEffectJob); + glActiveTexture(GL_TEXTURE5); + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); + glUniform3fv(glGetUniformLocation(forwardHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); + } break; } @@ -434,6 +463,10 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& BindModelUniforms(forwardSkinnedHandle, modelJob, scene); //bind textures BindModelTextures(forwardSkinnedHandle, modelJob); + glActiveTexture(GL_TEXTURE5); + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); + glUniform3fv(glGetUniformLocation(forwardHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); + std::vector frameBones; if (modelJob->AnimationOffset.animation != nullptr) { frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); @@ -449,6 +482,9 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& BindModelUniforms(forwardHandle, modelJob, scene); //bind textures BindModelTextures(forwardHandle, modelJob); + glActiveTexture(GL_TEXTURE5); + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); + glUniform3fv(glGetUniformLocation(forwardHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); } break; } @@ -807,6 +843,8 @@ void DrawFinalPass::BindModelUniforms(GLuint shaderHandle, std::shared_ptr& job) { + + switch (job->Type) { case RawModel::MaterialType::SingleTextures: case RawModel::MaterialType::Basic: diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index d1ed73dd..1eab9939 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -21,23 +21,13 @@ void PickingPass::InitializeTextures() { GenerateTexture(&m_PickingTexture, GL_CLAMP_TO_BORDER, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RG8, GL_RG, GL_UNSIGNED_BYTE); + + GenerateTexture(&m_DepthBuffer, GL_CLAMP_TO_BORDER, GL_NEAREST, + glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8); } void PickingPass::InitializeFrameBuffers() { - /* glGenRenderbuffers(1, &m_DepthBuffer); - glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height);*/ - - glGenTextures(1, &m_DepthBuffer); - - glBindTexture(GL_TEXTURE_2D, m_DepthBuffer); - glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, (int)(m_Renderer->GetViewportSize().Width), (int)(m_Renderer->GetViewportSize().Height), 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, nullptr); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); - m_PickingBuffer.AddResource(std::shared_ptr(new Texture2D(&m_DepthBuffer, GL_DEPTH_ATTACHMENT))); m_PickingBuffer.AddResource(std::shared_ptr(new Texture2D(&m_PickingTexture, GL_COLOR_ATTACHMENT0))); m_PickingBuffer.Generate(); @@ -64,6 +54,7 @@ void PickingPass::InitializeShaderPrograms() void PickingPass::Draw(RenderScene& scene) { + GLERROR("PRE"); PickingPassState* state = new PickingPassState(m_PickingBuffer.GetHandle()); //TODO: Render: Add code for more jobs than modeljobs. @@ -367,6 +358,7 @@ void PickingPass::Draw(RenderScene& scene) void PickingPass::ClearPicking() { + GLERROR("PRE"); m_PickingColorsToEntity.clear(); m_EntityColors.clear(); m_ColorCounter[0] = 0; @@ -376,14 +368,13 @@ void PickingPass::ClearPicking() glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_PickingBuffer.Unbind(); + GLERROR("END"); } void PickingPass::OnWindowResize() { InitializeTextures(); - glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); m_PickingBuffer.Generate(); } diff --git a/src/Engine/Rendering/PickingPassState.cpp b/src/Engine/Rendering/PickingPassState.cpp index 0c4f4aca..f2d42bff 100644 --- a/src/Engine/Rendering/PickingPassState.cpp +++ b/src/Engine/Rendering/PickingPassState.cpp @@ -3,9 +3,9 @@ PickingPassState::PickingPassState(GLuint frameBuffer) { - GLERROR("---2"); + GLERROR("PRE"); BindFramebuffer(frameBuffer); - GLERROR("---3"); + GLERROR("Bind Framebuffer"); Enable(GL_DEPTH_TEST); Enable(GL_CULL_FACE); Disable(GL_BLEND); @@ -13,6 +13,7 @@ PickingPassState::PickingPassState(GLuint frameBuffer) glm::vec4 clearColor = glm::vec4(0.f); //ClearColor(clearColor); //Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + GLERROR("END"); } PickingPassState::~PickingPassState() diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index 665c4027..7b0ea84f 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -52,6 +52,101 @@ void RenderSystem::fillSprites(std::list>& jobs, Worl continue; } + glm::mat4 modelMatrix; + + // See a sprite is an SpriteIndicator + bool isIndicator = false; + if (world->HasComponent(entity.ID, "SpriteIndicator")) + { + auto indicator = entity["SpriteIndicator"]; + + float minScale = (float)(double)indicator["MinScale"]; + bool hasTeam = indicator["VisibleForSingleTeamOnly"]; + isIndicator = true; + glm::vec3 pos = Transform::AbsolutePosition(entity); + + + EntityWrapper entityTeam; + if (hasTeam && (entity.HasComponent("Team") || entity.FirstParentWithComponent("Team").Valid()) && m_LocalPlayer.World != nullptr) { + if (!entity.HasComponent("Team")) { + entityTeam = entity.FirstParentWithComponent("Team"); + } + else { + entityTeam = entity; + } + + ComponentWrapper& entityTeamComponent = entityTeam["Team"]; + ComponentWrapper& localComponent = m_LocalPlayer["Team"]; + int entityTeamInt = entityTeamComponent["Team"]; + int localComponentInt = localComponent["Team"]; + int SpectatorInt = localComponent["Team"].Enum("Spectator"); + if (entityTeamInt != localComponentInt && localComponentInt != SpectatorInt) { + continue; + } + } + + // Code for check if sprite is inside or outside of screen + //glm::vec4 projectedPos = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix() * glm::vec4(pos, 1.0f); + //projectedPos /= projectedPos.w; + //// Check if inside of outside of screen. + //if (projectedPos.x < -1.0f || projectedPos.x > 1.0f || projectedPos.y < -1.0f || projectedPos.y > 1.0f) { + // // is outside of screen + //} else { + // // is inside of screen + //} + + + glm::vec3 zAxis = glm::vec3(0.0f, 1.0f, 0.0f); + glm::vec3 normal = pos - m_Camera->Position(); + + //float distance = glm::length(normal); + //if (distance < minDistance) { + // pos = pos - glm::normalize(normal) * (distance - minDistance); + //} else if (distance > maxDistance) { + // pos = pos - glm::normalize(normal) * (distance - maxDistance); + //} + normal.y = 0; + normal = glm::normalize(normal); + glm::vec3 right = glm::cross(normal, zAxis); + glm::vec3 up = glm::cross(right, normal); + + modelMatrix[0][0] = right.x; + modelMatrix[0][1] = right.y; + modelMatrix[0][2] = right.z; + modelMatrix[0][3] = 0.0f; + + modelMatrix[1][0] = zAxis.x; + modelMatrix[1][1] = zAxis.y; + modelMatrix[1][2] = zAxis.z; + modelMatrix[1][3] = 0.0f; + + modelMatrix[2][0] = normal.x; + modelMatrix[2][1] = normal.y; + modelMatrix[2][2] = normal.z; + modelMatrix[2][3] = 0.0f; + + modelMatrix[3][0] = pos.x; + modelMatrix[3][1] = pos.y; + modelMatrix[3][2] = pos.z; + modelMatrix[3][3] = 1.0f; + + glm::mat4 tranformationMatrix = modelMatrix * glm::scale(Transform::AbsoluteScale(entity)); + glm::vec4 tmp = tranformationMatrix * glm::vec4(glm::vec3(0.5, 0.5, 0), 1.0f); + glm::vec2 projectedTopRight = m_Camera->WorldToScreen(glm::vec3(tmp), m_Renderer->GetViewportSize()); + tmp = tranformationMatrix * glm::vec4(glm::vec3(-0.5, -0.5, 0), 1.0f); + glm::vec2 projectedBottomLeft = m_Camera->WorldToScreen(glm::vec3(tmp), m_Renderer->GetViewportSize()); + + float diag = glm::length(projectedBottomLeft - projectedTopRight); + if (diag < minScale) { + tranformationMatrix = tranformationMatrix * glm::scale(glm::vec3(minScale / diag, minScale / diag, minScale / diag)); + } + modelMatrix = tranformationMatrix; + } + else { + modelMatrix = Transform::ModelMatrix(entity.ID, world); + } + + std::string diffuseResource = cSprite["DiffuseTexture"]; std::string glowResource = cSprite["GlowMap"]; bool depthSorted = cSprite["DepthSort"]; @@ -67,11 +162,7 @@ void RenderSystem::fillSprites(std::list>& jobs, Worl fillColor = (glm::vec4)fillComponent["Color"]; } - glm::mat4 modelMatrix = Transform::ModelMatrix(entity.ID, world); - //modelMatrix *= m_Camera->BillboardMatrix(); - - - std::shared_ptr spriteJob = std::shared_ptr(new SpriteJob(cSprite, m_Camera, modelMatrix, world, fillColor, fillPercentage, depthSorted)); + std::shared_ptr spriteJob = std::shared_ptr(new SpriteJob(cSprite, m_Camera, modelMatrix, world, fillColor, fillPercentage, depthSorted, isIndicator)); jobs.push_back(spriteJob); } @@ -93,7 +184,6 @@ bool RenderSystem::isEntityVisible(EntityWrapper& entity) ) { return false; } - return true; } diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index 0c668cad..251bba2b 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -30,6 +30,7 @@ void Renderer::glfwFrameBufferCallback(GLFWwindow* window, int width, int height currentRenderer->m_LightCullingPass->OnWindowResize(); currentRenderer->m_PickingPass->OnWindowResize(); currentRenderer->m_DrawBloomPass->OnWindowResize(); + currentRenderer->m_SSAOPass->OnWindowResize(); } void Renderer::InitializeWindow() @@ -88,9 +89,6 @@ void Renderer::InitializeShaders() //m_ExplosionEffectProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ExplosionEffect.frag.glsl"))); //m_ExplosionEffectProgram->Compile(); //m_ExplosionEffectProgram->Link(); - - - } void Renderer::InputUpdate(double dt) @@ -108,7 +106,14 @@ void Renderer::Update(double dt) void Renderer::Draw(RenderFrame& frame) { + GLERROR("PRE"); ImGui::Combo("Draw textures", &m_DebugTextureToDraw, "Final\0Scene\0Bloom\0SceneLowRes\0BloomLowRes\0Gaussian\0Picking\0Ambient Occlusion"); + ImGui::Combo("CubeMap", &m_CubeMapTexture, "Nevada(512)\0Sky(1024)"); + if(m_CubeMapTexture == 0) { + m_CubeMapPass->LoadTextures("Nevada"); + } else if (m_CubeMapTexture == 1) { + m_CubeMapPass->LoadTextures("Sky"); + } ImGui::SliderFloat("SSAO sample radius", &m_SSAO_Radius, 0.01f, 5.0f); ImGui::SliderFloat("SSAO bias", &m_SSAO_Bias, 0.0f, 0.1f); @@ -117,6 +122,7 @@ void Renderer::Draw(RenderFrame& frame) ImGui::SliderInt("SSAO Number of Samples", &m_SSAO_NumOfSamples, 2, 100); ImGui::SliderInt("SSAO Number of Turns", &m_SSAO_NumOfTurns, 0, 50); m_SSAOPass->Setting(m_SSAO_Radius, m_SSAO_Bias, m_SSAO_Contrast, m_SSAO_IntensityScale, m_SSAO_NumOfSamples, m_SSAO_NumOfTurns); + GLERROR("SSAO Settings"); //clear buffer 0 glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); @@ -126,7 +132,9 @@ void Renderer::Draw(RenderFrame& frame) m_PickingPass->ClearPicking(); m_DrawFinalPass->ClearBuffer(); m_DrawBloomPass->ClearBuffer(); + m_SSAOPass->ClearBuffer(); PerformanceTimer::StopTimer("Renderer-ClearBuffers"); + GLERROR("ClearBuffers"); for (auto scene : frame.RenderScenes) { PerformanceTimer::StartTimer("Renderer-Depth"); m_PickingPass->Draw(*scene); @@ -239,9 +247,10 @@ void Renderer::InitializeRenderPasses() { m_PickingPass = new PickingPass(this, m_EventBroker); m_LightCullingPass = new LightCullingPass(this); - m_DrawFinalPass = new DrawFinalPass(this, m_LightCullingPass); + m_CubeMapPass = new CubeMapPass(this); + m_DrawFinalPass = new DrawFinalPass(this, m_LightCullingPass, m_CubeMapPass); m_DrawScreenQuadPass = new DrawScreenQuadPass(this); m_DrawBloomPass = new DrawBloomPass(this); m_DrawColorCorrectionPass = new DrawColorCorrectionPass(this); - m_SSAOPass = new SSAOPass(this); + m_SSAOPass = new SSAOPass(this); } diff --git a/src/Engine/Rendering/SSAOPass.cpp b/src/Engine/Rendering/SSAOPass.cpp index 331e040f..d4cdcb19 100644 --- a/src/Engine/Rendering/SSAOPass.cpp +++ b/src/Engine/Rendering/SSAOPass.cpp @@ -6,6 +6,7 @@ SSAOPass::SSAOPass(IRenderer* renderer) m_ScreenQuad = ResourceManager::Load("Models/Core/ScreenQuad.mesh"); + InitializeTexture(); InitializeBuffer(); InitializeShaderProgram(); Setting(0.1f, 0.012f, 1.0f, 1.0f, 13, 7); @@ -28,16 +29,16 @@ void SSAOPass::InitializeShaderProgram() m_SSAOViewSpaceZProgram->Link(); } +void SSAOPass::InitializeTexture() { + GenerateTexture(&m_SSAOTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_R8, GL_RED, GL_FLOAT); + GenerateTexture(&m_SSAOViewSpaceZTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_R32F, GL_RED, GL_FLOAT); +} void SSAOPass::InitializeBuffer() { - GenerateTexture(&m_SSAOTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_R8, GL_RED, GL_FLOAT); - m_SSAOFramBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SSAOTexture, GL_COLOR_ATTACHMENT0))); m_SSAOFramBuffer.Generate(); - GenerateTexture(&m_SSAOViewSpaceZTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_R32F, GL_RED, GL_FLOAT); - m_SSAOViewSpaceZFramBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SSAOViewSpaceZTexture, GL_COLOR_ATTACHMENT0))); m_SSAOViewSpaceZFramBuffer.Generate(); } @@ -45,12 +46,12 @@ void SSAOPass::InitializeBuffer() void SSAOPass::ClearBuffer() { m_SSAOFramBuffer.Bind(); - glClearColor(0.f, 0.f, 0.f, 0.f); + glClearColor(1.f, 1.f, 1.f, 1.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_SSAOFramBuffer.Unbind(); m_SSAOViewSpaceZFramBuffer.Bind(); - glClearColor(0.f, 0.f, 0.f, 0.f); + glClearColor(1.f, 1.f, 1.f, 1.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_SSAOViewSpaceZFramBuffer.Unbind(); } @@ -136,6 +137,9 @@ void SSAOPass::Draw(GLuint depthBuffer, Camera* camera) m_DrawBloomPass->Draw(m_SSAOTexture); } -void ComputeAO(GLuint depthBuffer, Camera* camera) { - +void SSAOPass::OnWindowResize() { + m_DrawBloomPass->OnWindowResize(); + InitializeTexture(); + m_SSAOFramBuffer.Generate(); + m_SSAOViewSpaceZFramBuffer.Generate(); } \ No newline at end of file diff --git a/src/Engine/Rendering/Texture.cpp b/src/Engine/Rendering/Texture.cpp index 256246a9..03347044 100644 --- a/src/Engine/Rendering/Texture.cpp +++ b/src/Engine/Rendering/Texture.cpp @@ -18,6 +18,7 @@ Texture::Texture(std::string path) this->Width = img->Width; this->Height = img->Height; + this->Data = img->Data; GLint format; switch (img->Format) { @@ -28,6 +29,7 @@ Texture::Texture(std::string path) format = GL_RGBA; break; } + // Construct the OpenGL texture glGenTextures(1, &m_Texture); diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 24b7cd1e..8be665e0 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -16,7 +16,7 @@ #include "Game/Systems/PickupSpawnSystem.h" #include "Game/Systems/AmmoPickupSystem.h" #include "Game/Systems/DamageIndicatorSystem.h" -#include "Game/Systems/Weapon/WeaponSystem.h" +#include "Game/Systems/Weapon/DefenderWeaponBehaviour.h" #include "Rendering/AnimationSystem.h" #include "Game/Systems/HealthHUDSystem.h" #include "Rendering/BoneAttachmentSystem.h" @@ -48,7 +48,6 @@ Game::Game(int argc, char* argv[]) ResourceManager::UseThreading = m_Config->Get("Multithreading.ResourceLoading", true); DisableMemoryPool::Value = m_Config->Get("Debug.DisableMemoryPool", false); LOG_LEVEL = static_cast<_LOG_LEVEL>(m_Config->Get("Debug.LogLevel", 1)); - PlayerSpawnSystem::SetRespawnTime(m_Config->Get("Debug.RespawnTime", 15.0f)); // Create the core event broker m_EventBroker = new EventBroker(); @@ -98,6 +97,10 @@ Game::Game(int argc, char* argv[]) m_NetworkClient->Connect(m_NetworkAddress, m_NetworkPort); m_Renderer->SetWindowTitle(m_Renderer->WindowTitle() + " CLIENT"); } + } else { + // If network is disabled, pretend we're a server + m_IsClient = true; + m_IsServer = true; } // Create Octrees @@ -120,7 +123,7 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); - m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_OctreeCollision); + m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_OctreeCollision); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); @@ -135,7 +138,6 @@ Game::Game(int argc, char* argv[]) ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision, "Collidable"); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeTrigger, "Player"); - m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeFrustrumCulling); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); @@ -145,6 +147,9 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeTrigger); + // Octree for frustum culling must be updated after collisions, otherwise players frustum may be moved after tree is filled, and wrong things are culled. + ++updateOrderLevel; + m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeFrustrumCulling); ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_RenderFrame, m_OctreeFrustrumCulling); ++updateOrderLevel; diff --git a/src/Game/Network/MultiplayerSnapshotFilter.cpp b/src/Game/Network/MultiplayerSnapshotFilter.cpp index 69b7f282..295cdd7a 100644 --- a/src/Game/Network/MultiplayerSnapshotFilter.cpp +++ b/src/Game/Network/MultiplayerSnapshotFilter.cpp @@ -13,6 +13,7 @@ bool MultiplayerSnapshotFilter::FilterComponent(EntityWrapper entity, SharedComp component.Info.Name == "Transform" || component.Info.Name == "Physics" || component.Info.Name == "AssaultWeapon" + || component.Info.Name == "DefenderWeapon" || component.Info.Name == "Animation" || component.Info.Name == "AnimationOffset" || entity.Name() == "PlayerName" diff --git a/src/Game/Systems/AmmoPickupSystem.cpp b/src/Game/Systems/AmmoPickupSystem.cpp index f6778fe4..250fa494 100644 --- a/src/Game/Systems/AmmoPickupSystem.cpp +++ b/src/Game/Systems/AmmoPickupSystem.cpp @@ -29,6 +29,7 @@ void AmmoPickupSystem::Update(double dt) newAmmoPickupEntity["Transform"]["Position"] = ammoPickupPosition.Pos; newAmmoPickupEntity["AmmoPickup"]["AmmoGain"] = ammoPickupPosition.AmmoGain; newAmmoPickupEntity["AmmoPickup"]["RespawnTimer"] = ammoPickupPosition.RespawnTimer; + m_World->SetParent(newAmmoPickupEntity.ID, ammoPickupPosition.parentID); //erase the current element (AmmoPickupPosition) m_ETriggerTouchVector.erase(it); @@ -69,8 +70,8 @@ bool AmmoPickupSystem::OnTriggerTouch(Events::TriggerTouch& e) //copy position, ammogain, respawntimer (twice since one of the values will be counted down to 0, the other will be set in the new object) //we need to copy all values since each value can be different for each ammoPickup - m_ETriggerTouchVector.push_back({ (glm::vec3)e.Trigger["Transform"]["Position"] ,e.Trigger["AmmoPickup"]["AmmoGain"], - e.Trigger["AmmoPickup"]["RespawnTimer"],e.Trigger["AmmoPickup"]["RespawnTimer"] }); + m_ETriggerTouchVector.push_back({ e.Trigger["Transform"]["Position"], e.Trigger["AmmoPickup"]["AmmoGain"], + e.Trigger["AmmoPickup"]["RespawnTimer"], e.Trigger["AmmoPickup"]["RespawnTimer"], m_World->GetParent(e.Trigger.ID) }); //delete the ammopickup m_World->DeleteEntity(e.Trigger.ID); diff --git a/src/Game/Systems/CapturePointSystem.cpp b/src/Game/Systems/CapturePointSystem.cpp index 5fdd74cd..c99a36a6 100644 --- a/src/Game/Systems/CapturePointSystem.cpp +++ b/src/Game/Systems/CapturePointSystem.cpp @@ -1,32 +1,39 @@ #include "Systems/CapturePointSystem.h" #include -CapturePointSystem::CapturePointSystem(SystemParams params) +CapturePointSystem::CapturePointSystem(SystemParams params) : System(params) , PureSystem("CapturePoint") { //subscribe/listenTo playerdamage,healthpickup events (using the eventBroker) - if (IsClient) { + if (!IsClient) { EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &CapturePointSystem::OnTriggerTouch); EVENT_SUBSCRIBE_MEMBER(m_ETriggerLeave, &CapturePointSystem::OnTriggerLeave); EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &CapturePointSystem::OnCaptured); } + } //here all capturepoints will update their component //NOTE: needs to run each frame, since we're possibly modifying the captureTimer for the capturePoints by dt void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, ComponentWrapper& cCapturePoint, double dt) { - if (!IsClient) { + if (IsClient) { return; } - if (m_WinnerWasFound) { return; } const int capturePointNumber = cCapturePoint["CapturePointNumber"]; const bool hasTeamComponent = capturePointEntity.HasComponent("Team"); + if (m_NumberOfCapturePoints != 0) { + if (!m_CapturePointNumberToEntityMap[0].HasComponent("CapturePoint")) { + //if map has changed, the capturepoints has changed, now have to redo them + m_NumberOfCapturePoints = 0; + m_CapturePointNumberToEntityMap.clear(); + } + } //if point doesnt have a teamComponent yet, add one. since: //what if capture point has no team -> we cant get/use the team enum from it... if (!hasTeamComponent) { @@ -71,8 +78,7 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp std::map nextPossibleCapturePoint; nextPossibleCapturePoint["Red"] = -1; nextPossibleCapturePoint["Blue"] = -1; - for (int i = 0; i < m_NumberOfCapturePoints; i++) - { + for (int i = 0; i < m_NumberOfCapturePoints; i++) { if (!m_CapturePointNumberToEntityMap[i].HasComponent("Team")) { continue; } @@ -84,8 +90,7 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp nextPossibleCapturePoint["Blue"] = i + 1; } } - for (int i = m_NumberOfCapturePoints - 1; i >= 0; i--) - { + for (int i = m_NumberOfCapturePoints - 1; i >= 0; i--) { if (!m_CapturePointNumberToEntityMap[i].HasComponent("Team")) { continue; } @@ -100,8 +105,7 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp //reset timers and reset the bool that triggers this if (m_ResetTimers) { - for (int i = 0; i < m_NumberOfCapturePoints; i++) - { + for (int i = 0; i < m_NumberOfCapturePoints; i++) { ComponentWrapper& capturePoint = m_CapturePointNumberToEntityMap[i]["CapturePoint"]; if ((int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Red"] && (int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Blue"]) { @@ -116,8 +120,7 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp } //check how many players are standing inside and are healthy - for (size_t i = m_ETriggerTouchVector.size(); i > 0; i--) - { + for (size_t i = m_ETriggerTouchVector.size(); i > 0; i--) { auto triggerTouched = m_ETriggerTouchVector[i - 1]; if (std::get<1>(triggerTouched) == capturePointEntity) { //some player has touched this - lets figure out: what team, health @@ -176,8 +179,8 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp cCapturePoint["CaptureTimer"] = (double)cCapturePoint["CaptureTimer"] + timerDeltaChange; } //if capturePoint is owned by the team, and the other team has been trying to take it, then increase/decrease the timer towards 0.0 - if ((ownedBy == currentTeam && currentTeam == redTeam && (double)cCapturePoint["CaptureTimer"] < 0.0) || - (ownedBy == currentTeam && currentTeam == blueTeam && (double)cCapturePoint["CaptureTimer"] > 0.0)) { + if ((ownedBy == currentTeam && currentTeam == redTeam && (double)cCapturePoint["CaptureTimer"] < captureTimeToTakeOver) || + (ownedBy == currentTeam && currentTeam == blueTeam && (double)cCapturePoint["CaptureTimer"] > -captureTimeToTakeOver)) { cCapturePoint["CaptureTimer"] = (double)cCapturePoint["CaptureTimer"] + timerDeltaChange; } //check if captureTimer > captureTimeToTakeOver and if so change owner and publish the eCaptured event @@ -195,17 +198,14 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp //check for possible winCondition = check if the homebase is owned by the other team bool checkForWinner = false; - if (capturePointNumber == m_RedTeamHomeCapturePoint && ownedBy != redTeam) - { + if (capturePointNumber == m_RedTeamHomeCapturePoint && ownedBy != redTeam) { checkForWinner = true; } - if (capturePointNumber == m_BlueTeamHomeCapturePoint && ownedBy != blueTeam) - { + if (capturePointNumber == m_BlueTeamHomeCapturePoint && ownedBy != blueTeam) { checkForWinner = true; } - if (checkForWinner && !m_WinnerWasFound) - { + if (checkForWinner && !m_WinnerWasFound) { //publish Win event Events::Win e; e.TeamThatWon = ownedBy; @@ -224,8 +224,7 @@ bool CapturePointSystem::OnTriggerTouch(const Events::TriggerTouch& e) bool CapturePointSystem::OnTriggerLeave(const Events::TriggerLeave& e) { - for (size_t i = 0; i < m_ETriggerTouchVector.size(); i++) - { + for (size_t i = 0; i < m_ETriggerTouchVector.size(); i++) { auto triggerTouched = m_ETriggerTouchVector[i]; if (std::get<0>(triggerTouched) == e.Entity && std::get<1>(triggerTouched) == e.Trigger) { m_ETriggerTouchVector.erase(m_ETriggerTouchVector.begin() + i); diff --git a/src/Game/Systems/DamageIndicatorSystem.cpp b/src/Game/Systems/DamageIndicatorSystem.cpp index 235eced0..ca26052d 100644 --- a/src/Game/Systems/DamageIndicatorSystem.cpp +++ b/src/Game/Systems/DamageIndicatorSystem.cpp @@ -12,51 +12,41 @@ DamageIndicatorSystem::DamageIndicatorSystem(SystemParams params) auto entityFile = ResourceManager::Load("Schema/Entities/DamageIndicator.xml"); } +void DamageIndicatorSystem::Update(double dt) { + if (!IsServer && LocalPlayer.Valid()) { + for (auto& iter = updateDamageIndicatorVector.begin(); iter != updateDamageIndicatorVector.end(); iter++) { + if (!iter->spriteEntity.Valid()) { + updateDamageIndicatorVector.erase(iter); + break; + } + auto angleBetweenVectors = CalculateAngle(LocalPlayer, iter->enemyPosition); + //simply set the rotation z-wise to the angleBetweenVectors + iter->spriteEntity["Transform"]["Orientation"] = glm::vec3(0, 0, angleBetweenVectors); + } + } +} + bool DamageIndicatorSystem::OnPlayerDamage(Events::PlayerDamage& e) { if (m_CurrentCamera == EntityID_Invalid) { return false; } - //if (e.Victim != LocalPlayer) { - // return false; - //} if (e.Victim.Valid() && e.Victim != LocalPlayer && !e.Victim.IsChildOf(LocalPlayer)) { return false; } if (!e.Inflictor.Valid() || !e.Victim.Valid()) { - return false; + return false; } - //grab players direction - auto playerOrientation = glm::quat((glm::vec3)e.Victim["Transform"]["Orientation"]); + glm::vec3 inflictorPos = e.Inflictor["Transform"]["Position"]; + //if testing +#ifdef INDICATOR_TEST + inflictorPos = DamageIndicatorTest(e.Victim); +#endif - //get the position vectors, but ignore the y-height - auto enemyPosition = (glm::vec3)e.Inflictor["Transform"]["Position"]; - auto playerPosition = (glm::vec3)e.Victim["Transform"]["Position"]; - enemyPosition.y = 0.0f; - playerPosition.y = 0.0f; - - //calculate the enemy to player vector - auto enemyPlayerVector = glm::normalize(playerPosition - enemyPosition); - - //get angle from players current rotation, this angle is how much you rotate around the y-axis - auto playerAngle = glm::angle(playerOrientation); - auto playerRotationVector = glm::normalize(glm::rotateY(glm::vec3(0, 0, 1), playerAngle)); - - //dot product of players direction-vector and enemys-to-playervector will give the cos of the angle between the vectors - auto playerRotationDot = glm::dot(playerRotationVector, enemyPlayerVector); - //to get the angle between the vectors just do cos-inverse - auto angleBetweenVectors = glm::acos(playerRotationDot); - - //rotate the direction-vector 90 degrees to get the players side-vector - auto playerSideVector = glm::normalize(glm::rotateY(glm::vec3(0, 0, 1), playerAngle + 1.57f)); - //dot of sidevector positive = enemy is on the right side, dot sidevector negative = left side - auto playerSideVectorDot = glm::dot(playerSideVector, enemyPlayerVector); - if (playerSideVectorDot < 0) { - angleBetweenVectors = -angleBetweenVectors; - } + float angleBetweenVectors = CalculateAngle(e.Victim, inflictorPos); //load & set the "2d" sprite auto entityFile = ResourceManager::Load("Schema/Entities/DamageIndicator.xml"); @@ -67,6 +57,10 @@ bool DamageIndicatorSystem::OnPlayerDamage(Events::PlayerDamage& e) //simply set the rotation z-wise to the angleBetweenVectors spriteWrapper["Transform"]["Orientation"] = glm::vec3(0, 0, angleBetweenVectors); + if (!IsServer) { + updateDamageIndicatorVector.emplace_back(spriteWrapper, inflictorPos); + } + return true; } @@ -74,3 +68,82 @@ bool DamageIndicatorSystem::OnSetCamera(const Events::SetCamera& e) { m_CurrentCamera = e.CameraEntity.ID; return true; } + +float DamageIndicatorSystem::CalculateAngle(EntityWrapper player, glm::vec3 enemyPos) { + //grab players direction + auto playerOrientation = glm::quat((glm::vec3)player["Transform"]["Orientation"]); + + //get the position vectors, but ignore the y-height + auto enemyPosition = enemyPos; + auto playerPosition = (glm::vec3)player["Transform"]["Position"]; + enemyPosition.y = 0.0f; + playerPosition.y = 0.0f; + + //calculate the enemy to player vector + auto enemyPlayerVector = glm::normalize(playerPosition - enemyPosition); + + //get the rotationvector relative to the z-axis + auto rotationVectorVec3 = glm::vec3(glm::toMat4(Transform::AbsoluteOrientation(player))*glm::vec4(0, 0, 1, 0)); + //rotate the direction-vector 90 degrees to get the players side-vector + auto playerSideVector = glm::vec3(glm::rotateY(rotationVectorVec3, 1.57f)); + + //dot product of players direction-vector and enemys-to-playervector will give the cos of the angle between the vectors + auto playerRotationDot = glm::dot(rotationVectorVec3, enemyPlayerVector); + //to get the angle between the vectors just do cos-inverse + auto angleBetweenVectors = glm::acos(playerRotationDot); + + //dot of sidevector positive = enemy is on the right side, dot sidevector negative = left side + auto playerSideVectorDot = glm::dot(playerSideVector, enemyPlayerVector); + if (playerSideVectorDot < 0) { + angleBetweenVectors = -angleBetweenVectors; + } + + return angleBetweenVectors; +} +#ifdef INDICATOR_TEST +glm::vec3 DamageIndicatorSystem::DamageIndicatorTest(EntityWrapper player) { + auto currentPos = (glm::vec3)player["Transform"]["Position"]; + + auto testVar = 1; + auto testVar2 = 1; + if (m_TestVar % 4 == 0) { + testVar = -1; + testVar2 = 1; + } + if (m_TestVar % 4 == 1) { + testVar = 1; + testVar2 = 1; + } + if (m_TestVar % 4 == 2) { + testVar *= -1; + testVar2 = -1; + } + if (m_TestVar % 4 == 3) { + testVar = 1; + testVar2 = -1; + } + m_TestVar++; + + auto inflictorPos = glm::vec3(currentPos.x + testVar*6.0f, currentPos.y, currentPos.z + testVar2*6.0f); + + //load the explosioneffect XML + auto deathEffect = ResourceManager::Load("Schema/Entities/PlayerDeathExplosionWithCamera.xml"); + EntityFileParser parser(deathEffect); + EntityID deathEffectID = parser.MergeEntities(m_World); + EntityWrapper deathEffectEW = EntityWrapper(m_World, deathEffectID); + + //components that we need from player + auto playerModel = player.FirstChildByName("PlayerModel"); + auto playerEntityModel = playerModel["Model"]; + auto playerEntityAnimation = playerModel["Animation"]; + + //copy the data from player to explosioneffectmodel + playerEntityModel.Copy(deathEffectEW["Model"]); + playerEntityAnimation.Copy(deathEffectEW["Animation"]); + + //copy the models position,orientation + deathEffectEW["Transform"]["Position"] = inflictorPos; + deathEffectEW["Transform"]["Orientation"] = (glm::vec3)player["Transform"]["Orientation"]; + return inflictorPos; +} +#endif \ No newline at end of file diff --git a/src/Game/Systems/PickupSpawnSystem.cpp b/src/Game/Systems/PickupSpawnSystem.cpp index 159f716b..abf59007 100644 --- a/src/Game/Systems/PickupSpawnSystem.cpp +++ b/src/Game/Systems/PickupSpawnSystem.cpp @@ -29,6 +29,7 @@ void PickupSpawnSystem::Update(double dt) newHealthPickupEntity["Transform"]["Position"] = healthPickupPosition.Pos; newHealthPickupEntity["HealthPickup"]["HealthGain"] = healthPickupPosition.HealthGain; newHealthPickupEntity["HealthPickup"]["RespawnTimer"] = healthPickupPosition.RespawnTimer; + m_World->SetParent(newHealthPickupEntity.ID, healthPickupPosition.parentID); //erase the current element (healthPickupPosition) m_ETriggerTouchVector.erase(it); @@ -58,7 +59,7 @@ bool PickupSpawnSystem::OnTriggerTouch(Events::TriggerTouch& e) //copy position, healthgain, respawntimer (twice since one of the values will be counted down to 0, the other will be set in the new object) //we need to copy all values since each value can be different for each healthPickup m_ETriggerTouchVector.push_back({ (glm::vec3)e.Trigger["Transform"]["Position"] ,e.Trigger["HealthPickup"]["HealthGain"], - e.Trigger["HealthPickup"]["RespawnTimer"],e.Trigger["HealthPickup"]["RespawnTimer"] }); + e.Trigger["HealthPickup"]["RespawnTimer"],e.Trigger["HealthPickup"]["RespawnTimer"], m_World->GetParent(e.Trigger.ID) }); //delete the healthpickup m_World->DeleteEntity(e.Trigger.ID); diff --git a/src/Game/Systems/PlayerDeathSystem.cpp b/src/Game/Systems/PlayerDeathSystem.cpp index 40a98278..844d2ed1 100644 --- a/src/Game/Systems/PlayerDeathSystem.cpp +++ b/src/Game/Systems/PlayerDeathSystem.cpp @@ -33,9 +33,8 @@ void PlayerDeathSystem::createDeathEffect(EntityWrapper player) EntityWrapper deathEffectEW = EntityWrapper(m_World, deathEffectID); //components that we need from player - auto playerCamera = player.FirstChildByName("Camera"); auto playerModel = player.FirstChildByName("PlayerModel"); - if (!playerCamera.Valid() || !playerModel.Valid()) { + if (!playerModel.Valid()) { return; } if (!playerModel.HasComponent("Model") || !playerModel.HasComponent("Animation")) { @@ -44,7 +43,7 @@ void PlayerDeathSystem::createDeathEffect(EntityWrapper player) auto playerEntityModel = playerModel["Model"]; auto playerEntityAnimation = playerModel["Animation"]; - //copy the data from player to explisioneffectmodel + //copy the data from player to explosioneffectmodel playerEntityModel.Copy(deathEffectEW["Model"]); playerEntityAnimation.Copy(deathEffectEW["Animation"]); //freeze the animation diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 71fb16ee..b9ce23d4 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -4,6 +4,7 @@ PlayerMovementSystem::PlayerMovementSystem(SystemParams params) : System(params) { EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &PlayerMovementSystem::OnPlayerSpawned); + EVENT_SUBSCRIBE_MEMBER(m_EDoubleJump, &PlayerMovementSystem::OnDoubleJump); } PlayerMovementSystem::~PlayerMovementSystem() @@ -16,7 +17,15 @@ PlayerMovementSystem::~PlayerMovementSystem() void PlayerMovementSystem::Update(double dt) { updateMovementControllers(dt); - updateVelocity(dt); + if (IsServer) { + for (auto& kv : m_PlayerInputControllers) { + updateVelocity(kv.first, dt); + } + } else { + if (LocalPlayer.Valid()) { + updateVelocity(LocalPlayer, dt); + } + } } void PlayerMovementSystem::updateMovementControllers(double dt) @@ -28,7 +37,6 @@ void PlayerMovementSystem::updateMovementControllers(double dt) if (!player.Valid()) { continue; } - // Aim pitch EntityWrapper cameraEntity = player.FirstChildByName("Camera"); if (cameraEntity.Valid()) { @@ -108,25 +116,29 @@ void PlayerMovementSystem::updateMovementControllers(double dt) ImGui::Text("velocity: (%f, %f, %f) |%f|", velocity.x, velocity.y, velocity.z, glm::length(velocity)); } - //you cant jump and dash at the same time - since there is no friction in the air and we would thus dash much further in the air - if (!controller->PlayerIsDashing() && controller->Jumping() && !controller->Crouching() && (isOnGround || !controller->DoubleJumping())) { - (bool)cPhysics["IsOnGround"] = false; + if (isOnGround) { + controller->SetDoubleJumping(false); + } + //If player presses Jump and is not crouching. + if (controller->Jumping() && !controller->Crouching()) { if (isOnGround) { - controller->SetDoubleJumping(false); - } else { + (bool)cPhysics["IsOnGround"] = false; + velocity.y = player["Player"]["JumpSpeed"]; + } else if (player.HasComponent("DoubleJump") && !controller->DoubleJumping()) { + //Enter here if player can double jump and is doing so. + (bool)cPhysics["IsOnGround"] = false; + velocity.y = player["DoubleJump"]["DoubleJumpSpeed"]; + // If IsServer and network is off this will not work if (IsClient) { //put a hexagon at the players feet - auto hexagonEffect = ResourceManager::Load("Schema/Entities/DoubleJumpHexagon.xml"); - EntityFileParser parser(hexagonEffect); - EntityID hexagonEffectID = parser.MergeEntities(m_World); - EntityWrapper hexagonEW = EntityWrapper(m_World, hexagonEffectID); - hexagonEW["Transform"]["Position"] = (glm::vec3)player["Transform"]["Position"]; + spawnHexagon(player); controller->SetDoubleJumping(true); + // Publish event for client to listen to Events::DoubleJump e; + e.entityID = player.ID; m_EventBroker->Publish(e); } } - velocity.y = 4.f; } if (player.HasComponent("AABB")) { @@ -221,15 +233,11 @@ void PlayerMovementSystem::updateMovementControllers(double dt) } -void PlayerMovementSystem::updateVelocity(double dt) +void PlayerMovementSystem::updateVelocity(EntityWrapper player, double dt) { // Only apply velocity to local player - if (!LocalPlayer.Valid()) { - return; - } - - ComponentWrapper& cTransform = LocalPlayer["Transform"]; - ComponentWrapper& cPhysics = LocalPlayer["Physics"]; + ComponentWrapper& cTransform = player["Transform"]; + ComponentWrapper& cPhysics = player["Physics"]; glm::vec3& velocity = cPhysics["Velocity"]; bool isOnGround = (bool)cPhysics["IsOnGround"]; @@ -291,3 +299,26 @@ bool PlayerMovementSystem::OnPlayerSpawned(Events::PlayerSpawned& e) } return true; } + +bool PlayerMovementSystem::OnDoubleJump(Events::DoubleJump & e) +{ + // If entity does not exist, exit + if (!EntityWrapper(m_World, e.entityID).Valid()) { + return false; + } + // If entity IsLocalPlayer, exit + if (e.entityID == m_LocalPlayer.ID) { + return false; + } + spawnHexagon(EntityWrapper(m_World, e.entityID)); +} + +void PlayerMovementSystem::spawnHexagon(EntityWrapper target) +{ + //put a hexagon at the entitys... feet? + auto hexagonEffect = ResourceManager::Load("Schema/Entities/DoubleJumpHexagon.xml"); + EntityFileParser parser(hexagonEffect); + EntityID hexagonEffectID = parser.MergeEntities(m_World); + EntityWrapper hexagonEW = EntityWrapper(m_World, hexagonEffectID); + hexagonEW["Transform"]["Position"] = (glm::vec3)target["Transform"]["Position"]; +} \ No newline at end of file diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index 6254c674..e03a1778 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -1,29 +1,40 @@ #include "Systems/PlayerSpawnSystem.h" -//This should be set by the config anyway. -float PlayerSpawnSystem::m_RespawnTime = 15.0f; - PlayerSpawnSystem::PlayerSpawnSystem(SystemParams params) : System(params) - , m_Timer(0.f) + , m_DbgConfigForceRespawn(false) { EVENT_SUBSCRIBE_MEMBER(m_OnInputCommand, &PlayerSpawnSystem::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_OnPlayerSpawnerd, &PlayerSpawnSystem::OnPlayerSpawned); EVENT_SUBSCRIBE_MEMBER(m_OnPlayerDeath, &PlayerSpawnSystem::OnPlayerDeath); - m_NetworkEnabled = ResourceManager::Load("Config.ini")->Get("Networking.StartNetwork", false); + ConfigFile* config = ResourceManager::Load("Config.ini"); + m_NetworkEnabled = config->Get("Networking.StartNetwork", false); + m_ForcedRespawnTime = config->Get("Debug.RespawnTime", -1.0f); + m_DbgConfigForceRespawn = m_ForcedRespawnTime > 0; } void PlayerSpawnSystem::Update(double dt) { - //Increase timer. - m_Timer += dt; - if (m_Timer < m_RespawnTime) { - return; + // If there are no CapturePointGameMode components we will just spawn immediately. + // Should be able to support older maps with this. + // TODO: In the future we might want to return instead, to avoid spawning in the menu for instance. + auto pool = m_World->GetComponents("CapturePointGameMode"); + if (pool != nullptr && pool->size() > 0) + { + // Take the first CapturePointGameMode component found. + ComponentWrapper& modeComponent = *pool->begin(); + // Increase timer. + double& timer = (double&)modeComponent["RespawnTime"]; + timer += dt; + double maxRespawnTime = m_DbgConfigForceRespawn ? m_ForcedRespawnTime : (double)modeComponent["MaxRespawnTime"]; + if (timer < maxRespawnTime) { + return; + } + // If respawn time has passed, we spawn all players that have requested to be spawned. + timer = 0; } - //If respawn time has passed, we spawn all players that have requested to be spawned. - m_Timer = 0.f; - //If there are no spawn requests, return immediately, if we are client the SpawnRequests should always be empty. + // If there are no spawn requests, return immediately, if we are client the SpawnRequests should always be empty. if (m_SpawnRequests.size() == 0) { return; } diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp index 7101311d..b4a37ad0 100644 --- a/src/Game/Systems/SoundSystem.cpp +++ b/src/Game/Systems/SoundSystem.cpp @@ -14,6 +14,7 @@ SoundSystem::SoundSystem(SystemParams params) EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &SoundSystem::OnPlayerDamage); EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &SoundSystem::OnCaptured); EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &SoundSystem::OnTriggerTouch); + EVENT_SUBSCRIBE_MEMBER(m_EPlayerDeath, &SoundSystem::OnPlayerDeath); } } @@ -90,6 +91,9 @@ bool SoundSystem::drumTimer(double dt) bool SoundSystem::OnCaptured(const Events::Captured & e) { + if (!LocalPlayer.Valid()) { + return false; + } int homeTeam = (int)m_World->GetComponent(e.CapturePointID, "Team")["Team"]; int team = (int)m_World->GetComponent(LocalPlayer.ID, "Team")["Team"]; Events::PlaySoundOnEntity ev; @@ -108,7 +112,12 @@ bool SoundSystem::OnCaptured(const Events::Captured & e) // Testing purposes atm... bool SoundSystem::OnPlayerDamage(const Events::PlayerDamage & e) { - // Should check for only local players here... + if (!IsClient) { // Only play for clients + return false; + } + if (LocalPlayer.ID = e.Victim.ID) { // You're local player was the one who took dmg + return false; + } std::uniform_int_distribution dist(1, 12); int rand = dist(generator); std::vector paths; @@ -128,8 +137,16 @@ bool SoundSystem::OnPlayerDamage(const Events::PlayerDamage & e) bool SoundSystem::OnPlayerDeath(const Events::PlayerDeath & e) { - Events::PlaySoundOnEntity ev; - ev.EmitterID = LocalPlayer.ID; + if (e.Player.ID != LocalPlayer.ID) { + return false; + } + if (!IsClient) { + return false; + } + // The local player is dead. The local player might be invalid? + // Play the sound from the listener. + // TODO: We might want to hear other players die. + Events::PlayBackgroundMusic ev; ev.FilePath = "Audio/die/die2.wav"; m_EventBroker->Publish(ev); return false; diff --git a/src/Game/Systems/SpawnerSystem.cpp b/src/Game/Systems/SpawnerSystem.cpp index 90f677fe..6500460f 100644 --- a/src/Game/Systems/SpawnerSystem.cpp +++ b/src/Game/Systems/SpawnerSystem.cpp @@ -36,7 +36,7 @@ EntityWrapper SpawnerSystem::Spawn(EntityWrapper spawner, EntityWrapper parent / } // Find any SpawnPoints existing as children of spawner - auto children = spawner.World->GetChildren(spawner.ID); + auto children = spawner.World->GetDirectChildren(spawner.ID); std::vector spawnPoints; for (auto kv = children.first; kv != children.second; ++kv) { const EntityID& child = kv->second; diff --git a/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp b/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp_ similarity index 87% rename from src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp rename to src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp_ index 84d3ccd4..c3b3385f 100644 --- a/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp +++ b/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp_ @@ -1,13 +1,5 @@ #include "Systems/Weapon/AssaultWeaponBehaviour.h" -AssaultWeaponBehaviour::AssaultWeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree, EntityWrapper player) - : WeaponBehaviour(systemParams, renderer, collisionOctree, player) -{ - m_FirstPersonModel = m_Player.FirstChildByName("Hands"); - m_ThirdPersonModel = m_Player.FirstChildByName("PlayerModel"); - EVENT_SUBSCRIBE_MEMBER(m_EAnimationComplete, &AssaultWeaponBehaviour::OnAnimationComplete); -} - void AssaultWeaponBehaviour::Fire() { m_TimeSinceLastFire = 0.0; @@ -36,7 +28,7 @@ void AssaultWeaponBehaviour::Reload() return; } - // Don't reload if we're completly out of ammo + // Don't reload if we're completely out of ammo if (ammo == 0) { playEmptySound(); m_TimeSinceLastFire = -0.0f; // HACK: To make empty sound play with interval @@ -56,14 +48,14 @@ void AssaultWeaponBehaviour::Update(double dt) { if (m_Reloading) { m_ReloadTimer -= dt; - // Re-enable glow on reload impersonator half-way through the animation + // Re-enable glow on reload impostor half-way through the animation if (IsClient) { if (m_ReloadTimer <= (double)m_Player["AssaultWeapon"]["ReloadTime"] / 2.0) { - if (m_FirstPersonReloadImpersonator.Valid()) { - m_FirstPersonReloadImpersonator["Model"]["GlowMap"] = true; + if (m_FirstPersonReloadImpostor.Valid()) { + m_FirstPersonReloadImpostor["Model"]["GlowMap"] = true; } - if (m_ThirdPersonReloadImpersonator.Valid()) { - m_ThirdPersonReloadImpersonator["Model"]["GlowMap"] = true; + if (m_ThirdPersonReloadImpostor.Valid()) { + m_ThirdPersonReloadImpostor["Model"]["GlowMap"] = true; } } } @@ -96,21 +88,6 @@ void AssaultWeaponBehaviour::Update(double dt) } } -bool AssaultWeaponBehaviour::OnAnimationComplete(Events::AnimationComplete& e) -{ - if (e.Entity != m_FirstPersonModel) { - return false; - } - - //if (e.Name == "ShootRifle") { - // if (!m_Firing) { - // playIdleAnimation(); - // } - //} - - return true; -} - bool AssaultWeaponBehaviour::hasAmmo() { ComponentWrapper& cAssaultWeapon = m_Player["AssaultWeapon"]; @@ -177,7 +154,6 @@ void AssaultWeaponBehaviour::spawnTracer() float AssaultWeaponBehaviour::traceRayDistance(glm::vec3 origin, glm::vec3 direction) { - // TODO: Cast a ray and size tracer appropriately float distance; glm::vec3 pos; auto entity = Collision::EntityFirstHitByRay(Ray(origin, direction), m_CollisionOctree, distance, pos); @@ -215,6 +191,12 @@ void AssaultWeaponBehaviour::playEmptySound() void AssaultWeaponBehaviour::viewPunch() { + // Since we send absolute client orientations to server, running this server side would + // cause aim desync. + if (!IsClient) { + return; + } + EntityWrapper playerCamera = m_Player.FirstChildByName("Camera"); if (!playerCamera.Valid()) { return; @@ -323,8 +305,8 @@ void AssaultWeaponBehaviour::playReloadAnimation() EntityWrapper firstPersonWeaponModel = m_Player.FirstChildByName("WeaponModel"); EntityWrapper reloadSpawner = m_Player.FirstChildByName("FirstPersonReloadSpawner"); if (IsClient) { - m_FirstPersonReloadImpersonator = SpawnerSystem::Spawn(reloadSpawner, reloadSpawner); - firstPersonWeaponModel["Model"].Copy(m_FirstPersonReloadImpersonator["Model"]); + m_FirstPersonReloadImpostor = SpawnerSystem::Spawn(reloadSpawner, reloadSpawner); + firstPersonWeaponModel["Model"].Copy(m_FirstPersonReloadImpostor["Model"]); } firstPersonWeaponModel["Model"]["Visible"] = false; } @@ -332,8 +314,8 @@ void AssaultWeaponBehaviour::playReloadAnimation() EntityWrapper thirdPersonWeaponModel = m_Player.FirstChildByName("ThirdPersonWeaponModel"); EntityWrapper reloadSpawner = m_Player.FirstChildByName("ThirdPersonReloadSpawner"); if (IsClient) { - m_ThirdPersonReloadImpersonator = SpawnerSystem::Spawn(reloadSpawner, reloadSpawner); - thirdPersonWeaponModel["Model"].Copy(m_ThirdPersonReloadImpersonator["Model"]); + m_ThirdPersonReloadImpostor = SpawnerSystem::Spawn(reloadSpawner, reloadSpawner); + thirdPersonWeaponModel["Model"].Copy(m_ThirdPersonReloadImpostor["Model"]); } thirdPersonWeaponModel["Model"]["Visible"] = false; } @@ -371,7 +353,7 @@ bool AssaultWeaponBehaviour::shoot(double damage) return false; } - // Don't let us shoot ourselves in the foot + // Don't let us shoot ourselves in the foot somehow if (victim == LocalPlayer) { return false; } diff --git a/src/Game/Systems/Weapon/DefenderWeaponBehaviour.cpp b/src/Game/Systems/Weapon/DefenderWeaponBehaviour.cpp new file mode 100644 index 00000000..028bd10c --- /dev/null +++ b/src/Game/Systems/Weapon/DefenderWeaponBehaviour.cpp @@ -0,0 +1,188 @@ +#include "Systems/Weapon/DefenderWeaponBehaviour.h" + +void DefenderWeaponBehaviour::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cWeapon, double dt) +{ + (double&)cWeapon["TimeSinceLastFire"] += dt; + WeaponBehaviour::UpdateComponent(entity, cWeapon, dt); +} + +void DefenderWeaponBehaviour::UpdateWeapon(WeaponInfo& wi, double dt) +{ + ComponentWrapper cWeapon = wi.GetComponent(); + + bool isFiring = cWeapon["IsFiring"]; + bool cooldownPassed = (double)cWeapon["TimeSinceLastFire"] >= (60.0 / (double)cWeapon["RPM"]); + bool isNotShielding = wi.Player.ChildrenWithComponent("Shield").size() == 0; + if (isFiring && cooldownPassed && isNotShielding) { + fireShell(wi); + } +} + +void DefenderWeaponBehaviour::OnPrimaryFire(WeaponInfo& wi) +{ + ComponentWrapper cWeapon = wi.GetComponent(); + cWeapon["IsFiring"] = true; + bool cooldownPassed = (double)cWeapon["TimeSinceLastFire"] >= (60.0 / (double)cWeapon["RPM"]); + bool isNotShielding = wi.Player.ChildrenWithComponent("Shield").size() == 0; + if (cooldownPassed && isNotShielding) { + fireShell(wi); + } +} + +void DefenderWeaponBehaviour::OnCeasePrimaryFire(WeaponInfo& wi) +{ + ComponentWrapper cWeapon = wi.GetComponent(); + cWeapon["IsFiring"] = false; +} + +bool DefenderWeaponBehaviour::OnInputCommand(WeaponInfo& wi, const Events::InputCommand& e) +{ + if (e.Command == "SpecialAbility" && IsServer) { + EntityWrapper attachment = wi.Player.FirstChildByName("ShieldAttachment"); + if (attachment.Valid()) { + if (e.Value > 0) { + SpawnerSystem::Spawn(attachment, attachment); + } else { + attachment.DeleteChildren(); + } + } + } + + return false; +} + +bool DefenderWeaponBehaviour::OnSetCamera(const Events::SetCamera& e) +{ + m_CurrentCamera = e.CameraEntity; + return true; +} + +void DefenderWeaponBehaviour::fireShell(WeaponInfo& wi) +{ + ComponentWrapper cWeapon = wi.GetComponent(); + + cWeapon["TimeSinceLastFire"] = 0.0; + int numPellets = cWeapon["NumPellets"]; + float spreadAngle = cWeapon["SpreadAngle"]; + std::uniform_real_distribution randomSpreadAngle(-spreadAngle, spreadAngle); + + // Calculate pellet angles + // HACK: Random for now? + // TODO: Make distribution even for each quadrant + std::vector pelletAngles; + for (int i = 0; i < numPellets; i++) { + pelletAngles.push_back(glm::vec2(randomSpreadAngle(m_RandomEngine), randomSpreadAngle(m_RandomEngine))); + LOG_DEBUG("%f %f", pelletAngles[i].x, pelletAngles[i].y); + } + + double pelletDamage = (double)cWeapon["BaseDamage"] / numPellets; + + // Tracers + EntityWrapper weaponModelEntity; + if (wi.Player == LocalPlayer) { + weaponModelEntity = wi.FirstPersonEntity; + } else { + weaponModelEntity = wi.ThirdPersonEntity; + } + if (weaponModelEntity.Valid()) { + EntityWrapper spawner = weaponModelEntity.FirstChildByName("WeaponMuzzle"); + for (auto& angles : pelletAngles) { + glm::vec3 direction = Transform::AbsoluteOrientation(spawner) * glm::quat(glm::vec3(angles, 0.f)) * glm::vec3(0, 0, -1); + float distance = traceRayDistance(Transform::AbsolutePosition(spawner), direction); + EntityWrapper ray = SpawnerSystem::Spawn(spawner); + ((glm::vec3&)ray["Transform"]["Scale"]).z = (distance / 100.f); + glm::vec3& orientation = ray["Transform"]["Orientation"]; + orientation.x += angles.x; + orientation.y += angles.y; + glm::vec3 trajectory = direction * distance; + dealDamage(wi, direction, pelletDamage); + } + } + +} + +void DefenderWeaponBehaviour::dealDamage(WeaponInfo& wi, glm::vec3 direction, double damage) +{ + // Only deal damage client side + if (!IsClient) { + return; + } + + // Only handle shooting for the local player + if (wi.Player != LocalPlayer) { + return; + } + + // Make sure the player isn't shooting from the grave + if (!wi.Player.Valid()) { + return; + } + + glm::vec3 maxRange = direction * 2.f; + EntityWrapper camera = wi.Player.FirstChildByName("Camera"); + glm::vec3 cameraPosition = Transform::AbsolutePosition(camera); + if (!camera.Valid()) { + return; + } + Rectangle screenResolution = m_Renderer->GetViewportSize(); + glm::vec2 centerScreen = glm::vec2(screenResolution.Width / 2, screenResolution.Height / 2); + glm::vec2 screenCoords = cameraFromEntity(m_CurrentCamera).WorldToScreen(cameraPosition + maxRange, m_Renderer->GetViewportSize()); + PickData pickData = m_Renderer->Pick(centerScreen + screenCoords); + EntityWrapper victim(m_World, pickData.Entity); + if (!victim.Valid()) { + return; + } + + // Don't let us shoot ourselves in the foot somehow + if (victim == LocalPlayer) { + return; + } + + // Only care about players being hit + if (!victim.HasComponent("Player")) { + victim = victim.FirstParentWithComponent("Player"); + } + if (!victim.Valid()) { + return; + } + + // Check for friendly fire + if ((ComponentInfo::EnumType)victim["Team"]["Team"] == (ComponentInfo::EnumType)wi.Player["Team"]["Team"]) { + return; + } + + // Deal damage! + Events::PlayerDamage ePlayerDamage; + ePlayerDamage.Inflictor = wi.Player; + ePlayerDamage.Victim = victim; + ePlayerDamage.Damage = damage; + m_EventBroker->Publish(ePlayerDamage); + LOG_DEBUG("Damage: %f", damage); +} + +float DefenderWeaponBehaviour::traceRayDistance(glm::vec3 origin, glm::vec3 direction) +{ + float distance; + glm::vec3 pos; + auto entity = Collision::EntityFirstHitByRay(Ray(origin, direction), m_CollisionOctree, distance, pos); + if (entity) { + return distance; + } else { + return 100.f; + } +} + +Camera DefenderWeaponBehaviour::cameraFromEntity(EntityWrapper camera) +{ + ComponentWrapper cTransform = camera["Transform"]; + ComponentWrapper cCamera = camera["Camera"]; + Camera cam( + (float)m_Renderer->Resolution().Width / m_Renderer->Resolution().Height, + (double)cCamera["FOV"], + (double)cCamera["NearClip"], + (double)cCamera["FarClip"] + ); + cam.SetPosition(cTransform["Position"]); + cam.SetOrientation(glm::quat((const glm::vec3&)cTransform["Orientation"])); + return cam; +} diff --git a/src/Game/Systems/Weapon/WeaponSystem.cpp b/src/Game/Systems/Weapon/WeaponSystem.cpp_ similarity index 56% rename from src/Game/Systems/Weapon/WeaponSystem.cpp rename to src/Game/Systems/Weapon/WeaponSystem.cpp_ index 3a49ae90..d33c5098 100644 --- a/src/Game/Systems/Weapon/WeaponSystem.cpp +++ b/src/Game/Systems/Weapon/WeaponSystem.cpp_ @@ -13,7 +13,7 @@ WeaponSystem::WeaponSystem(SystemParams params, IRenderer* renderer, Octree weaponAttachments = player.ChildrenWithComponent("WeaponAttachment"); + + // Find the weapon attachments matching the slot selected + EntityWrapper firstPersonAttachment; + EntityWrapper thirdPersonAttachment; + for (auto& attachment : weaponAttachments) { + ComponentWrapper cWeaponAttachment = attachment["WeaponAttachment"]; + if ((ComponentInfo::EnumType)cWeaponAttachment["Slot"] == slot) { + ComponentWrapper::SubscriptProxy person = cWeaponAttachment["Person"]; + if (person == person.Enum("FirstPerson")) { + firstPersonAttachment = attachment; + } else if (person == person.Enum("ThirdPerson")) { + thirdPersonAttachment = attachment; + } + } + } + + if (firstPersonAttachment.Valid() && thirdPersonAttachment.Valid()) { + LOG_WARNING("No weapon attachment found for slot %i of player #%i", slot, player.ID); + return; + } + + // TODO: Delete old weapons + + // Spawn the weapon(s) + EntityWrapper firstPersonWeapon; + EntityWrapper thirdPersonWeapon; + if (firstPersonAttachment.Valid()) { + firstPersonWeapon = SpawnerSystem::Spawn(firstPersonAttachment, firstPersonAttachment); + } + if (thirdPersonAttachment.Valid()) { + firstPersonWeapon = SpawnerSystem::Spawn(thirdPersonAttachment, thirdPersonAttachment); + } + + // Create the correct behaviour + if (firstPersonWeapon.Valid()) { + if (firstPersonWeapon.HasComponent("AssaultWeapon") { + + } + } + // Primary if (slot == 1) { // TODO: if class... - if (m_ActiveWeapons.count(player) == 0) { - m_ActiveWeapons.insert(std::make_pair(player, std::make_shared(m_SystemParams, m_Renderer, m_CollisionOctree, player))); - } else { - //m_ActiveWeapons.erase(player); - } + nextBehaviour = std::make_shared(m_SystemParams, m_Renderer, m_CollisionOctree, player); } // Secondary if (slot == 2) { //m_ActiveWeapons[player] = std::make_shared(); } + + if (nextBehaviour != nullptr) { + // TODO: Destroy previous behaviour and make new + if (m_ActiveWeapons.count(player) == 0) { + m_ActiveWeapons[player] = nextBehaviour; + } + } } bool WeaponSystem::OnPlayerSpawned(Events::PlayerSpawned& e) diff --git a/src/Tests/HealthSystemTest.h b/src/Tests/HealthSystemTest.h index 685a06dd..275558d2 100644 --- a/src/Tests/HealthSystemTest.h +++ b/src/Tests/HealthSystemTest.h @@ -6,7 +6,6 @@ #include "Core/EventBroker.h" #include "Rendering/Renderer.h" #include "Core/InputManager.h" -#include "GUI/Frame.h" #include "Core/World.h" #include "Input/InputProxy.h" #include "Input/KeyboardInputHandler.h"