diff --git a/CMakeLists.txt b/CMakeLists.txt index cbe8168a..43286658 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -14,6 +14,8 @@ endif() if(CMAKE_COMPILER_IS_GNUCXX) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14") +elseif(MSVC) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MP") endif() #set(BUILD_SHARED_LIBS FALSE) @@ -34,6 +36,12 @@ foreach(OUTPUTCONFIG ${CMAKE_CONFIGURATION_TYPES}) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_${OUTPUTCONFIG} ${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}) endforeach(OUTPUTCONFIG CMAKE_CONFIGURATION_TYPES) +# DEBUG definition +set_property(DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS + $<$:DEBUG> + $<$:DEBUG> +) + include(cotire) add_subdirectory(src/Engine) add_subdirectory(src/Game) diff --git a/assets b/assets index e4dc9529..9b2fa74a 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit e4dc9529f2178d373808ddf487165fa50a641a78 +Subproject commit 9b2fa74a6d535d512c13429997385f7aa3fb50f5 diff --git a/include/Engine/Collision/CollidableOctreeSystem.h b/include/Engine/Collision/CollidableOctreeSystem.h index 0dcf5829..39aea979 100644 --- a/include/Engine/Collision/CollidableOctreeSystem.h +++ b/include/Engine/Collision/CollidableOctreeSystem.h @@ -4,11 +4,12 @@ #include "../Core/System.h" #include "../Core/Octree.h" #include "Collision.h" +#include "EntityAABB.h" class CollidableOctreeSystem : public ImpureSystem, public PureSystem { public: - CollidableOctreeSystem(World* world, EventBroker* eventBroker, Octree* octree) + CollidableOctreeSystem(World* world, EventBroker* eventBroker, Octree* octree) : System(world, eventBroker) , PureSystem("Collidable") , m_Octree(octree) @@ -18,7 +19,7 @@ public: virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override; private: - Octree* m_Octree; + Octree* m_Octree; }; #endif \ No newline at end of file diff --git a/include/Engine/Collision/Collision.h b/include/Engine/Collision/Collision.h index 194a18dc..cd10dbb2 100644 --- a/include/Engine/Collision/Collision.h +++ b/include/Engine/Collision/Collision.h @@ -15,6 +15,7 @@ #include "../Core/Transform.h" #include "../Core/Entity.h" #include "../Core/EntityWrapper.h" +#include "EntityAABB.h" class World; struct ComponentWrapper; @@ -58,10 +59,9 @@ bool AABBVsAABB(const AABB& a, const AABB& b); //Return true if the boxes are intersecting. //Also outputs the minimum translation that box [a] would need in order to resolve collision. bool AABBVsAABB(const AABB& a, const AABB& b, glm::vec3& minimumTranslation); -bool IsSameBoxProbably(const AABB& first, const AABB& second, const float epsilon = 0.0001f); // Calculates an absolute AABB from an entity AABB component -boost::optional EntityAbsoluteAABB(EntityWrapper& entity); +boost::optional EntityAbsoluteAABB(EntityWrapper& entity); } diff --git a/include/Engine/Collision/CollisionSystem.h b/include/Engine/Collision/CollisionSystem.h index 5f15a3d5..f3a7e4fe 100644 --- a/include/Engine/Collision/CollisionSystem.h +++ b/include/Engine/Collision/CollisionSystem.h @@ -7,30 +7,23 @@ #include "../Common.h" #include "../Core/System.h" #include "../Core/EventBroker.h" -#include "../Core/EKeyUp.h" #include "../Core/Octree.h" +#include "EntityAABB.h" class CollisionSystem : public PureSystem { public: - CollisionSystem(World* world, EventBroker* eventBroker, Octree* octree) + CollisionSystem(World* world, EventBroker* eventBroker, Octree* octree) : System(world, eventBroker) , PureSystem("Collidable") , m_Octree(octree) - , zPress(false) - { - //TODO: Debug stuff, remove later. - EVENT_SUBSCRIBE_MEMBER(m_EKeyUp, &CollisionSystem::OnKeyUp); - } + { } virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override; private: - Octree* m_Octree; - bool zPress; - - EventRelay m_EKeyUp; - bool OnKeyUp(const Events::KeyUp &event); + Octree* m_Octree; + std::vector m_OctreeResult; }; #endif \ No newline at end of file diff --git a/include/Engine/Collision/ETrigger.h b/include/Engine/Collision/ETrigger.h index 687c73fa..0b35ef1b 100644 --- a/include/Engine/Collision/ETrigger.h +++ b/include/Engine/Collision/ETrigger.h @@ -2,7 +2,7 @@ #define Events_TriggerEnter_h__ #include "../Core/EventBroker.h" -#include "../Core/Entity.h" +#include "../Core/EntityWrapper.h" namespace Events { @@ -11,27 +11,27 @@ namespace Events struct TriggerTouch : Event { /** The id of the entity that touches the trigger. */ - EntityID Entity; + EntityWrapper Entity; /** The id of the trigger entity. */ - EntityID Trigger; + EntityWrapper Trigger; }; /** Thrown once, when an entity has completely left a trigger. */ struct TriggerLeave : Event { /** The id of the entity that left the trigger. */ - EntityID Entity; + EntityWrapper Entity; /** The id of the trigger entity. */ - EntityID Trigger; + EntityWrapper Trigger; }; /** Thrown once, when an entity is completely contained inside a trigger. */ struct TriggerEnter : Event { /** The id of the entity that entered the trigger. */ - EntityID Entity; + EntityWrapper Entity; /** The id of the trigger entity. */ - EntityID Trigger; + EntityWrapper Trigger; }; } diff --git a/include/Engine/Collision/EntityAABB.h b/include/Engine/Collision/EntityAABB.h new file mode 100644 index 00000000..79c21271 --- /dev/null +++ b/include/Engine/Collision/EntityAABB.h @@ -0,0 +1,22 @@ +#ifndef EntityAABB_h__ +#define EntityAABB_h__ + +#include "../Core/AABB.h" +#include "../Core/EntityWrapper.h" + +struct EntityAABB : AABB +{ + EntityAABB() = default; + + EntityAABB(const glm::vec3& minPos, const glm::vec3& maxPos) + : AABB(minPos, maxPos) + { } + + EntityAABB(const AABB& aabb) + : AABB(aabb) + { } + + EntityWrapper Entity; +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Collision/TriggerSystem.h b/include/Engine/Collision/TriggerSystem.h index 648c8585..fa322ddd 100644 --- a/include/Engine/Collision/TriggerSystem.h +++ b/include/Engine/Collision/TriggerSystem.h @@ -8,13 +8,14 @@ #include "../Core/EventBroker.h" #include "../Core/Octree.h" #include "ETrigger.h" +#include "EntityAABB.h" class AABB; class TriggerSystem : public PureSystem { public: - TriggerSystem(World* world, EventBroker* eventBroker, Octree* octree) + TriggerSystem(World* world, EventBroker* eventBroker, Octree* octree) : System(world, eventBroker) , PureSystem("Trigger") , m_Octree(octree) @@ -27,9 +28,10 @@ public: virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override; private: - Octree* m_Octree; - std::unordered_map> m_EntitiesTouchingTrigger; - std::unordered_map> m_EntitiesCompletelyInTrigger; + Octree* m_Octree; + std::vector m_OctreeOut; + std::unordered_map> m_EntitiesTouchingTrigger; + std::unordered_map> m_EntitiesCompletelyInTrigger; //TODO: Only exists for debug purposes, remove later. EventRelay m_EEnter; @@ -40,13 +42,13 @@ private: bool OnLeave(const Events::TriggerLeave &event); //True if leave event was thrown. - bool throwLeaveIfWasInTrigger(std::unordered_set& triggerSet, EntityID pId, EntityID tId); + bool throwLeaveIfWasInTrigger(std::unordered_set& triggerSet, EntityWrapper colliderENtity, EntityWrapper triggerEntity); template - void publish(EntityID pId, EntityID tId) + void publish(EntityWrapper collider, EntityWrapper trigger) { Event e; - e.Trigger = tId; - e.Entity = pId; + e.Trigger = trigger; + e.Entity = collider; m_EventBroker->Publish(e); } }; diff --git a/include/Engine/Common.h b/include/Engine/Common.h index 8038b8af..8295554c 100644 --- a/include/Engine/Common.h +++ b/include/Engine/Common.h @@ -5,6 +5,7 @@ #include #include #include +#include #include "Core/Util/Logging.h" #include "Core/Util/IfDebug.h" \ No newline at end of file diff --git a/include/Engine/Core/AABB.h b/include/Engine/Core/AABB.h index 5b9c6485..0dea9603 100644 --- a/include/Engine/Core/AABB.h +++ b/include/Engine/Core/AABB.h @@ -9,7 +9,6 @@ public: AABB() = default; //No checks are made. Values in minPos must be less than values in maxPos, i.e. min.x < max.x, etc. AABB(const glm::vec3& minPos, const glm::vec3& maxPos); - AABB(const glm::vec4& minPos, const glm::vec4& maxPos); //No checks are made. Size must consist of non-negative numbers. static AABB FromOriginSize(const glm::vec3& origin, const glm::vec3& size); virtual ~AABB(); diff --git a/include/Engine/Core/EntityWrapper.h b/include/Engine/Core/EntityWrapper.h index b2e0ce4c..bf34b9be 100644 --- a/include/Engine/Core/EntityWrapper.h +++ b/include/Engine/Core/EntityWrapper.h @@ -35,7 +35,6 @@ struct EntityWrapper bool operator==(const EntityWrapper& e) const; bool operator!=(const EntityWrapper& e) const; explicit operator EntityID() const; - operator bool(); private: EntityWrapper firstChildByNameRecursive(const std::string& name, EntityID parent); diff --git a/include/Engine/Core/Octree.h b/include/Engine/Core/Octree.h index 8bac5503..72825c3c 100644 --- a/include/Engine/Core/Octree.h +++ b/include/Engine/Core/Octree.h @@ -149,7 +149,7 @@ template template void Octree::ObjectsInSameRegion(const Box& box, std::vector& outObjects) { - static_assert(std::is_base_of::value, "template argument type Box in Octree::ObjectsInSameRegion must be a subclass of AABB."); + //static_assert(std::is_base_of::value, "template argument type Box in Octree::ObjectsInSameRegion must be a subclass of AABB."); falsifyObjectChecks(); m_Root->ObjectsInSameRegion(box, outObjects); } diff --git a/include/Engine/Core/Util/Logging.h b/include/Engine/Core/Util/Logging.h index 43f2c022..3d027937 100644 --- a/include/Engine/Core/Util/Logging.h +++ b/include/Engine/Core/Util/Logging.h @@ -29,41 +29,9 @@ enum _LOG_LEVEL extern _LOG_LEVEL LOG_LEVEL; -const static char* _LOG_LEVEL_PREFIX[] = -{ - "EE: ", - "", - "WW: ", - "DD: " -}; +extern const char* _LOG_LEVEL_PREFIX[]; -static void _LOG(_LOG_LEVEL logLevel, const char* file, const char* func, unsigned int line, const char* format, ...) -{ - if (logLevel > LOG_LEVEL) { - return; - } - - char* message = nullptr; - va_list args; - - va_start(args, format); - size_t size = vsnprintf(message, 0, format, args) + 1; - va_end(args); - - va_start(args, format); - message = new char[size]; - vsnprintf(message, size, format, args); - va_end(args); - - if (logLevel == LOG_LEVEL_ERROR) { - 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; - } - - delete[] message; -} +extern void _LOG(_LOG_LEVEL logLevel, const char* file, const char* func, unsigned int line, const char* format, ...); #define LOG(logLevel, format, ...) \ _LOG(logLevel, __BASE_FILE__, __func__, __LINE__, format, ##__VA_ARGS__) @@ -77,7 +45,11 @@ static void _LOG(_LOG_LEVEL logLevel, const char* file, const char* func, unsign #define LOG_INFO(format, ...) \ LOG(LOG_LEVEL_INFO, format, ##__VA_ARGS__) +#ifdef DEBUG #define LOG_DEBUG(format, ...) \ LOG(LOG_LEVEL_DEBUG, format, ##__VA_ARGS__) +#else +#define LOG_DEBUG(format, ...) +#endif #endif // Logging_h__ \ No newline at end of file diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index 4cf88842..74f505fe 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -30,9 +30,18 @@ public: private: void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const; void GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm::vec2 dimensions, GLint format, GLenum type, GLint numMipMaps) const; + void DrawModelRenderQueues(std::list>& job, RenderScene& scene); + + void BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene); + void BindModelUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene); + + void BindExplosionTextures(std::shared_ptr& job); + void BindModelTextures(std::shared_ptr& job); Texture* m_WhiteTexture; Texture* m_BlackTexture; + Texture* m_NeutralNormalTexture; + Texture* m_GreyTexture; FrameBuffer m_FinalPassFrameBuffer; GLuint m_BloomTexture; @@ -43,6 +52,7 @@ private: const LightCullingPass* m_LightCullingPass; ShaderProgram* m_ForwardPlusProgram; + ShaderProgram* m_ExplosionEffectProgram; }; #endif \ No newline at end of file diff --git a/include/Engine/Rendering/ExplosionEffectJob.h b/include/Engine/Rendering/ExplosionEffectJob.h new file mode 100644 index 00000000..89b1342b --- /dev/null +++ b/include/Engine/Rendering/ExplosionEffectJob.h @@ -0,0 +1,106 @@ +#ifndef ExplosionEffectJob_h__ +#define ExplosionEffectJob_h__ + +#include + +#include "../Common.h" +#include "../GLM.h" +#include "../Core/ComponentWrapper.h" +#include "Texture.h" +#include "Model.h" +#include "RenderJob.h" +#include "../Core/ResourceManager.h" +#include "Camera.h" +#include "../Core/World.h" + +struct ExplosionEffectJob : ModelJob +{ + ExplosionEffectJob(ComponentWrapper explosionEffectComponent, ::Model* model, Camera* camera, glm::mat4 matrix, ::RawModel::MaterialGroup matGroup, ComponentWrapper modelComponent, ::World* world, glm::vec4 fillColor, float fillPercentage) + : ModelJob(model, camera, matrix, matGroup, modelComponent, world, fillColor, fillPercentage) + { + ExplosionOrigin = (glm::vec3)explosionEffectComponent["ExplosionOrigin"]; + TimeSinceDeath = (double)explosionEffectComponent["TimeSinceDeath"]; + ExplosionDuration = (double)explosionEffectComponent["ExplosionDuration"]; + EndColor = (glm::vec4)explosionEffectComponent["EndColor"]; + Randomness = (bool)explosionEffectComponent["Randomness"]; + RandomnessScalar = (double)explosionEffectComponent["RandomnessScalar"]; + Velocity = (glm::vec2)explosionEffectComponent["Velocity"]; + ColorByDistance = (bool)explosionEffectComponent["ColorByDistance"]; + ExponentialAccelaration = (bool)explosionEffectComponent["ExponentialAccelaration"]; + }; + + glm::vec3 ExplosionOrigin; + double TimeSinceDeath = 0.f; //Seconds + double ExplosionDuration = 2.f; + //bool Gravity = true; + //double GravityForce = 1.f; // Speed + //double ObjectRadius = 2.f; // TODO: Change this for object radius when it's available + glm::vec4 EndColor; + bool Randomness = false; + + float RandomnessScalar = 1.f; + glm::vec2 Velocity; + bool ColorByDistance = false; + //bool ReverseAnimation = false; + //bool Wireframe = false; + bool ExponentialAccelaration = false; + + std::array RandomNumbers = { + 0.3257552917701f, + 0.07601508315467f, + 0.57408909014151f, + 0.0f, + 0.8618231368539f, + 0.074957156588769f, + 0.39413607511396f, + 0.54579346698979f, + 0.83222648353885f, + 0.83635707285086f, + 0.34473986148124f, + 0.98092448710507f, + 0.46346380070944f, + 0.7308761201477f, + 0.70832470371776f, + 0.28268750909841f, + 0.26291620883295f, + 0.07685032816457f, + 0.30760929515008f, + 0.2781575388639f , + 0.016950582161988f , + 0.25787915254844f , + 0.76293767279151f , + 0.67730279903733f , + 0.49042877018937f , + 0.13002237823327f , + 0.62803373841012f , + 0.94525353747665f , + 0.32893980076953f , + 0.95952951719962f , + 0.056386206790985f , + 0.012030893476694f , + 0.93090049220757f, + 0.83579883064879f, + 0.79733513938139f, + 0.8796381046435f , + 0.94160434600972f , + 0.76901855588379f , + 0.50253688101775f , + 0.82457069578793f , + 0.80157403359263f , + 0.87291810189975f , + 0.64679548919517f , + 0.42664138899494f , + 0.77171308303797f , + 0.75567959237643f , + 0.45190826265696f , + 0.59844922628181f , + 0.56534937655802f , + 0.195656257307f}; + + void CalculateHash() override + { + Hash = 0; + } +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Rendering/IRenderer.h b/include/Engine/Rendering/IRenderer.h index 6ef189f4..811ecd28 100644 --- a/include/Engine/Rendering/IRenderer.h +++ b/include/Engine/Rendering/IRenderer.h @@ -25,21 +25,27 @@ class IRenderer { public: GLFWwindow* Window() const { return m_Window; } + //Returns screensize including window border and header Rectangle Resolution() const { return m_Resolution; } void SetResolution(const Rectangle& resolution) { m_Resolution = resolution; } bool Fullscreen() { return m_Fullscreen; } void SetFullscreen(bool fullscreen) { m_Fullscreen = fullscreen; } bool VSYNC() const { return m_VSYNC; } void SetVSYNC(bool vsync) { m_VSYNC = vsync; } + //Returns screensize excluding window border and header + Rectangle GetViewPortSize() const { return m_ViewPortWidth; } + void SetViewPortSize(const Rectangle& viewportWidth) { m_ViewPortWidth = viewportWidth; } virtual void Initialize() = 0; virtual void Update(double dt) = 0; virtual void Draw(RenderFrame& rq) = 0; virtual PickData Pick(glm::vec2 screenCord) = 0; + World* m_World; //Temp world, untill viktor merge. protected: Rectangle m_Resolution = Rectangle::Rectangle(1280, 720); + Rectangle m_ViewPortWidth = Rectangle::Rectangle(1280, 720); bool m_Fullscreen = false; bool m_VSYNC = false; int m_GLVersion[2]; diff --git a/include/Engine/Rendering/ModelJob.h b/include/Engine/Rendering/ModelJob.h index df7f1aec..2cb2169c 100644 --- a/include/Engine/Rendering/ModelJob.h +++ b/include/Engine/Rendering/ModelJob.h @@ -22,10 +22,26 @@ struct ModelJob : RenderJob { Model = model; TextureID = (matGroup.Texture) ? matGroup.Texture->ResourceID : 0; - DiffuseTexture = matGroup.Texture.get(); - NormalTexture = matGroup.NormalMap.get(); - SpecularTexture = matGroup.SpecularMap.get(); - IncandescenceTexture = matGroup.IncandescenceMap.get(); + if (modelComponent["DiffuseTexture"]) { + DiffuseTexture = matGroup.Texture.get(); + } else { + DiffuseTexture = nullptr; + } + if (modelComponent["NormalMap"]) { + NormalTexture = matGroup.NormalMap.get(); + } else { + NormalTexture = nullptr; + } + if (modelComponent["SpecularMap"]) { + SpecularTexture = matGroup.SpecularMap.get(); + } else { + SpecularTexture = nullptr; + } + if (modelComponent["GlowMap"]) { + IncandescenceTexture = matGroup.IncandescenceMap.get(); + } else { + IncandescenceTexture = nullptr; + } DiffuseColor = matGroup.DiffuseColor; SpecularColor = matGroup.SpecularColor; IncandescenceColor = matGroup.IncandescenceColor; @@ -39,7 +55,6 @@ struct ModelJob : RenderJob Depth = worldpos.z; World = world; - FillColor = fillColor; FillPercentage = fillPercentage; Skeleton = Model->m_RawModel->m_Skeleton; diff --git a/include/Engine/Rendering/RawModelCustom.h b/include/Engine/Rendering/RawModelCustom.h index ef7a28e5..fe00d89c 100644 --- a/include/Engine/Rendering/RawModelCustom.h +++ b/include/Engine/Rendering/RawModelCustom.h @@ -110,7 +110,7 @@ private: void ReadAnimationJoint(unsigned int &offset, char* fileData, unsigned int& fileByteSize); void ReadAnimationClips(unsigned int &offset, char* fileData, unsigned int& fileByteSize, unsigned int numberOfClips); void ReadAnimationClipSingle(unsigned int &offset, char* fileData, unsigned int& fileByteSize, unsigned int clipIndex); - void ReadAnimationKeyFrame(unsigned int &offset, char* fileData, unsigned int& fileByteSize, unsigned int numberOfJoints, Skeleton::Animation& animation); + void ReadAnimationKeyFrame(unsigned int &offset, char* fileData, unsigned int& fileByteSize, Skeleton::Animation& animation); //void CreateSkeleton(std::vector> &boneInfo, std::map &boneNameMapping, aiNode* node, int parentID); }; diff --git a/include/Engine/Rendering/RenderQueue.h b/include/Engine/Rendering/RenderQueue.h index b533f992..57371146 100644 --- a/include/Engine/Rendering/RenderQueue.h +++ b/include/Engine/Rendering/RenderQueue.h @@ -14,11 +14,13 @@ #include "TextJob.h" #include "PointLightJob.h" #include "DirectionalLightJob.h" +#include "ExplosionEffectJob.h" struct RenderScene { ::Camera* Camera = nullptr; - std::list> ForwardJobs; + std::list> OpaqueObjects; + std::list> TransparentObjects; std::list> PointLightJobs; std::list> TextJobs; std::list> DirectionalLightJobs; @@ -27,7 +29,8 @@ struct RenderScene void Clear() { - ForwardJobs.clear(); + OpaqueObjects.clear(); + TransparentObjects.clear(); PointLightJobs.clear(); TextJobs.clear(); DirectionalLightJobs.clear(); diff --git a/include/Engine/Rendering/RenderSystem.h b/include/Engine/Rendering/RenderSystem.h index 37f99341..d64147b9 100644 --- a/include/Engine/Rendering/RenderSystem.h +++ b/include/Engine/Rendering/RenderSystem.h @@ -35,17 +35,19 @@ private: EventRelay m_ESetCamera; bool OnSetCamera(Events::SetCamera &event); + EventRelay m_EInputCommand; + bool OnInputCommand(const Events::InputCommand& e); + EventRelay m_EPlayerSpawned; + bool OnPlayerSpawned(Events::PlayerSpawned& e); + + void fillModels(std::list>& opaqueJobs, std::list>& transparentJobs); void fillText(std::list>& jobs, World* world); void fillPointLights(std::list>& jobs, World* world); void fillDirectionalLights(std::list>& jobs, World* world); - EventRelay m_EInputCommand; - bool OnInputCommand(const Events::InputCommand& e); - - void fillModels(std::list>& jobs); void fillLight(std::list>& jobs); + bool isChildOfACamera(EntityWrapper entity); + bool isChildOfCurrentCamera(EntityWrapper entity); - EventRelay m_EPlayerSpawned; - bool OnPlayerSpawned(Events::PlayerSpawned& e); }; #endif \ No newline at end of file diff --git a/include/Engine/Rendering/Renderer.h b/include/Engine/Rendering/Renderer.h index d84f41d5..33a61edf 100644 --- a/include/Engine/Rendering/Renderer.h +++ b/include/Engine/Rendering/Renderer.h @@ -73,6 +73,8 @@ private: void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type); //--------------------ShaderPrograms-------------------// ShaderProgram* m_BasicForwardProgram; + ShaderProgram* m_ExplosionEffectProgram; + }; #endif \ No newline at end of file diff --git a/include/Game/ExplosionEffectSystem.h b/include/Game/ExplosionEffectSystem.h new file mode 100644 index 00000000..061ad221 --- /dev/null +++ b/include/Game/ExplosionEffectSystem.h @@ -0,0 +1,24 @@ +#include "Common.h" +#include "Core/System.h" + +class ExplosionEffectSystem : public PureSystem +{ +public: + ExplosionEffectSystem(World* world, EventBroker* eventBroker) + : System(world, eventBroker) + , PureSystem("ExplosionEffect") + { } + + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override + { + + if ((double)component["TimeSinceDeath"] > (double)component["ExplosionDuration"]) { + (double)component["TimeSinceDeath"] = 0.f; + } + (double&)component["TimeSinceDeath"] += dt; + + //if ((bool)Component["Gravity"] == true) { + // (bool)Component["ExponentialAccelaration"] = false; + //} + } +}; \ No newline at end of file diff --git a/include/Game/Game.h b/include/Game/Game.h index fab10a49..671edfc5 100644 --- a/include/Game/Game.h +++ b/include/Game/Game.h @@ -14,6 +14,7 @@ #include "Core/EKeyDown.h" #include "Core/EntityFilePreprocessor.h" #include "Core/SystemPipeline.h" +#include "ExplosionEffectSystem.h" #include "Editor/EditorSystem.h" #include "Core/EntityFile.h" #include "Rendering/RenderSystem.h" @@ -21,6 +22,7 @@ #include "Core/Octree.h" #include "Rendering/Font.h" #include "Systems/InterpolationSystem.h" +#include "Collision/EntityAABB.h" // Network #include #include "Network/Network.h" @@ -48,8 +50,8 @@ private: InputProxy* m_InputProxy; GUI::Frame* m_FrameStack; World* m_World; - Octree* m_OctreeCollision; - Octree* m_OctreeFrustrumCulling; + Octree* m_OctreeCollision; + Octree* m_OctreeFrustrumCulling; SystemPipeline* m_SystemPipeline; RenderFrame* m_RenderFrame; // Network variables diff --git a/include/Game/Systems/CapturePointSystem.h b/include/Game/Systems/CapturePointSystem.h index 3b459c40..18c32c76 100644 --- a/include/Game/Systems/CapturePointSystem.h +++ b/include/Game/Systems/CapturePointSystem.h @@ -40,7 +40,7 @@ private: int m_BlueTeamHomeCapturePoint = m_NotACapturePoint; int m_NumberOfCapturePoints = 0; - std::map m_CapturePointNumberToEntityIDMap; + std::map m_CapturePointNumberToEntityMap; //std::vector @@ -48,8 +48,8 @@ private: bool m_ResetTimers = false; //vectors which will keep track of enter/leave changes - std::vector> m_ETriggerTouchVector; - std::vector> m_ETriggerLeaveVector; + std::vector> m_ETriggerTouchVector; + std::vector> m_ETriggerLeaveVector; }; #endif \ No newline at end of file diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index 5ce7fa5f..ab46b0ea 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -12,6 +12,7 @@ + @@ -27,4 +28,5 @@ + \ No newline at end of file diff --git a/resources/Schema/Components/Animation.xml b/resources/Schema/Components/Animation.xml index 01af2747..66d2865d 100644 --- a/resources/Schema/Components/Animation.xml +++ b/resources/Schema/Components/Animation.xml @@ -1,5 +1,6 @@ + 0 true diff --git a/resources/Schema/Components/CapturePoint.xsd b/resources/Schema/Components/CapturePoint.xsd index 9e96fca6..91afd366 100644 --- a/resources/Schema/Components/CapturePoint.xsd +++ b/resources/Schema/Components/CapturePoint.xsd @@ -2,18 +2,7 @@ - - - - - - - - - - - - + diff --git a/resources/Schema/Components/ExplosionEffect.xml b/resources/Schema/Components/ExplosionEffect.xml new file mode 100644 index 00000000..22692729 --- /dev/null +++ b/resources/Schema/Components/ExplosionEffect.xml @@ -0,0 +1,17 @@ + + + + 0 + 2 + + + + + 0 + 1 + + 0 + + + 0 + \ No newline at end of file diff --git a/resources/Schema/Components/ExplosionEffect.xsd b/resources/Schema/Components/ExplosionEffect.xsd new file mode 100644 index 00000000..cdde5e52 --- /dev/null +++ b/resources/Schema/Components/ExplosionEffect.xsd @@ -0,0 +1,57 @@ + + + + + + + + A component that trigger the death effect + + + + + The position in which to spawn the component + + + Seconds since death + + + How many seconds the death animation should be + + + + + + The tint the polys end with + + + Add some randomness to the explosion + + + Alter the power of the randomness + + + The velocity factors (start/end) + + + Change the color by its moved distance instead of by its time + + + + + Linear/Exponential accelaration + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/HealthHUD.xml b/resources/Schema/Components/HealthHUD.xml index d7e20f92..a48b9606 100644 --- a/resources/Schema/Components/HealthHUD.xml +++ b/resources/Schema/Components/HealthHUD.xml @@ -1,2 +1,2 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/resources/Schema/Components/HiddenForLocalPlayer.xml b/resources/Schema/Components/HiddenForLocalPlayer.xml new file mode 100644 index 00000000..5840385c --- /dev/null +++ b/resources/Schema/Components/HiddenForLocalPlayer.xml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/resources/Schema/Components/HiddenForLocalPlayer.xsd b/resources/Schema/Components/HiddenForLocalPlayer.xsd new file mode 100644 index 00000000..7f47fba5 --- /dev/null +++ b/resources/Schema/Components/HiddenForLocalPlayer.xsd @@ -0,0 +1,11 @@ + + + + + + + + Used to make the entity invisible if it's parented to the current local player entity (for first person player model and such) + + + \ No newline at end of file diff --git a/resources/Schema/Components/Lifetime.xml b/resources/Schema/Components/Lifetime.xml index d7e230d7..302429b1 100644 --- a/resources/Schema/Components/Lifetime.xml +++ b/resources/Schema/Components/Lifetime.xml @@ -1,4 +1,4 @@ - + 0 - \ No newline at end of file + \ No newline at end of file diff --git a/resources/Schema/Components/Model.xml b/resources/Schema/Components/Model.xml index 8f78b9ee..4b77dacb 100644 --- a/resources/Schema/Components/Model.xml +++ b/resources/Schema/Components/Model.xml @@ -2,5 +2,10 @@ + false true + true + true + true + true \ No newline at end of file diff --git a/resources/Schema/Components/Model.xsd b/resources/Schema/Components/Model.xsd index fb0774f8..9c0cd519 100644 --- a/resources/Schema/Components/Model.xsd +++ b/resources/Schema/Components/Model.xsd @@ -15,8 +15,23 @@ Color tint + + Wether the model is transparent or not + - Wether the model is visible or not + Whether the model is visible or not + + + Whether the model should use the Diffuse texture or not + + + Whether the model should use the Normalmap or not + + + Whether the model should use the Specularmap or not + + + Whether the model should use the Glowmap or not diff --git a/resources/Schema/Components/Team.xsd b/resources/Schema/Components/Team.xsd index a81a8978..d6e14684 100755 --- a/resources/Schema/Components/Team.xsd +++ b/resources/Schema/Components/Team.xsd @@ -2,18 +2,7 @@ - - - - - - - - - - - - + diff --git a/resources/Schema/Entities/EditorTestWorld.xml b/resources/Schema/Entities/EditorTestWorld.xml index 5649a630..9565e2d4 100755 --- a/resources/Schema/Entities/EditorTestWorld.xml +++ b/resources/Schema/Entities/EditorTestWorld.xml @@ -6,7 +6,7 @@ - + Models/Core/UnitCube.mesh @@ -18,69 +18,51 @@ - - - - An error - - - - - - - - - - - An error - - - - - - - - - - - + - + - + + 0.80000001192092896 + Models/DirectionalLightWidget.mesh + + 1.0499999523162842 + + - + - + Models/Assault.mesh - + + - + - Models/SecondaryWeapon.fbx + Models/SecondaryWeapon.mesh @@ -91,17 +73,219 @@ - + + + + + + + + + + + + Run + + 1 + + + models/AssaultAnimated.mesh + + + + + + + + + + + Walk + + 1 + + + models/AssaultAnimated.mesh + + + + + + + + Models/Core/UnitSphere.mesh + + true + + + + + + + + + + + + + - Models/Core/UnitSphere.mesh + Models/Log.mesh - + + + + + + + + + + + + + Models/NormalMapSphere.mesh + + + + + + + + + + + Models/SpecularMapSphere.mesh + + + + + + + + + + 1 + + + + + + + + + + + Models/Core/UnitSphere.mesh + + + + 3 + 1.1399998664855957 + + + + + + + + + + + + + + + + Models/IncandescenceMapSphere.mesh + + + + + + + + + + + models/NormSpecIncdMapSphere.mesh + + + + + + + + + 1 + + + + + + + + + + + Models/Core/UnitSphere.mesh + + + + 3 + 1.1399998664855957 + + + + + + + + + + + + Models/Core/UnitSphere.mesh + + + + 5.0100002288818359 + 0.69999998807907104 + + + + + + + + + + + + Models/Core/UnitSphere.mesh + + + + 4 + 0.80000001192092896 + + + + + + + + + + + + diff --git a/resources/Schema/Entities/FastWorld.xml b/resources/Schema/Entities/FastWorld.xml index 68d1dccb..1289d9d1 100644 --- a/resources/Schema/Entities/FastWorld.xml +++ b/resources/Schema/Entities/FastWorld.xml @@ -25,10 +25,16 @@ - Crouch Walk - - 32 + Run + + 1 + + + + 0.95625903442123672 + + Models/AssaultAnimated.mesh diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index 7914f82b..e81ec5aa 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -20,7 +20,7 @@ - + @@ -141,9 +141,10 @@ Hold Pos - + 1 + Models/AssaultAnimated.mesh diff --git a/resources/Schema/Entities/PointLightWithModel.xml b/resources/Schema/Entities/PointLightWithModel.xml new file mode 100644 index 00000000..17ca950c --- /dev/null +++ b/resources/Schema/Entities/PointLightWithModel.xml @@ -0,0 +1,20 @@ + + + + + + Models/Core/UnitSphere.mesh + + + + 3 + 1.1399998664855957 + + + + + + + + + diff --git a/resources/Schema/Entities/Test.xml b/resources/Schema/Entities/Test.xml index 1f8da1a3..2cdf4e17 100644 --- a/resources/Schema/Entities/Test.xml +++ b/resources/Schema/Entities/Test.xml @@ -18,6 +18,23 @@ + + + + 0 + 2 + + + + + 0 + 1 + + 0 + + + 0 + Models/Camera.mesh diff --git a/resources/Schema/Types/Entity.xsd b/resources/Schema/Types/Entity.xsd index 5d135847..99b90caa 100644 --- a/resources/Schema/Types/Entity.xsd +++ b/resources/Schema/Types/Entity.xsd @@ -15,6 +15,7 @@ + @@ -33,6 +34,9 @@ + + + @@ -43,7 +47,7 @@ - + @@ -51,7 +55,7 @@ - + \ No newline at end of file diff --git a/resources/Schema/Types/TeamEnum.xsd b/resources/Schema/Types/TeamEnum.xsd new file mode 100644 index 00000000..e98e06d3 --- /dev/null +++ b/resources/Schema/Types/TeamEnum.xsd @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/resources/Shaders/ExplosionEffect.frag.glsl b/resources/Shaders/ExplosionEffect.frag.glsl new file mode 100644 index 00000000..32ababe5 --- /dev/null +++ b/resources/Shaders/ExplosionEffect.frag.glsl @@ -0,0 +1,25 @@ +#version 430 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; +uniform vec4 Color; + +uniform sampler2D texture0; + +in VertexData{ + vec3 Position; + vec3 Normal; + vec2 TextureCoordinate; + vec4 DiffuseColor; + vec4 ExplosionColor; +}Input; + +out vec4 fragmentColor; + + +void main() +{ + vec4 texel = texture2D(texture0, Input.TextureCoordinate); + fragmentColor = texel * Input.DiffuseColor * Color + Input.ExplosionColor; +} \ No newline at end of file diff --git a/resources/Shaders/ExplosionEffect.geom.glsl b/resources/Shaders/ExplosionEffect.geom.glsl new file mode 100644 index 00000000..cb91b545 --- /dev/null +++ b/resources/Shaders/ExplosionEffect.geom.glsl @@ -0,0 +1,179 @@ +#version 430 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; +uniform vec3 ExplosionOrigin; +uniform float TimeSinceDeath; +uniform float ExplosionDuration; +uniform vec4 EndColor; +uniform bool Randomness; +uniform float RandomNumbers[50]; +uniform float RandomnessScalar; +uniform vec2 Velocity; +uniform bool ColorByDistance; +uniform bool ExponentialAccelaration; + +in VertexData{ + vec3 Position; + vec3 Normal; + vec2 TextureCoordinate; + vec4 ExplosionColor; +}Input[]; + +out VertexData{ + vec3 Position; + vec3 Normal; + vec2 TextureCoordinate; + vec4 ExplosionColor; +}Output; + +layout(triangles) in; +layout(triangle_strip, max_vertices = 3) out; + +// returns a "random" number based on input parameter +float GetRandomNumber(int polygon_index) +{ + int randomIndex = int(mod(polygon_index, 50)); + + return RandomNumbers[randomIndex]; +} + +float randomNumber = 0.0; +float randomDistance = 0.0; + +void main() +{ + // calculate middle of vectors + vec3 v1 = Input[1].Position - Input[0].Position; + vec3 v2 = Input[2].Position - Input[0].Position; + vec3 v3 = Input[2].Position - (v1 / 2); + vec3 v4 = Input[1].Position - (v2 / 2); + + // calculate intersection + + // normalize direction + vec3 dir1 = normalize(v1); + vec3 dir2 = normalize(v2); + + vec3 vecA = Input[2].Position - Input[1].Position; //o2 - o1 + vec3 vecB = cross(dir1, dir2); + + mat3 matrisA = mat3(vecA, dir2, vecB); + + float lengthA = length(vecB); + lengthA = lengthA * lengthA; + + float s = determinant(matrisA) / lengthA; + + // center position of triangle + vec3 centerOfTriangle = Input[1].Position + (s * dir1); + + // center position of triangle to origin vector + vec3 origin2TriangleCenterVector = centerOfTriangle - ExplosionOrigin; + vec3 normalizedOrigin2TriangleCenterVector = normalize(origin2TriangleCenterVector); + + // time percentage until end of explosion (0.0-1.0) + float timePercetage = TimeSinceDeath / ExplosionDuration; + + // get a random number if randomness is enabled, otherwise the random number will be zero and won't affect the other algorithms + if (Randomness == true) + { + randomDistance = GetRandomNumber(gl_PrimitiveIDIn) * RandomnessScalar; + } + + vec2 randomVelocity = Velocity * (randomDistance + 1.0); + + // accelaration to use on current frame. is a interpolation between start and end value + float currentVelocity = mix(randomVelocity.x, randomVelocity.y, timePercetage); + + if (ExponentialAccelaration == true) + { + currentVelocity = pow(currentVelocity, 2) / 2.0; + } + + // distance between origin and the center of the current triangle + float origin2TriangleCenterDistance = length(origin2TriangleCenterVector); + + // the distance from origin to the triangle center with eventual randomness added + float fullDistanceWithRandomness = origin2TriangleCenterDistance + randomDistance; + + // vector from the triangle center to the explosion's shockwave + vec3 triangleCenter2ExplosionRadius = (normalizedOrigin2TriangleCenterVector * (TimeSinceDeath * currentVelocity)) - (normalizedOrigin2TriangleCenterVector * fullDistanceWithRandomness); + + // if the triangle is inside the blast radius... + if (fullDistanceWithRandomness <= (TimeSinceDeath * currentVelocity)) + { + float maxRadius = max(TimeSinceDeath * currentVelocity, (ExplosionDuration * currentVelocity)); + + float a = (randomVelocity.y - randomVelocity.x) / ExplosionDuration; + //float t = sqrt((2 * origin2TriangleCenterDistance) / a); + + // if explosion color should be affected by distance instead of time... + if (ColorByDistance == true) + { + // calculate the max distance (s) the triangle will move + float s = (randomVelocity.x * ExplosionDuration) + (0.5 * a * pow(ExplosionDuration, 2)); + + Output.ExplosionColor = EndColor * (length(triangleCenter2ExplosionRadius) / s); + } + else + { + Output.ExplosionColor = EndColor * timePercetage; + } + + // for every vertex on the triangle... + for (int i = 0; i < gl_in.length(); i++) + { + // move the triangle to the blast radius + vec3 ExplodedPosition = Input[i].Position + triangleCenter2ExplosionRadius; + + // pass through vertex data + Output.Normal = Input[i].Normal; + Output.Position = Input[i].Position; + Output.TextureCoordinate = Input[i].TextureCoordinate; + + // convert to model space for the gravity to always be in -y + vec4 ExplodedPositionInModelSpace = M * vec4(ExplodedPosition, 1.0); + + // if there is gravity, apply it + //if (Gravity == true) + //{ + // // ---DO THIS----> //ExplodedPositionInModelSpace.y = ExplodedPositionInModelSpace.y - TimeSinceHit; + // + // ExplodedPositionInModelSpace.y = ExplodedPositionInModelSpace.y - pow(TimeSinceDeath, 2); + //} + + // convert to screen space + gl_Position = P*V * ExplodedPositionInModelSpace; + EmitVertex(); + } + } + else + { + // if explosion color should be affected by distance instead of time... + if (ColorByDistance == true) + { + Output.ExplosionColor = vec4(0.0); + } + else + { + Output.ExplosionColor = EndColor * timePercetage; + } + + // for every vertex on the triangle... + for(int i = 0; i < gl_in.length(); i++) + { + // pass through vertex data + Output.Normal = Input[i].Normal; + Output.Position = Input[i].Position; + Output.TextureCoordinate = Input[i].TextureCoordinate; + + // no change in position, pass through vertex + gl_Position = gl_in[i].gl_Position; + EmitVertex(); + } + } + + //EndPrimitive(); +} diff --git a/resources/Shaders/ExplosionEffect.vert.glsl b/resources/Shaders/ExplosionEffect.vert.glsl new file mode 100644 index 00000000..04e1bda2 --- /dev/null +++ b/resources/Shaders/ExplosionEffect.vert.glsl @@ -0,0 +1,36 @@ +#version 430 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; + +layout(location = 0) in vec3 Position; +layout(location = 1) in vec3 Normal; +layout(location = 2) in vec3 Tangent; +layout(location = 3) in vec3 BiTangent; +layout(location = 4) in vec2 TextureCoords; +layout(location = 5) in vec4 DiffuseVertexColor; +layout(location = 6) in vec4 SpecularVertexColor; +layout(location = 7) in vec4 BoneIndices1; +layout(location = 8) in vec4 BoneIndices2; +layout(location = 9) in vec4 BoneWeights1; +layout(location = 10) in vec4 BoneWeights2; + +out VertexData{ + vec3 Position; + vec3 Normal; + vec2 TextureCoordinate; + vec4 DiffuseColor; + vec4 ExplosionColor; +}Output; + +void main() +{ + gl_Position = P*V*M * vec4(Position, 1.0); + + Output.Position = Position; + Output.TextureCoordinate = TextureCoords; + Output.Normal = Normal; + Output.DiffuseColor = DiffuseVertexColor; + Output.ExplosionColor = vec4(0.0); +} \ No newline at end of file diff --git a/resources/Shaders/ForwardPlus.frag.glsl b/resources/Shaders/ForwardPlus.frag.glsl index f33d870b..de672dd1 100644 --- a/resources/Shaders/ForwardPlus.frag.glsl +++ b/resources/Shaders/ForwardPlus.frag.glsl @@ -9,7 +9,9 @@ uniform vec2 ScreenDimensions; uniform vec4 FillColor; uniform float FillPercentage; layout (binding = 0) uniform sampler2D DiffuseTexture; -layout (binding = 1) uniform sampler2D GlowMap; +layout (binding = 1) uniform sampler2D NormalMapTexture; +layout (binding = 2) uniform sampler2D SpecularMapTexture; +layout (binding = 3) uniform sampler2D GlowMapTexture; #define TILE_SIZE 16 @@ -49,7 +51,10 @@ layout (std430, binding = 4) buffer LightIndexBuffer in VertexData{ vec3 Position; vec3 Normal; + vec3 Tangent; + vec3 BiTangent; vec2 TextureCoordinate; + vec4 ExplosionColor; }Input; out vec4 sceneColor; @@ -101,13 +106,21 @@ LightResult CalcDirectionalLightSource(vec4 direction, vec4 color, float intensi return result; } +vec4 CalcNormalMappedValue(vec3 normal, vec3 tangent, vec3 bitangent, vec2 textureCoordinate, sampler2D normalMap) +{ + mat3 TBN = mat3(tangent, bitangent, normal); + vec3 NormalMap = texture(normalMap, textureCoordinate).xyz * 2.0 - vec3(1.0); + return vec4(TBN * normalize(NormalMap), 0.0); +} void main() { vec4 diffuseTexel = texture2D(DiffuseTexture, Input.TextureCoordinate); - vec4 glowTexel = texture2D(GlowMap, Input.TextureCoordinate); + vec4 glowTexel = texture2D(GlowMapTexture, Input.TextureCoordinate); + vec4 specularTexel = texture2D(SpecularMapTexture, Input.TextureCoordinate); vec4 position = V * M * vec4(Input.Position, 1.0); - vec4 normal = normalize(V * vec4(Input.Normal, 0.0)); + vec4 normal = V * CalcNormalMappedValue(Input.Normal, Input.Tangent, Input.BiTangent, Input.TextureCoordinate, NormalMapTexture); + //vec4 normal = normalize(V * vec4(Input.Normal, 0.0)); vec4 viewVec = normalize(-position); vec2 tilePos; @@ -137,8 +150,8 @@ void main() totalLighting.Specular += light_result.Specular; } - //sceneColor += Input.DiffuseColor; - vec4 color_result = DiffuseColor * (totalLighting.Diffuse + totalLighting.Specular) * diffuseTexel * Color; + + vec4 color_result = (DiffuseColor + Input.ExplosionColor) * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)) * diffuseTexel * Color; float pos = ((P * vec4(Input.Position, 1)).y + 1.0)/2.0; @@ -146,27 +159,10 @@ void main() if(pos <= FillPercentage) { color_result += FillColor; } - //bloomColor = vec4(0.3, 0.8, 0.6, 1.0); sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); - //These if statements should be removed if they are slow. color_result += glowTexel; - - - bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), 1.0); - /* - if(color_result.x > 1 || color_result.y > 1 || color_result.z > 1) { - bloomColor = vec4(color_result.xyz, 1.0); - } else { - bloomColor = vec4(0.0, 0.0, 0.0, 1.0); - } */ - - //sceneColor += Input.DiffuseColor * (totalLighting.Diffuse) * diffuseTexel * Color; - //sceneColor += Input.DiffuseColor + vec4(0.0, LightGrids.Data[currentTile].Amount/3, 0, 1); - - - //Tiled Debug Code /* diff --git a/resources/Shaders/ForwardPlus.vert.glsl b/resources/Shaders/ForwardPlus.vert.glsl index c51216cb..1a7cca12 100644 --- a/resources/Shaders/ForwardPlus.vert.glsl +++ b/resources/Shaders/ForwardPlus.vert.glsl @@ -16,7 +16,10 @@ layout(location = 6) in vec4 BoneWeights; out VertexData{ vec3 Position; vec3 Normal; + vec3 Tangent; + vec3 BiTangent; vec2 TextureCoordinate; + vec4 ExplosionColor; }Output; void main() @@ -36,4 +39,7 @@ void main() Output.Position = (boneTransform * vec4(Position, 1.0)).xyz; 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.ExplosionColor = vec4(0.0); } \ No newline at end of file diff --git a/resources/Shaders/Gaussian_horiz.frag.glsl b/resources/Shaders/Gaussian_horiz.frag.glsl index bd48d2d5..6a9572c2 100644 --- a/resources/Shaders/Gaussian_horiz.frag.glsl +++ b/resources/Shaders/Gaussian_horiz.frag.glsl @@ -1,4 +1,5 @@ #version 430 +#extension GL_EXT_gpu_shader4 : enable layout (binding = 0) uniform sampler2D Texture; @@ -12,7 +13,7 @@ uniform float weight[5] = float[](0.227027, 0.1945946, 0.1216216, 0.054054, 0.01 void main() { - vec2 tex_offset = 1.0 / textureSize(Texture, 0); + vec2 tex_offset = 1.0 / textureSize2D(Texture, 0); vec3 result = texture(Texture, Input.TextureCoordinate).rgb * weight[0]; for(int i = 1; i < 5; ++i) { diff --git a/resources/Shaders/Gaussian_vert.frag.glsl b/resources/Shaders/Gaussian_vert.frag.glsl index 25b08f9f..8b0e861a 100644 --- a/resources/Shaders/Gaussian_vert.frag.glsl +++ b/resources/Shaders/Gaussian_vert.frag.glsl @@ -1,4 +1,5 @@ #version 430 +#extension GL_EXT_gpu_shader4 : enable layout (binding = 0) uniform sampler2D Texture; @@ -12,7 +13,7 @@ uniform float weight[5] = float[](0.227027, 0.1945946, 0.1216216, 0.054054, 0.01 void main() { - vec2 tex_offset = 1.0 / textureSize(Texture, 0); + vec2 tex_offset = 1.0 / textureSize2D(Texture, 0); vec3 result = texture(Texture, Input.TextureCoordinate).rgb * weight[0]; for(int i = 1; i < 5; ++i) { diff --git a/src/Engine/Collision/CollidableOctreeSystem.cpp b/src/Engine/Collision/CollidableOctreeSystem.cpp index e5da7910..476414dd 100644 --- a/src/Engine/Collision/CollidableOctreeSystem.cpp +++ b/src/Engine/Collision/CollidableOctreeSystem.cpp @@ -8,7 +8,7 @@ void CollidableOctreeSystem::Update(double dt) void CollidableOctreeSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) { if (entity.HasComponent("AABB")) { - boost::optional absoluteAABB = Collision::EntityAbsoluteAABB(entity); + boost::optional absoluteAABB = Collision::EntityAbsoluteAABB(entity); if (absoluteAABB) { m_Octree->AddDynamicObject(*absoluteAABB); } diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index 4a9c77a0..11288560 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -239,20 +239,6 @@ bool AABBvsTriangles(const AABB& box, const std::vector& model return hit; } -bool IsSameBoxProbably(const AABB& first, const AABB& second, const float epsilon) -{ - const glm::vec3& ma1 = first.MaxCorner(); - const glm::vec3& ma2 = second.MaxCorner(); - const glm::vec3& mi1 = first.MinCorner(); - const glm::vec3& mi2 = second.MinCorner(); - return (std::abs(ma1.x - ma2.x) < epsilon) && - (std::abs(mi1.x - mi2.x) < epsilon) && - (std::abs(ma1.z - ma2.z) < epsilon) && - (std::abs(mi1.z - mi2.z) < epsilon) && - (std::abs(ma1.y - ma2.y) < epsilon) && - (std::abs(mi1.y - mi2.y) < epsilon); -} - bool attachAABBComponentFromModel(World* world, EntityID id) { if (!world->HasComponent(id, "Model")) { @@ -284,7 +270,7 @@ bool attachAABBComponentFromModel(World* world, EntityID id) return true; } -boost::optional EntityAbsoluteAABB(EntityWrapper& entity) +boost::optional EntityAbsoluteAABB(EntityWrapper& entity) { if (!entity.HasComponent("AABB")) { return boost::none; @@ -295,7 +281,11 @@ boost::optional EntityAbsoluteAABB(EntityWrapper& entity) glm::vec3 absScale = Transform::AbsoluteScale(entity.World, entity.ID); glm::vec3 origin = absPosition + (glm::vec3)cAABB["Origin"]; glm::vec3 size = (glm::vec3)cAABB["Size"] * absScale; - return AABB::FromOriginSize(origin, size); + + EntityAABB aabb = EntityAABB::FromOriginSize(origin, size); + aabb.Entity = entity; + + return aabb; } } diff --git a/src/Engine/Collision/CollisionSystem.cpp b/src/Engine/Collision/CollisionSystem.cpp index ba841e36..382238e7 100644 --- a/src/Engine/Collision/CollisionSystem.cpp +++ b/src/Engine/Collision/CollisionSystem.cpp @@ -9,29 +9,27 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c } ComponentWrapper& cPhysics = entity["Physics"]; - boost::optional boundingBox = Collision::EntityAbsoluteAABB(entity); + boost::optional boundingBox = Collision::EntityAbsoluteAABB(entity); if (!boundingBox) { return; } ComponentWrapper& cTransform = entity["Transform"]; - AABB& boxA = *boundingBox; + EntityAABB& boxA = *boundingBox; - //Press 'Z' to enable/disable collision. - if (zPress) { - return; - } - - // Collide against octree - std::vector octreeResult; - m_Octree->ObjectsInSameRegion(*boundingBox, octreeResult); - for (auto& boxB : octreeResult) { + // Collide against octree items + m_OctreeResult.clear(); + m_Octree->ObjectsInSameRegion(*boundingBox, m_OctreeResult); + for (auto& boxB : m_OctreeResult) { glm::vec3 resolutionVector; - if (Collision::IsSameBoxProbably(boxA, boxB)) { + if (boxA.Entity == boxB.Entity) { continue; } + if (Collision::AABBVsAABB(boxA, boxB, resolutionVector)) { (glm::vec3&)cTransform["Position"] += resolutionVector; - ((glm::vec3&)cPhysics["Velocity"]).y = 0.f; + if (resolutionVector.y > 0) { + ((glm::vec3&)cPhysics["Velocity"]).y = 0.f; + } } } @@ -56,12 +54,4 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c // (glm::vec3&)cTransform["Position"] += resolutionVector; // } //} -} - -bool CollisionSystem::OnKeyUp(const Events::KeyUp & event) -{ - if (event.KeyCode == GLFW_KEY_Z) { - zPress = !zPress; - } - return false; -} +} \ No newline at end of file diff --git a/src/Engine/Collision/TriggerSystem.cpp b/src/Engine/Collision/TriggerSystem.cpp index ca169e16..dc7c77ff 100644 --- a/src/Engine/Collision/TriggerSystem.cpp +++ b/src/Engine/Collision/TriggerSystem.cpp @@ -3,79 +3,72 @@ #include "Core/AABB.h" #include "Rendering/Model.h" -void TriggerSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) +void TriggerSystem::UpdateComponent(EntityWrapper& triggerEntity, ComponentWrapper& cTrigger, double dt) { - //Currently only players can trigger things. - auto players = m_World->GetComponents("Player"); - if (players == nullptr) { - return; - } - EntityID tId = component.EntityID; - boost::optional triggerBox = Collision::EntityAbsoluteAABB(entity); - //The trigger *should* have a bounding box, or something, to test against so it can be triggered. + // The trigger *should* have a bounding box, or something, to test against so it can be triggered. + boost::optional triggerBox = Collision::EntityAbsoluteAABB(triggerEntity); if (!triggerBox) { return; } - for (auto& pc : *players) { - EntityID pId = pc.EntityID; - boost::optional playerBox = Collision::EntityAbsoluteAABB(EntityWrapper(m_World, pId)); - //The player can't trigger anything without an AABB. - if (!playerBox) { - continue; - } - if (!Collision::AABBVsAABB(*triggerBox, *playerBox)) { - //Entity is not touching the trigger, - //Throw event if it was previously. - if (throwLeaveIfWasInTrigger(m_EntitiesTouchingTrigger[tId], pId, tId)) { - continue; - } - //This only occurs if the entity was completely inside the trigger one frame, - //then completely outside the trigger, e.g. when dying and respawning. - throwLeaveIfWasInTrigger(m_EntitiesCompletelyInTrigger[tId], pId, tId); - } else { - //Entity is at least touching the trigger. + + m_OctreeOut.clear(); + m_Octree->ObjectsInSameRegion(*triggerBox, m_OctreeOut); + + for (EntityAABB& colliderBox : m_OctreeOut) { + EntityWrapper colliderEntity = colliderBox.Entity; + + if (Collision::AABBVsAABB(*triggerBox, colliderBox)) { AABB completelyInsideBox; - bool playerFitsInTrigger = glm::all(glm::greaterThan((*triggerBox).Size(), (*playerBox).Size())); - if (playerFitsInTrigger) { - completelyInsideBox = AABB::FromOriginSize((*triggerBox).Origin(), (*triggerBox).Size() - 2.0f * (*playerBox).Size()); + bool colliderFitsInTrigger = glm::all(glm::greaterThan((*triggerBox).Size(), colliderBox.Size())); + if (colliderFitsInTrigger) { + completelyInsideBox = AABB::FromOriginSize((*triggerBox).Origin(), (*triggerBox).Size() - 2.0f * colliderBox.Size()); } - if (playerFitsInTrigger && Collision::AABBVsAABB(completelyInsideBox, *playerBox)) { - //Entity is completely inside the trigger. - //If it was only touching before, it is erased. - m_EntitiesTouchingTrigger[tId].erase(pId); - std::unordered_set& completeSet = m_EntitiesCompletelyInTrigger[tId]; - if (completeSet.count(pId) == 0) { - //If it wasn't completely in the trigger, throw Enter and add to the set. - completeSet.insert(pId); - publish(pId, tId); + if (colliderFitsInTrigger && Collision::AABBVsAABB(completelyInsideBox, colliderBox)) { + // Entity is completely inside the trigger. + // If it was only touching before, it is erased. + m_EntitiesTouchingTrigger[triggerEntity].erase(colliderEntity); + auto& completeSet = m_EntitiesCompletelyInTrigger[triggerEntity]; + if (completeSet.count(colliderEntity) == 0) { + // If it wasn't completely in the trigger, throw Enter and add to the set. + completeSet.insert(colliderEntity); + publish(colliderEntity, triggerEntity); } } else { - //Entity is only touching the trigger. - std::unordered_set& touchSet = m_EntitiesTouchingTrigger[tId]; - std::unordered_set& completeSet = m_EntitiesCompletelyInTrigger[tId]; - const auto& it = completeSet.find(pId); + // Entity is only touching the trigger. + auto& touchSet = m_EntitiesTouchingTrigger[triggerEntity]; + auto& completeSet = m_EntitiesCompletelyInTrigger[triggerEntity]; + const auto& it = completeSet.find(colliderEntity); //If it was completely inside before. if (it != completeSet.end()) { completeSet.erase(it); - touchSet.insert(pId); + touchSet.insert(colliderEntity); //If it was completely outside before. - } else if (touchSet.count(pId) == 0) { - publish(pId, tId); - touchSet.insert(pId); + } else if (touchSet.count(colliderEntity) == 0) { + publish(colliderEntity, triggerEntity); + touchSet.insert(colliderEntity); } - //Else, it was touching the trigger last frame too and nothing is done. + // Else, it was touching the trigger last frame too and nothing is done. } + } else { + // Entity is not touching the trigger, + // Throw event if it was previously. + if (throwLeaveIfWasInTrigger(m_EntitiesTouchingTrigger[triggerEntity], colliderEntity, triggerEntity)) { + continue; + } + // This only occurs if the entity was completely inside the trigger one frame, + // then completely outside the trigger, e.g. when dying and respawning. + throwLeaveIfWasInTrigger(m_EntitiesCompletelyInTrigger[triggerEntity], colliderEntity, triggerEntity); } } } -bool TriggerSystem::throwLeaveIfWasInTrigger(std::unordered_set& triggerSet, EntityID pId, EntityID tId) +bool TriggerSystem::throwLeaveIfWasInTrigger(std::unordered_set& triggerSet, EntityWrapper colliderEntity, EntityWrapper triggerEntity) { - const auto& it = triggerSet.find(pId); + const auto& it = triggerSet.find(colliderEntity); if (it != triggerSet.end()) { //If it was in the trigger, but not anymore, throw leaveEvent and erase from the set. triggerSet.erase(it); - publish(pId, tId); + publish(colliderEntity, triggerEntity); return true; } return false; diff --git a/src/Engine/Core/AABB.cpp b/src/Engine/Core/AABB.cpp index 55b362fe..13e92d9c 100644 --- a/src/Engine/Core/AABB.cpp +++ b/src/Engine/Core/AABB.cpp @@ -20,10 +20,6 @@ AABB::AABB(const glm::vec3& minPos, const glm::vec3& maxPos) } } -AABB::AABB(const glm::vec4& minPos, const glm::vec4& maxPos) - : AABB(glm::vec3(minPos), glm::vec3(maxPos)) -{ } - AABB AABB::FromOriginSize(const glm::vec3& origin, const glm::vec3& size) { return AABB(origin - (size/2.f), origin + (size/2.f)); diff --git a/src/Engine/Core/EntityFile.cpp b/src/Engine/Core/EntityFile.cpp index a8e93e49..d5585317 100644 --- a/src/Engine/Core/EntityFile.cpp +++ b/src/Engine/Core/EntityFile.cpp @@ -20,7 +20,7 @@ void EntityFile::Parse(const EntityFileHandler* handler) const { using namespace xercesc; - EntityFileSAXHandler saxHandler(handler, nullptr); + EntityFileSAXHandler saxHandler(handler, m_SAX2XMLReader); setReaderFeatures(m_SAX2XMLReader); m_SAX2XMLReader->setContentHandler(&saxHandler); m_SAX2XMLReader->setErrorHandler(&saxHandler); @@ -37,6 +37,7 @@ void EntityFile::setReaderFeatures(xercesc::SAX2XMLReader* reader) reader->setFeature(XMLUni::fgSAX2CoreNameSpaces, true); reader->setFeature(XMLUni::fgXercesSchema, true); reader->setFeature(XMLUni::fgXercesSchemaFullChecking, true); + reader->setFeature(XMLUni::fgXercesCalculateSrcOfs, true); } std::size_t EntityFile::GetTypeStride(std::string typeName) @@ -111,8 +112,9 @@ void EntityFile::WriteValueData(char* outData, const ComponentInfo::Field_t& fie } catch (const boost::bad_lexical_cast&) { } } -EntityFileSAXHandler::EntityFileSAXHandler(const EntityFileHandler* handler, xercesc::SAX2XMLReader* reader) : m_Handler(handler) -, m_Reader(reader) +EntityFileSAXHandler::EntityFileSAXHandler(const EntityFileHandler* handler, xercesc::SAX2XMLReader* reader) + : m_Handler(handler) + , m_Reader(reader) { // 0 is imaginary base parent m_EntityStack.push(0); @@ -188,21 +190,29 @@ void EntityFileSAXHandler::characters(const XMLCh* const chars, const XMLSize_t void EntityFileSAXHandler::fatalError(const xercesc::SAXParseException& e) { - XS::ToString s(e.getMessage()); - LOG_ERROR("SAXParseException: %s", ((std::string)s).c_str()); - //throw e; + std::string message = XS::ToString(e.getMessage()); + std::string systemId = XS::ToString(e.getSystemId()); + XMLFileLoc line = e.getLineNumber(); + XMLFileLoc column = e.getColumnNumber(); + LOG_ERROR("SAXParseException\n\tLocation: %s:%i:%i\n\tFatal Error: %s", systemId.c_str(), line, column, message.c_str()); } void EntityFileSAXHandler::error(const xercesc::SAXParseException& e) { - XS::ToString s(e.getMessage()); - LOG_ERROR("SAXParseException: %s", ((std::string)s).c_str()); + std::string message = XS::ToString(e.getMessage()); + std::string systemId = XS::ToString(e.getSystemId()); + XMLFileLoc line = e.getLineNumber(); + XMLFileLoc column = e.getColumnNumber(); + LOG_ERROR("SAXParseException\n\tLocation: %s:%i:%i\n\tError: %s", systemId.c_str(), line, column, message.c_str()); } void EntityFileSAXHandler::warning(const xercesc::SAXParseException& e) { - XS::ToString s(e.getMessage()); - LOG_ERROR("SAXParseException: %s", ((std::string)s).c_str()); + std::string message = XS::ToString(e.getMessage()); + std::string systemId = XS::ToString(e.getSystemId()); + XMLFileLoc line = e.getLineNumber(); + XMLFileLoc column = e.getColumnNumber(); + LOG_ERROR("SAXParseException\n\tLocation: %s:%i:%i\n\tWarning: %s", systemId.c_str(), line, column, message.c_str()); } void EntityFileSAXHandler::onStartEntity(const xercesc::Attributes& attrs) diff --git a/src/Engine/Core/EntityFilePreprocessor.cpp b/src/Engine/Core/EntityFilePreprocessor.cpp index 7b4b2bb7..2a1d22d6 100644 --- a/src/Engine/Core/EntityFilePreprocessor.cpp +++ b/src/Engine/Core/EntityFilePreprocessor.cpp @@ -65,6 +65,7 @@ void EntityFilePreprocessor::parseComponentInfo() // Name compInfo.Name = XS::ToString(element->getName()); + bool brk = compInfo.Name == "HiddenForLocalPlayer"; // Known allocation compInfo.Meta->Allocation = m_ComponentCounts[compInfo.Name]; // Annotation @@ -90,7 +91,7 @@ void EntityFilePreprocessor::parseComponentInfo() // auto modelGroupParticle = complexTypeDefinition->getParticle(); if (modelGroupParticle == nullptr || modelGroupParticle->getTermType() != XSParticle::TERM_MODELGROUP) { - //LOG_ERROR("Failed to parse component definition for \"%s\": Model group particle was null or wasn't TERM_MODELGROUP!", compInfo.Name.c_str()); + LOG_ERROR("Failed to parse component definition for \"%s\": Model group particle was null or wasn't TERM_MODELGROUP!", compInfo.Name.c_str()); continue; } auto modelGroup = modelGroupParticle->getModelGroupTerm(); diff --git a/src/Engine/Core/EntityWrapper.cpp b/src/Engine/Core/EntityWrapper.cpp index 1f3fc1ab..071329a3 100644 --- a/src/Engine/Core/EntityWrapper.cpp +++ b/src/Engine/Core/EntityWrapper.cpp @@ -97,11 +97,6 @@ EntityWrapper::operator EntityID() const return this->ID; } -EntityWrapper::operator bool() -{ - return this->Valid(); -} - EntityWrapper EntityWrapper::firstChildByNameRecursive(const std::string& name, EntityID parent) { if (!this->World->ValidEntity(parent)) { diff --git a/src/Engine/Core/Octree.cpp b/src/Engine/Core/Octree.cpp index 18effea5..f3cafcfc 100644 --- a/src/Engine/Core/Octree.cpp +++ b/src/Engine/Core/Octree.cpp @@ -105,8 +105,7 @@ bool Child::BoxCollides(const AABB& boxToTest, AABB& outBoxIntersected) const for (int i : m_DynamicObjIndices) { if (!m_DynamicObjectsRef[i].Checked) { const AABB& objBox = *m_DynamicObjectsRef[i].Box; - if (!Collision::IsSameBoxProbably(boxToTest, objBox) && - Collision::AABBVsAABB(boxToTest, objBox)) { + if (Collision::AABBVsAABB(boxToTest, objBox)) { outBoxIntersected = objBox; return true; } diff --git a/src/Engine/Core/Util/Logging.cpp b/src/Engine/Core/Util/Logging.cpp index 5c88d98b..63a6f380 100644 --- a/src/Engine/Core/Util/Logging.cpp +++ b/src/Engine/Core/Util/Logging.cpp @@ -4,4 +4,40 @@ _LOG_LEVEL LOG_LEVEL = LOG_LEVEL_DEBUG; #else _LOG_LEVEL LOG_LEVEL = LOG_LEVEL_INFO; -#endif \ No newline at end of file +#endif + +const char* _LOG_LEVEL_PREFIX[] = +{ + "EE: ", + "", + "WW: ", + "DD: " +}; + +void _LOG(_LOG_LEVEL logLevel, const char* file, const char* func, unsigned int line, const char* format, ...) +{ + if (logLevel > LOG_LEVEL) { + return; + } + + char* message = nullptr; + va_list args; + + va_start(args, format); + size_t size = vsnprintf(message, 0, format, args) + 1; + va_end(args); + + va_start(args, format); + message = new char[size]; + vsnprintf(message, size, format, args); + va_end(args); + + if (logLevel == LOG_LEVEL_ERROR) { + 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; + } + + delete[] message; +} \ No newline at end of file diff --git a/src/Engine/Core/World.cpp b/src/Engine/Core/World.cpp index 0c4c9ce4..8b212d31 100644 --- a/src/Engine/Core/World.cpp +++ b/src/Engine/Core/World.cpp @@ -54,8 +54,12 @@ ComponentWrapper World::AttachComponent(EntityID entity, const std::string& comp bool World::HasComponent(EntityID entity, const std::string& componentType) const { - ComponentPool* pool = m_ComponentPools.at(componentType); - return pool->KnowsEntity(entity); + auto it = m_ComponentPools.find(componentType); + if (it == m_ComponentPools.end()) { + return false; + } else { + return it->second->KnowsEntity(entity); + } } ComponentWrapper World::GetComponent(EntityID entity, const std::string& componentType) diff --git a/src/Engine/Editor/EditorRenderSystem.cpp b/src/Engine/Editor/EditorRenderSystem.cpp index 2aad1340..898eac9d 100644 --- a/src/Engine/Editor/EditorRenderSystem.cpp +++ b/src/Engine/Editor/EditorRenderSystem.cpp @@ -12,7 +12,7 @@ EditorRenderSystem::EditorRenderSystem(World* m_World, EventBroker* eventBroker, void EditorRenderSystem::Update(double dt) { - if (m_CurrentCamera) { + if (m_CurrentCamera.Valid()) { ComponentWrapper cameraTransform = m_CurrentCamera["Transform"]; m_EditorCamera->SetPosition(cameraTransform["Position"]); m_EditorCamera->SetOrientation(glm::quat((const glm::vec3&)cameraTransform["Orientation"])); @@ -49,7 +49,11 @@ void EditorRenderSystem::Update(double dt) glm::mat4 modelMatrix = Transform::ModelMatrix(entity.ID, entity.World); for (auto matGroup : model->MaterialGroups()) { std::shared_ptr modelJob = std::make_shared(model, scene.Camera, modelMatrix, matGroup, cModel, entity.World, glm::vec4(0), 0.f); - scene.ForwardJobs.push_back(modelJob); + if(cModel["Transparent"]) { + scene.TransparentObjects.push_back(modelJob); + } else { + scene.OpaqueObjects.push_back(modelJob); + } } } } diff --git a/src/Engine/Editor/EditorWidgetSystem.cpp b/src/Engine/Editor/EditorWidgetSystem.cpp index 479671e2..8352c5c1 100644 --- a/src/Engine/Editor/EditorWidgetSystem.cpp +++ b/src/Engine/Editor/EditorWidgetSystem.cpp @@ -30,7 +30,7 @@ void EditorWidgetSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper auto camera = m_PickData.Camera; glm::vec3 axis = cEditorWidget["Axis"]; - glm::vec2 axisScreen = camera->WorldToScreen(axis, m_Renderer->Resolution()) - camera->WorldToScreen(glm::vec3(0, 0, 0), m_Renderer->Resolution()); + glm::vec2 axisScreen = camera->WorldToScreen(axis, m_Renderer->GetViewPortSize()) - camera->WorldToScreen(glm::vec3(0, 0, 0), m_Renderer->GetViewPortSize()); float dot = glm::dot(m_MouseDelta, glm::normalize(axisScreen)) / glm::length(axisScreen); glm::vec3 worldMovement = dot * axis; diff --git a/src/Engine/Rendering/DrawBloomPass.cpp b/src/Engine/Rendering/DrawBloomPass.cpp index 8fe1d807..4f48831b 100644 --- a/src/Engine/Rendering/DrawBloomPass.cpp +++ b/src/Engine/Rendering/DrawBloomPass.cpp @@ -13,7 +13,7 @@ DrawBloomPass::DrawBloomPass(IRenderer* renderer) void DrawBloomPass::InitializeTextures() { - m_WhiteTexture = ResourceManager::Load("Textures/Core/Blank.png"); + m_WhiteTexture = ResourceManager::Load("Textures/Core/White.png"); } void DrawBloomPass::InitializeShaderPrograms() @@ -34,12 +34,12 @@ void DrawBloomPass::InitializeShaderPrograms() void DrawBloomPass::InitializeBuffers() { - GenerateTexture(&m_GaussianTexture_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->Resolution().Width, m_Renderer->Resolution().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + GenerateTexture(&m_GaussianTexture_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); m_GaussianFrameBuffer_horiz.AddResource(std::shared_ptr(new Texture2D(&m_GaussianTexture_horiz, GL_COLOR_ATTACHMENT0))); m_GaussianFrameBuffer_horiz.Generate(); - GenerateTexture(&m_GaussianTexture_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->Resolution().Width, m_Renderer->Resolution().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + GenerateTexture(&m_GaussianTexture_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); m_GaussianFrameBuffer_vert.AddResource(std::shared_ptr(new Texture2D(&m_GaussianTexture_vert, GL_COLOR_ATTACHMENT0))); m_GaussianFrameBuffer_vert.Generate(); diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 0cd0e576..48ea4144 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -11,21 +11,23 @@ DrawFinalPass::DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCulling void DrawFinalPass::InitializeTextures() { - m_WhiteTexture = ResourceManager::Load("Textures/Core/Blank.png"); + m_WhiteTexture = ResourceManager::Load("Textures/Core/White.png"); m_BlackTexture = ResourceManager::Load("Textures/Core/Black.png"); + m_NeutralNormalTexture = ResourceManager::Load("Textures/Core/NeutralNormalMap.png"); + m_GreyTexture = ResourceManager::Load("Textures/Core/Grey.png"); } void DrawFinalPass::InitializeFrameBuffers() { glGenRenderbuffers(1, &m_DepthBuffer); glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Renderer->Resolution().Width, m_Renderer->Resolution().Height); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height); + + GenerateTexture(&m_SceneTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + //GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + //GenerateMipMapTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_FLOAT, 4); - GenerateTexture(&m_SceneTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->Resolution().Width, m_Renderer->Resolution().Height), GL_RGB16F, GL_RGB, GL_FLOAT); - //GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->Resolution().Width, m_Renderer->Resolution().Height), GL_RGB16F, GL_RGB, GL_FLOAT); - GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->Resolution().Width, m_Renderer->Resolution().Height), GL_RGB16F, GL_RGB, GL_FLOAT); - //GenerateMipMapTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, glm::vec2(m_Renderer->Resolution().Width, m_Renderer->Resolution().Height), GL_RGB16F, GL_FLOAT, 4); - m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new RenderBuffer(&m_DepthBuffer, GL_DEPTH_ATTACHMENT))); m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SceneTexture, GL_COLOR_ATTACHMENT0))); m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_BloomTexture, GL_COLOR_ATTACHMENT1))); @@ -42,6 +44,15 @@ void DrawFinalPass::InitializeShaderPrograms() m_ForwardPlusProgram->BindFragDataLocation(0, "sceneColor"); m_ForwardPlusProgram->BindFragDataLocation(1, "bloomColor"); m_ForwardPlusProgram->Link(); + + m_ExplosionEffectProgram = ResourceManager::Load("#ExplosionEffectProgram"); + m_ExplosionEffectProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlus.vert.glsl"))); + m_ExplosionEffectProgram->AddShader(std::shared_ptr(new GeometryShader("Shaders/ExplosionEffect.geom.glsl"))); + m_ExplosionEffectProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlus.frag.glsl"))); + m_ExplosionEffectProgram->Compile(); + m_ExplosionEffectProgram->BindFragDataLocation(0, "sceneColor"); + m_ExplosionEffectProgram->BindFragDataLocation(1, "bloomColor"); + m_ExplosionEffectProgram->Link(); } void DrawFinalPass::Draw(RenderScene& scene) @@ -49,69 +60,15 @@ void DrawFinalPass::Draw(RenderScene& scene) GLERROR("DrawFinalPass::Draw: Pre"); DrawFinalPassState* state = new DrawFinalPassState(m_FinalPassFrameBuffer.GetHandle()); - - m_ForwardPlusProgram->Bind(); - GLuint shaderHandle = m_ForwardPlusProgram->GetHandle(); - if (scene.ClearDepth) { glClear(GL_DEPTH_BUFFER_BIT); } - glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, m_LightCullingPass->LightSSBO()); - glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightCullingPass->LightGridSSBO()); - glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightCullingPass->LightIndexSSBO()); + DrawModelRenderQueues(scene.OpaqueObjects, scene); + GLERROR("DrawFinalPass::Draw: OpaqueObjects"); + DrawModelRenderQueues(scene.TransparentObjects, scene); + GLERROR("DrawFinalPass::Draw: TransparentObjects"); - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); - glUniform2f(glGetUniformLocation(shaderHandle, "ScreenDimensions"), m_Renderer->Resolution().Width, m_Renderer->Resolution().Height); - - - //TODO: Render: Add code for more jobs than modeljobs. - for (auto &job : scene.ForwardJobs) { - auto modelJob = std::dynamic_pointer_cast(job); - if(modelJob) { - //TODO: Kolla upp "header/include/common" shader saken så man slipper skicka in asmycket uniforms - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); - glUniform4fv(glGetUniformLocation(shaderHandle, "Color"), 1, glm::value_ptr(modelJob->Color)); - glUniform4fv(glGetUniformLocation(shaderHandle, "DiffuseColor"), 1, glm::value_ptr(modelJob->DiffuseColor)); - - glUniform4fv(glGetUniformLocation(shaderHandle, "FillColor"), 1, glm::value_ptr(modelJob->FillColor)); - glUniform1f(glGetUniformLocation(shaderHandle, "FillPercentage"), modelJob->FillPercentage); - - - glActiveTexture(GL_TEXTURE0); - if(modelJob->DiffuseTexture != nullptr) { - glBindTexture(GL_TEXTURE_2D, modelJob->DiffuseTexture->m_Texture); - } else { - glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture); - } - glActiveTexture(GL_TEXTURE1); - if (modelJob->IncandescenceTexture != nullptr) { - glBindTexture(GL_TEXTURE_2D, modelJob->IncandescenceTexture->m_Texture); - } else { - glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture); - } - - /*if(modelJob->GlowMap != nullptr) { - glBindTexture(GL_TEXTURE_2D, modelJob->GlowMap->m_Texture); - } else { - glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture); - }*/ - - //TODO: Fixa så att modelsJobs kan spela upp olika animationer och så att den kan få in en tid istället för 1.0f - Hälsningar Johan och Andreas :) - if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { - - if (modelJob->Animation != nullptr) { - std::vector frameBones = modelJob->Skeleton->GetFrameBones( *modelJob->Animation, modelJob->AnimationTime); - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } - } - - glBindVertexArray(modelJob->Model->VAO); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); - glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex * sizeof(unsigned int))); - } - } GLERROR("DrawFinalPass::Draw: END"); delete state; } @@ -149,4 +106,152 @@ void DrawFinalPass::GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); GLERROR("MipMap Texture initialization failed"); -} \ No newline at end of file +} + +void DrawFinalPass::DrawModelRenderQueues(std::list>& job, RenderScene& scene) +{ + GLuint forwardHandle = m_ForwardPlusProgram->GetHandle(); + GLuint explosionHandle = m_ExplosionEffectProgram->GetHandle(); + + glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, m_LightCullingPass->LightSSBO()); + glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightCullingPass->LightGridSSBO()); + glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightCullingPass->LightIndexSSBO()); + + for(auto &job : job) + { + auto explosionEffectJob = std::dynamic_pointer_cast(job); + if(explosionEffectJob) { + //Bind program + m_ExplosionEffectProgram->Bind(); + + //Bind uniforms + BindExplosionUniforms(explosionHandle, explosionEffectJob, scene); + + if (explosionEffectJob->Model->m_RawModel->m_Skeleton != nullptr) { + + if (explosionEffectJob->Animation != nullptr) { + std::vector frameBones = explosionEffectJob->Skeleton->GetFrameBones(*explosionEffectJob->Animation, explosionEffectJob->AnimationTime); + glUniformMatrix4fv(glGetUniformLocation(explosionHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + } + + //bind textures + BindExplosionTextures(explosionEffectJob); + //draw + glBindVertexArray(explosionEffectJob->Model->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, explosionEffectJob->Model->ElementBuffer); + glDrawElements(GL_TRIANGLES, explosionEffectJob->EndIndex - explosionEffectJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(explosionEffectJob->StartIndex*sizeof(unsigned int))); + + } else { + auto modelJob = std::dynamic_pointer_cast(job); + if (modelJob) { + //bind forward program + m_ForwardPlusProgram->Bind(); + + //bind uniforms + BindModelUniforms(forwardHandle, modelJob, scene); + + //bind textures + BindModelTextures(modelJob); + + if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { + + if (modelJob->Animation != nullptr) { + std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); + glUniformMatrix4fv(glGetUniformLocation(forwardHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + } + + //draw + glBindVertexArray(modelJob->Model->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); + glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex*sizeof(unsigned int))); + GLERROR("DrawFinalPass::Model: END"); + } + } + } + +} + +void DrawFinalPass::BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene) +{ + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); + glUniform2f(glGetUniformLocation(shaderHandle, "ScreenDimensions"), m_Renderer->Resolution().Width, m_Renderer->Resolution().Height); + + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(job->Matrix)); + glUniform4fv(glGetUniformLocation(shaderHandle, "Color"), 1, glm::value_ptr(job->Color)); + glUniform3fv(glGetUniformLocation(shaderHandle, "ExplosionOrigin"), 1, glm::value_ptr(job->ExplosionOrigin)); + glUniform1f(glGetUniformLocation(shaderHandle, "TimeSinceDeath"), job->TimeSinceDeath); + glUniform1f(glGetUniformLocation(shaderHandle, "ExplosionDuration"), job->ExplosionDuration); + glUniform4fv(glGetUniformLocation(shaderHandle, "EndColor"), 1, glm::value_ptr(job->EndColor)); + glUniform1i(glGetUniformLocation(shaderHandle, "Randomness"), job->Randomness); + glUniform1f(glGetUniformLocation(shaderHandle, "RandomnessScalar"), job->RandomnessScalar); + glUniform2fv(glGetUniformLocation(shaderHandle, "Velocity"), 1, glm::value_ptr(job->Velocity)); + glUniform1i(glGetUniformLocation(shaderHandle, "ColorByDistance"), job->ColorByDistance); + glUniform1i(glGetUniformLocation(shaderHandle, "ExponentialAccelaration"), job->ExponentialAccelaration); + glUniform4fv(glGetUniformLocation(shaderHandle, "DiffuseColor"), 1, glm::value_ptr(job->DiffuseColor)); + glUniform1fv(glGetUniformLocation(shaderHandle, "RandomNumbers"), 50, job->RandomNumbers.data()); +} + +void DrawFinalPass::BindModelUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene) +{ + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); + glUniform2f(glGetUniformLocation(shaderHandle, "ScreenDimensions"), m_Renderer->Resolution().Width, m_Renderer->Resolution().Height); + + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(job->Matrix)); + glUniform4fv(glGetUniformLocation(shaderHandle, "Color"), 1, glm::value_ptr(job->Color)); + glUniform4fv(glGetUniformLocation(shaderHandle, "DiffuseColor"), 1, glm::value_ptr(job->DiffuseColor)); + glUniform4fv(glGetUniformLocation(shaderHandle, "FillColor"), 1, glm::value_ptr(job->FillColor)); + glUniform1f(glGetUniformLocation(shaderHandle, "FillPercentage"), job->FillPercentage); +} + + +void DrawFinalPass::BindExplosionTextures(std::shared_ptr& job) +{ + glActiveTexture(GL_TEXTURE0); + if (job->DiffuseTexture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture->m_Texture); + } else { + glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture); + } + glActiveTexture(GL_TEXTURE1); + if (job->IncandescenceTexture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture->m_Texture); + } else { + glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture); + } +} + +void DrawFinalPass::BindModelTextures(std::shared_ptr& job) +{ + glActiveTexture(GL_TEXTURE0); + if (job->DiffuseTexture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture->m_Texture); + } else { + glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture); + } + + glActiveTexture(GL_TEXTURE1); + if (job->NormalTexture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->NormalTexture->m_Texture); + } else { + glBindTexture(GL_TEXTURE_2D, m_NeutralNormalTexture->m_Texture); + } + + glActiveTexture(GL_TEXTURE2); + if (job->SpecularTexture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->SpecularTexture->m_Texture); + } else { + glBindTexture(GL_TEXTURE_2D, m_GreyTexture->m_Texture); + } + + glActiveTexture(GL_TEXTURE3); + if (job->IncandescenceTexture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture->m_Texture); + } else { + glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture); + } +} + diff --git a/src/Engine/Rendering/LightCullingPass.cpp b/src/Engine/Rendering/LightCullingPass.cpp index a68fe4d1..46a17286 100644 --- a/src/Engine/Rendering/LightCullingPass.cpp +++ b/src/Engine/Rendering/LightCullingPass.cpp @@ -25,8 +25,8 @@ void LightCullingPass::GenerateNewFrustum(RenderScene& scene) glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, m_FrustumSSBO); glUniformMatrix4fv(glGetUniformLocation(m_CalculateFrustumProgram->GetHandle(), "P"), 1, false, glm::value_ptr(scene.Camera->ProjectionMatrix())); - glUniform2f(glGetUniformLocation(m_CalculateFrustumProgram->GetHandle(), "ScreenDimensions"), m_Renderer->Resolution().Width, m_Renderer->Resolution().Height); - glDispatchCompute((int)(m_Renderer->Resolution().Width/(TILE_SIZE*TILE_SIZE) + 1), (int)(m_Renderer->Resolution().Height/(TILE_SIZE*TILE_SIZE) + 1), 1); + glUniform2f(glGetUniformLocation(m_CalculateFrustumProgram->GetHandle(), "ScreenDimensions"), m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height); + glDispatchCompute((int)(m_Renderer->GetViewPortSize().Width/(TILE_SIZE*TILE_SIZE) + 1), (int)(m_Renderer->GetViewPortSize().Height/(TILE_SIZE*TILE_SIZE) + 1), 1); GLERROR("CalculateFrustum Error: End"); } @@ -40,7 +40,7 @@ void LightCullingPass::OnResolutionChange() void LightCullingPass::SetSSBOSizes() { - m_NumberOfTiles = (int)(m_Renderer->Resolution().Width/TILE_SIZE) * (int)(m_Renderer->Resolution().Height/TILE_SIZE); + m_NumberOfTiles = (int)(m_Renderer->GetViewPortSize().Width/TILE_SIZE) * (int)(m_Renderer->GetViewPortSize().Height/TILE_SIZE); m_Frustums = new Frustum[m_NumberOfTiles]; m_LightGrid = new LightGrid[m_NumberOfTiles]; @@ -67,14 +67,14 @@ void LightCullingPass::CullLights(RenderScene& scene) glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); m_LightCullProgram->Bind(); - glUniform2f(glGetUniformLocation(m_LightCullProgram->GetHandle(), "ScreenDimensions"), m_Renderer->Resolution().Width, m_Renderer->Resolution().Height); + glUniform2f(glGetUniformLocation(m_LightCullProgram->GetHandle(), "ScreenDimensions"), m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height); glUniformMatrix4fv(glGetUniformLocation(m_LightCullProgram->GetHandle(), "V"), 1, false, glm::value_ptr(scene.Camera->ViewMatrix())); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, m_FrustumSSBO); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, m_LightSSBO); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightGridSSBO); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, m_LightOffsetSSBO); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightIndexSSBO); - glDispatchCompute(glm::ceil(m_Renderer->Resolution().Width / TILE_SIZE), glm::ceil(m_Renderer->Resolution().Height / TILE_SIZE), 1); + glDispatchCompute(glm::ceil(m_Renderer->GetViewPortSize().Width/ TILE_SIZE), glm::ceil(m_Renderer->GetViewPortSize().Height / TILE_SIZE), 1); GLERROR("CullLights Error: End"); } diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index c7e23479..ec7533bd 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -18,14 +18,14 @@ PickingPass::~PickingPass() void PickingPass::InitializeTextures() { GenerateTexture(&m_PickingTexture, GL_CLAMP_TO_BORDER, GL_LINEAR, - glm::vec2(m_Renderer->Resolution().Width, m_Renderer->Resolution().Height), GL_RG8, GL_RG, GL_UNSIGNED_BYTE); + glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RG8, GL_RG, GL_UNSIGNED_BYTE); } void PickingPass::InitializeFrameBuffers() { glGenRenderbuffers(1, &m_DepthBuffer); glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Renderer->Resolution().Width, m_Renderer->Resolution().Height); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height); m_PickingBuffer.AddResource(std::shared_ptr(new RenderBuffer(&m_DepthBuffer, GL_DEPTH_ATTACHMENT))); m_PickingBuffer.AddResource(std::shared_ptr(new Texture2D(&m_PickingTexture, GL_COLOR_ATTACHMENT0))); @@ -56,7 +56,7 @@ void PickingPass::Draw(RenderScene& scene) } m_Camera = scene.Camera; - for (auto &job : scene.ForwardJobs) { + for (auto &job : scene.OpaqueObjects) { auto modelJob = std::dynamic_pointer_cast(job); if (modelJob) { @@ -101,6 +101,52 @@ void PickingPass::Draw(RenderScene& scene) glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex * sizeof(unsigned int))); } } + + for (auto &job : scene.TransparentObjects) { + auto modelJob = std::dynamic_pointer_cast(job); + + if (modelJob) { + int pickColor[2] = { m_ColorCounter[0], m_ColorCounter[1] }; + + PickingInfo pickInfo; + pickInfo.Entity = modelJob->Entity; + pickInfo.World = modelJob->World; + pickInfo.Camera = scene.Camera; + + auto color = m_EntityColors.find(std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)); + if (color != m_EntityColors.end()) { + pickColor[0] = color->second[0]; + pickColor[1] = color->second[1]; + } else { + m_EntityColors[std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)] = glm::ivec2(pickColor[0], pickColor[1]); + if (m_ColorCounter[0] > 255) { + m_ColorCounter[0] = 0; + m_ColorCounter[1] += 5; + } else { + m_ColorCounter[0] += 50; + } + } + + m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; + + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); + glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); + + if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { + + if (modelJob->Animation != nullptr) { + std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + } + + glBindVertexArray(modelJob->Model->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); + glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex * sizeof(unsigned int))); + } + } m_PickingBuffer.Unbind(); GLERROR("PickingPass Error"); diff --git a/src/Engine/Rendering/RawModelCustom.cpp b/src/Engine/Rendering/RawModelCustom.cpp index 5d3c3fb0..c1939bdf 100644 --- a/src/Engine/Rendering/RawModelCustom.cpp +++ b/src/Engine/Rendering/RawModelCustom.cpp @@ -341,22 +341,16 @@ void RawModelCustom::ReadAnimationClipSingle(unsigned int &offset, char* fileDat unsigned int nrOfKeyframes = *(unsigned int*)(fileData + offset); offset += sizeof(unsigned int); - if (offset + sizeof(unsigned int) > fileByteSize) { - throw Resource::FailedLoadingException("Reading AnimationClip NrOfJoints failed"); - } - unsigned int nrOfJoints = *(unsigned int*)(fileData + offset); - offset += sizeof(unsigned int); - newAnimation.Keyframes.reserve(nrOfKeyframes); for (unsigned int i = 0; i < nrOfKeyframes; i++) { - ReadAnimationKeyFrame(offset, fileData, fileByteSize, nrOfJoints, newAnimation); + ReadAnimationKeyFrame(offset, fileData, fileByteSize, newAnimation); } m_Skeleton->Animations[newAnimation.Name] = newAnimation; #else #endif } -void RawModelCustom::ReadAnimationKeyFrame(unsigned int &offset, char* fileData, unsigned int& fileByteSize, unsigned int nrOfJoints, Skeleton::Animation& animation) +void RawModelCustom::ReadAnimationKeyFrame(unsigned int &offset, char* fileData, unsigned int& fileByteSize, Skeleton::Animation& animation) { Skeleton::Animation::Keyframe newKeyFrame; @@ -372,6 +366,12 @@ void RawModelCustom::ReadAnimationKeyFrame(unsigned int &offset, char* fileData, newKeyFrame.Time = *(float*)(fileData + offset); offset += sizeof(float); + if (offset + sizeof(unsigned int) > fileByteSize) { + throw Resource::FailedLoadingException("Reading AnimationKeyFrame NrOfJoints failed"); + } + unsigned int nrOfJoints = *(unsigned int*)(fileData + offset); + offset += sizeof(unsigned int); + if (offset + sizeof(Skeleton::Animation::Keyframe::BoneProperty) * nrOfJoints> fileByteSize) { throw Resource::FailedLoadingException("Reading AnimationKeyFrame joints failed"); } diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index a67f2c75..a0912a45 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -31,33 +31,41 @@ bool RenderSystem::OnSetCamera(Events::SetCamera& e) return true; } -void RenderSystem::fillModels(std::list>& jobs) +bool RenderSystem::isChildOfACamera(EntityWrapper entity) +{ + return entity.FirstParentWithComponent("Camera").Valid(); +} +bool RenderSystem::isChildOfCurrentCamera(EntityWrapper entity) +{ + return entity == m_CurrentCamera || entity.IsChildOf(m_CurrentCamera); +} + +void RenderSystem::fillModels(std::list>& opaqueJobs, std::list>& transparentJobs) { auto models = m_World->GetComponents("Model"); if (models == nullptr) { return; } - for (auto& modelComponent : *models) { - bool visible = modelComponent["Visible"]; + for (auto& cModel : *models) { + bool visible = cModel["Visible"]; if (!visible) { continue; } - std::string resource = modelComponent["Resource"]; + std::string resource = cModel["Resource"]; if (resource.empty()) { continue; } - EntityWrapper entity(m_World, modelComponent.EntityID); + EntityWrapper entity(m_World, cModel.EntityID); - // Don't render the local player - if (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer)) { - if (!entity.HasComponent("HealthHUD") && entity.Name() != "Crosshair" && entity.Name() != "Weapon") { //Should work but needs to be fixed. Should only render the things "childed" to the local player camera - continue; - } + // Only render children of a camera if that camera is currently active + if (isChildOfACamera(entity) && !isChildOfCurrentCamera(entity)) { + continue; } - if ((entity.Name() == "Weapon" || entity.HasComponent("HealthHUD")) && !entity.IsChildOf(m_LocalPlayer)) { + // Hide things parented to local player if they have the HiddenFromLocalPlayer component + if (entity.HasComponent("HiddenForLocalPlayer") && (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer))) { continue; } @@ -75,22 +83,58 @@ void RenderSystem::fillModels(std::list>& jobs) } } - float fillPercentage = 0.f; glm::vec4 fillColor = glm::vec4(0); - - if(m_World->HasComponent(modelComponent.EntityID, "Fill")) { - auto fillComponent = m_World->GetComponent(modelComponent.EntityID, "Fill"); + if(m_World->HasComponent(cModel.EntityID, "Fill")) { + auto fillComponent = m_World->GetComponent(cModel.EntityID, "Fill"); fillPercentage = (float)(double)fillComponent["Percentage"]; fillColor = (glm::vec4)fillComponent["Color"]; } - - - glm::mat4 modelMatrix = Transform::ModelMatrix(modelComponent.EntityID, m_World); + glm::mat4 modelMatrix = Transform::ModelMatrix(cModel.EntityID, m_World); for (auto matGroup : model->MaterialGroups()) { - std::shared_ptr modelJob = std::shared_ptr(new ModelJob(model, m_Camera, modelMatrix, matGroup, modelComponent, m_World, fillColor, fillPercentage)); - jobs.push_back(modelJob); + if (m_World->HasComponent(cModel.EntityID, "ExplosionEffect")) { + auto explosionEffectComponent = m_World->GetComponent(cModel.EntityID, "ExplosionEffect"); + std::shared_ptr explosionEffectJob = std::shared_ptr(new ExplosionEffectJob( + explosionEffectComponent, + model, + m_Camera, + modelMatrix, + matGroup, + cModel, + m_World, + fillColor, + fillPercentage + )); + if(explosionEffectJob->Color.a != 1.f || explosionEffectJob->EndColor.a != 1.f || explosionEffectJob->DiffuseColor.a != 1.f) { + cModel["Transparent"] = true; + } + + if (cModel["Transparent"]) { + transparentJobs.push_back(explosionEffectJob); + } else { + opaqueJobs.push_back(explosionEffectJob); + } + } else { + std::shared_ptr modelJob = std::shared_ptr(new ModelJob( + model, + m_Camera, + modelMatrix, + matGroup, + cModel, + m_World, + fillColor, + fillPercentage + )); + if (modelJob->Color.a != 1.f || modelJob->DiffuseColor.a != 1.f) { + cModel["Transparent"] = true; + } + if (cModel["Transparent"]) { + transparentJobs.push_back(modelJob); + } else { + opaqueJobs.push_back(modelJob); + } + } } } } @@ -200,7 +244,7 @@ void RenderSystem::Update(double dt) RenderScene scene; scene.Camera = m_Camera; scene.Viewport = Rectangle(1280, 720); - fillModels(scene.ForwardJobs); + fillModels(scene.OpaqueObjects, scene.TransparentObjects); fillPointLights(scene.PointLightJobs, m_World); fillDirectionalLights(scene.DirectionalLightJobs, m_World); fillText(scene.TextJobs, m_World); diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index 4f687a99..55cd8b03 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -58,11 +58,25 @@ void Renderer::InitializeWindow() LOG_ERROR("GLEW: Initialization failed"); exit(EXIT_FAILURE); } + + int res[2]; + glfwGetWindowSize(m_Window, &res[0], &res[1]); + SetViewPortSize(Rectangle::Rectangle(res[0], res[1])); + } void Renderer::InitializeShaders() { m_BasicForwardProgram = ResourceManager::Load("#m_BasicForwardProgram"); + m_ExplosionEffectProgram = ResourceManager::Load("#ExplosionEffectProgram"); + //m_ExplosionEffectProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ExplosionEffect.vert.glsl"))); + //m_ExplosionEffectProgram->AddShader(std::shared_ptr(new GeometryShader("Shaders/ExplosionEffect.geom.glsl"))); + //m_ExplosionEffectProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ExplosionEffect.frag.glsl"))); + //m_ExplosionEffectProgram->Compile(); + //m_ExplosionEffectProgram->Link(); + + + } void Renderer::InputUpdate(double dt) @@ -98,6 +112,7 @@ void Renderer::Draw(RenderFrame& frame) m_LightCullingPass->FillLightList(*scene); m_LightCullingPass->CullLights(*scene); m_DrawFinalPass->Draw(*scene); + //m_DrawScenePass->Draw(*scene); GLERROR("Renderer::Draw m_DrawScenePass->Draw"); @@ -133,14 +148,14 @@ PickData Renderer::Pick(glm::vec2 screenCoord) void Renderer::InitializeTextures() { m_ErrorTexture = ResourceManager::Load("Textures/Core/ErrorTexture.png"); - m_WhiteTexture = ResourceManager::Load("Textures/Core/Blank.png"); + m_WhiteTexture = ResourceManager::Load("Textures/Core/White.png"); } void Renderer::SortRenderJobsByDepth(RenderScene &scene) { //Sort all forward jobs so transparency is good. - scene.ForwardJobs.sort(Renderer::DepthSort); + scene.TransparentObjects.sort(Renderer::DepthSort); } void Renderer::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 903b270f..515540bf 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -1,5 +1,6 @@ #include "Game.h" #include "Collision/CollidableOctreeSystem.h" +#include "Collision/EntityAABB.h" #include "Collision/TriggerSystem.h" #include "Collision/CollisionSystem.h" #include "Systems/RaptorCopterSystem.h" @@ -42,7 +43,7 @@ Game::Game(int argc, char* argv[]) 0, m_Config->Get("Video.Width", 1280), m_Config->Get("Video.Height", 720) - )); + )); m_Renderer->Initialize(); //m_Renderer->Camera()->SetFOV(glm::radians(m_Config->Get("Video.FOV", 90.f))); m_RenderFrame = new RenderFrame(); @@ -72,14 +73,15 @@ Game::Game(int argc, char* argv[]) // Create Octrees - m_OctreeCollision = new Octree(AABB(glm::vec3(-100), glm::vec3(100)), 4); - m_OctreeFrustrumCulling = new Octree(AABB(glm::vec3(-100), glm::vec3(100)), 4); + m_OctreeCollision = new Octree(AABB(glm::vec3(-100), glm::vec3(100)), 4); + m_OctreeFrustrumCulling = new Octree(AABB(glm::vec3(-100), glm::vec3(100)), 4); // Create system pipeline m_SystemPipeline = new SystemPipeline(m_World, m_EventBroker); // All systems with orderlevel 0 will be updated first. unsigned int updateOrderLevel = 0; m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); @@ -87,6 +89,7 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer); m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel); // Populate Octree with collidables ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision); @@ -98,7 +101,6 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision); ++updateOrderLevel; - m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_RenderFrame); ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_RenderFrame); diff --git a/src/Game/Systems/CapturePointSystem.cpp b/src/Game/Systems/CapturePointSystem.cpp index fbd20e38..43876822 100644 --- a/src/Game/Systems/CapturePointSystem.cpp +++ b/src/Game/Systems/CapturePointSystem.cpp @@ -13,27 +13,27 @@ CapturePointSystem::CapturePointSystem(World* world, EventBroker* eventBroker) //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& entity, ComponentWrapper& capturePoint, double dt) +void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, ComponentWrapper& cCapturePoint, double dt) { if (m_WinnerWasFound) { return; } - const int capturePointNumber = capturePoint["CapturePointNumber"]; - const bool hasTeamComponent = m_World->HasComponent(capturePoint.EntityID, "Team"); + const int capturePointNumber = cCapturePoint["CapturePointNumber"]; + const bool hasTeamComponent = capturePointEntity.HasComponent("Team"); //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) { - m_World->AttachComponent(capturePoint.EntityID, "Team"); - ComponentWrapper& teamComponent = m_World->GetComponent(capturePoint.EntityID, "Team"); + m_World->AttachComponent(cCapturePoint.EntityID, "Team"); + ComponentWrapper& teamComponent = capturePointEntity["Team"]; teamComponent["Team"] = (int)teamComponent["Team"].Enum("Spectator"); } - ComponentWrapper& teamComponent = m_World->GetComponent(capturePoint.EntityID, "Team"); + ComponentWrapper& teamComponent = capturePointEntity["Team"]; const int redTeam = (int)teamComponent["Team"].Enum("Red"); const int blueTeam = (int)teamComponent["Team"].Enum("Blue"); const int spectatorTeam = (int)teamComponent["Team"].Enum("Spectator"); - int homePointForTeam = (int)capturePoint["HomePointForTeam"]; + int homePointForTeam = (int)cCapturePoint["HomePointForTeam"]; if (m_NumberOfCapturePoints == 0 && capturePointNumber != 0 && (homePointForTeam == redTeam || homePointForTeam == blueTeam)) { m_NumberOfCapturePoints = capturePointNumber + 1;//ex 2 -> 0,1,2 = 3 if (homePointForTeam == redTeam) { @@ -46,8 +46,8 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper } //if we havent received all capturepoints yet, just return - if (m_NumberOfCapturePoints == 0 || m_NumberOfCapturePoints != m_CapturePointNumberToEntityIDMap.size()) { - m_CapturePointNumberToEntityIDMap.insert(std::make_pair(capturePointNumber, capturePoint.EntityID)); + if (m_NumberOfCapturePoints == 0 || m_NumberOfCapturePoints != m_CapturePointNumberToEntityMap.size()) { + m_CapturePointNumberToEntityMap.insert(std::make_pair(capturePointNumber, capturePointEntity)); return; } @@ -55,9 +55,9 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper int ownedBy = teamComponent["Team"]; int redTeamPlayersStandingInside = 0; int blueTeamPlayersStandingInside = 0; - if (entity.HasComponent("Model")) { + if (capturePointEntity.HasComponent("Model")) { //Now sets team color to the capturepoint, or white if it is uncaptured. - entity["Model"]["Color"] = ownedBy == blueTeam ? glm::vec4(0, 0.2f, 1, 1) : ownedBy == redTeam ? glm::vec4(1, 0.2f, 0, 1) : glm::vec4(1, 1, 1, 1); + capturePointEntity["Model"]["Color"] = ownedBy == blueTeam ? glm::vec4(0, 0.2f, 1, 1) : ownedBy == redTeam ? glm::vec4(1, 0.2f, 0, 1) : glm::vec4(1, 1, 1, 1); } //calculate next possible capturePoint for both teams @@ -66,10 +66,10 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper nextPossibleCapturePoint["Blue"] = -1; for (size_t i = 0; i < m_NumberOfCapturePoints; i++) { - if (!m_World->HasComponent(m_CapturePointNumberToEntityIDMap[i], "Team")) { + if (m_CapturePointNumberToEntityMap[i].HasComponent("Team")) { continue; } - ComponentWrapper& capturePointOwnedBy = m_World->GetComponent(m_CapturePointNumberToEntityIDMap[i], "Team"); + ComponentWrapper& capturePointOwnedBy = m_CapturePointNumberToEntityMap[i]["Team"]; if ((int)capturePointOwnedBy["Team"] == redTeam && m_RedTeamHomeCapturePoint == 0) { nextPossibleCapturePoint["Red"] = i + 1; } @@ -79,10 +79,10 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper } for (int i = m_NumberOfCapturePoints - 1; i >= 0; i--) { - if (!m_World->HasComponent(m_CapturePointNumberToEntityIDMap[i], "Team")) { + if (!m_CapturePointNumberToEntityMap[i].HasComponent("Team")) { continue; } - ComponentWrapper& capturePointOwnedBy = m_World->GetComponent(m_CapturePointNumberToEntityIDMap[i], "Team"); + ComponentWrapper& capturePointOwnedBy = m_CapturePointNumberToEntityMap[i]["Team"]; if ((int)capturePointOwnedBy["Team"] == redTeam && m_RedTeamHomeCapturePoint != 0) { nextPossibleCapturePoint["Red"] = i - 1; } @@ -95,7 +95,7 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper if (m_ResetTimers) { for (size_t i = 0; i < m_NumberOfCapturePoints; i++) { - ComponentWrapper& capturePoint = m_World->GetComponent(m_CapturePointNumberToEntityIDMap[i], "CapturePoint"); + ComponentWrapper& capturePoint = m_CapturePointNumberToEntityMap[i]["CapturePoint"]; if ((int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Red"] && (int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Blue"]) { capturePoint["CaptureTimer"] = 0.0; @@ -106,34 +106,34 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper //colorize next possible capturepoint if (nextPossibleCapturePoint["Red"] == capturePointNumber) { - entity["Model"]["Color"] = glm::vec4(1, 1, 0, 1); + capturePointEntity["Model"]["Color"] = glm::vec4(1, 1, 0, 1); } if (nextPossibleCapturePoint["Blue"] == capturePointNumber) { - entity["Model"]["Color"] = glm::vec4(0, 1, 1, 1); + capturePointEntity["Model"]["Color"] = glm::vec4(0, 1, 1, 1); } //check how many players are standing inside and are healthy for (size_t i = m_ETriggerTouchVector.size(); i > 0; i--) { auto triggerTouched = m_ETriggerTouchVector[i - 1]; - if (std::get<1>(triggerTouched) == capturePoint.EntityID) { + if (std::get<1>(triggerTouched) == capturePointEntity) { //some player has touched this - lets figure out: what team, health - EntityID playerID = std::get<0>(triggerTouched); - if (!m_World->HasComponent(playerID, "Player")) { + EntityWrapper player = std::get<0>(triggerTouched); + if (!player.HasComponent("Player")) { //if a non-player has entered the capturePoint, just erase that event and continue m_ETriggerTouchVector.erase(m_ETriggerTouchVector.begin() + i - 1); continue; } - bool hasHealthComponent = m_World->HasComponent(playerID, "Health"); + bool hasHealthComponent = player.HasComponent("Health"); if (hasHealthComponent) { - double currentHealth = m_World->GetComponent(playerID, "Health")["Health"]; + double currentHealth = player["Health"]["Health"]; //check if player is dead if ((int)currentHealth == 0) { continue; } } //check team - spectatorNumber = "no team" - int teamNumber = m_World->GetComponent(playerID, "Team")["Team"]; + int teamNumber = player["Team"]["Team"]; if (teamNumber == redTeam) { redTeamPlayersStandingInside++; } else if (teamNumber == blueTeam) { @@ -169,24 +169,24 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper //B. at most one of the teams have players inside //if capturePoint is not owned by the take-over team, just modify the CaptureTimer accordingly if (ownedBy != currentTeam && canCapture) { - if (abs((double)capturePoint["CaptureTimer"]) < 0.001f) { + if (abs((double)cCapturePoint["CaptureTimer"]) < 0.001f) { LOG_DEBUG("Point is being captured by team %i", currentTeam); //Remove when we tested sufficiently. } - capturePoint["CaptureTimer"] = (double)capturePoint["CaptureTimer"] + timerDeltaChange; + 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)capturePoint["CaptureTimer"] < 0.0) || - (ownedBy == currentTeam && currentTeam == blueTeam && (double)capturePoint["CaptureTimer"] > 0.0)) { - capturePoint["CaptureTimer"] = (double)capturePoint["CaptureTimer"] + timerDeltaChange; + if ((ownedBy == currentTeam && currentTeam == redTeam && (double)cCapturePoint["CaptureTimer"] < 0.0) || + (ownedBy == currentTeam && currentTeam == blueTeam && (double)cCapturePoint["CaptureTimer"] > 0.0)) { + cCapturePoint["CaptureTimer"] = (double)cCapturePoint["CaptureTimer"] + timerDeltaChange; } //check if captureTimer > m_CaptureTimeToTakeOver and if so change owner and publish the eCaptured event - if (abs((double)capturePoint["CaptureTimer"]) > abs(m_CaptureTimeToTakeOver) && canCapture) { + if (abs((double)cCapturePoint["CaptureTimer"]) > abs(m_CaptureTimeToTakeOver) && canCapture) { teamComponent["Team"] = currentTeam; - capturePoint["CaptureTimer"] = 0.0; + cCapturePoint["CaptureTimer"] = 0.0; //publish Captured event LOG_DEBUG("Point is captured by team %i!", currentTeam); //Remove when we tested sufficiently. Events::Captured e; - e.CapturePointID = capturePoint.EntityID; + e.CapturePointID = cCapturePoint.EntityID; e.TeamNumberThatCapturedCapturePoint = currentTeam; m_EventBroker->Publish(e); //NextPossibleCapturePoint will be calculated in the next update... diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 0f6588be..6eab02c5 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -80,14 +80,14 @@ void PlayerMovementSystem::Update(double dt) velocity.y += 4.f; } - //if (player.HasComponent("AABB")) { - // glm::vec3& size = player["AABB"]["Size"]; - // if (controller->Crouching()) { - // size = glm::vec3(1.f, 1.f, 1.f); - // } else { - // size = glm::vec3(1.f, 1.6f, 1.f); - // } - //} + if (player.HasComponent("AABB")) { + glm::vec3& size = player["AABB"]["Size"]; + if (controller->Crouching()) { + size = glm::vec3(1.f, 1.f, 1.f); + } else { + size = glm::vec3(1.f, 1.6f, 1.f); + } + } // Animations EntityWrapper playerModel = player.FirstChildByName("PlayerModel"); diff --git a/src/Game/Systems/WeaponSystem.cpp b/src/Game/Systems/WeaponSystem.cpp index f78e092f..4b4b8da2 100644 --- a/src/Game/Systems/WeaponSystem.cpp +++ b/src/Game/Systems/WeaponSystem.cpp @@ -25,6 +25,16 @@ bool WeaponSystem::OnPlayerSpawned(const Events::PlayerSpawned& e) bool WeaponSystem::OnInputCommand(const Events::InputCommand& e) { + // Only shoot client-side! + if (e.PlayerID != -1) { + return false; + } + + // Only shoot if the player is alive + if (!m_LocalPlayer.Valid()) { + return false; + } + if (e.Command == "PrimaryFire" && e.Value > 0) { Events::Shoot eShoot; if (e.PlayerID == -1) { @@ -94,7 +104,7 @@ bool WeaponSystem::OnShoot(Events::Shoot& eShoot) // Screen center, based on current resolution! // TODO: check if player has enough ammo and if weapon has a cooldown or not - Rectangle screenResolution = m_Renderer->Resolution(); + Rectangle screenResolution = m_Renderer->GetViewPortSize(); glm::vec2 centerScreen = glm::vec2(screenResolution.Width / 2, screenResolution.Height / 2); // TODO: check if player has enough ammo and if weapon has a cooldown or not diff --git a/tools/MayaExporter/MayaExporter/Skeleton.cpp b/tools/MayaExporter/MayaExporter/Skeleton.cpp index bb8c10d3..a6ee5897 100644 --- a/tools/MayaExporter/MayaExporter/Skeleton.cpp +++ b/tools/MayaExporter/MayaExporter/Skeleton.cpp @@ -68,92 +68,92 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e std::vector animatedJoints; std::vector m_Hierarchy; - Animation returnData; - double oneDivSixty = 1 / 60.0; - returnData.Name = animationName; + Animation returnData; + double oneDivSixty = 1 / 60.0; + returnData.Name = animationName; returnData.nameLength = animationName.size() + 1; - returnData.Duration = (endFrame - startFrame) * oneDivSixty; + returnData.Duration = (endFrame - startFrame) * oneDivSixty; - std::map, 4>> joinCheckMap; - std::map exportJoint; + std::map, 4>> joinCheckMap; + std::map exportJoint; - MItDag jointIt(MItDag::TraversalType::kDepthFirst, MFn::kJoint); - for (unsigned int i = startFrame; i <= endFrame; i++) - { - MAnimControl::setCurrentTime(MTime(i, MTime::kNTSCField)); - while (!jointIt.isDone()) - { - m_Hierarchy.push_back(jointIt.item()); + //MItDag jointIt(MItDag::TraversalType::kDepthFirst, MFn::kJoint); + //for (unsigned int i = startFrame; i <= endFrame; i++) + //{ + // MAnimControl::setCurrentTime(MTime(i, MTime::kNTSCField)); + // while (!jointIt.isDone()) + // { + // m_Hierarchy.push_back(jointIt.item()); - MFnTransform MayaJoint(jointIt.item()); - MMatrix transformationMatrix = MayaJoint.transformationMatrix(); + // MFnTransform MayaJoint(jointIt.item()); + // MMatrix transformationMatrix = MayaJoint.transformationMatrix(); - if (i == startFrame) - { - double doubleMat[4][4]; - transformationMatrix.get(doubleMat); + // if (i == startFrame) + // { + // double doubleMat[4][4]; + // transformationMatrix.get(doubleMat); - joinCheckMap[MayaJoint.name().asChar()][0][0] = doubleMat[0][0]; - joinCheckMap[MayaJoint.name().asChar()][0][1] = doubleMat[0][1]; - joinCheckMap[MayaJoint.name().asChar()][0][2] = doubleMat[0][2]; - joinCheckMap[MayaJoint.name().asChar()][0][3] = doubleMat[0][3]; - joinCheckMap[MayaJoint.name().asChar()][1][0] = doubleMat[1][0]; - joinCheckMap[MayaJoint.name().asChar()][1][1] = doubleMat[1][1]; - joinCheckMap[MayaJoint.name().asChar()][1][2] = doubleMat[1][2]; - joinCheckMap[MayaJoint.name().asChar()][1][3] = doubleMat[1][3]; - joinCheckMap[MayaJoint.name().asChar()][2][0] = doubleMat[2][0]; - joinCheckMap[MayaJoint.name().asChar()][2][1] = doubleMat[2][1]; - joinCheckMap[MayaJoint.name().asChar()][2][2] = doubleMat[2][2]; - joinCheckMap[MayaJoint.name().asChar()][2][3] = doubleMat[2][3]; - joinCheckMap[MayaJoint.name().asChar()][3][0] = doubleMat[3][0]; - joinCheckMap[MayaJoint.name().asChar()][3][1] = doubleMat[3][1]; - joinCheckMap[MayaJoint.name().asChar()][3][2] = doubleMat[3][2]; - joinCheckMap[MayaJoint.name().asChar()][3][3] = doubleMat[3][3]; + // joinCheckMap[MayaJoint.name().asChar()][0][0] = doubleMat[0][0]; + // joinCheckMap[MayaJoint.name().asChar()][0][1] = doubleMat[0][1]; + // joinCheckMap[MayaJoint.name().asChar()][0][2] = doubleMat[0][2]; + // joinCheckMap[MayaJoint.name().asChar()][0][3] = doubleMat[0][3]; + // joinCheckMap[MayaJoint.name().asChar()][1][0] = doubleMat[1][0]; + // joinCheckMap[MayaJoint.name().asChar()][1][1] = doubleMat[1][1]; + // joinCheckMap[MayaJoint.name().asChar()][1][2] = doubleMat[1][2]; + // joinCheckMap[MayaJoint.name().asChar()][1][3] = doubleMat[1][3]; + // joinCheckMap[MayaJoint.name().asChar()][2][0] = doubleMat[2][0]; + // joinCheckMap[MayaJoint.name().asChar()][2][1] = doubleMat[2][1]; + // joinCheckMap[MayaJoint.name().asChar()][2][2] = doubleMat[2][2]; + // joinCheckMap[MayaJoint.name().asChar()][2][3] = doubleMat[2][3]; + // joinCheckMap[MayaJoint.name().asChar()][3][0] = doubleMat[3][0]; + // joinCheckMap[MayaJoint.name().asChar()][3][1] = doubleMat[3][1]; + // joinCheckMap[MayaJoint.name().asChar()][3][2] = doubleMat[3][2]; + // joinCheckMap[MayaJoint.name().asChar()][3][3] = doubleMat[3][3]; - exportJoint[MayaJoint.name().asChar()] = false; - } - else if(!exportJoint[MayaJoint.name().asChar()])//!exportJoint[MayaJoint.name().asChar()]) - { - double doubleMat[4][4]; + // exportJoint[MayaJoint.name().asChar()] = false; + // } + // else if(!exportJoint[MayaJoint.name().asChar()])//!exportJoint[MayaJoint.name().asChar()]) + // { + // double doubleMat[4][4]; - doubleMat[0][0] = joinCheckMap[MayaJoint.name().asChar()][0][0]; - doubleMat[0][1] = joinCheckMap[MayaJoint.name().asChar()][0][1]; - doubleMat[0][2] = joinCheckMap[MayaJoint.name().asChar()][0][2]; - doubleMat[0][3] = joinCheckMap[MayaJoint.name().asChar()][0][3]; - doubleMat[1][0] = joinCheckMap[MayaJoint.name().asChar()][1][0]; - doubleMat[1][1] = joinCheckMap[MayaJoint.name().asChar()][1][1]; - doubleMat[1][2] = joinCheckMap[MayaJoint.name().asChar()][1][2]; - doubleMat[1][3] = joinCheckMap[MayaJoint.name().asChar()][1][3]; - doubleMat[2][0] = joinCheckMap[MayaJoint.name().asChar()][2][0]; - doubleMat[2][1] = joinCheckMap[MayaJoint.name().asChar()][2][1]; - doubleMat[2][2] = joinCheckMap[MayaJoint.name().asChar()][2][2]; - doubleMat[2][3] = joinCheckMap[MayaJoint.name().asChar()][2][3]; - doubleMat[3][0] = joinCheckMap[MayaJoint.name().asChar()][3][0]; - doubleMat[3][1] = joinCheckMap[MayaJoint.name().asChar()][3][1]; - doubleMat[3][2] = joinCheckMap[MayaJoint.name().asChar()][3][2]; - doubleMat[3][3] = joinCheckMap[MayaJoint.name().asChar()][3][3]; + // doubleMat[0][0] = joinCheckMap[MayaJoint.name().asChar()][0][0]; + // doubleMat[0][1] = joinCheckMap[MayaJoint.name().asChar()][0][1]; + // doubleMat[0][2] = joinCheckMap[MayaJoint.name().asChar()][0][2]; + // doubleMat[0][3] = joinCheckMap[MayaJoint.name().asChar()][0][3]; + // doubleMat[1][0] = joinCheckMap[MayaJoint.name().asChar()][1][0]; + // doubleMat[1][1] = joinCheckMap[MayaJoint.name().asChar()][1][1]; + // doubleMat[1][2] = joinCheckMap[MayaJoint.name().asChar()][1][2]; + // doubleMat[1][3] = joinCheckMap[MayaJoint.name().asChar()][1][3]; + // doubleMat[2][0] = joinCheckMap[MayaJoint.name().asChar()][2][0]; + // doubleMat[2][1] = joinCheckMap[MayaJoint.name().asChar()][2][1]; + // doubleMat[2][2] = joinCheckMap[MayaJoint.name().asChar()][2][2]; + // doubleMat[2][3] = joinCheckMap[MayaJoint.name().asChar()][2][3]; + // doubleMat[3][0] = joinCheckMap[MayaJoint.name().asChar()][3][0]; + // doubleMat[3][1] = joinCheckMap[MayaJoint.name().asChar()][3][1]; + // doubleMat[3][2] = joinCheckMap[MayaJoint.name().asChar()][3][2]; + // doubleMat[3][3] = joinCheckMap[MayaJoint.name().asChar()][3][3]; - MMatrix tmp(doubleMat); - if (!tmp.isEquivalent(transformationMatrix)) { - MGlobal::displayInfo(MString() + MayaJoint.name() + " is exported"); - exportJoint[MayaJoint.name().asChar()] = true; - animatedJoints.push_back(MayaJoint.object()); - } - } + // MMatrix tmp(doubleMat); + // if (!tmp.isEquivalent(transformationMatrix)) { + // MGlobal::displayInfo(MString() + MayaJoint.name() + " is exported"); + // exportJoint[MayaJoint.name().asChar()] = true; + // animatedJoints.push_back(MayaJoint.object()); + // } + // } - /*for (int i = 0; i < 9; i++) - { - MStatus tmp; - MPlug plug = depNode.findPlug(attr[i].c_str(), &tmp); + /*for (int i = 0; i < 9; i++) + { + MStatus tmp; + MPlug plug = depNode.findPlug(attr[i].c_str(), &tmp); - MPlugArray connections; - plug.connectedTo(connections, true, false, 0); - for (int j = 0; j != connections.length(); j++) { - MObject connected = connections[j].node(); + MPlugArray connections; + plug.connectedTo(connections, true, false, 0); + for (int j = 0; j != connections.length(); j++) { + MObject connected = connections[j].node(); - if (connected.hasFn(MFn::kAnimCurve)) { + if (connected.hasFn(MFn::kAnimCurve)) { - MFnAnimCurve jointAnim(connected); + MFnAnimCurve jointAnim(connected); //MGlobal::displayInfo(MString() + "curve : " + jointAnim.name()); //MGlobal::displayInfo(MString() + "curve keys : " + jointAnim.numKeys()); @@ -161,89 +161,133 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e //MGlobal::displayInfo(MString() + "startFrame : " + startFrame); //MGlobal::displayInfo(MString() + "endFrame : " + endFrame); - unsigned int startKeyFrameIndex = jointAnim.findClosest(MTime(startFrame, MTime::kNTSCField), &tmp); + unsigned int startKeyFrameIndex = jointAnim.findClosest(MTime(startFrame, MTime::kNTSCField), &tmp); - if (tmp == MStatus::kFailure) - MGlobal::displayInfo(MString() + "Fail :c"); + if (tmp == MStatus::kFailure) + MGlobal::displayInfo(MString() + "Fail :c"); - if (startFrame * oneDivSixty <= jointAnim.time(startKeyFrameIndex).value() && jointAnim.time(startKeyFrameIndex).value() <= endFrame * oneDivSixty) { + if (startFrame * oneDivSixty <= jointAnim.time(startKeyFrameIndex).value() && jointAnim.time(startKeyFrameIndex).value() <= endFrame * oneDivSixty) { //MGlobal::displayInfo(MString() + "Start key time : " + jointAnim.time(startKeyFrameIndex).value()); - if (startFrame <= jointAnim.time(startKeyFrameIndex).value() && jointAnim.time(startKeyFrameIndex).value() <= endFrame ) { - animatedJoints.push_back(jointIt.item()); - i = 9; - break; - } + if (startFrame <= jointAnim.time(startKeyFrameIndex).value() && jointAnim.time(startKeyFrameIndex).value() <= endFrame ) { + animatedJoints.push_back(jointIt.item()); + i = 9; + break; + } - unsigned int endKeyFrameIndex = jointAnim.findClosest(MTime(endFrame, MTime::kNTSCField)); - MGlobal::displayInfo(MString() + startKeyFrameIndex + " " + endKeyFrameIndex); + unsigned int endKeyFrameIndex = jointAnim.findClosest(MTime(endFrame, MTime::kNTSCField)); + MGlobal::displayInfo(MString() + startKeyFrameIndex + " " + endKeyFrameIndex); MGlobal::displayInfo(MString() + "Fail!!!!!!!!!!!!!!!!!!!!!!!!!"); - if (startFrame * oneDivSixty <= jointAnim.time(endKeyFrameIndex).value() && jointAnim.time(endKeyFrameIndex).value() <= endFrame * oneDivSixty || endKeyFrameIndex - startKeyFrameIndex > 0) { + if (startFrame * oneDivSixty <= jointAnim.time(endKeyFrameIndex).value() && jointAnim.time(endKeyFrameIndex).value() <= endFrame * oneDivSixty || endKeyFrameIndex - startKeyFrameIndex > 0) { //MGlobal::displayInfo(MString() + "End key index : " + endKeyFrameIndex); //MGlobal::displayInfo(MString() + "end key time : " + jointAnim.time(endKeyFrameIndex).value()); - /*MGlobal::displayInfo(MString() + "start keyfram index: " + startKeyFrameIndex + ". End keyfram index: " + endKeyFrameIndex + ".");*/ + /*MGlobal::displayInfo(MString() + "start keyfram index: " + startKeyFrameIndex + ". End keyfram index: " + endKeyFrameIndex + ".");*/ - // if (startFrame <= jointAnim.time(endKeyFrameIndex).value() && jointAnim.time(endKeyFrameIndex).value() <= endFrame || endKeyFrameIndex - startKeyFrameIndex > 0) { - // animatedJoints.push_back(jointIt.item()); - // i = 9; - // break; - // } + /*if (startFrame <= jointAnim.time(endKeyFrameIndex).value() && jointAnim.time(endKeyFrameIndex).value() <= endFrame || endKeyFrameIndex - startKeyFrameIndex > 0) { + animatedJoints.push_back(jointIt.item()); + i = 9; + break; + } - // MFnTransform MayaJoint(jointIt.item()); + MFnTransform MayaJoint(jointIt.item()); - // MPlug BindPose = MayaJoint.findPlug("bindPose"); - // MDataHandle DataHandle; - // BindPose.getValue(DataHandle); - // MFnMatrixData MartixFn(DataHandle.data()); - // MMatrix BindPoseMatrix = MartixFn.matrix(); + MPlug BindPose = MayaJoint.findPlug("bindPose"); + MDataHandle DataHandle; + BindPose.getValue(DataHandle); + MFnMatrixData MartixFn(DataHandle.data()); + MMatrix BindPoseMatrix = MartixFn.matrix(); - // if (!BindPoseMatrix.isEquivalent(MayaJoint.transformationMatrix())) - // { - // MGlobal::displayError(MString() + animationName.c_str() + " is using " + MayaJoint.name() + " that is not in bind pose nor is it key framed in the animation, the exported animation will NOT correspond to the animation in Maya"); - // } - // } - // } - // } + if (!BindPoseMatrix.isEquivalent(MayaJoint.transformationMatrix())) + { + MGlobal::displayError(MString() + animationName.c_str() + " is using " + MayaJoint.name() + " that is not in bind pose nor is it key framed in the animation, the exported animation will NOT correspond to the animation in Maya"); + } + } + } + } - //} // end of int i loop - jointIt.next(); - } - jointIt.reset(); - } + } // end of int i loop*/ + /* jointIt.next(); + } + jointIt.reset(); + }*/ - int currentFrame = startFrame; - while (currentFrame <= endFrame) { // ANDREAS - Animation::Keyframe thisKeyFrame; - thisKeyFrame.Index = currentFrame - startFrame; - thisKeyFrame.Time = thisKeyFrame.Index * oneDivSixty; + int currentFrame = startFrame; + while (currentFrame <= endFrame) { // ANDREAS + Animation::Keyframe thisKeyFrame; + thisKeyFrame.Index = currentFrame - startFrame; + thisKeyFrame.Time = thisKeyFrame.Index * oneDivSixty; - MAnimControl::setCurrentTime(MTime(currentFrame, MTime::kNTSCField)); - MTime time = MAnimControl::currentTime(); + MAnimControl::setCurrentTime(MTime(currentFrame, MTime::kNTSCField)); + MTime time = MAnimControl::currentTime(); - for (auto aJoint : animatedJoints){ - MFnTransform thisJoint(aJoint); - Animation::Keyframe::JointProperty joint; + MItDag jointIt(MItDag::TraversalType::kDepthFirst, MFn::kJoint); + unsigned int jointID = 0; + while (!jointIt.isDone()) { + MFnTransform thisJoint(jointIt.currentItem()); + MMatrix transformationMatrix = thisJoint.transformationMatrix(); + + double doubleMat[4][4]; - auto it = std::find(m_Hierarchy.begin(), m_Hierarchy.end(), thisJoint.object()); - if (it != m_Hierarchy.end()) { - joint.ID = it - m_Hierarchy.begin(); - } - else { - MGlobal::displayError(MString() + "Could not find joint ID for: " + thisJoint.name()); - } - - MTransformationMatrix Matrix = thisJoint.transformation(); + if (currentFrame != startFrame){ + Animation::Keyframe::JointProperty joint; + + doubleMat[0][0] = joinCheckMap[thisJoint.name().asChar()][0][0]; + doubleMat[0][1] = joinCheckMap[thisJoint.name().asChar()][0][1]; + doubleMat[0][2] = joinCheckMap[thisJoint.name().asChar()][0][2]; + doubleMat[0][3] = joinCheckMap[thisJoint.name().asChar()][0][3]; + doubleMat[1][0] = joinCheckMap[thisJoint.name().asChar()][1][0]; + doubleMat[1][1] = joinCheckMap[thisJoint.name().asChar()][1][1]; + doubleMat[1][2] = joinCheckMap[thisJoint.name().asChar()][1][2]; + doubleMat[1][3] = joinCheckMap[thisJoint.name().asChar()][1][3]; + doubleMat[2][0] = joinCheckMap[thisJoint.name().asChar()][2][0]; + doubleMat[2][1] = joinCheckMap[thisJoint.name().asChar()][2][1]; + doubleMat[2][2] = joinCheckMap[thisJoint.name().asChar()][2][2]; + doubleMat[2][3] = joinCheckMap[thisJoint.name().asChar()][2][3]; + doubleMat[3][0] = joinCheckMap[thisJoint.name().asChar()][3][0]; + doubleMat[3][1] = joinCheckMap[thisJoint.name().asChar()][3][1]; + doubleMat[3][2] = joinCheckMap[thisJoint.name().asChar()][3][2]; + doubleMat[3][3] = joinCheckMap[thisJoint.name().asChar()][3][3]; + + MMatrix LastJointMatrix(doubleMat); + //Is same as last KeyFrame + if (LastJointMatrix.isEquivalent(transformationMatrix)) { + jointID++; + jointIt.next(); + continue; + } + } + + transformationMatrix.get(doubleMat); + + joinCheckMap[thisJoint.name().asChar()][0][0] = doubleMat[0][0]; + joinCheckMap[thisJoint.name().asChar()][0][1] = doubleMat[0][1]; + joinCheckMap[thisJoint.name().asChar()][0][2] = doubleMat[0][2]; + joinCheckMap[thisJoint.name().asChar()][0][3] = doubleMat[0][3]; + joinCheckMap[thisJoint.name().asChar()][1][0] = doubleMat[1][0]; + joinCheckMap[thisJoint.name().asChar()][1][1] = doubleMat[1][1]; + joinCheckMap[thisJoint.name().asChar()][1][2] = doubleMat[1][2]; + joinCheckMap[thisJoint.name().asChar()][1][3] = doubleMat[1][3]; + joinCheckMap[thisJoint.name().asChar()][2][0] = doubleMat[2][0]; + joinCheckMap[thisJoint.name().asChar()][2][1] = doubleMat[2][1]; + joinCheckMap[thisJoint.name().asChar()][2][2] = doubleMat[2][2]; + joinCheckMap[thisJoint.name().asChar()][2][3] = doubleMat[2][3]; + joinCheckMap[thisJoint.name().asChar()][3][0] = doubleMat[3][0]; + joinCheckMap[thisJoint.name().asChar()][3][1] = doubleMat[3][1]; + joinCheckMap[thisJoint.name().asChar()][3][2] = doubleMat[3][2]; + joinCheckMap[thisJoint.name().asChar()][3][3] = doubleMat[3][3]; + + MTransformationMatrix Matrix = thisJoint.transformation(); MPlug BindPose = thisJoint.findPlug("bindPose"); MDataHandle DataHandle; BindPose.getValue(DataHandle); MFnMatrixData MartixFn(DataHandle.data()); MMatrix BindPoseMatrix = MartixFn.matrix(); Matrix = Matrix.asMatrix(); - + MObject jointOrientObj = thisJoint.attribute("jointOrient"); MFnNumericAttribute jointOrient(jointOrientObj); double jointOrientDouble[3]; @@ -257,79 +301,83 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e MEulerRotation joEuler(jointOrientDouble[0], jointOrientDouble[1], jointOrientDouble[2]); MQuaternion jo = joEuler.asQuaternion(); - double tmp[4]; + double tmp[4]; Matrix.getRotationQuaternion(tmp[0], tmp[1], tmp[2], tmp[3]); MQuaternion rotation(tmp); rotation = rotation * jo; rotation.get(tmp); - joint.Rotation[0] = tmp[0]; - joint.Rotation[1] = tmp[1]; - joint.Rotation[2] = tmp[2]; - joint.Rotation[3] = tmp[3]; - Matrix.getTranslation(MSpace::kTransform).get(tmp); - joint.Position[0] = tmp[0]; - joint.Position[1] = tmp[1]; - joint.Position[2] = tmp[2]; - Matrix.getScale(tmp, MSpace::kTransform); - joint.Scale[0] = tmp[0]; - joint.Scale[1] = tmp[1]; - joint.Scale[2] = tmp[2]; + Animation::Keyframe::JointProperty joint; + joint.ID = jointID; - thisKeyFrame.JointProperties.push_back(joint); - } - returnData.Keyframes.push_back(thisKeyFrame); - currentFrame++; - } + joint.Rotation[0] = tmp[0]; + joint.Rotation[1] = tmp[1]; + joint.Rotation[2] = tmp[2]; + joint.Rotation[3] = tmp[3]; + Matrix.getTranslation(MSpace::kTransform).get(tmp); + joint.Position[0] = tmp[0]; + joint.Position[1] = tmp[1]; + joint.Position[2] = tmp[2]; + Matrix.getScale(tmp, MSpace::kTransform); + joint.Scale[0] = tmp[0]; + joint.Scale[1] = tmp[1]; + joint.Scale[2] = tmp[2]; + + thisKeyFrame.JointProperties.push_back(joint); + + jointID++; + jointIt.next(); + } + thisKeyFrame.NumberOfJoints = thisKeyFrame.JointProperties.size(); + returnData.Keyframes.push_back(thisKeyFrame); + currentFrame++; + } returnData.NumKeyFrames = returnData.Keyframes.size(); - returnData.NumberOfJoints = animatedJoints.size(); - return returnData; + return returnData; } std::vector Skeleton::GetBindPoses() { MStatus status; - std::vector m_AllSkeletons; - std::vector m_Hierarchy; + std::vector m_AllSkeletons; + std::vector m_Hierarchy; - MItDag jointIt(MItDag::TraversalType::kDepthFirst, MFn::kJoint); - BindPoseSkeletonNode SkeletonStorage; - while (!jointIt.isDone()) { - MFnTransform MayaJoint(jointIt.currentItem()); - BindPoseSkeletonNode::BindPoseJoint NewJoint; + MItDag jointIt(MItDag::TraversalType::kDepthFirst, MFn::kJoint); + BindPoseSkeletonNode SkeletonStorage; + while (!jointIt.isDone()) { + MFnTransform MayaJoint(jointIt.currentItem()); + BindPoseSkeletonNode::BindPoseJoint NewJoint; - if (MFnDependencyNode(MayaJoint.parent(0)).object().apiType() != MFn::kJoint) { - if (SkeletonStorage.Joints.size() != 0) { - m_AllSkeletons.push_back(SkeletonStorage); + if (MFnDependencyNode(MayaJoint.parent(0)).object().apiType() != MFn::kJoint) { + if (SkeletonStorage.Joints.size() != 0) { + m_AllSkeletons.push_back(SkeletonStorage); - SkeletonStorage.Joints.clear(); - SkeletonStorage.Name.clear(); - } - SkeletonStorage.Name = std::string(MayaJoint.name().asChar()); - NewJoint.ParentID = -1; // This joint is root - } - else { - auto it = std::find(m_Hierarchy.begin(), m_Hierarchy.end(), MayaJoint.parent(0)); - if (it != m_Hierarchy.end()) { - NewJoint.ParentID = it - m_Hierarchy.begin(); - } - else { - MGlobal::displayError(MString() + "Could not find joint parent for: " + MayaJoint.name()); - } - } - m_Hierarchy.push_back(MayaJoint.object()); + SkeletonStorage.Joints.clear(); + SkeletonStorage.Name.clear(); + } + SkeletonStorage.Name = std::string(MayaJoint.name().asChar()); + NewJoint.ParentID = -1; // This joint is root + } else { + auto it = std::find(m_Hierarchy.begin(), m_Hierarchy.end(), MayaJoint.parent(0)); + if (it != m_Hierarchy.end()) { + NewJoint.ParentID = it - m_Hierarchy.begin(); + } else { + MGlobal::displayError(MString() + "Could not find joint parent for: " + MayaJoint.name()); + } + } + m_Hierarchy.push_back(MayaJoint.object()); - MPlug BindPose = MayaJoint.findPlug("bindPose", &status); - if (status != MS::kSuccess) { + MPlug BindPose = MayaJoint.findPlug("bindPose", &status); + if (status != MS::kSuccess) { MGlobal::displayError(MString() + "Could not find bindPose plug: " + status.errorString()); } - MDataHandle DataHandle; - BindPose.getValue(DataHandle); - MFnMatrixData MartixFn(DataHandle.data()); - MMatrix Matrix = MartixFn.matrix(); + MDataHandle DataHandle; + BindPose.getValue(DataHandle); + MFnMatrixData MartixFn(DataHandle.data()); + MMatrix Matrix = MartixFn.matrix(); MVector tmp = MayaJoint.transformation().getTranslation(MSpace::kObject); @@ -342,7 +390,7 @@ std::vector Skeleton::GetBindPoses() MTransformationMatrix::RotationOrder order = MTransformationMatrix::RotationOrder::kXYZ; MayaJoint.transformation().getRotation(test, order); - + //----- test @@ -389,33 +437,33 @@ std::vector Skeleton::GetBindPoses() Matrix = Matrix.inverse(); - for (int i = 0; i < 4; i++) { - for (int j = 0; j < 4; j++) { - NewJoint.OffsetMatrix[i][j] = Matrix.matrix[i][j]; - } - } + for (int i = 0; i < 4; i++) { + for (int j = 0; j < 4; j++) { + NewJoint.OffsetMatrix[i][j] = Matrix.matrix[i][j]; + } + } - NewJoint.Name = MayaJoint.name().asChar(); + NewJoint.Name = MayaJoint.name().asChar(); NewJoint.NameLength = MayaJoint.name().length() + 1; NewJoint.ID = SkeletonStorage.Joints.size(); - //double tmp[3]; - //((MTransformationMatrix)Matrix).eulerRotation().asVector().get(tmp); - //NewJoint.Rotation[0] = tmp[0]; - //NewJoint.Rotation[1] = tmp[1]; - //NewJoint.Rotation[2] = tmp[2]; - //((MTransformationMatrix)Matrix).getScale(tmp, MSpace::Space::kTransform); - //NewJoint.Scale[0] = tmp[0]; - //NewJoint.Scale[1] = tmp[1]; - //NewJoint.Scale[2] = tmp[2]; - //((MTransformationMatrix)Matrix).getTranslation(MSpace::Space::kTransform).get(tmp); - //NewJoint.Translation[0] = tmp[0]; - //NewJoint.Translation[1] = tmp[1]; - //NewJoint.Translation[2] = tmp[2]; - SkeletonStorage.Joints.push_back(NewJoint); + //double tmp[3]; + //((MTransformationMatrix)Matrix).eulerRotation().asVector().get(tmp); + //NewJoint.Rotation[0] = tmp[0]; + //NewJoint.Rotation[1] = tmp[1]; + //NewJoint.Rotation[2] = tmp[2]; + //((MTransformationMatrix)Matrix).getScale(tmp, MSpace::Space::kTransform); + //NewJoint.Scale[0] = tmp[0]; + //NewJoint.Scale[1] = tmp[1]; + //NewJoint.Scale[2] = tmp[2]; + //((MTransformationMatrix)Matrix).getTranslation(MSpace::Space::kTransform).get(tmp); + //NewJoint.Translation[0] = tmp[0]; + //NewJoint.Translation[1] = tmp[1]; + //NewJoint.Translation[2] = tmp[2]; + SkeletonStorage.Joints.push_back(NewJoint); SkeletonStorage.numBones++; - jointIt.next(); - } - m_AllSkeletons.push_back(SkeletonStorage); + jointIt.next(); + } + m_AllSkeletons.push_back(SkeletonStorage); - return m_AllSkeletons; + return m_AllSkeletons; } \ No newline at end of file diff --git a/tools/MayaExporter/MayaExporter/Skeleton.h b/tools/MayaExporter/MayaExporter/Skeleton.h index 9033441d..47ae6f4c 100644 --- a/tools/MayaExporter/MayaExporter/Skeleton.h +++ b/tools/MayaExporter/MayaExporter/Skeleton.h @@ -22,6 +22,7 @@ public: int Index = 0; float Time = 0; + int NumberOfJoints; std::vector JointProperties; }; @@ -29,7 +30,6 @@ public: int nameLength = 0; float Duration = 0; int NumKeyFrames = 0; - int NumberOfJoints = 0; std::vector Keyframes; virtual void WriteBinary(std::ostream& out) @@ -38,11 +38,11 @@ public: out.write(Name.c_str(), Name.size() + 1); out.write((char*)&Duration, sizeof(float)); out.write((char*)&NumKeyFrames, sizeof(int)); - out.write((char*)&NumberOfJoints, sizeof(int)); //Här under loopas alla key frames igenom for (auto aKeyframe : Keyframes) { out.write((char*)&aKeyframe.Index, sizeof(int)); out.write((char*)&aKeyframe.Time, sizeof(float)); + out.write((char*)&aKeyframe.NumberOfJoints, sizeof(int)); for (auto aJoint : aKeyframe.JointProperties) { out.write((char*)&aJoint.ID, sizeof(int)); out.write((char*)aJoint.Position, sizeof(float) * 3); @@ -56,11 +56,11 @@ public: { out << "Animation Name: " << Name << endl; out << "Duration: " << Duration << endl; - out << "Number of KeyFrames: " << NumKeyFrames << endl; - out << "Number of Joints: " << NumberOfJoints << endl; + out << "Number of KeyFrames: " << NumKeyFrames << endl; for (auto aKeyframe : Keyframes) { out << "Frame: " << aKeyframe.Index << endl; out << "Time: " << aKeyframe.Time << endl; + out << "Number of Joints: " << aKeyframe.NumberOfJoints << endl; for (auto aJoint : aKeyframe.JointProperties) { out << "Joint ID: " << aJoint.ID << endl; out << aJoint.Position[0] << " " << aJoint.Position[1] << " " << aJoint.Position[2] << endl;