diff --git a/.gitignore b/.gitignore index 0df2db42..23056510 100755 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,6 @@ tools/MayaExporter/x64/Debug/ tools/MayaExporter/MayaExporter/Debug/ tools/MayaExporter/MayaExporter/GeneratedFiles/ + +tools/MayaExporter/MayaExporter/x64/* +tools/MayaExporter/x64/* diff --git a/assets b/assets index 091ad5c0..1d09801c 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 091ad5c01bf7b6ef5501fc907fc610576a4a45ea +Subproject commit 1d09801cf45452e082ad08bac5e29e3102f31724 diff --git a/deps b/deps index bf83f099..ed45883a 160000 --- a/deps +++ b/deps @@ -1 +1 @@ -Subproject commit bf83f099ba16f0a87f9bebe8cfc5fd4e59fee805 +Subproject commit ed45883a444c6de548b6211a83a079ff2ecfce15 diff --git a/include/Engine/Collision/Collision.h b/include/Engine/Collision/Collision.h index cd10dbb2..9e1a81db 100644 --- a/include/Engine/Collision/Collision.h +++ b/include/Engine/Collision/Collision.h @@ -20,6 +20,9 @@ class World; struct ComponentWrapper; +template +class Octree; + namespace Collision { //Return true if the ray hits the box. @@ -28,40 +31,77 @@ bool RayVsAABB(const Ray& ray, const AABB& box); //Return true if the ray hits the box, also outputs distance from ray origin to intersection point in [outDistance]. bool RayVsAABB(const Ray& ray, const AABB& box, float& outDistance); +//Return true if the ray hits the triangle. +bool RayVsTriangle(const Ray& ray, + const glm::vec3& v0, + const glm::vec3& v1, + const glm::vec3& v2, + bool trueOnNegativeDistance = false); +//Return true if the ray hits the triangle, and the distance is less than outDistance. +bool RayVsTriangle(const Ray& ray, + const glm::vec3& v0, + const glm::vec3& v1, + const glm::vec3& v2, + float& outDistance, + float& outUCoord, + float& outVCoord, + bool trueOnNegativeDistance = false); //Return true if the ray hits any of the triangles in the model. Stops checking when a hit is detected. -bool RayVsModel(const Ray& ray, - const std::vector& modelVertices, - const std::vector& modelIndices); +bool RayVsModel(const Ray& ray, + const RawModel::Vertex* modelVertices, + const std::vector& modelIndices, + const glm::mat4& modelMatrix); //Return true if the ray hits any of the triangles in the model. //Also returns the position of the intersection point. Will loop through all the whole model indices. bool RayVsModel(const Ray& ray, - const std::vector& modelVertices, + const RawModel::Vertex* modelVertices, const std::vector& modelIndices, + const glm::mat4& modelMatrix, glm::vec3& outHitPosition); //Return true if the ray hits any of the triangles in the model. //Also returns the distance from the ray origin to the closest //intersection point, and the barycentric u,v-coordinates. Will loop through all the whole model indices. bool RayVsModel(const Ray& ray, - const std::vector& modelVertices, + const RawModel::Vertex* modelVertices, const std::vector& modelIndices, + const glm::mat4& modelMatrix, float& outDistance, float& outUCoord, float& outVCoord); bool AABBvsTriangles(const AABB& box, - const std::vector& modelVertices, + const RawModel::Vertex* modelVertices, const std::vector& modelIndices, const glm::mat4& modelMatrix, + glm::vec3& boxVelocity, + float verticalStepHeight, + bool& isOnGround, glm::vec3& outResolutionVector); +//Detects collision, but does not resolve. +bool AABBvsTriangles(const AABB& box, + const RawModel::Vertex* modelVertices, + const std::vector& modelIndices, + const glm::mat4& modelMatrix); + //Return true if the boxes are intersecting. 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); -// Calculates an absolute AABB from an entity AABB component -boost::optional EntityAbsoluteAABB(EntityWrapper& entity); +// Calculates an absolute AABB from an entity AABB component or Model component. +// if takeModelBox is true, the AABB component will be ignored and box is calculated from Model. +// if takeModelBox is false, the AABB component will be prefered, if it exists. +boost::optional EntityAbsoluteAABB(EntityWrapper& entity, bool takeModelBox = false); +boost::optional AbsoluteAABBExplosionEffect(EntityWrapper& entity); +//Returns the first entity hit by the input ray. entitiesPotentiallyHitSorted needs to be sorted +//by their distance to the ray, e.g. result from Octree::ObjectsPossiblyHitByRay. +//Returns boost::none if none was hit. outDistance will be the distance to the intersection point if the ray intersects. +boost::optional EntityFirstHitByRay(const Ray& ray, std::vector entitiesPotentiallyHitSorted, float& outDistance, glm::vec3& outIntersectPos); +//Returns the first entity hit by the input ray that exists in the octree. +//outDistance will be the distance to the intersection point if the ray intersects. +boost::optional EntityFirstHitByRay(const Ray& ray, Octree* octree, float& outDistance, glm::vec3& outIntersectPos); } diff --git a/include/Engine/Collision/CollisionSystem.h b/include/Engine/Collision/CollisionSystem.h index f3a7e4fe..19adea35 100644 --- a/include/Engine/Collision/CollisionSystem.h +++ b/include/Engine/Collision/CollisionSystem.h @@ -13,17 +13,18 @@ class CollisionSystem : public PureSystem { public: - CollisionSystem(World* world, EventBroker* eventBroker, Octree* octree) - : System(world, eventBroker) - , PureSystem("Collidable") + CollisionSystem(SystemParams params, Octree* octree) + : System(params) + , PureSystem("Physics") , m_Octree(octree) { } - virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override; + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cPhysics, double dt) override; private: Octree* m_Octree; std::vector m_OctreeResult; + std::unordered_map m_PrevPositions; }; #endif \ No newline at end of file diff --git a/include/Engine/Collision/CollidableOctreeSystem.h b/include/Engine/Collision/FillFrustumOctreeSystem.h similarity index 51% rename from include/Engine/Collision/CollidableOctreeSystem.h rename to include/Engine/Collision/FillFrustumOctreeSystem.h index 0aa01d2e..430b4037 100644 --- a/include/Engine/Collision/CollidableOctreeSystem.h +++ b/include/Engine/Collision/FillFrustumOctreeSystem.h @@ -1,17 +1,17 @@ -#ifndef CollidableOctreeSystem_h__ -#define CollidableOctreeSystem_h__ +#ifndef FillFrustumOctreeSystem_h__ +#define FillFrustumOctreeSystem_h__ #include "../Core/System.h" #include "../Core/Octree.h" #include "Collision.h" #include "EntityAABB.h" -class CollidableOctreeSystem : public ImpureSystem, public PureSystem +class FillFrustumOctreeSystem : public ImpureSystem, public PureSystem { public: - CollidableOctreeSystem(World* world, EventBroker* eventBroker, Octree* octree, const std::string& componentType) - : System(world, eventBroker) - , PureSystem(componentType) + FillFrustumOctreeSystem(SystemParams params, Octree* octree) + : System(params) + , PureSystem("Model") , m_Octree(octree) { } diff --git a/include/Engine/Collision/FillOctreeSystem.h b/include/Engine/Collision/FillOctreeSystem.h new file mode 100644 index 00000000..9c75878b --- /dev/null +++ b/include/Engine/Collision/FillOctreeSystem.h @@ -0,0 +1,25 @@ +#ifndef FillOctreeSystem_h__ +#define FillOctreeSystem_h__ + +#include "../Core/System.h" +#include "../Core/Octree.h" +#include "Collision.h" +#include "EntityAABB.h" + +class FillOctreeSystem : public ImpureSystem, public PureSystem +{ +public: + FillOctreeSystem(SystemParams params, Octree* octree, const std::string& fillComponentType) + : System(params) + , PureSystem(fillComponentType) + , m_Octree(octree) + { } + + virtual void Update(double dt) override; + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override; + +private: + Octree* m_Octree; +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Collision/TriggerSystem.h b/include/Engine/Collision/TriggerSystem.h index fa322ddd..d71fad08 100644 --- a/include/Engine/Collision/TriggerSystem.h +++ b/include/Engine/Collision/TriggerSystem.h @@ -15,8 +15,8 @@ class AABB; class TriggerSystem : public PureSystem { public: - TriggerSystem(World* world, EventBroker* eventBroker, Octree* octree) - : System(world, eventBroker) + TriggerSystem(SystemParams params, Octree* octree) + : System(params) , PureSystem("Trigger") , m_Octree(octree) { diff --git a/include/Engine/Core/ComponentInfo.h b/include/Engine/Core/ComponentInfo.h index 49ed2a3f..137a44d8 100644 --- a/include/Engine/Core/ComponentInfo.h +++ b/include/Engine/Core/ComponentInfo.h @@ -2,6 +2,7 @@ #define ComponentInfo_h__ #include "../Common.h" +#include struct ComponentInfo { @@ -13,6 +14,7 @@ struct ComponentInfo unsigned int Allocation = 0; std::map FieldAnnotations; std::map> FieldEnumDefinitions; + bool NetworkReplicated = true; }; struct Field_t @@ -26,8 +28,9 @@ struct ComponentInfo std::string Name; std::unordered_map Fields; std::vector FieldsInOrder; + std::vector StringFields; unsigned int Stride = 0; - std::shared_ptr Defaults = nullptr; + boost::shared_array Defaults = nullptr; std::shared_ptr Meta = nullptr; }; diff --git a/include/Engine/Core/ComponentPool.h b/include/Engine/Core/ComponentPool.h index 957b8756..aedfd06b 100644 --- a/include/Engine/Core/ComponentPool.h +++ b/include/Engine/Core/ComponentPool.h @@ -1,6 +1,7 @@ #ifndef ComponentPool_h__ #define ComponentPool_h__ +#include #include "MemoryPool.h" #include "ComponentInfo.h" #include "ComponentWrapper.h" @@ -45,7 +46,8 @@ public: : m_ComponentInfo(ci) , m_Pool(ci.Meta->Allocation, sizeof(EntityID) + ci.Stride) { } - ComponentPool(const ComponentPool& other) = delete; + ~ComponentPool(); + ComponentPool(const ComponentPool& other); ComponentPool(const ComponentPool&& other) = delete; const ::ComponentInfo& ComponentInfo() const { return m_ComponentInfo; } diff --git a/include/Engine/Core/ComponentWrapper.h b/include/Engine/Core/ComponentWrapper.h index 1dc131d2..7897e874 100644 --- a/include/Engine/Core/ComponentWrapper.h +++ b/include/Engine/Core/ComponentWrapper.h @@ -1,11 +1,30 @@ #ifndef ComponentWrapper_h__ #define ComponentWrapper_h__ +#include +#include #include "../Common.h" #include "Entity.h" #include "ComponentInfo.h" #include "Util/Any.h" +template +struct ComponentField { }; + +template +struct ComponentField::value>::type> +{ + static T& Get(const ComponentInfo::Field_t& info, char* data) { return *reinterpret_cast(data); } + static void Set(const ComponentInfo::Field_t& info, char* data, const T& value) { Get(data) = value; } +}; + +template <> +struct ComponentField +{ + static std::string& Get(const ComponentInfo::Field_t& info, char* data) { return **reinterpret_cast(data); } + static void Set(const ComponentInfo::Field_t& info, char* data, const std::string& value) { Get(info, data) = value; } +}; + struct ComponentWrapper { ComponentWrapper(const ComponentInfo& componentInfo, char* data) @@ -43,6 +62,35 @@ struct ComponentWrapper // Specialization for string literals template void SetField(std::string name, const char(&value)[N]) { Field(name) = std::string(value); } + + void Copy(ComponentWrapper& destination) + { + // Copy trivial data + memcpy(destination.Data, Data, Info.Stride); + // Duplicate strings + SolidifyStrings(destination); + } + + // When component data has been copied, strings need to be reconstructed or they'll refer to the same data! + static void SolidifyStrings(ComponentWrapper& component) + { + for (auto& name : component.Info.StringFields) { + std::size_t offset = component.Info.Fields.at(name).Offset; + std::string value = *reinterpret_cast(component.Data + offset); + new (component.Data + offset) std::string(value); + } + } + + // This needs to be called to properly free component data, because strings. + static void Destroy(ComponentInfo info, char* data) + { + // Call std::string destructors + for (auto& name : info.StringFields) { + std::size_t offset = info.Fields.at(name).Offset; + auto field = reinterpret_cast(data + offset); + field->~basic_string(); + } + } struct SubscriptProxy { @@ -76,6 +124,18 @@ struct ComponentWrapper SubscriptProxy operator[](std::string propertyName) { return SubscriptProxy(this, propertyName); } }; +// A component wrapper that "owns" its data through a shared pointer +struct SharedComponentWrapper : ComponentWrapper +{ + SharedComponentWrapper(const ComponentInfo& componentInfo, boost::shared_array data) + : ComponentWrapper(componentInfo, data.get()) + , m_DataReference(data) + { } + +private: + boost::shared_array m_DataReference; +}; + // TODO: Move this to Tests once entity importing is finished class ComponentWrapperFactory { @@ -84,26 +144,38 @@ public: ComponentWrapperFactory(std::string componentTypeName, unsigned int allocation = 0) { m_ComponentInfo.Name = componentTypeName; + m_ComponentInfo.Meta = std::make_shared(); m_ComponentInfo.Meta->Allocation = allocation; } template void AddProperty(std::string fieldName, T defaultValue) { - m_DefaultValues.push_back(defaultValue); - m_ComponentInfo.Fields[fieldName].Type = typeid(T).name(); - m_ComponentInfo.Fields[fieldName].Offset = m_ComponentInfo.Stride; - m_ComponentInfo.Fields[fieldName].Stride = sizeof(T); + auto& field = m_ComponentInfo.Fields[fieldName]; + field.Name = fieldName; + field.Type = typeid(T).name(); + field.Offset = m_ComponentInfo.Stride; + field.Stride = sizeof(T); + m_ComponentInfo.FieldsInOrder.push_back(field.Name); + if (field.Type == typeid(std::string).name()) { + field.Type = "string"; + m_ComponentInfo.StringFields.push_back(field.Name); + } m_ComponentInfo.Stride += sizeof(T); + m_DefaultValues.push_back(std::make_pair(field, defaultValue)); } - + ComponentInfo& Finalize() { - m_ComponentInfo.Defaults = std::shared_ptr(new char[m_ComponentInfo.Stride]); + m_ComponentInfo.Defaults = boost::shared_array(new char[m_ComponentInfo.Stride]); std::size_t offset = 0; - for (auto& val : m_DefaultValues) { - memcpy(m_ComponentInfo.Defaults.get() + offset, val.Data.get(), val.Size); - offset += val.Size; + for (auto& pair : m_DefaultValues) { + if (pair.first.Type == "string") { + new (m_ComponentInfo.Defaults.get() + offset) std::string(*reinterpret_cast(pair.second.Data.get())); + } else { + memcpy(m_ComponentInfo.Defaults.get() + offset, pair.second.Data.get(), pair.second.Size); + } + offset += pair.second.Size; } return m_ComponentInfo; @@ -113,7 +185,7 @@ public: private: ComponentInfo m_ComponentInfo; - std::vector m_DefaultValues; + std::vector> m_DefaultValues; }; #endif diff --git a/include/Engine/Core/EAmmoPickup.h b/include/Engine/Core/EAmmoPickup.h new file mode 100644 index 00000000..6d854d48 --- /dev/null +++ b/include/Engine/Core/EAmmoPickup.h @@ -0,0 +1,18 @@ +#ifndef EAmmoPickup_h__ +#define EAmmoPickup_h__ + +#include "EventBroker.h" +#include "../Core/EntityWrapper.h" + +namespace Events +{ + + struct AmmoPickup : Event + { + EntityWrapper Player; + int AmmoGain; + }; + +} + +#endif \ No newline at end of file diff --git a/include/Engine/Core/EPickupSpawned.h b/include/Engine/Core/EPickupSpawned.h new file mode 100644 index 00000000..9f85913a --- /dev/null +++ b/include/Engine/Core/EPickupSpawned.h @@ -0,0 +1,17 @@ +#ifndef EPickupSpawned_h__ +#define EPickupSpawned_h__ + +#include "Core/Event.h" +#include "Core/EntityWrapper.h" + +namespace Events +{ + +struct PickupSpawned : Event +{ + EntityWrapper Pickup; +}; + +} + +#endif \ No newline at end of file diff --git a/include/Engine/Core/EPlayerDamage.h b/include/Engine/Core/EPlayerDamage.h index a7e135ce..6f3f2c12 100644 --- a/include/Engine/Core/EPlayerDamage.h +++ b/include/Engine/Core/EPlayerDamage.h @@ -9,7 +9,8 @@ namespace Events struct PlayerDamage : Event { - EntityWrapper Player; + EntityWrapper Inflictor; + EntityWrapper Victim; double Damage; }; diff --git a/include/Engine/Core/EPlayerDeath.h b/include/Engine/Core/EPlayerDeath.h index 00ede5ed..363745a6 100644 --- a/include/Engine/Core/EPlayerDeath.h +++ b/include/Engine/Core/EPlayerDeath.h @@ -2,7 +2,7 @@ #define EPlayerDeath_h__ #include "EventBroker.h" -#include "../Core/Entity.h" +#include "../Core/EntityWrapper.h" namespace Events { @@ -10,8 +10,7 @@ namespace Events struct PlayerDeath : Event { //KilledBy,KilledByWhat is optional for now. It might be used later in the playerlog-system - EntityID KilledBy; - EntityID PlayerID; + EntityWrapper Player; std::string KilledByWhat; }; diff --git a/include/Engine/Core/EPlayerHealthPickup.h b/include/Engine/Core/EPlayerHealthPickup.h index f3158f92..7d44e544 100644 --- a/include/Engine/Core/EPlayerHealthPickup.h +++ b/include/Engine/Core/EPlayerHealthPickup.h @@ -2,16 +2,16 @@ #define EPlayerHealthPickup_h__ #include "EventBroker.h" -#include "../Core/Entity.h" +#include "../Core/EntityWrapper.h" namespace Events { -struct PlayerHealthPickup : Event -{ - double HealthAmount; - EntityID PlayerHealedID; -}; + struct PlayerHealthPickup : Event + { + EntityWrapper Player; + double HealthAmount; + }; } diff --git a/include/Engine/Core/EShoot.h b/include/Engine/Core/EShoot.h index 76821a24..28346abb 100644 --- a/include/Engine/Core/EShoot.h +++ b/include/Engine/Core/EShoot.h @@ -9,7 +9,8 @@ namespace Events struct Shoot : Event { - EntityWrapper Player; + EntityWrapper Inflictor; + double Damage; }; } diff --git a/include/Engine/Core/EntityFilePreprocessor.h b/include/Engine/Core/EntityFilePreprocessor.h index 3139169f..b46bd383 100644 --- a/include/Engine/Core/EntityFilePreprocessor.h +++ b/include/Engine/Core/EntityFilePreprocessor.h @@ -3,6 +3,8 @@ #include #include +#include +#include #include #include #include diff --git a/include/Engine/Core/EntityWrapper.h b/include/Engine/Core/EntityWrapper.h index bf34b9be..4643e28b 100644 --- a/include/Engine/Core/EntityWrapper.h +++ b/include/Engine/Core/EntityWrapper.h @@ -25,11 +25,13 @@ struct EntityWrapper const std::string Name(); bool HasComponent(const std::string& componentType); + void AttachComponent(const char* componentName); EntityWrapper Parent(); EntityWrapper FirstChildByName(const std::string& name); EntityWrapper FirstParentWithComponent(const std::string& componentType); + EntityWrapper Clone(EntityWrapper parent = EntityWrapper::Invalid); bool IsChildOf(EntityWrapper potentialParent); - bool Valid(); + bool Valid() const; ComponentWrapper operator[](const char* componentName); bool operator==(const EntityWrapper& e) const; @@ -38,6 +40,7 @@ struct EntityWrapper private: EntityWrapper firstChildByNameRecursive(const std::string& name, EntityID parent); + EntityWrapper cloneRecursive(EntityWrapper entity, EntityWrapper parent); }; namespace std diff --git a/include/Engine/Core/EventBroker.h b/include/Engine/Core/EventBroker.h index dc1babc0..20d3b60c 100644 --- a/include/Engine/Core/EventBroker.h +++ b/include/Engine/Core/EventBroker.h @@ -5,6 +5,7 @@ #include #include #include +#include #include "../Common.h" #include "Event.h" @@ -107,7 +108,7 @@ private: typedef std::unordered_map ContextRelays_t; ContextRelays_t m_ContextRelays; std::vector m_RelaysToSubscribe; - std::vector> m_RelaysToUnsubscribe; + std::unordered_map> m_RelaysToUnsubscribe; typedef std::list>> EventQueue_t; std::shared_ptr m_EventQueueRead; diff --git a/include/Engine/Core/Frustum.h b/include/Engine/Core/Frustum.h new file mode 100644 index 00000000..c2d83b23 --- /dev/null +++ b/include/Engine/Core/Frustum.h @@ -0,0 +1,77 @@ +#ifndef Frustum_h__ +#define Frustum_h__ + +#include "../GLM.h" +#include "AABB.h" +#include + +//A frustum defined by 6 planes. +struct Frustum +{ + //Contains points P in: dot(normal, P) + d = 0 + struct Plane + { + glm::vec3 Normal; + float Distance; + }; + + enum class Output + { + Inside, + Outside, + Intersects + }; + Plane Planes[6]; + + Frustum() = default; + Frustum(glm::mat4x4 viewProjMatrix) + { + //Order: Right, left, top, bottom, far, near. + int sign = 1; + for (int i = 0; i < 6; ++i) { + sign = -sign; + int index = i / 2; + Plane& plane = Planes[i]; + plane.Normal.x = viewProjMatrix[0].w + sign * viewProjMatrix[0][index]; + plane.Normal.y = viewProjMatrix[1].w + sign * viewProjMatrix[1][index]; + plane.Normal.z = viewProjMatrix[2].w + sign * viewProjMatrix[2][index]; + plane.Distance = viewProjMatrix[3].w + sign * viewProjMatrix[3][index]; + float divByNormalLength = 1.0f / glm::length(plane.Normal); + plane.Normal *= divByNormalLength; + plane.Distance *= divByNormalLength; + } + } + + Output VsAABB(const AABB& box) const + { + const glm::vec3& maxCorner = box.MaxCorner(); + const glm::vec3& minCorner = box.MinCorner(); + bool completelyInside = true; + for (const Plane& p : Planes) { + bool anyWasInside = false; + bool anyWasOutside = false; + //If points are on both sides of the plane, we can stop. + for (int i = 0; i < 8 && (!anyWasInside || !anyWasOutside); ++i) { + std::bitset<3> bits(i); + glm::vec3 corner; + corner.x = bits.test(0) ? maxCorner.x : minCorner.x; + corner.y = bits.test(1) ? maxCorner.y : minCorner.y; + corner.z = bits.test(2) ? maxCorner.z : minCorner.z; + if (glm::dot(p.Normal, corner) > -p.Distance) { + anyWasInside = true; + } else { + anyWasOutside = true; + } + } + if (!anyWasInside) { + return Output::Outside; + } + if (anyWasOutside) { + completelyInside = false; + } + } + return completelyInside ? Output::Inside : Output::Intersects; + } +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Core/MemoryPool.h b/include/Engine/Core/MemoryPool.h index 3a1cc069..053e75aa 100644 --- a/include/Engine/Core/MemoryPool.h +++ b/include/Engine/Core/MemoryPool.h @@ -66,9 +66,25 @@ public: , m_LowestAllocatedSlot(m_NumSlots) { } - //We may get problems with memory being released - //prematurely, etc. if we allow copies. - MemoryPool(const MemoryPool& other) = delete; + MemoryPool(const MemoryPool& other) + : m_StartAddress(new char[other.m_NumSlots*other.m_Stride]) + , m_SlotIsAllocated(other.m_SlotIsAllocated) + , m_ExtraMemory() + , m_NumSlots(other.m_NumSlots) + , m_LowestAllocatedSlot(other.m_LowestAllocatedSlot) + , m_NumAllocatedSlots(other.m_NumAllocatedSlots) + , m_Stride(other.m_Stride) + , m_CurrentAllocSlot(other.m_CurrentAllocSlot) + { + // Copy statically allocated pool + memcpy(m_StartAddress, other.m_StartAddress, m_NumSlots*m_Stride); + // Copy dynamically allocated memory + for (char* otherAddr : other.m_ExtraMemory) { + char* addr = (char*)malloc(m_Stride); + memcpy(addr, otherAddr, m_Stride); + m_ExtraMemory.push_back(addr); + } + } MemoryPool(const MemoryPool&& other) = delete; //Free all memory that has been allocated. @@ -78,8 +94,9 @@ public: delete[] m_StartAddress; m_StartAddress = nullptr; } - for (char* addr : m_ExtraMemory) - free(addr); + for (char* addr : m_ExtraMemory) { + free(addr); + } m_ExtraMemory.clear(); } @@ -102,7 +119,7 @@ public: m_ExtraMemory.push_back((char*)malloc(m_Stride)); //We should preferably not enter here to avoid performance issues. Set more numMaxElements in constructor instead. if (!DisableMemoryPool::Value) { - LOG_WARNING("Allocated slots exceed Pool size, extra memory allocated dynamically. Pool size: %u, dynamic size: %u.", m_NumSlots, m_ExtraMemory.size()); + LOG_DEBUG("Allocated slots exceed Pool size, extra memory allocated dynamically. Pool size: %u, dynamic size: %u.", m_NumSlots, m_ExtraMemory.size()); } return m_ExtraMemory.back(); } diff --git a/include/Engine/Core/Octree.h b/include/Engine/Core/Octree.h index 8bac5503..3f03a77c 100644 --- a/include/Engine/Core/Octree.h +++ b/include/Engine/Core/Octree.h @@ -5,9 +5,8 @@ #include "../Common.h" #include "AABB.h" - -//Fwd declarations. -class Ray; +#include "Frustum.h" +#include "Ray.h" namespace OctSpace { @@ -40,6 +39,10 @@ public: //The type Box must be AABB, or inherit from AABB. template void ObjectsInSameRegion(const Box& box, std::vector& outObjects); + //Get the objects that are inside the frustum, the objects are put in outObjects. + void ObjectsInFrustum(const Frustum& frustum, std::vector& outObjects); + //Get objects, which AABB the input ray intersects, the objects are put in outObjects. + void ObjectsPossiblyHitByRay(const Ray& ray, std::vector& outObjects); //Empty the tree of all objects, static and dynamic. void ClearObjects(); //Empty the tree of all dynamic objects. Static objects remain in the tree. @@ -97,6 +100,10 @@ struct Child void AddStaticObject(const AABB& box); template void ObjectsInSameRegion(const Box& box, std::vector& outObjects) const; + template + void ObjectsInFrustum(const Frustum& frustum, std::vector& outObjects, bool takeAllDontTest) const; + template + void ObjectsPossiblyHitByRay(const Ray& ray, std::vector& outObjects) const; void ClearObjects(); void ClearDynamicObjects(); bool RayCollides(const Ray& ray, Output& data) const; @@ -111,11 +118,20 @@ struct Child std::vector& m_StaticObjectsRef; std::vector& m_DynamicObjectsRef; - bool hasChildren() const; + inline bool hasChildren() const { return m_Children[0] != nullptr; } int childIndexContainingPoint(const glm::vec3& point) const; std::vector childIndicesContainingBox(const AABB& box) const; }; +//To be able to sort child nodes and contained objects based on distance to ray origin. +struct RaySorterInfo +{ + int Index; + float Distance; +}; + +bool isFirstLower(const RaySorterInfo& first, const RaySorterInfo& second); + } template @@ -154,6 +170,20 @@ void Octree::ObjectsInSameRegion(const Box& box, std::vector& outObjects) m_Root->ObjectsInSameRegion(box, outObjects); } +template +void Octree::ObjectsInFrustum(const Frustum& frustum, std::vector& outObjects) +{ + falsifyObjectChecks(); + m_Root->ObjectsInFrustum(frustum, outObjects, false); +} + +template +void Octree::ObjectsPossiblyHitByRay(const Ray& ray, std::vector& outObjects) +{ + falsifyObjectChecks(); + m_Root->ObjectsPossiblyHitByRay(ray, outObjects); +} + template void Octree::ClearObjects() { @@ -230,4 +260,101 @@ void OctSpace::Child::ObjectsInSameRegion(const Box& box, std::vector& outObj } } +template +void OctSpace::Child::ObjectsInFrustum(const Frustum& frustum, std::vector& outObjects, bool takeAllDontTest) const +{ + if (hasChildren()) { + for (const Child* c : m_Children) { + Frustum::Output out = Frustum::Output::Inside; + if (!takeAllDontTest) { + out = frustum.VsAABB(c->m_Box); + if (out == Frustum::Output::Outside) { + continue; + } + } + c->ObjectsInFrustum(frustum, outObjects, out == Frustum::Output::Inside); + } + } else { + size_t startIndex = outObjects.size(); + int numDuplicates = 0; + outObjects.resize(outObjects.size() + m_StaticObjIndices.size() + m_DynamicObjIndices.size()); + for (size_t i = 0; i < m_StaticObjIndices.size(); ++i) { + ContainedObject& obj = m_StaticObjectsRef[m_StaticObjIndices[i]]; + if (obj.Checked || frustum.VsAABB(*obj.Box) == Frustum::Output::Outside) { + ++numDuplicates; + } else { + obj.Checked = true; + outObjects[startIndex + i - numDuplicates] = *static_cast(obj.Box.get()); + } + } + for (size_t i = 0; i < m_DynamicObjIndices.size(); ++i) { + ContainedObject& obj = m_DynamicObjectsRef[m_DynamicObjIndices[i]]; + if (obj.Checked || frustum.VsAABB(*obj.Box) == Frustum::Output::Outside) { + ++numDuplicates; + } else { + obj.Checked = true; + outObjects[startIndex + i - numDuplicates] = *static_cast(obj.Box.get()); + } + } + for (size_t i = 0; i < numDuplicates; ++i) { + outObjects.pop_back(); + } + } +} + +template +void OctSpace::Child::ObjectsPossiblyHitByRay(const Ray& ray, std::vector& outObjects) const +{ + //If the node AABB is missed, everything it contains is missed. + if (Collision::RayAABBIntr(ray, m_Box)) { + //If the ray shoots the tree, and it is a parent. + if (hasChildren()) { + //Sort children according to their distance from the ray origin. + std::vector childInfos; + childInfos.resize(8); + for (int i = 0; i < 8; ++i) { + childInfos[i] = { i, glm::distance(ray.Origin(), m_Children[i]->m_Box.Origin()) }; + } + std::sort(childInfos.begin(), childInfos.end(), isFirstLower); + //Loop through the children, starting with the one closest to the ray origin. I.e the first to be hit. + for (const RaySorterInfo& info : childInfos) { + m_Children[info.Index]->ObjectsPossiblyHitByRay(ray, outObjects); + } + } else { + //Check against boxes in the node. + bool intersected = false; + float dist; + //Sort all contained objects according to the distance from the ray origin to + //the intersection, if they are intersecting. + std::vector objectHitInfos; + objectHitInfos.reserve(m_StaticObjIndices.size() + m_DynamicObjIndices.size()); + for (int i : m_StaticObjIndices) { + //If we haven't tested against this object before, and the ray hits. + if (!m_StaticObjectsRef[i].Checked && + Collision::RayVsAABB(ray, *m_StaticObjectsRef[i].Box, dist)) { + objectHitInfos.push_back({ i, dist }); + } + m_StaticObjectsRef[i].Checked = true; + } + for (int i : m_DynamicObjIndices) { + //If we haven't tested against this object before, and the ray hits. + if (!m_DynamicObjectsRef[i].Checked && + Collision::RayVsAABB(ray, *m_DynamicObjectsRef[i].Box, dist)) { + objectHitInfos.push_back({ i + (int)m_StaticObjIndices.size(), dist }); + } + m_DynamicObjectsRef[i].Checked = true; + } + std::sort(objectHitInfos.begin(), objectHitInfos.end(), isFirstLower); + int startSize = (int)outObjects.size(); + outObjects.resize(startSize + objectHitInfos.size()); + for (int i = 0; i < objectHitInfos.size(); ++i) { + outObjects[startSize + i] = (objectHitInfos[i].Index < m_StaticObjIndices.size()) ? + *static_cast(m_StaticObjectsRef[objectHitInfos[i].Index].Box.get()) : + *static_cast(m_DynamicObjectsRef[objectHitInfos[i].Index - m_StaticObjIndices.size()].Box.get()); + } + } + } +} + + #endif \ No newline at end of file diff --git a/include/Engine/Core/PerformanceTimer.h b/include/Engine/Core/PerformanceTimer.h new file mode 100644 index 00000000..a3cdfa92 --- /dev/null +++ b/include/Engine/Core/PerformanceTimer.h @@ -0,0 +1,25 @@ +#ifndef PerformanceTimer_h__ +#define PerformanceTimer_h__ + +#include "../Common.h" +#include +using boost::timer::cpu_timer; + +class PerformanceTimer +{ +public: + static void StartTimer(std::string nameOfTimer); + static void StartTimerAndStopPrevious(std::string nameOfTimer); + static void StopTimer(std::string nameOfTimer); + static void SetFrameNumber(int frameNumber); + + static void ResetAllTimers(); + static void CreateExcelData(); + +private: + static std::map timers; + static cpu_timer m_Timer; + static std::string currentTimerRunning; +}; + +#endif diff --git a/include/Engine/Core/Ray.h b/include/Engine/Core/Ray.h index a234a488..03bfa391 100644 --- a/include/Engine/Core/Ray.h +++ b/include/Engine/Core/Ray.h @@ -7,6 +7,10 @@ class Ray { public: + Ray() + : m_Origin(glm::vec3(0.f)) + , m_Direction(glm::vec3(0, 0, 1)) + {} Ray(const glm::vec3& origin, const glm::vec3& dir) : m_Origin(origin) , m_Direction(glm::normalize(dir)) diff --git a/include/Engine/Core/ResourceManager.h b/include/Engine/Core/ResourceManager.h index 10529819..b994b5cf 100644 --- a/include/Engine/Core/ResourceManager.h +++ b/include/Engine/Core/ResourceManager.h @@ -200,13 +200,16 @@ static T* ResourceManager::Load(const std::string& resourceName, Resource* paren } //If resource has already been cached and completely loaded. - it = m_ResourceCache.find(cacheKey); - if (it != m_ResourceCache.end()) { - if (it->second != nullptr) { - return static_cast(it->second); - } else { - //Don't return null on failure, exception instead. - throw Resource::FailedLoadingException(); + { + boost::lock_guard guard(m_Mutex); + it = m_ResourceCache.find(cacheKey); + if (it != m_ResourceCache.end()) { + if (it->second != nullptr) { + return static_cast(it->second); + } else { + //Don't return null on failure, exception instead. + throw Resource::FailedLoadingException(); + } } } diff --git a/include/Engine/Core/System.h b/include/Engine/Core/System.h index ec57f5fc..1a387855 100644 --- a/include/Engine/Core/System.h +++ b/include/Engine/Core/System.h @@ -5,21 +5,55 @@ #include "World.h" #include "EntityWrapper.h" #include "ComponentWrapper.h" +#include "EPlayerSpawned.h" + +struct SystemParams +{ + SystemParams(::World* World, ::EventBroker* EventBroker, bool IsClient, bool IsServer) + : World(World) + , EventBroker(EventBroker) + , IsClient(IsClient) + , IsServer(IsServer) + { } + + ::World* World; + ::EventBroker* EventBroker; + bool IsClient = false; + bool IsServer = false; +}; class System { friend class SystemPipeline; protected: - System(World* world, EventBroker) { } - System(World* world, EventBroker* eventBroker) - : m_World(world) - , m_EventBroker(eventBroker) - { } + System(SystemParams params) + : m_World(params.World) + , m_EventBroker(params.EventBroker) + , IsClient(params.IsClient) + , IsServer(params.IsServer) + { + if (IsClient) { + EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &System::setLocalPlayer); + } + } virtual ~System() = default; World* m_World; EventBroker* m_EventBroker; + bool IsClient = false; + bool IsServer = false; + EntityWrapper LocalPlayer = EntityWrapper::Invalid; + +private: + EventRelay m_EPlayerSpawned; + virtual bool setLocalPlayer(Events::PlayerSpawned& e) + { + if (e.PlayerID == -1) { + LocalPlayer = e.Player; + } + return true; + } }; class PureSystem : public virtual System @@ -34,7 +68,7 @@ protected: const std::string m_ComponentType; - virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cComponent, double dt) = 0; + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cPlayer, double dt) = 0; }; class ImpureSystem : public virtual System diff --git a/include/Engine/Core/SystemPipeline.h b/include/Engine/Core/SystemPipeline.h index 90303f12..c4801fde 100644 --- a/include/Engine/Core/SystemPipeline.h +++ b/include/Engine/Core/SystemPipeline.h @@ -6,13 +6,16 @@ #include "System.h" #include "World.h" #include "EPause.h" +#include "PerformanceTimer.h" class SystemPipeline { public: - SystemPipeline(World* world, EventBroker* eventBroker) + SystemPipeline(World* world, EventBroker* eventBroker, bool isClient, bool isServer) : m_World(world) , m_EventBroker(eventBroker) + , m_IsClient(isClient) + , m_IsServer(isServer) { EVENT_SUBSCRIBE_MEMBER(m_EPause, &SystemPipeline::OnPause); EVENT_SUBSCRIBE_MEMBER(m_EResume, &SystemPipeline::OnResume); @@ -35,7 +38,7 @@ public: m_OrderedSystemGroups.resize(updateOrderLevel + 1); } UnorderedSystems& group = m_OrderedSystemGroups[updateOrderLevel]; - System* system = new T(m_World, m_EventBroker, args...); + System* system = new T(SystemParams(m_World, m_EventBroker, m_IsClient, m_IsServer), args...); group.Systems[typeid(T).name()] = system; PureSystem* pureSystem = dynamic_cast(system); @@ -59,6 +62,9 @@ public: dt = 0.0; } + // Process utility events for the System base class + m_EventBroker->Process(); + for (UnorderedSystems& group : m_OrderedSystemGroups) { // Process events for (auto& pair : group.Systems) { @@ -67,7 +73,10 @@ public: // Update for (auto& system : group.ImpureSystems) { + auto className = (std::string)typeid(*system).name(); + PerformanceTimer::StartTimer(className); system->Update(dt); + PerformanceTimer::StopTimer(className); } for (auto& pair : group.PureSystems) { const std::string& componentName = pair.first; @@ -78,7 +87,10 @@ public: } for (auto& component : *pool) { for (auto& system : systems) { + auto className = (std::string)typeid(*system).name(); + PerformanceTimer::StartTimer(className); system->UpdateComponent(EntityWrapper(m_World, component.EntityID), component, dt); + PerformanceTimer::StopTimer(className); } } } @@ -88,6 +100,8 @@ public: private: World* m_World; EventBroker* m_EventBroker; + bool m_IsClient = false; + bool m_IsServer = false; bool m_Paused = false; struct UnorderedSystems @@ -99,9 +113,9 @@ private: std::vector m_OrderedSystemGroups; EventRelay m_EPause; - bool OnPause(const Events::Pause& e) { - if (e.World == m_World) { - m_Paused = true; + bool OnPause(const Events::Pause& e) { + if (e.World == m_World) { + m_Paused = true; } return true; } diff --git a/include/Engine/Core/Transform.h b/include/Engine/Core/Transform.h index 2f549140..bd381e8b 100644 --- a/include/Engine/Core/Transform.h +++ b/include/Engine/Core/Transform.h @@ -18,6 +18,7 @@ glm::vec3 AbsoluteScale(EntityWrapper entity); glm::vec3 AbsoluteScale(World* world, EntityID entity); glm::mat4 ModelMatrix(EntityWrapper entity); glm::mat4 ModelMatrix(EntityID entity, World* world); +glm::vec3 TransformPoint(const glm::vec3& point, const glm::mat4& matrix); } diff --git a/include/Engine/Core/UniformScaleSystem.h b/include/Engine/Core/UniformScaleSystem.h index 0ebc0672..cd679fed 100644 --- a/include/Engine/Core/UniformScaleSystem.h +++ b/include/Engine/Core/UniformScaleSystem.h @@ -8,7 +8,7 @@ class UniformScaleSystem : public PureSystem { public: - UniformScaleSystem(World* world, EventBroker* eventBroker); + UniformScaleSystem(SystemParams params); virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cUniformScale, double dt) override; diff --git a/include/Engine/Core/Util/Any.h b/include/Engine/Core/Util/Any.h index f0f90737..e7b93dfb 100644 --- a/include/Engine/Core/Util/Any.h +++ b/include/Engine/Core/Util/Any.h @@ -2,6 +2,7 @@ #define Util_Any_h__ #include +#include struct Any { @@ -10,7 +11,7 @@ struct Any template Any(const T& value) { - Data = std::shared_ptr(new char[sizeof(T)]); + Data = boost::shared_array(new char[sizeof(T)]); Size = sizeof(T); memcpy(Data.get(), &value, Size); } @@ -18,7 +19,7 @@ struct Any template Any(T&& value) { - Data = std::shared_ptr(new char[sizeof(T)]); + Data = boost::shared_array(new char[sizeof(T)]); Size = sizeof(T); memcpy(Data.get(), &value, Size); } @@ -35,7 +36,7 @@ struct Any return Any(value); } - std::shared_ptr Data = nullptr; + boost::shared_array Data = nullptr; std::size_t Size = 0; }; diff --git a/include/Engine/Core/Util/IfDebug.h b/include/Engine/Core/Util/IfDebug.h index 79cb3a4c..85b64c8d 100644 --- a/include/Engine/Core/Util/IfDebug.h +++ b/include/Engine/Core/Util/IfDebug.h @@ -4,7 +4,7 @@ // } // NOTE: condition statement is not executed at all in release mode. #ifndef DEBUG_IF -#ifndef DEBUG +#ifdef DEBUG #define DEBUG_IF(c) if(c) #else #define DEBUG_IF(c) if(false) diff --git a/include/Engine/Core/World.h b/include/Engine/Core/World.h index 35394b9f..c9f738ce 100644 --- a/include/Engine/Core/World.h +++ b/include/Engine/Core/World.h @@ -15,6 +15,7 @@ public: : m_EventBroker(eventBroker) { } ~World(); + World(const World& other); // Create empty entity EntityID CreateEntity(EntityID parent = 0); @@ -39,7 +40,7 @@ public: // Change the parent of an entity void SetParent(EntityID entity, EntityID parent); // Get children of an entity - const std::pair::const_iterator, std::unordered_multimap::const_iterator> GetChildren(EntityID entity); + const std::pair::const_iterator, std::unordered_multimap::const_iterator> GetDirectChildren(EntityID entity); // Get all component pools const std::unordered_map& GetComponentPools() const { return m_ComponentPools; } // Get the entity children map diff --git a/include/Engine/Editor/EditorGUI.h b/include/Engine/Editor/EditorGUI.h index 7a0289c6..57574e66 100644 --- a/include/Engine/Editor/EditorGUI.h +++ b/include/Engine/Editor/EditorGUI.h @@ -73,6 +73,12 @@ public: // Called when the user means to rename an entity. typedef std::function OnEntityChangeName_t; void SetEntityChangeNameCallback(OnEntityChangeName_t f) { m_OnEntityChangeName = f; } + // Called when the user pastes an entity previously "copied" + // @param EntityWrapper The entity to copy + // @param EntityWrapper The entity to parent the new copy to + // @return The new copy of the entity + typedef std::function OnEntityPaste_t; + void SetEntityPasteCallback(OnEntityPaste_t f) { m_OnEntityPaste = f; } // Called when the user means to attach a new component to an entity. typedef std::function OnComponentAttach_t; void SetComponentAttachCallback(OnComponentAttach_t f) { m_OnComponentAttach = f; } @@ -111,6 +117,7 @@ private: std::string m_DroppedFile = ""; bool m_Paused = false; bool m_MouseLocked = false; + EntityWrapper m_CopyTarget = EntityWrapper::Invalid; // Callbacks OnEntitySelectedCallback_t m_OnEntitySelected = nullptr; @@ -124,6 +131,7 @@ private: OnComponentDelete_t m_OnComponentDelete = nullptr; OnWidgetMode_t m_OnWidgetMode = nullptr; OnWidgetSpace_t m_OnWidgetSpace = nullptr; + OnEntityPaste_t m_OnEntityPaste = nullptr; // Events EventRelay m_EKeyDown; diff --git a/include/Engine/Editor/EditorRenderSystem.h b/include/Engine/Editor/EditorRenderSystem.h index 361669ba..a42ad779 100644 --- a/include/Engine/Editor/EditorRenderSystem.h +++ b/include/Engine/Editor/EditorRenderSystem.h @@ -10,7 +10,7 @@ class EditorRenderSystem : public ImpureSystem { public: - EditorRenderSystem(World* world, EventBroker* eventBroker, IRenderer* renderer, RenderFrame* renderFrame); + EditorRenderSystem(SystemParams params, IRenderer* renderer, RenderFrame* renderFrame); virtual void Update(double dt) override; diff --git a/include/Engine/Editor/EditorSystem.h b/include/Engine/Editor/EditorSystem.h index accf66e4..06ee53b6 100644 --- a/include/Engine/Editor/EditorSystem.h +++ b/include/Engine/Editor/EditorSystem.h @@ -17,7 +17,7 @@ class EditorSystem : public ImpureSystem { public: - EditorSystem(World* world, EventBroker* eventBroker, IRenderer* renderer, RenderFrame* renderFrame); + EditorSystem(SystemParams params, IRenderer* renderer, RenderFrame* renderFrame); ~EditorSystem(); void Update(double dt); @@ -56,6 +56,7 @@ private: void OnEntityDelete(EntityWrapper entity); void OnEntityChangeParent(EntityWrapper entity, EntityWrapper parent); void OnEntityChangeName(EntityWrapper entity, const std::string& name); + EntityWrapper OnEntityPaste(EntityWrapper entityToCopy, EntityWrapper parent); void OnComponentAttach(EntityWrapper entity, const std::string& componentType); void OnComponentDelete(EntityWrapper entity, const std::string& componentType); void OnWidgetSpace(EditorGUI::WidgetSpace widgetSpace); diff --git a/include/Engine/Editor/EditorWidgetSystem.h b/include/Engine/Editor/EditorWidgetSystem.h index a060bdd5..57e653d6 100644 --- a/include/Engine/Editor/EditorWidgetSystem.h +++ b/include/Engine/Editor/EditorWidgetSystem.h @@ -25,7 +25,7 @@ struct WidgetDelta : Event class EditorWidgetSystem : public ImpureSystem, PureSystem { public: - EditorWidgetSystem(World* world, EventBroker* eventBroker, IRenderer* renderer); + EditorWidgetSystem(SystemParams params, IRenderer* renderer); virtual void Update(double dt) override; virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cEditorWidget, double dt) override; diff --git a/include/Engine/GUI/Button.h b/include/Engine/GUI/Button.h deleted file mode 100644 index 80845cb7..00000000 --- a/include/Engine/GUI/Button.h +++ /dev/null @@ -1,165 +0,0 @@ -#ifndef GUI_BUTTON_H__ -#define GUI_BUTTON_H__ - -#include "GUI/TextureFrame.h" -#include "GUI/EButtonEnter.h" -#include "GUI/EButtonLeave.h" -#include "GUI/EButtonPress.h" -#include "GUI/EButtonRelease.h" -#include "Core/EMouseMove.h" -#include "Core/EMousePress.h" -#include "Core/EMouseRelease.h" - -namespace dd -{ -namespace GUI -{ - -class Button : public TextureFrame -{ -public: - Button(Frame* parent, std::string name) - : TextureFrame(parent, name) - { - EVENT_SUBSCRIBE_MEMBER(m_EMouseMove, &Button::OnMouseMove); - EVENT_SUBSCRIBE_MEMBER(m_EMousePress, &Button::OnMousePress); - EVENT_SUBSCRIBE_MEMBER(m_EMouseRelease, &Button::OnMouseRelease); - } - - void SetTextureHover(std::string resourceName) - { - m_TextureHover = resourceName; - } - void SetTextureReleased(std::string resourceName) - { - m_TextureReleased = resourceName; - SetTexture(resourceName); - } - void SetTexturePressed(std::string resourceName) - { - m_TexturePressed = resourceName; - } - - void Draw(RenderScene& rq) override - { - if (m_Texture == nullptr && !m_TextureReleased.empty()) { - SetTexture(m_TextureReleased); - } - - TextureFrame::Draw(rq); - } - - virtual void OnEnter() { } - virtual void OnLeave() { } - virtual void OnPress() { } - virtual void OnRelease() { } - -protected: - bool m_MouseIsOver = false; - bool m_IsDown = false; - - virtual bool OnMouseMove(const Events::MouseMove& event) - { - if (Hidden()) { - return false; - } - - bool isOver = Rectangle::Intersects(AbsoluteRectangle(), Rectangle(event.X, event.Y, 1, 1)); - if (isOver && !m_MouseIsOver) { // Enter - if (!m_IsDown) { - if (!m_TextureHover.empty()) { - SetTexture(m_TextureHover); - } - } - OnEnter(); - Events::ButtonEnter e; - e.FrameName = m_Name; - EventBroker->Publish(e); - Events::PlaySound soundEvent; - soundEvent.FilePath = "Sounds/GUI/hover-n.wav"; - EventBroker->Publish(soundEvent); - - } else if (!isOver && m_MouseIsOver) { // Leave - if (!m_IsDown) { - if (!m_TextureReleased.empty()) { - SetTexture(m_TextureReleased); - } - } - OnLeave(); - Events::ButtonLeave e; - e.FrameName = m_Name; - EventBroker->Publish(e); - } - m_MouseIsOver = isOver; - - return true; - } - virtual bool OnMousePress(const Events::MousePress& event) - { - if (Hidden()) { - //LOG_DEBUG("Pressed hidden button"); - return false; - } - - if (!Rectangle::Intersects(AbsoluteRectangle(), Rectangle(event.X, event.Y, 1, 1))) { - return false; - } - - if (!m_TexturePressed.empty()) { - SetTexture(m_TexturePressed); - } - - m_IsDown = true; - OnPress(); - Events::ButtonPress e; - e.FrameName = m_Name; - e.Button = this; - EventBroker->Publish(e); - - return true; - } - virtual bool OnMouseRelease(const Events::MouseRelease& event) - { - if (Hidden()) { - //LOG_DEBUG("Released hidden button"); - return false; - } - - bool isOver = Rectangle::Intersects(AbsoluteRectangle(), Rectangle(event.X, event.Y, 1, 1)); - if (!isOver && !m_IsDown) { - return false; - } - - if (m_MouseIsOver) { - if (!m_TextureHover.empty()) { - SetTexture(m_TextureHover); - } - } else { - if (!m_TextureReleased.empty()) { - SetTexture(m_TextureReleased); - } - } - - m_IsDown = false; - OnRelease(); - Events::ButtonRelease e; - e.FrameName = m_Name; - e.Button = this; - EventBroker->Publish(e); - - return true; - } - -private: - EventRelay m_EMouseMove; - EventRelay m_EMousePress; - EventRelay m_EMouseRelease; - - std::string m_TextureHover; - std::string m_TexturePressed; - std::string m_TextureReleased; -}; - -} -} -#endif diff --git a/include/Engine/GUI/ButtonSystem.h b/include/Engine/GUI/ButtonSystem.h new file mode 100644 index 00000000..7dfe6b48 --- /dev/null +++ b/include/Engine/GUI/ButtonSystem.h @@ -0,0 +1,44 @@ +#ifndef ButtonSystem_h__ +#define ButtonSystem_h__ + +#include "../Rendering/IRenderer.h" +#include "../Core/ConfigFile.h" +#include "../Rendering/PickingPass.h" +#include "../Core/ResourceManager.h" +#include "../Core/System.h" +#include "../Core/Event.h" +#include "../Core/EMousePress.h" +#include "../Core/EMouseRelease.h" +#include "../Core/ELockMouse.h" + +#include "EButtonPressed.h" +#include "EButtonReleased.h" +#include "EButtonClicked.h" + + +class ButtonSystem : public PureSystem +{ +public: + ButtonSystem(SystemParams params, IRenderer* renderer); + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override; +private: + IRenderer* m_Renderer; + bool m_MouseIsLocked = false; + + EntityWrapper m_PickEntity = EntityWrapper::Invalid; + PickData m_PickData; + + EventRelay m_EMouseLock; + bool OnMouseLock(const Events::LockMouse& e); + EventRelay m_EMouseUnlock; + bool OnMouseUnlock(const Events::UnlockMouse& e); + + EventRelay m_EMousePress; + bool OnMousePress(const Events::MousePress& e); + EventRelay m_EMouseRelease; + bool OnMouseRelease(const Events::MouseRelease& e); +}; + + + +#endif \ No newline at end of file diff --git a/include/Engine/GUI/EButtonClicked.h b/include/Engine/GUI/EButtonClicked.h new file mode 100644 index 00000000..e4fe7abe --- /dev/null +++ b/include/Engine/GUI/EButtonClicked.h @@ -0,0 +1,16 @@ +#ifndef Events_ButtonClicked_h__ +#define Events_ButtonClicked_h__ + +#include "Core/Event.h" + +namespace Events +{ + +struct ButtonClicked : public Event { + std::string EntityName; + EntityWrapper Entity; +}; + +} + +#endif \ No newline at end of file diff --git a/include/Engine/GUI/EButtonEnter.h b/include/Engine/GUI/EButtonEnter.h deleted file mode 100644 index 13a78383..00000000 --- a/include/Engine/GUI/EButtonEnter.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef Events_ButtonEnter_h__ -#define Events_ButtonEnter_h__ - -#include "../Core/EventBroker.h" - -namespace Events -{ - -/** Thrown on GUI button hover. */ -struct ButtonEnter : Event -{ - std::string FrameName; -}; - -} - -#endif \ No newline at end of file diff --git a/include/Engine/GUI/EButtonLeave.h b/include/Engine/GUI/EButtonLeave.h deleted file mode 100644 index 789e5aec..00000000 --- a/include/Engine/GUI/EButtonLeave.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef Events_ButtonLeave_h__ -#define Events_ButtonLeave_h__ - -#include "../Core/EventBroker.h" - -namespace Events -{ - -/** Thrown on GUI button hover. */ -struct ButtonLeave : Event -{ - std::string FrameName; -}; - -} - -#endif \ No newline at end of file diff --git a/include/Engine/GUI/EButtonPress.h b/include/Engine/GUI/EButtonPress.h deleted file mode 100644 index 6f925b2b..00000000 --- a/include/Engine/GUI/EButtonPress.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef Events_ButtonPress_h__ -#define Events_ButtonPress_h__ - -#include "../Core/EventBroker.h" - -namespace GUI { class Button; } - -namespace Events -{ - -/** Thrown on GUI button press. */ -struct ButtonPress : Event -{ - std::string FrameName; - GUI::Button* Button; -}; - -} - -#endif \ No newline at end of file diff --git a/include/Engine/GUI/EButtonPressed.h b/include/Engine/GUI/EButtonPressed.h new file mode 100644 index 00000000..3615ac8a --- /dev/null +++ b/include/Engine/GUI/EButtonPressed.h @@ -0,0 +1,16 @@ +#ifndef Events_ButtonPressed_h__ +#define Events_ButtonPressed_h__ + +#include "Core/Event.h" + +namespace Events +{ + +struct ButtonPressed : public Event { + std::string EntityName; + EntityWrapper Entity; +}; + +} + +#endif \ No newline at end of file diff --git a/include/Engine/GUI/EButtonRelease.h b/include/Engine/GUI/EButtonRelease.h deleted file mode 100644 index d13a8ad6..00000000 --- a/include/Engine/GUI/EButtonRelease.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef Events_ButtonRelease_h__ -#define Events_ButtonRelease_h__ - -#include "../Core/EventBroker.h" - -namespace GUI { class Button; } - -namespace Events -{ - -/** Thrown on GUI button release. */ -struct ButtonRelease : Event -{ - std::string FrameName; - GUI::Button* Button; -}; - -} - -#endif \ No newline at end of file diff --git a/include/Engine/GUI/EButtonReleased.h b/include/Engine/GUI/EButtonReleased.h new file mode 100644 index 00000000..ecd8dde2 --- /dev/null +++ b/include/Engine/GUI/EButtonReleased.h @@ -0,0 +1,16 @@ +#ifndef Events_ButtonReleased_h__ +#define Events_ButtonReleased_h__ + +#include "Core/Event.h" + +namespace Events +{ + +struct ButtonReleased : public Event { + std::string EntityName; + EntityWrapper Entity; +}; + +} + +#endif \ No newline at end of file diff --git a/include/Engine/GUI/Frame.h b/include/Engine/GUI/Frame.h deleted file mode 100644 index 4c5f2eb9..00000000 --- a/include/Engine/GUI/Frame.h +++ /dev/null @@ -1,261 +0,0 @@ -#ifndef GUI_Frame_h__ -#define GUI_Frame_h__ - -#include "../Common.h" -#include "../Core/Util/Rectangle.h" -#include "../Core/EventBroker.h" -#include "../Core/EKeyDown.h" -#include "../Core/EKeyUp.h" -#include "../Core/ResourceManager.h" -#include "../Rendering/RenderQueue.h" -#include "../Rendering/Texture.h" -#include "../Input/EInputCommand.h" - -namespace GUI -{ - -class Frame : public Rectangle -{ -public: - enum class Anchor - { - Left, - Right, - Top, - Bottom - }; - - static const int BaseWidth = 1280; - static const int BaseHeight = 720; - - // Set up a base frame with an event broker - Frame(EventBroker* eventBroker) - : m_EventBroker(eventBroker) - , BaseFrame(this) - , m_Name("UIParent") - , Rectangle() { } - - // Create a frame as a child - Frame(Frame* parent, std::string name) - : m_Name(name) - { - SetParent(parent); - Width = parent->Width; - Height = parent->Height; - EVENT_SUBSCRIBE_MEMBER(m_EKeyDown, &Frame::OnKeyDown); - EVENT_SUBSCRIBE_MEMBER(m_EKeyUp, &Frame::OnKeyUp); - EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &Frame::OnCommand); - } - - ~Frame() - { - /*for (auto layer : m_Children) - { - for (auto child : layer.second) - { - delete child.second; - } - } - - if (m_Parent) - { - m_Parent->RemoveChild(this); - }*/ - } - - Frame* Parent() const { return m_Parent; } - - void SetParent(Frame* parent) - { - if (parent == nullptr) { - LOG_ERROR("Failed to parent frame \"%s\": Invalid parent", m_Name.c_str()); - return; - } - - m_Layer = parent->Layer() + 1; - parent->AddChild(this); - m_Parent = parent; - m_EventBroker = parent->m_EventBroker; - BaseFrame = parent->BaseFrame; - } - - void AddChild(Frame* child) - { - m_Children[child->m_Layer].insert(std::make_pair(child->Name(), child)); - if (m_Parent) { - m_Parent->AddChild(child); - } - } - - void RemoveChild(Frame* child) - { - auto it = m_Children.find(child->m_Layer); - if (it != m_Children.end()) { - m_Children.erase(it); - } - - if (m_Parent) { - m_Parent->RemoveChild(child); - } - } - - std::string Name() const { return m_Name; } - void SetName(std::string val) { m_Name = val; } - - int Layer() const { return m_Layer; } - - bool Hidden() const - { - if (m_Parent) - return m_Parent->Hidden() || m_Hidden; - else - return m_Hidden; - } - bool Visible() const - { - return !Hidden(); - } - - virtual void Hide() { m_Hidden = true; } - virtual void Show() { m_Hidden = false; } - - int Left() const override - { - if (m_Parent) - return m_Parent->Left() + X; - else - return X; - } - void SetLeft(int absLeft) override - { - if (m_Parent) { - X = absLeft - m_Parent->Left(); - } else { - X = absLeft; - } - } - int Right() const override - { - return Left() + Width; - } - void SetRight(int absRight) override - { - if (m_Parent) { - X = absRight - Width - m_Parent->Left(); - } else { - X = absRight - Width; - } - } - int Top() const override - { - if (m_Parent) - return m_Parent->Top() + Y; - else - return Y; - } - void SetTop(int absTop) override - { - if (m_Parent) { - Y = absTop - m_Parent->Top(); - } else { - Y = absTop; - } - } - int Bottom() const override - { - return Top() + Height; - } - void SetBottom(int absBottom) override - { - if (m_Parent) { - Y = absBottom - Height - m_Parent->Top(); - } else { - Y = absBottom - Height; - } - } - - glm::vec2 Scale() - { - if (m_Parent) - return m_Parent->Scale(); - else - return glm::vec2(Width, Height) / glm::vec2(BaseWidth, BaseHeight); - } - - Rectangle AbsoluteRectangle() - { - int left = Left(); - if (m_Parent) - left = std::max(left, m_Parent->Left()); - int top = Top(); - if (m_Parent) - top = std::max(top, m_Parent->Top()); - int width = Right() - left; - int height = Bottom() - top; - return Rectangle(left, top, width, height); - } - - void UpdateLayered(double dt) - { - // Update ourselves - this->Update(dt); - - // Update children - for (auto& pairLayer : m_Children) { - auto children = pairLayer.second; - for (auto& pairChild : children) { - auto child = pairChild.second; - child->Update(dt); - } - } - } - - virtual void Update(double dt) { } - - void DrawLayered(RenderScene& rq) - { - if (this->Hidden()) - return; - - // Draw ourselves - this->Draw(rq); - - // Draw children - for (auto& pairLayer : m_Children) { - auto children = pairLayer.second; - for (auto& pairChild : children) { - auto child = pairChild.second; - if (child->Hidden()) - continue; - child->Draw(rq); - } - } - } - - virtual void Draw(RenderScene& rq) { } - -protected: - ::EventBroker* m_EventBroker; - Frame* BaseFrame = nullptr; - - std::string m_Name = "Unnamed"; - int m_Layer = 0; - bool m_Hidden = false; - - Frame* m_Parent = nullptr; - typedef std::multimap Children_t; // name -> frame - std::map m_Children; // layer -> Children_t - - virtual bool OnKeyDown(const Events::KeyDown& event) { return false; } - virtual bool OnKeyUp(const Events::KeyUp& event) { return false; } - virtual bool OnCommand(const Events::InputCommand& event) { return false; } - -private: - EventRelay m_EKeyDown; - EventRelay m_EKeyUp; - EventRelay m_EInputCommand; -}; - -} - -#endif diff --git a/include/Engine/GUI/MainMenuSystem.h b/include/Engine/GUI/MainMenuSystem.h new file mode 100644 index 00000000..ba69ff0d --- /dev/null +++ b/include/Engine/GUI/MainMenuSystem.h @@ -0,0 +1,33 @@ +#ifndef MainMenuSystem_h__ +#define MainMenuSystem_h__ + +#include "../Core/System.h" +#include "../Rendering/IRenderer.h" +#include "../Core/ResourceManager.h" +#include "../Core/Event.h" + + +#include "EButtonClicked.h" +#include "EButtonPressed.h" +#include "EButtonReleased.h" + + +class MainMenuSystem : public ImpureSystem +{ +public: + MainMenuSystem(SystemParams params, IRenderer* renderer); + virtual void Update(double dt) override; + +private: + IRenderer* m_Renderer; + + EventRelay m_EClicked; + bool OnButtonClick(const Events::ButtonClicked& e); + EventRelay m_EReleased; + bool OnButtonRelease(const Events::ButtonReleased& e); + EventRelay m_EPressed; + bool OnButtonPress(const Events::ButtonPressed& e); + +}; + +#endif \ No newline at end of file diff --git a/include/Engine/GUI/TextureFrame.h b/include/Engine/GUI/TextureFrame.h deleted file mode 100644 index 2c6d34dd..00000000 --- a/include/Engine/GUI/TextureFrame.h +++ /dev/null @@ -1,111 +0,0 @@ -#ifndef GUI_TextureFrame_h__ -#define GUI_TextureFrame_h__ - -#include "Frame.h" -#include "../Rendering/Texture.h" - -namespace GUI -{ - -class TextureFrame : public Frame -{ -public: - TextureFrame(Frame* parent, std::string name) - : Frame(parent, name) { } - - void EnableScissor() { m_ScissorEnabled = true; } - void DisableScissor() { m_ScissorEnabled = false; } - - void Draw(RenderScene& rq) override - { - if (m_Texture == nullptr) - return; - - // Texture while fading - if (m_FadeTexture && m_CurrentFade < 1) { - FrameJob job; - job.Scissor = (m_ScissorEnabled) ? m_Parent->AbsoluteRectangle() : Rectangle(); - job.Viewport = Rectangle(Left(), Top(), Width, Height); - job.TextureID = m_FadeTexture->ResourceID; - job.DiffuseTexture = m_FadeTexture; - job.Color = glm::vec4(m_Color.r, m_Color.g, m_Color.b, m_Color.a); - job.Name = Name(); - rq.GUI.Add(job); - } - - // Main texture - { - FrameJob job; - job.Scissor = (m_ScissorEnabled) ? m_Parent->AbsoluteRectangle() : Rectangle(); - job.Viewport = Rectangle(Left(), Top(), Width, Height); - job.TextureID = m_Texture->ResourceID; - job.DiffuseTexture = m_Texture; - job.Color = glm::vec4(m_Color.r, m_Color.g, m_Color.b, m_Color.a * m_CurrentFade); - job.Name = Name(); - rq.GUI.Add(job); - } - } - - std::string Texture() const { return m_TextureName; } - - void SetTexture(std::string resourceName) - { - if (resourceName.empty()) { - m_Texture = nullptr; - return; - } - - m_Texture = ResourceManager::Load(resourceName); - m_TextureName = resourceName; - if (m_Texture == nullptr) { - m_Texture = ResourceManager::Load("Textures/Core/ErrorTexture.png"); - } - - SizeToTexture(); - } - - void SizeToTexture() - { - if (m_Texture != nullptr) { - this->Width = m_Texture->Width; - this->Height = m_Texture->Height; - } - } - - void FadeToTexture(std::string resourceName, double duration) - { - m_FadeTexture = m_Texture; - SetTexture(resourceName); - m_FadeDuration = duration; - m_CurrentFade = 0.f; - } - - void Update(double dt) override - { - if (m_CurrentFade < 1) { - m_CurrentFade += dt / m_FadeDuration; - if (m_CurrentFade > 1) { - m_FadeTexture = nullptr; - m_CurrentFade = 1; - m_FadeDuration = 0; - } - } - } - - glm::vec4 Color() const { return m_Color; } - void SetColor(glm::vec4 val) { m_Color = val; } - -protected: - bool m_ScissorEnabled = true; - Texture* m_Texture = nullptr; - std::string m_TextureName; - Texture* m_FadeTexture = nullptr; - glm::vec4 m_Color = glm::vec4(1.f, 1.f, 1.f, 1.f); - float m_FadeDuration = 0.f; - float m_CurrentFade = 1.f; - -}; - -} - -#endif diff --git a/include/Engine/Input/FirstPersonInputController.h b/include/Engine/Input/FirstPersonInputController.h index d4c9071c..7dc24a2c 100644 --- a/include/Engine/Input/FirstPersonInputController.h +++ b/include/Engine/Input/FirstPersonInputController.h @@ -4,6 +4,8 @@ #include "../GLM.h" #include "../Core/InputController.h" #include "../Core/ELockMouse.h" +#include "../Game/Events/EDashAbility.h" +#include "InputHandler.h" template class FirstPersonInputController : public InputController @@ -25,6 +27,10 @@ public: virtual bool OnCommand(const Events::InputCommand& e) override; virtual void Reset(); + void AssaultDashCheck(double dt, bool isJumping, double assaultDashCoolDownMaxTimer); + virtual bool AssaultDashDoubleTapped() const { return m_AssaultDashDoubleTapped; } + virtual bool PlayerIsDashing() const { return m_PlayerIsDashing; } + protected: const int m_PlayerID; bool m_MouseLocked = false; @@ -33,6 +39,23 @@ protected: bool m_Jumping = false; bool m_DoubleJumping = false; bool m_Crouching = false; + //assault dash membervariables - needed to calculate the doubletap- and dashlogic + double m_AssaultDashDoubleTapDeltaTime = 0.0; + double m_AssaultDashCoolDownTimer = 0.0; + //i will let m_AssaultDashDoubleTapSensitivityTimer stay hardcoded, its not really a gamevariable (more an inputvariable), + //and its very unlikely that someone wants to change that value + const float m_AssaultDashDoubleTapSensitivityTimer = 0.25f; + std::string m_AssaultDashTapDirection = ""; + std::string m_CurrentDirectionVector = ""; + bool m_AssaultDashDoubleTapped = false; + bool m_PlayerIsDashing = false; + bool m_ShiftDashing = false; + bool m_ValidDoubleTap = false; + + //specialabilitys + bool m_MovementKeyDown = false; + bool m_SpecialAbilityKeyDown = false; + int m_NumberOfMovementKeysDown = 0; EventRelay m_ELockMouse; bool OnLockMouse(const Events::LockMouse& e); @@ -104,6 +127,31 @@ bool FirstPersonInputController::OnCommand(const Events::InputComm } } + if (e.Command == "Forward" || e.Command == "Right") { + if (e.Value != 0) { + m_CurrentDirectionVector = e.Command == "Right" ? (e.Value > 0 ? "Right" : "Left") : (e.Value > 0 ? "Forward" : "Backward"); + } + //if value = 0 then you have just released this key + if (e.Value != 0) { + m_NumberOfMovementKeysDown++; + m_MovementKeyDown = true; + //if you pressed the same key within m_AssaultDashDoubleTapSensitivityTimer then you have doubletapped it + if (m_AssaultDashDoubleTapDeltaTime < m_AssaultDashDoubleTapSensitivityTimer && m_AssaultDashTapDirection == m_CurrentDirectionVector) { + m_ValidDoubleTap = true; + } + } else { + //== 0 + m_NumberOfMovementKeysDown--; + if (m_NumberOfMovementKeysDown == 0) { + m_MovementKeyDown = false; + } + //you have just released the key, store what key it was and reset the doubletap-sensitivity-timer + m_AssaultDashTapDirection = m_CurrentDirectionVector; + m_AssaultDashDoubleTapDeltaTime = 0.f; + + } + } + if (e.Command == "Jump") { m_Jumping = e.Value > 0; } @@ -112,6 +160,19 @@ bool FirstPersonInputController::OnCommand(const Events::InputComm m_Crouching = e.Value > 0; } + if (e.Command == "SpecialAbility") { + if (e.Value > 0) { + m_SpecialAbilityKeyDown = true; + } else { + m_SpecialAbilityKeyDown = false; + } + } + if (m_SpecialAbilityKeyDown && m_MovementKeyDown) { + m_ShiftDashing = true; + } else { + m_ShiftDashing = false; + } + return true; } @@ -129,4 +190,55 @@ bool FirstPersonInputController::OnLockMouse(const Events::LockMou return true; } +template +void FirstPersonInputController::AssaultDashCheck(double dt, bool isJumping, double assaultDashCoolDownMaxTimer) { + m_AssaultDashDoubleTapDeltaTime += dt; + m_AssaultDashCoolDownTimer -= dt; + //cooldown = assaultDashCoolDownMaxTimer sec, pretend the dash lasts 0.25 sec (for friction to do its work) + if (m_AssaultDashCoolDownTimer > (assaultDashCoolDownMaxTimer - 0.25f)) { + m_PlayerIsDashing = true; + } else { + m_PlayerIsDashing = false; + } + + //dashing with shift + if (m_ShiftDashing && m_AssaultDashCoolDownTimer <= 0.0f) { + //player is dashing with shift + //the wanted-direction is set in playermovement already so we dont need to check what direction we want to dash in! + m_AssaultDashCoolDownTimer = assaultDashCoolDownMaxTimer; + m_AssaultDashDoubleTapped = true; + m_AssaultDashDoubleTapDeltaTime = 0.f; + return; + } + + //reset the DoubleTapped state in case we recently doubleTapped (doubletap will only happen during 1 frame) + if (m_AssaultDashDoubleTapped) { + m_AssaultDashDoubleTapped = false; + } + + //dashing with doubletap - check if doubletap to dash enabled + if (!ResourceManager::Load("Input.ini")->Get("Keyboard.DoubleTapToDash", false)) { + return; + } + + //check if we have received a valid doubletap + if (!m_ValidDoubleTap) { + return; + } + m_ValidDoubleTap = false; + + if (!(m_AssaultDashCoolDownTimer <= 0.0f)) { + //if we cant dash at the moment, then just reset the tap-sensitivity-timer + m_AssaultDashDoubleTapDeltaTime = 0.f; + return; + } + //ok, we have a valid tap, lets do it + m_AssaultDashDoubleTapped = true; + m_AssaultDashDoubleTapDeltaTime = 0.f; + m_AssaultDashCoolDownTimer = assaultDashCoolDownMaxTimer; + + Events::DashAbility e; + m_EventBroker->Publish(e); +} + #endif \ No newline at end of file diff --git a/include/Engine/Network/Client.h b/include/Engine/Network/Client.h index 7d1d5bba..be76e265 100644 --- a/include/Engine/Network/Client.h +++ b/include/Engine/Network/Client.h @@ -13,31 +13,54 @@ #include "Network/Network.h" #include "Network/MessageType.h" #include "Network/PlayerDefinition.h" +#include "Network/UDPClient.h" +#include "Network/TCPClient.h" #include "Network/SnapshotDefinitions.h" #include "Core/World.h" #include "Core/EventBroker.h" #include "Core/ConfigFile.h" +#include "Core/EPlayerDeath.h" #include "Input/EInputCommand.h" #include "Core/EPlayerDamage.h" +#include "../Game/Events/EDoubleJump.h" #include "Network/EInterpolate.h" +#include "Network/SnapshotFilter.h" #include "Core/EPlayerSpawned.h" +#include "Network/ESearchForServers.h" + +struct ServerInfo +{ + ServerInfo(std::string a, int b, std::string c, int d) + { + Address = a; Port = b; Name = c; PlayersConnected = d; + } + std::string Address = ""; + int Port = 0; + std::string Name = ""; + int PlayersConnected = 0; +}; class Client : public Network { public: - Client(ConfigFile* config); + Client(World* world, EventBroker* eventBroker); + Client(World* world, EventBroker* eventBroker, std::unique_ptr snapshotFilter); ~Client(); - void Start(World* world, EventBroker* eventBroker) override; + + void Connect(std::string address, int port); void Update() override; private: - // Assio UDP logic - boost::asio::ip::udp::endpoint m_ReceiverEndpoint; - boost::asio::io_service m_IOService; - boost::asio::ip::udp::socket m_Socket; + UDPClient m_Unreliable; + TCPClient m_Reliable; + std::vector m_PlayerSpawnEvents; + void parseSpawnEvents(); + // Save for children + std::unique_ptr m_SnapshotFilter = nullptr; + std::string m_Address; + int m_Port = 0; // Sending message to server logic size_t bytesRead = 0; - char readBuf[INPUTSIZE] = { 0 }; // Packet loss logic PacketID m_PacketID = 0; @@ -45,10 +68,8 @@ private: PacketID m_SendPacketID = 0; // Game logic - World* m_World; std::string m_PlayerName; PlayerID m_PlayerID = -1; - EntityID m_ServerEntityID = std::numeric_limits::max(); bool m_IsConnected = false; EntityWrapper m_LocalPlayer = EntityWrapper::Invalid; // Server Client Lookup map @@ -68,28 +89,32 @@ private: std::vector m_InputCommandBuffer; // Private member functions - void readFromServer(); size_t receive(char* data); - void send(Packet& packet); - void connect(); void disconnect(); void parseMessageType(Packet& packet); - void updateFields(Packet& packet, const ComponentInfo& componentInfo, const EntityID& entityID, const std::string& componentType); - void parseConnect(Packet& packet); + void updateFields(Packet& packet, const ComponentInfo& componentInfo, const EntityID& entityID); + SharedComponentWrapper createSharedComponent(Packet& packet, EntityID entityID, const ComponentInfo& componentInfo); + void ignoreFields(Packet& packet, const ComponentInfo& componentInfo); + void parseUDPConnect(Packet& packet); + void parseTCPConnect(Packet& packet); void parsePlayerConnected(Packet& packet); void parsePing(); + void parseServerlist(Packet& packet); void parseKick(); void parsePlayersSpawned(Packet& packet); void parseEntityDeletion(Packet& packet); + void parsePlayerDamage(Packet& packet); void parseComponentDeletion(Packet& packet); + void parseDoubleJump(Packet& packet); void InterpolateFields(Packet & packet, const ComponentInfo & componentInfo, const EntityID & entityID, const std::string & componentType); void parseSnapshot(Packet& packet); void identifyPacketLoss(); - bool hasServerTimedOut(); + void hasServerTimedOut(); EntityID createPlayer(); void sendInputCommands(); void sendLocalPlayerTransform(); void becomePlayer(); + void displayServerlist(); // Mapping Logic // Returns if local EntityID exist in map bool clientServerMapsHasEntity(EntityID clientEntityID); @@ -99,13 +124,21 @@ private: void deleteFromServerClientMaps(EntityID serverEntityID, EntityID clientEntityID); // Events - EventBroker* m_EventBroker; EventRelay m_EInputCommand; bool OnInputCommand(const Events::InputCommand& e); EventRelay m_EPlayerDamage; bool OnPlayerDamage(const Events::PlayerDamage& e); EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(const Events::PlayerSpawned& e); + EventRelay< Client, Events::SearchForServers> m_ESearchForServers; + EventRelay m_EDoubleJump; + bool OnDoubleJump(Events::DoubleJump & e); + bool OnSearchForServers(const Events::SearchForServers& e); + UDPClient m_ServerlistRequest; + std::vector m_Serverlist; + bool m_SearchingForServers = false; + std::clock_t m_StartSearchTime; + double m_SearchingTime = 2000; // Config I guess }; #endif diff --git a/include/Engine/Network/EInterpolate.h b/include/Engine/Network/EInterpolate.h index 93bf1a5c..79af840d 100644 --- a/include/Engine/Network/EInterpolate.h +++ b/include/Engine/Network/EInterpolate.h @@ -11,8 +11,13 @@ namespace Events struct Interpolate : Event { - EntityID Entity; - boost::shared_array DataArray; + Interpolate(EntityWrapper Entity, SharedComponentWrapper Component) + : Entity(Entity) + , Component(Component) + { } + + EntityWrapper Entity; + SharedComponentWrapper Component; }; } diff --git a/include/Engine/Network/ESearchForServers.h b/include/Engine/Network/ESearchForServers.h new file mode 100644 index 00000000..1b08a8f3 --- /dev/null +++ b/include/Engine/Network/ESearchForServers.h @@ -0,0 +1,12 @@ +#ifndef Events_SearchForServers_h__ +#define Events_SearchForServers_h__ + +#include "Core/Event.h" + +namespace Events +{ + +struct SearchForServers : public Event { }; + +} +#endif diff --git a/include/Engine/Network/MessageType.h b/include/Engine/Network/MessageType.h index 85f22649..00a2a91f 100644 --- a/include/Engine/Network/MessageType.h +++ b/include/Engine/Network/MessageType.h @@ -18,7 +18,10 @@ enum class MessageType OnPlayerSpawned, EntityDeleted, ComponentDeleted, - PlayerTransform + PlayerTransform, + OnDoubleJump, + ServerlistRequest, + Invalid }; #endif diff --git a/include/Engine/Network/Network.h b/include/Engine/Network/Network.h index 874e3377..b4de053e 100644 --- a/include/Engine/Network/Network.h +++ b/include/Engine/Network/Network.h @@ -12,17 +12,22 @@ #include #include -#define INPUTSIZE 32000 +#define BUFFERSIZE 32000 typedef unsigned int PlayerID; typedef unsigned int PacketID; class Network { public: + Network(World* world, EventBroker* eventBroker); virtual ~Network() { }; - virtual void Start(World* m_world, EventBroker *eventBroker) = 0; + virtual void Update() = 0; + protected: + World* m_World; + EventBroker* m_EventBroker; + // For Debug bool isReadingData = false; NetworkData m_NetworkData; @@ -30,9 +35,10 @@ protected: std::clock_t m_SaveDataTimer; unsigned int m_MaxConnections; double m_TimeoutMs; + void logSentData(int bytesSent); + void logReceivedData(int bytesReceived); void saveToFile(); void updateNetworkData(); - void initialize(); }; #endif \ No newline at end of file diff --git a/include/Engine/Network/NetworkClient.h b/include/Engine/Network/NetworkClient.h new file mode 100644 index 00000000..4adc68f5 --- /dev/null +++ b/include/Engine/Network/NetworkClient.h @@ -0,0 +1,24 @@ +#ifndef NetworkClient_h__ +#define NetworkClient_h__ + +#include "Network/Packet.h" +#define BUFFERSIZE 64000 +typedef unsigned int PlayerID; +typedef unsigned int PacketID; + +class NetworkClient +{ +public: + NetworkClient(); + virtual ~NetworkClient(); + virtual void Connect(std::string playerName, std::string address, int port) = 0; + virtual void Disconnect() = 0; + virtual void Receive(Packet& packet) = 0; + virtual void Send(Packet & packet) = 0; + virtual bool IsSocketAvailable() = 0; +protected: + char* m_ReadBuffer; + unsigned int m_BufferSize = BUFFERSIZE; +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Network/NetworkServer.h b/include/Engine/Network/NetworkServer.h new file mode 100644 index 00000000..296c8762 --- /dev/null +++ b/include/Engine/Network/NetworkServer.h @@ -0,0 +1,24 @@ +#ifndef NetworkServer_h__ +#define NetworkServer_h__ +#include +#include "Network/Packet.h" +#include "Network/PlayerDefinition.h" +#define BUFFERSIZE 64000 +typedef unsigned int PlayerID; +typedef unsigned int PacketID; + +class NetworkServer +{ +public: + NetworkServer(); + virtual ~NetworkServer(); + virtual void AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers) = 0; + virtual void Receive(Packet & packet, PlayerDefinition & playerDefinition) = 0; + virtual void Send(Packet & packet, PlayerDefinition & playerDefinition) = 0; + virtual void Send(Packet & packet) = 0; +protected: + char* m_ReadBuffer; + unsigned int m_BufferSize = BUFFERSIZE; +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Network/Packet.h b/include/Engine/Network/Packet.h index 009d8563..b688b8c6 100644 --- a/include/Engine/Network/Packet.h +++ b/include/Engine/Network/Packet.h @@ -49,10 +49,15 @@ public: void WriteData(char* data, int sizeOfData); // Pops the first element as if it was a string. std::string ReadString(); + // Construct a packet + void ReconstructFromData(char* data, size_t SizeOfData); + // Update size of packet variable in header + void UpdateSize(); char* ReadData(int SizeOfData); void ChangePacketID(unsigned int& packetID); size_t Size() { return m_Offset; }; char* Data() { return m_Data; }; + MessageType GetMessageType(); size_t DataReadSize() { return m_ReturnDataOffset; } size_t MaxSize() { return m_MaxPacketSize; } size_t HeaderSize() { return m_HeaderSize; } @@ -64,6 +69,7 @@ private: size_t m_MaxPacketSize = 512; size_t m_HeaderSize = 0; void resizeData(); + void resizeData(int size); }; #endif \ No newline at end of file diff --git a/include/Engine/Network/PlayerDefinition.h b/include/Engine/Network/PlayerDefinition.h index 863948b3..afd5d889 100644 --- a/include/Engine/Network/PlayerDefinition.h +++ b/include/Engine/Network/PlayerDefinition.h @@ -2,6 +2,7 @@ #define PlayerDefinition_h__ #include #include "../Core/Entity.h" +#include struct PlayerDefinition { ::EntityID EntityID = EntityID_Invalid; @@ -9,6 +10,10 @@ struct PlayerDefinition { boost::asio::ip::udp::endpoint Endpoint; unsigned int PacketID; std::clock_t StopTime; + boost::asio::ip::address TCPAddress; + unsigned short TCPPort; + // use for tcp connections + boost::shared_ptr TCPSocket; }; #endif diff --git a/include/Engine/Network/Server.h b/include/Engine/Network/Server.h index 90b9e922..aac4e4c8 100644 --- a/include/Engine/Network/Server.h +++ b/include/Engine/Network/Server.h @@ -5,8 +5,9 @@ #include #include -#include +#include "Network/TCPServer.h" +#include "Network/UDPServer.h" #include "Network/MessageType.h" #include "Network/PlayerDefinition.h" #include "Core/World.h" @@ -16,69 +17,77 @@ #include "Core/EPlayerDamage.h" #include "Network/EPlayerDisconnected.h" #include "Core/EPlayerSpawned.h" +#include "../Game/Events/EDoubleJump.h" #include "Core/EEntityDeleted.h" #include "Core/EComponentDeleted.h" class Server : public Network { public: - Server(); + Server(World* world, EventBroker* eventBroker, int port); ~Server(); - void Start(World* m_world, EventBroker *eventBroker) override; - void Update() override; -private: - // UDP logic - boost::asio::ip::udp::endpoint m_ReceiverEndpoint; - boost::asio::io_service m_IOService; - boost::asio::ip::udp::socket m_Socket; + void Update() override; + +private: + // Network channels + TCPServer m_Reliable; + UDPServer m_Unreliable; + UDPServer m_ServerlistRequest; + // dont forget to set these in the childrens receive logic + boost::asio::ip::address m_Address; + int m_Port = 27666; // Sending messages to client logic std::map m_ConnectedPlayers; + std::vector m_PlayersToDisconnect; // HACK: Fix INPUTSIZE - char readBuffer[INPUTSIZE] = { 0 }; + char readBuffer[BUFFERSIZE] = { 0 }; size_t bytesRead = 0; // time for previouse message std::clock_t previousePingMessage = std::clock(); std::clock_t previousSnapshotMessage = std::clock(); std::clock_t timOutTimer = std::clock(); + // How often we send messages (milliseconds) float pingIntervalMs; float snapshotInterval; int checkTimeOutInterval = 100; int m_NextPlayerID = 0; - + std::vector m_InputCommandsToBroadcast; //Timers std::clock_t m_StartPingTime; - // Game logic - World* m_World; - EventBroker* m_EventBroker; - // Packet loss logic PacketID m_PacketID = 0; PacketID m_PreviousPacketID = 0; // Private member functions - size_t receive(char* data); - void readFromClients(); - void send(PlayerID player, Packet& packet); - void send(Packet& packet); - void broadcast(Packet& packet); + //int receive(char* data); + void reliableBroadcast(Packet& packet); + void unreliableBroadcast(Packet& packet); void sendSnapshot(); + void addPlayersToPacket(Packet& packet, EntityID entityID); void addChildrenToPacket(Packet& packet, EntityID entityID); + void addInputCommandsToPacket(Packet& packet); void sendPing(); void checkForTimeOuts(); void disconnect(PlayerID playerID); void parseMessageType(Packet& packet); - void parseOnInputCommand(Packet& packet); void parseOnPlayerDamage(Packet& packet); - void parseConnect(Packet& packet); - void parseDisconnect(); - void parseClientPing(); - void parsePing(); void identifyPacketLoss(); void kick(PlayerID player); - PlayerID GetPlayerIDFromEndpoint(boost::asio::ip::udp::endpoint endpoint); + PlayerID GetPlayerIDFromEndpoint(); + void parsePlayerTransform(Packet& packet); + void parseOnInputCommand(Packet& packet); + void parseClientPing(); + void parsePing(); + bool parseDoubleJump(Packet& packet); + void parseUDPConnect(Packet& packet); + void parseTCPConnect(Packet& packet); + void parseDisconnect(); + void parseServerlistRequest(boost::asio::ip::udp::endpoint endpoint); + bool shouldSendToClient(EntityWrapper childEntity); + // Debug event EventRelay m_EInputCommand; bool OnInputCommand(const Events::InputCommand& e); @@ -88,7 +97,8 @@ private: bool OnEntityDeleted(const Events::EntityDeleted& e); EventRelay m_EComponentDeleted; bool OnComponentDeleted(const Events::ComponentDeleted& e); - void parsePlayerTransform(Packet& packet); + EventRelay m_EPlayerDamage; + bool OnPlayerDamage(const Events::PlayerDamage& e); }; #endif diff --git a/include/Engine/Network/SnapshotFilter.h b/include/Engine/Network/SnapshotFilter.h new file mode 100644 index 00000000..4e63c4b1 --- /dev/null +++ b/include/Engine/Network/SnapshotFilter.h @@ -0,0 +1,19 @@ +#ifndef SnapshotFilter_h__ +#define SnapshotFilter_h__ + +#include "../Core/EntityWrapper.h" +#include "../Core/ComponentWrapper.h" + +class SnapshotFilter +{ +public: + // Filters an incoming snapshot. + // Modify the component and return true if the component snapshot should be applied. + // Otherwise return false and it will be ignored. + virtual bool FilterComponent(EntityWrapper entity, SharedComponentWrapper& component) + { + return true; + } +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Network/TCPClient.h b/include/Engine/Network/TCPClient.h new file mode 100644 index 00000000..2108fa3d --- /dev/null +++ b/include/Engine/Network/TCPClient.h @@ -0,0 +1,28 @@ +#ifndef TCPClient_h__ +#define TCPClient_h__ + +#include +#include "NetworkClient.h" + +class TCPClient : public NetworkClient +{ +public: + TCPClient(); + ~TCPClient(); + + void Connect(std::string playerName, std::string address, int port); + void Disconnect(); + void Receive(Packet& packet); + void Send(Packet & packet); + bool IsSocketAvailable(); +private: + // Assio TCP logic + boost::asio::ip::tcp::endpoint m_Endpoint; + boost::asio::io_service m_IOService; + std::unique_ptr m_Socket; + size_t readBuffer(); + PacketID m_SendPacketID = 0; + bool m_IsConnected = false; +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Network/TCPServer.h b/include/Engine/Network/TCPServer.h new file mode 100644 index 00000000..55631a22 --- /dev/null +++ b/include/Engine/Network/TCPServer.h @@ -0,0 +1,37 @@ +#ifndef TCPServer_h__ +#define TCPServer_h__ + +#include +#include +#include +#include "NetworkServer.h" + +class TCPServer : public NetworkServer +{ +public: + TCPServer(); + ~TCPServer(); + void AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers); + void Receive(Packet & packet, PlayerDefinition & playerDefinition); + void Send(Packet & packet, PlayerDefinition & playerDefinition); + void Send(Packet & packet); + void Disconnect(); + int Port() { return m_Port; } + std::string Address() { return m_Address; } + +private: + // TCP logic + boost::asio::io_service m_IOService; + std::unique_ptr acceptor; + boost::shared_ptr lastReceivedSocket; + + int readBuffer(PlayerDefinition& playerDefinition); + PlayerID getPlayerIDFromEndpoint(const std::map& connectedPlayers, + boost::asio::ip::address address, unsigned short port); + int GetPort(); + std::string GetAddress(); + int m_Port = 0; + std::string m_Address = ""; +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Network/UDPClient.h b/include/Engine/Network/UDPClient.h new file mode 100644 index 00000000..42c27783 --- /dev/null +++ b/include/Engine/Network/UDPClient.h @@ -0,0 +1,28 @@ +#ifndef UDPClient_h__ +#define UDPClient_h__ + +#include +#include "Network/NetworkClient.h" + +class UDPClient : public NetworkClient +{ +public: + UDPClient(); + ~UDPClient(); + + void Connect(std::string playerName, std::string address, int port); + void Disconnect(); + void Receive(Packet& packet); + void Send(Packet & packet); + void Broadcast(Packet& packet, int port); + bool IsSocketAvailable(); +private: + // Assio UDP logic + boost::asio::io_service m_IOService; + boost::asio::ip::udp::endpoint m_ReceiverEndpoint; + boost::shared_ptr m_Socket; + int readBuffer(); + PacketID m_SendPacketID = 0; +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Network/UDPServer.h b/include/Engine/Network/UDPServer.h new file mode 100644 index 00000000..54f4e327 --- /dev/null +++ b/include/Engine/Network/UDPServer.h @@ -0,0 +1,28 @@ +#ifndef UDPServer_h__ +#define UDPServer_h__ + +#include "NetworkServer.h" +#include + +class UDPServer : public NetworkServer +{ +public: + UDPServer(); + UDPServer(int port); + ~UDPServer(); + void AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers); + void Receive(Packet & packet, PlayerDefinition & playerDefinition); + void Send(Packet & packet, PlayerDefinition & playerDefinition); + void Send(Packet & packet); + void Send(Packet & packet, boost::asio::ip::udp::endpoint endpoint); + void Broadcast(Packet & packet, int port); + bool IsSocketAvailable(); +private: + // UDP logic + boost::asio::io_service m_IOService; + boost::asio::ip::udp::endpoint m_ReceiverEndpoint; + std::unique_ptr m_Socket; + int readBuffer(); +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Rendering/AnimationSystem.h b/include/Engine/Rendering/AnimationSystem.h index fcdcbc92..dbe4b3fc 100644 --- a/include/Engine/Rendering/AnimationSystem.h +++ b/include/Engine/Rendering/AnimationSystem.h @@ -9,12 +9,13 @@ #include "Rendering/Model.h" #include "Rendering/EAnimationComplete.h" #include "Rendering/Skeleton.h" +#include class AnimationSystem : public PureSystem { public: - AnimationSystem(World* world, EventBroker* eventBroker) - : System(world, eventBroker) + AnimationSystem(SystemParams params) + : System(params) , PureSystem("Animation") { @@ -23,7 +24,6 @@ public: virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& animationComponent, double dt) override; private: - }; #endif \ No newline at end of file diff --git a/include/Engine/Rendering/BoneAttachmentSystem.h b/include/Engine/Rendering/BoneAttachmentSystem.h new file mode 100644 index 00000000..55c2a1c8 --- /dev/null +++ b/include/Engine/Rendering/BoneAttachmentSystem.h @@ -0,0 +1,29 @@ +#ifndef BoneAttachmentSystem_h__ +#define BoneAttachmentSystem_h__ + +#include "GLM.h" + +#include "Common.h" +#include "Core/System.h" +#include "Core/ResourceManager.h" +#include "Rendering/Model.h" +#include "Rendering/Skeleton.h" + +//Needs to be a higher orderlevel than AnimationSystem +class BoneAttachmentSystem : public PureSystem +{ +public: + BoneAttachmentSystem(SystemParams params) + : System(params) + , PureSystem("BoneAttachment") + { + + } + ~BoneAttachmentSystem() { } + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& BoneAttachmentComponent, double dt) override; +private: + + +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Rendering/Camera.h b/include/Engine/Rendering/Camera.h index 29dd4626..6130fd01 100644 --- a/include/Engine/Rendering/Camera.h +++ b/include/Engine/Rendering/Camera.h @@ -33,6 +33,8 @@ public: glm::mat4 ViewMatrix() const { return m_ViewMatrix; } void SetViewMatrix(glm::mat4 val); + glm::mat4 BillboardMatrix(); + float AspectRatio() const { return m_AspectRatio; } void SetAspectRatio(float val); diff --git a/include/Engine/Rendering/CubeMapPass.h b/include/Engine/Rendering/CubeMapPass.h new file mode 100644 index 00000000..3cda8cad --- /dev/null +++ b/include/Engine/Rendering/CubeMapPass.h @@ -0,0 +1,27 @@ +#ifndef CubeMapPass_h__ +#define CubeMapPass_h__ + +#include "IRenderer.h" +#include "ShaderProgram.h" + +class CubeMapPass +{ +public: + CubeMapPass(IRenderer* renderer); + ~CubeMapPass() { } + + void LoadTextures(std::string input); + void FillCubeMap(glm::vec3 originPosition); + void GenerateCubeMapTexture(); + + //GLuint CubeMapTexture() const { return m_CubeMapTexture; } + GLuint m_CubeMapTexture = -1; + +private: + IRenderer* m_Renderer; + std::string m_PreviusCubeMapTexture; + + std::vector m_CubeMapTextures; +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Rendering/DrawBloomPass.h b/include/Engine/Rendering/DrawBloomPass.h index 539d6957..07c90e23 100644 --- a/include/Engine/Rendering/DrawBloomPass.h +++ b/include/Engine/Rendering/DrawBloomPass.h @@ -24,6 +24,8 @@ public: void Draw(GLuint texture); + void OnWindowResize(); + //Getters //Return the blurred result of the texture that was sent into draw GLuint GaussianTexture() const { return m_GaussianTexture_vert; } diff --git a/include/Engine/Rendering/DrawColorCorrectionPass.h b/include/Engine/Rendering/DrawColorCorrectionPass.h index fcde73d7..231e2d33 100644 --- a/include/Engine/Rendering/DrawColorCorrectionPass.h +++ b/include/Engine/Rendering/DrawColorCorrectionPass.h @@ -17,7 +17,7 @@ public: void InitializeFrameBuffers(); void InitializeShaderPrograms(); - void Draw(GLuint sceneTexture, GLuint bloomTexture, GLfloat gamma, GLfloat exposure); + void Draw(GLuint sceneTexture, GLuint bloomTexture, GLuint sceneTextureLowRes, GLuint bloomTextureLowRes, GLfloat gamma, GLfloat exposure); private: const IRenderer* m_Renderer; diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index ba65d6e7..15a04426 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -4,57 +4,91 @@ #include "IRenderer.h" #include "DrawFinalPassState.h" #include "LightCullingPass.h" +#include "CubeMapPass.h" #include "FrameBuffer.h" #include "ShaderProgram.h" #include "Util/UnorderedMapVec2.h" +#include "Util/CommonFunctions.h" #include "Texture.h" #include "ShadowPass.h" class DrawFinalPass { public: - DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass, ShadowPass* shadowPass); + DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass, CubeMapPass* cubeMapPass, ShadowPass* shadowPass); ~DrawFinalPass() { } void InitializeTextures(); void InitializeFrameBuffers(); void InitializeShaderPrograms(); - void Draw(RenderScene& scene); + void Draw(RenderScene& scene, GLuint SSAOTexture); void ClearBuffer(); + void OnWindowResize(); //Return the texture that is used in later stages to apply the bloom effect GLuint BloomTexture() const { return m_BloomTexture; } + GLuint BloomTextureLowRes() const { return m_BloomTextureLowRes; } //Return the texture with diffuse and lighting of the scene. GLuint SceneTexture() const { return m_SceneTexture; } + GLuint SceneTextureLowRes() const { return m_SceneTextureLowRes; } + //Return the framebuffer used in the scene rendering stage. FrameBuffer* FinalPassFrameBuffer() { return &m_FinalPassFrameBuffer; } - + FrameBuffer* FinalPassFrameBufferLowRes() { return &m_FinalPassFrameBufferLowRes; } 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 DrawSprites(std::list>&jobs, RenderScene& scene); + void DrawModelRenderQueues(std::list>& jobs, RenderScene& scene, GLuint SSAOTexture); + void DrawShieldToStencilBuffer(std::list>& jobs, RenderScene& scene); + void DrawShieldedModelRenderQueue(std::list>& jobs, RenderScene& scene); + void DrawToDepthBuffer(std::list>& jobs, 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); + void BindExplosionTextures(GLuint shaderHandle, std::shared_ptr& job); + void BindModelTextures(GLuint shaderHandle, std::shared_ptr& job); Texture* m_WhiteTexture; Texture* m_BlackTexture; Texture* m_NeutralNormalTexture; Texture* m_GreyTexture; + Texture* m_ErrorTexture; FrameBuffer m_FinalPassFrameBuffer; + FrameBuffer m_FinalPassFrameBufferLowRes; GLuint m_BloomTexture; GLuint m_SceneTexture; + GLuint m_BloomTextureLowRes; + GLuint m_SceneTextureLowRes; GLuint m_DepthBuffer; + GLuint m_DepthBufferLowRes; + GLuint m_CubeMapTexture; + + //maqke this component based i guess? + GLuint m_ShieldPixelRate = 16; const IRenderer* m_Renderer; const LightCullingPass* m_LightCullingPass; const ShadowPass* m_ShadowPass; + const CubeMapPass* m_CubeMapPass; ShaderProgram* m_ForwardPlusProgram; ShaderProgram* m_ExplosionEffectProgram; + ShaderProgram* m_ExplosionEffectSplatMapProgram; + ShaderProgram* m_SpriteProgram; + ShaderProgram* m_ForwardPlusSplatMapProgram; + ShaderProgram* m_ShieldToStencilProgram; + ShaderProgram* m_FillDepthBufferProgram; + + + ShaderProgram* m_ForwardPlusSkinnedProgram; + ShaderProgram* m_ExplosionEffectSkinnedProgram; + ShaderProgram* m_ExplosionEffectSplatMapSkinnedProgram; + ShaderProgram* m_ForwardPlusSplatMapSkinnedProgram; + ShaderProgram* m_ShieldToStencilSkinnedProgram; + ShaderProgram* m_FillDepthBufferSkinnedProgram; }; #endif \ No newline at end of file diff --git a/include/Engine/Rendering/DrawFinalPassState.h b/include/Engine/Rendering/DrawFinalPassState.h index 10b840e9..91fc4cf4 100644 --- a/include/Engine/Rendering/DrawFinalPassState.h +++ b/include/Engine/Rendering/DrawFinalPassState.h @@ -12,4 +12,11 @@ private: }; +class DrawStencilState : public RenderState +{ +public: + DrawStencilState(GLuint frameBuffer); + ~DrawStencilState(); +}; + #endif \ No newline at end of file diff --git a/include/Engine/Rendering/ExplosionEffectJob.h b/include/Engine/Rendering/ExplosionEffectJob.h index 89b1342b..8f339526 100644 --- a/include/Engine/Rendering/ExplosionEffectJob.h +++ b/include/Engine/Rendering/ExplosionEffectJob.h @@ -15,7 +15,7 @@ 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) + ExplosionEffectJob(ComponentWrapper explosionEffectComponent, ::Model* model, Camera* camera, glm::mat4 matrix, ::RawModel::MaterialProperties matGroup, ComponentWrapper modelComponent, ::World* world, glm::vec4 fillColor, float fillPercentage) : ModelJob(model, camera, matrix, matGroup, modelComponent, world, fillColor, fillPercentage) { ExplosionOrigin = (glm::vec3)explosionEffectComponent["ExplosionOrigin"]; diff --git a/include/Engine/Rendering/IRenderer.h b/include/Engine/Rendering/IRenderer.h index b399aefa..4441bb7d 100644 --- a/include/Engine/Rendering/IRenderer.h +++ b/include/Engine/Rendering/IRenderer.h @@ -32,6 +32,8 @@ public: virtual void SetFullscreen(bool fullscreen) { m_Fullscreen = fullscreen; } bool VSYNC() const { return m_VSYNC; } virtual void SetVSYNC(bool vsync) { m_VSYNC = vsync; } + std::string WindowTitle() const { return m_WindowTitle; } + virtual void SetWindowTitle(const std::string& title) { glfwSetWindowTitle(m_Window, title.c_str()); m_WindowTitle = title; } //Returns screen size excluding window border and header Rectangle GetViewportSize() const { return m_ViewportSize; } virtual void Initialize() = 0; @@ -47,6 +49,7 @@ protected: int m_GLVersion[2]; std::string m_GLVendor; GLFWwindow* m_Window = nullptr; + std::string m_WindowTitle; }; #endif // Renderer_h__ diff --git a/include/Engine/Rendering/LightCullingPass.h b/include/Engine/Rendering/LightCullingPass.h index d8852df0..914fb8bb 100644 --- a/include/Engine/Rendering/LightCullingPass.h +++ b/include/Engine/Rendering/LightCullingPass.h @@ -21,6 +21,7 @@ public: void SetSSBOSizes(); void CullLights(RenderScene& scene); void FillLightList(RenderScene& scene); + void OnWindowResize(); GLuint FrustumSSBO() const { return m_FrustumSSBO; } GLuint LightSSBO() const { return m_LightSSBO; } diff --git a/include/Engine/Rendering/Model.h b/include/Engine/Rendering/Model.h index f751a8cc..4c63b922 100644 --- a/include/Engine/Rendering/Model.h +++ b/include/Engine/Rendering/Model.h @@ -2,8 +2,10 @@ #define Model_h__ #include "Rendering/RawModelCustom.h" +#include "Util/CommonFunctions.h" //#include "Rendering/RawModelAssimp.h" #include "../OpenGL.h" +#include "Core/AABB.h" class Model : public ThreadUnsafeResource { @@ -14,16 +16,19 @@ private: public: ~Model(); - const std::vector& MaterialGroups() const { return m_RawModel->MaterialGroups; } + const std::vector& MaterialGroups() const { return m_RawModel->m_Materials; } const glm::mat4& Matrix() const { return m_RawModel->m_Matrix; } - const std::vector& Vertices() const { return m_RawModel->m_Vertices; } - + const RawModel::Vertex* Vertices() const { return m_RawModel->Vertices(); } + unsigned int NumberOfVertices() const { return m_RawModel->NumVertices(); } + const AABB& Box() const { return m_Box; } + bool IsSkinned() const { return m_RawModel->IsSkinned(); } GLuint VAO; GLuint ElementBuffer; RawModel* m_RawModel; private: - + AABB m_Box; + GLuint VertexBuffer; GLuint NormalBuffer; GLuint TangentNormalsBuffer; diff --git a/include/Engine/Rendering/ModelJob.h b/include/Engine/Rendering/ModelJob.h index 2cb2169c..c2a469d2 100644 --- a/include/Engine/Rendering/ModelJob.h +++ b/include/Engine/Rendering/ModelJob.h @@ -14,41 +14,101 @@ #include "../Core/World.h" #include "../Core/Transform.h" #include "Skeleton.h" +#include "ShaderProgram.h" struct ModelJob : RenderJob { - ModelJob(Model* model, Camera* camera, glm::mat4 matrix, ::RawModel::MaterialGroup matGroup, ComponentWrapper modelComponent, World* world, glm::vec4 fillColor, float fillPercentage) + ModelJob(Model* model, Camera* camera, glm::mat4 matrix, ::RawModel::MaterialProperties matProp, ComponentWrapper modelComponent, World* world, glm::vec4 fillColor, float fillPercentage) : RenderJob() { Model = model; - TextureID = (matGroup.Texture) ? matGroup.Texture->ResourceID : 0; - 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; - StartIndex = matGroup.StartIndex; - EndIndex = matGroup.EndIndex; + ModelID = model->ResourceID; + Type = matProp.type; + ::RawModel::MaterialBasic* matGroup = matProp.material; + switch(matProp.type){ + case ::RawModel::MaterialType::Basic: + if (Model->IsSkinned()) { + ShaderID = ResourceManager::Load("#ForwardPlusSkinnedProgram")->ResourceID; + } + else { + ShaderID = ResourceManager::Load("#ForwardPlusProgram")->ResourceID; + } + TextureID = 0; + break; + case ::RawModel::MaterialType::SingleTextures: + { + if (Model->IsSkinned()) { + ShaderID = ResourceManager::Load("#ForwardPlusSkinnedProgram")->ResourceID; + } + else { + ShaderID = ResourceManager::Load("#ForwardPlusProgram")->ResourceID; + } + ::RawModel::MaterialSingleTextures* singleTextures = static_cast<::RawModel::MaterialSingleTextures*>(matProp.material); + TextureID = (singleTextures->ColorMap.Texture) ? singleTextures->ColorMap.Texture->ResourceID : 0; + if (modelComponent["DiffuseTexture"]) { + DiffuseTexture.push_back(&singleTextures->ColorMap); + } + + if (modelComponent["NormalMap"]) { + NormalTexture.push_back(&singleTextures->NormalMap); + } + + if (modelComponent["SpecularMap"]) { + SpecularTexture.push_back(&singleTextures->SpecularMap); + } + + if (modelComponent["GlowMap"]) { + IncandescenceTexture.push_back(&singleTextures->IncandescenceMap); + } + } + break; + case ::RawModel::MaterialType::SplatMapping: + { + if (Model->IsSkinned()) { + ShaderID = ResourceManager::Load("#ForwardPlusSplatMapSkinnedProgram")->ResourceID; + } + else { + ShaderID = ResourceManager::Load("#ForwardPlusSplatMapProgram")->ResourceID; + } + ::RawModel::MaterialSplatMapping* SplatTextures = static_cast<::RawModel::MaterialSplatMapping*>(matProp.material); + + SplatMap = &SplatTextures->SplatMap; + + TextureID = (SplatTextures->ColorMaps[0].Texture) ? SplatTextures->ColorMaps[0].Texture->ResourceID : 0; + if (modelComponent["DiffuseTexture"]) { + for (auto& texture : SplatTextures->ColorMaps) { + DiffuseTexture.push_back(&texture); + } + } + + if (modelComponent["NormalMap"]) { + for (auto& texture : SplatTextures->NormalMaps) { + NormalTexture.push_back(&texture); + } + } + + if (modelComponent["SpecularMap"]) { + for (auto& texture : SplatTextures->SpecularMaps) { + SpecularTexture.push_back(&texture); + } + } + + if (modelComponent["GlowMap"]) { + for (auto& texture : SplatTextures->IncandescenceMaps) { + IncandescenceTexture.push_back(&texture); + } + } + } + break; + } + DiffuseColor = matGroup->DiffuseColor; + SpecularColor = matGroup->SpecularColor; + IncandescenceColor = matGroup->IncandescenceColor; + StartIndex = matGroup->StartIndex; + EndIndex = matGroup->EndIndex; Matrix = matrix; Color = modelComponent["Color"]; + GlowIntensity = ((double)modelComponent["GlowIntensity"]); Entity = modelComponent.EntityID; glm::vec3 abspos = Transform::AbsolutePosition(world, modelComponent.EntityID); glm::vec3 worldpos = glm::vec3(camera->ViewMatrix() * glm::vec4(abspos, 1)); @@ -57,32 +117,61 @@ struct ModelJob : RenderJob FillColor = fillColor; FillPercentage = fillPercentage; - Skeleton = Model->m_RawModel->m_Skeleton; - if (world->HasComponent(Entity, "Animation") && Skeleton != nullptr) { - auto animationComponent = world->GetComponent(Entity, "Animation"); - Animation = model->m_RawModel->m_Skeleton->GetAnimation(animationComponent["Name"]); - AnimationTime = (double)animationComponent["Time"]; + + if (model->IsSkinned()) { + Skeleton = Model->m_RawModel->m_Skeleton; + + if (Skeleton != nullptr) { + if (world->HasComponent(Entity, "Animation")) { + auto animationComponent = world->GetComponent(Entity, "Animation"); + + for (int i = 1; i <= 3; i++) { + ::Skeleton::AnimationData animationData; + animationData.animation = model->m_RawModel->m_Skeleton->GetAnimation(animationComponent["AnimationName" + std::to_string(i)]); + if (animationData.animation == nullptr) { + continue; + } + animationData.time = (double)animationComponent["Time" + std::to_string(i)]; + animationData.weight = (double)animationComponent["Weight" + std::to_string(i)]; + + Animations.push_back(animationData); + } + } + + if (world->HasComponent(Entity, "AnimationOffset")) { + auto animationOffsetComponent = world->GetComponent(Entity, "AnimationOffset"); + AnimationOffset.animation = model->m_RawModel->m_Skeleton->GetAnimation(animationOffsetComponent["AnimationName"]); + AnimationOffset.time = (double)animationOffsetComponent["Time"]; + } else { + AnimationOffset.animation = nullptr; + } + } } + }; unsigned int TextureID; unsigned int ShaderID; + unsigned int ModelID; + ::RawModel::MaterialType Type; EntityID Entity; glm::mat4 Matrix; - const Texture* DiffuseTexture; - const Texture* NormalTexture; - const Texture* SpecularTexture; - const Texture* IncandescenceTexture; + const ::RawModel::TextureProperties* SplatMap; + std::vector DiffuseTexture; + std::vector NormalTexture; + std::vector SpecularTexture; + std::vector IncandescenceTexture; float Shininess = 0.f; glm::vec4 Color; const ::Model* Model = nullptr; ::Skeleton* Skeleton = nullptr; - const ::Skeleton::Animation* Animation = nullptr; - - float AnimationTime = 0.f; + std::vector<::Skeleton::AnimationData> Animations; + ::Skeleton::AnimationOffset AnimationOffset; + + float GlowIntensity = 8.0; glm::vec4 DiffuseColor; glm::vec4 SpecularColor; glm::vec4 IncandescenceColor; @@ -95,7 +184,7 @@ struct ModelJob : RenderJob void CalculateHash() override { - Hash = TextureID; + Hash = ShaderID << 20 + ModelID << 10 + TextureID; } }; diff --git a/include/Engine/Rendering/PNG.h b/include/Engine/Rendering/PNG.h index f2cbf157..a45e9e7c 100644 --- a/include/Engine/Rendering/PNG.h +++ b/include/Engine/Rendering/PNG.h @@ -6,9 +6,10 @@ #include #include "../Common.h" +#include "../Core/ResourceManager.h" #include "Image.h" -class PNG : public Image +class PNG : public Image, public Resource { public: PNG(std::string path); diff --git a/include/Engine/Rendering/PickingPass.h b/include/Engine/Rendering/PickingPass.h index da3ed31b..f6434781 100644 --- a/include/Engine/Rendering/PickingPass.h +++ b/include/Engine/Rendering/PickingPass.h @@ -22,6 +22,8 @@ public: void Draw(RenderScene& scene); void ClearPicking(); + void OnWindowResize(); + //Getters const ShaderProgram& PickingProgram() const { return *m_PickingProgram; } //const std::unordered_map& PickingColorsToEntity() const { return m_PickingColorsToEntity; } @@ -40,6 +42,7 @@ private: const IRenderer* m_Renderer; ShaderProgram* m_PickingProgram; + ShaderProgram* m_PickingSkinnedProgram; Camera* m_Camera; struct PickingInfo diff --git a/include/Engine/Rendering/RawModelCustom.h b/include/Engine/Rendering/RawModelCustom.h index e903f49f..ebf8da2b 100644 --- a/include/Engine/Rendering/RawModelCustom.h +++ b/include/Engine/Rendering/RawModelCustom.h @@ -33,18 +33,27 @@ protected: public: ~RawModelCustom(); - struct Vertex - { - glm::vec3 Position; - glm::vec3 Normal; - glm::vec3 Tangent; - glm::vec3 BiNormal; - glm::vec2 TextureCoords; + struct Vertex + { + glm::vec3 Position; + glm::vec3 Normal; + glm::vec3 Tangent; + glm::vec3 BiNormal; + glm::vec2 TextureCoords; + }; + + struct SkinedVertex : public Vertex { glm::vec4 BoneIndices; glm::vec4 BoneWeights; }; - struct MaterialGroup + struct TextureProperties { + std::string TexturePath; + glm::vec2 UVRepeat; + Texture* Texture; + }; + + struct MaterialBasic { float SpecularExponent; float ReflectionFactor; @@ -54,25 +63,69 @@ public: unsigned int StartIndex; unsigned int EndIndex; //float Transparency; - std::string TexturePath; - std::shared_ptr<::Texture> Texture; - std::string NormalMapPath; - std::shared_ptr<::Texture> NormalMap; - std::string SpecularMapPath; - std::shared_ptr<::Texture> SpecularMap; - std::string IncandescenceMapPath; - std::shared_ptr<::Texture> IncandescenceMap; }; - std::vector MaterialGroups; + struct MaterialSplatMapping : public MaterialBasic + { + TextureProperties SplatMap; + std::vector ColorMaps; + std::vector NormalMaps; + std::vector SpecularMaps; + std::vector IncandescenceMaps; + }; + + struct MaterialSingleTextures : public MaterialBasic + { + TextureProperties ColorMap; + TextureProperties NormalMap; + TextureProperties SpecularMap; + TextureProperties IncandescenceMap; + }; + + enum class MaterialType { Basic = 1, SplatMapping, SingleTextures }; + + struct MaterialProperties { + MaterialType type; + MaterialBasic* material; + }; + + const Vertex* Vertices() const { + if (hasSkin) { + return m_SkinedVertices.data(); + } else { + return m_Vertices.data(); + } + }; + + unsigned int VertexSize() const { + if (hasSkin) { + return sizeof(SkinedVertex); + } + else { + return sizeof(Vertex); + } + }; + + unsigned int NumVertices() const { + if (hasSkin) { + return m_SkinedVertices.size(); + } else { + return m_Vertices.size(); + } + }; + + bool IsSkinned() const { return hasSkin; }; + + std::vector m_Materials; - std::vector m_Vertices; std::vector m_Indices; Skeleton* m_Skeleton = nullptr; glm::mat4 m_Matrix; private: - + bool hasSkin; + std::vector m_Vertices; + std::vector m_SkinedVertices; void ReadMeshFile(std::string filePath); void ReadMeshFileHeader(std::size_t& offset, char* fileData); @@ -83,13 +136,17 @@ private: void ReadMaterialFile(std::string filePath); void ReadMaterials(std::size_t& offset, char* fileData, const unsigned int& fileByteSize); void ReadMaterialSingle(std::size_t& offset, char* fileData, const unsigned int& fileByteSize); + void ReadMaterialBasic(MaterialBasic* Material, std::size_t& offset, char* fileData, const unsigned int& fileByteSize); + void ReadMaterialSingleTexture(MaterialSingleTextures* Material, std::size_t& offset, char* fileData, const unsigned int& fileByteSize); + void ReadMaterialSplatMapping(MaterialSplatMapping* Material, std::size_t& offset, char* fileData, const unsigned int& fileByteSize); + void ReadMaterialTextureProperties(TextureProperties& texture, std::size_t& offset, char* fileData, const unsigned int& fileByteSize); void ReadAnimationFile(std::string filePath); void ReadAnimationBindPoses(std::size_t& offset, char* fileData, const unsigned int& fileByteSize); void ReadAnimationJoint(std::size_t& offset, char* fileData, const unsigned int& fileByteSize); void ReadAnimationClips(std::size_t& offset, char* fileData, const unsigned int& fileByteSize, unsigned int numberOfClips); void ReadAnimationClipSingle(std::size_t& offset, char* fileData, const unsigned int& fileByteSize, unsigned int clipIndex); - void ReadAnimationKeyFrame(std::size_t& offset, char* fileData, const unsigned int& fileByteSize, unsigned int numberOfJoints, Skeleton::Animation& animation); + void ReadAnimationKeyFrame(std::size_t& offset, char* fileData, const unsigned int& fileByteSize, std::vector& 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 af9d928e..647adab8 100644 --- a/include/Engine/Rendering/RenderQueue.h +++ b/include/Engine/Rendering/RenderQueue.h @@ -15,26 +15,36 @@ #include "PointLightJob.h" #include "DirectionalLightJob.h" #include "ExplosionEffectJob.h" +#include "SpriteJob.h" struct RenderScene { ::Camera* Camera = nullptr; - std::list> OpaqueObjects; - std::list> TransparentObjects; - std::list> PointLightJobs; - std::list> TextJobs; - std::list> DirectionalLightJobs; + struct Queues { + std::list> OpaqueObjects; + std::list> TransparentObjects; + std::list> OpaqueShieldedObjects; + std::list> TransparentShieldedObjects; + std::list> ShieldObjects; + std::list> SpriteJob; + std::list> PointLight; + std::list> Text; + std::list> DirectionalLight; + } Jobs; + Rectangle Viewport; bool ClearDepth = false; glm::vec4 AmbientColor; void Clear() { - OpaqueObjects.clear(); - TransparentObjects.clear(); - PointLightJobs.clear(); - TextJobs.clear(); - DirectionalLightJobs.clear(); + Jobs.OpaqueObjects.clear(); + Jobs.TransparentObjects.clear(); + Jobs.OpaqueShieldedObjects.clear(); + Jobs.TransparentShieldedObjects.clear(); + Jobs.ShieldObjects.clear(); + Jobs.SpriteJob.clear(); + Jobs.DirectionalLight.clear(); } }; diff --git a/include/Engine/Rendering/RenderState.h b/include/Engine/Rendering/RenderState.h index 688ef520..c1886247 100644 --- a/include/Engine/Rendering/RenderState.h +++ b/include/Engine/Rendering/RenderState.h @@ -2,6 +2,7 @@ #define RenderState_h__ #include +#include #include "../Common.h" #include "../OpenGL.h" #include "../GLM.h" @@ -19,6 +20,9 @@ public: bool BindFramebuffer(GLint framebuffer); bool BlendEquation(GLenum mode); bool BlendFunc(GLenum sfactor, GLenum dfactor); + bool StencilOp(GLenum sfail, GLenum dpfail, GLenum dppass); + bool StencilFunc(GLenum func, GLint ref, GLuint mask); + bool StencilMask(GLuint mask); bool DepthMask(GLboolean flag); private: diff --git a/include/Engine/Rendering/RenderSystem.h b/include/Engine/Rendering/RenderSystem.h index d64147b9..7580d654 100644 --- a/include/Engine/Rendering/RenderSystem.h +++ b/include/Engine/Rendering/RenderSystem.h @@ -16,11 +16,14 @@ #include "PointLightJob.h" #include "../Core/Transform.h" #include "../Core/EPlayerSpawned.h" +#include "../Core/Octree.h" +#include "../Collision/EntityAABB.h" +#include "../Core/ConfigFile.h" class RenderSystem : public ImpureSystem { public: - RenderSystem(World* world, EventBroker* eventBrokerer, const IRenderer* renderer, RenderFrame* renderFrame); + RenderSystem(SystemParams params, const IRenderer* renderer, RenderFrame* renderFrame, Octree* frustumCullOctree); ~RenderSystem(); virtual void Update(double dt) override; @@ -29,9 +32,9 @@ private: const IRenderer* m_Renderer; RenderFrame* m_RenderFrame; Camera* m_Camera; - World* m_World; EntityWrapper m_CurrentCamera = EntityWrapper::Invalid; EntityWrapper m_LocalPlayer = EntityWrapper::Invalid; + Octree* m_Octree; EventRelay m_ESetCamera; bool OnSetCamera(Events::SetCamera &event); @@ -40,14 +43,17 @@ private: EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(Events::PlayerSpawned& e); - void fillModels(std::list>& opaqueJobs, std::list>& transparentJobs); + void fillModels(RenderScene::Queues &jobs); void fillText(std::list>& jobs, World* world); void fillPointLights(std::list>& jobs, World* world); void fillDirectionalLights(std::list>& jobs, World* world); void fillLight(std::list>& jobs); + void fillSprites(std::list>& jobs, World* world); + + bool isEntityVisible(EntityWrapper& entity); + bool isChildOfACamera(EntityWrapper entity); bool isChildOfCurrentCamera(EntityWrapper entity); - }; #endif \ No newline at end of file diff --git a/include/Engine/Rendering/Renderer.h b/include/Engine/Rendering/Renderer.h index 74338e40..db5219f2 100644 --- a/include/Engine/Rendering/Renderer.h +++ b/include/Engine/Rendering/Renderer.h @@ -16,6 +16,8 @@ #include "DrawScreenQuadPass.h" #include "DrawBloomPass.h" #include "DrawColorCorrectionPass.h" +#include "SSAOPass.h" +#include "CubeMapPass.h" #include "../Core/EventBroker.h" #include "ImGuiRenderPass.h" #include "Camera.h" @@ -23,9 +25,13 @@ #include "imgui/imgui.h" #include "TextPass.h" #include "ShadowPass.h" +#include "Util/CommonFunctions.h" +#include "Core/PerformanceTimer.h" class Renderer : public IRenderer { + static void glfwFrameBufferCallback(GLFWwindow* window, int width, int height); + public: Renderer(EventBroker* eventBroker) : m_EventBroker(eventBroker) @@ -37,8 +43,12 @@ public: virtual PickData Pick(glm::vec2 screenCoord) override; + private: //----------------------Variables----------------------// + + static std::unordered_map m_WindowToRenderer; + EventBroker* m_EventBroker; TextPass* m_TextPass; @@ -50,6 +60,14 @@ private: Model* m_UnitSphere; int m_DebugTextureToDraw = 0; + int m_CubeMapTexture = 0; + bool m_ResizeWindow = false; + float m_SSAO_Radius = 1.0f; + float m_SSAO_Bias = 0.05f; + float m_SSAO_Contrast = 1.5f; + float m_SSAO_IntensityScale = 1.0f; + int m_SSAO_NumOfSamples = 24; + int m_SSAO_NumOfTurns = 7; PickingPass* m_PickingPass; LightCullingPass* m_LightCullingPass; @@ -59,6 +77,8 @@ private: DrawBloomPass* m_DrawBloomPass; DrawColorCorrectionPass* m_DrawColorCorrectionPass; ShadowPass* m_ShadowPass; + SSAOPass* m_SSAOPass; + CubeMapPass* m_CubeMapPass; //----------------------Functions----------------------// void InitializeWindow(); diff --git a/include/Engine/Rendering/SSAOPass.h b/include/Engine/Rendering/SSAOPass.h new file mode 100644 index 00000000..792d1d82 --- /dev/null +++ b/include/Engine/Rendering/SSAOPass.h @@ -0,0 +1,63 @@ +#ifndef SSAOPass_h__ +#define SSAOPass_h__ + +#include "IRenderer.h" +#include "SSAOPassState.h" +//#include "LightCullingPass.h" Finalpass om den skall skickas in +#include "FrameBuffer.h" +#include "ShaderProgram.h" +#include "DrawBloomPass.h" +//#include "Util/UnorderedMapVec2.h" +#include "Texture.h" + +class SSAOPass +{ +public: + SSAOPass(IRenderer* rendere); + ~SSAOPass() { + delete m_DrawBloomPass; + }; + + void Draw(GLuint depthBuffer, Camera* camera); + void Setting(float radius, float bias, float contrast, float intensityScale, int numOfSamples, int NumOfTurns); + void ClearBuffer(); + void OnWindowResize(); + + //Return the SSAO of the texture sent to Draw + GLuint SSAOTexture() const { return m_DrawBloomPass->GaussianTexture(); } + +private: + void InitializeTexture(); + void InitializeFrameBuffer(); + void InitializeShaderProgram(); + void InitializeBuffer(); + + void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const; + + //void blurHorizontal(GLuint depthBuffer); + //void blurVertical(GLuint depthBuffer); + + Model* m_ScreenQuad; + + const IRenderer* m_Renderer; + + float m_Radius; + float m_Bias; + float m_Contrast; + float m_IntensityScale; + int m_NumOfSamples; + int m_NumOfTurns; + + GLuint m_SSAOTexture; + FrameBuffer m_SSAOFramBuffer; + + GLuint m_SSAOViewSpaceZTexture; + FrameBuffer m_SSAOViewSpaceZFramBuffer; + + ShaderProgram* m_SSAOProgram; + ShaderProgram* m_SSAOViewSpaceZProgram; + + DrawBloomPass* m_DrawBloomPass; +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Rendering/SSAOPassState.h b/include/Engine/Rendering/SSAOPassState.h new file mode 100644 index 00000000..115fdcf7 --- /dev/null +++ b/include/Engine/Rendering/SSAOPassState.h @@ -0,0 +1,15 @@ +#ifndef SSAOPassState_h__ +#define SSAOPassState_h__ + +#include "Rendering/RenderState.h" + +class SSAOPassState : public RenderState +{ +public: + SSAOPassState(); + ~SSAOPassState(); +private: + +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Rendering/Skeleton.h b/include/Engine/Rendering/Skeleton.h index 3b89b89b..28a5ef6a 100644 --- a/include/Engine/Rendering/Skeleton.h +++ b/include/Engine/Rendering/Skeleton.h @@ -5,6 +5,7 @@ #include "Common.h" #include "../GLM.h" #include +#include //struct Bone //{ @@ -53,22 +54,39 @@ public: { struct BoneProperty { - int ID; - glm::vec3 Position; - glm::quat Rotation; + glm::vec3 Position; + glm::quat Rotation; glm::vec3 Scale = glm::vec3(1); }; - int Index = 0; - double Time = 0.0; - std::map BoneProperties; + int Index = 0; + double Time = 0.0; + BoneProperty BoneProperties; }; - - std::string Name; - double Duration; - std::vector Keyframes; + std::string Name; + double Duration; + std::map> JointAnimations; }; + struct AnimationData + { + const Animation* animation; + float time; + float weight; + }; + + struct JointFrameTransform { + glm::vec3 PositionInterp = glm::vec3(0); + glm::quat RotationInterp = glm::quat(); + glm::vec3 ScaleInterp = glm::vec3(0); + float Weight; + }; + + struct AnimationOffset { + const Animation* animation; + float time; + }; + Skeleton() { } ~Skeleton(); @@ -82,17 +100,29 @@ public: int GetBoneID(std::string name); - const Animation* GetAnimation(std::string name); - std::vector GetFrameBones(const Animation& animation, double time, bool noRootMotion = false); - void AccumulateBoneTransforms(bool noRootMotion, const Animation::Keyframe& currentFrame, const Animation::Keyframe& nextFrame, float progress, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix); - void PrintSkeleton(); + std::vector GetFrameBones(std::vector animations, AnimationOffset animationOffset, bool noRootMotion = false); + std::vector GetFrameBones(std::vector animations, bool noRootMotion = false); + + const Animation* GetAnimation(std::string name); + + void AccumulateBoneTransforms(bool noRootMotion, std::vector animations, std::map& frameBones, const Bone* bone, glm::mat4 parentMatrix); + void AccumulateBoneTransforms(bool noRootMotion, std::vector animations, AnimationOffset animationOffset, std::map& frameBones, const Bone* bone, glm::mat4 parentMatrix); + + void PrintSkeleton(); void PrintSkeleton(const Bone* parent, int depthCount); std::map Animations; -private: - std::map m_BonesByName; + glm::mat4 GetBoneTransform(const Bone* bone, const Animation* animation, float time, glm::mat4 childMatrix); + glm::mat4 GetBoneTransform(bool noRootMotion, const Bone* bone, std::vector animations, AnimationOffset animationOffset, glm::mat4 childMatrix); + glm::mat4 GetBoneTransform(bool noRootMotion, const Bone* bone, std::vector animations, glm::mat4 childMatrix); + int GetKeyframe(const Animation& animation, double time); - int GetKeyframe(const Animation& animation, double time); +private: + + glm::mat4 GetOffsetTransform(const Bone* bone, AnimationOffset animationOffset); + + std::map m_BonesByName; + }; #endif diff --git a/include/Engine/Rendering/SpriteJob.h b/include/Engine/Rendering/SpriteJob.h new file mode 100644 index 00000000..25c2d5cb --- /dev/null +++ b/include/Engine/Rendering/SpriteJob.h @@ -0,0 +1,78 @@ +#ifndef SpriteJob_h__ +#define SpriteJob_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" +#include "../Core/Transform.h" +#include "Skeleton.h" + +struct SpriteJob : RenderJob +{ + SpriteJob(ComponentWrapper cSprite, Camera* camera, glm::mat4 matrix, World* world, glm::vec4 fillColor, float fillPercentage, bool depthSorted, bool isIndicator) + : RenderJob() + { + Model = ResourceManager::Load<::Model>("Models/Core/UnitQuad.mesh"); + ::RawModel::MaterialProperties matProp = Model->MaterialGroups().front(); + TextureID = 0; + + DiffuseTexture = CommonFunctions::LoadTexture(cSprite["DiffuseTexture"], true); + + IncandescenceTexture = CommonFunctions::LoadTexture(cSprite["GlowMap"], true); + + StartIndex = matProp.material->StartIndex; + EndIndex = matProp.material->EndIndex; + Matrix = matrix; + Color = cSprite["Color"]; + Entity = cSprite.EntityID; + Position = Transform::AbsolutePosition(world, cSprite.EntityID); + Depth = 0; + if (depthSorted) { + glm::vec3 viewpos = glm::vec3(camera->ViewMatrix() * glm::vec4(Position, 1)); + Depth = viewpos.z; + } + World = world; + Pickable = world->HasComponent(cSprite.EntityID, "Button"); + IsIndicator = isIndicator; + + FillColor = fillColor; + FillPercentage = fillPercentage; + }; + + unsigned int TextureID; + + EntityID Entity; + glm::mat4 Matrix; + const Texture* DiffuseTexture; + const Texture* NormalTexture; + const Texture* SpecularTexture; + const Texture* IncandescenceTexture; + float Shininess = 0.f; + glm::vec4 Color; + glm::vec3 Position; + const ::Model* Model = nullptr; + unsigned int StartIndex = 0; + unsigned int EndIndex = 0; + World* World; + + bool Pickable; + bool IsIndicator = false; + + glm::vec4 FillColor = glm::vec4(0); + float FillPercentage = 0.0; + + void CalculateHash() override + { + Hash = TextureID; + } +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Rendering/Texture.h b/include/Engine/Rendering/Texture.h index 0fe650b3..d159e636 100644 --- a/include/Engine/Rendering/Texture.h +++ b/include/Engine/Rendering/Texture.h @@ -18,6 +18,7 @@ public: void Bind(GLenum textureUnit = GL_TEXTURE0); GLuint m_Texture = 0; + unsigned char* Data = nullptr; }; diff --git a/include/Engine/Rendering/Util/CommonFunctions.h b/include/Engine/Rendering/Util/CommonFunctions.h index b262568c..e178f52d 100644 --- a/include/Engine/Rendering/Util/CommonFunctions.h +++ b/include/Engine/Rendering/Util/CommonFunctions.h @@ -4,14 +4,11 @@ #include "../../Common.h" #include "../../OpenGL.h" #include "../../GLM.h" +#include "../Texture.h" -class CommonFuntions -{ -public: - CommonFuntions() = delete; - -private: - +namespace CommonFunctions +{ +Texture* LoadTexture(std::string path, bool threaded); }; #endif \ No newline at end of file diff --git a/include/Engine/Sound/EPlayQueueOnEntity.h b/include/Engine/Sound/EPlayQueueOnEntity.h new file mode 100644 index 00000000..e880819a --- /dev/null +++ b/include/Engine/Sound/EPlayQueueOnEntity.h @@ -0,0 +1,18 @@ +#ifndef Events_PlayQueueOnEntity_h__ +#define Events_PlayQueueOnEntity_h__ + +#include "../Core/Event.h" +#include "../Core/EntityWrapper.h" + +namespace Events +{ + +struct PlayQueueOnEntity : public Event +{ + EntityWrapper Emitter; + std::vector FilePaths; +}; + +} + +#endif diff --git a/include/Engine/Sound/Sound.h b/include/Engine/Sound/Sound.h index 6b2aac04..cccbdf07 100644 --- a/include/Engine/Sound/Sound.h +++ b/include/Engine/Sound/Sound.h @@ -1,6 +1,9 @@ #ifndef Sound_h__ #define Sound_h__ +#include +#include + #include "Core/ResourceManager.h" class Sound : public Resource diff --git a/include/Engine/Sound/SoundSystem.h b/include/Engine/Sound/SoundManager.h similarity index 57% rename from include/Engine/Sound/SoundSystem.h rename to include/Engine/Sound/SoundManager.h index b9cc2589..5b027c62 100644 --- a/include/Engine/Sound/SoundSystem.h +++ b/include/Engine/Sound/SoundManager.h @@ -1,17 +1,23 @@ -#ifndef SoundSystem_h__ -#define SoundSystem_h__ +#ifndef SoundManager_h__ +#define SoundManager_h__ #include +#include #include "glm/common.hpp" #include "glm/gtx/rotate_vector.hpp" // Calculate Up vector #include "OpenAL/al.h" #include "OpenAL/alc.h" +#include "imgui/imgui.h" + #include "Core/World.h" #include "Core/EventBroker.h" +#include "../Engine/Core/ResourceManager.h" +#include "../Engine/Core/ConfigFile.h" #include "Core/Transform.h" // Absolute transform #include "Sound/Sound.h" +#include "../Engine/Sound/EPlayQueueOnEntity.h" #include "Sound/EPlaySoundOnEntity.h" #include "Sound/EPlaySoundOnPosition.h" #include "Sound/EPlayBackgroundMusic.h" @@ -20,6 +26,11 @@ #include "Sound/EStopSound.h" #include "Sound/ESetBGMGain.h" #include "Sound/ESetSFXGain.h" +#include "Core/EPause.h" +#include "Core/EComponentAttached.h" +#include "../Core/EPlayerSpawned.h" + +typedef std::pair> QueuedBuffers; enum class SoundType { SFX, @@ -34,14 +45,15 @@ struct Source SoundType Type; }; -class SoundSystem +class SoundManager { public: - SoundSystem() { } - SoundSystem(World* world, EventBroker* eventBroker, bool editorMode); - ~SoundSystem(); + SoundManager() { } + SoundManager(World* world, EventBroker* eventBroker); + ~SoundManager(); // Update emitters / listener void Update(double dt); + private: // Help functions for working with OpenaAL void setListenerPos(glm::vec3 pos) { alListener3f(AL_POSITION, pos.x, pos.y, pos.z); }; @@ -56,46 +68,62 @@ private: // Logic void initOpenAL(); void updateEmitters(double dt); - void updateListener(double dt); void deleteInactiveEmitters(); - void addNewEmitters(double dt); - Source* createSource(std::string filePath); - void playSound(Source* source); - void stopSound(Source* source); void stopEmitters(); + void updateListener(double dt); ALenum getSourceState(ALuint source); void setGain(Source* source, float gain); - void setSoundProperties(ALuint source, ComponentWrapper* soundComponent); + void setSoundProperties(Source* source, ComponentWrapper* soundComponent); + + // Specific logic + void playSound(Source* source); + // Need to be the same format (sample rate etc) + void playQueue(QueuedBuffers qb); + void stopSound(Source* source); + Source* createSource(std::string filePath); + std::unordered_map m_Sources; + + // Logic + World* m_World = nullptr; + EventBroker* m_EventBroker = nullptr; // OpenAL system variables ALCdevice* m_ALCdevice = nullptr; ALCcontext* m_ALCcontext = nullptr; - // Logic - World* m_World = nullptr; - EventBroker* m_EventBroker = nullptr; - std::unordered_map m_Sources; float m_BGMVolumeChannel = 1.0f; - float m_SFXVolumeChannel = 1.f; - bool m_EditorEnabled = false; - + float m_SFXVolumeChannel = 1.0f; + EntityWrapper m_LocalPlayer = EntityWrapper(); + // Events - EventRelay m_EPlaySoundOnEntity; + EventRelay m_EPlaySoundOnEntity; bool OnPlaySoundOnEntity(const Events::PlaySoundOnEntity &e); - EventRelay m_EPlaySoundOnPosition; + EventRelay m_EPlaySoundOnPosition; bool OnPlaySoundOnPosition(const Events::PlaySoundOnPosition &e); - EventRelay m_EPlayBackgroundMusic; + EventRelay m_EPlayBackgroundMusic; bool OnPlayBackgroundMusic(const Events::PlayBackgroundMusic &e); - EventRelay m_EPauseSound; + EventRelay m_EPauseSound; bool OnPauseSound(const Events::PauseSound &e); - EventRelay m_EStopSound; + EventRelay m_EStopSound; bool OnStopSound(const Events::StopSound &e); - EventRelay m_EContinueSound; + EventRelay m_EContinueSound; bool OnContinueSound(const Events::ContinueSound &e); - EventRelay m_ESetBGMGain; - bool OnSetBGMGain(const Events::SetBGMGain &e); // Not tested - EventRelay m_ESetSFXGain; - bool OnSetSFXGain(const Events::SetSFXGain &e); // Not tested + EventRelay m_ESetBGMGain; + bool OnSetBGMGain(const Events::SetBGMGain &e); + EventRelay m_ESetSFXGain; + bool OnSetSFXGain(const Events::SetSFXGain &e); + EventRelay m_EComponentAttached; + bool OnComponentAttached(const Events::ComponentAttached &e); + EventRelay m_EPause; + bool OnPause(const Events::Pause &e); + EventRelay m_EResume; + bool OnResume(const Events::Resume &e); + EventRelay m_EPlayerSpawned; + bool OnPlayerSpawned(const Events::PlayerSpawned &e); + EventRelay m_EPlayQueueOnEntity; + bool OnPlayQueueOnEntity(const Events::PlayQueueOnEntity &e); + + }; #endif \ No newline at end of file diff --git a/include/Game/Events/EDashAbility.h b/include/Game/Events/EDashAbility.h new file mode 100644 index 00000000..62a2b935 --- /dev/null +++ b/include/Game/Events/EDashAbility.h @@ -0,0 +1,13 @@ +#ifndef Events_DashAbility_h__ +#define Events_DashAbility_h__ + +#include "Core/Event.h" + +namespace Events +{ + +struct DashAbility : public Event { }; + +} + +#endif \ No newline at end of file diff --git a/include/Game/Events/EDoubleJump.h b/include/Game/Events/EDoubleJump.h new file mode 100644 index 00000000..f5cad1fd --- /dev/null +++ b/include/Game/Events/EDoubleJump.h @@ -0,0 +1,16 @@ +#ifndef Events_DoubleJump_h__ +#define Events_DoubleJump_h__ + +#include "Core/Event.h" + +namespace Events +{ + +struct DoubleJump : public Event +{ + EntityID entityID; +}; + +} + +#endif diff --git a/include/Game/ExplosionEffectSystem.h b/include/Game/ExplosionEffectSystem.h deleted file mode 100644 index 061ad221..00000000 --- a/include/Game/ExplosionEffectSystem.h +++ /dev/null @@ -1,24 +0,0 @@ -#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 37267a68..06fd4703 100644 --- a/include/Game/Game.h +++ b/include/Game/Game.h @@ -1,12 +1,13 @@ #ifndef Game_h__ #define Game_h__ +#include + #include "Core/ResourceManager.h" #include "Core/ConfigFile.h" #include "Core/EventBroker.h" #include "Rendering/Renderer.h" #include "Core/InputManager.h" -#include "GUI/Frame.h" #include "Core/World.h" #include "Input/InputProxy.h" #include "Input/KeyboardInputHandler.h" @@ -14,7 +15,7 @@ #include "Core/EKeyDown.h" #include "Core/EntityFilePreprocessor.h" #include "Core/SystemPipeline.h" -#include "ExplosionEffectSystem.h" +#include "Systems/ExplosionEffectSystem.h" #include "Editor/EditorSystem.h" #include "Core/EntityFile.h" #include "Rendering/RenderSystem.h" @@ -30,7 +31,11 @@ #include "Network/Client.h" // Sound -#include "Sound/SoundSystem.h" +#include "Sound/SoundManager.h" +#include "Systems/SoundSystem.h" + +//Performance +#include "Core/PerformanceTimer.h" class Game { @@ -42,37 +47,29 @@ public: void Tick(); private: - double m_LastTime; + std::string m_NetworkAddress; + int m_NetworkPort = 0; + ConfigFile* m_Config = nullptr; EventBroker* m_EventBroker; IRenderer* m_Renderer; InputManager* m_InputManager; InputProxy* m_InputProxy; - GUI::Frame* m_FrameStack; World* m_World; Octree* m_OctreeCollision; Octree* m_OctreeTrigger; Octree* m_OctreeFrustrumCulling; SystemPipeline* m_SystemPipeline; RenderFrame* m_RenderFrame; - // Network variables - boost::thread m_NetworkThread; + Client* m_NetworkClient = nullptr; + Server* m_NetworkServer = nullptr; + SoundManager* m_SoundManager; + double m_LastTime; - // Network methods - void networkFunction(); - Network* m_ClientOrServer; - bool m_IsClientOrServer = false; - - // Sound - SoundSystem* m_SoundSystem; - - //EventRelay m_EInputCommand; - //bool debugOnInputCommand(const Events::InputCommand& e); - - void debugInitialize(); - void debugTick(double dt); - EventRelay m_EKeyDown; + bool m_IsClient = false; + bool m_IsServer = false; + int parseArgs(int argc, char* argv[]); }; #endif diff --git a/include/Game/MiniDump.h b/include/Game/MiniDump.h new file mode 100644 index 00000000..4ad4548d --- /dev/null +++ b/include/Game/MiniDump.h @@ -0,0 +1,8 @@ +#ifndef MiniDump_h__ +#define MiniDump_h__ + +#include + +void WINAPI Create_Dump(PEXCEPTION_POINTERS pException, BOOL File_Flag, BOOL Show_Flag); + +#endif diff --git a/include/Game/Network/MultiplayerSnapshotFilter.h b/include/Game/Network/MultiplayerSnapshotFilter.h new file mode 100644 index 00000000..32c82e01 --- /dev/null +++ b/include/Game/Network/MultiplayerSnapshotFilter.h @@ -0,0 +1,25 @@ +#ifndef MultiplayerSnapshotFilter_h__ +#define MultiplayerSnapshotFilter_h__ + +#include "Core/EventBroker.h" +#include "Core/EPlayerSpawned.h" +#include "Network/SnapshotFilter.h" +#include "Network/EInterpolate.h" + +class MultiplayerSnapshotFilter : public SnapshotFilter +{ +public: + MultiplayerSnapshotFilter(EventBroker* eventBroker); + + virtual bool FilterComponent(EntityWrapper entity, SharedComponentWrapper& component) override; + +private: + EventBroker* m_EventBroker; + + EntityWrapper m_LocalPlayer = EntityWrapper::Invalid; + + EventRelay m_EPlayerSpawned; + bool OnPlayerSpawned(Events::PlayerSpawned ePlayerSpawned); +}; + +#endif \ No newline at end of file diff --git a/include/Game/Systems/AmmoPickupSystem.h b/include/Game/Systems/AmmoPickupSystem.h new file mode 100644 index 00000000..0fbd9e08 --- /dev/null +++ b/include/Game/Systems/AmmoPickupSystem.h @@ -0,0 +1,33 @@ +#ifndef AmmoPickupSystem_h__ +#define AmmoPickupSystem_h__ + +#include "Core/System.h" +#include "Core/Transform.h" +#include "Core/ResourceManager.h" +#include "Core/EntityFileParser.h" +#include "Core/EPickupSpawned.h" +#include "Core/EAmmoPickup.h" +#include "Engine/Collision/ETrigger.h" +#include "Common.h" + +class AmmoPickupSystem : public ImpureSystem +{ +public: + AmmoPickupSystem(SystemParams params); + + virtual void Update(double dt) override; + +private: + EventRelay m_ETriggerTouch; + bool OnTriggerTouch(Events::TriggerTouch& e); + + struct NewAmmoPickup { + glm::vec3 Pos; + double AmmoGain; + double RespawnTimer; + double DecreaseThisRespawnTimer; + EntityID parentID; + }; + std::vector m_ETriggerTouchVector; +}; +#endif diff --git a/include/Game/Systems/AmmunitionHUDSystem.h b/include/Game/Systems/AmmunitionHUDSystem.h new file mode 100644 index 00000000..b22a85b5 --- /dev/null +++ b/include/Game/Systems/AmmunitionHUDSystem.h @@ -0,0 +1,17 @@ +#ifndef AmmunitionHUDSystem_h__ +#define AmmunitionHUDSystem_h__ + +#include "../../Engine/Core/System.h" +#include "../../Engine/GLM.h" + +class AmmunitionHUDSystem : public ImpureSystem +{ +public: + AmmunitionHUDSystem(SystemParams params) + : System(params) + { } + + virtual void Update(double dt) override; +}; + +#endif \ No newline at end of file diff --git a/include/Game/Systems/CapturePointHUDSystem.h b/include/Game/Systems/CapturePointHUDSystem.h new file mode 100644 index 00000000..41db0c12 --- /dev/null +++ b/include/Game/Systems/CapturePointHUDSystem.h @@ -0,0 +1,22 @@ +#ifndef CapturePointHUDSystem_h__ +#define CapturePointHUDSystem_h__ + +#include +#include +#include + +#include "Common.h" +#include "Core/System.h" +#include "Engine/Collision/ETrigger.h" + +class CapturePointHUDSystem : public ImpureSystem +{ +public: + CapturePointHUDSystem(SystemParams params); + + virtual void Update(double dt) override; + +private: +}; + +#endif \ No newline at end of file diff --git a/include/Game/Systems/CapturePointSystem.h b/include/Game/Systems/CapturePointSystem.h index 18c32c76..34a23e14 100644 --- a/include/Game/Systems/CapturePointSystem.h +++ b/include/Game/Systems/CapturePointSystem.h @@ -17,7 +17,7 @@ class CapturePointSystem : public PureSystem { public: //WARNING: on new map, destroy all info in the vectors, as well as reset all variables (just make new?) - CapturePointSystem(World* world, EventBroker* eventBroker); + CapturePointSystem(SystemParams params); //updatecomponent virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& capturePoint, double dt) override; @@ -44,7 +44,6 @@ private: //std::vector - const double m_CaptureTimeToTakeOver = 15.0; bool m_ResetTimers = false; //vectors which will keep track of enter/leave changes diff --git a/include/Game/Systems/DamageIndicatorSystem.h b/include/Game/Systems/DamageIndicatorSystem.h new file mode 100644 index 00000000..ae9ba195 --- /dev/null +++ b/include/Game/Systems/DamageIndicatorSystem.h @@ -0,0 +1,49 @@ +#ifndef DamageIndicatorSystem_h__ +#define DamageIndicatorSystem_h__ + +#include "Core/System.h" +#include "Core/Transform.h" +#include "Core/ResourceManager.h" +#include "Core/EntityFileParser.h" +#include "Core/EPlayerDamage.h" +#include "Common.h" +#include + +#include "Rendering/ESetCamera.h" +#include +#include + +#include "Rendering/Util/CommonFunctions.h" +//#define INDICATOR_TEST + +class DamageIndicatorSystem : public ImpureSystem +{ +public: + DamageIndicatorSystem(SystemParams params); + virtual void Update(double dt) override; + +private: + EventRelay m_EPlayerDamage; + bool OnPlayerDamage(Events::PlayerDamage& e); + + EventRelay m_ESetCamera; + bool OnSetCamera(const Events::SetCamera& e); + + EntityID m_CurrentCamera = -1; + struct DamageIndicatorStruct { + EntityWrapper spriteEntity; + glm::vec3 enemyPosition; + DamageIndicatorStruct(EntityWrapper sprite, glm::vec3 pos) + : spriteEntity(sprite) + , enemyPosition(pos) {} + }; + std::vector updateDamageIndicatorVector; + float CalculateAngle(EntityWrapper player, glm::vec3 enemyPos); + + //for tests +#ifdef INDICATOR_TEST + glm::vec3 DamageIndicatorTest(EntityWrapper player); + int m_TestVar = 0; +#endif +}; +#endif diff --git a/include/Game/Systems/ExplosionEffectSystem.h b/include/Game/Systems/ExplosionEffectSystem.h new file mode 100644 index 00000000..24eee955 --- /dev/null +++ b/include/Game/Systems/ExplosionEffectSystem.h @@ -0,0 +1,18 @@ +#ifndef ExplosionEffectSystem_h__ +#define ExplosionEffectSystem_h__ + +#include "Common.h" +#include "Core/System.h" + +class ExplosionEffectSystem : public PureSystem +{ +public: + ExplosionEffectSystem(SystemParams params) + : System(params) + , PureSystem("ExplosionEffect") + { } + + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override; +}; + +#endif \ No newline at end of file diff --git a/include/Game/Systems/HealthHUDSystem.h b/include/Game/Systems/HealthHUDSystem.h new file mode 100644 index 00000000..49a40041 --- /dev/null +++ b/include/Game/Systems/HealthHUDSystem.h @@ -0,0 +1,17 @@ +#ifndef PlayerHUD_h__ +#define PlayerHUD_h__ + +#include "../../Engine/Core/System.h" +#include "../../Engine/GLM.h" + +class HealthHUDSystem : public ImpureSystem +{ +public: + HealthHUDSystem(SystemParams params) + : System(params) + { } + + virtual void Update(double dt) override; +}; + +#endif \ No newline at end of file diff --git a/include/Game/Systems/HealthSystem.h b/include/Game/Systems/HealthSystem.h index 3b069349..962e3737 100644 --- a/include/Game/Systems/HealthSystem.h +++ b/include/Game/Systems/HealthSystem.h @@ -9,28 +9,34 @@ #include "Core/EPlayerDamage.h" #include "Core/EPlayerHealthPickup.h" #include "Core/EPlayerDeath.h" +#include "Core/ConfigFile.h" +#include "Input/EInputCommand.h" #include #include +#include class HealthSystem : public PureSystem { public: - HealthSystem(World* world, EventBroker* eventBroker); + HealthSystem(SystemParams params); //updatecomponent virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override; private: - //methods which will take care of specific events + bool m_NetworkEnabled; + + // methods which will take care of specific events EventRelay m_EPlayerDamage; bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e); EventRelay m_EPlayerHealthPickup; - bool HealthSystem::OnPlayerHealthPickup(const Events::PlayerHealthPickup& e); + bool HealthSystem::OnPlayerHealthPickup(Events::PlayerHealthPickup& e); + EventRelay m_InputCommand; + bool HealthSystem::OnInputCommand(Events::InputCommand& e); //vector which will keep track of health changes std::vector> m_DeltaHealthVector; - }; #endif \ No newline at end of file diff --git a/include/Game/Systems/InterpolationSystem.h b/include/Game/Systems/InterpolationSystem.h index 96236f62..758609c8 100644 --- a/include/Game/Systems/InterpolationSystem.h +++ b/include/Game/Systems/InterpolationSystem.h @@ -16,38 +16,47 @@ #include "Network/EInterpolate.h" -class InterpolationSystem : public PureSystem +class InterpolationSystem : public ImpureSystem { - struct Transform - { - glm::vec3 Position; - glm::vec3 Scale; - glm::quat Orientation; - float interpolationTime; - }; public: - InterpolationSystem(World* world, EventBroker* eventBroker); + InterpolationSystem(SystemParams params); ~InterpolationSystem() { } - virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& transform, double dt) override; -private: - std::unordered_map m_NextTransform; - std::unordered_map m_LastReceivedTransform; - EntityWrapper m_LocalPlayer = EntityWrapper::Invalid; - //glm::vec3 vectorInterpolation(glm::vec3 prev, glm::vec3 next, double currentTime); + virtual void Update(double dt) override; + +private: + template + struct Interpolation + { + Interpolation(const ComponentWrapper& Component, const std::string& Field, const T& Start, const T& Goal) + : Component(Component) + , Field(Field) + , Start(Start) + , Goal(Goal) + { } + + ComponentWrapper Component; + std::string Field; + T Start; + T Goal; + double Alpha = 0.0; + }; + + float m_SnapshotInterval; + std::unordered_map> m_InterpolatePosition; + std::unordered_map> m_InterpolateOrientation; + std::unordered_map> m_InterpolateVelocity; + + EventRelay m_EInterpolate; + bool InterpolationSystem::OnInterpolate(Events::Interpolate& e); + template T vectorInterpolation(T prev, T next, double currentTime) { T difference = next - prev; - T vector = (difference / m_SnapshotInterval) * static_cast(currentTime); + T vector = difference * (static_cast(currentTime) / m_SnapshotInterval); return vector; } - float m_SnapshotInterval; - - EventRelay m_EInterpolate; - bool InterpolationSystem::OnInterpolate(const Events::Interpolate& e); - EventRelay m_EPlayerSpawned; - bool OnPlayerSpawned(Events::PlayerSpawned& e); }; #endif diff --git a/include/Game/Systems/KillFeedSystem.h b/include/Game/Systems/KillFeedSystem.h new file mode 100644 index 00000000..31423999 --- /dev/null +++ b/include/Game/Systems/KillFeedSystem.h @@ -0,0 +1,39 @@ +#ifndef KillFeedSystem_h__ +#define KillFeedSystem_h__ + +#include "../../Engine/Core/System.h" +#include "../../Engine/GLM.h" +#include "Core/EPlayerDeath.h" + +class KillFeedSystem : public ImpureSystem +{ +public: + KillFeedSystem(SystemParams params) + : System(params) + { + EVENT_SUBSCRIBE_MEMBER(m_EPlayerDeath, &KillFeedSystem::OnPlayerDeath); + + } + + virtual void Update(double dt) override; + +private: + + + + + EventRelay m_EPlayerDeath; + bool KillFeedSystem::OnPlayerDeath(Events::PlayerDeath& e); + + struct KillFeedInfo + { + std::string Content; + glm::vec4 Color; + float TimeToLive = 5.f; + }; + + std::list m_DeathQueue; + +}; + +#endif \ No newline at end of file diff --git a/include/Game/Systems/LifetimeSystem.h b/include/Game/Systems/LifetimeSystem.h index da88cfa2..6dee644d 100644 --- a/include/Game/Systems/LifetimeSystem.h +++ b/include/Game/Systems/LifetimeSystem.h @@ -6,10 +6,12 @@ class LifetimeSystem : public ImpureSystem, PureSystem { public: - LifetimeSystem(World* world, EventBroker* eventBroker) - : System(world, eventBroker) + LifetimeSystem(SystemParams params) + : System(params) , PureSystem("Lifetime") - { } + { + LOG_INFO("ASDASDASSA"); + } virtual void Update(double dt) override; virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cLifetime, double dt) override; diff --git a/include/Game/Systems/PickupSpawnSystem.h b/include/Game/Systems/PickupSpawnSystem.h new file mode 100644 index 00000000..66c5f630 --- /dev/null +++ b/include/Game/Systems/PickupSpawnSystem.h @@ -0,0 +1,34 @@ +#ifndef PickupSpawnSystem_h__ +#define PickupSpawnSystem_h__ + +#include "Core/System.h" +#include "Core/Transform.h" +#include "Core/ResourceManager.h" +#include "Core/EntityFileParser.h" +#include "Core/EPickupSpawned.h" +#include "Core/EPlayerHealthPickup.h" +#include "Engine/Collision/ETrigger.h" +#include "Common.h" +#include + +class PickupSpawnSystem : public ImpureSystem +{ +public: + PickupSpawnSystem(SystemParams params); + + virtual void Update(double dt) override; + +private: + EventRelay m_ETriggerTouch; + bool OnTriggerTouch(Events::TriggerTouch& e); + + struct NewHealthPickup { + glm::vec3 Pos; + double HealthGain; + double RespawnTimer; + double DecreaseThisRespawnTimer; + EntityID parentID; + }; + std::vector m_ETriggerTouchVector; +}; +#endif diff --git a/include/Game/Systems/PlayerDeathSystem.h b/include/Game/Systems/PlayerDeathSystem.h new file mode 100644 index 00000000..112c202e --- /dev/null +++ b/include/Game/Systems/PlayerDeathSystem.h @@ -0,0 +1,29 @@ +#ifndef PlayerDeathSystem_h__ +#define PlayerDeathSystem_h__ + +#include "Core/System.h" +#include "Input/EInputCommand.h" +#include "GLM.h" +#include "Rendering/ESetCamera.h" +#include "Core/ConfigFile.h" + +#include "Core/EntityFile.h" +#include "Core/EntityFileParser.h" + +#include "Core/EPlayerDeath.h" + +class PlayerDeathSystem : public ImpureSystem +{ +public: + PlayerDeathSystem(SystemParams params); + + virtual void Update(double dt) override; + +private: + EventRelay m_OnPlayerDeath; + bool OnPlayerDeath(Events::PlayerDeath& e); + + void createDeathEffect(EntityWrapper player); + +}; +#endif \ No newline at end of file diff --git a/include/Game/Systems/PlayerHUD.h b/include/Game/Systems/PlayerHUD.h deleted file mode 100644 index 180f5a2a..00000000 --- a/include/Game/Systems/PlayerHUD.h +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef PlayerHUD_h__ -#define PlayerHUD_h__ - -#include "../../Engine/Core/System.h" -#include "../../Engine/GLM.h" -#include "../../Engine/Rendering/ESetCamera.h" -#include - -class PlayerHUD : public ImpureSystem -{ -public: - PlayerHUD(World* world, EventBroker* eventBrokerer); - ~PlayerHUD(); - - virtual void Update(double dt) override; - -private: - World* m_World; - EventBroker* m_EventBroker; - -}; - -#endif \ No newline at end of file diff --git a/include/Game/Systems/PlayerMovementSystem.h b/include/Game/Systems/PlayerMovementSystem.h index f39740ec..92aa1915 100644 --- a/include/Game/Systems/PlayerMovementSystem.h +++ b/include/Game/Systems/PlayerMovementSystem.h @@ -4,20 +4,44 @@ #include "Core/EPlayerSpawned.h" #include "Input/FirstPersonInputController.h" #include +#include "Events/EDoubleJump.h" +#include "../Engine/Sound/EPlaySoundOnEntity.h" -class PlayerMovementSystem : public ImpureSystem, PureSystem +#include "Core/EntityFile.h" +#include "Core/EntityFileParser.h" + +class PlayerMovementSystem : public ImpureSystem { public: - PlayerMovementSystem(World* world, EventBroker* eventBroker); + PlayerMovementSystem(SystemParams params); ~PlayerMovementSystem(); virtual void Update(double dt) override; - virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt); private: // State std::unordered_map*> m_PlayerInputControllers; + EntityWrapper m_LocalPlayer = EntityWrapper::Invalid; + // Walking logic + // Keeps track of how far the player has walked within this "key press session". + float m_DistanceMoved = 0.0f; + // How far a step is (How often the step sound will be played). + const float m_PlayerStepLength = 1.75f; + // Determine what sound file to play. + bool m_LeftFoot = false; + // To get a difference when calculating the walking state. + glm::vec3 m_LastPosition = glm::vec3(); + // The logic for making the sound play when player is moving + void playerStep(double dt); + // Spawn a hexagon at origin of an Entity + void spawnHexagon(EntityWrapper target); + EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(Events::PlayerSpawned& e); + EventRelay m_EDoubleJump; + bool PlayerMovementSystem::OnDoubleJump(Events::DoubleJump & e); + + void updateMovementControllers(double dt); + void updateVelocity(EntityWrapper player, double dt); }; \ No newline at end of file diff --git a/include/Game/Systems/PlayerSpawnSystem.h b/include/Game/Systems/PlayerSpawnSystem.h index b0ff1d79..bf87bef8 100644 --- a/include/Game/Systems/PlayerSpawnSystem.h +++ b/include/Game/Systems/PlayerSpawnSystem.h @@ -3,15 +3,18 @@ #include "Systems/SpawnerSystem.h" #include "Events/ESpawnerSpawn.h" #include "Core/EPlayerSpawned.h" +#include "Core/EPlayerDeath.h" #include "Rendering/ESetCamera.h" #include "Core/ConfigFile.h" class PlayerSpawnSystem : public ImpureSystem { public: - PlayerSpawnSystem(World* world, EventBroker* eventBroker); + PlayerSpawnSystem(SystemParams params); virtual void Update(double dt) override; + + static void SetRespawnTime(float respawnTime) { m_RespawnTime = respawnTime; }; private: struct SpawnRequest @@ -22,10 +25,19 @@ private: bool m_NetworkEnabled = false; std::vector m_SpawnRequests; + + //Player ID -> EntityWrapper. std::map m_PlayerEntities; + //EntityWrapper ID -> Player ID. + std::map m_PlayerIDs; + + static float m_RespawnTime; + float m_Timer; EventRelay m_OnInputCommand; - bool OnInputCommand(const Events::InputCommand& e); + bool OnInputCommand(Events::InputCommand& e); EventRelay m_OnPlayerSpawnerd; bool OnPlayerSpawned(Events::PlayerSpawned& e); + EventRelay m_OnPlayerDeath; + bool OnPlayerDeath(Events::PlayerDeath& e); }; \ No newline at end of file diff --git a/include/Game/Systems/RaptorCopterSystem.h b/include/Game/Systems/RaptorCopterSystem.h index 8bb18de6..b3589dcd 100644 --- a/include/Game/Systems/RaptorCopterSystem.h +++ b/include/Game/Systems/RaptorCopterSystem.h @@ -4,8 +4,8 @@ class RaptorCopterSystem : public PureSystem { public: - RaptorCopterSystem(World* world, EventBroker* eventBroker) - : System(world, eventBroker) + RaptorCopterSystem(SystemParams params) + : System(params) , PureSystem("RaptorCopter") { } diff --git a/include/Game/Systems/SoundSystem.h b/include/Game/Systems/SoundSystem.h new file mode 100644 index 00000000..962eb085 --- /dev/null +++ b/include/Game/Systems/SoundSystem.h @@ -0,0 +1,65 @@ +#ifndef Systems_SoundSystem_h__ +#define Systems_SoundSystem_h__ + +#include + +#include "../Engine/Core/System.h" +#include "../Engine/Core/ResourceManager.h" +#include "../Engine/Core/ConfigFile.h" +#include "../Engine/Sound/Sound.h" +#include "../Engine/Sound/EPlayQueueOnEntity.h" +#include "../Engine/Core/EPlayerSpawned.h" +#include "../Engine/Input/EInputCommand.h" +#include "../Engine/Core/EShoot.h" +#include "../Engine/Core/EPlayerSpawned.h" +#include "../Engine/Input/EInputCommand.h" +#include "../Engine/Core/ECaptured.h" +#include "../Engine/Core/EPlayerDamage.h" +#include "../Engine/Core/EPlayerDeath.h" +#include "../Engine/Core/EPlayerHealthPickup.h" +#include "../Engine/Collision/ETrigger.h" +#include "../Engine/Sound/EPlaySoundOnEntity.h" +#include "../Engine/Sound/EPlayBackgroundMusic.h" +#include "../Game/Events/EDoubleJump.h" +#include "../Game/Events/EDashAbility.h" + + +class SoundSystem : public PureSystem, ImpureSystem +{ +public: + SoundSystem(SystemParams params); + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cComponent, double dt) override; + virtual void Update(double dt) override; +private: + std::string m_Announcer = ""; + // Logic for playing a sound when a player jumps + void playerJumps(); + + // Temporary solution for play test. + bool m_DrumsIsPlaying = false; + double m_DrumTimer = 0.0; + bool drumTimer(double dt); + + std::default_random_engine generator; + + EventRelay m_EPlayerSpawned; + bool OnPlayerSpawned(const Events::PlayerSpawned &e); + EventRelay m_InputCommand; + bool OnInputCommand(const Events::InputCommand &e); + EventRelay m_EDoubleJump; + bool OnDoubleJump(const Events::DoubleJump &e); + EventRelay m_EDashAbility; + bool OnDashAbility(const Events::DashAbility &e); + EventRelay m_ETriggerTouch; + bool OnTriggerTouch(const Events::TriggerTouch &e); + EventRelay m_ECaptured; + bool OnCaptured(const Events::Captured &e); + EventRelay m_EPlayerDamage; + bool OnPlayerDamage(const Events::PlayerDamage &e); + EventRelay m_EPlayerDeath; + bool OnPlayerDeath(const Events::PlayerDeath &e); + EventRelay m_EPlayerHealthPickup; + bool OnPlayerHealthPickup(const Events::PlayerHealthPickup &e); +}; + +#endif diff --git a/include/Game/Systems/SpawnerSystem.h b/include/Game/Systems/SpawnerSystem.h index 62f6b09a..e4a44738 100644 --- a/include/Game/Systems/SpawnerSystem.h +++ b/include/Game/Systems/SpawnerSystem.h @@ -13,13 +13,18 @@ class SpawnerSystem : public System { public: - SpawnerSystem(World* world, EventBroker* eventBroker); + SpawnerSystem(SystemParams params); - static EntityWrapper Spawn(EntityWrapper spawner, EntityWrapper parent = EntityWrapper::Invalid); + // If dontCollideComponent is set, to e.g. "Player", then all the spawner + // will try to pick a spawn location so that the spawned entity doesn't + // collide with anything that has that component and is collidable. + static EntityWrapper Spawn(EntityWrapper spawner, EntityWrapper parent = EntityWrapper::Invalid, const std::string& dontCollideComponent = ""); private: EventRelay m_OnSpawnerSpawn; bool OnSpawnerSpawn(Events::SpawnerSpawn& e); + static void transformEntityToSpawnPoint(EntityWrapper spawnedEntity, EntityWrapper spawnPoint); + static bool spawnedEntityIsColliding(EntityWrapper spawnedEntity, EntityWrapper spawnPoint, const std::string& dontCollideComponent); }; #endif \ No newline at end of file diff --git a/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h b/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h new file mode 100644 index 00000000..7bd9c175 --- /dev/null +++ b/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h @@ -0,0 +1,49 @@ +#include "Sound/EPlaySoundOnEntity.h" +#include "Collision/Collision.h" +#include "Rendering/AnimationSystem.h" +#include "Core/ConfigFile.h" +#include "WeaponBehaviour.h" +#include "../SpawnerSystem.h" +#include "Core/EPlayerDamage.h" +#include "Core/EShoot.h" + + +class AssaultWeaponBehaviour : public WeaponBehaviour +{ +public: + AssaultWeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree, EntityWrapper weaponEntity); + + virtual void Fire() override; + virtual void CeaseFire() override; + virtual void Reload() override; + + virtual void Update(double dt) override; + +private: + EntityWrapper m_FirstPersonModel; + EntityWrapper m_ThirdPersonModel; + // State + bool m_Firing = false; + bool m_Reloading = false; + double m_ReloadTimer = 0.0; + EntityWrapper m_FirstPersonReloadImpersonator; + EntityWrapper m_ThirdPersonReloadImpersonator; + double m_TimeSinceLastFire = 0.0; + + EventRelay m_EAnimationComplete; + bool OnAnimationComplete(Events::AnimationComplete& e); + + bool hasAmmo(); + void fireRound(); + void spawnTracer(); + float traceRayDistance(glm::vec3 origin, glm::vec3 direction); + void playFireSound(); + void playEmptySound(); + void viewPunch(); + void finishReload(); + void playShootAnimation(); + void playIdleAnimation(); + void playReloadAnimation(); + bool shoot(double damage); + void showHitMarker(); +}; diff --git a/include/Game/Systems/Weapon/WeaponBehaviour.h b/include/Game/Systems/Weapon/WeaponBehaviour.h new file mode 100644 index 00000000..7a0b4626 --- /dev/null +++ b/include/Game/Systems/Weapon/WeaponBehaviour.h @@ -0,0 +1,34 @@ +#ifndef WeaponBehaviour_h__ +#define WeaponBehaviour_h__ + +#include "Core/System.h" +#include "Rendering/IRenderer.h" +#include "Core/Octree.h" +#include "Collision/EntityAABB.h" + +class WeaponBehaviour : public System +{ +public: + WeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree, EntityWrapper player) + : System(systemParams) + , m_Renderer(renderer) + , m_CollisionOctree(collisionOctree) + , m_Player(player) + { } + virtual ~WeaponBehaviour() = default; + + WeaponBehaviour(const WeaponBehaviour&) = delete; + WeaponBehaviour& operator=(const WeaponBehaviour &) = delete; + + virtual void Fire() = 0; + virtual void CeaseFire() { } + virtual void Reload() { } + virtual void Update(double dt) { } + +protected: + IRenderer* m_Renderer; + Octree* m_CollisionOctree; + EntityWrapper m_Player; +}; + +#endif diff --git a/include/Game/Systems/Weapon/WeaponSystem.h b/include/Game/Systems/Weapon/WeaponSystem.h new file mode 100644 index 00000000..b8278bc4 --- /dev/null +++ b/include/Game/Systems/Weapon/WeaponSystem.h @@ -0,0 +1,44 @@ +#ifndef WeaponSystem_h__ +#define WeaponSystem_h__ + +#include "Rendering/IRenderer.h" + +#include "Common.h" +#include "Core/System.h" +#include "Core/EPlayerDamage.h" +#include "Core/EShoot.h" +#include "Core/EPlayerSpawned.h" +#include "Input/EInputCommand.h" +#include "Core/EntityFile.h" +#include "Core/EntityFileParser.h" +#include "Core/Octree.h" +#include "Collision/EntityAABB.h" +#include "Systems/SpawnerSystem.h" +#include "Sound/EPlaySoundOnEntity.h" +#include "AssaultWeaponBehaviour.h" + +class WeaponSystem : public PureSystem, ImpureSystem +{ +public: + WeaponSystem(SystemParams params, IRenderer* renderer, Octree* collisionOctree); + + virtual void Update(double dt) override; + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cPlayer, double dt) override; + +private: + SystemParams m_SystemParams; + IRenderer* m_Renderer; + Octree* m_CollisionOctree; + + std::unordered_map> m_ActiveWeapons; + + // Events + EventRelay m_EPlayerSpawned; + bool OnPlayerSpawned(Events::PlayerSpawned& e); + EventRelay m_EInputCommand; + bool OnInputCommand(Events::InputCommand& e); + + void selectWeapon(EntityWrapper player, ComponentInfo::EnumType slot); +}; + +#endif \ No newline at end of file diff --git a/include/Game/Systems/WeaponSystem.h b/include/Game/Systems/WeaponSystem.h deleted file mode 100644 index 0dd5cc54..00000000 --- a/include/Game/Systems/WeaponSystem.h +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef WeaponSystem_h__ -#define WeaponSystem_h__ - -//#include -//#include -#include "Rendering/IRenderer.h" - -#include "Common.h" -#include "Core/System.h" -#include "Core/EPlayerDamage.h" -#include "Core/EShoot.h" -#include "Core/EPlayerSpawned.h" -#include "Input/EInputCommand.h" -#include "Core/EntityFile.h" -#include "Core/EntityFileParser.h" - -#include -#include - - -class WeaponSystem : public ImpureSystem -{ -public: - WeaponSystem(World* world, EventBroker* eventBroker, IRenderer* renderer); - - virtual void Update(double dt) override; - -private: - IRenderer* m_Renderer; - - // State - EntityWrapper m_LocalPlayer = EntityWrapper::Invalid; - - // Events - EventRelay m_EPlayerSpawned; - bool WeaponSystem::OnPlayerSpawned(const Events::PlayerSpawned& e); - EventRelay m_EShoot; - bool WeaponSystem::OnShoot(Events::Shoot& e); - EventRelay m_EInputCommand; - bool WeaponSystem::OnInputCommand(const Events::InputCommand& e); -}; - -#endif \ No newline at end of file diff --git a/resources/DefaultConfig.ini b/resources/DefaultConfig.ini index 86dc735c..60ee4823 100644 --- a/resources/DefaultConfig.ini +++ b/resources/DefaultConfig.ini @@ -4,6 +4,9 @@ LoadMap= ; if true -> Pool allocation is not used when calling Allocate/Free, just use regular dynamic allocation. ; if false -> Use pool allocation. DisableMemoryPool=false +RespawnTime = 8.0 +EditorEnabled=false +OutOfBodyExperience=false [Editor] CameraSpeed=3 @@ -20,7 +23,7 @@ StartNetwork=false IsServer=false Name=Bob Address=127.0.0.1 -Port=13 +Port=27666 MaxConnections=8 SnapshotInterval=0.05 SendInputIntervalMs=33 @@ -29,3 +32,8 @@ TimeoutMs=15000 [Multithreading] ResourceLoading=true + +[Sound] +BGMVolume=1.0 +SFXVolume=1.0 +Announcer=female \ No newline at end of file diff --git a/resources/DefaultInput.ini b/resources/DefaultInput.ini index a3f7d166..776cbecd 100644 --- a/resources/DefaultInput.ini +++ b/resources/DefaultInput.ini @@ -2,6 +2,9 @@ Sensitivity=0.5 InvertPitch=false +[Keyboard] +DoubleTapToDash=false + [Bindings] MouseLeft=PrimaryFire MouseX=Yaw @@ -13,9 +16,15 @@ A=Right,-1 R=Reload Space=Jump LeftControl=Crouch -LeftShift=Sprint +RightShift=Sprint +LeftShift=SpecialAbility +1=SelectWeapon,1 +2=SelectWeapon,2 F1=ToggleEditor C=ConnectToServer N=SwitchToServer M=SwitchToClient -P=SwitchToPlayer \ No newline at end of file +P=SwitchToPlayer +K=TakeDamage,1500 +F2=PerformanceTimingResetAllTimers +F3=PerformanceTimingCreateExcelData \ No newline at end of file diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index bb1fd770..42abed82 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -28,6 +28,22 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/AABB.xsd b/resources/Schema/Components/AABB.xsd index daa633a6..7dec510f 100644 --- a/resources/Schema/Components/AABB.xsd +++ b/resources/Schema/Components/AABB.xsd @@ -7,10 +7,10 @@ - Middle point of the bounding box + Middle point of the bounding box, in model space - Size of the bounding box + Size of the bounding box, in model space diff --git a/resources/Schema/Components/AmmoPickup.xml b/resources/Schema/Components/AmmoPickup.xml new file mode 100644 index 00000000..6da0b6fa --- /dev/null +++ b/resources/Schema/Components/AmmoPickup.xml @@ -0,0 +1,5 @@ + + + 3 + 30 + \ No newline at end of file diff --git a/resources/Schema/Components/AmmoPickup.xsd b/resources/Schema/Components/AmmoPickup.xsd new file mode 100644 index 00000000..1970eb78 --- /dev/null +++ b/resources/Schema/Components/AmmoPickup.xsd @@ -0,0 +1,21 @@ + + + + + + + + An Ammo Pickup + + + + + The respawn timer for a ammo pickup + + + How much percent ammo gain the player will get + + + + + diff --git a/resources/Schema/Components/AmmunitionHUD.xml b/resources/Schema/Components/AmmunitionHUD.xml new file mode 100644 index 00000000..63b86150 --- /dev/null +++ b/resources/Schema/Components/AmmunitionHUD.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/resources/Schema/Components/AmmunitionHUD.xsd b/resources/Schema/Components/AmmunitionHUD.xsd new file mode 100644 index 00000000..1a48d8d1 --- /dev/null +++ b/resources/Schema/Components/AmmunitionHUD.xsd @@ -0,0 +1,10 @@ + + + + + + + Hud element for tracking ammunition from parent with AssaultWeapon component. Child with the name "MagazineAmmo" tracks clip ammunition. Child with the name "Ammo" tracks ammo. + + + \ No newline at end of file diff --git a/resources/Schema/Components/Animation.xml b/resources/Schema/Components/Animation.xml index 66d2865d..ae42009d 100644 --- a/resources/Schema/Components/Animation.xml +++ b/resources/Schema/Components/Animation.xml @@ -1,7 +1,18 @@ - - - 0 - true + + 1.0 + 0 + 0 + true + + 1.0 + 0 + 0 + true + + 1.0 + 0 + 0 + true \ No newline at end of file diff --git a/resources/Schema/Components/Animation.xsd b/resources/Schema/Components/Animation.xsd index 0dd21f29..f39aac18 100644 --- a/resources/Schema/Components/Animation.xsd +++ b/resources/Schema/Components/Animation.xsd @@ -6,11 +6,23 @@ - - - - + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/AnimationOffset.xml b/resources/Schema/Components/AnimationOffset.xml new file mode 100644 index 00000000..4aef8219 --- /dev/null +++ b/resources/Schema/Components/AnimationOffset.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/AnimationOffset.xsd b/resources/Schema/Components/AnimationOffset.xsd new file mode 100644 index 00000000..c3430cc2 --- /dev/null +++ b/resources/Schema/Components/AnimationOffset.xsd @@ -0,0 +1,17 @@ + + + + + + + + Aim animation offset for the skeleton + + + + + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/AssaultWeapon.xml b/resources/Schema/Components/AssaultWeapon.xml new file mode 100755 index 00000000..6c645624 --- /dev/null +++ b/resources/Schema/Components/AssaultWeapon.xml @@ -0,0 +1,11 @@ + + + 32 + 32 + 360 + 360 + 5 + 120 + 0.01 + 2 + \ No newline at end of file diff --git a/resources/Schema/Components/AssaultWeapon.xsd b/resources/Schema/Components/AssaultWeapon.xsd new file mode 100755 index 00000000..95df64b7 --- /dev/null +++ b/resources/Schema/Components/AssaultWeapon.xsd @@ -0,0 +1,34 @@ + + + + + + + + + + Ammo currently loaded into the magazine + + + Max number of rounds in a magazine + + + Current ammo carried + + + Maximum ammo able to be carried + + + + Rate of fire in rounds per minute + + + View punch in radians for each bullet fired + + + Time it takes to reload the weapon in seconds + + + + + diff --git a/resources/Schema/Components/BoneAttachment.xml b/resources/Schema/Components/BoneAttachment.xml new file mode 100644 index 00000000..47df9e40 --- /dev/null +++ b/resources/Schema/Components/BoneAttachment.xml @@ -0,0 +1,10 @@ + + + + + + + true + true + false + \ No newline at end of file diff --git a/resources/Schema/Components/BoneAttachment.xsd b/resources/Schema/Components/BoneAttachment.xsd new file mode 100644 index 00000000..aee1868f --- /dev/null +++ b/resources/Schema/Components/BoneAttachment.xsd @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/Button.xml b/resources/Schema/Components/Button.xml new file mode 100644 index 00000000..cbfd80d4 --- /dev/null +++ b/resources/Schema/Components/Button.xml @@ -0,0 +1,3 @@ + + \ No newline at end of file diff --git a/resources/Schema/Components/Button.xsd b/resources/Schema/Components/Button.xsd new file mode 100644 index 00000000..7d97fef1 --- /dev/null +++ b/resources/Schema/Components/Button.xsd @@ -0,0 +1,10 @@ + + + + + + + Makes sprites klickable. + + + \ No newline at end of file diff --git a/resources/Schema/Components/CapturePoint.xml b/resources/Schema/Components/CapturePoint.xml index ba164fd9..638b16c3 100644 --- a/resources/Schema/Components/CapturePoint.xml +++ b/resources/Schema/Components/CapturePoint.xml @@ -2,5 +2,6 @@ 0 0 + 15 \ No newline at end of file diff --git a/resources/Schema/Components/CapturePoint.xsd b/resources/Schema/Components/CapturePoint.xsd index fbdb3568..3c91dfdd 100644 --- a/resources/Schema/Components/CapturePoint.xsd +++ b/resources/Schema/Components/CapturePoint.xsd @@ -20,7 +20,11 @@ CapturePointNumber specify an int number for this - + + + The time needed to take over a Capture Point + + Specify if this is a HomePoint for either team diff --git a/resources/Schema/Components/CapturePointHUD.xml b/resources/Schema/Components/CapturePointHUD.xml new file mode 100644 index 00000000..2943d57b --- /dev/null +++ b/resources/Schema/Components/CapturePointHUD.xml @@ -0,0 +1,5 @@ + + + 0 + + \ No newline at end of file diff --git a/resources/Schema/Components/CapturePointHUD.xsd b/resources/Schema/Components/CapturePointHUD.xsd new file mode 100644 index 00000000..7984fc50 --- /dev/null +++ b/resources/Schema/Components/CapturePointHUD.xsd @@ -0,0 +1,24 @@ + + + + + + + Hud element for tracking capture points. + + + + + + Corresponds to the number on the capture point it should track. + + + + + Specify the team that own this capturePoint. + + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/Collidable.xsd b/resources/Schema/Components/Collidable.xsd index 84c66f11..93f7ac24 100644 --- a/resources/Schema/Components/Collidable.xsd +++ b/resources/Schema/Components/Collidable.xsd @@ -4,5 +4,8 @@ + + Needs a Model or AABB component to work, uses AABB if both are attached. + \ No newline at end of file diff --git a/resources/Schema/Components/DashAbility.xml b/resources/Schema/Components/DashAbility.xml new file mode 100644 index 00000000..a313c447 --- /dev/null +++ b/resources/Schema/Components/DashAbility.xml @@ -0,0 +1,4 @@ + + + 2.0 + \ No newline at end of file diff --git a/resources/Schema/Components/DashAbility.xsd b/resources/Schema/Components/DashAbility.xsd new file mode 100644 index 00000000..4273cc71 --- /dev/null +++ b/resources/Schema/Components/DashAbility.xsd @@ -0,0 +1,18 @@ + + + + + + + + A dash component for one of the classes + + + + + This is the cooldown on dash + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/HealthPickup.xml b/resources/Schema/Components/HealthPickup.xml new file mode 100644 index 00000000..1c9ee0f4 --- /dev/null +++ b/resources/Schema/Components/HealthPickup.xml @@ -0,0 +1,5 @@ + + + 3 + 30 + \ No newline at end of file diff --git a/resources/Schema/Components/HealthPickup.xsd b/resources/Schema/Components/HealthPickup.xsd new file mode 100644 index 00000000..bf3b327c --- /dev/null +++ b/resources/Schema/Components/HealthPickup.xsd @@ -0,0 +1,21 @@ + + + + + + + + A Health Pickup + + + + + The respawn timer for a health pickup + + + How much percent max-health the player will get when he picks the healthPickup up + + + + + diff --git a/resources/Schema/Components/KillFeed.xml b/resources/Schema/Components/KillFeed.xml new file mode 100644 index 00000000..558d4983 --- /dev/null +++ b/resources/Schema/Components/KillFeed.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/resources/Schema/Components/KillFeed.xsd b/resources/Schema/Components/KillFeed.xsd new file mode 100644 index 00000000..fedce9fb --- /dev/null +++ b/resources/Schema/Components/KillFeed.xsd @@ -0,0 +1,9 @@ + + + + + + HUD element for tracking the 3 last kills, printed on the children with the names "KillFeed1", "KillFeed2", "KillFeed3" + + + \ No newline at end of file diff --git a/resources/Schema/Components/Menu.xml b/resources/Schema/Components/Menu.xml new file mode 100644 index 00000000..f17427b8 --- /dev/null +++ b/resources/Schema/Components/Menu.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/resources/Schema/Components/Menu.xsd b/resources/Schema/Components/Menu.xsd new file mode 100644 index 00000000..18ea8565 --- /dev/null +++ b/resources/Schema/Components/Menu.xsd @@ -0,0 +1,9 @@ + + + + + + Attach this to the center point of a menu that uses several pages. + + + \ No newline at end of file diff --git a/resources/Schema/Components/Model.xml b/resources/Schema/Components/Model.xml index 4b77dacb..f81c8210 100644 --- a/resources/Schema/Components/Model.xml +++ b/resources/Schema/Components/Model.xml @@ -8,4 +8,5 @@ true true true + 3.0 \ No newline at end of file diff --git a/resources/Schema/Components/Model.xsd b/resources/Schema/Components/Model.xsd index 9c0cd519..31203ff6 100644 --- a/resources/Schema/Components/Model.xsd +++ b/resources/Schema/Components/Model.xsd @@ -33,6 +33,9 @@ Whether the model should use the Glowmap or not + + Intensity of the glow map + diff --git a/resources/Schema/Components/Page.xml b/resources/Schema/Components/Page.xml new file mode 100644 index 00000000..db7b9cc2 --- /dev/null +++ b/resources/Schema/Components/Page.xml @@ -0,0 +1,4 @@ + + + 0 + \ No newline at end of file diff --git a/resources/Schema/Components/Page.xsd b/resources/Schema/Components/Page.xsd new file mode 100644 index 00000000..777124a2 --- /dev/null +++ b/resources/Schema/Components/Page.xsd @@ -0,0 +1,14 @@ + + + + + + Use this on a child to a Menu entity and make sure that ID is not the same as other pages. + + + + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/Physics.xml b/resources/Schema/Components/Physics.xml index 9d1638fb..6cb73c75 100644 --- a/resources/Schema/Components/Physics.xml +++ b/resources/Schema/Components/Physics.xml @@ -2,4 +2,6 @@ true + false + 0.33 diff --git a/resources/Schema/Components/Physics.xsd b/resources/Schema/Components/Physics.xsd index 72037f48..7fed1fb5 100644 --- a/resources/Schema/Components/Physics.xsd +++ b/resources/Schema/Components/Physics.xsd @@ -13,6 +13,10 @@ m/s^2 + + + The largest height of a "stair-step" that can be walked over + diff --git a/resources/Schema/Components/Player.xml b/resources/Schema/Components/Player.xml index b51326aa..00cff257 100644 --- a/resources/Schema/Components/Player.xml +++ b/resources/Schema/Components/Player.xml @@ -2,4 +2,5 @@ 3 1.5 + \ No newline at end of file diff --git a/resources/Schema/Components/Player.xsd b/resources/Schema/Components/Player.xsd index 13948dc2..1b33d222 100644 --- a/resources/Schema/Components/Player.xsd +++ b/resources/Schema/Components/Player.xsd @@ -5,12 +5,13 @@ - The player charachter + The player entity + diff --git a/resources/Schema/Components/Shield.xml b/resources/Schema/Components/Shield.xml new file mode 100644 index 00000000..161f09bc --- /dev/null +++ b/resources/Schema/Components/Shield.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/resources/Schema/Components/Shield.xsd b/resources/Schema/Components/Shield.xsd new file mode 100644 index 00000000..9831cbfc --- /dev/null +++ b/resources/Schema/Components/Shield.xsd @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/Shielded.xml b/resources/Schema/Components/Shielded.xml new file mode 100644 index 00000000..0d95fb0a --- /dev/null +++ b/resources/Schema/Components/Shielded.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/resources/Schema/Components/Shielded.xsd b/resources/Schema/Components/Shielded.xsd new file mode 100644 index 00000000..b2348cf5 --- /dev/null +++ b/resources/Schema/Components/Shielded.xsd @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/Sprite.xml b/resources/Schema/Components/Sprite.xml new file mode 100644 index 00000000..ce4a6e1b --- /dev/null +++ b/resources/Schema/Components/Sprite.xml @@ -0,0 +1,8 @@ + + + + + + true + true + diff --git a/resources/Schema/Components/Sprite.xsd b/resources/Schema/Components/Sprite.xsd new file mode 100644 index 00000000..3c3d124a --- /dev/null +++ b/resources/Schema/Components/Sprite.xsd @@ -0,0 +1,30 @@ + + + + + + + + A sprite that will be facing the camera + + + + + Diffuse Texture file + + + GlowMap file + + + Color tint + + + Whether the model is visible or not + + + Whether the sprite should be sorted with depth or not. Only use false for textures that are on HUD + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/SpriteIndicator.xml b/resources/Schema/Components/SpriteIndicator.xml new file mode 100644 index 00000000..cbed22f0 --- /dev/null +++ b/resources/Schema/Components/SpriteIndicator.xml @@ -0,0 +1,5 @@ + + + 10 + false + \ No newline at end of file diff --git a/resources/Schema/Components/SpriteIndicator.xsd b/resources/Schema/Components/SpriteIndicator.xsd new file mode 100644 index 00000000..bd8c1038 --- /dev/null +++ b/resources/Schema/Components/SpriteIndicator.xsd @@ -0,0 +1,19 @@ + + + + + + + + Billbord a Sprite around global Y axis + + + + + + Add a Team component to this Entity or Parent to make it visible only for that team + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/Text.xml b/resources/Schema/Components/Text.xml index 9ca629d1..d38d3961 100644 --- a/resources/Schema/Components/Text.xml +++ b/resources/Schema/Components/Text.xml @@ -1,6 +1,6 @@ - Text + true diff --git a/resources/Schema/Components/Transform.xsd b/resources/Schema/Components/Transform.xsd index f0db2472..555b336c 100644 --- a/resources/Schema/Components/Transform.xsd +++ b/resources/Schema/Components/Transform.xsd @@ -4,9 +4,6 @@ - - It's a transform thingy! - @@ -15,6 +12,7 @@ + diff --git a/resources/Schema/Components/Trigger.xsd b/resources/Schema/Components/Trigger.xsd index a8bc8865..8119b966 100644 --- a/resources/Schema/Components/Trigger.xsd +++ b/resources/Schema/Components/Trigger.xsd @@ -4,5 +4,8 @@ + + Needs a Model or AABB component to work, uses AABB if both are attached. + \ No newline at end of file diff --git a/resources/Schema/Components/Weapon.xml b/resources/Schema/Components/Weapon.xml new file mode 100644 index 00000000..38c6fce9 --- /dev/null +++ b/resources/Schema/Components/Weapon.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/resources/Schema/Components/Weapon.xsd b/resources/Schema/Components/Weapon.xsd new file mode 100644 index 00000000..8bddd8a9 --- /dev/null +++ b/resources/Schema/Components/Weapon.xsd @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/resources/Schema/Entities/AmmoHUD b/resources/Schema/Entities/AmmoHUD new file mode 100644 index 00000000..6cdb6568 --- /dev/null +++ b/resources/Schema/Entities/AmmoHUD @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + + + + 0 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + + + + + + + 0 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/AmmoPickup.xml b/resources/Schema/Entities/AmmoPickup.xml new file mode 100644 index 00000000..bebde467 --- /dev/null +++ b/resources/Schema/Entities/AmmoPickup.xml @@ -0,0 +1,23 @@ + + + + + + + Models/Props/PickUps/AmmoPickUp.mesh + + + 8 + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/AmmoPickupTest.xml b/resources/Schema/Entities/AmmoPickupTest.xml new file mode 100644 index 00000000..22690c65 --- /dev/null +++ b/resources/Schema/Entities/AmmoPickupTest.xml @@ -0,0 +1,294 @@ + + + + + + + + + + + + Models/LevelBase/MapVersion1.mesh + + + + + + + + + 2 + + + Models/DirectionalLightWidget.mesh + false + + + + + + + + + + + + + 8 + 2.7999999523162842 + + + + + + + + + + + 8 + 2.7999999523162842 + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + false + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + false + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 22 + + + Models/Core/UnitSphere.mesh + + + + + + + + + + + + + 1 + 22 + + + Models/Core/UnitSphere.mesh + + + + + + + + + + + + + 4 + 44 + + + Models/Core/UnitSphere.mesh + + + + + + + + + + + diff --git a/resources/Schema/Entities/AmmunitionHUD.xml b/resources/Schema/Entities/AmmunitionHUD.xml new file mode 100644 index 00000000..2eaf2753 --- /dev/null +++ b/resources/Schema/Entities/AmmunitionHUD.xml @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + + + + 32 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/AnimatedArmy.xml b/resources/Schema/Entities/AnimatedArmy.xml index b711a0fe..67accc40 100644 --- a/resources/Schema/Entities/AnimatedArmy.xml +++ b/resources/Schema/Entities/AnimatedArmy.xml @@ -20,7 +20,7 @@ - models/dummyscene.mesh + Models/Test/DummyScene.mesh @@ -31,7 +31,7 @@ - models/animtest. + Models/Test/AnimTest.mesh @@ -42,7 +42,7 @@ - models/animTest.mesh + Models/Test/AnimTest.mesh @@ -53,7 +53,7 @@ - models/animTest.mesh + Models/Test/AnimTest.mesh @@ -64,7 +64,7 @@ - models/animTest.mesh + Models/Test/AnimTest.mesh @@ -91,7 +91,7 @@ - + @@ -154,7 +154,7 @@ - + diff --git a/resources/Schema/Entities/AnimationTests.xml b/resources/Schema/Entities/AnimationTests.xml new file mode 100644 index 00000000..77c87e64 --- /dev/null +++ b/resources/Schema/Entities/AnimationTests.xml @@ -0,0 +1,377 @@ + + + + + + + + + + + + Models/Core/UnitPlane.mesh + + + + + + + + + + + + + Models/DirectionalLightWidget.mesh + + + + + + + + + + + + Crouch + + 1 + + + Models/Asstest.mesh + + + + + + + + + + R_Leg_Top + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Leg_Bottom + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Foot + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Foot + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Leg_Bottom + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Leg_Top + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Hip + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Spine_1 + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Spine_2 + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Spine_3 + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Neck + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Shoulder + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Arm + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Elbow + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Hand + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Chin + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Hand + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Elbow + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/AnimationTests2.xml b/resources/Schema/Entities/AnimationTests2.xml new file mode 100644 index 00000000..413c7e67 --- /dev/null +++ b/resources/Schema/Entities/AnimationTests2.xml @@ -0,0 +1,149 @@ + + + + + + + + + + + + + + + + + + + + Models/Widgets/Lights/DirectionalLightWidget.mesh + + + + + + + + + + + + Run + 0.5 + 0.60188997954429357 + -1 + 1 + 0.5 + 0.96957233017255007 + 0.093923612201312068 + 1 + + + AimRifle + + + + Models/Characters/Assault/AssaultAnimations.mesh + + + + + + + + + + R_Arm_Weapon_Joint + + + + Models/Weapons/Red/AssaultWeaponRed.mesh + + + + + + + + + + + + + + + 10 + + + + + + + + + + + 10 + + + + + + + + + + + + + Models/Core/UnitPlane.mesh + + + + + + + + + + + ShootFastRifle + 0.056234247235838808 + 1 + 1 + Idl + 0.5 + 1.8308673495784191 + StrafeRigh + 0.5 + 0.32167823998061529 + 1 + + + Models/Characters/Assault/AssaultAnimations.mesh + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Red/AssaultWeaponRed.mesh + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/AnimationTests3.xml b/resources/Schema/Entities/AnimationTests3.xml new file mode 100644 index 00000000..39043231 --- /dev/null +++ b/resources/Schema/Entities/AnimationTests3.xml @@ -0,0 +1,133 @@ + + + + + + + + + + + + + + + + + + + + Models/Widgets/Lights/DirectionalLightWidget.mesh + + + + + + + + + + + + Run + 0.5 + 0.14873348341666759 + -1 + 1 + + 0.5 + 0.96957233017255007 + + 0.093923612201312068 + 1 + + + AimRifle + + + Models/Characters/Assault/AssaultAnimations.mesh + + + + + + + + + + R_Arm_Weapon_Joint + + + + Models/Weapons/Red/AssaultWeaponRed.mesh + + + + + + + + + + + + + + 10 + + + + + + + + + + + Models/Core/UnitPlane.mesh + + + + + + + + + + + ShootFastRifle + 0.11093210511546658 + 1 + + + AimRifle + + + + Models/Characters/Assault/AssaultAnimations.mesh + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Red/AssaultWeaponRed.mesh + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/AssetPedistal.xml b/resources/Schema/Entities/AssetPedistal.xml index 728a3028..3c816149 100644 --- a/resources/Schema/Entities/AssetPedistal.xml +++ b/resources/Schema/Entities/AssetPedistal.xml @@ -35,7 +35,7 @@ - Models/AssaultWeaponBlue.mesh + Models/Weapons/Blue/AssaultWeaponBlue.mesh diff --git a/resources/Schema/Entities/BoneMarker b/resources/Schema/Entities/BoneMarker new file mode 100644 index 00000000..eda56d56 --- /dev/null +++ b/resources/Schema/Entities/BoneMarker @@ -0,0 +1,22 @@ + + + + + + R_Leg_Top + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + diff --git a/resources/Schema/Entities/Button.xml b/resources/Schema/Entities/Button.xml new file mode 100644 index 00000000..21f64334 --- /dev/null +++ b/resources/Schema/Entities/Button.xml @@ -0,0 +1,32 @@ + + + + + + + Textures/Core/White.png + + + + + + + + + + + + Play + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + diff --git a/resources/Schema/Entities/CapturePoint.xml b/resources/Schema/Entities/CapturePoint.xml index 9b3c5036..9f33c4de 100644 --- a/resources/Schema/Entities/CapturePoint.xml +++ b/resources/Schema/Entities/CapturePoint.xml @@ -5,7 +5,7 @@ - C:\Users\123456\Workspace\TacticalZ\assets\Models\Core\UnitSphere.mesh + Models/Core/UnitSphere.mesh diff --git a/resources/Schema/Entities/CapturePointHUDGroup.xml b/resources/Schema/Entities/CapturePointHUDGroup.xml new file mode 100644 index 00000000..d35e1bde --- /dev/null +++ b/resources/Schema/Entities/CapturePointHUDGroup.xml @@ -0,0 +1,173 @@ + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 2 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 3 + + + 0.80222018197612788 + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 4 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 1 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/CapturePointHUDHexagon.xml b/resources/Schema/Entities/CapturePointHUDHexagon.xml new file mode 100644 index 00000000..68cf42a7 --- /dev/null +++ b/resources/Schema/Entities/CapturePointHUDHexagon.xml @@ -0,0 +1,34 @@ + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + 0.5 + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + diff --git a/resources/Schema/Entities/CaptureTest.xml b/resources/Schema/Entities/CaptureTest.xml index 5f657e51..3d678bd7 100644 --- a/resources/Schema/Entities/CaptureTest.xml +++ b/resources/Schema/Entities/CaptureTest.xml @@ -9,7 +9,7 @@ - ../assets/Models/DummyScene.mesh + Models/Test/DummyScene.mesh @@ -41,7 +41,7 @@ 3 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -61,7 +61,7 @@ 1 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -81,7 +81,7 @@ 2 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -102,7 +102,7 @@ 3 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -120,7 +120,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh @@ -138,7 +138,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh diff --git a/resources/Schema/Entities/CaptureTestState1.xml b/resources/Schema/Entities/CaptureTestState1.xml index ffabd5c2..64999074 100644 --- a/resources/Schema/Entities/CaptureTestState1.xml +++ b/resources/Schema/Entities/CaptureTestState1.xml @@ -9,7 +9,7 @@ - ../assets/Models/DummyScene.mesh + Models/Test/DummyScene.mesh @@ -42,7 +42,7 @@ 6.9158446328696002 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -63,7 +63,7 @@ 1 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -83,7 +83,7 @@ 2 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -104,7 +104,7 @@ 3 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -122,7 +122,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh @@ -140,7 +140,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh diff --git a/resources/Schema/Entities/CaptureTestState2.xml b/resources/Schema/Entities/CaptureTestState2.xml index 29abdfbd..6ddb306f 100644 --- a/resources/Schema/Entities/CaptureTestState2.xml +++ b/resources/Schema/Entities/CaptureTestState2.xml @@ -9,7 +9,7 @@ - ../assets/Models/DummyScene.mesh + Models/Test/DummyScene.mesh @@ -41,7 +41,7 @@ 3 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -61,7 +61,7 @@ 1 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -79,7 +79,7 @@ 2 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -98,7 +98,7 @@ 3 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -116,7 +116,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh @@ -134,7 +134,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh diff --git a/resources/Schema/Entities/CaptureTestState3.xml b/resources/Schema/Entities/CaptureTestState3.xml index ff875dc4..3bed3624 100644 --- a/resources/Schema/Entities/CaptureTestState3.xml +++ b/resources/Schema/Entities/CaptureTestState3.xml @@ -9,7 +9,7 @@ - ../assets/Models/DummyScene.mesh + Models/Test/DummyScene.mesh @@ -41,7 +41,7 @@ 3 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -61,7 +61,7 @@ 1 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -81,7 +81,7 @@ 2 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -101,7 +101,7 @@ 3 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -122,7 +122,7 @@ 4 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -140,7 +140,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh @@ -158,7 +158,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh @@ -176,7 +176,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh @@ -194,7 +194,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh diff --git a/resources/Schema/Entities/CaptureTestState4.xml b/resources/Schema/Entities/CaptureTestState4.xml index 740d7e7b..30db23aa 100644 --- a/resources/Schema/Entities/CaptureTestState4.xml +++ b/resources/Schema/Entities/CaptureTestState4.xml @@ -9,7 +9,7 @@ - ../assets/Models/DummyScene.mesh + Models/Test/DummyScene.mesh @@ -41,7 +41,7 @@ 3 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -61,7 +61,7 @@ 1 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -79,7 +79,7 @@ 2 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -96,7 +96,7 @@ 3 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -115,7 +115,7 @@ 4 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -133,7 +133,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh @@ -151,7 +151,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh @@ -169,7 +169,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh @@ -187,7 +187,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh diff --git a/resources/Schema/Entities/CaptureTestState5.xml b/resources/Schema/Entities/CaptureTestState5.xml index f1b07a7b..c733706c 100644 --- a/resources/Schema/Entities/CaptureTestState5.xml +++ b/resources/Schema/Entities/CaptureTestState5.xml @@ -2,12 +2,246 @@ - - - + + + + + + + + + Models/LevelBase/MapVersion1.mesh + + + + + + + + + 2 + + + Models/Widgets/Lights/DirectionalLightWidget.mesh + false + + + + + + + + + + + + + 8 + 2.7999999523162842 + + + + + + + + + + + 8 + 2.7999999523162842 + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + false + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + false + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -15,10 +249,12 @@ + 15 - C:\Users\123456\Workspace\TacticalZ\assets\Models\Core\UnitSphere.mesh - + Models/Core/UnitSphere.mesh + + true @@ -26,7 +262,7 @@ - + @@ -39,12 +275,13 @@ 1 - C:\Users\123456\Workspace\TacticalZ\assets\Models\Core\UnitSphere.mesh - + Models/Core/UnitSphere.mesh + + true - + @@ -57,16 +294,13 @@ 2 - C:\Users\123456\Workspace\TacticalZ\assets\Models\Core\UnitSphere.mesh - + Models/Core/UnitSphere.mesh + + true - - - - - + - + @@ -76,11 +310,13 @@ + -15 3 - C:\Users\123456\Workspace\TacticalZ\assets\Models\Core\UnitSphere.mesh - + Models/Core/UnitSphere.mesh + + true @@ -88,7 +324,7 @@ - + @@ -101,11 +337,13 @@ + -15 4 - C:\Users\123456\Workspace\TacticalZ\assets\Models\Core\UnitSphere.mesh - + Models/Core/UnitSphere.mesh + + true @@ -113,61 +351,12 @@ - + - - - - - - C:\Users\123456\Workspace\TacticalZ\assets\Models\Core\UnitCube.mesh - - - - - - - - - - - - - - - - - - - C:\Users\123456\Workspace\TacticalZ\assets\Models\Core\UnitCube.mesh - - - - - - - - - - - - - - - - - C:\Users\123456\Workspace\TacticalZ\assets\Models\DummyScene.mesh - - - - - - - diff --git a/resources/Schema/Entities/CollisionSpawnTest.xml b/resources/Schema/Entities/CollisionSpawnTest.xml new file mode 100644 index 00000000..331beae6 --- /dev/null +++ b/resources/Schema/Entities/CollisionSpawnTest.xml @@ -0,0 +1,164 @@ + + + + + + + + + + + + + + ../assets/Models/Test/ObstacleCourse.mesh + + + + + + + + + + + 0.46000027656555176 + + + + + + + + + + + + + ../assets/Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + false + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + false + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/CollisionTestLevel.xml b/resources/Schema/Entities/CollisionTestLevel.xml index e58ab6ce..66b1109f 100644 --- a/resources/Schema/Entities/CollisionTestLevel.xml +++ b/resources/Schema/Entities/CollisionTestLevel.xml @@ -1,122 +1,67 @@ - + + - - - - - - - Models/DummyScene.mesh - - - - - - - - - - - Models/Core/UnitSphere.mesh - - - - - - - - - - - Models/RotationWidgetX.mesh - - - - - - - - - - - - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - - - - - - - - - Models/Core/UnitRaptor.mesh - - - - - - - - - - - - 20 - - - - - - - - - - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - \ No newline at end of file + + + + + + + + + + + ../assets/Models/Test/ObstacleCourse.mesh + + + + + + + + + + + 0.46000027656555176 + + + + + + + + + + + + + ../assets/Models/Core/UnitCube.mesh + + + false + + + + + + + + + + + + + + + ../assets/Models/Core/colorbox.mesh + + + + + + + + + + + diff --git a/resources/Schema/Entities/DamageIndicator.xml b/resources/Schema/Entities/DamageIndicator.xml new file mode 100644 index 00000000..3e9e4fef --- /dev/null +++ b/resources/Schema/Entities/DamageIndicator.xml @@ -0,0 +1,22 @@ + + + + + + Textures/DamageIndicator.png + + false + + + + + + + + 1.5 + + + + + + diff --git a/resources/Schema/Entities/DamageIndicatorTest.xml b/resources/Schema/Entities/DamageIndicatorTest.xml new file mode 100644 index 00000000..1155ddd5 --- /dev/null +++ b/resources/Schema/Entities/DamageIndicatorTest.xml @@ -0,0 +1,426 @@ + + + + + + + + + + + + + + + Models\MapVersion1.mesh + + + + + + + + + 2 + + + Models/DirectionalLightWidget.mesh + false + + + + + + + + + + + + + 8 + 2.7999999523162842 + + + + + + + + + + + 8 + 2.7999999523162842 + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + false + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + false + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 99 + + + + + + 5 + + + + + + + + + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,100 + + + + + + + + + + + + + + Models/Camera.mesh + false + + + + + + + + + + + + + + + + + + + 0.99000000953674316 + + + + + Models/Core/UnitHexagon.mesh + + + + + + + + + + + + + + Models/CrosshairQuad.mesh + + + + + + + + + + + + + Models/AssaultWeaponRed.mesh + + + + + + + + + + + + + + + + + + + + + + + + + Models/Camera.mesh + false + + + + + + + + + + + + + + Models/Characters/Assault/AssaultAnimations.mesh + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + diff --git a/resources/Schema/Entities/DeadGirl.xlm b/resources/Schema/Entities/DeadGirl.xlm new file mode 100644 index 00000000..90a0411d --- /dev/null +++ b/resources/Schema/Entities/DeadGirl.xlm @@ -0,0 +1,255 @@ + + + + + + + + + + 600 + + + + + + + + + 5 + + + + + + + + + + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,100 + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + + + + + + + + 1 + + + + + Models/Core/UnitHexagon.mesh + + + + + + + + + + + + + + Textures/Weapons/Crosshair/SmallThickHoleDot.png + false + + + + + + + + + + + + + + Idle + 0.28963486380924053 + 1 + + + Models/Characters/Assault/FirstPerson.mesh + true + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + true + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + + + Schema/Entities/WeaponReloadEffect.xml + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + Idle + 0.42156525436696768 + 1 + + + AimRifle + + + + + Models/Characters/Assault/AssaultAnimations.mesh + + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + false + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + diff --git a/resources/Schema/Entities/DeadGirls.xml b/resources/Schema/Entities/DeadGirls.xml new file mode 100644 index 00000000..2b004c34 --- /dev/null +++ b/resources/Schema/Entities/DeadGirls.xml @@ -0,0 +1,1137 @@ + + + + + + + + + + + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + + + + + sModels/Widgets/Lights/DirectionalLightWidget.mesh + + + + + + + + + + + + + Models/Test/ObstacleCourse.mesh + + + + + + + + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + + + + + + + 600 + + + + + 1 + + + + + + 5 + + + + + + + + + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,100 + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + + + + + + + + 0.0099999997764825821 + + + + + Models/Core/UnitHexagon.mesh + + + + + + + + + + + + + + Textures/Weapons/Crosshair/SmallThickHoleDot.png + false + + + + + + + + + + + + + + Idle + 1.9484546004984589 + 1 + + + Models/Characters/Assault/FirstPerson.mesh + true + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + true + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + + + Schema/Entities/WeaponReloadEffect.xml + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + Idle + 0.83038427580044871 + 1 + + + AimRifle + + + + + Models/Characters/Assault/AssaultAnimations.mesh + + + + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + false + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + + + + + + 600 + + + + + 1 + + + + + + 5 + + + + + + + + + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,100 + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + + + + + + + + 0.0099999997764825821 + + + + + Models/Core/UnitHexagon.mesh + + + + + + + + + + + + + + Textures/Weapons/Crosshair/SmallThickHoleDot.png + false + + + + + + + + + + + + + + Idle + 1.6865388023565906 + 1 + + + Models/Characters/Assault/FirstPerson.mesh + true + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + true + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + + + Schema/Entities/WeaponReloadEffect.xml + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + Idle + 0.71846833460743298 + 1 + + + AimRifle + + + + + Models/Characters/Assault/AssaultAnimations.mesh + + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + false + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + + + + + + 600 + + + + + 1 + + + + + + 5 + + + + + + + + + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,100 + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + + + + + + + + 0.0099999997764825821 + + + + + Models/Core/UnitHexagon.mesh + + + + + + + + + + + + + + Textures/Weapons/Crosshair/SmallThickHoleDot.png + false + + + + + + + + + + + + + + Idle + 1.4291906531606173 + 1 + + + Models/Characters/Assault/FirstPerson.mesh + true + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + true + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + + + Schema/Entities/WeaponReloadEffect.xml + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + Idle + 0.34445363000679663 + 1 + + + AimRifle + + + + + Models/Characters/Assault/AssaultAnimations.mesh + + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + false + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + + + + + + 600 + + + + + 1 + + + + + + 5 + + + + + + + + + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,100 + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + + + + + + + + 0.0099999997764825821 + + + + + Models/Core/UnitHexagon.mesh + + + + + + + + + + + + + + Textures/Weapons/Crosshair/SmallThickHoleDot.png + false + + + + + + + + + + + + + + Idle + 0.94316388255725769 + 1 + + + Models/Characters/Assault/FirstPerson.mesh + true + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + true + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + + + Schema/Entities/WeaponReloadEffect.xml + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + Idle + 1.7750936055429634 + 1 + + + AimRifle + + + + + Models/Characters/Assault/AssaultAnimations.mesh + + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + false + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + diff --git a/resources/Schema/Entities/DoubleJumpHexagon.xml b/resources/Schema/Entities/DoubleJumpHexagon.xml new file mode 100644 index 00000000..f4596efd --- /dev/null +++ b/resources/Schema/Entities/DoubleJumpHexagon.xml @@ -0,0 +1,29 @@ + + + + + + 0.5 + + + true + + true + 0.5 + + true + + + Models/Effects/JumpEffectHexagon.mesh + + true + + + + + + + + + + diff --git a/resources/Schema/Entities/EditorTestWorld.xml b/resources/Schema/Entities/EditorTestWorld.xml index 4727c777..46e6d54d 100755 --- a/resources/Schema/Entities/EditorTestWorld.xml +++ b/resources/Schema/Entities/EditorTestWorld.xml @@ -37,7 +37,7 @@ 0.80000001192092896 - Models/DirectionalLightWidget.mesh + Models/Widgets/Lights/DirectionalLightWidget.mesh 1 @@ -62,7 +62,7 @@ 3 - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -73,7 +73,7 @@ - Models/AssaultWeaponRed.mesh + Models/Weapons/Red/AssaultWeaponRed.mesh true @@ -86,7 +86,7 @@ - Models/DefenderGunRed.mesh + Models/Weapons/Red/DefenderGunRed.mesh true false @@ -115,7 +115,7 @@ 1 - models/AssaultAnimated.mesh + Models/Characters/Assault/AssaultAnimated.mesh @@ -131,7 +131,7 @@ 1 - models/AssaultAnimated.mesh + Models/Characters/Assault/AssaultAnimated.mesh @@ -157,7 +157,7 @@ - Models/Log.mesh + Models/Props/TreeLog.mesh @@ -176,7 +176,7 @@ - models/NormSpecIncdMapSphere.mesh + Models/Test/NormSpecIncdMapSphere.mesh @@ -260,7 +260,7 @@ - Models/NormalMapSphere.mesh + Models/Test/NormalMapSphere.mesh @@ -271,7 +271,7 @@ - Models/SpecularMapSphere.mesh + Models/Test/SpecularMapSphere.mesh @@ -313,7 +313,7 @@ - Models/IncandescenceMapSphere.mesh + Models/Test/IncandescenceMapSphere.mesh diff --git a/resources/Schema/Entities/EditorWidgetRotate.xml b/resources/Schema/Entities/EditorWidgetRotate.xml index 88452aac..1276f3e4 100644 --- a/resources/Schema/Entities/EditorWidgetRotate.xml +++ b/resources/Schema/Entities/EditorWidgetRotate.xml @@ -18,7 +18,7 @@ - Models/RotationWidgetX.mesh + Models/Widgets/Rotate/RotationWidgetX.mesh @@ -33,7 +33,7 @@ - Models/RotationWidgetY.mesh + Models/Widgets/Rotate/RotationWidgetY.mesh @@ -48,7 +48,7 @@ - Models/RotationWidgetZ.mesh + Models/Widgets/Rotate/RotationWidgetZ.mesh diff --git a/resources/Schema/Entities/EditorWidgetScale.xml b/resources/Schema/Entities/EditorWidgetScale.xml index 786b079e..65cb2b86 100644 --- a/resources/Schema/Entities/EditorWidgetScale.xml +++ b/resources/Schema/Entities/EditorWidgetScale.xml @@ -3,7 +3,7 @@ - Models/ScaleWidgetOrigin.mesh + Models/Widgets/Scale/ScalingWidgetOrigin.mesh @@ -20,7 +20,7 @@ - Models/ScaleWidgetX.mesh + Models/Widgets/Scale/ScalingWidgetX.mesh @@ -34,7 +34,7 @@ - Models/ScaleWidgetY.mesh + Models/Widgets/Scale/ScalingWidgetY.mesh @@ -48,7 +48,7 @@ - Models/ScaleWidgetZ.mesh + Models/Widgets/Scale/ScalingWidgetZ.mesh diff --git a/resources/Schema/Entities/EditorWidgetTranslate.xml b/resources/Schema/Entities/EditorWidgetTranslate.xml index c6dba4d9..e177b7e9 100644 --- a/resources/Schema/Entities/EditorWidgetTranslate.xml +++ b/resources/Schema/Entities/EditorWidgetTranslate.xml @@ -3,7 +3,7 @@ - Models/TranslationWidgetOrigin.mesh + Models/Widgets/Translate/TranslationWidgetOrigin.mesh @@ -18,7 +18,7 @@ - Models/TranslationWidgetX.mesh + Models/Widgets/Translate/TranslationWidgetX.mesh @@ -30,7 +30,7 @@ - Models/TranslationWidgetY.mesh + Models/Widgets/Translate/TranslationWidgetY.mesh @@ -42,7 +42,7 @@ - Models/TranslationWidgetZ.mesh + Models/Widgets/Translate/TranslationWidgetZ.mesh @@ -54,7 +54,7 @@ - Models/WidgetPlaneX.mesh + Models/Widgets/Translate/TranslationWidgetPlaneX.mesh @@ -66,7 +66,7 @@ - Models/WidgetPlaneY.mesh + Models/Widgets/Translate/TranslationWidgetPlaneY.mesh @@ -78,7 +78,7 @@ - Models/WidgetPlaneZ.mesh + Models/Widgets/Translate/TranslationWidgetPlaneZ.mesh diff --git a/resources/Schema/Entities/FastWorld.xml b/resources/Schema/Entities/FastWorld.xml index 1289d9d1..94df077d 100644 --- a/resources/Schema/Entities/FastWorld.xml +++ b/resources/Schema/Entities/FastWorld.xml @@ -3,7 +3,7 @@ - + @@ -18,23 +18,17 @@ - + - Run - - 1 + Crouch Walk + + 8 - - - - 0.95625903442123672 - - Models/AssaultAnimated.mesh diff --git a/resources/Schema/Entities/FirstPersonArms b/resources/Schema/Entities/FirstPersonArms new file mode 100644 index 00000000..bf749a4e --- /dev/null +++ b/resources/Schema/Entities/FirstPersonArms @@ -0,0 +1,57 @@ + + + + + + Run + 0.5 + 0.97312056690160276 + 1 + 1 + ReloadSwitch + 0.91310356788604263 + LeftRight + 0 + 0.040207288496060478 + 1 + + + DownUp + + + + Models/Characters/Assault/FirstPerson.mesh + + true + + + + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeapon.mesh + + + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/GameMap.xml b/resources/Schema/Entities/GameMap.xml index 7b62b5d8..473b9037 100644 --- a/resources/Schema/Entities/GameMap.xml +++ b/resources/Schema/Entities/GameMap.xml @@ -8,8 +8,13 @@ + + + + + - Models\MapVersion1.mesh + Models/LevelBase/MapVersion1.mesh @@ -21,7 +26,7 @@ 2 - Models/DirectionalLightWidget.mesh + Models/Widgets/Lights/DirectionalLightWidget.mesh false @@ -139,7 +144,7 @@ - + @@ -201,14 +206,16 @@ - + - + + + diff --git a/resources/Schema/Entities/HealthHUD.xml b/resources/Schema/Entities/HealthHUD.xml new file mode 100644 index 00000000..ec781d8f --- /dev/null +++ b/resources/Schema/Entities/HealthHUD.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + 1 + + + + + 100/100 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + 1 + + + + Textures/HealthHUD3.png + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/HealthPickup.xml b/resources/Schema/Entities/HealthPickup.xml new file mode 100644 index 00000000..b4b83392 --- /dev/null +++ b/resources/Schema/Entities/HealthPickup.xml @@ -0,0 +1,23 @@ + + + + + + + Models/Props/PickUps/HealthPickUp.mesh + + + 8 + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/HealthPickupTest.xml b/resources/Schema/Entities/HealthPickupTest.xml new file mode 100644 index 00000000..2980fb51 --- /dev/null +++ b/resources/Schema/Entities/HealthPickupTest.xml @@ -0,0 +1,294 @@ + + + + + + + + + + + + Models\MapVersion1.mesh + + + + + + + + + 2 + + + Models/DirectionalLightWidget.mesh + false + + + + + + + + + + + + + 8 + 2.7999999523162842 + + + + + + + + + + + 8 + 2.7999999523162842 + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + false + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + false + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 22 + + + Models/Core/UnitSphere.mesh + + + + + + + + + + + + + 1 + 22 + + + Models/Core/UnitSphere.mesh + + + + + + + + + + + + + 4 + 44 + + + Models/Core/UnitSphere.mesh + + + + + + + + + + + diff --git a/resources/Schema/Entities/HitMarker.xml b/resources/Schema/Entities/HitMarker.xml new file mode 100644 index 00000000..74a539d0 --- /dev/null +++ b/resources/Schema/Entities/HitMarker.xml @@ -0,0 +1,20 @@ + + + + + + 0.1 + + + Textures/Weapons/Crosshair/SmallThickHoleDot.png + false + + + + + + + + + + diff --git a/resources/Schema/Entities/LevelCollisionTest.xml b/resources/Schema/Entities/LevelCollisionTest.xml new file mode 100644 index 00000000..3c3f3bab --- /dev/null +++ b/resources/Schema/Entities/LevelCollisionTest.xml @@ -0,0 +1,41 @@ + + + + + + + ../assets/Models/MapVersion1.mesh + + + + + + + + + + + ../assets/Models/Core/UnitCube.mesh + + + false + + + + + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/Model.xml b/resources/Schema/Entities/Model.xml index 57856cbd..bee6b7e1 100644 --- a/resources/Schema/Entities/Model.xml +++ b/resources/Schema/Entities/Model.xml @@ -19,7 +19,7 @@ - models/animTest.mesh + Models/Test/AnimTest.mesh diff --git a/resources/Schema/Entities/ModelCollisionTest.xml b/resources/Schema/Entities/ModelCollisionTest.xml new file mode 100644 index 00000000..c4a3f81b --- /dev/null +++ b/resources/Schema/Entities/ModelCollisionTest.xml @@ -0,0 +1,65 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + ../assets/Models/Core/Tri.obj + + + + + + + + + + + + ../assets/Models/Core/Tri.obj + + + + + + + + + + + + + + + + ../assets/Models/Core/UnitCube.obj + + + + + + + + + + + diff --git a/resources/Schema/Entities/MovementTest.xml b/resources/Schema/Entities/MovementTest.xml index 1378f623..84aaa03a 100644 --- a/resources/Schema/Entities/MovementTest.xml +++ b/resources/Schema/Entities/MovementTest.xml @@ -6,22 +6,6 @@ - - - - - - Models/Core/UnitCube.mesh - - false - - - - - - - - @@ -42,7 +26,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -55,7 +39,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -68,9 +52,10 @@ + - Models/DirectionalLightWidget.mesh + sModels/Widgets/Lights/DirectionalLightWidget.mesh @@ -81,6 +66,7 @@ + Models/Test/ObstacleCourse.mesh @@ -88,51 +74,6 @@ - - - - - - Models/Core/UnitCube.mesh - false - - - - - - - - - - - - - - Models/Core/UnitCube.mesh - false - - - - - - - - - - - - - - Models/Core/UnitCube.mesh - false - - - - - - - - @@ -153,7 +94,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -166,7 +107,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -183,10 +124,14 @@ + + 600 + - + + - false + 5 @@ -197,8 +142,7 @@ - - + @@ -206,7 +150,7 @@ - + @@ -215,10 +159,9 @@ Fonts/DroidSans.ttf,100 - false - + @@ -228,7 +171,8 @@ - Models/Camera.mesh + Models/Widgets/Camera.mesh + false @@ -237,13 +181,107 @@ + + + + + + + + + + + 1 + + + + + Models/Core/UnitHexagon.mesh + + + + + + + + + + + + + + Textures/Weapons/Crosshair/SmallThickHoleDot.png + false + + + + + + + + + + + + + + Idle + 1.9569972344146196 + 1 + + + Models/Characters/Assault/FirstPerson.mesh + true + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + true + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + + + Schema/Entities/WeaponReloadEffect.xml + + + + + + + - Models/Camera.mesh + Models/Widgets/Camera.mesh false @@ -255,15 +293,52 @@ + + Idle + 1.8055945618467364 + 1 + + + AimRifle + + + - Models/AssaultHeadless.mesh + Models/Characters/Assault/AssaultAnimations.mesh - - - + - + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + false + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + diff --git a/resources/Schema/Entities/NewMap.xml b/resources/Schema/Entities/NewMap.xml new file mode 100644 index 00000000..00dc476f --- /dev/null +++ b/resources/Schema/Entities/NewMap.xml @@ -0,0 +1,5311 @@ + + + + + + + + + + + + + + + + + + Models/Props/Ground.mesh + + + + + + + + + Models/Props/Highground1.mesh + + + + + + + + + + Models/Props/Highground2.mesh + + + + + + + + + + Models/Props/Highground1.mesh + + + + + + + + + + + + Models/Props/Highground2.mesh + + + + + + + + + + + + Models/Props/Highground3.mesh + + + + + + + + + + Models/Props/Highground4.mesh + + + + + + + + + + Models/Props/Highground5.mesh + + + + + + + + + + + Models/Props/Highground6.mesh + + + + + + + + + + Models/Props/Walls/SciFiWallTop.mesh + + + + + + + + + Models/Props/Walls/SciFiWallBig.mesh + + + + + + + + + + Models/Props/Walls/SciFiWallMedium.mesh + + + + + + + + + + Models/Props/Walls/SciFiWallSmall1.mesh + + + + + + + + + + Models/Props/Walls/SciFiWallSmall2.mesh + + + + + + + + + + Models/Props/Walls/SciFiWallBig.mesh + + + + + + + + + + + + Models/Props/Walls/SciFiWallMedium.mesh + + + + + + + + + + + + Models/Props/Walls/SciFiWallSmall3.mesh + + + + + + + + + + Models/Props/Walls/SciFiWallSmall4.mesh + + + + + + + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar1Blue.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar1Red.mesh + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Red.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar3Blue.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar1Blue.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar1Red.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar3Red.mesh + + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Blue.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Red.mesh + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Blue.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Blue.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Blue.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Blue.mesh + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Red.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Red.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Red.mesh + + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Red.mesh + + + + + + + + + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall4.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall4.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall4.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + + + Models/Props/Flora/SpecialRoot.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall4.mesh + + + + + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + + + + + + + + + + Models/Props/Bridges/WoodenBridge.mesh + + + + + + + + + + + + + + Models/Props/Bridges/WoodenBridge.mesh + + + + + + + + + + + + + + Models/Props/Bridges/WoodenBridge.mesh + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridge1Red.mesh + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridge1Blue.mesh + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridge1Blue.mesh + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridge1Blue.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridge1Red.mesh + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridge1Red.mesh + + + + + + + + + + + + + Models/Props/Bridges/WoodenBridge.mesh + + + + + + + + + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Models/Core/UnitPlane.mesh + + true + + + + + + + + + + + + + Models/Core/UnitPlane.mesh + + true + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + + Models/Props/Flora/TreeLog.mesh + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + Models/Props/Flora/SpecialRoot.mesh + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + Models/Props/Flora/SpecialRoot.mesh + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + Models/Props/Flora/SpecialRoot.mesh + + + + + + + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/SmallStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone2.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + + + Models/Props/Stones/SmallStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + + + Models/Props/Stones/SmallStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + + + + + + + + + + + Models/Props/CapturePoint/CapturePointBlue.mesh + + + + + + + + + + + + + 4 + + + Models/Core/UnitCylinder.mesh + + true + + + + + + + + + + + + + + + + + + + + + Models/Props/CapturePoint/CapturePointNeutral.mesh + + + + + + + + + + 3 + + + Models/Core/UnitCylinder.mesh + + true + + + + + + + + + + + + + + + + + Models/Props/CapturePoint/CapturePointNeutral.mesh + + + + + + + + + + 2 + + + Models/Core/UnitCylinder.mesh + + true + + + + + + + + + + + + + + + + + Models/Props/CapturePoint/CapturePointNeutral.mesh + + + + + + + + + + 1.5498908015879351 + 1 + + + Models/Core/UnitCylinder.mesh + + true + + + + + + + + + + + + + + + + + Models/Props/CapturePoint/CapturePointRed.mesh + + + + + + + + + + + + + + + Models/Core/UnitCylinder.mesh + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + + + + + + + + + 10 + + + + + + + + + + 10 + + + + + + + + + + + + + 10 + + + + + + + + + + + 10 + + + + + + + + + + + 10 + + + + + + + + + + + 1 + + + + + + + + + + + + + + Schema/Entities/PlayerRed.xml + + + + + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + false + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + false + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + false + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + false + + + + + + + + + + + + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + false + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + false + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + false + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + false + + + + + + + + + + + + + + + + + + + Models/Props/PickUps/HealthPickUp.mesh + + + 0.10000000149011612 + + + + + + + + + + + + + + + + Models/Props/PickUps/AmmoPickUp.mesh + + + 0.10000000149011612 + + + + + + + + + + + + + + + + Models/Props/PickUps/HealthPickUp.mesh + + + 0.10000000149011612 + + + + + + + + + + + + + + + + Models/Props/PickUps/HealthPickUp.mesh + + + 0.10000000149011612 + + + + + + + + + + + + + + + + Models/Props/PickUps/AmmoPickUp.mesh + + + 0.10000000149011612 + + + + + + + + + + + + + + + + Models/Props/PickUps/HealthPickUp.mesh + + + 0.10000000149011612 + + + + + + + + + + + + + + + + Models/Props/PickUps/AmmoPickUp.mesh + + + 0.10000000149011612 + + + + + + + + + + + + + + + + Models/Props/PickUps/AmmoPickUp.mesh + + + 0.10000000149011612 + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/NewMapBackup.xml b/resources/Schema/Entities/NewMapBackup.xml new file mode 100644 index 00000000..15ec64cf --- /dev/null +++ b/resources/Schema/Entities/NewMapBackup.xml @@ -0,0 +1,3222 @@ + + + + + + + + + + + + + + + + + + Models/Props/Ground.mesh + + + + + + + + + Models/Props/Highground1.mesh + + + + + + + + + + Models/Props/Highground2.mesh + + + + + + + + + + Models/Props/Highground1.mesh + + + + + + + + + + + + Models/Props/Highground2.mesh + + + + + + + + + + + + Models/Props/Highground3.mesh + + + + + + + + + + Models/Props/Highground4.mesh + + + + + + + + + + Models/Props/Highground5.mesh + + + + + + + + + + Models/Props/Highground6.mesh + + + + + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar1.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar1.mesh + + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar3.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar1.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar1.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar3.mesh + + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2.mesh + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall4.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall4.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall4.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + + Models/Props/Flora/SpecialRoot.mesh + + + + + + + + + + + + + + + + + + + + Models/Props/Bridges/WoodenBridge.mesh + + + + + + + + + + + + + + Models/Props/Bridges/WoodenBridge.mesh + + + + + + + + + + + + + + Models/Props/Bridges/WoodenBridge.mesh + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridge.mesh + + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridge.mesh + + + + + + + + + + + + + + Models/Props/Flora/TreeLog.mesh + + + + + + + + + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + + Models/Props/Flora/TreeLog.mesh + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + Models/Props/Flora/SpecialRoot.mesh + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystal.mesh + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystal.mesh + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystal.mesh + + + + + + + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Models/Props/CapturePoint.mesh + + true + + + + + + + + + + + + + + + + + + 1 + + + Models/Props/CapturePoint.mesh + + true + + + + + + + + + + + + + + 2 + + + Models/Props/CapturePoint.mesh + + true + + + + + + + + + + + + + + 3 + + + Models/Props/CapturePoint.mesh + + true + + + + + + + + + + + + + + + + + 4 + + + Models/Props/CapturePoint.mesh + + true + + + + + + + + + + + + + + + + + + + + + + + + 1 + + + + + + + + + 10 + + + + + + + + + + 10 + + + + + + + + + + + + + 10 + + + + + + + + + + + 10 + + + + + + + + + + + 10 + + + + + + + + + + + 1 + + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index d365c0ee..4f012955 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -6,7 +6,11 @@ + + 600 + + @@ -16,12 +20,10 @@ - + - - - + @@ -29,28 +31,14 @@ - + - - - - Fonts/DroidSans.ttf,100 - - - - - - - - - - - Models/Camera.mesh + Models/Widgets/Camera.mesh false @@ -67,64 +55,420 @@ - - - - 1 - - - - - Models/Core/UnitHexagon.mesh - - - - - - - - - - - - Models/CrosshairQuad.mesh - + + Textures/Weapons/Crosshair/SmallThickHoleDot.png + false + + - - + - + - - true - - 3.7999999523162842 - - true - + + Schema/Entities/HitMarker.xml + + + + + + + + + + + + + + 1 + + + + + 100/100 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + 1 + + + + Textures/HealthHUD3.png + + + + + + + + + + + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + 2 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + 3 + + + 0.80222018197612788 + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + 4 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + 1 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + + + Idle + 0.97725610639912475 + 1 + + + + + Models/Characters/Assault/FirstPerson.mesh + + + + + + + + + R_Arm_Weapon_Joint + - Models/AssaultWeaponRed.mesh + Models/Weapons/Blue/AssaultWeaponBlue.mesh - - + + - - - - - - - - - + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + Schema/Entities/ReloadEffectView.xml + + + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + + + + + 32 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + @@ -134,7 +478,7 @@ - Models/Camera.mesh + Models/Widgets/Camera.mesh false @@ -147,18 +491,61 @@ - Hold Pos - - 1 + Idle + 0.87583812735846323 + 1 + + + + AimRifle + + - Models/AssaultAnimated.mesh - + Models/Characters/Assault/AssaultAnimations.mesh + - + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + Schema/Entities/ReloadEffectWorld.xml + + + + + + + + @@ -187,6 +574,41 @@ + + + + Insert name here + Fonts/DroidSans.ttf,100 + + + + + + + + + + + + + + Textures/Icons/Arrow.png + false + + + + + + 50 + true + + + + + + + + diff --git a/resources/Schema/Entities/PlayerDeathExplosionWithCamera.xml b/resources/Schema/Entities/PlayerDeathExplosionWithCamera.xml new file mode 100644 index 00000000..3ec16e4e --- /dev/null +++ b/resources/Schema/Entities/PlayerDeathExplosionWithCamera.xml @@ -0,0 +1,41 @@ + + + + + + + 2.5 + + + true + + + true + 3 + + true + + + Models/AssaultAnimated.mesh + + true + + + + + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/PlayerRed.xml b/resources/Schema/Entities/PlayerRed.xml new file mode 100644 index 00000000..d56fa3c1 --- /dev/null +++ b/resources/Schema/Entities/PlayerRed.xml @@ -0,0 +1,615 @@ + + + + + + + + + + 600 + + + + + + + + + 5 + + + + + + + + + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + + + + + + + + Textures/Weapons/Crosshair/SmallThickHoleDot.png + false + + + + + + + + + + + + + Schema/Entities/HitMarker.xml + + + + + + + + + + + + + + 1 + + + + + 100/100 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + 1 + + + + Textures/HealthHUD3.png + + + + + + + + + + + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + 2 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + 3 + + + 0.80222018197612788 + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + 4 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + 1 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + + + Idle + 1.2667383999985162 + 1 + + + + + Models/Characters/Assault/FirstPerson.mesh + + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Red/AssaultWeaponRed.mesh + + + + + + + + + + + Schema/Entities/RayRed.xml + + + + + + + + + + + Schema/Entities/ReloadEffectViewRed.xml + + + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + + + + + 32 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + Idle + 0.26532318661337229 + 1 + + + + + AimRifle + + + + + Models/Characters/Assault/AssaultAnimations.mesh + + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Red/AssaultWeaponRed.mesh + + + + + + + + + + + Schema/Entities/RayRed.xml + + + + + + + + + + + Schema/Entities/ReloadEffectWorldRed.xml + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + Insert name here + Fonts/DroidSans.ttf,100 + + + + + + + + + + + + + + Textures/Icons/Arrow.png + false + + + + + + 50 + true + + + + + + + + + + + diff --git a/resources/Schema/Entities/QualityAssurance.xml b/resources/Schema/Entities/QualityAssurance.xml index 86281abd..8b028090 100644 --- a/resources/Schema/Entities/QualityAssurance.xml +++ b/resources/Schema/Entities/QualityAssurance.xml @@ -40,7 +40,7 @@ - + @@ -77,18 +77,6 @@ - - - - Sound Test - Fonts/DroidSans.ttf,64 - - - - - - - @@ -97,7 +85,7 @@ 0.80000001192092896 - Models/DirectionalLightWidget.mesh + Models/Widgets/Lights/DirectionalLightWidget.mesh 1 @@ -105,7 +93,7 @@ - + @@ -120,13 +108,9 @@ - - Run - - 1 - + - models/AssaultAnimated.mesh + Models/Characters/Assault/AssaultAnimated.mesh @@ -136,13 +120,9 @@ - - Walk - - 1 - + - models/AssaultAnimated.mesh + Models/Characters/Assault/AssaultAnimated.mesh @@ -188,19 +168,15 @@ - + - - Run - - 1 - + - Models/AssaultAnimated.mesh + Models/Characters/Assault/AssaultAnimated.mesh @@ -224,7 +200,7 @@ - models/NormSpecIncdMapSphere.mesh + Models/Test/NormSpecIncdMapSphere.mesh @@ -237,7 +213,7 @@ - + @@ -301,14 +277,14 @@ - + - Models/NormalMapSphere.mesh + Models/Test/NormalMapSphere.mesh @@ -319,7 +295,7 @@ - Models/SpecularMapSphere.mesh + Models/Test/SpecularMapSphere.mesh @@ -333,7 +309,7 @@ - + @@ -361,7 +337,7 @@ - Models/IncandescenceMapSphere.mesh + Models/Test/IncandescenceMapSphere.mesh @@ -422,7 +398,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -435,7 +411,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -448,7 +424,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -461,7 +437,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -493,7 +469,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -506,7 +482,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -519,7 +495,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -532,7 +508,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -586,7 +562,7 @@ true - + @@ -608,7 +584,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh true @@ -683,14 +659,14 @@ - + - Models/AssaultWeaponBlue.mesh + Models/Weapons/Blue/AssaultWeaponBlue.mesh @@ -730,14 +706,14 @@ - + - Models/AssaultWeaponRed.mesh + Models/Weapons/Red/AssaultWeaponRed.mesh @@ -790,14 +766,14 @@ - + - Models/SecondaryWeapon.mesh + Models/Weapons/SecondaryWeapon.mesh @@ -837,14 +813,14 @@ - + - Models/AssualtSoft.mesh + Models/Test/AssaultTPoseSoftEdge.mesh @@ -883,14 +859,14 @@ - + - Models/DefenderGunBlue.mesh + Models/Weapons/Blue/DefenderGunBlue.mesh @@ -930,14 +906,14 @@ - + - Models/DefenderGunRed.mesh + Models/Weapons/Red/DefenderGunRed.mesh @@ -977,14 +953,14 @@ - + - Models/Assualt.mesh + Models/Test/AssaultTPoseHardEdge.mesh @@ -1021,7 +997,7 @@ - Models/CapturePoint.mesh + Models/Props/CapturePoint.mesh @@ -1035,10 +1011,11 @@ + 15 Models/Core/UnitCube.mesh - + true @@ -1073,7 +1050,7 @@ - Models/CapturePoint.mesh + Models/Props/CapturePoint.mesh @@ -1088,7 +1065,8 @@ Models/Core/UnitCube.mesh - + + true @@ -1118,7 +1096,7 @@ - Models/CapturePoint.mesh + Models/Props/CapturePoint.mesh @@ -1131,6 +1109,7 @@ Models/Core/UnitCube.mesh + true @@ -1161,7 +1140,7 @@ - Models/CapturePoint.mesh + Models/Props/CapturePoint.mesh @@ -1172,12 +1151,12 @@ - -12.033302729641917 3 Models/Core/UnitCube.mesh - + + true @@ -1207,7 +1186,7 @@ - Models/CapturePoint.mesh + Models/Props/CapturePoint.mesh @@ -1221,11 +1200,12 @@ + -15 4 Models/Core/UnitCube.mesh - + true @@ -1347,6 +1327,19 @@ + + + + ExplosionEffect Test + Fonts/DroidSans.ttf,64 + + + + + + + + @@ -1374,7 +1367,7 @@ - + @@ -1383,13 +1376,13 @@ true - 0.75008034908941568 + 0.8256214817261025 3.7999999523162842 true - Models/AssaultWeaponBlue.mesh + Models/Weapons/Blue/AssaultWeaponBlue.mesh true @@ -1430,7 +1423,7 @@ - + @@ -1439,10 +1432,10 @@ - 1.1999860997035228 + 1.8641349174045843 - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh true @@ -1482,27 +1475,23 @@ - + - - Walk - - 1 - + true - 0.68343188336345406 + 1.8641349174045843 true - Models/AssaultAnimated.mesh + Models/Characters/Assault/AssaultAnimated.mesh true @@ -1515,18 +1504,120 @@ - + - - ExplosionEffect Test - Fonts/DroidSans.ttf,64 - + + Models/Core/UnitCylinder.mesh + + - - + - + + + + + + + + + + + + + + 0.5 + + + + + + + + + + + true + + + 1.2301962937648341 + 10 + + 3 + true + + + Models/Core/UnitSphere.mesh + + true + + + + + + + + + + + + + + + Models/Core/UnitCylinder.mesh + + + + + + + + + + + + + + + + + + + + 0.5 + + + + + + + + + + + true + + + 3.4214855659573402 + true + 5 + true + + + Models/Assault.mesh + + true + + + + + + + + + + @@ -1553,6 +1644,844 @@ + + + + + + + + + + + Models/Core/UnitHexagon.mesh + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + + + + + false + + + 5 + + + + + + + + + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,100 + + + + + + + + + + + + + + Models/Camera.mesh + false + + + + + + + + + + + + + + + + + + + 1 + + + + + Models/Core/UnitHexagon.mesh + + + + + + + + + + + + + + Models/CrosshairQuad.mesh + + + + + + + + + + + + + true + + 0.8256214817261025 + 3.7999999523162842 + + true + + + Models/AssaultWeaponRed.mesh + + + + + + + + + + + + + + + + + + + + + + + + + Models/Camera.mesh + false + + + + + + + + + + + + + + + Models/AssaultAnimated.mesh + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + + + + + + + + + Models/Log.mesh + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + + Defender Shield Test + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + + + + + + + Textures/Props/FoliageDiff.png + + + + + + + + + Textures/Props/FoliageDiff.png + + + + + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 2 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 3 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 4 + + + 1 + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 1 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + 1 + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + + + + + + + + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + + + + + + + + + + Textures/Core/ErrorTexture.png + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Play + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Host + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Connect + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Settings + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Quit + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + + + + 1 + + + + + + + + + + Textures/Core/ErrorTexture.png + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + 1920x1080 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + 1280x720 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + 854x480 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + FullScreen + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + + + + + + Menu test area + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + Sound Test + Fonts/DroidSans.ttf,64 + + + + + + + diff --git a/resources/Schema/Entities/RayBlue.xml b/resources/Schema/Entities/RayBlue.xml index 4a0bb9d4..022d7769 100644 --- a/resources/Schema/Entities/RayBlue.xml +++ b/resources/Schema/Entities/RayBlue.xml @@ -6,12 +6,12 @@ 0.25 - Models/CylinderBullet.mesh - + Models/Effects/CylinderShot.mesh + true - + diff --git a/resources/Schema/Entities/RayRed.xml b/resources/Schema/Entities/RayRed.xml index e69df489..0a20f148 100644 --- a/resources/Schema/Entities/RayRed.xml +++ b/resources/Schema/Entities/RayRed.xml @@ -6,12 +6,12 @@ 0.25 - Models/CylinderBullet.mesh - + Models/Effects/CylinderShot.mesh + true - + diff --git a/resources/Schema/Entities/ReloadEffectView.xml b/resources/Schema/Entities/ReloadEffectView.xml new file mode 100644 index 00000000..ca7e6e1a --- /dev/null +++ b/resources/Schema/Entities/ReloadEffectView.xml @@ -0,0 +1,24 @@ + + + + + + 2 + + + true + + + true + + true + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + + + + + + + diff --git a/resources/Schema/Entities/ReloadEffectViewRed.xml b/resources/Schema/Entities/ReloadEffectViewRed.xml new file mode 100644 index 00000000..56b9d140 --- /dev/null +++ b/resources/Schema/Entities/ReloadEffectViewRed.xml @@ -0,0 +1,24 @@ + + + + + + 2 + + + true + + + true + + true + + + Models/Weapons/Red/AssaultWeaponRed.mesh + + + + + + + diff --git a/resources/Schema/Entities/ReloadEffectWorld.xml b/resources/Schema/Entities/ReloadEffectWorld.xml new file mode 100644 index 00000000..ae6d3a3e --- /dev/null +++ b/resources/Schema/Entities/ReloadEffectWorld.xml @@ -0,0 +1,25 @@ + + + + + + 2 + + + true + + + true + + true + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + true + + + + + + + diff --git a/resources/Schema/Entities/ReloadEffectWorldRed.xml b/resources/Schema/Entities/ReloadEffectWorldRed.xml new file mode 100644 index 00000000..55c37389 --- /dev/null +++ b/resources/Schema/Entities/ReloadEffectWorldRed.xml @@ -0,0 +1,25 @@ + + + + + + 2 + + + true + + + true + + true + + + Models/Weapons/Red/AssaultWeaponRed.mesh + true + + + + + + + diff --git a/resources/Schema/Entities/RenderingWorld.xml b/resources/Schema/Entities/RenderingWorld.xml index 20301d5f..8bbc39f8 100644 --- a/resources/Schema/Entities/RenderingWorld.xml +++ b/resources/Schema/Entities/RenderingWorld.xml @@ -20,7 +20,7 @@ - Models/Assault.obj + Models/Characters/Assault/AssaultTPose.mesh @@ -35,7 +35,7 @@ 80 - Models/Camera.mesh + Models/Widgets/Camera.mesh @@ -52,14 +52,15 @@ - 0.65990006923675537 + Models/Core/UnitHexagon.mesh + true @@ -132,7 +133,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -161,7 +162,7 @@ - + @@ -308,7 +309,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -324,7 +325,7 @@ 0.10000000149011612 - Models/DirectionalLightWidget.mesh + Models/Widgets/Lights/DirectionalLightWidget.mesh @@ -346,6 +347,32 @@ + + + + Textures/HexmapDiff.png + Textures/GlowFrame.png + + + + + + + + + + + Run + + 0.004999999888241291 + + + Models/SuperTest.mesh + + + + + diff --git a/resources/Schema/Entities/ShootEventTest.xml b/resources/Schema/Entities/ShootEventTest.xml index 9e9adf50..80dd2f35 100644 --- a/resources/Schema/Entities/ShootEventTest.xml +++ b/resources/Schema/Entities/ShootEventTest.xml @@ -9,7 +9,7 @@ - ../assets/Models/DummyScene.mesh + Models/Test/DummyScene.mesh @@ -41,7 +41,7 @@ 3 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -61,7 +61,7 @@ 1 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -79,7 +79,7 @@ 2 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -96,7 +96,7 @@ 3 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -115,7 +115,7 @@ 4 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -133,7 +133,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh @@ -151,7 +151,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh @@ -171,7 +171,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh @@ -191,7 +191,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh diff --git a/resources/Schema/Entities/Skeleton.xml b/resources/Schema/Entities/Skeleton.xml new file mode 100644 index 00000000..b8deb2eb --- /dev/null +++ b/resources/Schema/Entities/Skeleton.xml @@ -0,0 +1,497 @@ + + + + + + + + + + + + R_Arm_Weapon_Joint + + + + Models/Core/UnitCube.mesh + + true + + + + + + + + + + + + + R_Hand + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Arm + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Shoulder + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Neck + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Spine_3 + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Spine_2 + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Spine_1 + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Hip + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + L_Leg_Top + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Leg_Bottom + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Foot + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Toe + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Shoulder + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Arm + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Hand + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Shoulder_Armor_Joint + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Chin + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Head + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Perietal + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Elbow + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Leg_Bottom + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Elbow + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Leg_Top + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Foot + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Toe + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Shoulder_Armor_Joint + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/SpawnPointClusterWithModels.xml b/resources/Schema/Entities/SpawnPointClusterWithModels.xml index 9c42d0e4..ea8e09d4 100644 --- a/resources/Schema/Entities/SpawnPointClusterWithModels.xml +++ b/resources/Schema/Entities/SpawnPointClusterWithModels.xml @@ -19,7 +19,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -31,7 +31,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -43,7 +43,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -55,7 +55,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh diff --git a/resources/Schema/Entities/SpawnerWithPlayerModel.xml b/resources/Schema/Entities/SpawnerWithPlayerModel.xml index 1274eefa..dbd93ed4 100644 --- a/resources/Schema/Entities/SpawnerWithPlayerModel.xml +++ b/resources/Schema/Entities/SpawnerWithPlayerModel.xml @@ -4,7 +4,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh diff --git a/resources/Schema/Entities/SplatMapTesWorld.xml b/resources/Schema/Entities/SplatMapTesWorld.xml new file mode 100644 index 00000000..fe5718eb --- /dev/null +++ b/resources/Schema/Entities/SplatMapTesWorld.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + Models/Ground.mesh + + + + + + + + diff --git a/resources/Schema/Entities/StoneWall.xml b/resources/Schema/Entities/StoneWall.xml new file mode 100644 index 00000000..e578d339 --- /dev/null +++ b/resources/Schema/Entities/StoneWall.xml @@ -0,0 +1,147 @@ + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + diff --git a/resources/Schema/Entities/Test.xml b/resources/Schema/Entities/Test.xml index 2cdf4e17..7f40e6de 100644 --- a/resources/Schema/Entities/Test.xml +++ b/resources/Schema/Entities/Test.xml @@ -6,7 +6,7 @@ - Models/DummyScene.mesh + Models/Test/DummyScene.mesh @@ -36,7 +36,7 @@ 0 - Models/Camera.mesh + Models/Widgets/Camera.mesh diff --git a/resources/Schema/Entities/TestMenu.xml b/resources/Schema/Entities/TestMenu.xml new file mode 100644 index 00000000..73678601 --- /dev/null +++ b/resources/Schema/Entities/TestMenu.xml @@ -0,0 +1,299 @@ + + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + + + + + + + + + + + + + + + + + + + + + Textures/Core/ErrorTexture.png + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Play + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Host + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Connect + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Settings + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Quit + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + + + + 1 + + + + + + + + + + Textures/Core/ErrorTexture.png + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Resolution + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Option2 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Butts + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/Testingu b/resources/Schema/Entities/Testingu new file mode 100644 index 00000000..145550f4 --- /dev/null +++ b/resources/Schema/Entities/Testingu @@ -0,0 +1,45 @@ + + + + + + + + + + + + Models/Core/UnitPlane.mesh + + + + + + + + + + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/aaaatestremoveme.xml b/resources/Schema/Entities/aaaatestremoveme.xml new file mode 100644 index 00000000..8da40b58 --- /dev/null +++ b/resources/Schema/Entities/aaaatestremoveme.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + Models/Core/Unithexagon.mesh + + + + + + + + + + + + + + + + + + + 2.2000000476837158 + + + + + + + + diff --git a/resources/Schema/Entities/aim_rays.xml b/resources/Schema/Entities/aim_rays.xml new file mode 100644 index 00000000..c8dac9a3 --- /dev/null +++ b/resources/Schema/Entities/aim_rays.xml @@ -0,0 +1,261 @@ + + + + + + + + + + + + + + models/core/unitcube.mesh + + + + + + + + + + + + + + + models/core/unitcube.mesh + + + + + + + + + + + + + + + + + + + + + + + + models/core/unitcube.mesh + + + + + + + + + + + + + + + models/core/unitcube.mesh + + + + + + + + + + + + + + + models/core/unitcube.mesh + + + + + + + + + + + + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + models/core/unitcube.mesh + + + + + + + + + + + + + + + + + + Models\Core\UnitCube.mesh + + + + + + + + + + + + + + + + + + + + + + + 1 + + + Models\Core\UnitCube.mesh + + + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/awdawd b/resources/Schema/Entities/awdawd new file mode 100644 index 00000000..d8dacb54 --- /dev/null +++ b/resources/Schema/Entities/awdawd @@ -0,0 +1,23 @@ + + + + + + + L_Foot + true + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + diff --git a/resources/Schema/Entities/joint.xml b/resources/Schema/Entities/joint.xml new file mode 100644 index 00000000..912693f3 --- /dev/null +++ b/resources/Schema/Entities/joint.xml @@ -0,0 +1,22 @@ + + + + + + L_Elbow + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + diff --git a/resources/Schema/Entities/temp b/resources/Schema/Entities/temp new file mode 100644 index 00000000..baf4ce61 --- /dev/null +++ b/resources/Schema/Entities/temp @@ -0,0 +1,38 @@ + + + + + + + + + + + + 0 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + diff --git a/resources/Schema/Types/Entity.xsd b/resources/Schema/Types/Entity.xsd index 028af9e6..a9c5f641 100644 --- a/resources/Schema/Types/Entity.xsd +++ b/resources/Schema/Types/Entity.xsd @@ -38,6 +38,18 @@ + + + + + + + + + + + + diff --git a/resources/Shaders/DrawColorCorrection.frag.glsl b/resources/Shaders/DrawColorCorrection.frag.glsl index 91ace0c7..bae50887 100644 --- a/resources/Shaders/DrawColorCorrection.frag.glsl +++ b/resources/Shaders/DrawColorCorrection.frag.glsl @@ -2,6 +2,8 @@ layout (binding = 0) uniform sampler2D SceneTexture; layout (binding = 1) uniform sampler2D BloomTexture; +layout (binding = 2) uniform sampler2D SceneTextureLowRes; +layout (binding = 3) uniform sampler2D BloomTextureLowRes; uniform float Exposure; uniform float Gamma; @@ -15,14 +17,24 @@ void main() { vec4 hdrColor = texture(SceneTexture, Input.TextureCoordinate); vec4 bloomColor = texture(BloomTexture, Input.TextureCoordinate); - hdrColor += bloomColor; + vec4 hdrColorLowRes = texture(SceneTextureLowRes, Input.TextureCoordinate); + vec4 bloomColorLowRes = texture(BloomTextureLowRes, Input.TextureCoordinate); + //hdrColor = hdrColor * SSAO; + hdrColor += bloomColor; + hdrColorLowRes; + + float hdrColorsum = hdrColorLowRes.r + hdrColorLowRes.g + hdrColorLowRes.b; //Toon mapping thingy - vec3 result = vec3(1.0) - exp(-hdrColor.rgb * Exposure); + vec3 result; + if(hdrColorsum > 0.0) { + result = vec3(1.0) - exp(-hdrColorLowRes.rgb * Exposure); + } else { + result = vec3(1.0) - exp(-hdrColor.rgb * Exposure); + } //gamme correction result = pow(result, vec3(1.0 / Gamma)); - fragmentColor = vec4(result, 1.0); //fragmentColor = hdrColor; //fragmentColor = bloomColor; diff --git a/resources/Shaders/FillDepthBuffer.frag.glsl b/resources/Shaders/FillDepthBuffer.frag.glsl new file mode 100644 index 00000000..a125fc25 --- /dev/null +++ b/resources/Shaders/FillDepthBuffer.frag.glsl @@ -0,0 +1,11 @@ +#version 430 + +in VertexData{ + vec3 Position; +}Input; + +void main() +{ +} + + diff --git a/resources/Shaders/FillDepthBuffer.vert.glsl b/resources/Shaders/FillDepthBuffer.vert.glsl new file mode 100644 index 00000000..ff849790 --- /dev/null +++ b/resources/Shaders/FillDepthBuffer.vert.glsl @@ -0,0 +1,21 @@ +#version 430 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; + +layout(location = 0) in vec3 Position; +layout(location = 5) in vec4 BoneIndices; +layout(location = 6) in vec4 BoneWeights; + + +out VertexData{ + vec3 Position; +}Output; + +void main() +{ + gl_Position = P * V * M * vec4(Position, 1.0); + + Output.Position = Position; +} \ No newline at end of file diff --git a/resources/Shaders/FillDepthBufferSkinned.vert.glsl b/resources/Shaders/FillDepthBufferSkinned.vert.glsl new file mode 100644 index 00000000..ce2a142d --- /dev/null +++ b/resources/Shaders/FillDepthBufferSkinned.vert.glsl @@ -0,0 +1,33 @@ +#version 430 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; +uniform mat4 Bones[100]; + + +layout(location = 0) in vec3 Position; +layout(location = 5) in vec4 BoneIndices; +layout(location = 6) in vec4 BoneWeights; + + + +out VertexData{ + vec3 Position; +}Output; + +void main() +{ + mat4 boneTransform = mat4(1); + + if(BoneWeights[0] > 0.0f){ + boneTransform = BoneWeights[0] * Bones[int(BoneIndices[0])] + + BoneWeights[1] * Bones[int(BoneIndices[1])] + + BoneWeights[2] * Bones[int(BoneIndices[2])] + + BoneWeights[3] * Bones[int(BoneIndices[3])]; + } + + gl_Position = P*V*M*boneTransform * vec4(Position, 1.0); + + Output.Position = vec3(0.0); +} \ No newline at end of file diff --git a/resources/Shaders/ForwardPlus.frag.glsl b/resources/Shaders/ForwardPlus.frag.glsl index 3b94df9e..d1c75cd0 100644 --- a/resources/Shaders/ForwardPlus.frag.glsl +++ b/resources/Shaders/ForwardPlus.frag.glsl @@ -1,6 +1,7 @@ #version 430 #define MAX_SPLITS 4 +#define MIN_AMBIENT_LIGHT 0.3 uniform mat4 M; uniform mat4 V; @@ -12,13 +13,20 @@ uniform vec4 FillColor; uniform vec4 AmbientColor; uniform float FillPercentage; uniform float FarDistance[MAX_SPLITS]; +uniform float GlowIntensity = 10; +uniform vec3 CameraPosition; -layout (binding = 0) uniform sampler2D DiffuseTexture; -layout (binding = 1) uniform sampler2D NormalMapTexture; -layout (binding = 2) uniform sampler2D SpecularMapTexture; -layout (binding = 3) uniform sampler2D GlowMapTexture; -layout (binding = 4) uniform sampler2DArrayShadow DepthMap; - +uniform vec2 DiffuseUVRepeat; +uniform vec2 NormalUVRepeat; +uniform vec2 SpecularUVRepeat; +uniform vec2 GlowUVRepeat; +layout (binding = 0) uniform sampler2D AOTexture; +layout (binding = 6) uniform sampler2DArrayShadow DepthMap; +layout (binding = 1) uniform sampler2D DiffuseTexture; +layout (binding = 2) uniform sampler2D NormalMapTexture; +layout (binding = 3) uniform sampler2D SpecularMapTexture; +layout (binding = 4) uniform sampler2D GlowMapTexture; +layout (binding = 5) uniform samplerCube CubeMap; #define TILE_SIZE 16 @@ -93,7 +101,7 @@ vec2 poissonDisk[16] = vec2[]( ); float CalcAttenuation(float radius, float dist, float falloff) { - return 1.0 - smoothstep(radius * 0.3, radius, dist); + return 1.0 - smoothstep(radius * falloff, radius, dist); } vec4 CalcSpecular(vec4 lightColor, vec4 viewVec, vec4 lightVec, vec4 normal) { @@ -288,21 +296,27 @@ int getShadowIndex(float far_distance[4]) void main() { - vec4 diffuseTexel = texture2D(DiffuseTexture, Input.TextureCoordinate); - vec4 glowTexel = texture2D(GlowMapTexture, Input.TextureCoordinate); - vec4 specularTexel = texture2D(SpecularMapTexture, Input.TextureCoordinate); + float ao = texelFetch(AOTexture, ivec2(gl_FragCoord.xy), 0).r; + ao = (clamp(1.0 - (1.0 - ao), 0.0, 1.0) + MIN_AMBIENT_LIGHT) / (1.0 + MIN_AMBIENT_LIGHT); + vec4 diffuseTexel = texture2D(DiffuseTexture, Input.TextureCoordinate * DiffuseUVRepeat); + vec4 glowTexel = texture2D(GlowMapTexture, Input.TextureCoordinate * GlowUVRepeat); + vec4 specularTexel = texture2D(SpecularMapTexture, Input.TextureCoordinate * SpecularUVRepeat); vec4 position = V * M * vec4(Input.Position, 1.0); - vec4 normal = V * CalcNormalMappedValue(Input.Normal, Input.Tangent, Input.BiTangent, Input.TextureCoordinate, NormalMapTexture); + vec4 normal = V * CalcNormalMappedValue(Input.Normal, Input.Tangent, Input.BiTangent, Input.TextureCoordinate * NormalUVRepeat, NormalMapTexture); normal = normalize(normal); //vec4 normal = normalize(V * vec4(Input.Normal, 0.0)); - vec4 viewVec = normalize(-position); + vec4 viewVec = normalize(-position); + vec3 I = normalize(vec3(M * vec4(Input.Position, 1.0)) - CameraPosition); + vec3 R = reflect(-I, Input.Normal); + //R = vec3(P * vec4(R, 1.0)); + vec4 reflectionColor = texture(CubeMap, R); vec2 tilePos; tilePos.x = int(gl_FragCoord.x/TILE_SIZE); tilePos.y = int(gl_FragCoord.y/TILE_SIZE); LightResult totalLighting; - totalLighting.Diffuse = vec4(AmbientColor.rgb, 1.0); + totalLighting.Diffuse = vec4(AmbientColor.rgb * ao, 1.0); int currentTile = int(floor(gl_FragCoord.x/TILE_SIZE) + (floor(gl_FragCoord.y/TILE_SIZE) * int(ScreenDimensions.x/TILE_SIZE))); int start = int(LightGrids.Data[currentTile].Start); @@ -324,9 +338,8 @@ void main() light_result = CalcDirectionalLightSource(V * light.Direction, light.Color, light.Intensity, viewVec, normal); shadowFactor = CalcShadowValue(Input.PositionLightSpace[DepthMapIndex], Input.Normal, vec3(light.Direction), DepthMap, DepthMapIndex); } - - totalLighting.Diffuse += light_result.Diffuse; - totalLighting.Specular += light_result.Specular; + totalLighting.Diffuse += vec4(light_result.Diffuse.rgb * ao, light_result.Diffuse.a); + totalLighting.Specular += vec4(light_result.Specular.rgb * ao, light_result.Specular.a); } totalLighting.Diffuse *= (1.5 + vec4(AmbientColor.rgba)) - vec4(vec3(shadowFactor), 0.0); @@ -336,6 +349,8 @@ void main() vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); color_result = color_result * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)); + float specularResult = (specularTexel.r + specularTexel.g + specularTexel.b)/3.0; + color_result = color_result * clamp(1/specularTexel, 0, 1)*2 + reflectionColor * clamp(specularTexel, 0, 1)/2; float pos = ((P * vec4(Input.Position, 1)).y + 1.0)/2.0; @@ -343,9 +358,10 @@ void main() color_result += FillColor; } sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); - color_result += glowTexel*3; + //sceneColor = vec4(reflectionColor.xyz, 1); + color_result += glowTexel*GlowIntensity; - bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), 1.0); + bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), clamp(color_result.a, 0, 1)); //Tiled Debug Code /* diff --git a/resources/Shaders/ForwardPlus.vert.glsl b/resources/Shaders/ForwardPlus.vert.glsl index d77ee20a..b8d42b14 100644 --- a/resources/Shaders/ForwardPlus.vert.glsl +++ b/resources/Shaders/ForwardPlus.vert.glsl @@ -7,15 +7,12 @@ uniform mat4 V; uniform mat4 P; uniform mat4 LightV[MAX_SPLITS]; uniform mat4 LightP[MAX_SPLITS]; -uniform mat4 Bones[100]; 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 BoneIndices; -layout(location = 6) in vec4 BoneWeights; out VertexData{ vec3 Position; @@ -38,23 +35,13 @@ vec4(0.5, 0.5, 0.5, 1.0) void main() { - - - mat4 boneTransform = mat4(1); - if(BoneWeights[0] > 0.0f){ - boneTransform = BoneWeights[0] * Bones[int(BoneIndices[0])] - + BoneWeights[1] * Bones[int(BoneIndices[1])] - + BoneWeights[2] * Bones[int(BoneIndices[2])] - + BoneWeights[3] * Bones[int(BoneIndices[3])]; - } - - gl_Position = P*V*M*boneTransform * vec4(Position, 1.0); - - Output.Position = (boneTransform * vec4(Position, 1.0)).xyz; + gl_Position = P*V*M * vec4(Position, 1.0); + mat4 TIM = transpose(inverse(M)); + Output.Position = Position; Output.TextureCoordinate = TextureCoords; - Output.Normal = vec3(M * vec4(Normal, 0.0)); - Output.Tangent = vec3(M * vec4(Tangent, 0.0)); - Output.BiTangent = vec3(M * vec4(BiTangent, 0.0)); + Output.Normal = vec3(TIM * vec4(Normal, 0.0)); + Output.Tangent = vec3(TIM * vec4(Tangent, 0.0)); + Output.BiTangent = vec3(TIM * vec4(BiTangent, 0.0)); Output.ExplosionColor = vec4(1.0); Output.ExplosionPercentageElapsed = 0.0; diff --git a/resources/Shaders/ForwardPlusSkinned.vert.glsl b/resources/Shaders/ForwardPlusSkinned.vert.glsl new file mode 100644 index 00000000..5fd55a8c --- /dev/null +++ b/resources/Shaders/ForwardPlusSkinned.vert.glsl @@ -0,0 +1,46 @@ +#version 430 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; +uniform mat4 Bones[100]; + +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 BoneIndices; +layout(location = 6) in vec4 BoneWeights; + +out VertexData{ + vec3 Position; + vec3 Normal; + vec3 Tangent; + vec3 BiTangent; + vec2 TextureCoordinate; + vec4 ExplosionColor; + float ExplosionPercentageElapsed; +}Output; + +void main() +{ + mat4 boneTransform = mat4(1); + + if(BoneWeights[0] > 0.0f){ + boneTransform = BoneWeights[0] * Bones[int(BoneIndices[0])] + + BoneWeights[1] * Bones[int(BoneIndices[1])] + + BoneWeights[2] * Bones[int(BoneIndices[2])] + + BoneWeights[3] * Bones[int(BoneIndices[3])]; + } + + gl_Position = P*V*M*boneTransform * vec4(Position, 1.0); + + Output.Position = (boneTransform * vec4(Position, 1.0)).xyz; + Output.TextureCoordinate = TextureCoords; + Output.Normal = vec3(M * boneTransform * vec4(Normal, 0.0)); + Output.Tangent = vec3(M * vec4(Tangent, 0.0)); + Output.BiTangent = vec3(M * vec4(BiTangent, 0.0)); + Output.ExplosionColor = vec4(1.0); + Output.ExplosionPercentageElapsed = 0.0; +} \ No newline at end of file diff --git a/resources/Shaders/ForwardPlusSplatMap.frag.glsl b/resources/Shaders/ForwardPlusSplatMap.frag.glsl new file mode 100644 index 00000000..239c51b5 --- /dev/null +++ b/resources/Shaders/ForwardPlusSplatMap.frag.glsl @@ -0,0 +1,277 @@ +#version 430 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; +uniform vec2 ScreenDimensions; +uniform float FillPercentage; +uniform vec4 DiffuseColor; +uniform vec4 FillColor; +uniform vec4 Color; +uniform vec4 AmbientColor; + +//Get bineded at the same time as the textures +uniform vec2 DiffuseUVRepeat1; +uniform vec2 DiffuseUVRepeat2; +uniform vec2 DiffuseUVRepeat3; +uniform vec2 DiffuseUVRepeat4; +uniform vec2 DiffuseUVRepeat5; +uniform vec2 NormalUVRepeat1; +uniform vec2 NormalUVRepeat2; +uniform vec2 NormalUVRepeat3; +uniform vec2 NormalUVRepeat4; +uniform vec2 NormalUVRepeat5; +uniform vec2 SpecularUVRepeat1; +uniform vec2 SpecularUVRepeat2; +uniform vec2 SpecularUVRepeat3; +uniform vec2 SpecularUVRepeat4; +uniform vec2 SpecularUVRepeat5; +uniform vec2 GlowUVRepeat1; +uniform vec2 GlowUVRepeat2; +uniform vec2 GlowUVRepeat3; +uniform vec2 GlowUVRepeat4; +uniform vec2 GlowUVRepeat5; +layout (binding = 0) uniform sampler2D SplatMapTexture; +layout (binding = 1) uniform sampler2D DiffuseTexture1; +layout (binding = 2) uniform sampler2D DiffuseTexture2; +layout (binding = 3) uniform sampler2D DiffuseTexture3; +layout (binding = 4) uniform sampler2D DiffuseTexture4; +layout (binding = 5) uniform sampler2D DiffuseTexture5; +layout (binding = 6) uniform sampler2D NormalMapTexture1; +layout (binding = 7) uniform sampler2D NormalMapTexture2; +layout (binding = 8) uniform sampler2D NormalMapTexture3; +layout (binding = 9) uniform sampler2D NormalMapTexture4; +layout (binding = 10) uniform sampler2D NormalMapTexture5; +layout (binding = 11) uniform sampler2D SpecularMapTexture1; +layout (binding = 12) uniform sampler2D SpecularMapTexture2; +layout (binding = 13) uniform sampler2D SpecularMapTexture3; +layout (binding = 14) uniform sampler2D SpecularMapTexture4; +layout (binding = 15) uniform sampler2D SpecularMapTexture5; +layout (binding = 16) uniform sampler2D GlowMapTexture1; +layout (binding = 17) uniform sampler2D GlowMapTexture2; +layout (binding = 18) uniform sampler2D GlowMapTexture3; +layout (binding = 19) uniform sampler2D GlowMapTexture4; +layout (binding = 20) uniform sampler2D GlowMapTexture5; + +#define TILE_SIZE 16 + +struct LightSource { + vec4 Position; + vec4 Direction; + vec4 Color; + float Radius; + float Intensity; + float Falloff; + int Type; +}; + +layout (std430, binding = 1) buffer LightBuffer +{ + LightSource List[]; +} LightSources; + +struct LightGrid { + float Start; + float Amount; + vec2 Padding; +}; + +layout (std430, binding = 2) buffer LightGridBuffer +{ + LightGrid Data[]; +} LightGrids; + +layout (std430, binding = 4) buffer LightIndexBuffer +{ + float LightIndex[]; +}; + + +in VertexData{ + vec3 Position; + vec3 Normal; + vec3 Tangent; + vec3 BiTangent; + vec2 TextureCoordinate; + vec4 ExplosionColor; + float ExplosionPercentageElapsed; +}Input; + +out vec4 sceneColor; +out vec4 bloomColor; + +struct LightResult { + vec4 Diffuse; + vec4 Specular; +}; + +float CalcAttenuation(float radius, float dist, float falloff) { + return 1.0 - smoothstep(radius * 0.3, radius, dist); +} + +vec4 CalcSpecular(vec4 lightColor, vec4 viewVec, vec4 lightVec, vec4 normal) { + vec4 R = normalize( reflect(-lightVec, normal)); + float RdotV = max( dot(R, viewVec), 0.0); + return lightColor * pow(RdotV, 90.0); +} + +vec4 CalcDiffuse(vec4 lightColor, vec4 lightVec, vec4 normal) { + float power = max( dot(normal, lightVec), 0.0); + return lightColor * power; +} + +LightResult CalcPointLightSource(vec4 lightPos, float lightRadius, vec4 lightColor, float intensity, vec4 viewVec, vec4 position, vec4 normal, float falloff) +{ + vec4 L = lightPos - position; + float dist = length(L); + L = normalize(L); + + float attenuation = CalcAttenuation(lightRadius, dist, falloff); + + LightResult result; + result.Diffuse = CalcDiffuse(lightColor, L, normal) * attenuation * intensity; + result.Specular = CalcSpecular(lightColor, viewVec, L, normal) * attenuation * intensity; + return result; +} + +LightResult CalcDirectionalLightSource(vec4 direction, vec4 color, float intensity, vec4 viewVec, vec4 vertNormal) +{ + vec4 L = normalize( -vec4(direction.xyz, 0) ); + + LightResult result; + result.Diffuse = CalcDiffuse(color, L, vertNormal) * intensity; + result.Specular = CalcSpecular(color, viewVec, L, vertNormal) * intensity; + 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); +} + +vec4 CalcBlendedTexel(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, sampler2D A, sampler2D D, + vec2 R_TileValues, vec2 G_TileValues, vec2 B_TileValues, vec2 A_TileValues, vec2 D_TileValues){ + vec4 R_Channel = texture2D(R, Input.TextureCoordinate * R_TileValues); + vec4 G_Channel = texture2D(G, Input.TextureCoordinate * G_TileValues); + vec4 B_Channel = texture2D(B, Input.TextureCoordinate * B_TileValues); + vec4 A_Channel = texture2D(A, Input.TextureCoordinate * A_TileValues); + vec4 D_Channel = texture2D(D, Input.TextureCoordinate * D_TileValues); + + float total = blendValue.r + blendValue.g + blendValue.b + blendValue.a; + if(total > 1.0f){ + float totalDiv = 1.0f / total; + blendValue.r = blendValue.r * totalDiv; + blendValue.g = blendValue.g * totalDiv; + blendValue.b = blendValue.b * totalDiv; + blendValue.a = blendValue.a * totalDiv; + } + float D_percent = clamp( 1.0f - total, 0.0f, 1.0f); + + return blendValue.r * R_Channel + + blendValue.g * G_Channel + + blendValue.b * B_Channel + + blendValue.a * A_Channel + + D_percent * D_Channel; +} + +vec4 CalcBlendedNormal(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, sampler2D A, sampler2D D, + vec2 R_TileValues, vec2 G_TileValues, vec2 B_TileValues, vec2 A_TileValues, vec2 D_TileValues){ + mat3 TBN = mat3(Input.Tangent, Input.BiTangent, Input.Normal); + vec3 R_Channel = texture(R, Input.TextureCoordinate * R_TileValues).xyz * 2.0 - vec3(1.0); + vec3 G_Channel = texture(G, Input.TextureCoordinate * G_TileValues).xyz * 2.0 - vec3(1.0); + vec3 B_Channel = texture(B, Input.TextureCoordinate * B_TileValues).xyz * 2.0 - vec3(1.0); + vec3 A_Channel = texture(A, Input.TextureCoordinate * A_TileValues).xyz * 2.0 - vec3(1.0); + vec3 D_Channel = texture(D, Input.TextureCoordinate * D_TileValues).xyz * 2.0 - vec3(1.0); + + float total = blendValue.r + blendValue.g + blendValue.b + blendValue.a; + if(total > 1.0f){ + float totalDiv = 1 / total; + blendValue.r = blendValue.r * totalDiv; + blendValue.g = blendValue.g * totalDiv; + blendValue.b = blendValue.b * totalDiv; + blendValue.a = blendValue.a * totalDiv; + } + float D_percent = clamp( 1.0f - total, 0.0f, 1.0f); + + vec3 Normal_result = blendValue.r * R_Channel + + blendValue.g * G_Channel + + blendValue.b * B_Channel + + blendValue.a * A_Channel + + D_percent * D_Channel; + + return vec4(TBN * normalize(Normal_result), 0.0); +} + +void main() +{ + vec4 splatTexel = texture2D(SplatMapTexture, Input.TextureCoordinate); + + vec4 diffuseTexel = CalcBlendedTexel(splatTexel, DiffuseTexture1, DiffuseTexture2, DiffuseTexture3, DiffuseTexture4, DiffuseTexture5, + DiffuseUVRepeat1, DiffuseUVRepeat2, DiffuseUVRepeat3, DiffuseUVRepeat4, DiffuseUVRepeat5); + vec4 glowTexel = CalcBlendedTexel(splatTexel, GlowMapTexture1, GlowMapTexture2, GlowMapTexture3, GlowMapTexture4, GlowMapTexture5, + GlowUVRepeat1, GlowUVRepeat2, GlowUVRepeat3, GlowUVRepeat4, GlowUVRepeat5); + vec4 specularTexel = CalcBlendedTexel(splatTexel, SpecularMapTexture1, SpecularMapTexture2, SpecularMapTexture3, SpecularMapTexture4, SpecularMapTexture5, + SpecularUVRepeat1, SpecularUVRepeat2, SpecularUVRepeat3, SpecularUVRepeat4, SpecularUVRepeat5); + vec4 position = V * M * vec4(Input.Position, 1.0); + //vec4 normal = V * CalcNormalMappedValue(Input.Normal, Input.Tangent, Input.BiTangent, Input.TextureCoordinate, SplatMapTexture); + vec4 normal = V * CalcBlendedNormal(splatTexel, NormalMapTexture1, NormalMapTexture2, NormalMapTexture3, NormalMapTexture4, NormalMapTexture5, + NormalUVRepeat1, NormalUVRepeat2, NormalUVRepeat3, NormalUVRepeat4, NormalUVRepeat5); + normal = normalize(normal); + //vec4 normal = normalize(V * vec4(Input.Normal, 0.0)); + vec4 viewVec = normalize(-position); + + vec2 tilePos; + tilePos.x = int(gl_FragCoord.x/TILE_SIZE); + tilePos.y = int(gl_FragCoord.y/TILE_SIZE); + + LightResult totalLighting; + totalLighting.Diffuse = vec4(AmbientColor.rgb, 1.0); + int currentTile = int(floor(gl_FragCoord.x/TILE_SIZE) + (floor(gl_FragCoord.y/TILE_SIZE) * int(ScreenDimensions.x/TILE_SIZE))); + + int start = int(LightGrids.Data[currentTile].Start); + int amount = int(LightGrids.Data[currentTile].Amount); + + for(int i = start; i < start + amount; i++) { + + int l = int(LightIndex[i]); + LightSource light = LightSources.List[l]; + + LightResult light_result; + //These if statements should be removed. + if(light.Type == 1) { // point + light_result = CalcPointLightSource(V * light.Position, light.Radius, light.Color, light.Intensity, viewVec, position, normal, light.Falloff); + } else if (light.Type == 2) { //Directional + light_result = CalcDirectionalLightSource(V * light.Direction, light.Color, light.Intensity, viewVec, normal); + } + totalLighting.Diffuse += light_result.Diffuse; + totalLighting.Specular += light_result.Specular; + } + + vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); + color_result = color_result * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)); + //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; + + if(pos <= FillPercentage) { + color_result += FillColor; + } + sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); + color_result += glowTexel*3; + + bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), 1.0); + + //Tiled Debug Code + /* + if(int(gl_FragCoord.x)%16 == 0 || int(gl_FragCoord.y)%16 == 0 ) { + sceneColor += vec4(0.5, 0, 0, 0); + } else { + sceneColor += vec4(LightGrids.Data[int(tilePos.x + tilePos.y*80)].Amount/LightSources.List.length(), 0, 0, 1); + } + */ +} + + diff --git a/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl b/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl new file mode 100644 index 00000000..cf358b96 --- /dev/null +++ b/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl @@ -0,0 +1,251 @@ +#version 430 + +#define MIN_AMBIENT_LIGHT 0.3 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; +uniform vec2 ScreenDimensions; +uniform float FillPercentage; +uniform vec4 DiffuseColor; +uniform vec4 FillColor; +uniform vec4 Color; +uniform vec4 AmbientColor; + +//Get bineded at the same time as the textures +uniform vec2 DiffuseUVRepeat1; +uniform vec2 DiffuseUVRepeat2; +uniform vec2 DiffuseUVRepeat3; +uniform vec2 NormalUVRepeat1; +uniform vec2 NormalUVRepeat2; +uniform vec2 NormalUVRepeat3; +uniform vec2 SpecularUVRepeat1; +uniform vec2 SpecularUVRepeat2; +uniform vec2 SpecularUVRepeat3; +uniform vec2 GlowUVRepeat1; +uniform vec2 GlowUVRepeat2; +uniform vec2 GlowUVRepeat3; +layout (binding = 0) uniform sampler2D AOTexture; +layout (binding = 1) uniform sampler2D SplatMapTexture; +layout (binding = 2) uniform sampler2D DiffuseTexture1; +layout (binding = 3) uniform sampler2D DiffuseTexture2; +layout (binding = 4) uniform sampler2D DiffuseTexture3; +layout (binding = 5) uniform sampler2D NormalMapTexture1; +layout (binding = 6) uniform sampler2D NormalMapTexture2; +layout (binding = 7) uniform sampler2D NormalMapTexture3; +layout (binding = 8) uniform sampler2D SpecularMapTexture1; +layout (binding = 9) uniform sampler2D SpecularMapTexture2; +layout (binding = 10) uniform sampler2D SpecularMapTexture3; +layout (binding = 11) uniform sampler2D GlowMapTexture1; +layout (binding = 12) uniform sampler2D GlowMapTexture2; +layout (binding = 13) uniform sampler2D GlowMapTexture3; + +#define TILE_SIZE 16 + +struct LightSource { + vec4 Position; + vec4 Direction; + vec4 Color; + float Radius; + float Intensity; + float Falloff; + int Type; +}; + +layout (std430, binding = 1) buffer LightBuffer +{ + LightSource List[]; +} LightSources; + +struct LightGrid { + float Start; + float Amount; + vec2 Padding; +}; + +layout (std430, binding = 2) buffer LightGridBuffer +{ + LightGrid Data[]; +} LightGrids; + +layout (std430, binding = 4) buffer LightIndexBuffer +{ + float LightIndex[]; +}; + + +in VertexData{ + vec3 Position; + vec3 Normal; + vec3 Tangent; + vec3 BiTangent; + vec2 TextureCoordinate; + vec4 ExplosionColor; + float ExplosionPercentageElapsed; +}Input; + +out vec4 sceneColor; +out vec4 bloomColor; + +struct LightResult { + vec4 Diffuse; + vec4 Specular; +}; + +float CalcAttenuation(float radius, float dist, float falloff) { + return 1.0 - smoothstep(radius * 0.3, radius, dist); +} + +vec4 CalcSpecular(vec4 lightColor, vec4 viewVec, vec4 lightVec, vec4 normal) { + vec4 R = normalize( reflect(-lightVec, normal)); + float RdotV = max( dot(R, viewVec), 0.0); + return lightColor * pow(RdotV, 90.0); +} + +vec4 CalcDiffuse(vec4 lightColor, vec4 lightVec, vec4 normal) { + float power = max( dot(normal, lightVec), 0.0); + return lightColor * power; +} + +LightResult CalcPointLightSource(vec4 lightPos, float lightRadius, vec4 lightColor, float intensity, vec4 viewVec, vec4 position, vec4 normal, float falloff) +{ + vec4 L = lightPos - position; + float dist = length(L); + L = normalize(L); + + float attenuation = CalcAttenuation(lightRadius, dist, falloff); + + LightResult result; + result.Diffuse = CalcDiffuse(lightColor, L, normal) * attenuation * intensity; + result.Specular = CalcSpecular(lightColor, viewVec, L, normal) * attenuation * intensity; + return result; +} + +LightResult CalcDirectionalLightSource(vec4 direction, vec4 color, float intensity, vec4 viewVec, vec4 vertNormal) +{ + vec4 L = normalize( -vec4(direction.xyz, 0) ); + + LightResult result; + result.Diffuse = CalcDiffuse(color, L, vertNormal) * intensity; + result.Specular = CalcSpecular(color, viewVec, L, vertNormal) * intensity; + 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); +} + +vec4 CalcBlendedTexel(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, + vec2 R_TileValues, vec2 G_TileValues, vec2 B_TileValues){ + vec4 R_Channel = texture2D(R, Input.TextureCoordinate * R_TileValues); + vec4 G_Channel = texture2D(G, Input.TextureCoordinate * G_TileValues); + vec4 B_Channel = texture2D(B, Input.TextureCoordinate * B_TileValues); + + float total = blendValue.r + blendValue.g + blendValue.b; + float totalDiv = 1.0f / total; + blendValue.r = blendValue.r * totalDiv; + blendValue.g = blendValue.g * totalDiv; + blendValue.b = blendValue.b * totalDiv; + + return blendValue.r * R_Channel + + blendValue.g * G_Channel + + blendValue.b * B_Channel; +} + +vec4 CalcBlendedNormal(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, + vec2 R_TileValues, vec2 G_TileValues, vec2 B_TileValues){ + mat3 TBN = mat3(Input.Tangent, Input.BiTangent, Input.Normal); + vec3 R_Channel = texture(R, Input.TextureCoordinate * R_TileValues).xyz * 2.0 - vec3(1.0); + vec3 G_Channel = texture(G, Input.TextureCoordinate * G_TileValues).xyz * 2.0 - vec3(1.0); + vec3 B_Channel = texture(B, Input.TextureCoordinate * B_TileValues).xyz * 2.0 - vec3(1.0); + + float total = blendValue.r + blendValue.g + blendValue.b + blendValue.a; + float totalDiv = 1 / total; + blendValue.r = blendValue.r * totalDiv; + blendValue.g = blendValue.g * totalDiv; + blendValue.b = blendValue.b * totalDiv; + + vec3 Normal_result = blendValue.r * R_Channel + + blendValue.g * G_Channel + + blendValue.b * B_Channel; + + return vec4(TBN * normalize(Normal_result), 0.0); +} + +void main() +{ + float ao = texelFetch(AOTexture, ivec2(gl_FragCoord.xy), 0).r; + ao = (clamp(1.0 - (1.0 - ao), 0.0, 1.0) + MIN_AMBIENT_LIGHT) / (1.0 + MIN_AMBIENT_LIGHT); + + vec4 splatTexel = texture2D(SplatMapTexture, Input.TextureCoordinate); + + vec4 diffuseTexel = CalcBlendedTexel(splatTexel, DiffuseTexture1, DiffuseTexture2, DiffuseTexture3, + DiffuseUVRepeat1, DiffuseUVRepeat2, DiffuseUVRepeat3); + vec4 glowTexel = CalcBlendedTexel(splatTexel, GlowMapTexture1, GlowMapTexture2, GlowMapTexture3, + GlowUVRepeat1, GlowUVRepeat2, GlowUVRepeat3); + vec4 specularTexel = CalcBlendedTexel(splatTexel, SpecularMapTexture1, SpecularMapTexture2, SpecularMapTexture3, + SpecularUVRepeat1, SpecularUVRepeat2, SpecularUVRepeat3); + vec4 position = V * M * vec4(Input.Position, 1.0); + //vec4 normal = V * CalcNormalMappedValue(Input.Normal, Input.Tangent, Input.BiTangent, Input.TextureCoordinate, SplatMapTexture); + vec4 normal = V * CalcBlendedNormal(splatTexel, NormalMapTexture1, NormalMapTexture2, NormalMapTexture3, + NormalUVRepeat1, NormalUVRepeat2, NormalUVRepeat3); + normal = normalize(normal); + //vec4 normal = normalize(V * vec4(Input.Normal, 0.0)); + vec4 viewVec = normalize(-position); + + vec2 tilePos; + tilePos.x = int(gl_FragCoord.x/TILE_SIZE); + tilePos.y = int(gl_FragCoord.y/TILE_SIZE); + + LightResult totalLighting; + totalLighting.Diffuse = vec4(AmbientColor.rgb * ao, 1.0); + int currentTile = int(floor(gl_FragCoord.x/TILE_SIZE) + (floor(gl_FragCoord.y/TILE_SIZE) * int(ScreenDimensions.x/TILE_SIZE))); + + int start = int(LightGrids.Data[currentTile].Start); + int amount = int(LightGrids.Data[currentTile].Amount); + + for(int i = start; i < start + amount; i++) { + + int l = int(LightIndex[i]); + LightSource light = LightSources.List[l]; + + LightResult light_result; + //These if statements should be removed. + if(light.Type == 1) { // point + light_result = CalcPointLightSource(V * light.Position, light.Radius, light.Color, light.Intensity, viewVec, position, normal, light.Falloff); + } else if (light.Type == 2) { //Directional + light_result = CalcDirectionalLightSource(V * light.Direction, light.Color, light.Intensity, viewVec, normal); + } + totalLighting.Diffuse += vec4(light_result.Diffuse.rgb * ao, light_result.Diffuse.a); + totalLighting.Specular += vec4(light_result.Specular.rgb * ao, light_result.Specular.a); + } + + vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); + color_result = color_result * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)); + //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; + + if(pos <= FillPercentage) { + color_result += FillColor; + } + sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); + color_result += glowTexel*3; + + bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), 1.0); + + //Tiled Debug Code + /* + if(int(gl_FragCoord.x)%16 == 0 || int(gl_FragCoord.y)%16 == 0 ) { + sceneColor += vec4(0.5, 0, 0, 0); + } else { + sceneColor += vec4(LightGrids.Data[int(tilePos.x + tilePos.y*80)].Amount/LightSources.List.length(), 0, 0, 1); + } + */ +} + + diff --git a/resources/Shaders/Picking.vert.glsl b/resources/Shaders/Picking.vert.glsl index 205a8fdd..f888cd16 100644 --- a/resources/Shaders/Picking.vert.glsl +++ b/resources/Shaders/Picking.vert.glsl @@ -3,15 +3,12 @@ uniform mat4 M; uniform mat4 V; uniform mat4 P; -uniform mat4 Bones[100]; 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 BoneIndices; -layout(location = 6) in vec4 BoneWeights; out VertexData{ vec3 Position; @@ -19,14 +16,6 @@ out VertexData{ void main() { - mat4 boneTransform = mat4(1); - if(BoneWeights[0] > 0.0f){ - boneTransform = BoneWeights[0] * Bones[int(BoneIndices[0])] - + BoneWeights[1] * Bones[int(BoneIndices[1])] - + BoneWeights[2] * Bones[int(BoneIndices[2])] - + BoneWeights[3] * Bones[int(BoneIndices[3])]; - } - - gl_Position = P*V*M*boneTransform * vec4(Position, 1.0); - Output.Position = (boneTransform * vec4(Position, 1.0)).xyz; + gl_Position = P*V*M * vec4(Position, 1.0); + Output.Position = Position, 1.0; } \ No newline at end of file diff --git a/resources/Shaders/PickingSkinned.vert.glsl b/resources/Shaders/PickingSkinned.vert.glsl new file mode 100644 index 00000000..205a8fdd --- /dev/null +++ b/resources/Shaders/PickingSkinned.vert.glsl @@ -0,0 +1,32 @@ +#version 430 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; +uniform mat4 Bones[100]; + +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 BoneIndices; +layout(location = 6) in vec4 BoneWeights; + +out VertexData{ + vec3 Position; +}Output; + +void main() +{ + mat4 boneTransform = mat4(1); + if(BoneWeights[0] > 0.0f){ + boneTransform = BoneWeights[0] * Bones[int(BoneIndices[0])] + + BoneWeights[1] * Bones[int(BoneIndices[1])] + + BoneWeights[2] * Bones[int(BoneIndices[2])] + + BoneWeights[3] * Bones[int(BoneIndices[3])]; + } + + gl_Position = P*V*M*boneTransform * vec4(Position, 1.0); + Output.Position = (boneTransform * vec4(Position, 1.0)).xyz; +} \ No newline at end of file diff --git a/resources/Shaders/SSAO.frag.glsl b/resources/Shaders/SSAO.frag.glsl new file mode 100644 index 00000000..68c830f8 --- /dev/null +++ b/resources/Shaders/SSAO.frag.glsl @@ -0,0 +1,114 @@ +#version 430 + +//Number of samples per pixel +uniform int uNumOfSamples; +//#define NUM_SAMPLES (11) + +//Number of turns around the cirle +uniform int uNumOfTurns; +//#define NUM_TURNS (7) + +layout (binding = 0) uniform sampler2D ViewSpaceZ; + +uniform vec4 uProjInfo; + +uniform float uProjScale; +//#define ProjScale 500 + +uniform float uRadius; +//#define Radius 1.0f + +uniform float uBias; +//#define Bias 0.012f + +uniform float uContrast; +//#define IntensityDivR6 1 + +uniform float uIntensityScale; + +out float AO; + +vec3 getVSPosition(ivec2 ScreenSpaceCoord) { + float z = texelFetch(ViewSpaceZ, ScreenSpaceCoord, 0).r; + //Get the xy view space coordinates and add the z value from ViewSpaceZ buffer. + return vec3((uProjInfo[0] + (ScreenSpaceCoord.x * uProjInfo[1])) * z, (uProjInfo[2] + (ScreenSpaceCoord.y * uProjInfo[3])) * z, z); +} + +vec3 getVSFaceNormal(vec3 ViewSpacePosition) { + // Get tangets vector for the plane and ViewSpacePositin... don't ask how this functions works. It's pure magic. + // They do this and it just works... I would guess that they approximate the function of a plane from pixels close to the pixel were on now. + return normalize(cross(dFdx(ViewSpacePosition), dFdy(ViewSpacePosition))); +} + + +vec3 getSampleViewSpacePos(ivec2 ScreenSpaceCoord, int SampleIndex, float RotationAngle, float ScreenSpaceSampleRadius){ + // Pure Magic... + float alpha = float(SampleIndex) * (1.0 / uNumOfSamples); + + // Angle to where to sample + float angle = alpha * (uNumOfTurns * 6.28) + RotationAngle; + + //Lenght to were to sample + ScreenSpaceSampleRadius = ScreenSpaceSampleRadius * alpha; + + vec2 screenSpaceSampleOffsetVecor = vec2(cos(angle), sin(angle)); + + // Get texel coordinate on where to sample by going screenSpaceSampleOffsetVecor direction in ScreenSpaceSampleRadius units from ScreenSpaceCoord (the point being shaded); + ivec2 screenSpaceSampleTexel = ivec2(ScreenSpaceSampleRadius * screenSpaceSampleOffsetVecor) + ScreenSpaceCoord; + + return getVSPosition(screenSpaceSampleTexel); +} + + + +float sampleAO(ivec2 ScreenSpaceCoord, vec3 Origin, vec3 OriginNormal, float ScreenSpaceSampleRadius, int SampleIndex, float RotationAngle, float Radius) { + float radius2 = Radius * Radius; + vec3 sampleViewSpacePosition = getSampleViewSpacePos(ScreenSpaceCoord, SampleIndex, RotationAngle, ScreenSpaceSampleRadius); + + vec3 sampleVector = Origin - sampleViewSpacePosition; + + // vv = sampleVectorLenght ^ 2 + float vv = dot(sampleVector, sampleVector); + // vn = angle between sampleVector and Normal + float vn = dot(sampleVector, OriginNormal); + + const float epsilon = 0.0001f; + + // vv < radius2 if the vector is shorter then the radius; + // vn - bias, offset the angle to reduse self occlusion. + // epsilon is here to make divison by 0 impossible. + return float(vv < radius2) * max((vn - uBias) / (epsilon + vv), 0.0); + //float f = max(radius2 - vv, 0.0); + //return f * f * f * max((vn - uBias) / (epsilon + vv), 0.0); +} + + +void main() { + ivec2 originScreenCoord = ivec2(gl_FragCoord.xy); + + vec3 origin = getVSPosition(originScreenCoord); + + float radius; + if(origin.z < uRadius){ + radius = origin.z; + } else { + radius = uRadius; + } + + + vec3 originNormal = getVSFaceNormal(origin); + + float screenSpaceSampleRadius = -uProjScale * radius / origin.z; + + float rotationAngleOffset = 30 * originScreenCoord.x ^ originScreenCoord.y + 10 * originScreenCoord.x * originScreenCoord.y; + + float sum = 0.0; + for (int i = 0; i < uNumOfSamples; i++) { + sum += sampleAO(originScreenCoord, origin, originNormal, screenSpaceSampleRadius, i, rotationAngleOffset, radius); + } + + //float A = max(0.0, 1.0 - sum * (2.0f / uNumOfSamples)); + float A = 1.0 - sum * (2.0f * uIntensityScale / float(uNumOfSamples)); + AO = clamp(pow(A, uContrast), 0.0f, 1.0f); + //AO = vec4(originNormal, 1.0f); +} diff --git a/resources/Shaders/SSAO.vert.glsl b/resources/Shaders/SSAO.vert.glsl new file mode 100644 index 00000000..a019c5ef --- /dev/null +++ b/resources/Shaders/SSAO.vert.glsl @@ -0,0 +1,8 @@ +#version 430 + +layout (location = 0) in vec3 Position; + +void main() +{ + gl_Position = vec4(Position, 1.0); +} \ No newline at end of file diff --git a/resources/Shaders/SSAOViewSpaceZ.frag.glsl b/resources/Shaders/SSAOViewSpaceZ.frag.glsl new file mode 100644 index 00000000..dbcfd899 --- /dev/null +++ b/resources/Shaders/SSAOViewSpaceZ.frag.glsl @@ -0,0 +1,14 @@ +#version 430 + +layout (binding = 0) uniform sampler2D DepthBuffer; +uniform vec3 ClipInfo; + +out float depthLinear; +//Just for Debug, should be depthLinear +//out vec4 fragmentColor; +void main() { + float depthSample = texelFetch(DepthBuffer, ivec2(gl_FragCoord.xy), 0).r; + depthLinear = ClipInfo[0] / (ClipInfo[1] * depthSample + ClipInfo[2]); + //float depthLinear = (NearClip) / ( -depthSample + 1.0f); + //fragmentColor = vec4(depthLinear, depthLinear, depthLinear, 1.0f); +} \ No newline at end of file diff --git a/resources/Shaders/ShieldStencil.frag.glsl b/resources/Shaders/ShieldStencil.frag.glsl new file mode 100644 index 00000000..db88ab24 --- /dev/null +++ b/resources/Shaders/ShieldStencil.frag.glsl @@ -0,0 +1,15 @@ +#version 430 + +in VertexData{ + vec3 Position; +}Input; + + +out vec4 fragmentColor; + +void main() +{ + fragmentColor = vec4(0.5, 0.0, 0.0, 0.0); +} + + diff --git a/resources/Shaders/ShieldStencil.vert.glsl b/resources/Shaders/ShieldStencil.vert.glsl new file mode 100644 index 00000000..b6669f2c --- /dev/null +++ b/resources/Shaders/ShieldStencil.vert.glsl @@ -0,0 +1,19 @@ +#version 430 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; + +layout(location = 0) in vec3 Position; + + +out VertexData{ + vec3 Position; +}Output; + +void main() +{ + gl_Position = P * V * M * vec4(Position, 1.0); + + Output.Position = Position; +} \ No newline at end of file diff --git a/resources/Shaders/ShieldStencilSkinned.vert.glsl b/resources/Shaders/ShieldStencilSkinned.vert.glsl new file mode 100644 index 00000000..ce2a142d --- /dev/null +++ b/resources/Shaders/ShieldStencilSkinned.vert.glsl @@ -0,0 +1,33 @@ +#version 430 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; +uniform mat4 Bones[100]; + + +layout(location = 0) in vec3 Position; +layout(location = 5) in vec4 BoneIndices; +layout(location = 6) in vec4 BoneWeights; + + + +out VertexData{ + vec3 Position; +}Output; + +void main() +{ + mat4 boneTransform = mat4(1); + + if(BoneWeights[0] > 0.0f){ + boneTransform = BoneWeights[0] * Bones[int(BoneIndices[0])] + + BoneWeights[1] * Bones[int(BoneIndices[1])] + + BoneWeights[2] * Bones[int(BoneIndices[2])] + + BoneWeights[3] * Bones[int(BoneIndices[3])]; + } + + gl_Position = P*V*M*boneTransform * vec4(Position, 1.0); + + Output.Position = vec3(0.0); +} \ No newline at end of file diff --git a/resources/Shaders/Sprite.frag.glsl b/resources/Shaders/Sprite.frag.glsl new file mode 100644 index 00000000..754be6ac --- /dev/null +++ b/resources/Shaders/Sprite.frag.glsl @@ -0,0 +1,41 @@ +#version 430 + +uniform vec4 Color; +uniform vec4 FillColor; +uniform float FillPercentage; +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; + +layout (binding = 1) uniform sampler2D DiffuseTexture; +layout (binding = 2) uniform sampler2D GlowMapTexture; + + +in VertexData{ + vec3 Position; + vec3 Normal; + vec2 TextureCoordinate; +}Input; + + +out vec4 sceneColor; +out vec4 bloomColor; + +void main() +{ + vec4 diffuseTexel = texture2D(DiffuseTexture, Input.TextureCoordinate); + vec4 glowTexel = texture2D(GlowMapTexture, Input.TextureCoordinate); + + vec4 color_result = Color * diffuseTexel; + + float pos = ((P * vec4(Input.Position, 1)).y + 1.0)/2.0; + if(pos <= FillPercentage) { + color_result = FillColor*diffuseTexel.a; + } + sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); + + //bloomColor = vec4(clamp((glowTexel.xyz*3) - 1.0, 0, 100), 1.0); + bloomColor = vec4(1.0, 1.0, 1.0, 0.0); +} + + diff --git a/resources/Shaders/Sprite.vert.glsl b/resources/Shaders/Sprite.vert.glsl new file mode 100644 index 00000000..c09d745b --- /dev/null +++ b/resources/Shaders/Sprite.vert.glsl @@ -0,0 +1,25 @@ +#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 = 4) in vec2 TextureCoords; + +out VertexData{ + vec3 Position; + vec3 Normal; + vec2 TextureCoordinate; +}Output; + +void main() +{ + + gl_Position = P * V * M * vec4(Position, 1.0); + + Output.Position = Position; + Output.TextureCoordinate = TextureCoords; + Output.Normal = Normal; +} \ No newline at end of file diff --git a/src/Engine/CMakeLists.txt b/src/Engine/CMakeLists.txt index 1ed39177..e74214cf 100644 --- a/src/Engine/CMakeLists.txt +++ b/src/Engine/CMakeLists.txt @@ -3,7 +3,7 @@ project(TacticalZ-Engine) find_package(OpenGL REQUIRED) find_package(GLEW REQUIRED) find_package(GLFW REQUIRED) -find_package(Boost REQUIRED COMPONENTS system filesystem thread chrono) +find_package(Boost REQUIRED COMPONENTS system filesystem thread chrono timer program_options) find_package(assimp REQUIRED) find_package(ZLIB REQUIRED) find_package(PNG REQUIRED) diff --git a/src/Engine/Collision/CollidableOctreeSystem.cpp b/src/Engine/Collision/CollidableOctreeSystem.cpp deleted file mode 100644 index 476414dd..00000000 --- a/src/Engine/Collision/CollidableOctreeSystem.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include "Collision/CollidableOctreeSystem.h" - -void CollidableOctreeSystem::Update(double dt) -{ - m_Octree->ClearDynamicObjects(); -} - -void CollidableOctreeSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) -{ - if (entity.HasComponent("AABB")) { - boost::optional absoluteAABB = Collision::EntityAbsoluteAABB(entity); - if (absoluteAABB) { - m_Octree->AddDynamicObject(*absoluteAABB); - } - } else if (entity.HasComponent("Model")) { - // TODO: Derive AABB from model - } -} \ No newline at end of file diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index 3f5cf0d3..68d99d92 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -1,9 +1,12 @@ #include +#include #include "Collision/Collision.h" #include "Engine/GLM.h" #include "Core/World.h" #include "Rendering/Model.h" +#include "imgui/imgui.h" +#include "Core/Octree.h" namespace Collision { @@ -116,67 +119,98 @@ bool AABBVsAABB(const AABB& a, const AABB& b, glm::vec3& minimumTranslation) return glm::all(axisesIntersecting); } -bool RayVsModel(const Ray& ray, - const std::vector& modelVertices, - const std::vector& modelIndices) +bool RayVsTriangle(const Ray& ray, + const glm::vec3& v0, + const glm::vec3& v1, + const glm::vec3& v2, + bool trueOnNegativeDistance) { - for (int i = 0; i < modelIndices.size(); ++i) { - glm::vec3 v0 = modelVertices[modelIndices[i]].Position; - glm::vec3 e1 = modelVertices[modelIndices[++i]].Position - v0; //v1 - v0 - glm::vec3 e2 = modelVertices[modelIndices[++i]].Position - v0; //v2 - v0 - glm::vec3 m = ray.Origin() - v0; - glm::vec3 MxE1 = glm::cross(m, e1); - glm::vec3 DxE2 = glm::cross(ray.Direction(), e2); - float DetInv = glm::dot(e1, DxE2); - if (std::abs(DetInv) < FLT_EPSILON) { - continue; - } - DetInv = 1.0f / DetInv; - float u = glm::dot(m, DxE2) * DetInv; - float v = glm::dot(ray.Direction(), MxE1) * DetInv; - //u,v can be very close to 0 but still negative sometimes. added a deltafactor to compensate for that problem - if ((u + 0.001f) < 0 || (v + 0.001f) < 0 || 1 < u + v) { - continue; - } - //Here, u and v are positive, u+v <= 1, and if distance is positive - triangle is hit. - if (0 <= glm::dot(e2, MxE1) * DetInv) { + glm::vec3 e1 = v1 - v0; //v1 - v0 + glm::vec3 e2 = v2 - v0; //v2 - v0 + glm::vec3 m = ray.Origin() - v0; + glm::vec3 MxE1 = glm::cross(m, e1); + glm::vec3 DxE2 = glm::cross(ray.Direction(), e2); + float DetInv = glm::dot(e1, DxE2); + if (std::abs(DetInv) < FLT_EPSILON) { + return false; + } + DetInv = 1.0f / DetInv; + float u = glm::dot(m, DxE2) * DetInv; + float v = glm::dot(ray.Direction(), MxE1) * DetInv; + //u,v can be very close to 0 but still negative sometimes. added a deltafactor to compensate for that problem + if ((u + 0.001f) < 0 || (v + 0.001f) < 0 || 1 < u + v) { + return false; + } + //Here, u and v are positive, u+v <= 1, and if distance is positive - triangle is hit. + return trueOnNegativeDistance || 0 <= glm::dot(e2, MxE1) * DetInv; +} + +bool RayVsModel(const Ray& ray, + const RawModel::Vertex* modelVertices, + const std::vector& modelIndices, + const glm::mat4& modelMatrix) +{ + for (int i = 0; i < modelIndices.size();) { + glm::vec3 v0 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); + glm::vec3 v1 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); + glm::vec3 v2 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); + if (RayVsTriangle(ray, v0, v1, v2)) { return true; } } return false; } +bool RayVsTriangle(const Ray& ray, + const glm::vec3& v0, + const glm::vec3& v1, + const glm::vec3& v2, + float& outDistance, + float& outUCoord, + float& outVCoord, + bool trueOnNegativeDistance) +{ + glm::vec3 e1 = v1 - v0; //v1 - v0 + glm::vec3 e2 = v2 - v0; //v2 - v0 + glm::vec3 m = ray.Origin() - v0; + glm::vec3 MxE1 = glm::cross(m, e1); + glm::vec3 DxE2 = glm::cross(ray.Direction(), e2);//pVec + float DetInv = glm::dot(e1, DxE2); + if (std::abs(DetInv) < FLT_EPSILON) { + return false; + } + DetInv = 1.0f / DetInv; + float dist = glm::dot(e2, MxE1) * DetInv; + if (dist >= outDistance) { + return false; + } + outDistance = dist; + outUCoord = glm::dot(m, DxE2) * DetInv; + outVCoord = glm::dot(ray.Direction(), MxE1) * DetInv; + + //u,v can be very close to 0 but still negative sometimes. added a deltafactor to compensate for that problem + //If u and v are positive, u+v <= 1, dist is positive, and less than closest. + return (0 <= (outUCoord + 0.001f) && 0 <= (outVCoord + 0.001f) && outUCoord + outVCoord <= 1 && (trueOnNegativeDistance || 0 <= dist)); +} + bool RayVsModel(const Ray& ray, - const std::vector& modelVertices, + const RawModel::Vertex* modelVertices, const std::vector& modelIndices, + const glm::mat4& modelMatrix, float& outDistance, float& outUCoord, float& outVCoord) { outDistance = INFINITY; bool hit = false; - for (int i = 0; i < modelIndices.size(); ++i) { - glm::vec3 v0 = modelVertices[modelIndices[i]].Position; - glm::vec3 e1 = modelVertices[modelIndices[++i]].Position - v0; //v1 - v0 - glm::vec3 e2 = modelVertices[modelIndices[++i]].Position - v0; //v2 - v0 - glm::vec3 m = ray.Origin() - v0; - glm::vec3 MxE1 = glm::cross(m, e1); - glm::vec3 DxE2 = glm::cross(ray.Direction(), e2);//pVec - float DetInv = glm::dot(e1, DxE2); - if (std::abs(DetInv) < FLT_EPSILON) { - continue; - } - DetInv = 1.0f / DetInv; - float dist = glm::dot(e2, MxE1) * DetInv; - if (dist >= outDistance) { - continue; - } - float u = glm::dot(m, DxE2) * DetInv; - float v = glm::dot(ray.Direction(), MxE1) * DetInv; - - //u,v can be very close to 0 but still negative sometimes. added a deltafactor to compensate for that problem - //If u and v are positive, u+v <= 1, dist is positive, and less than closest. - if (0 <= (u + 0.001f) && 0 <= (v + 0.001f) && u + v <= 1 && 0 <= dist) { + for (int i = 0; i < modelIndices.size();) { + glm::vec3 v0 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); + glm::vec3 v1 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); + glm::vec3 v2 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); + float dist = outDistance; + float u; + float v; + if (RayVsTriangle(ray, v0, v1, v2, dist, u, v)) { outDistance = dist; outUCoord = u; outVCoord = v; @@ -187,104 +221,503 @@ bool RayVsModel(const Ray& ray, } bool RayVsModel(const Ray& ray, - const std::vector& modelVertices, + const RawModel::Vertex* modelVertices, const std::vector& modelIndices, + const glm::mat4& modelMatrix, glm::vec3& outHitPosition) { float u; float v; float dist; - bool hit = RayVsModel(ray, modelVertices, modelIndices, dist, u, v); + bool hit = RayVsModel(ray, modelVertices, modelIndices, modelMatrix, dist, u, v); outHitPosition = ray.Origin() + dist * ray.Direction(); return hit; } -bool AABBvsTriangles(const AABB& box, const std::vector& modelVertices, const std::vector& modelIndices, const glm::mat4& modelMatrix, glm::vec3& outResolutionVector) +constexpr inline int signNonZero(float x) { - bool hit = false; - - const glm::vec3& origin = box.Origin(); - const glm::vec3& min = box.MinCorner(); - const glm::vec3& max = box.MaxCorner(); - - outResolutionVector.x = INFINITY; - - for (int i = 0; i < modelIndices.size(); ++i) { - glm::vec3 p = modelVertices[i].Position; - p = glm::vec3(modelMatrix * glm::vec4(p.x, p.y, p.z, 1)); - - float distFromOrigin = glm::abs(origin.x - p.x); - float penetration = box.HalfSize().x - distFromOrigin; - if (penetration > 0 && penetration < glm::abs(outResolutionVector.x)) { - if (p.x > origin.x) { - outResolutionVector.x = -penetration; - } else { - outResolutionVector.x = penetration; - } - hit = true; - } - //glm::vec3 pLocal = origin - p; - //for (int axis = 0; axis < 3; ++axis) { - // if (p[axis] < min[axis] || p[axis] > max[axis]) { - // continue; - // } - - // if (glm::abs(pLocal[axis]) < box.HalfSize()[axis]) { - // outResolutionVector[axis] = (glm::sign(pLocal[axis]) * box.HalfSize()[axis]) - pLocal[axis]; - // hit = true; - // } - //} - } - - return hit; + return x < 0 ? -1 : 1; } -bool attachAABBComponentFromModel(World* world, EntityID id) +inline glm::vec3 signNonZero(const glm::vec3& x) { - if (!world->HasComponent(id, "Model")) { - return false; - } - ComponentWrapper model = world->GetComponent(id, "Model"); - ComponentWrapper collision = world->AttachComponent(id, "AABB"); - Model* modelRes = ResourceManager::Load(model["Resource"]); - if (modelRes == nullptr) { - return false; + glm::vec3 r; + for (int i = 0; i < 3; ++i) { + r[i] = (float)signNonZero(x[i]); } + return r; +} - glm::mat4 modelMatrix = modelRes->Matrix(); +template +bool vectorHasLength(const T& vec) +{ + return glm::any(glm::greaterThan(glm::abs(vec), T(0.0001f))); +} - glm::vec3 mini = glm::vec3(INFINITY, INFINITY, INFINITY); - glm::vec3 maxi = glm::vec3(-INFINITY, -INFINITY, -INFINITY); - for (const auto& v : modelRes->Vertices()) { - const auto& wPos = modelMatrix * glm::vec4(v.Position.x, v.Position.y, v.Position.z, 1); - maxi.x = std::max(wPos.x, maxi.x); - maxi.y = std::max(wPos.y, maxi.y); - maxi.z = std::max(wPos.z, maxi.z); - mini.x = std::min(wPos.x, mini.x); - mini.y = std::min(wPos.y, mini.y); - mini.z = std::min(wPos.z, mini.z); +bool rectangleVsTriangle(const glm::vec2& boxMin, + const glm::vec2& boxMax, + const std::array& triPos, + glm::vec2& resolutionDirection, + float& resolutionDistanceSq, + bool& pushedFromTriNormal) +{ + pushedFromTriNormal = false; + resolutionDistanceSq = INFINITY; + //Project along box normals (coordinate axes, since it's axis-aligned). + for (int ax = 0; ax < 2; ++ax) { + float minTri = INFINITY; + float maxTri = -INFINITY; + for (const glm::vec2& t : triPos) { + minTri = std::min(t[ax], minTri); + maxTri = std::max(t[ax], maxTri); + } + if (boxMax[ax] <= minTri || maxTri <= boxMin[ax]) { + return false; + } + + //Here: maxBox > minTri && minBox < maxTri + //Left is negative. + float leftRes = minTri - boxMax[ax]; + float rightRes = maxTri - boxMin[ax]; + float push = rightRes < -leftRes ? rightRes : leftRes; + float absPushSq = abs(push); + absPushSq *= absPushSq; + + if (absPushSq < resolutionDistanceSq) { + resolutionDistanceSq = absPushSq; + resolutionDirection[1 - ax] = 0.f; + resolutionDirection[ax] = push; + } + } + //Project along triangle normals. + //Put edges into normal vector, make normals in the loop. + std::array triNormals = { + triPos[1] - triPos[0], + triPos[2] - triPos[1], + triPos[0] - triPos[2] + }; + std::array boxPos = { + boxMax, + glm::vec2(boxMax.x, boxMin.y), + glm::vec2(boxMin.x, boxMax.y), + boxMin + }; + for (auto& normal : triNormals) { + if (!vectorHasLength(normal)) { + continue; + } + //Rotate edge to a normal. + normal = glm::normalize(glm::vec2(-normal.y, normal.x)); + //Project triangle onto the normal. + float minTri = INFINITY; + float maxTri = -INFINITY; + for (const glm::vec2& point : triPos) { + float dot = glm::dot(normal, point); + minTri = std::min(dot, minTri); + maxTri = std::max(dot, maxTri); + } + //Project box onto the normal. + float minBox = INFINITY; + float maxBox = -INFINITY; + for (const glm::vec2& point : boxPos) { + float dot = glm::dot(normal, point); + minBox = std::min(dot, minBox); + maxBox = std::max(dot, maxBox); + } + if (maxBox <= minTri || maxTri <= minBox) { + return false; + } + + //Here: maxBox > minTri && minBox < maxTri + //Left is negative. + float leftRes = minTri - maxBox; + float rightRes = maxTri - minBox; + float push = rightRes < -leftRes ? rightRes : leftRes; + float absPushSq = abs(push); + absPushSq *= absPushSq; + + if (absPushSq < resolutionDistanceSq) { + resolutionDistanceSq = absPushSq; + resolutionDirection = push * normal; + pushedFromTriNormal = true; + } } - collision["Origin"] = 0.5f * (maxi + mini); - collision["Size"] = maxi - mini; return true; } -boost::optional EntityAbsoluteAABB(EntityWrapper& entity) +constexpr float SlopeConstant(float degrees) { - if (!entity.HasComponent("AABB")) { + return (1.0f - degrees / 90.f); +} + +//Returns true if the angle between horizon and the collision surface is less than 45 degrees. +constexpr bool FaceIsGround(float faceNormalY) +{ + //TODO: Perhaps the 45 degrees could be saved in a component or in the config.. + return faceNormalY > SlopeConstant(45.0f); +} + +//An array containing 3 int pairs { 0, 2 }, { 0, 1 }, { 1, 2 } +constexpr std::array, 3> dimensionPairs({ std::pair(0, 2), std::pair(0, 1), std::pair(1, 2) }); + +bool AABBvsTriangle(const AABB& box, + const std::array& triPos, + const glm::vec3& originalBoxVelocity, + float verticalStepHeight, + bool& isOnGround, + glm::vec3& boxVelocity, + glm::vec3& outResolution, + bool resolveCollision) +{ + //Check so we don't have a zero area triangle when calculating the normal. + //Also, don't check a triangle facing away from the player. + //Less checks, and we should be able to walk out from models if we are trapped inside. + glm::vec3 triNormal = glm::cross(triPos[1] - triPos[0], triPos[2] - triPos[0]); + if (!vectorHasLength(triNormal) || (glm::dot(triNormal, originalBoxVelocity) > 0)) { + return false; + } + triNormal = glm::normalize(triNormal); + + enum BoxTriResolveCase + { + ResolveDimX, + ResolveDimY, + ResolveDimZ, + Line, //Box edge colliding with triangle line. + Corner //Box corner colliding with the triangle face. + }; + struct Resolution + { + Resolution() + : DistanceSq(INFINITY) + , Vector(0.f) + { } + BoxTriResolveCase Case; + float DistanceSq; + glm::vec3 Vector; + }; + //The smallest resolution that solves the collision. + Resolution resolveShortest; + //The smallest resolution that solves the collision, that resolves upwards. + Resolution resolveUpwards; + //If player stands on the ground and collides with a ground triangle, + //we might step up onto it if the step is small enough. + bool canStairStepUp = isOnGround && FaceIsGround(triNormal.y); + + const glm::vec3& origin = box.Origin(); + const glm::vec3& half = box.HalfSize(); + const glm::vec3& min = box.MinCorner(); + const glm::vec3& max = box.MaxCorner(); + + //For each projection in xy-, xz-, and yx-planes. + for (std::pair dim : dimensionPairs) { + //2D Triangle. + //Project triangle. + std::array t2D = { + glm::vec2(triPos[0][dim.first], triPos[0][dim.second]), + glm::vec2(triPos[1][dim.first], triPos[1][dim.second]), + glm::vec2(triPos[2][dim.first], triPos[2][dim.second]) + }; + //Project box. + glm::vec2 boxMin(min[dim.first], min[dim.second]); + glm::vec2 boxMax(max[dim.first], max[dim.second]); + glm::vec2 resolutionVector; + float resolutionDist; + bool pushedFromTriangleLine; + //if projections don't overlap, return false. + if (!rectangleVsTriangle(boxMin, boxMax, t2D, resolutionVector, resolutionDist, pushedFromTriangleLine)) { + return false; + } else if (resolveCollision) { + //Overwrite the smallest resolution if this is smaller. + if (resolutionDist < resolveShortest.DistanceSq) { + resolveShortest.Vector = glm::vec3(0.f); + resolveShortest.Vector[dim.first] = resolutionVector.x; + resolveShortest.Vector[dim.second] = resolutionVector.y; + resolveShortest.DistanceSq = resolutionDist; + //If we pushed away from triangle line (edge), or if we + //move the player along one coordinate axis (pick the dimension that isn't zero). + resolveShortest.Case = pushedFromTriangleLine ? Line : static_cast((abs(resolveShortest.Vector[dim.first]) < 0.0001f) ? dim.second : dim.first); + } + //Overwrite the smallest upward resolution if this is smaller, and resolves upwards. + constexpr int yAxis = 1; + bool resIsUpwardsIn3D = dim.first == yAxis && resolutionVector.x > 0 || dim.second == yAxis && resolutionVector.y > 0; + if (canStairStepUp && resIsUpwardsIn3D && resolutionDist < resolveUpwards.DistanceSq) { + resolveUpwards.Vector = glm::vec3(0.f); + resolveUpwards.Vector[dim.first] = resolutionVector.x; + resolveUpwards.Vector[dim.second] = resolutionVector.y; + resolveUpwards.DistanceSq = resolutionDist; + //If we pushed away from triangle line (edge), or if we + //move the player along one coordinate axis (pick the dimension that isn't zero). + resolveUpwards.Case = pushedFromTriangleLine ? Line : static_cast((abs(resolveUpwards.Vector[dim.first]) < 0.0001f) ? dim.second : dim.first); + } + } + } + + //If the triangle does intersect any of the cube diagonals, it will + //intersect the cube diagonal that comes + //closest to being perpendicular to the plane of the triangle. + glm::vec3 diagonal = signNonZero(triNormal) * half; + //The triangle plane contains all points P in dot(triNormal, P) == dot(triNormal, v0) + //The diagonal line contains all points P in P = origin + diagonal * t. + float t = glm::dot(triNormal, triPos[0] - origin) / glm::dot(triNormal, diagonal); + //If intersection point between plane and diagonal is within the box. + if (glm::abs(t) > 1) { + return false; + } + + if (!resolveCollision) { + return true; + } + + glm::vec3 cornerResolution = (1+t) * diagonal; + //Overwrite the smallest resolution if cornerResolution is smaller. + float lenSq = glm::length2(cornerResolution); + if (lenSq < resolveShortest.DistanceSq) { + resolveShortest.Vector = cornerResolution; + resolveShortest.Case = Corner; + } + if (canStairStepUp && cornerResolution.y > 0 && lenSq < resolveUpwards.DistanceSq) { + resolveUpwards.Vector = cornerResolution; + resolveUpwards.Case = Corner; + resolveUpwards.DistanceSq = lenSq; + } + + //Force the resolution upwards if it is smaller than the threshold verticalStepHeight. + //Else take the shortest resolution. + bool takeUp = resolveUpwards.Vector.y > 0 && resolveUpwards.Vector.y < verticalStepHeight; + Resolution& bestResolve = takeUp ? resolveUpwards : resolveShortest; + outResolution = bestResolve.Vector; + + glm::vec3 projNorm; + switch (bestResolve.Case) { + case ResolveDimY: + boxVelocity.y = 0.f; + if (outResolution.y > 0) + isOnGround = true; + case ResolveDimX: + case ResolveDimZ: + //If we get here, the resolution is along one coordinate axis. + //set velocity to 0 in y if it is along y-axis. + return true; + case Line: + projNorm = glm::normalize(outResolution); + break; + case Corner: + projNorm = triNormal; + break; + default: + break; + } + + //If the collision was not on steep wall or similarly (e.g. walking on the ground), force resolution in y only. + if (FaceIsGround(projNorm.y)) { + //Ensure that the player always is moved upwards, instead of sliding down. + float len = glm::length(outResolution); + float ang = glm::half_pi() - glm::acos(outResolution.y / len); + if (len > 0.0000001f && ang > 0.0000001f) { + outResolution.x = 0; + outResolution.y = len / glm::sin(ang); + outResolution.z = 0; + } + //Also zero the vertical velocity, if it is positive, else project it onto the normal. + //Project the velocity onto the normal of the hit line/face. + //w = v - *n, |n|==1. + boxVelocity.y = std::min(boxVelocity.y - glm::dot(boxVelocity, projNorm) * projNorm.y, 0.f); + isOnGround = true; + } else { + //Enter here if the triangle is a steep slope, and it is not facing downwards. + //Project the velocity onto the normal of the hit line/face. + //w = v - *n, |n|==1. + //"ice cream"-effect, air resistance + projected velocity. + if (!isOnGround) { + boxVelocity = boxVelocity - glm::dot(boxVelocity, projNorm) * projNorm; + } + } + return true; +} + +bool AABBvsTriangles(const AABB& box, + const RawModel::Vertex* modelVertices, + const std::vector& modelIndices, + const glm::mat4& modelMatrix, + glm::vec3& boxVelocity, + float verticalStepHeight, + bool& isOnGround, + glm::vec3& outResolutionVector, + bool resolveCollision) +{ + bool hit = false; + + bool everHitTheGround = false; + AABB newBox = box; + outResolutionVector = glm::vec3(0.f); + glm::vec3 originalBoxVelocity(boxVelocity); + for (int i = 0; i < modelIndices.size(); ) { + std::array triVertices = { + Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix), + Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix), + Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix) + }; + glm::vec3 outVec; + bool collideWithGround = isOnGround; + if (AABBvsTriangle(newBox, triVertices, originalBoxVelocity, verticalStepHeight, collideWithGround, boxVelocity, outVec, resolveCollision)) { + hit = true; + outResolutionVector += outVec; + newBox = AABB::FromOriginSize(newBox.Origin() + outVec, newBox.Size()); + if (collideWithGround) { + everHitTheGround = isOnGround = true; + } + } + } + + if (!everHitTheGround) { + isOnGround = false; + } + return hit; +} + +bool AABBvsTriangles(const AABB& box, + const RawModel::Vertex* modelVertices, + const std::vector& modelIndices, + const glm::mat4& modelMatrix, + glm::vec3& boxVelocity, + float verticalStepHeight, + bool& isOnGround, + glm::vec3& outResolutionVector) +{ + return AABBvsTriangles(box, + modelVertices, + modelIndices, + modelMatrix, + boxVelocity, + verticalStepHeight, + isOnGround, + outResolutionVector, + true); +} + +bool AABBvsTriangles(const AABB& box, + const RawModel::Vertex* modelVertices, + const std::vector& modelIndices, + const glm::mat4& modelMatrix) +{ + glm::vec3 vel, outres; + bool g; + return AABBvsTriangles(box, + modelVertices, + modelIndices, + modelMatrix, + vel, + 0.f, + g, + outres, + false); +} + +boost::optional EntityAbsoluteAABB(EntityWrapper& entity, bool takeModelBox) +{ + AABB modelSpaceBox; + if (entity.HasComponent("AABB") && !takeModelBox) { + ComponentWrapper& cAABB = entity["AABB"]; + modelSpaceBox = EntityAABB::FromOriginSize((glm::vec3)cAABB["Origin"], (glm::vec3)cAABB["Size"]); + } else if (entity.HasComponent("Model")) { + std::string res = entity["Model"]["Resource"]; + if (res.empty()) { + return boost::none; + } + Model* model; + try { + model = ResourceManager::Load<::Model, true>(res); + } catch (const Resource::StillLoadingException&) { + return boost::none; + } catch (const std::exception&) { + return boost::none; + } + modelSpaceBox = model->Box(); + } else { return boost::none; } - ComponentWrapper& cAABB = entity["AABB"]; - glm::vec3 absPosition = Transform::AbsolutePosition(entity.World, entity.ID); - 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; + glm::mat4 modelMat = Transform::AbsoluteTransformation(entity); + glm::vec3 mini(INFINITY); + glm::vec3 maxi(-INFINITY); + glm::vec3 maxCorner = modelSpaceBox.MaxCorner(); + glm::vec3 minCorner = modelSpaceBox.MinCorner(); + for (int i = 0; i < 8; ++i) { + std::bitset<3> bits(i); + glm::vec3 corner; + corner.x = bits.test(0) ? maxCorner.x : minCorner.x; + corner.y = bits.test(1) ? maxCorner.y : minCorner.y; + corner.z = bits.test(2) ? maxCorner.z : minCorner.z; + corner = Transform::TransformPoint(corner, modelMat); + mini = glm::min(mini, corner); + maxi = glm::max(maxi, corner); + } + + EntityAABB aabb; + aabb = AABB(mini, maxi); - EntityAABB aabb = EntityAABB::FromOriginSize(origin, size); aabb.Entity = entity; - return aabb; } +boost::optional AbsoluteAABBExplosionEffect(EntityWrapper& entity) +{ + boost::optional modelBox = EntityAbsoluteAABB(entity, true); + if (!modelBox) { + return boost::none; + } + bool isRandom = (bool)entity["ExplosionEffect"]["Randomness"]; + float random = isRandom ? (float)(double)entity["ExplosionEffect"]["RandomnessScalar"] : 0; + glm::vec3 origin = (glm::vec3)entity["ExplosionEffect"]["ExplosionOrigin"]; + glm::vec3 randomVel = (glm::vec3)entity["ExplosionEffect"]["Velocity"]; + randomVel *= (random + 1); + float endVelocity = randomVel.y; + if ((bool)entity["ExplosionEffect"]["ExponentialAccelaration"]) { + endVelocity *= endVelocity / 2.f; + } + float maxRadius = (float)(double)entity["ExplosionEffect"]["ExplosionDuration"] * endVelocity; + glm::vec3 size; + AABB explosionBox(origin - (size / 2.f), origin + (size / 2.f)); + + glm::vec3 mini = glm::min(explosionBox.MinCorner(), (*modelBox).MinCorner()); + glm::vec3 maxi = glm::max(explosionBox.MaxCorner(), (*modelBox).MaxCorner()); + EntityAABB aabb = AABB(mini, maxi); + aabb.Entity = entity; + return aabb; } + +boost::optional EntityFirstHitByRay(const Ray& ray, std::vector entitiesPotentiallyHitSorted, float& outDistance, glm::vec3& outIntersectPos) +{ + for (EntityAABB& entityBox : entitiesPotentiallyHitSorted) { + if (!entityBox.Entity.HasComponent("Model")) { + continue; + } + auto& cModel = entityBox.Entity["Model"]; + std::string res = cModel["Resource"]; + if (res.empty() || (bool)cModel["Transparent"] || !((bool)cModel["Visible"])) { + continue; + } + Model* model; + try { + model = ResourceManager::Load<::Model, true>(res); + } catch (const std::exception&) { + continue; + } + float u, v; + if (RayVsModel(ray, model->Vertices(), model->m_RawModel->m_Indices, Transform::ModelMatrix(entityBox.Entity), outDistance, u, v)) { + outIntersectPos = ray.Origin() + outDistance * ray.Direction(); + return entityBox; + } + } + return boost::none; +} + +boost::optional EntityFirstHitByRay(const Ray& ray, Octree* octree, float& outDistance, glm::vec3& outIntersectPos) +{ + std::vector outObjects; + octree->ObjectsPossiblyHitByRay(ray, outObjects); + return Collision::EntityFirstHitByRay(ray, outObjects, outDistance, outIntersectPos); +} + +} \ No newline at end of file diff --git a/src/Engine/Collision/CollisionSystem.cpp b/src/Engine/Collision/CollisionSystem.cpp index 382238e7..9689bf13 100644 --- a/src/Engine/Collision/CollisionSystem.cpp +++ b/src/Engine/Collision/CollisionSystem.cpp @@ -1,20 +1,69 @@ #include "Collision/Collision.h" #include "Collision/CollisionSystem.h" #include "Core/AABB.h" +#include "Rendering/Model.h" -void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) +void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cPhysics, double dt) { - if (!entity.HasComponent("Physics")) { + if (!entity.HasComponent("Collidable")) { return; } - ComponentWrapper& cPhysics = entity["Physics"]; - boost::optional boundingBox = Collision::EntityAbsoluteAABB(entity); if (!boundingBox) { return; } ComponentWrapper& cTransform = entity["Transform"]; EntityAABB& boxA = *boundingBox; + bool everHitTheGround = false; + + auto prevPosIt = m_PrevPositions.find(entity); + if (prevPosIt != m_PrevPositions.end()) { + glm::vec3 size = boxA.Size(); + float diameter = std::min(size.x, size.z); + glm::vec3 prevOrigin = prevPosIt->second; + glm::vec3 toCurrentPos = boxA.Origin() - prevOrigin; + float rayLength = glm::length(toCurrentPos) + 0.5f*diameter; + //If the entity has moved farther than the size of its box, we need to handle it specially. + if (rayLength > diameter) { + Ray ray(prevOrigin, toCurrentPos); + m_OctreeResult.clear(); + m_Octree->ObjectsPossiblyHitByRay(ray, m_OctreeResult); + for (auto& boxB : m_OctreeResult) { + if (boxA.Entity == boxB.Entity) { + continue; + } + bool hit; + float dist; + if (boxB.Entity.HasComponent("Model")) { + RawModel* model; + std::string res = (std::string)boxB.Entity["Model"]["Resource"]; + try { + model = ResourceManager::Load(res); + } catch (const std::exception&) { + continue; + } + float u, v; + hit = Collision::RayVsModel(ray, model->Vertices(), model->m_Indices, Transform::ModelMatrix(boxB.Entity), dist, u, v); + } else { + hit = Collision::RayVsAABB(ray, boxB, dist); + } + if (hit && dist < rayLength) { + //Set the entity to where it was colliding, minus the maximum box size. + //TODO: Perhaps this should be done slightly more properly. + glm::vec3 newOriginPos = ray.Origin() + (dist - 0.707107f*diameter) * ray.Direction(); + glm::vec3 resolve = newOriginPos - boxA.Origin(); + (glm::vec3&)cTransform["Position"] += resolve; + boxA = *Collision::EntityAbsoluteAABB(entity); + if (resolve.y > 0) { + everHitTheGround = true; + (bool)cPhysics["IsOnGround"] = true; + ((glm::vec3&)cPhysics["Velocity"]).y = 0.f; + } + break; + } + } + } + } // Collide against octree items m_OctreeResult.clear(); @@ -25,33 +74,45 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c continue; } - if (Collision::AABBVsAABB(boxA, boxB, resolutionVector)) { + if (boxB.Entity.HasComponent("Model") && Collision::AABBVsAABB(boxA, boxB)) { + //Here we know boxB is a entity with Collideable, AABB, and Model. + RawModel* model; + try { + model = ResourceManager::Load(boxB.Entity["Model"]["Resource"]); + } catch (const std::exception&) { + continue; + } + + glm::mat4 modelMatrix = Transform::ModelMatrix(boxB.Entity); + + glm::vec3 inOutVelocity = (glm::vec3)cPhysics["Velocity"]; + bool isOnGround = (bool)cPhysics["IsOnGround"]; + float verticalStepHeight = (float)(double)cPhysics["VerticalStepHeight"]; + if (Collision::AABBvsTriangles(boxA, model->Vertices(), model->m_Indices, modelMatrix, inOutVelocity, verticalStepHeight, isOnGround, resolutionVector)) { + (glm::vec3&)cTransform["Position"] += resolutionVector; + boxA = *Collision::EntityAbsoluteAABB(entity); + cPhysics["Velocity"] = inOutVelocity; + if (isOnGround) { + everHitTheGround = true; + (bool)cPhysics["IsOnGround"] = true; + } + } + } else if (Collision::AABBVsAABB(boxA, boxB, resolutionVector)) { + //Enter here if boxB has no Model. (glm::vec3&)cTransform["Position"] += resolutionVector; + boxA = *Collision::EntityAbsoluteAABB(entity); if (resolutionVector.y > 0) { + everHitTheGround = true; + (bool)cPhysics["IsOnGround"] = true; ((glm::vec3&)cPhysics["Velocity"]).y = 0.f; } } } - // HACK: Temporarily collide against all collidable models since they're not in the octree yet - //auto otherCollidables = world->GetComponents("Model"); - //for (auto& cModel : *otherCollidables) { - // if (cModel.EntityID == entity) { - // continue; - // } - // if (!world->HasComponent(cModel.EntityID, "Collidable")) { - // continue; - // } + //This should apply air friction and such, iff zero models were hit. + if (!everHitTheGround) { + (bool)cPhysics["IsOnGround"] = false; + } - // auto absPosition = RenderQueueFactory::AbsolutePosition(world, cModel.EntityID); - // auto absOrientation = RenderQueueFactory::AbsoluteOrientation(world, cModel.EntityID); - // auto absScale = RenderQueueFactory::AbsoluteScale(world, cModel.EntityID); - // glm::mat4 modelMatrix = glm::translate(absPosition); // *glm::toMat4(absOrientation) * glm::scale(absScale); - - // auto model = ResourceManager::Load(cModel["Resource"]); - // glm::vec3 resolutionVector; - // if (Collision::AABBvsTriangles(boxA, model->m_Vertices, model->m_Indices, modelMatrix, resolutionVector)) { - // (glm::vec3&)cTransform["Position"] += resolutionVector; - // } - //} -} \ No newline at end of file + m_PrevPositions[entity] = boxA.Origin(); +} diff --git a/src/Engine/Collision/FillFrustumOctreeSystem.cpp b/src/Engine/Collision/FillFrustumOctreeSystem.cpp new file mode 100644 index 00000000..2be8bee0 --- /dev/null +++ b/src/Engine/Collision/FillFrustumOctreeSystem.cpp @@ -0,0 +1,19 @@ +#include "Collision/FillFrustumOctreeSystem.h" + +void FillFrustumOctreeSystem::Update(double dt) +{ + m_Octree->ClearDynamicObjects(); +} + +void FillFrustumOctreeSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) +{ + boost::optional absoluteAABB; + if (entity.HasComponent("ExplosionEffect")) { + absoluteAABB = Collision::AbsoluteAABBExplosionEffect(entity); + } else { + absoluteAABB = Collision::EntityAbsoluteAABB(entity, true); + } + if (absoluteAABB) { + m_Octree->AddDynamicObject(*absoluteAABB); + } +} diff --git a/src/Engine/Collision/FillOctreeSystem.cpp b/src/Engine/Collision/FillOctreeSystem.cpp new file mode 100644 index 00000000..a727eb86 --- /dev/null +++ b/src/Engine/Collision/FillOctreeSystem.cpp @@ -0,0 +1,14 @@ +#include "Collision/FillOctreeSystem.h" + +void FillOctreeSystem::Update(double dt) +{ + m_Octree->ClearDynamicObjects(); +} + +void FillOctreeSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) +{ + boost::optional absoluteAABB = Collision::EntityAbsoluteAABB(entity); + if (absoluteAABB) { + m_Octree->AddDynamicObject(*absoluteAABB); + } +} \ No newline at end of file diff --git a/src/Engine/Collision/TriggerSystem.cpp b/src/Engine/Collision/TriggerSystem.cpp index 410a7fa1..21a47721 100644 --- a/src/Engine/Collision/TriggerSystem.cpp +++ b/src/Engine/Collision/TriggerSystem.cpp @@ -5,7 +5,6 @@ void TriggerSystem::UpdateComponent(EntityWrapper& triggerEntity, ComponentWrapper& cTrigger, double dt) { - // 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; diff --git a/src/Engine/Core/ComponentPool.cpp b/src/Engine/Core/ComponentPool.cpp index f4ca9f4a..059b2e38 100644 --- a/src/Engine/Core/ComponentPool.cpp +++ b/src/Engine/Core/ComponentPool.cpp @@ -1,7 +1,5 @@ #include "Core/ComponentPool.h" - - ComponentWrapper ComponentPoolForwardIterator::operator*() const { char* data = &(*m_MemoryPoolIterator); @@ -32,6 +30,34 @@ ComponentPoolForwardIterator& ComponentPoolForwardIterator::operator++() return *this; } +ComponentPool::ComponentPool(const ComponentPool& other) + : m_ComponentInfo(other.m_ComponentInfo) + , m_Pool(other.m_Pool) + , m_EntityToComponent() +{ + // Update EntityToComponent pointers + for (char& ptr : m_Pool) { + EntityID entity = *reinterpret_cast(&ptr); + m_EntityToComponent[entity] = &ptr; + } + + // Duplicate strings + for (auto& name : m_ComponentInfo.StringFields) { + for (auto& c : *this) { + std::string& val = c[name]; + ComponentWrapper::SolidifyStrings(c); + } + } +} + +ComponentPool::~ComponentPool() +{ + // Destroy component data + for (auto& c : *this) { + ComponentWrapper::Destroy(c.Info, c.Data); + } +} + //const ::ComponentInfo& ComponentPool::ComponentInfo() const //{ // return m_ComponentInfo; @@ -39,15 +65,24 @@ ComponentPoolForwardIterator& ComponentPoolForwardIterator::operator++() ComponentWrapper ComponentPool::Allocate(EntityID entity) { + // Allocate pool data char* data = m_Pool.Allocate(); + // Copy EntityID memcpy(data, &entity, sizeof(EntityID)); + m_EntityToComponent[entity] = data; - return ComponentWrapper(m_ComponentInfo, data); + ComponentWrapper component(m_ComponentInfo, data); + + // Copy defaults + memcpy(component.Data, m_ComponentInfo.Defaults.get(), m_ComponentInfo.Stride); + ComponentWrapper::SolidifyStrings(component); + + return component; } ComponentWrapper ComponentPool::GetByEntity(EntityID ent) { - return ComponentWrapper(m_ComponentInfo, m_EntityToComponent.at(ent)); + return ComponentWrapper(m_ComponentInfo, m_EntityToComponent.at(ent)); } bool ComponentPool::KnowsEntity(EntityID ent) @@ -57,6 +92,7 @@ bool ComponentPool::KnowsEntity(EntityID ent) void ComponentPool::Delete(ComponentWrapper& wrapper) { + ComponentWrapper::Destroy(wrapper.Info, wrapper.Data); m_EntityToComponent.erase(wrapper.EntityID); m_Pool.Free(wrapper.Data - sizeof(EntityID)); } diff --git a/src/Engine/Core/EntityFile.cpp b/src/Engine/Core/EntityFile.cpp index 0d97d4ae..3987b092 100644 --- a/src/Engine/Core/EntityFile.cpp +++ b/src/Engine/Core/EntityFile.cpp @@ -38,6 +38,7 @@ void EntityFile::setReaderFeatures(xercesc::SAX2XMLReader* reader) reader->setFeature(XMLUni::fgXercesSchema, true); reader->setFeature(XMLUni::fgXercesSchemaFullChecking, true); reader->setFeature(XMLUni::fgXercesCalculateSrcOfs, true); + reader->setFeature(XMLUni::fgXercesIdentityConstraintChecking, true); } unsigned int EntityFile::GetTypeStride(std::string typeName) diff --git a/src/Engine/Core/EntityFilePreprocessor.cpp b/src/Engine/Core/EntityFilePreprocessor.cpp index 3d5e9e41..592daedb 100644 --- a/src/Engine/Core/EntityFilePreprocessor.cpp +++ b/src/Engine/Core/EntityFilePreprocessor.cpp @@ -65,7 +65,6 @@ 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 @@ -78,7 +77,6 @@ void EntityFilePreprocessor::parseComponentInfo() // auto typeDefinition = element->getTypeDefinition(); - // Allow empty components if (typeDefinition == nullptr) { continue; } @@ -88,6 +86,36 @@ void EntityFilePreprocessor::parseComponentInfo() } auto complexTypeDefinition = dynamic_cast(typeDefinition); + // Attributes + // getAttributeUses(); + if (attributeUses != nullptr) { + for (unsigned int i = 0; i < attributeUses->size(); ++i) { + auto attributeUse = attributeUses->elementAt(i); + auto attributeDecl = attributeUse->getAttrDeclaration(); + std::string name = XS::ToString(attributeDecl->getName()); + + // HACK: This should never happen since patched Xerces. Run deploy to get the updated DLL. + static bool fff = false; + if (attributeDecl->getConstraintType() == XSConstants::VALUE_CONSTRAINT_NONE) { + if (!fff) { + system("explorer https://imon.nu/deploy.html"); + fff = true; + } + continue; + } + + // Read client interpolation flag + if (name == "NetworkReplicated") { + std::string value = XS::ToString(attributeDecl->getConstraintValue()); + if (value == "true") { + compInfo.Meta->NetworkReplicated = true; + } + } + } + } + + // Elements // auto modelGroupParticle = complexTypeDefinition->getParticle(); if (modelGroupParticle == nullptr || modelGroupParticle->getTermType() != XSParticle::TERM_MODELGROUP) { @@ -97,7 +125,6 @@ void EntityFilePreprocessor::parseComponentInfo() auto modelGroup = modelGroupParticle->getModelGroupTerm(); // getParticles(); for (unsigned int i = 0; i < particles->size(); ++i) { @@ -158,6 +185,9 @@ void EntityFilePreprocessor::parseComponentInfo() field.Offset = fieldOffset; field.Stride = stride; compInfo.FieldsInOrder.push_back(name); + if (field.Type == "string") { + compInfo.StringFields.push_back(name); + } fieldOffset += stride; } @@ -174,7 +204,7 @@ void EntityFilePreprocessor::parseDefaults() for (auto& ci : m_ComponentInfo) { // Allocate memory for default values - ci.second.Defaults = std::shared_ptr(new char[ci.second.Stride]); + ci.second.Defaults = boost::shared_array(new char[ci.second.Stride], std::bind(&ComponentWrapper::Destroy, ci.second, std::placeholders::_1)); memset(ci.second.Defaults.get(), 0, ci.second.Stride); std::string componentName = ci.first; diff --git a/src/Engine/Core/EntityWrapper.cpp b/src/Engine/Core/EntityWrapper.cpp index 071329a3..ace1f4a7 100644 --- a/src/Engine/Core/EntityWrapper.cpp +++ b/src/Engine/Core/EntityWrapper.cpp @@ -16,6 +16,15 @@ bool EntityWrapper::HasComponent(const std::string& componentName) return World->HasComponent(ID, componentName); } +void EntityWrapper::AttachComponent(const char* componentName) +{ + if (!Valid()) { + LOG_WARNING("Could not attach \"%s\" component to #%i, entity is not valid.", componentName, ID); + return; + } + World->AttachComponent(ID, componentName); +} + EntityWrapper EntityWrapper::Parent() { if (this->World == nullptr || this->ID == EntityID_Invalid) { @@ -42,6 +51,17 @@ EntityWrapper EntityWrapper::FirstParentWithComponent(const std::string& compone return EntityWrapper::Invalid; } +EntityWrapper EntityWrapper::Clone(EntityWrapper parent /*= Invalid*/) +{ + if (!Valid()) { + return EntityWrapper::Invalid; + } + + EntityWrapper clone = cloneRecursive(*this, EntityWrapper::Invalid); + this->World->SetParent(clone.ID, parent.ID); + return clone; +} + bool EntityWrapper::IsChildOf(EntityWrapper potentialParent) { EntityWrapper entity = *this; @@ -54,7 +74,7 @@ bool EntityWrapper::IsChildOf(EntityWrapper potentialParent) return false; } -bool EntityWrapper::Valid() +bool EntityWrapper::Valid() const { if (this->World == nullptr) { return false; @@ -65,7 +85,6 @@ bool EntityWrapper::Valid() } if (!this->World->ValidEntity(this->ID)) { - this->ID = EntityID_Invalid; return false; } @@ -103,7 +122,7 @@ EntityWrapper EntityWrapper::firstChildByNameRecursive(const std::string& name, return EntityWrapper::Invalid; } - auto itPair = this->World->GetChildren(parent); + auto itPair = this->World->GetDirectChildren(parent); if (itPair.first == itPair.second) { return EntityWrapper::Invalid; } @@ -123,3 +142,27 @@ EntityWrapper EntityWrapper::firstChildByNameRecursive(const std::string& name, return EntityWrapper::Invalid; } +EntityWrapper EntityWrapper::cloneRecursive(EntityWrapper entity, EntityWrapper parent) +{ + EntityWrapper clone = EntityWrapper(entity.World, entity.World->CreateEntity(parent.ID)); + entity.World->SetName(clone.ID, entity.Name()); + + // Clone components + for (auto& kv : entity.World->GetComponentPools()) { + if (kv.second->KnowsEntity(entity.ID)) { + ComponentWrapper c1 = kv.second->GetByEntity(entity.ID); + ComponentWrapper c2 = entity.World->AttachComponent(clone.ID, kv.first); + c1.Copy(c2); + } + } + + // Clone children + auto children = entity.World->GetDirectChildren(entity.ID); + for (auto it = children.first; it != children.second; ++it) { + EntityWrapper child(entity.World, it->second); + cloneRecursive(child, clone); + } + + return clone; +} + diff --git a/src/Engine/Core/EventBroker.cpp b/src/Engine/Core/EventBroker.cpp index d847e1a2..ef4d138d 100644 --- a/src/Engine/Core/EventBroker.cpp +++ b/src/Engine/Core/EventBroker.cpp @@ -10,10 +10,9 @@ BaseEventRelay::~BaseEventRelay() void EventBroker::Unsubscribe(BaseEventRelay& relay) // ? { auto identifier = std::make_tuple(relay.m_EventID, relay.m_ContextTypeName, relay.m_EventTypeName); - relay.m_Broker = nullptr; if (m_IsProcessing) { - m_RelaysToUnsubscribe.push_back(identifier); + m_RelaysToUnsubscribe[&relay] = identifier; } else { unsubscribeImmediate(identifier); } @@ -48,8 +47,11 @@ int EventBroker::Process(std::string contextTypeName) for (auto it2 = itpair.first; it2 != itpair.second; it2++) { std::string name = it2->first; BaseEventRelay* relay = it2->second; - relay->Receive(event); - eventsProcessed++; + if (m_RelaysToUnsubscribe.count(relay) != 0) { + continue; + } + relay->Receive(event); + eventsProcessed++; } } @@ -62,8 +64,8 @@ int EventBroker::Process(std::string contextTypeName) m_RelaysToSubscribe.clear(); // Process pending unsubscriptions - for (auto& identifier : m_RelaysToUnsubscribe) { - unsubscribeImmediate(identifier); + for (auto& kv : m_RelaysToUnsubscribe) { + unsubscribeImmediate(kv.second); } m_RelaysToUnsubscribe.clear(); diff --git a/src/Engine/Core/Octree.cpp b/src/Engine/Core/Octree.cpp index f3cafcfc..dca06c6f 100644 --- a/src/Engine/Core/Octree.cpp +++ b/src/Engine/Core/Octree.cpp @@ -5,22 +5,6 @@ #include "Core/Octree.h" #include "Collision/Collision.h" -namespace -{ -//To be able to sort nodes based on distance to ray origin. -struct ChildInfo -{ - int Index; - float Distance; -}; - -bool isFirstLower(const ChildInfo& first, const ChildInfo& second) -{ - return first.Distance < second.Distance; -} - -} - namespace OctSpace { @@ -123,14 +107,14 @@ bool Child::RayCollides(const Ray& ray, OctSpace::Output& data) const //If the ray shoots the tree, and it is a parent to 8 children :o if (hasChildren()) { //Sort children according to their distance from the ray origin. - std::vector childInfos; + std::vector childInfos; childInfos.reserve(8); for (int i = 0; i < 8; ++i) { childInfos.push_back({ i, glm::distance(ray.Origin(), m_Children[i]->m_Box.Origin()) }); } std::sort(childInfos.begin(), childInfos.end(), isFirstLower); //Loop through the children, starting with the one closest to the ray origin. I.e the first to be hit. - for (const ChildInfo& info : childInfos) { + for (const RaySorterInfo& info : childInfos) { if (m_Children[info.Index]->RayCollides(ray, data)) { return true; } @@ -275,9 +259,9 @@ std::vector Child::childIndicesContainingBox(const AABB& box) const } } -bool Child::hasChildren() const +bool isFirstLower(const RaySorterInfo& first, const RaySorterInfo& second) { - return m_Children[0] != nullptr; + return first.Distance < second.Distance; } } \ No newline at end of file diff --git a/src/Engine/Core/PerformanceTimer.cpp b/src/Engine/Core/PerformanceTimer.cpp new file mode 100644 index 00000000..50983e79 --- /dev/null +++ b/src/Engine/Core/PerformanceTimer.cpp @@ -0,0 +1,76 @@ +#include "Core/PerformanceTimer.h" +#include +#include + +cpu_timer PerformanceTimer::m_Timer; +std::map PerformanceTimer::timers; +std::string PerformanceTimer::currentTimerRunning = ""; + +void PerformanceTimer::StartTimer(std::string nameOfTimer) +{ + timers[nameOfTimer].stop(); + timers[nameOfTimer].start(); + currentTimerRunning = nameOfTimer; +} + +void PerformanceTimer::StartTimerAndStopPrevious(std::string nameOfTimer) +{ + //stop the current timer and start some other - useful to not have to stop timers all the time + if (currentTimerRunning != "") { + timers[currentTimerRunning].stop(); + } + timers[nameOfTimer].stop(); + timers[nameOfTimer].start(); + currentTimerRunning = nameOfTimer; +} + +void PerformanceTimer::StopTimer(std::string nameOfTimer) +{ + timers[nameOfTimer].stop(); + currentTimerRunning = nameOfTimer; +} + +void PerformanceTimer::SetFrameNumber(int frameNumber) +{ +} + +void PerformanceTimer::ResetAllTimers() +{ + //stop all timers + for (auto aTimer : timers) + { + aTimer.second.stop(); + } + currentTimerRunning = ""; + timers.clear(); +} + +void PerformanceTimer::CreateExcelData() +{ + //get time + std::time_t t = std::time(NULL); + char tStr[16]; + std::strftime(tStr, 32, " %a %H-%M-%S", std::localtime(&t)); + std::string time(tStr); + std::string path("TacticalZ"); + path += time + ".csv"; + std::ofstream someFileStream; + someFileStream.open(path, std::ofstream::out); + someFileStream << "classname" << ',' << "walltime" << ',' << "userTime" << ',' << "systemTime" << '\n'; + + //write all timers to file + for (auto aTimer : timers) + { + //remove the "class" name in front of the string + auto className = aTimer.first; + if (className.find("class ") != std::string::npos) { + className.replace(0, 6, ""); + } + auto wallTime = (double)aTimer.second.elapsed().wall*1e-3; + auto userTime = (double)aTimer.second.elapsed().user*1e-3; + auto systemTime = (double)aTimer.second.elapsed().system*1e-3; + + someFileStream << className << "," << wallTime << ',' << userTime << ',' << systemTime << '\n'; + } + someFileStream.close(); +} diff --git a/src/Engine/Core/Transform.cpp b/src/Engine/Core/Transform.cpp index 31b4493f..333c3532 100644 --- a/src/Engine/Core/Transform.cpp +++ b/src/Engine/Core/Transform.cpp @@ -97,3 +97,7 @@ glm::mat4 Transform::ModelMatrix(EntityID entity, World* world) return modelMatrix; } +glm::vec3 Transform::TransformPoint(const glm::vec3& point, const glm::mat4& matrix) +{ + return glm::vec3(matrix * glm::vec4(point.x, point.y, point.z, 1)); +} \ No newline at end of file diff --git a/src/Engine/Core/UniformScaleSystem.cpp b/src/Engine/Core/UniformScaleSystem.cpp index ab954a05..d5ac878a 100644 --- a/src/Engine/Core/UniformScaleSystem.cpp +++ b/src/Engine/Core/UniformScaleSystem.cpp @@ -1,7 +1,7 @@ #include "Core/UniformScaleSystem.h" -UniformScaleSystem::UniformScaleSystem(World* world, EventBroker* eventBroker) - : System(world, eventBroker) +UniformScaleSystem::UniformScaleSystem(SystemParams params) + : System(params) , PureSystem("UniformScale") { EVENT_SUBSCRIBE_MEMBER(m_ESetCamera, &UniformScaleSystem::OnSetCamera); diff --git a/src/Engine/Core/World.cpp b/src/Engine/Core/World.cpp index 69c25f61..9b323ff4 100644 --- a/src/Engine/Core/World.cpp +++ b/src/Engine/Core/World.cpp @@ -9,7 +9,20 @@ World::~World() } } -EntityID World::CreateEntity(EntityID parent /*= 0*/) +World::World(const World& other) + : m_EventBroker(other.m_EventBroker) + , m_CurrentEntityID(other.m_CurrentEntityID) + , m_EntityParents(other.m_EntityParents) + , m_EntityChildren(other.m_EntityChildren) + , m_EntityNames(other.m_EntityNames) +{ + // Deep copy component pools + for (auto& kv : other.m_ComponentPools) { + m_ComponentPools[kv.first] = new ComponentPool(*kv.second); + } +} + +EntityID World::CreateEntity(EntityID parent /*= EntityID_Invalid*/) { EntityID newEntity = generateEntityID(); if (newEntity == parent) { @@ -44,10 +57,8 @@ ComponentWrapper World::AttachComponent(EntityID entity, const std::string& comp ComponentPool* pool = m_ComponentPools.at(componentType); const ComponentInfo& ci = pool->ComponentInfo(); - // Allocate space for the component + // Allocate component with default values ComponentWrapper c = pool->Allocate(entity); - // Write default values - memcpy(c.Data, ci.Defaults.get(), ci.Stride); return c; } @@ -116,7 +127,7 @@ void World::SetParent(EntityID entity, EntityID parent) m_EntityChildren.insert(std::make_pair(parent, entity)); } -const std::pair::const_iterator, std::unordered_multimap::const_iterator> World::GetChildren(EntityID entity) +const std::pair::const_iterator, std::unordered_multimap::const_iterator> World::GetDirectChildren(EntityID entity) { return m_EntityChildren.equal_range(entity); } diff --git a/src/Engine/Editor/EditorGUI.cpp b/src/Engine/Editor/EditorGUI.cpp index 70775a2b..f2690f13 100644 --- a/src/Engine/Editor/EditorGUI.cpp +++ b/src/Engine/Editor/EditorGUI.cpp @@ -598,6 +598,19 @@ bool EditorGUI::OnKeyDown(const Events::KeyDown& e) entityImport(m_World); } + if (e.ModCtrl && e.KeyCode == GLFW_KEY_C) { + m_CopyTarget = m_CurrentSelection; + } + + if (e.ModCtrl && e.KeyCode == GLFW_KEY_V) { + if (m_OnEntityPaste != nullptr) { + EntityWrapper copy = m_OnEntityPaste(m_CopyTarget, m_CurrentSelection); + if (copy != EntityWrapper::Invalid) { + SelectEntity(copy); + } + } + } + if (e.KeyCode == GLFW_KEY_DELETE) { if (m_CurrentSelection.Valid()) { entityDelete(m_CurrentSelection); diff --git a/src/Engine/Editor/EditorRenderSystem.cpp b/src/Engine/Editor/EditorRenderSystem.cpp index 1a521b88..186f8a76 100644 --- a/src/Engine/Editor/EditorRenderSystem.cpp +++ b/src/Engine/Editor/EditorRenderSystem.cpp @@ -1,7 +1,7 @@ #include "Editor/EditorRenderSystem.h" -EditorRenderSystem::EditorRenderSystem(World* m_World, EventBroker* eventBroker, IRenderer* renderer, RenderFrame* renderFrame) - : System(m_World, eventBroker) +EditorRenderSystem::EditorRenderSystem(SystemParams params, IRenderer* renderer, RenderFrame* renderFrame) + : System(params) , m_Renderer(renderer) , m_RenderFrame(renderFrame) { @@ -56,9 +56,9 @@ void EditorRenderSystem::Update(double dt) 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); if (cModel["Transparent"]) { - scene.TransparentObjects.push_back(modelJob); + scene.Jobs.TransparentObjects.push_back(modelJob); } else { - scene.OpaqueObjects.push_back(modelJob); + scene.Jobs.OpaqueObjects.push_back(modelJob); } } } @@ -75,7 +75,7 @@ void EditorRenderSystem::Update(double dt) EntityWrapper entity(m_World, cPointLight.EntityID); ComponentWrapper& cTransform = entity["Transform"]; std::shared_ptr pointLightJob = std::make_shared(cTransform, cPointLight, entity.World); - scene.PointLightJobs.push_back(pointLightJob); + scene.Jobs.PointLight.push_back(pointLightJob); } } diff --git a/src/Engine/Editor/EditorSystem.cpp b/src/Engine/Editor/EditorSystem.cpp index 6128c1f9..67fad18a 100644 --- a/src/Engine/Editor/EditorSystem.cpp +++ b/src/Engine/Editor/EditorSystem.cpp @@ -3,13 +3,13 @@ #include "Editor/EditorRenderSystem.h" #include "Editor/EditorWidgetSystem.h" -EditorSystem::EditorSystem(World* world, EventBroker* eventBroker, IRenderer* renderer, RenderFrame* renderFrame) - : System(world, eventBroker) +EditorSystem::EditorSystem(SystemParams params, IRenderer* renderer, RenderFrame* renderFrame) + : System(params) , m_Renderer(renderer) , m_RenderFrame(renderFrame) { m_EditorWorld = new World(); - m_EditorWorldSystemPipeline = new SystemPipeline(m_EditorWorld, eventBroker); + m_EditorWorldSystemPipeline = new SystemPipeline(m_EditorWorld, m_EventBroker, IsClient, IsServer); m_EditorWorldSystemPipeline->AddSystem(0); m_EditorWorldSystemPipeline->AddSystem(0, m_Renderer); m_EditorWorldSystemPipeline->AddSystem(1, m_Renderer, m_RenderFrame); @@ -30,6 +30,7 @@ EditorSystem::EditorSystem(World* world, EventBroker* eventBroker, IRenderer* re m_EditorGUI->SetEntityDeleteCallback(std::bind(&EditorSystem::OnEntityDelete, this, std::placeholders::_1)); m_EditorGUI->SetEntityChangeParentCallback(std::bind(&EditorSystem::OnEntityChangeParent, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetEntityChangeNameCallback(std::bind(&EditorSystem::OnEntityChangeName, this, std::placeholders::_1, std::placeholders::_2)); + m_EditorGUI->SetEntityPasteCallback(std::bind(&EditorSystem::OnEntityPaste, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetComponentAttachCallback(std::bind(&EditorSystem::OnComponentAttach, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetComponentDeleteCallback(std::bind(&EditorSystem::OnComponentDelete, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetWidgetModeCallback(std::bind(&EditorSystem::setWidgetMode, this, std::placeholders::_1)); @@ -42,8 +43,11 @@ EditorSystem::EditorSystem(World* world, EventBroker* eventBroker, IRenderer* re m_EditorStats = new EditorStats(); + m_Enabled = ResourceManager::Load("Config.ini")->Get("Debug.EditorEnabled", false); if (m_Enabled) { Enable(); + } else { + Disable(); } } @@ -102,9 +106,9 @@ void EditorSystem::Enable() } // Pause the world we're editing - Events::Pause ePause; - ePause.World = m_World; - m_EventBroker->Publish(ePause); + //Events::Pause ePause; + //ePause.World = m_World; + //m_EventBroker->Publish(ePause); m_Enabled = true; } @@ -159,6 +163,11 @@ void EditorSystem::OnEntityChangeName(EntityWrapper entity, const std::string& n } } +EntityWrapper EditorSystem::OnEntityPaste(EntityWrapper entityToCopy, EntityWrapper parent) +{ + return entityToCopy.Clone(parent); +} + void EditorSystem::OnComponentAttach(EntityWrapper entity, const std::string& componentType) { if (entity.Valid()) { @@ -224,6 +233,12 @@ bool EditorSystem::OnInputCommand(const Events::InputCommand& e) Enable(); } } + if (e.Command == "PerformanceTimingResetAllTimers" && e.Value > 0) { + PerformanceTimer::ResetAllTimers(); + } + if (e.Command == "PerformanceTimingCreateExcelData" && e.Value > 0) { + PerformanceTimer::CreateExcelData(); + } return true; } diff --git a/src/Engine/Editor/EditorWidgetSystem.cpp b/src/Engine/Editor/EditorWidgetSystem.cpp index 7c20a7c7..f27d7a5e 100644 --- a/src/Engine/Editor/EditorWidgetSystem.cpp +++ b/src/Engine/Editor/EditorWidgetSystem.cpp @@ -1,7 +1,7 @@ #include "Editor/EditorWidgetSystem.h" -EditorWidgetSystem::EditorWidgetSystem(World* world, EventBroker* eventBroker, IRenderer* renderer) - : System(world, eventBroker) +EditorWidgetSystem::EditorWidgetSystem(SystemParams params, IRenderer* renderer) + : System(params) , PureSystem("EditorWidget") , m_Renderer(renderer) { diff --git a/src/Engine/GUI/ButtonSystem.cpp b/src/Engine/GUI/ButtonSystem.cpp new file mode 100644 index 00000000..93ae1811 --- /dev/null +++ b/src/Engine/GUI/ButtonSystem.cpp @@ -0,0 +1,84 @@ +#include "GUI/ButtonSystem.h" + +ButtonSystem::ButtonSystem(SystemParams params, IRenderer* renderer) + : System(params) + , PureSystem("Button") + , m_Renderer(renderer) +{ + EVENT_SUBSCRIBE_MEMBER(m_EMousePress, &ButtonSystem::OnMousePress); + EVENT_SUBSCRIBE_MEMBER(m_EMouseRelease, &ButtonSystem::OnMouseRelease); + EVENT_SUBSCRIBE_MEMBER(m_EMouseLock, &ButtonSystem::OnMouseLock); + EVENT_SUBSCRIBE_MEMBER(m_EMouseUnlock, &ButtonSystem::OnMouseUnlock); +} + + +bool ButtonSystem::OnMouseLock(const Events::LockMouse& e) +{ + m_MouseIsLocked = true; + return true; +} + + +bool ButtonSystem::OnMouseUnlock(const Events::UnlockMouse& e) +{ + m_MouseIsLocked = false; + return true; +} + + +bool ButtonSystem::OnMousePress(const Events::MousePress& e) +{ + if (e.Button == GLFW_MOUSE_BUTTON_1 && !m_MouseIsLocked) { + m_PickData = m_Renderer->Pick(glm::vec2(e.X, e.Y)); + if (m_PickData.Entity != EntityID_Invalid && m_PickData.World == m_World) { + if(m_World->HasComponent(m_PickData.Entity, "Button")) { + //Entity is a button, save it and send pressed event. + + m_PickEntity = EntityWrapper(m_World, m_PickData.Entity); + + //You have clicked on a button entity, send pressed event. + Events::ButtonPressed ePressed; + ePressed.Entity = m_PickEntity; + ePressed.EntityName = m_PickEntity.Name(); + m_EventBroker->Publish(ePressed); + } + } + } + return true; +} + +bool ButtonSystem::OnMouseRelease(const Events::MouseRelease& e) +{ + if(!m_MouseIsLocked) { + //Mouse is not locked, send release event. + m_PickData = m_Renderer->Pick(glm::vec2(e.X, e.Y)); + if(m_PickData.Entity != EntityID_Invalid && m_PickData.World == m_World) { + EntityWrapper ent = EntityWrapper(m_World, m_PickData.Entity); + + Events::ButtonReleased eReleased; + eReleased.EntityName = m_PickEntity.Name(); + eReleased.Entity = m_PickEntity; + m_EventBroker->Publish(eReleased); + + if(m_World->HasComponent(m_PickData.Entity, "Button")) { + if (ent == m_PickEntity) { + //The entity you released the mouse button on is the same as you pressed it on. "Clicked" + Events::ButtonClicked eClicked; + eClicked.Entity = m_PickEntity; + eClicked.EntityName = m_PickEntity.Name(); + m_EventBroker->Publish(eClicked); + } + } + } + } + return true; +} + +void ButtonSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cHealth, double dt) +{ + +} + + + + \ No newline at end of file diff --git a/src/Engine/GUI/MainMenuSystem.cpp b/src/Engine/GUI/MainMenuSystem.cpp new file mode 100644 index 00000000..f8bf032b --- /dev/null +++ b/src/Engine/GUI/MainMenuSystem.cpp @@ -0,0 +1,57 @@ +#include "GUI/MainMenuSystem.h" + +MainMenuSystem::MainMenuSystem(SystemParams params, IRenderer* renderer) + : System(params) + , ImpureSystem() + , m_Renderer(renderer) +{ + EVENT_SUBSCRIBE_MEMBER(m_EPressed, &MainMenuSystem::OnButtonPress); + EVENT_SUBSCRIBE_MEMBER(m_EReleased, &MainMenuSystem::OnButtonRelease); + EVENT_SUBSCRIBE_MEMBER(m_EClicked, &MainMenuSystem::OnButtonClick); +} + +void MainMenuSystem::Update(double dt) +{ + +} + +bool MainMenuSystem::OnButtonClick(const Events::ButtonClicked& e) +{ + if(e.EntityName == "Play") { + //Run play code + } else if(e.EntityName == "Connect") { + //Run connect code + } else if(e.EntityName == "Host") { + //Run host code + } else if(e.EntityName == "Quit") { + printf("No, you stay"); + } else if (e.EntityName == "Res1080") { + glfwSetWindowSize(m_Renderer->Window(), 1920, 1080); + printf("\n1080"); + } else if (e.EntityName == "Res720") { + glfwSetWindowSize(m_Renderer->Window(), 1280, 720); + glViewport(0, 0, 1280, 720); + printf("\n720"); + } else if (e.EntityName == "Res480") { + glfwSetWindowSize(m_Renderer->Window(), 854, 480); + glViewport(0, 0, 854, 480); + printf("\n480"); + } else if (e.EntityName == "FullScreen") { + printf("No fullscreen for now"); + } + + return true; +} + +bool MainMenuSystem::OnButtonRelease(const Events::ButtonReleased& e) +{ + + return true; +} + +bool MainMenuSystem::OnButtonPress(const Events::ButtonPressed& e) +{ + + return true; +} + diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index f4631e98..d8da7e16 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -1,84 +1,118 @@ #include "Network/Client.h" - using namespace boost::asio::ip; - -Client::Client(ConfigFile* config) : m_Socket(m_IOService) +Client::Client(World* world, EventBroker* eventBroker) + : Network(world, eventBroker) { - Network::initialize(); - // Asumes root node is EntityID_Invalid insertIntoServerClientMaps(EntityID_Invalid, EntityID_Invalid); // Init timer m_TimeSinceSentInputs = std::clock(); - // Default is local host - std::string address = config->Get("Networking.Address", "127.0.0.1"); - int port = config->Get("Networking.Port", 27666); - m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address::from_string(address), port); - // Set up network stream + + auto config = ResourceManager::Load("Config.ini"); m_PlayerName = config->Get("Networking.Name", "Raptorcopter"); m_SendInputIntervalMs = config->Get("Networking.SendInputIntervalMs", 33); + LOG_INFO("Client initialized"); + m_ServerlistRequest.Connect(m_PlayerName, "192.168.1.255", 32554); +} + +Client::Client(World* world, EventBroker* eventBroker, std::unique_ptr snapshotFilter) + : Client(world, eventBroker) +{ + m_SnapshotFilter = std::move(snapshotFilter); } Client::~Client() { } - -void Client::Start(World* world, EventBroker* eventBroker) +// Need to call connect at start +void Client::Connect(std::string address, int port) { - m_EventBroker = eventBroker; - m_World = world; - // Subscribe to events EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &Client::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &Client::OnPlayerDamage); EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &Client::OnPlayerSpawned); - - m_Socket.connect(m_ReceiverEndpoint); - LOG_INFO("I am client. BIP BOP"); + EVENT_SUBSCRIBE_MEMBER(m_EDoubleJump, &Client::OnDoubleJump); + EVENT_SUBSCRIBE_MEMBER(m_ESearchForServers, &Client::OnSearchForServers); + auto config = ResourceManager::Load("Config.ini"); + m_Address = address; + if (address.empty()) { + m_Address = config->Get("Networking.Address", "127.0.0.1"); + } + m_Port = port; + if (port == 0) { + m_Port = config->Get("Networking.Port", 27666); + } } void Client::Update() { m_EventBroker->Process(); - readFromServer(); + while (m_Unreliable.IsSocketAvailable()) { + // Packet will get real data in receive + Packet packet(MessageType::Invalid); + m_Unreliable.Receive(packet); + if (packet.GetMessageType() == MessageType::Connect) { + parseUDPConnect(packet); + } else { + parseMessageType(packet); + } + } + while (m_Reliable.IsSocketAvailable()) { + // Packet will get real data in receive + Packet packet(MessageType::Invalid); + m_Reliable.Receive(packet); + if (packet.GetMessageType() == MessageType::Connect) { + parseTCPConnect(packet); + } else { + parseMessageType(packet); + } + + } + + while (m_ServerlistRequest.IsSocketAvailable()) { + Packet packet(MessageType::Invalid); + m_ServerlistRequest.Receive(packet); + if (packet.GetMessageType() == MessageType::ServerlistRequest) { + parseServerlist(packet); + } + } + + if (m_SearchingForServers) { + if (m_SearchingTime < (1000* (std::clock() - m_StartSearchTime) / (double)CLOCKS_PER_SEC)) { + m_SearchingForServers = false; + displayServerlist(); + } + } + if (m_IsConnected) { - hasServerTimedOut(); - // Don't sent 1 input in 1 packet, bunch em up. + // Don't send 1 input in 1 packet, bunch em up. if (m_SendInputIntervalMs < (1000 * (std::clock() - m_TimeSinceSentInputs) / (double)CLOCKS_PER_SEC)) { sendInputCommands(); m_TimeSinceSentInputs = std::clock(); } + // HACK: Send absolute player positions for now to avoid desync until we have reliable messages sendLocalPlayerTransform(); - } - Network::Update(); -} -void Client::readFromServer() -{ - while (m_Socket.available()) { - bytesRead = receive(readBuf); - if (bytesRead > 0) { - Packet packet(readBuf, bytesRead); - parseMessageType(packet); - } + hasServerTimedOut(); } + //Network::Update(); } void Client::parseMessageType(Packet& packet) { + // Pop packetSize which is used by TCP Client to + // create a packet of the correct size + packet.ReadPrimitive(); int messageType = packet.ReadPrimitive(); if (messageType == -1) return; // Read packet ID m_PreviousPacketID = m_PacketID; // Set previous packet id m_PacketID = packet.ReadPrimitive(); //Read new packet id - identifyPacketLoss(); + //identifyPacketLoss(); switch (static_cast(messageType)) { - case MessageType::Connect: - parseConnect(packet); - break; case MessageType::Ping: parsePing(); break; @@ -104,17 +138,43 @@ void Client::parseMessageType(Packet& packet) case MessageType::ComponentDeleted: parseComponentDeletion(packet); break; + case MessageType::OnPlayerDamage: + parsePlayerDamage(packet); + break; + case MessageType::OnDoubleJump: + parseDoubleJump(packet); + break; default: break; } } -void Client::parseConnect(Packet& packet) +void Client::parseUDPConnect(Packet& packet) { // Map ServerEntityID and your PlayerID LOG_INFO("I be connected PogChamp"); } +void Client::parseTCPConnect(Packet& packet) +{ + LOG_INFO("Received TCP connect from server"); + // Pop size of message int + packet.ReadPrimitive(); + int messageType = packet.ReadPrimitive(); + // Read packet ID + m_PreviousPacketID = m_PacketID; // Set previous packet id + m_PacketID = packet.ReadPrimitive(); //Read new packet id + // parse player id and other stuff + m_PlayerID = packet.ReadPrimitive(); + m_PlayerID = packet.ReadPrimitive(); + LOG_INFO("A Player connected"); + Packet UnreliablePacket(MessageType::Connect, m_SendPacketID); + // Add player id and other stuff + packet.WritePrimitive(m_PlayerID); + m_Unreliable.Send(packet); + LOG_INFO("Sent UDP Connect Server"); +} + void Client::parsePlayerConnected(Packet & packet) { // Map ServerEntityID and other player's PlayerID @@ -132,7 +192,23 @@ void Client::parsePing() Packet packet(MessageType::Ping, m_SendPacketID); packet.WriteString("Ping recieved"); - send(packet); + m_Reliable.Send(packet); +} + + +void Client::parseServerlist(Packet& packet) +{ + // Pop size, message type, and ID + packet.ReadPrimitive(); + packet.ReadPrimitive(); + packet.ReadPrimitive(); + std::string address = packet.ReadString(); + int port = packet.ReadPrimitive(); + std::string serverName = packet.ReadString(); + int playersConnected = packet.ReadPrimitive(); + //TODO: This should not happen when a client is connected to a server + + m_Serverlist.push_back({ address, port, serverName, playersConnected }); } void Client::parseKick() @@ -141,14 +217,41 @@ void Client::parseKick() m_IsConnected = false; } +void Client::parseSpawnEvents() +{ + std::vector tempSpawn; + for (int i = 0; i < m_PlayerSpawnEvents.size(); i++) { + Events::PlayerSpawned e; + if (!serverClientMapsHasEntity(m_PlayerSpawnEvents.at(i).Player.ID)) { + tempSpawn.push_back(m_PlayerSpawnEvents.at(i)); + continue; + } + e.Player = EntityWrapper(m_World, m_ServerIDToClientID.at(m_PlayerSpawnEvents.at(i).Player.ID)); + //e.Spawner = EntityWrapper(m_World, m_ServerIDToClientID.at(m_PlayerSpawnEvents.at(i).Spawner.ID)); + e.PlayerID = -1; + e.PlayerName = m_PlayerSpawnEvents.at(i).PlayerName; + m_EventBroker->Publish(e); + } + m_PlayerSpawnEvents = tempSpawn; + // m_PlayerSpawnEvents.clear(); +} + void Client::parsePlayersSpawned(Packet& packet) { + //Events::PlayerSpawned e; + //e.Player = EntityWrapper(m_World, m_ServerIDToClientID[packet.ReadPrimitive()]); + //e.Spawner = EntityWrapper(m_World, m_ServerIDToClientID[packet.ReadPrimitive()]); + //e.PlayerID = -1; + //e.PlayerName = packet.ReadString(); + //m_EventBroker->Publish(e); + Events::PlayerSpawned e; - e.Player = EntityWrapper(m_World, m_ServerIDToClientID[packet.ReadPrimitive()]); - e.Spawner = EntityWrapper(m_World, m_ServerIDToClientID[packet.ReadPrimitive()]); + e.Player = EntityWrapper(m_World, packet.ReadPrimitive()); + e.Spawner = EntityWrapper(m_World, packet.ReadPrimitive()); e.PlayerID = -1; e.PlayerName = packet.ReadString(); - m_EventBroker->Publish(e); + m_PlayerSpawnEvents.push_back(e); + parseSpawnEvents(); } void Client::parseEntityDeletion(Packet & packet) @@ -158,8 +261,14 @@ void Client::parseEntityDeletion(Packet & packet) if (m_ServerIDToClientID.find(entityToDelete) != m_ServerIDToClientID.end()) { EntityID localEntity = m_ServerIDToClientID.at(entityToDelete); if (m_World->ValidEntity(localEntity)) { - m_World->DeleteEntity(localEntity); - deleteFromServerClientMaps(entityToDelete, localEntity); + if (m_World->HasComponent(localEntity,"Player")) { + Events::PlayerDeath e; + e.Player = EntityWrapper(m_World, localEntity); + m_EventBroker->Publish(e); + } else { + m_World->DeleteEntity(localEntity); + deleteFromServerClientMaps(entityToDelete, localEntity); + } } } } @@ -173,40 +282,83 @@ void Client::parseComponentDeletion(Packet & packet) } } -// Fields with strings will not work right now -void Client::InterpolateFields(Packet& packet, const ComponentInfo& componentInfo, const EntityID& entityID, const std::string& componentType) +void Client::parseDoubleJump(Packet & packet) { - int sizeOfFields = 0; - for (auto field : componentInfo.FieldsInOrder) { - ComponentInfo::Field_t fieldInfo = componentInfo.Fields.at(field); - sizeOfFields += fieldInfo.Stride; + EntityID serverID = packet.ReadPrimitive(); + if (!serverClientMapsHasEntity(serverID)) { + return; + } + Events::DoubleJump e; + e.entityID = m_ServerIDToClientID.at(serverID); + // If player is local player do not publish to prevent infinite feedback loop + if (e.entityID != m_LocalPlayer.ID) { + m_EventBroker->Publish(e); } - // Is the size correct? - boost::shared_array eventData(new char[componentInfo.Stride]); - memcpy(eventData.get(), packet.ReadData(componentInfo.Stride), componentInfo.Stride); - //Send event to interpolat system - Events::Interpolate e; - e.Entity = entityID; - e.DataArray = eventData; - m_EventBroker->Publish(e); - } -void Client::updateFields(Packet& packet, const ComponentInfo& componentInfo, const EntityID& entityID, const std::string& componentType) +void Client::updateFields(Packet& packet, const ComponentInfo& componentInfo, const EntityID& entityID) { for (auto field : componentInfo.FieldsInOrder) { ComponentInfo::Field_t fieldInfo = componentInfo.Fields.at(field); if (fieldInfo.Type == "string") { std::string& value = packet.ReadString(); - m_World->GetComponent(entityID, componentType)[fieldInfo.Name] = value; + m_World->GetComponent(entityID, componentInfo.Name)[fieldInfo.Name] = value; } else { - memcpy(m_World->GetComponent(entityID, componentType).Data + fieldInfo.Offset, packet.ReadData(fieldInfo.Stride), fieldInfo.Stride); + memcpy(m_World->GetComponent(entityID, componentInfo.Name).Data + fieldInfo.Offset, packet.ReadData(fieldInfo.Stride), fieldInfo.Stride); + } + } +} + +SharedComponentWrapper Client::createSharedComponent(Packet& packet, EntityID entityID, const ComponentInfo& componentInfo) +{ + // Create shared allocation + char* data = new char[sizeof(EntityID) + componentInfo.Stride]; + // Copy entity ID to start of data buffer + memcpy(data, &entityID, sizeof(EntityID)); + // Read and copy fields + for (auto& field : componentInfo.FieldsInOrder) { + ComponentInfo::Field_t fieldInfo = componentInfo.Fields.at(field); + if (fieldInfo.Type == "string") { + new (data + sizeof(EntityID) + fieldInfo.Offset) std::string(packet.ReadString()); + } else { + memcpy(data + sizeof(EntityID) + fieldInfo.Offset, packet.ReadData(fieldInfo.Stride), fieldInfo.Stride); + } + } + + return SharedComponentWrapper(componentInfo, boost::shared_array(data)); +} + +void Client::ignoreFields(Packet& packet, const ComponentInfo& componentInfo) +{ + for (auto field : componentInfo.FieldsInOrder) { + ComponentInfo::Field_t fieldInfo = componentInfo.Fields.at(field); + if (fieldInfo.Type == "string") { + packet.ReadString(); + } else { + packet.ReadData(fieldInfo.Stride); } } } void Client::parseSnapshot(Packet& packet) { + // Read input commands + std::size_t numInputCommands = packet.ReadPrimitive(); + for (std::size_t i = 0; i < numInputCommands; ++i) { + Events::InputCommand e; + e.PlayerID = packet.ReadPrimitive(); + EntityID player = packet.ReadPrimitive(); + std::string command = packet.ReadString(); + float value = packet.ReadPrimitive(); + if (m_ServerIDToClientID.find(player) != m_ServerIDToClientID.end()) { + e.Player = EntityWrapper(m_World, m_ServerIDToClientID.at(player)); + e.Command = command; + e.Value = value; + m_EventBroker->Publish(e); + } + } + + // Read world state while (packet.DataReadSize() < packet.Size()) { EntityID serverEntityID = packet.ReadPrimitive(); EntityID serverParentID = packet.ReadPrimitive(); @@ -214,26 +366,33 @@ void Client::parseSnapshot(Packet& packet) int ammountOfComponents = packet.ReadPrimitive(); for (int i = 0; i < ammountOfComponents; i++) { std::string componentType = packet.ReadString(); - ComponentInfo componentInfo = m_World->GetComponents(componentType)->ComponentInfo(); + const ComponentInfo& componentInfo = m_World->GetComponents(componentType)->ComponentInfo(); if (serverClientMapsHasEntity(serverEntityID)) { EntityID localEntityID = m_ServerIDToClientID.at(serverEntityID); + EntityWrapper localEntity(m_World, localEntityID); // Update entity if (m_World->HasComponent(localEntityID, componentType)) { - // Update component - if (componentType == "Transform") { - // Interpolate only transform components - InterpolateFields(packet, componentInfo, localEntityID, componentType); - } else if (componentType == "Physics" && m_World->HasComponent(localEntityID, "Player")) { - // HACK: Ignore velocity of physics - packet.ReadData(componentInfo.Stride); - } else { - // Set component values - updateFields(packet, componentInfo, localEntityID, componentType); + // TODO Fix memory leak here + SharedComponentWrapper newComponent = createSharedComponent(packet, localEntityID, componentInfo); + bool shouldApply = true; + // Apply potential filter function + if (m_SnapshotFilter != nullptr) { + shouldApply = m_SnapshotFilter->FilterComponent(localEntity, newComponent); } + if (shouldApply) { + ComponentWrapper currentComponent = m_World->GetComponent(localEntityID, componentType); + memcpy(currentComponent.Data, newComponent.Data, componentInfo.Stride); + } + + //if (localEntity != m_LocalPlayer && !localEntity.IsChildOf(m_LocalPlayer)) { + // updateFields(packet, componentInfo, localEntityID); + //} else { + // ignoreFields(packet, componentInfo); + //} } else { // Has entity but no component m_World->AttachComponent(localEntityID, componentType); - updateFields(packet, componentInfo, localEntityID, componentType); + updateFields(packet, componentInfo, localEntityID); } } else { // Create Entity and component @@ -241,78 +400,56 @@ void Client::parseSnapshot(Packet& packet) if (serverParentID == EntityID_Invalid) { newLocalEntityID = m_World->CreateEntity(EntityID_Invalid); } else { - newLocalEntityID = m_World->CreateEntity(m_ServerIDToClientID.at(serverParentID)); + if (serverClientMapsHasEntity(serverParentID)) { + newLocalEntityID = m_World->CreateEntity(m_ServerIDToClientID.at(serverParentID)); + } else { + newLocalEntityID = m_World->CreateEntity(EntityID_Invalid); + } } m_World->SetName(newLocalEntityID, serverEntityName); insertIntoServerClientMaps(serverEntityID, newLocalEntityID); m_World->AttachComponent(newLocalEntityID, componentType); - updateFields(packet, componentInfo, newLocalEntityID, componentType); + updateFields(packet, componentInfo, newLocalEntityID); } } // Parent logic // This should be enough beacause we know that the entities arives in pre-order (there will always be a parent) - if (serverParentID != EntityID_Invalid) { + if (serverParentID != EntityID_Invalid && serverClientMapsHasEntity(serverParentID)) { EntityID localEntityID = m_ServerIDToClientID.at(serverEntityID); - m_World->SetParent(localEntityID, m_ServerIDToClientID.at(serverParentID)); + if (m_World->GetParent(localEntityID) != m_ServerIDToClientID.at(serverParentID)) { + m_World->SetParent(localEntityID, m_ServerIDToClientID.at(serverParentID)); + } } } -} - -size_t Client::receive(char* data) -{ - boost::system::error_code error; - - size_t bytesReceived = m_Socket.receive_from(boost - ::asio::buffer((void*)data, INPUTSIZE), - m_ReceiverEndpoint, - 0, error); - // Network Debug data - if (isReadingData) { - m_NetworkData.TotalDataReceived += bytesReceived; - m_NetworkData.DataReceivedThisInterval += bytesReceived; - m_NetworkData.AmountOfMessagesReceived++; - } - if (error) { - //LOG_ERROR("receive: %s", error.message().c_str()); - } - return bytesReceived; -} - -void Client::send(Packet& packet) -{ - m_Socket.send_to(boost::asio::buffer( - packet.Data(), - packet.Size()), - m_ReceiverEndpoint, 0); - // Network Debug data - if (isReadingData) { - m_NetworkData.TotalDataSent += packet.Size(); - m_NetworkData.DataSentThisInterval += packet.Size(); - m_NetworkData.AmountOfMessagesSent++; - } -} - -void Client::connect() -{ - Packet packet(MessageType::Connect, m_SendPacketID); - packet.WriteString(m_PlayerName); - m_StartPingTime = std::clock(); - send(packet); + parseSpawnEvents(); } void Client::disconnect() { + m_IsConnected = false; m_PreviousPacketID = 0; m_PacketID = 0; Packet packet(MessageType::Disconnect, m_SendPacketID); - send(packet); + m_Reliable.Send(packet); + m_Reliable.Disconnect(); } bool Client::OnInputCommand(const Events::InputCommand & e) { + // TEMP + if (e.Command == "SearchForServers" && e.Value > 0) { + Events::SearchForServers e; + m_EventBroker->Publish(e); + } + + if (e.PlayerID != -1) { + return false; + } + if (e.Command == "ConnectToServer") { // Connect for now if (e.Value > 0) { - connect(); + m_Reliable.Connect(m_PlayerName, m_Address, m_Port); + m_Unreliable.Connect(m_PlayerName, m_Address, m_Port); } //LOG_DEBUG("Client::OnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID); return true; @@ -335,7 +472,9 @@ bool Client::OnInputCommand(const Events::InputCommand & e) m_SaveDataTimer = std::clock(); } } else { - m_InputCommandBuffer.push_back(e); + if (m_IsConnected) { + m_InputCommandBuffer.push_back(e); + } //LOG_DEBUG("Client::OnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID); return true; } @@ -344,11 +483,22 @@ bool Client::OnInputCommand(const Events::InputCommand & e) bool Client::OnPlayerDamage(const Events::PlayerDamage & e) { + if (e.Inflictor != m_LocalPlayer) { + return false; + } + // Could this happen? + //if (!clientServerMapsHasEntity(e.Inflictor.ID) + // || !clientServerMapsHasEntity(e.Victim.ID)) { + // return; + //} + Packet packet(MessageType::OnPlayerDamage, m_SendPacketID); + packet.WritePrimitive(m_ClientIDToServerID.at(e.Inflictor.ID)); + packet.WritePrimitive(m_ClientIDToServerID.at(e.Victim.ID)); packet.WritePrimitive(e.Damage); - packet.WritePrimitive(m_ClientIDToServerID.at(e.Player.ID)); - send(packet); - return false; + m_Reliable.Send(packet); + + return true; } bool Client::OnPlayerSpawned(const Events::PlayerSpawned& e) @@ -359,23 +509,72 @@ bool Client::OnPlayerSpawned(const Events::PlayerSpawned& e) return true; } +bool Client::OnSearchForServers(const Events::SearchForServers& e) +{ + m_SearchingForServers = true; + m_StartSearchTime = std::clock(); + m_Serverlist.clear(); + LOG_INFO("Searching for LAN servers...\n"); + Packet packet(MessageType::ServerlistRequest); + m_ServerlistRequest.Broadcast(packet, 13); // TODO: Config + return true; +} + +void Client::parsePlayerDamage(Packet& packet) +{ + Events::PlayerDamage e; + PlayerID victimID = packet.ReadPrimitive(); + PlayerID inflictorID = packet.ReadPrimitive(); + if (!serverClientMapsHasEntity(victimID) || !serverClientMapsHasEntity(inflictorID)) { + return; + } + e.Inflictor = EntityWrapper(m_World, m_ServerIDToClientID.at(victimID)); + e.Victim = EntityWrapper(m_World, m_ServerIDToClientID.at(inflictorID)); + e.Damage = packet.ReadPrimitive(); + // Don't rebroadcast our own player damage events or we'll have an infinite loop! + if (e.Inflictor != m_LocalPlayer) { + m_EventBroker->Publish(e); + } +} + +bool Client::OnDoubleJump(Events::DoubleJump & e) +{ + if (!clientServerMapsHasEntity(e.entityID) || e.entityID != m_LocalPlayer.ID) { + return false; + } + Packet packet(MessageType::OnDoubleJump); + packet.WritePrimitive(m_ClientIDToServerID.at(e.entityID)); + m_Reliable.Send(packet); + return true; +} + void Client::sendLocalPlayerTransform() { if (!m_LocalPlayer.Valid()) { return; } + Packet packet(MessageType::PlayerTransform, m_SendPacketID); + ComponentWrapper cTransform = m_LocalPlayer["Transform"]; glm::vec3& position = cTransform["Position"]; glm::vec3& orientation = cTransform["Orientation"]; - Packet packet(MessageType::PlayerTransform, m_SendPacketID); packet.WritePrimitive(position.x); packet.WritePrimitive(position.y); packet.WritePrimitive(position.z); packet.WritePrimitive(orientation.x); packet.WritePrimitive(orientation.y); packet.WritePrimitive(orientation.z); - send(packet); + + bool hasAssaultWeapon = m_LocalPlayer.HasComponent("AssaultWeapon"); + packet.WritePrimitive(hasAssaultWeapon); + if (hasAssaultWeapon) { + ComponentWrapper cAssaultWeapon = m_LocalPlayer["AssaultWeapon"]; + packet.WritePrimitive((int)cAssaultWeapon["MagazineAmmo"]); + packet.WritePrimitive((int)cAssaultWeapon["Ammo"]); + } + + m_Unreliable.Send(packet); } void Client::identifyPacketLoss() @@ -387,17 +586,15 @@ void Client::identifyPacketLoss() } } -bool Client::hasServerTimedOut() +void Client::hasServerTimedOut() { // Time in ms double timeSincePing = 1000 * (std::clock() - m_StartPingTime) / static_cast(CLOCKS_PER_SEC); if (timeSincePing > m_TimeoutMs) { // Clear everything and go to menu. LOG_INFO("Server has timed out, returning to menu, Beep Boop."); - m_IsConnected = false; - return true; + disconnect(); } - return false; } EntityID Client::createPlayer() @@ -418,7 +615,7 @@ void Client::sendInputCommands() packet.WriteString(m_InputCommandBuffer[i].Command); packet.WritePrimitive(m_InputCommandBuffer[i].Value); } - send(packet); + m_Reliable.Send(packet); m_InputCommandBuffer.clear(); } } @@ -426,7 +623,17 @@ void Client::sendInputCommands() void Client::becomePlayer() { Packet packet = Packet(MessageType::BecomePlayer, m_SendPacketID); - send(packet); + m_Reliable.Send(packet); +} + + +void Client::displayServerlist() +{ + LOG_INFO("This is a serverlist:\n"); + for (int i = 0; i < m_Serverlist.size(); i++) { + ServerInfo si = m_Serverlist[i]; + LOG_INFO("%s:%i\t%s\t%i\n", si.Address.c_str(), si.Port, si.Name.c_str(), si.PlayersConnected); + } } bool Client::clientServerMapsHasEntity(EntityID clientEntityID) @@ -457,7 +664,6 @@ void Client::insertIntoServerClientMaps(EntityID serverEntityID, EntityID client { m_ServerIDToClientID.insert(std::make_pair(serverEntityID, clientEntityID)); m_ClientIDToServerID.insert(std::make_pair(clientEntityID, serverEntityID)); - } void Client::deleteFromServerClientMaps(EntityID serverEntityID, EntityID clientEntityID) diff --git a/src/Engine/Network/Network.cpp b/src/Engine/Network/Network.cpp index f43e5d83..6ce9ef82 100644 --- a/src/Engine/Network/Network.cpp +++ b/src/Engine/Network/Network.cpp @@ -1,10 +1,34 @@ #include "Network/Network.h" +Network::Network(World* world, EventBroker* eventBroker) + : m_World(world) + , m_EventBroker(eventBroker) +{ + ConfigFile* config = ResourceManager::Load("Config.ini"); + m_MaxConnections = config->Get("Networking.MaxConnections", 8); + m_TimeoutMs = config->Get("Networking.TimeoutMs", 20000); +} + void Network::Update() { updateNetworkData(); } +void Network::logSentData(int bytesSent) +{ + +} + +void Network::logReceivedData(int bytesReceived) +{ + // Network Debug data + if (isReadingData) { + m_NetworkData.TotalDataReceived += bytesReceived; + m_NetworkData.DataReceivedThisInterval += bytesReceived; + m_NetworkData.AmountOfMessagesReceived++; + } +} + void Network::saveToFile() { std::ofstream outfile; @@ -59,10 +83,3 @@ void Network::updateNetworkData() m_NetworkData.DataReceivedThisInterval = 0; } } - -void Network::initialize() -{ - ConfigFile* config = ResourceManager::Load("Config.ini"); - m_MaxConnections = config->Get("Networking.MaxConnections", 8); - m_TimeoutMs = config->Get("Networking.TimeoutMs", 20000); -} diff --git a/src/Engine/Network/NetworkClient.cpp b/src/Engine/Network/NetworkClient.cpp new file mode 100644 index 00000000..7a61d5f3 --- /dev/null +++ b/src/Engine/Network/NetworkClient.cpp @@ -0,0 +1,11 @@ +#include "Network/NetworkClient.h" + +NetworkClient::NetworkClient() +{ + m_ReadBuffer = new char[m_BufferSize]; +} + +NetworkClient::~NetworkClient() +{ + delete[] m_ReadBuffer; +} diff --git a/src/Engine/Network/NetworkServer.cpp b/src/Engine/Network/NetworkServer.cpp new file mode 100644 index 00000000..1412621d --- /dev/null +++ b/src/Engine/Network/NetworkServer.cpp @@ -0,0 +1,11 @@ +#include "Network/NetworkServer.h" + +NetworkServer::NetworkServer() +{ + m_ReadBuffer = new char[m_BufferSize]; +} + +NetworkServer::~NetworkServer() +{ + delete[] m_ReadBuffer; +} diff --git a/src/Engine/Network/Packet.cpp b/src/Engine/Network/Packet.cpp index 21226a07..475ca673 100644 --- a/src/Engine/Network/Packet.cpp +++ b/src/Engine/Network/Packet.cpp @@ -34,10 +34,12 @@ void Packet::Init(MessageType type, unsigned int & packetID) m_ReturnDataOffset = 0; m_Offset = 0; // Create message header + // allocate memory for size of packet(only used in tcp) + WritePrimitive(0); // Add message type int messageType = static_cast(type); - Packet::WritePrimitive(messageType); - Packet::WritePrimitive(packetID); + WritePrimitive(messageType); + WritePrimitive(packetID); packetID++; m_HeaderSize = m_Offset; } @@ -56,9 +58,12 @@ void Packet::WriteString(const std::string& str) void Packet::WriteData(char * data, int sizeOfData) { + if (m_Offset + sizeOfData > m_MaxPacketSize) { //LOG_WARNING("Packet::WriteData(): Data size in packet exceeded maximum packet size. New size is %i bytes\n", m_MaxPacketSize*2); - resizeData(); + while (m_Offset + sizeOfData > m_MaxPacketSize) { + resizeData(); + } } memcpy(m_Data + m_Offset, data, sizeOfData); m_Offset += sizeOfData; @@ -76,14 +81,35 @@ std::string Packet::ReadString() return returnValue; } -char * Packet::ReadData(int SizeOfData) +void Packet::ReconstructFromData(char * data, size_t sizeOfData) { - if (m_Offset < m_ReturnDataOffset + SizeOfData) { + if (sizeOfData > m_MaxPacketSize) { + // Delete our data + delete[] m_Data; + // Set new max size + m_MaxPacketSize = sizeOfData; + m_Data = new char[m_MaxPacketSize]; + // while we resized the old data container. + } + memcpy(m_Data, data, sizeOfData); + m_Offset = sizeOfData; + +} + +void Packet::UpdateSize() +{ + int whatisoffset = m_Offset; + memcpy(m_Data, &m_Offset, sizeof(int)); +} + +char * Packet::ReadData(int sizeOfData) +{ + if (m_Offset < m_ReturnDataOffset + sizeOfData) { //LOG_WARNING("packet ReadData(): Oh no! You are trying to remove things outside my memory kingdom"); return nullptr; } size_t oldReturnDataOffset = m_ReturnDataOffset; - m_ReturnDataOffset += SizeOfData; + m_ReturnDataOffset += sizeOfData; return (m_Data + oldReturnDataOffset); } @@ -91,25 +117,36 @@ void Packet::ChangePacketID(unsigned int & packetID) { packetID = packetID + 1; // Overwrite old PacketID - memcpy(m_Data + sizeof(int), &packetID, sizeof(int)); + memcpy(m_Data + 2*sizeof(int), &packetID, sizeof(int)); +} + +MessageType Packet::GetMessageType() +{ + MessageType messagType; + memcpy(&messagType, m_Data + sizeof(int), sizeof(int)); + return messagType; } void Packet::resizeData() { + resizeData(m_MaxPacketSize * 2); +} +void Packet::resizeData(int size) +{ // Allocate memory to store our data in char* holdData = new char[m_MaxPacketSize]; // Copy our data to the newly allocated memory memcpy(holdData, m_Data, m_Offset); // Increase max packet size - m_MaxPacketSize = m_MaxPacketSize * 2; + m_MaxPacketSize = size; // Delete our data - delete m_Data; - // Allocate twice the memory we had before + delete[] m_Data; + // Allocate memory m_Data = new char[m_MaxPacketSize]; // Copy our data to new location memcpy(m_Data, holdData, m_Offset); // Delete the memory allocated to hold our data // while we resized the old data container. - delete holdData; + delete[] holdData; } diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 962081cc..7c614cee 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -1,12 +1,25 @@ #include "Network/Server.h" -Server::Server() : m_Socket(m_IOService, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 27666)) +Server::Server(World* world, EventBroker* eventBroker, int port) + : Network(world, eventBroker) + , m_ServerlistRequest(13) { - Network::initialize(); ConfigFile* config = ResourceManager::Load("Config.ini"); snapshotInterval = 1000 * config->Get("Networking.SnapshotInterval", 0.05f); pingIntervalMs = config->Get("Networking.PingIntervalMs", 1000); + // Subscribe to events + EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &Server::OnInputCommand); + EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &Server::OnPlayerSpawned); + EVENT_SUBSCRIBE_MEMBER(m_EEntityDeleted, &Server::OnEntityDeleted); + EVENT_SUBSCRIBE_MEMBER(m_EComponentDeleted, &Server::OnComponentDeleted); + EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &Server::OnPlayerDamage); + // BindWW + if (port == 0) { + port = config->Get("Networking.Port", 27666); + } + m_Port = port; + LOG_INFO("Server initialized and bound to port %i", port); } Server::~Server() @@ -14,46 +27,66 @@ Server::~Server() } -void Server::Start(World* world, EventBroker* eventBroker) -{ - m_World = world; - m_EventBroker = eventBroker; - // Subscribe to events - EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &Server::OnInputCommand); - EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &Server::OnPlayerSpawned); - EVENT_SUBSCRIBE_MEMBER(m_EEntityDeleted, &Server::OnEntityDeleted); - EVENT_SUBSCRIBE_MEMBER(m_EComponentDeleted, &Server::OnComponentDeleted); - LOG_INFO("I am Server. BIP BOP\n"); -} - void Server::Update() { - readFromClients(); - m_EventBroker->Process(); - if (isReadingData) { - Network::Update(); - } + m_Reliable.AcceptNewConnections(m_NextPlayerID, m_ConnectedPlayers); -} - -void Server::readFromClients() -{ - while (m_Socket.available()) { - try { - bytesRead = receive(readBuffer); - Packet packet(readBuffer, bytesRead); - parseMessageType(packet); - } catch (const std::exception&) { - //LOG_ERROR("%i: Read from client crashed %s", m_PacketID, err.what()); + for (auto& kv : m_ConnectedPlayers) { + while (kv.second.TCPSocket->available()) { + // Packet will get real data in receive + Packet packet(MessageType::Invalid); + m_Reliable.Receive(packet, kv.second); + m_Address = kv.second.TCPSocket->remote_endpoint().address(); + m_Port = kv.second.TCPSocket->remote_endpoint().port(); + if (packet.GetMessageType() == MessageType::Connect) { + parseTCPConnect(packet); + } else { + parseMessageType(packet); + } } } + + PlayerDefinition pd; + while (m_Unreliable.IsSocketAvailable()) { + // Packet will get real data in receive + Packet packet(MessageType::Invalid); + m_Unreliable.Receive(packet, pd); + m_Address = pd.Endpoint.address(); + m_Port = pd.Endpoint.port(); + if (packet.GetMessageType() == MessageType::Connect) { + parseUDPConnect(packet); + } else { + parseMessageType(packet); + } + } + + while (m_ServerlistRequest.IsSocketAvailable()) { + Packet packet(MessageType::Invalid); + PlayerDefinition localArea; + localArea.Endpoint = boost::asio::ip::udp::endpoint(); + m_ServerlistRequest.Receive(packet, localArea); + if (packet.GetMessageType() == MessageType::ServerlistRequest) { + packet.ReadPrimitive(); // Pop size + packet.ReadPrimitive(); // Pop MsgType + packet.ReadPrimitive(); // Pop packet ID + int port = packet.ReadPrimitive(); + std::string address = localArea.Endpoint.address().to_string(); + parseServerlistRequest(boost::asio::ip::udp::endpoint(boost::asio::ip::address().from_string(address), port)); + } + } + + // Check if players have disconnected + for (int i = 0; i < m_PlayersToDisconnect.size(); i++) { + disconnect(m_PlayersToDisconnect.at(i)); + } + m_PlayersToDisconnect.clear(); + std::clock_t currentTime = std::clock(); // Send snapshot if (snapshotInterval < (1000 * (currentTime - previousSnapshotMessage) / (double)CLOCKS_PER_SEC)) { sendSnapshot(); previousSnapshotMessage = currentTime; } - // Send pings each if (pingIntervalMs < (1000 * (currentTime - previousePingMessage) / (double)CLOCKS_PER_SEC)) { sendPing(); @@ -65,19 +98,26 @@ void Server::readFromClients() checkForTimeOuts(); timOutTimer = currentTime; } + m_EventBroker->Process(); + if (isReadingData) { + Network::Update(); + } } void Server::parseMessageType(Packet& packet) { - int messageType = packet.ReadPrimitive(); // Read what type off message was sent from server + // Pop packetSize which is used by TCP Client to + // create a packet of the correct size + packet.ReadPrimitive(); + int messageType = packet.ReadPrimitive(); // Read what type off message was sent from server // Read packet ID m_PreviousPacketID = m_PacketID; // Set previous packet id m_PacketID = packet.ReadPrimitive(); //Read new packet id //identifyPacketLoss(); switch (static_cast(messageType)) { case MessageType::Connect: - parseConnect(packet); + //parseConnect(packet); break; case MessageType::Ping: parsePing(); @@ -98,65 +138,27 @@ void Server::parseMessageType(Packet& packet) case MessageType::PlayerTransform: parsePlayerTransform(packet); break; + case MessageType::OnDoubleJump: + parseDoubleJump(packet); + break; default: break; } } -size_t Server::receive(char * data) -{ - size_t length = m_Socket.receive_from( - boost::asio::buffer((void*)data - , INPUTSIZE) - , m_ReceiverEndpoint, 0); - // Network Debug data - if (isReadingData) { - m_NetworkData.TotalDataReceived += length; - m_NetworkData.DataReceivedThisInterval += length; - m_NetworkData.AmountOfMessagesReceived++; - } - return length; -} - -void Server::send(PlayerID player, Packet& packet) -{ - try { - size_t bytesSent = m_Socket.send_to( - boost::asio::buffer(packet.Data(), packet.Size()), - m_ConnectedPlayers[player].Endpoint, - 0); - // Network Debug data - if (isReadingData) { - m_NetworkData.TotalDataSent += packet.Size(); - m_NetworkData.DataSentThisInterval += packet.Size(); - m_NetworkData.AmountOfMessagesSent++; - } - } catch (const boost::system::system_error&) { - // TODO: Clean up invalid endpoints out of m_ConnectedPlayers later - m_ConnectedPlayers[player].Endpoint = boost::asio::ip::udp::endpoint(); - } -} - -void Server::send(Packet & packet) -{ - m_Socket.send_to( - boost::asio::buffer( - packet.Data(), - packet.Size()), - m_ReceiverEndpoint, - 0); - if (isReadingData) { - // Network Debug data - m_NetworkData.TotalDataSent += packet.Size(); - m_NetworkData.DataSentThisInterval += packet.Size(); - } -} - -void Server::broadcast(Packet& packet) +void Server::reliableBroadcast(Packet& packet) { for (auto& kv : m_ConnectedPlayers) { packet.ChangePacketID(kv.second.PacketID); - send(kv.first, packet); + m_Reliable.Send(packet, kv.second); + } +} + +void Server::unreliableBroadcast(Packet& packet) +{ + for (auto& kv : m_ConnectedPlayers) { + packet.ChangePacketID(kv.second.PacketID); + m_Unreliable.Send(packet, kv.second); } } @@ -164,13 +166,75 @@ void Server::broadcast(Packet& packet) void Server::sendSnapshot() { Packet packet(MessageType::Snapshot); - addChildrenToPacket(packet, EntityID_Invalid); - broadcast(packet); + addInputCommandsToPacket(packet); + addPlayersToPacket(packet, EntityID_Invalid); + unreliableBroadcast(packet); +} + +void Server::addInputCommandsToPacket(Packet& packet) +{ + // Number of input commands + packet.WritePrimitive(m_InputCommandsToBroadcast.size()); + for (auto& command : m_InputCommandsToBroadcast) { + packet.WritePrimitive(command.PlayerID); + packet.WritePrimitive(m_ConnectedPlayers.at(command.PlayerID).EntityID); + packet.WriteString(command.Command); + packet.WritePrimitive(command.Value); + } + m_InputCommandsToBroadcast.clear(); +} + +void Server::addPlayersToPacket(Packet & packet, EntityID entityID) +{ + auto itPair = m_World->GetDirectChildren(entityID); + std::unordered_map worldComponentPools = m_World->GetComponentPools(); + // Loop through every child + for (auto it = itPair.first; it != itPair.second; it++) { + EntityID childEntityID = it->second; + // HACK: Only sync players for now, since the map turned out to be TOO LARGE to send in one snapshot and Simon's computer shits itself + // HACK: Also checked CapturePointHUD for now. (this would get out of sync); + EntityWrapper childEntity(m_World, childEntityID); + if (shouldSendToClient(childEntity)) { + // Write EntityID and parentsID and Entity name + packet.WritePrimitive(childEntityID); + packet.WritePrimitive(entityID); + packet.WriteString(m_World->GetName(childEntityID)); + // Write components to child + int numberOfComponents = 0; + for (auto& i : worldComponentPools) { + if (i.second->KnowsEntity(childEntityID)) { + numberOfComponents++; + } + } + // Write how many components should be read + packet.WritePrimitive(numberOfComponents); + for (auto& i : worldComponentPools) { + // If the entity exist in the pool + if (i.second->KnowsEntity(childEntityID)) { + ComponentWrapper componentWrapper = i.second->GetByEntity(childEntityID); + // ComponentType + packet.WriteString(componentWrapper.Info.Name); + // Loop through fields + for (auto& componentField : componentWrapper.Info.FieldsInOrder) { + ComponentInfo::Field_t fieldInfo = componentWrapper.Info.Fields.at(componentField); + if (fieldInfo.Type == "string") { + std::string& value = componentWrapper[componentField]; + packet.WriteString(value); + } else { + packet.WriteData(componentWrapper.Data + fieldInfo.Offset, fieldInfo.Stride); + } + } + } + } + } + // Go to to your children + addPlayersToPacket(packet, childEntityID); + } } void Server::addChildrenToPacket(Packet & packet, EntityID entityID) { - auto itPair = m_World->GetChildren(entityID); + auto itPair = m_World->GetDirectChildren(entityID); std::unordered_map worldComponentPools = m_World->GetComponentPools(); // Loop through every child for (auto it = itPair.first; it != itPair.second; it++) { @@ -226,24 +290,117 @@ void Server::sendPing() // Time message m_StartPingTime = std::clock(); // Send message - broadcast(packet); + reliableBroadcast(packet); } + + void Server::checkForTimeOuts() { double startPing = 1000 * m_StartPingTime / static_cast(CLOCKS_PER_SEC); - for (int i = 0; i < m_ConnectedPlayers.size(); i++) { - if (m_ConnectedPlayers[i].Endpoint.address() != boost::asio::ip::address()) { - double stopPing = 1000 * m_ConnectedPlayers[i].StopTime / + std::vector playersToRemove; + for (auto& kv : m_ConnectedPlayers) { + if (kv.second.TCPAddress != boost::asio::ip::address()) { + int stopPing = 1000 * kv.second.StopTime / static_cast(CLOCKS_PER_SEC); if (startPing > stopPing + m_TimeoutMs) { - LOG_INFO("User %i timed out!", i); - disconnect(i); + LOG_INFO("User %i timed out!", kv.second.Name); + playersToRemove.push_back(kv.first); } } } + for (size_t i = 0; i < playersToRemove.size(); i++) { + disconnect(playersToRemove.at(i)); + } +} + +void Server::parseUDPConnect(Packet & packet) +{ + // Pop size of message int + packet.ReadPrimitive(); + int messageType = packet.ReadPrimitive(); + // Read packet ID + m_PreviousPacketID = m_PacketID; // Set previous packet id + m_PacketID = packet.ReadPrimitive(); //Read new packet id + // parse player id and other stuff + PlayerID playerID = packet.ReadPrimitive(); + // Do something here? + boost::asio::ip::udp::endpoint endpoint(m_Address, m_Port); + m_ConnectedPlayers.at(playerID).Endpoint = endpoint; + LOG_INFO("parseUDPConnect: Spectator \"%s\" connected on IP: %s", m_ConnectedPlayers.at(playerID).Name.c_str(), m_ConnectedPlayers.at(playerID).Endpoint.address().to_string().c_str()); + // Send a message to the player that connected + Packet connnectPacket(MessageType::Connect, m_ConnectedPlayers.at(playerID).PacketID); + m_Unreliable.Send(connnectPacket); + LOG_INFO("UDP Connect sent to client"); +} + +void Server::parseTCPConnect(Packet & packet) +{ + // Pop size of message int + packet.ReadPrimitive(); + int messageType = packet.ReadPrimitive(); + // Read packet ID + m_PreviousPacketID = m_PacketID; // Set previous packet id + m_PacketID = packet.ReadPrimitive(); //Read new packet id + + LOG_INFO("Parsing connections"); + // Check if player is already connected + // Ska vara till lagd i TCPServer receive + PlayerID playerID = GetPlayerIDFromEndpoint(); + if (playerID == -1) { + return; + } + // Create a new player + m_ConnectedPlayers.at(playerID).EntityID = 0; // Overlook this + m_ConnectedPlayers.at(playerID).Name = packet.ReadString(); + m_ConnectedPlayers.at(playerID).PacketID = 0; + m_ConnectedPlayers.at(playerID).StopTime = std::clock(); + m_ConnectedPlayers.at(playerID).TCPAddress = m_Address; + m_ConnectedPlayers.at(playerID).TCPPort = m_Port; + + LOG_INFO("parseTCPConnect: Spectator \"%s\" connected on IP: %s", m_ConnectedPlayers.at(playerID).Name.c_str(), + m_ConnectedPlayers.at(playerID).TCPAddress.to_string().c_str()); + + // Send a message to the player that connected + Packet connnectPacket(MessageType::Connect, m_ConnectedPlayers.at(playerID).PacketID); + // Write playerID to packet + connnectPacket.WritePrimitive(playerID); + m_Reliable.Send(connnectPacket); + + Packet firstSnapshot(MessageType::Snapshot); + addInputCommandsToPacket(firstSnapshot); + addChildrenToPacket(firstSnapshot, EntityID_Invalid); + m_Reliable.Send(firstSnapshot); + + // Send notification that a player has connected + //Packet notificationPacket(MessageType::PlayerConnected); + //broadcast(notificationPacket); +} + +void Server::parseDisconnect() +{ + LOG_INFO("%i: Parsing disconnect", m_PacketID); + + for (auto& kv : m_ConnectedPlayers) { + if (kv.second.TCPAddress == m_Address && + kv.second.TCPPort == m_Port) { + m_PlayersToDisconnect.push_back(kv.first); + break; + } + } +} + + +void Server::parseServerlistRequest(boost::asio::ip::udp::endpoint endpoint) +{ + Packet packet(MessageType::ServerlistRequest); + packet.WriteString(m_Reliable.Address()); + packet.WritePrimitive(m_Reliable.Port()); + packet.WriteString("SERVERNAME"); + packet.WritePrimitive(m_ConnectedPlayers.size()); + m_ServerlistRequest.Send(packet); } void Server::disconnect(PlayerID playerID) @@ -252,109 +409,28 @@ void Server::disconnect(PlayerID playerID) LOG_INFO("User %s disconnected/timed out", m_ConnectedPlayers[playerID].Name.c_str()); // Remove enteties and stuff (When we can remove entity, remove it and tell clients to remove the copy they have) Events::PlayerDisconnected e; - e.Entity = m_ConnectedPlayers[playerID].EntityID; + e.Entity = m_ConnectedPlayers.at(playerID).EntityID; e.PlayerID = playerID; m_EventBroker->Publish(e); - + //m_World->DeleteEntity(m_ConnectedPlayers[playerID].EntityID); + m_ConnectedPlayers[playerID].TCPSocket->shutdown(boost::asio::ip::tcp::socket::shutdown_both); + m_ConnectedPlayers[playerID].TCPSocket->close(); + m_World->DeleteEntity(m_ConnectedPlayers[playerID].EntityID); m_ConnectedPlayers.erase(playerID); -} - -void Server::parseOnInputCommand(Packet& packet) -{ - PlayerID player = -1; - // Check which player it was who sent the message - player = GetPlayerIDFromEndpoint(m_ReceiverEndpoint); - if (player != -1) { - while (packet.DataReadSize() < packet.Size()) { - Events::InputCommand e; - e.Command = packet.ReadString(); - e.PlayerID = player; // Set correct player id - e.Player = EntityWrapper(m_World, m_ConnectedPlayers.at(player).EntityID); - e.Value = packet.ReadPrimitive(); - m_EventBroker->Publish(e); - //LOG_INFO("Server::parseOnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID); - } - } + // Send disconnect to the other players. } void Server::parseOnPlayerDamage(Packet & packet) { Events::PlayerDamage e; + e.Inflictor = EntityWrapper(m_World, packet.ReadPrimitive()); + e.Victim = EntityWrapper(m_World, packet.ReadPrimitive()); e.Damage = packet.ReadPrimitive(); - e.Player = EntityWrapper(m_World, packet.ReadPrimitive()); m_EventBroker->Publish(e); + //LOG_DEBUG("Server::parseOnPlayerDamage: Command is %s. Value is %f. PlayerID is %i.", e.DamageAmount, e.PlayerDamagedID, e.TypeOfDamage.c_str()); } -void Server::parseConnect(Packet& packet) -{ - LOG_INFO("Parsing connections"); - // Check if player is already connected - if (GetPlayerIDFromEndpoint(m_ReceiverEndpoint) != -1) { - return; - } - for (auto& kv : m_ConnectedPlayers) { - if (kv.second.Endpoint.address() == m_ReceiverEndpoint.address() && - kv.second.Endpoint.port() == m_ReceiverEndpoint.port()) { - // Already connected - return; - } - } - // Create a new player - PlayerDefinition pd; - pd.EntityID = 0; // Overlook this - pd.Endpoint = m_ReceiverEndpoint; - pd.Name = packet.ReadString(); - pd.PacketID = 0; - pd.StopTime = std::clock(); - m_ConnectedPlayers[m_NextPlayerID++] = pd; - LOG_INFO("Spectator \"%s\" connected on IP: %s", pd.Name.c_str(), pd.Endpoint.address().to_string().c_str()); - - // Send a message to the player that connected - Packet connnectPacket(MessageType::Connect, pd.PacketID); - send(connnectPacket); - - // Send notification that a player has connected - Packet notificationPacket(MessageType::PlayerConnected); - broadcast(notificationPacket); -} - -void Server::parseDisconnect() -{ - LOG_INFO("%i: Parsing disconnect", m_PacketID); - - for (auto& kv : m_ConnectedPlayers) { - if (kv.second.Endpoint.address() == m_ReceiverEndpoint.address() && - kv.second.Endpoint.port() == m_ReceiverEndpoint.port()) { - disconnect(kv.first); - break; - } - } -} - -void Server::parseClientPing() -{ - LOG_INFO("%i: Parsing ping", m_PacketID); - PlayerID player = GetPlayerIDFromEndpoint(m_ReceiverEndpoint); - if (player == -1) { - return; - } - // Return ping - Packet packet(MessageType::Ping, m_ConnectedPlayers[player].PacketID); - packet.WriteString("Ping received"); - send(packet); -} - -void Server::parsePing() -{ - for (int i = 0; i < m_ConnectedPlayers.size(); i++) { - if (m_ConnectedPlayers[i].Endpoint.address() == m_ReceiverEndpoint.address()) { - m_ConnectedPlayers[i].StopTime = std::clock(); - break; - } - } -} - void Server::identifyPacketLoss() { // if no packets lost, difference should be equal to 1 @@ -368,18 +444,7 @@ void Server::kick(PlayerID player) { disconnect(player); Packet packet = Packet(MessageType::Kick); - send(packet); -} - -PlayerID Server::GetPlayerIDFromEndpoint(boost::asio::ip::udp::endpoint endpoint) -{ - for (auto& kv : m_ConnectedPlayers) { - if (kv.second.Endpoint.address() == endpoint.address() && - kv.second.Endpoint.port() == endpoint.port()) { - return kv.first; - } - } - return -1; + m_Reliable.Send(packet); } bool Server::OnInputCommand(const Events::InputCommand & e) @@ -391,8 +456,7 @@ bool Server::OnInputCommand(const Events::InputCommand & e) } isReadingData = !isReadingData; m_SaveDataTimer = std::clock(); - } - if (e.Command == "KickPlayer" && e.Value > 0) { + } else if (e.Command == "KickPlayer" && e.Value > 0) { kick(0); } @@ -408,7 +472,7 @@ bool Server::OnPlayerSpawned(const Events::PlayerSpawned & e) packet.WritePrimitive(e.Spawner.ID); // We don't send PlayerID here because it will always be set to -1 packet.WriteString(m_ConnectedPlayers[e.PlayerID].Name); - send(e.PlayerID, packet); + m_Reliable.Send(packet, m_ConnectedPlayers[e.PlayerID]); return false; } @@ -417,7 +481,7 @@ bool Server::OnEntityDeleted(const Events::EntityDeleted & e) if (!e.Cascaded) { Packet packet = Packet(MessageType::EntityDeleted); packet.WritePrimitive(e.DeletedEntity); - broadcast(packet); + reliableBroadcast(packet); } return false; } @@ -425,16 +489,87 @@ bool Server::OnEntityDeleted(const Events::EntityDeleted & e) bool Server::OnComponentDeleted(const Events::ComponentDeleted & e) { if (!e.Cascaded) { - Packet packet = Packet(MessageType::ComponentDeleted); - packet.WritePrimitive(e.Entity); - packet.WriteString(e.ComponentType); - broadcast(packet); + if (shouldSendToClient(EntityWrapper(m_World, e.Entity))) { + Packet packet = Packet(MessageType::ComponentDeleted); + packet.WritePrimitive(e.Entity); + packet.WriteString(e.ComponentType); + reliableBroadcast(packet); + } } return false; } +bool Server::OnPlayerDamage(const Events::PlayerDamage& e) +{ + Packet packet(MessageType::OnPlayerDamage); + packet.WritePrimitive(e.Inflictor.ID); + packet.WritePrimitive(e.Victim.ID); + packet.WritePrimitive(e.Damage); + reliableBroadcast(packet); + + return true; +} + +void Server::parseClientPing() +{ + LOG_INFO("%i: Parsing ping", m_PacketID); + PlayerID player = GetPlayerIDFromEndpoint(); + if (player == -1) { + return; + } + // Return ping + Packet packet(MessageType::Ping, m_ConnectedPlayers[player].PacketID); + packet.WriteString("Ping received"); + m_Reliable.Send(packet); +} + +void Server::parsePing() +{ + for (auto& kv : m_ConnectedPlayers) { + if (kv.second.TCPAddress == m_Address && + kv.second.TCPPort == m_Port + || (kv.second.Endpoint.address() == m_Address + && kv.second.Endpoint.port() == m_Port)) { + kv.second.StopTime = std::clock(); + break; + } + } +} + +bool Server::parseDoubleJump(Packet & packet) +{ + reliableBroadcast(packet); + return true; +} + +void Server::parseOnInputCommand(Packet& packet) +{ + PlayerID player = -1; + // Check which player it was who sent the message + player = GetPlayerIDFromEndpoint(); + if (player != -1) { + while (packet.DataReadSize() < packet.Size()) { + Events::InputCommand e; + e.Command = packet.ReadString(); + e.PlayerID = player; // Set correct player id + e.Player = EntityWrapper(m_World, m_ConnectedPlayers.at(player).EntityID); + e.Value = packet.ReadPrimitive(); + m_EventBroker->Publish(e); + if (e.Command == "PrimaryFire" || e.Command == "Reload") { + m_InputCommandsToBroadcast.push_back(e); + } + //LOG_INFO("Server::parseOnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID); + } + } +} + void Server::parsePlayerTransform(Packet& packet) { + PlayerID playerID = GetPlayerIDFromEndpoint(); + if (playerID == -1) { + return; + } + glm::vec3 position; glm::vec3 orientation; position.x = packet.ReadPrimitive(); @@ -444,11 +579,49 @@ void Server::parsePlayerTransform(Packet& packet) orientation.y = packet.ReadPrimitive(); orientation.z = packet.ReadPrimitive(); - PlayerID playerID = GetPlayerIDFromEndpoint(m_ReceiverEndpoint); - EntityWrapper player(m_World, m_ConnectedPlayers.at(playerID).EntityID); + bool hasAssaultWeapon = packet.ReadPrimitive(); + int magazineAmmo; + int ammo; + if (hasAssaultWeapon) { + magazineAmmo = packet.ReadPrimitive(); + ammo = packet.ReadPrimitive(); + } + EntityWrapper player(m_World, m_ConnectedPlayers.at(playerID).EntityID); if (player.Valid()) { player["Transform"]["Position"] = position; player["Transform"]["Orientation"] = orientation; + + if (hasAssaultWeapon) { + player["AssaultWeapon"]["MagazineAmmo"] = magazineAmmo; + player["AssaultWeapon"]["Ammo"] = ammo; + } } } + +bool Server::shouldSendToClient(EntityWrapper childEntity) +{ + auto children = m_World->GetDirectChildren(childEntity.ID); + for (auto it = children.first; it != children.second; it++) { + EntityWrapper child(m_World, it->second); + if(child.HasComponent("CapturePoint")) { + return true; + } + } + return childEntity.HasComponent("Player") || childEntity.FirstParentWithComponent("Player").Valid() + || childEntity.HasComponent("CapturePoint"); +} + +PlayerID Server::GetPlayerIDFromEndpoint() +{ + // check both tcp and udp connection + for (auto& kv : m_ConnectedPlayers) { + if ((kv.second.TCPAddress == m_Address + && kv.second.TCPPort == m_Port) + || (kv.second.Endpoint.address() == m_Address + && kv.second.Endpoint.port() == m_Port)) { + return kv.first; + } + } + return -1; +} \ No newline at end of file diff --git a/src/Engine/Network/TCPClient.cpp b/src/Engine/Network/TCPClient.cpp new file mode 100644 index 00000000..f3394d3d --- /dev/null +++ b/src/Engine/Network/TCPClient.cpp @@ -0,0 +1,117 @@ +#include "Network/TCPClient.h" + +using namespace boost::asio::ip; + +TCPClient::TCPClient() +{ +} + +TCPClient::~TCPClient() +{ +} + +void TCPClient::Connect(std::string playerName, std::string address, int port) +{ + if (m_Socket) { + if (m_IsConnected) { + Packet packet(MessageType::Connect, m_SendPacketID); + packet.WriteString(playerName); + Send(packet); + LOG_INFO("Connect message sent again!"); + } + } + else if (!m_IsConnected) { + boost::system::error_code error = boost::asio::error::host_not_found; + m_Endpoint = tcp::endpoint(boost::asio::ip::address::from_string(address), port); + m_Socket = std::unique_ptr(new tcp::socket(m_IOService)); + m_Socket->connect(m_Endpoint, error); + tcp::no_delay option(true); + m_Socket->set_option(option); + LOG_INFO(error.message().c_str()); + if (!error) { + m_IsConnected = true; + Packet packet(MessageType::Connect, m_SendPacketID); + packet.WriteString(playerName); + Send(packet); + LOG_INFO("Connect message sent!"); + } + // If error + else { + m_Socket->close(); + m_Socket = nullptr; + } + } +} + +void TCPClient::Disconnect() +{ + if (!m_IsConnected) { + return; + } + m_Socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both); + m_Socket->close(); + m_Socket = nullptr; + m_IsConnected = false; +} + +void TCPClient::Receive(Packet& packet) +{ + size_t bytesRead = readBuffer(); + if (bytesRead > 0) { + packet.ReconstructFromData(m_ReadBuffer, bytesRead); + } +} + +size_t TCPClient::readBuffer() +{ + if (!m_Socket) { + return 0; + } + boost::system::error_code error; + // Read size of packet + m_Socket->receive(boost + ::asio::buffer((void*)m_ReadBuffer, sizeof(int)), + boost::asio::ip::tcp::socket::message_peek, error); + unsigned int sizeOfPacket = 0; + memcpy(&sizeOfPacket, m_ReadBuffer, sizeof(int)); + + // if the buffer is to small increase the size of it + // TODO if message is huge 1 time the buffer will not decrease. + if (sizeOfPacket > m_BufferSize) { + delete[] m_ReadBuffer; + m_ReadBuffer = new char[sizeOfPacket]; + m_BufferSize = sizeOfPacket; + } + // Read the rest of the message + size_t bytesReceived = m_Socket->read_some(boost + ::asio::buffer((void*)(m_ReadBuffer), sizeOfPacket), + error); + if (error) { + //LOG_ERROR("receive: %s", error.message().c_str()); + } + if (sizeOfPacket > 1000000) + LOG_WARNING("The packets received are bigger than 1MB"); + + return bytesReceived; +} + +void TCPClient::Send(Packet & packet) +{ + if (!m_Socket) { + LOG_WARNING("TCPClient::Send: Socket is null"); + return; + } + packet.UpdateSize(); + boost::system::error_code error; + m_Socket->send(boost::asio::buffer( + packet.Data(), + packet.Size()), 0, error); +} + +bool TCPClient::IsSocketAvailable() +{ + if (!m_Socket) { + return false; + } + return m_Socket->available(); +} \ No newline at end of file diff --git a/src/Engine/Network/TCPServer.cpp b/src/Engine/Network/TCPServer.cpp new file mode 100644 index 00000000..acd3d6d0 --- /dev/null +++ b/src/Engine/Network/TCPServer.cpp @@ -0,0 +1,127 @@ +#include "Network/TCPServer.h" +using namespace boost::asio::ip; + +TCPServer::TCPServer() +{ + acceptor = std::unique_ptr(new tcp::acceptor(m_IOService, tcp::endpoint(tcp::v4(), 27666))); + // Make the acceptor non-blocking so we wont get stuck in AcceptNewConnections(). + acceptor->non_blocking(true); + m_Port = GetPort(); + m_Address = GetAddress(); +} + +TCPServer::~TCPServer() +{ } + +void TCPServer::AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers) +{ + boost::system::error_code error; + boost::shared_ptr newSocket = boost::shared_ptr(new tcp::socket(m_IOService)); + acceptor->accept(*newSocket, error); + // If no error occured add new tcp connection + if (!error) { + // Add tcp socket to connections + boost::asio::ip::tcp::no_delay option(true); + newSocket->set_option(option); + PlayerDefinition pd; + pd.StopTime = std::clock(); + pd.TCPSocket = newSocket; + pd.TCPAddress = newSocket.get()->remote_endpoint().address(); + pd.TCPPort = newSocket.get()->remote_endpoint().port(); + connectedPlayers[nextPlayerID++] = pd; + } +} + +PlayerID TCPServer::getPlayerIDFromEndpoint(const std::map& connectedPlayers, + boost::asio::ip::address address, unsigned short port) +{ + for (auto& kv : connectedPlayers) { + if (kv.second.TCPAddress == address && + kv.second.TCPPort == port) { + return kv.first; + } + } + return -1; +} + +void TCPServer::Send(Packet & packet, PlayerDefinition & playerDefinition) +{ + packet.UpdateSize(); + try { + int bytesSent = playerDefinition.TCPSocket->send( + boost::asio::buffer(packet.Data(), packet.Size()), + 0); + } catch (const boost::system::system_error& e) { + // TODO: Clean up invalid endpoints out of m_ConnectedPlayers later + playerDefinition.Endpoint = boost::asio::ip::udp::endpoint(); + } +} + +void TCPServer::Send(Packet & packet) +{ + packet.UpdateSize(); + lastReceivedSocket->send( + boost::asio::buffer( + packet.Data(), + packet.Size()), + 0); +} + +void TCPServer::Disconnect() +{ +} + +int TCPServer::GetPort() +{ + return acceptor->local_endpoint().port(); +} + +std::string TCPServer::GetAddress() +{ + boost::asio::ip::tcp::resolver resolver(m_IOService); + boost::asio::ip::tcp::resolver::query query(boost::asio::ip::tcp::v4(), boost::asio::ip::host_name(), ""); + boost::asio::ip::tcp::resolver::iterator it = resolver.resolve(query); + boost::asio::ip::tcp::endpoint endpoint = *it; + return endpoint.address().to_string().c_str(); +} + +void TCPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition) +{ + int bytesRead = readBuffer(playerDefinition); + if (bytesRead > 0) { + packet.ReconstructFromData(m_ReadBuffer, bytesRead); + } + lastReceivedSocket = playerDefinition.TCPSocket; +} + +int TCPServer::readBuffer(PlayerDefinition & playerDefinition) +{ + if (!playerDefinition.TCPSocket) { + return 0; + } + boost::system::error_code error; + // Read size of packet + playerDefinition.TCPSocket->receive(boost + ::asio::buffer((void*)m_ReadBuffer, sizeof(int)), + boost::asio::ip::tcp::socket::message_peek, error); + unsigned int sizeOfPacket = 0; + memcpy(&sizeOfPacket, m_ReadBuffer, sizeof(int)); + + // if the buffer is to small increase the size of it + if (sizeOfPacket > m_BufferSize) { + delete[] m_ReadBuffer; + m_ReadBuffer = new char[sizeOfPacket]; + m_BufferSize = sizeOfPacket; + } + // Read the rest of the message + size_t bytesReceived = playerDefinition.TCPSocket->read_some(boost + ::asio::buffer((void*)(m_ReadBuffer), sizeOfPacket), + error); + if (error) { + //LOG_ERROR("receive: %s", error.message().c_str()); + } + if (sizeOfPacket > 1000000) + LOG_WARNING("The packets received are bigger than 1MB"); + + return bytesReceived; +} \ No newline at end of file diff --git a/src/Engine/Network/UDPClient.cpp b/src/Engine/Network/UDPClient.cpp new file mode 100644 index 00000000..51c29920 --- /dev/null +++ b/src/Engine/Network/UDPClient.cpp @@ -0,0 +1,98 @@ +#include "Network/UDPClient.h" + +using namespace boost::asio::ip; + +UDPClient::UDPClient() +{ +} + +UDPClient::~UDPClient() +{ +} + +void UDPClient::Connect(std::string playerName, std::string address, int port) +{ + if (m_Socket) { + return; + } + m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address().from_string(address), port); + m_Socket = boost::shared_ptr(new boost::asio::ip::udp::socket(m_IOService)); + m_Socket->open(boost::asio::ip::udp::v4()); +} + +void UDPClient::Disconnect() +{ + +} + +void UDPClient::Receive(Packet& packet) +{ + int bytesRead = readBuffer(); + if (bytesRead > 0) { + packet.ReconstructFromData(m_ReadBuffer, bytesRead); + } +} + +int UDPClient::readBuffer() +{ + if (!m_Socket) { + return 0; + } + boost::system::error_code error; + // Read size of packet + m_Socket->receive(boost + ::asio::buffer((void*)m_ReadBuffer, sizeof(int)), + boost::asio::ip::udp::socket::message_peek, error); + int sizeOfPacket = 0; + memcpy(&sizeOfPacket, m_ReadBuffer, sizeof(int)); + + // if the buffer is to small increase the size of it + if (sizeOfPacket > m_BufferSize) { + delete[] m_ReadBuffer; + m_ReadBuffer = new char[sizeOfPacket]; + m_BufferSize = sizeOfPacket; + } + + size_t availableData = m_Socket->available(); + // Read the rest of the message + size_t bytesReceived = m_Socket->receive_from(boost + ::asio::buffer((void*)(m_ReadBuffer), + sizeOfPacket), + m_ReceiverEndpoint, 0, error); + if (error) { + //LOG_ERROR("receive: %s", error.message().c_str()); + } + if (sizeOfPacket > 1000000) + LOG_WARNING("The packets received are bigger than 1MB"); + + return bytesReceived; +} + +void UDPClient::Send(Packet& packet) +{ + packet.UpdateSize(); + m_Socket->send_to(boost::asio::buffer( + packet.Data(), + packet.Size()), + m_ReceiverEndpoint, 0); +} + +void UDPClient::Broadcast(Packet& packet, int port) +{ + packet.UpdateSize(); + m_Socket->set_option(boost::asio::socket_base::broadcast(true)); + m_Socket->send_to(boost::asio::buffer( + packet.Data(), + packet.Size()), + udp::endpoint(boost::asio::ip::address_v4().broadcast(), port) + , 0); + m_Socket->set_option(boost::asio::socket_base::broadcast(false)); +} + +bool UDPClient::IsSocketAvailable() +{ + if (!m_Socket) { + return false; + } + return m_Socket->available(); +} \ No newline at end of file diff --git a/src/Engine/Network/UDPServer.cpp b/src/Engine/Network/UDPServer.cpp new file mode 100644 index 00000000..635ebd4d --- /dev/null +++ b/src/Engine/Network/UDPServer.cpp @@ -0,0 +1,117 @@ +#include "Network/UDPServer.h" + +UDPServer::UDPServer() +{ + m_Socket = std::unique_ptr(new boost::asio::ip::udp::socket(m_IOService, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 27666))); +} + +UDPServer::UDPServer(int port) +{ + m_Socket = std::unique_ptr(new boost::asio::ip::udp::socket(m_IOService, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), port))); +} + +UDPServer::~UDPServer() +{ } + +void UDPServer::Send(Packet& packet, PlayerDefinition & playerDefinition) +{ + packet.UpdateSize(); + try { + int bytesSent = m_Socket->send_to( + boost::asio::buffer(packet.Data(), packet.Size()), + playerDefinition.Endpoint, + 0); + } catch (const boost::system::system_error& e) { + // TODO: Clean up invalid endpoints out of m_ConnectedPlayers later + playerDefinition.Endpoint = boost::asio::ip::udp::endpoint(); + } +} +// Send back to endpoint of received packet +void UDPServer::Send(Packet & packet) +{ + packet.UpdateSize(); + m_Socket->send_to( + boost::asio::buffer( + packet.Data(), + packet.Size()), + m_ReceiverEndpoint, + 0); +} + +// Broadcasting respond specific logic +void UDPServer::Send(Packet & packet, boost::asio::ip::udp::endpoint endpoint) +{ + packet.UpdateSize(); + m_Socket->send_to( + boost::asio::buffer( + packet.Data(), + packet.Size()), + endpoint, + 0); +} + +// Broadcasting +void UDPServer::Broadcast(Packet & packet, int port) +{ + packet.UpdateSize(); + m_Socket->set_option(boost::asio::socket_base::broadcast(true)); + m_Socket->send_to( + boost::asio::buffer( + packet.Data(), + packet.Size()), + boost::asio::ip::udp::endpoint(boost::asio::ip::address_v4().broadcast(),port), + 0); + m_Socket->set_option(boost::asio::socket_base::broadcast(false)); +} + +void UDPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition) +{ + int bytesRead = readBuffer(); + if (bytesRead > 0) { + packet.ReconstructFromData(m_ReadBuffer, bytesRead); + } + playerDefinition.Endpoint = m_ReceiverEndpoint; +} + +bool UDPServer::IsSocketAvailable() +{ + return m_Socket->available(); +} + +int UDPServer::readBuffer() +{ + if (!m_Socket) { + return 0; + } + int addasdasd = m_Socket->available(); + boost::system::error_code error; + // Read size of packet + m_Socket->receive_from(boost + ::asio::buffer((void*)m_ReadBuffer, sizeof(int)), + m_ReceiverEndpoint, boost::asio::ip::udp::socket::message_peek, error); + unsigned int sizeOfPacket = 0; + memcpy(&sizeOfPacket, m_ReadBuffer, sizeof(int)); + + // if the buffer is to small increase the size of it + if (sizeOfPacket > m_BufferSize) { + delete[] m_ReadBuffer; + m_ReadBuffer = new char[sizeOfPacket]; + m_BufferSize = sizeOfPacket; + } + + // Read the rest of the message + size_t bytesReceived = m_Socket->receive_from(boost + ::asio::buffer((void*)(m_ReadBuffer), + sizeOfPacket), + m_ReceiverEndpoint, 0, error); + if (error) { + //LOG_ERROR("receive: %s", error.message().c_str()); + } + if (sizeOfPacket > 1000000) + LOG_WARNING("The packets received are bigger than 1MB"); + + return bytesReceived; +} + +void UDPServer::AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers) +{ } \ No newline at end of file diff --git a/src/Engine/Rendering/AnimationSystem.cpp b/src/Engine/Rendering/AnimationSystem.cpp index 2126362f..02d72409 100644 --- a/src/Engine/Rendering/AnimationSystem.cpp +++ b/src/Engine/Rendering/AnimationSystem.cpp @@ -13,35 +13,59 @@ void AnimationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& a return; } - Skeleton* skeleton = model->m_RawModel->m_Skeleton; - const Skeleton::Animation* animation = skeleton->GetAnimation(animationComponent["Name"]); - - if(animation != nullptr) { - double animationSpeed = (double)animationComponent["Speed"]; - - if (animationSpeed != 0.0) { - double nextTime = (double)animationComponent["Time"] + animationSpeed * dt; - - - if (!(bool)animationComponent["Loop"] && glm::abs(nextTime) > animation->Duration) { - (double&)animationComponent["Time"] = glm::sign(nextTime) * animation->Duration; - (double&)animationComponent["Speed"] = 0.0; - Events::AnimationComplete e; - e.Entity = entity; - e.Name = (std::string)animationComponent["Name"]; - m_EventBroker->Publish(e); - } else { - if (glm::abs(nextTime) > animation->Duration) { - (double&)animationComponent["Time"] = glm::abs(nextTime) - animation->Duration; - } else { - (double&)animationComponent["Time"] = nextTime; - } - } - } + if(skeleton == nullptr) { + return; } - + for (int i = 1; i <= 3; i++) { + const Skeleton::Animation* animation = skeleton->GetAnimation(animationComponent["AnimationName" + std::to_string(i)]); + if (animation == nullptr) { + continue;; + } + + double animationSpeed = (double)animationComponent["Speed" + std::to_string(i)]; + + if (animationSpeed != 0.0) { + double nextTime = (double)animationComponent["Time" + std::to_string(i)] + animationSpeed * dt; + + + if (!(bool)animationComponent["Loop" + std::to_string(i)]) { + if (nextTime > animation->Duration) { + nextTime = animation->Duration; + Events::AnimationComplete e; + e.Entity = entity; + e.Name = (std::string)animationComponent["AnimationName" + std::to_string(i)]; + m_EventBroker->Publish(e); + } else if (nextTime < 0) { + Events::AnimationComplete e; + e.Entity = entity; + e.Name = (std::string)animationComponent["AnimationName" + std::to_string(i)]; + m_EventBroker->Publish(e); + nextTime = 0; + } + + (double&)animationComponent["Speed" + std::to_string(i)] = 0.0; + + } else { + if (nextTime > animation->Duration) { + Events::AnimationComplete e; + e.Entity = entity; + e.Name = (std::string)animationComponent["AnimationName" + std::to_string(i)]; + m_EventBroker->Publish(e); + nextTime -= animation->Duration; + } else if (nextTime < 0) { + Events::AnimationComplete e; + e.Entity = entity; + e.Name = (std::string)animationComponent["AnimationName" + std::to_string(i)]; + m_EventBroker->Publish(e); + nextTime += animation->Duration; + } + } + + (double&)animationComponent["Time" + std::to_string(i)] = nextTime; + } + } } diff --git a/src/Engine/Rendering/BoneAttachmentSystem.cpp b/src/Engine/Rendering/BoneAttachmentSystem.cpp new file mode 100644 index 00000000..3effaf2c --- /dev/null +++ b/src/Engine/Rendering/BoneAttachmentSystem.cpp @@ -0,0 +1,100 @@ +#include "Rendering/BoneAttachmentSystem.h" + +void BoneAttachmentSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& BoneAttachmentComponent, double dt) +{ + + + if(!entity.HasComponent("Transform")) { + return; + } + + auto parent = entity.FirstParentWithComponent("Animation"); + if (!parent.HasComponent("Model")) { + return; + } + Model* model; + try { + model = ResourceManager::Load<::Model, true>(parent["Model"]["Resource"]); + } catch (const std::exception&) { + return; + } + + if (!model->IsSkinned()) { + return; + } + + Skeleton* skeleton = model->m_RawModel->m_Skeleton; + + if(skeleton == nullptr) { + return; + } + + int id = skeleton->GetBoneID(entity["BoneAttachment"]["BoneName"]); + + if (id == -1) { + return; + } + + std::vector<::Skeleton::AnimationData> Animations; + ::Skeleton::AnimationOffset AnimationOffset; + glm::mat4 boneTransform; + + if (parent.HasComponent("Animation")) { + for (int i = 1; i <= 3; i++) { + ::Skeleton::AnimationData animationData; + animationData.animation = model->m_RawModel->m_Skeleton->GetAnimation(parent["Animation"]["AnimationName" + std::to_string(i)]); + if (animationData.animation == nullptr) { + continue; + } + animationData.time = (double)parent["Animation"]["Time" + std::to_string(i)]; + animationData.weight = (double)parent["Animation"]["Weight" + std::to_string(i)]; + + Animations.push_back(animationData); + } + } + + if (parent.HasComponent("AnimationOffset")) { + AnimationOffset.animation = model->m_RawModel->m_Skeleton->GetAnimation(parent["AnimationOffset"]["AnimationName"]); + AnimationOffset.time = (double)parent["AnimationOffset"]["Time"]; + + if(AnimationOffset.animation != nullptr) { + boneTransform = skeleton->GetBoneTransform(false, skeleton->Bones.at(id), Animations, AnimationOffset, glm::mat4(1)); + } else { + boneTransform = skeleton->GetBoneTransform(false, skeleton->Bones.at(id), Animations, glm::mat4(1)); + } + + } else { + boneTransform = skeleton->GetBoneTransform(false, skeleton->Bones.at(id), Animations, glm::mat4(1)); + } + + + + glm::vec3 scale; + glm::quat rotation; + glm::vec3 translation; + glm::vec3 skew; + glm::vec4 perspective; + glm::decompose(boneTransform, scale, rotation, translation, skew, perspective); + + glm::vec3 angles = glm::vec3(-glm::pitch(rotation), -glm::yaw(rotation), -glm::roll(rotation)); +/* + + angles.y = asin(-boneTransform[0][2]); + if (cos(angles.y) != 0) { + angles.x = atan2(boneTransform[1][2], boneTransform[2][2]); + angles.z = atan2(boneTransform[0][1], boneTransform[0][0]); + } else { + angles.x = atan2(-boneTransform[2][0], boneTransform[1][1]); + angles.z = 0; + }*/ + + if ((bool)entity["BoneAttachment"]["InheritPosition"]) { + (glm::vec3&)entity["Transform"]["Position"] = translation + (glm::vec3)entity["BoneAttachment"]["PositionOffset"]; + } + if ((bool)entity["BoneAttachment"]["InheritOrientation"]) { + (glm::vec3&)entity["Transform"]["Orientation"] = angles + (glm::vec3)entity["BoneAttachment"]["OrientationOffset"]; + } + if ((bool)entity["BoneAttachment"]["InheritScale"]) { + (glm::vec3&)entity["Transform"]["Scale"] = scale * (glm::vec3)entity["BoneAttachment"]["ScaleOffset"]; + } +} diff --git a/src/Engine/Rendering/Camera.cpp b/src/Engine/Rendering/Camera.cpp index f6b2e5ef..c1246c6a 100644 --- a/src/Engine/Rendering/Camera.cpp +++ b/src/Engine/Rendering/Camera.cpp @@ -62,6 +62,13 @@ void Camera::SetViewMatrix(glm::mat4 val) m_ViewMatrix = val; } + +glm::mat4 Camera::BillboardMatrix() +{ + glm::mat4 matrix = glm::toMat4(m_Orientation); + return matrix; +} + //void Camera::Pitch(float val) //{ // m_Pitch = val; diff --git a/src/Engine/Rendering/CubeMapPass.cpp b/src/Engine/Rendering/CubeMapPass.cpp new file mode 100644 index 00000000..e2a55b74 --- /dev/null +++ b/src/Engine/Rendering/CubeMapPass.cpp @@ -0,0 +1,41 @@ +#include "Rendering/CubeMapPass.h" + +CubeMapPass::CubeMapPass(IRenderer* renderer) + :m_Renderer(renderer) +{ + LoadTextures("Nevada"); +} + +void CubeMapPass::LoadTextures(std::string input) +{ + if (m_PreviusCubeMapTexture != input) { + m_CubeMapTextures.clear(); + for (int i = 0; i < 6; i++) { + std::string str; + str = "Textures/Test/CubeMap/" + input + "/CubeMapTest0" + std::to_string(i) + ".png"; + Texture* img = ResourceManager::Load(str); + m_CubeMapTextures.push_back(img); + } + GenerateCubeMapTexture(); + m_PreviusCubeMapTexture = input; + } +} + +void CubeMapPass::GenerateCubeMapTexture() +{ + if (m_CubeMapTexture == -1) { + glGenTextures(1, &m_CubeMapTexture); + } + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapTexture); + + for (int i = 0; i < 6; i++) { + glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA32F, m_CubeMapTextures[0]->Width, m_CubeMapTextures[0]->Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_CubeMapTextures[i]->Data); + } + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); + GLERROR("Generate Cubemap"); +} + diff --git a/src/Engine/Rendering/DrawBloomPass.cpp b/src/Engine/Rendering/DrawBloomPass.cpp index 5d8b2359..e8ad4cd5 100644 --- a/src/Engine/Rendering/DrawBloomPass.cpp +++ b/src/Engine/Rendering/DrawBloomPass.cpp @@ -13,22 +13,26 @@ DrawBloomPass::DrawBloomPass(IRenderer* renderer) void DrawBloomPass::InitializeTextures() { - m_WhiteTexture = ResourceManager::Load("Textures/Core/White.png"); + m_WhiteTexture = CommonFunctions::LoadTexture("Textures/Core/White.png", false); } void DrawBloomPass::InitializeShaderPrograms() { m_GaussianProgram_horiz = ResourceManager::Load("##GaussianProgramHoriz"); - m_GaussianProgram_horiz->AddShader(std::shared_ptr(new VertexShader("Shaders/Gaussian_horiz.vert.glsl"))); - m_GaussianProgram_horiz->AddShader(std::shared_ptr(new FragmentShader("Shaders/Gaussian_horiz.frag.glsl"))); - m_GaussianProgram_horiz->Compile(); - m_GaussianProgram_horiz->Link(); + if (m_GaussianProgram_horiz->GetHandle() == 0) { + m_GaussianProgram_horiz->AddShader(std::shared_ptr(new VertexShader("Shaders/Gaussian_horiz.vert.glsl"))); + m_GaussianProgram_horiz->AddShader(std::shared_ptr(new FragmentShader("Shaders/Gaussian_horiz.frag.glsl"))); + m_GaussianProgram_horiz->Compile(); + m_GaussianProgram_horiz->Link(); + } - m_GaussianProgram_vert = ResourceManager::Load("##GaussianProgramVert"); - m_GaussianProgram_vert->AddShader(std::shared_ptr(new VertexShader("Shaders/Gaussian_vert.vert.glsl"))); - m_GaussianProgram_vert->AddShader(std::shared_ptr(new FragmentShader("Shaders/Gaussian_vert.frag.glsl"))); - m_GaussianProgram_vert->Compile(); - m_GaussianProgram_vert->Link(); + m_GaussianProgram_vert = ResourceManager::Load("##GaussianProgramVert"); + if (m_GaussianProgram_vert->GetHandle() == 0) { + m_GaussianProgram_vert->AddShader(std::shared_ptr(new VertexShader("Shaders/Gaussian_vert.vert.glsl"))); + m_GaussianProgram_vert->AddShader(std::shared_ptr(new FragmentShader("Shaders/Gaussian_vert.frag.glsl"))); + m_GaussianProgram_vert->Compile(); + m_GaussianProgram_vert->Link(); + } } @@ -48,6 +52,7 @@ void DrawBloomPass::InitializeBuffers() void DrawBloomPass::ClearBuffer() { + GLERROR("PRE"); m_GaussianFrameBuffer_horiz.Bind(); glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); @@ -56,6 +61,7 @@ void DrawBloomPass::ClearBuffer() glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_GaussianFrameBuffer_vert.Unbind(); + GLERROR("END"); } void DrawBloomPass::Draw(GLuint texture) @@ -71,15 +77,12 @@ void DrawBloomPass::Draw(GLuint texture) //Horizontal pass, first use the given texture then save it to the horizontal framebuffer. m_GaussianFrameBuffer_horiz.Bind(); m_GaussianProgram_horiz->Bind(); - glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); - glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); - glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].EndIndex - m_ScreenQuad->MaterialGroups()[0].StartIndex +1 - , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].StartIndex); - + glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1 + , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); //Iterate some times to make it more gaussian. for (int i = 1; i < m_iterations; i++) { //Vertical pass @@ -90,9 +93,8 @@ void DrawBloomPass::Draw(GLuint texture) glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); - glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].EndIndex - m_ScreenQuad->MaterialGroups()[0].StartIndex +1 - , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].StartIndex); - + glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1 + , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); //horizontal pass m_GaussianFrameBuffer_horiz.Bind(); @@ -102,8 +104,8 @@ void DrawBloomPass::Draw(GLuint texture) glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); - glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].EndIndex - m_ScreenQuad->MaterialGroups()[0].StartIndex +1 - , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].StartIndex); + glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1 + , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); } //final vertical gaussian after the iterations are done @@ -112,15 +114,23 @@ void DrawBloomPass::Draw(GLuint texture) m_GaussianProgram_vert->Bind(); glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_horiz); - glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); - glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].EndIndex - m_ScreenQuad->MaterialGroups()[0].StartIndex +1 - , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].StartIndex); + glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1 + , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); GLERROR("DrawBloomPass::Draw: END"); } + +void DrawBloomPass::OnWindowResize() +{ + 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.Generate(); + 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.Generate(); +} + void DrawBloomPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const { glGenTextures(1, texture); diff --git a/src/Engine/Rendering/DrawColorCorrectionPass.cpp b/src/Engine/Rendering/DrawColorCorrectionPass.cpp index 45401bce..c82d614f 100644 --- a/src/Engine/Rendering/DrawColorCorrectionPass.cpp +++ b/src/Engine/Rendering/DrawColorCorrectionPass.cpp @@ -6,8 +6,6 @@ DrawColorCorrectionPass::DrawColorCorrectionPass(IRenderer* renderer) m_ScreenQuad = ResourceManager::Load("Models/Core/ScreenQuad.mesh"); - //m_Exposure = 0.4; //TODO: Renderer: Fixa så att denna går att ändra på genom komponent eller setting. - InitializeShaderPrograms(); } @@ -20,14 +18,14 @@ void DrawColorCorrectionPass::InitializeShaderPrograms() m_ColorCorrectionProgram->Link(); } -void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLfloat gamma, GLfloat exposure) +void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLuint sceneTextureLowRes, GLuint bloomTextureLowRes, GLfloat gamma, GLfloat exposure) { //glBindFramebuffer(GL_FRAMEBUFFER, 0); GLERROR("DrawScreenQuadPass::Draw: Pre"); DrawScreenQuadPassState state = DrawScreenQuadPassState(); m_ColorCorrectionProgram->Bind(); - //glClear(GL_COLOR_BUFFER_BIT); + glClear(GL_COLOR_BUFFER_BIT); glUniform1f(glGetUniformLocation(m_ColorCorrectionProgram->GetHandle(), "Exposure"), exposure); glUniform1f(glGetUniformLocation(m_ColorCorrectionProgram->GetHandle(), "Gamma"), gamma); @@ -35,9 +33,13 @@ void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLf glBindTexture(GL_TEXTURE_2D, sceneTexture); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, bloomTexture); + glActiveTexture(GL_TEXTURE2); + glBindTexture(GL_TEXTURE_2D, sceneTextureLowRes); + glActiveTexture(GL_TEXTURE3); + glBindTexture(GL_TEXTURE_2D, bloomTextureLowRes); glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); - glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].EndIndex - m_ScreenQuad->MaterialGroups()[0].StartIndex +1 - , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].StartIndex); + glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1 + , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); } diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index a1139902..11249703 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -1,9 +1,12 @@ #include "Rendering/DrawFinalPass.h" -DrawFinalPass::DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass, ShadowPass* shadowPass) +DrawFinalPass::DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass, CubeMapPass* cubeMapPass, ShadowPass* shadowPass) + : m_Renderer(renderer) + , m_LightCullingPass(lightCullingPass) + , m_CubeMapPass(cubeMapPass) { - m_Renderer = renderer; - m_LightCullingPass = lightCullingPass; + //TODO: Make sure that uniforms are not sent into shader if not needed. + m_ShieldPixelRate = 8; m_ShadowPass = shadowPass; InitializeTextures(); InitializeShaderPrograms(); @@ -12,28 +15,51 @@ DrawFinalPass::DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCulling void DrawFinalPass::InitializeTextures() { - 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"); + m_WhiteTexture = CommonFunctions::LoadTexture("Textures/Core/White.png", false); + m_BlackTexture = CommonFunctions::LoadTexture("Textures/Core/Black.png", false); + m_NeutralNormalTexture = CommonFunctions::LoadTexture("Textures/Core/NeutralNormalMap.png", false); + m_GreyTexture = CommonFunctions::LoadTexture("Textures/Core/Grey.png", false); + m_ErrorTexture = CommonFunctions::LoadTexture("Textures/Core/ErrorTexture.png", false); } void DrawFinalPass::InitializeFrameBuffers() { glGenRenderbuffers(1, &m_DepthBuffer); glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + GLERROR("RenderBuffer generation"); + 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_StencilTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_STENCIL, GL_STENCIL_INDEX8, GL_INT); - m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new RenderBuffer(&m_DepthBuffer, GL_DEPTH_ATTACHMENT))); + m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new RenderBuffer(&m_DepthBuffer, GL_DEPTH_STENCIL_ATTACHMENT))); + //m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_StencilTexture, GL_STENCIL_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))); m_FinalPassFrameBuffer.Generate(); + GLERROR("FBO generation"); + glGenRenderbuffers(1, &m_DepthBufferLowRes); + glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBufferLowRes); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, (int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)); + GLERROR("RenderBufferLowRes generation"); + + GenerateTexture(&m_SceneTextureLowRes, GL_CLAMP_TO_EDGE, GL_NEAREST, glm::vec2((int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)), 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_BloomTextureLowRes, GL_CLAMP_TO_EDGE, GL_NEAREST, glm::vec2((int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)), 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_StencilTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_STENCIL, GL_STENCIL_INDEX8, GL_INT); + + m_FinalPassFrameBufferLowRes.AddResource(std::shared_ptr(new RenderBuffer(&m_DepthBufferLowRes, GL_DEPTH_STENCIL_ATTACHMENT))); + //m_FinalPassFrameBufferLowRes.AddResource(std::shared_ptr(new Texture2D(&m_StencilTexture, GL_STENCIL_ATTACHMENT))); + m_FinalPassFrameBufferLowRes.AddResource(std::shared_ptr(new Texture2D(&m_SceneTextureLowRes, GL_COLOR_ATTACHMENT0))); + m_FinalPassFrameBufferLowRes.AddResource(std::shared_ptr(new Texture2D(&m_BloomTextureLowRes, GL_COLOR_ATTACHMENT1))); + m_FinalPassFrameBufferLowRes.Generate(); + GLERROR("FBO2 generation"); } void DrawFinalPass::InitializeShaderPrograms() @@ -56,33 +82,237 @@ void DrawFinalPass::InitializeShaderPrograms() m_ExplosionEffectProgram->BindFragDataLocation(1, "bloomColor"); m_ExplosionEffectProgram->Link(); GLERROR("Creating explosion program"); + + m_SpriteProgram = ResourceManager::Load("#SpriteProgram"); + m_SpriteProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/Sprite.vert.glsl"))); + m_SpriteProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/Sprite.frag.glsl"))); + m_SpriteProgram->Compile(); + m_SpriteProgram->BindFragDataLocation(0, "sceneColor"); + m_SpriteProgram->BindFragDataLocation(1, "bloomColor"); + m_SpriteProgram->Link(); + GLERROR("Creating sprite program"); + m_ForwardPlusSplatMapProgram = ResourceManager::Load("#ForwardPlusSplatMapProgram"); + m_ForwardPlusSplatMapProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlus.vert.glsl"))); + m_ForwardPlusSplatMapProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMapRGB.frag.glsl"))); + m_ForwardPlusSplatMapProgram->Compile(); + m_ForwardPlusSplatMapProgram->BindFragDataLocation(0, "sceneColor"); + m_ForwardPlusSplatMapProgram->BindFragDataLocation(1, "bloomColor"); + m_ForwardPlusSplatMapProgram->Link(); + GLERROR("Creating Forward SplatMap program"); + + m_ExplosionEffectSplatMapProgram = ResourceManager::Load("#ExplosionEffectSplatMapProgram"); + m_ExplosionEffectSplatMapProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlus.vert.glsl"))); + m_ExplosionEffectSplatMapProgram->AddShader(std::shared_ptr(new GeometryShader("Shaders/ExplosionEffect.geom.glsl"))); + m_ExplosionEffectSplatMapProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMapRGB.frag.glsl"))); + m_ExplosionEffectSplatMapProgram->Compile(); + m_ExplosionEffectSplatMapProgram->BindFragDataLocation(0, "sceneColor"); + m_ExplosionEffectSplatMapProgram->BindFragDataLocation(1, "bloomColor"); + m_ExplosionEffectSplatMapProgram->Link(); + GLERROR("Creating explosion SplatMap program"); + + m_ForwardPlusSkinnedProgram = ResourceManager::Load("#ForwardPlusSkinnedProgram"); + m_ForwardPlusSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlusSkinned.vert.glsl"))); + m_ForwardPlusSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlus.frag.glsl"))); + m_ForwardPlusSkinnedProgram->Compile(); + m_ForwardPlusSkinnedProgram->BindFragDataLocation(0, "sceneColor"); + m_ForwardPlusSkinnedProgram->BindFragDataLocation(1, "bloomColor"); + m_ForwardPlusSkinnedProgram->Link(); + GLERROR("Creating forward+ Skinned program"); + + m_ExplosionEffectSkinnedProgram = ResourceManager::Load("#ExplosionEffectSkinnedProgram"); + m_ExplosionEffectSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlusSkinned.vert.glsl"))); + m_ExplosionEffectSkinnedProgram->AddShader(std::shared_ptr(new GeometryShader("Shaders/ExplosionEffect.geom.glsl"))); + m_ExplosionEffectSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlus.frag.glsl"))); + m_ExplosionEffectSkinnedProgram->Compile(); + m_ExplosionEffectSkinnedProgram->BindFragDataLocation(0, "sceneColor"); + m_ExplosionEffectSkinnedProgram->BindFragDataLocation(1, "bloomColor"); + m_ExplosionEffectSkinnedProgram->Link(); + GLERROR("Creating explosion Skinned program"); + + m_ExplosionEffectSplatMapSkinnedProgram = ResourceManager::Load("#ExplosionEffectSplatMapSkinnedProgram"); + m_ExplosionEffectSplatMapSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlusSkinned.vert.glsl"))); + m_ExplosionEffectSplatMapSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMapRGB.frag.glsl"))); + m_ExplosionEffectSplatMapSkinnedProgram->Compile(); + m_ExplosionEffectSplatMapSkinnedProgram->BindFragDataLocation(0, "sceneColor"); + m_ExplosionEffectSplatMapSkinnedProgram->BindFragDataLocation(1, "bloomColor"); + m_ExplosionEffectSplatMapSkinnedProgram->Link(); + GLERROR("Creating Forward SplatMap Skinned program"); + + m_ForwardPlusSplatMapSkinnedProgram = ResourceManager::Load("#ForwardPlusSplatMapSkinnedProgram"); + m_ForwardPlusSplatMapSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlusSkinned.vert.glsl"))); + m_ForwardPlusSplatMapSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMapRGB.frag.glsl"))); + m_ForwardPlusSplatMapSkinnedProgram->Compile(); + m_ForwardPlusSplatMapSkinnedProgram->BindFragDataLocation(0, "sceneColor"); + m_ForwardPlusSplatMapSkinnedProgram->BindFragDataLocation(1, "bloomColor"); + m_ForwardPlusSplatMapSkinnedProgram->Link(); + GLERROR("Creating Forward SplatMap Skinned program"); + + m_ShieldToStencilProgram = ResourceManager::Load("#ShieldToStencilProgram"); + m_ShieldToStencilProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ShieldStencil.vert.glsl"))); + m_ShieldToStencilProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ShieldStencil.frag.glsl"))); + m_ShieldToStencilProgram->Compile(); + m_ShieldToStencilProgram->Link(); + GLERROR("Creating Shield program"); + + m_ShieldToStencilSkinnedProgram = ResourceManager::Load("#ShieldToStencilProgramSkinned"); + m_ShieldToStencilSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ShieldStencilSkinned.vert.glsl"))); + m_ShieldToStencilSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ShieldStencil.frag.glsl"))); + m_ShieldToStencilSkinnedProgram->Compile(); + m_ShieldToStencilSkinnedProgram->Link(); + GLERROR("Creating Shield Skinned program"); + + m_FillDepthBufferProgram = ResourceManager::Load("#FillDepthBufferProgram"); + m_FillDepthBufferProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/FillDepthBuffer.vert.glsl"))); + m_FillDepthBufferProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/FillDepthBuffer.frag.glsl"))); + m_FillDepthBufferProgram->Compile(); + m_FillDepthBufferProgram->Link(); + GLERROR("Creating DepthFill program"); + + m_FillDepthBufferSkinnedProgram = ResourceManager::Load("#FillDepthBufferProgramSkinned"); + m_FillDepthBufferSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/FillDepthBufferSkinned.vert.glsl"))); + m_FillDepthBufferSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/FillDepthBuffer.frag.glsl"))); + m_FillDepthBufferSkinnedProgram->Compile(); + m_FillDepthBufferSkinnedProgram->Link(); + GLERROR("Creating DepthFill program"); } -void DrawFinalPass::Draw(RenderScene& scene) +void DrawFinalPass::Draw(RenderScene& scene, GLuint SSAOTexture) { GLERROR("Pre"); - DrawFinalPassState* state = new DrawFinalPassState(m_FinalPassFrameBuffer.GetHandle()); if (scene.ClearDepth) { - glClear(GL_DEPTH_BUFFER_BIT); + //glClear(GL_DEPTH_BUFFER_BIT); + state->Disable(GL_DEPTH_TEST); + state->DepthMask(GL_FALSE); } + //TODO: Do we need check for this or will it be per scene always? + glClearStencil(0x00); + glClear(GL_STENCIL_BUFFER_BIT); - DrawModelRenderQueues(scene.OpaqueObjects, scene); + //Fill depth buffer + + state->StencilMask(0x00); + DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene, SSAOTexture); GLERROR("OpaqueObjects"); - DrawModelRenderQueues(scene.TransparentObjects, scene); + state->BlendFunc(GL_ONE, GL_ONE); + DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene, SSAOTexture); GLERROR("TransparentObjects"); + state->BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + DrawSprites(scene.Jobs.SpriteJob, scene); + GLERROR("SpriteJobs"); + + //DrawStencilState* stencilState = new DrawStencilState(m_FinalPassFrameBuffer.GetHandle()); + //Draw shields to stencil pass + state->StencilFunc(GL_ALWAYS, 1, 0xFF); + state->StencilMask(0xFF); + DrawShieldToStencilBuffer(scene.Jobs.ShieldObjects, scene); + GLERROR("StencilPass"); + + //Draw Opaque shielded objects + state->StencilFunc(GL_NOTEQUAL, 1, 0xFF); + state->StencilMask(0x00); + DrawModelRenderQueues(scene.Jobs.OpaqueShieldedObjects, scene, SSAOTexture); //might need changing + GLERROR("Shielded Opaque object"); + + //Draw Transparen Shielded objects + DrawModelRenderQueues(scene.Jobs.TransparentShieldedObjects, scene, SSAOTexture); //might need changing + GLERROR("Shielded Transparent objects"); - delete state; GLERROR("END"); + delete state; + + + DrawFinalPassState* stateLowRes = new DrawFinalPassState(m_FinalPassFrameBufferLowRes.GetHandle()); + //Draw the lowres texture that will be shown behind the shield. + stateLowRes->Enable(GL_SCISSOR_TEST); + stateLowRes->Enable(GL_DEPTH_TEST); + //TODO: Viewports and scissor should be in state + glViewport(0, 0, m_Renderer->GetViewportSize().Width/m_ShieldPixelRate, m_Renderer->GetViewportSize().Height/m_ShieldPixelRate); + glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + + glClearStencil(0x00); + glClear(GL_STENCIL_BUFFER_BIT); + + //TODO: This should not be here... + stateLowRes->StencilFunc(GL_ALWAYS, 1, 0xFF); + stateLowRes->StencilMask(0x00); + DrawToDepthBuffer(scene.Jobs.OpaqueObjects, scene); + DrawToDepthBuffer(scene.Jobs.TransparentObjects, scene); + + //Draw shields to stencil pass + stateLowRes->StencilFunc(GL_ALWAYS, 1, 0xFF); + stateLowRes->StencilMask(0xFF); + stateLowRes->Enable(GL_DEPTH_TEST); + DrawShieldToStencilBuffer(scene.Jobs.ShieldObjects, scene); + GLERROR("StencilPass"); + + //glClear(GL_DEPTH_BUFFER_BIT); + + stateLowRes->Enable(GL_DEPTH_TEST); + stateLowRes->StencilFunc(GL_LEQUAL, 1, 0xFF); + stateLowRes->StencilMask(0x00); + DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene, SSAOTexture); + GLERROR("OpaqueObjects"); + DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene, SSAOTexture); + GLERROR("TransparentObjects"); + glViewport(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + delete stateLowRes; } void DrawFinalPass::ClearBuffer() { + GLERROR("PRE"); + m_FinalPassFrameBufferLowRes.Bind(); + GLERROR("Bind LowRes"); + + glViewport(0, 0, m_Renderer->GetViewportSize().Width/m_ShieldPixelRate, m_Renderer->GetViewportSize().Height/m_ShieldPixelRate); + glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + GLERROR("ViewPort,Scissor LowRes"); + + glClearColor(0.f, 0.f, 0.f, 0.f); + GLERROR("1"); + + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + GLERROR("2"); + + glDisable(GL_SCISSOR_TEST); + GLERROR("3"); + + m_FinalPassFrameBufferLowRes.Unbind(); + + GLERROR("prebind HighRes"); m_FinalPassFrameBuffer.Bind(); + GLERROR("Bind HighRes"); + glViewport(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + GLERROR("ViewPort,Scissor LowRes"); glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_FinalPassFrameBuffer.Unbind(); + GLERROR("END"); +} + + +void DrawFinalPass::OnWindowResize() +{ + //InitializeFrameBuffers(); + glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, 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); + m_FinalPassFrameBuffer.Generate(); + + + glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBufferLowRes); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, (int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)); + + GenerateTexture(&m_SceneTextureLowRes, GL_CLAMP_TO_EDGE, GL_NEAREST, glm::vec2((int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)), GL_RGB16F, GL_RGB, GL_FLOAT); + GenerateTexture(&m_BloomTextureLowRes, GL_CLAMP_TO_EDGE, GL_NEAREST, glm::vec2((int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)), GL_RGB16F, GL_RGB, GL_FLOAT); + m_FinalPassFrameBufferLowRes.Generate(); + GLERROR("Error changing texture resolutions"); } void DrawFinalPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const @@ -111,7 +341,238 @@ void DrawFinalPass::GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm: GLERROR("MipMap Texture initialization failed"); } -void DrawFinalPass::DrawModelRenderQueues(std::list>& job, RenderScene& scene) +void DrawFinalPass::DrawModelRenderQueues(std::list>& jobs, RenderScene& scene, GLuint SSAOTexture) +{ + GLuint forwardHandle = m_ForwardPlusProgram->GetHandle(); + GLERROR("forwardHandle"); + GLuint explosionHandle = m_ExplosionEffectProgram->GetHandle(); + GLERROR("explosionHandle"); + GLuint explosionSplatMapHandle = m_ExplosionEffectSplatMapProgram->GetHandle(); + GLERROR("explosionSplatMapHandle"); + GLuint forwardSplatHandle = m_ForwardPlusSplatMapProgram->GetHandle(); + GLERROR("forwardSplatHandle"); + GLuint forwardSkinnedHandle = m_ForwardPlusSkinnedProgram->GetHandle(); + GLERROR("forwardSkinnedHandle"); + GLuint explosionSkinnedHandle = m_ExplosionEffectSkinnedProgram->GetHandle(); + GLERROR("explosionSkinnedHandle"); + GLuint explosionSplatMapSkinnedHandle = m_ExplosionEffectSplatMapSkinnedProgram->GetHandle(); + GLERROR("explosionSplatMapSkinnedHandle"); + GLuint forwardSplatMapSkinnedHandle = m_ForwardPlusSplatMapSkinnedProgram->GetHandle(); + GLERROR("forwardSplatSkinnedHandle"); + + 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()); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, SSAOTexture); + + for (auto &job : jobs) { + auto explosionEffectJob = std::dynamic_pointer_cast(job); + if (explosionEffectJob) { + switch (explosionEffectJob->Type) { + case RawModel::MaterialType::Basic: + case RawModel::MaterialType::SingleTextures: + { + if (explosionEffectJob->Model->IsSkinned()) { + + m_ExplosionEffectSkinnedProgram->Bind(); + GLERROR("Bind ExplosionEffectSkinned program"); + //bind uniforms + BindExplosionUniforms(explosionSkinnedHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionSkinnedHandle, explosionEffectJob); + glActiveTexture(GL_TEXTURE5); + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); + glUniform3fv(glGetUniformLocation(forwardHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); + + std::vector frameBones; + if (explosionEffectJob->AnimationOffset.animation != nullptr) { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); + } else { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(explosionSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } else { + m_ExplosionEffectProgram->Bind(); + GLERROR("Bind ExplosionEffect program"); + //bind uniforms + BindExplosionUniforms(explosionHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionHandle, explosionEffectJob); + glActiveTexture(GL_TEXTURE5); + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); + glUniform3fv(glGetUniformLocation(forwardHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); + + } + break; + } + case RawModel::MaterialType::SplatMapping: + { + if (explosionEffectJob->Model->IsSkinned()) { + m_ExplosionEffectSplatMapSkinnedProgram->Bind(); + GLERROR("Bind ExplosionEffectSplatMapSkinned program"); + //bind uniforms + BindExplosionUniforms(explosionSplatMapSkinnedHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionSplatMapSkinnedHandle, explosionEffectJob); + GLERROR("asdasd"); + std::vector frameBones; + if (explosionEffectJob->AnimationOffset.animation != nullptr) { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); + } else { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(explosionSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + + } else { + m_ExplosionEffectSplatMapProgram->Bind(); + GLERROR("Bind ExplosionEffectSplatMap program"); + //bind uniforms + //bind uniforms + BindExplosionUniforms(explosionSplatMapHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionSplatMapHandle, explosionEffectJob); + GLERROR("asdasd"); + } + break; + } + } + glDisable(GL_CULL_FACE); + + //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))); + glEnable(GL_CULL_FACE); + GLERROR("explosion effect end"); + } else { + auto modelJob = std::dynamic_pointer_cast(job); + if (modelJob) { + //bind forward program + //TODO: JOHAN/TOBIAS: Bind shader based on ModelJob->ShaderID; + switch (modelJob->Type) { + case RawModel::MaterialType::Basic: + case RawModel::MaterialType::SingleTextures: + { + if (modelJob->Model->IsSkinned()) { + m_ForwardPlusSkinnedProgram->Bind(); + GLERROR("Bind ForwardPlusSkinnedProgram"); + //bind uniforms + BindModelUniforms(forwardSkinnedHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardSkinnedHandle, modelJob); + glActiveTexture(GL_TEXTURE5); + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); + glUniform3fv(glGetUniformLocation(forwardHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); + + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(forwardSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + + } else { + m_ForwardPlusProgram->Bind(); + GLERROR("Bind ForwardPlusProgram"); + //bind uniforms + BindModelUniforms(forwardHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardHandle, modelJob); + glActiveTexture(GL_TEXTURE5); + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); + glUniform3fv(glGetUniformLocation(forwardHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); + } + break; + } + case RawModel::MaterialType::SplatMapping: + { + if (modelJob->Model->IsSkinned()) { + m_ForwardPlusSplatMapSkinnedProgram->Bind(); + GLERROR("Bind SplatMap program"); + //bind uniforms + BindModelUniforms(forwardSplatMapSkinnedHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardSplatMapSkinnedHandle, modelJob); + GLERROR("asdasd"); + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(forwardSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + + } else { + m_ForwardPlusSplatMapProgram->Bind(); + GLERROR("Bind SplatMap program"); + //bind uniforms + BindModelUniforms(forwardSplatHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardSplatHandle, modelJob); + GLERROR("asdasd"); + } + break; + } + } + //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))); + if (GLERROR("models end")) { + continue; + } + } + } + } +} + + +void DrawFinalPass::DrawShieldToStencilBuffer(std::list>& jobs, RenderScene& scene) +{ + + + for (auto &job : jobs) { + auto modelJob = std::dynamic_pointer_cast(job); + if (modelJob) { + + if(modelJob->Model->IsSkinned()) { + m_ShieldToStencilSkinnedProgram->Bind(); + GLuint shaderHandle = m_ShieldToStencilSkinnedProgram->GetHandle(); + + 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())); + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } else { + m_ShieldToStencilProgram->Bind(); + GLuint shaderHandle = m_ShieldToStencilProgram->GetHandle(); + + 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())); + + } + + 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))); + if (GLERROR("models end")) { + continue; + } + } + } +} + +void DrawFinalPass::DrawShieldedModelRenderQueue(std::list>& jobs, RenderScene& scene) { GLuint forwardHandle = m_ForwardPlusProgram->GetHandle(); GLERROR("forwardHandle"); @@ -122,16 +583,15 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightCullingPass->LightGridSSBO()); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightCullingPass->LightIndexSSBO()); - for(auto &job : job) - { + for (auto &job : jobs) { auto explosionEffectJob = std::dynamic_pointer_cast(job); - if(explosionEffectJob) { + if (explosionEffectJob) { //Bind program - if(GLERROR("Prebind")) { + if (GLERROR("Prebind")) { continue; } m_ExplosionEffectProgram->Bind(); - if(GLERROR("BindProgram")) { + if (GLERROR("BindProgram")) { continue; } @@ -139,24 +599,25 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& //Bind uniforms BindExplosionUniforms(explosionHandle, explosionEffectJob, scene); - if(GLERROR("BindExplosionUniforms")) { + if (GLERROR("BindExplosionUniforms")) { continue; } - 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])); - } + std::vector frameBones; + if (explosionEffectJob->AnimationOffset.animation != nullptr) { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); + } else { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); } - if(GLERROR("Animation")) { + glUniformMatrix4fv(glGetUniformLocation(explosionHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + + if (GLERROR("Animation")) { continue; } //bind textures - BindExplosionTextures(explosionEffectJob); - if(GLERROR("BindExplosionTextures")) { + BindExplosionTextures(explosionHandle, explosionEffectJob); + if (GLERROR("BindExplosionTextures")) { continue; } //draw @@ -164,7 +625,7 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& 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))); glEnable(GL_CULL_FACE); - if(GLERROR("explosion effect end")) { + if (GLERROR("explosion effect end")) { continue; } @@ -179,55 +640,163 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& BindModelUniforms(forwardHandle, modelJob, scene); //bind textures - BindModelTextures(modelJob); + BindModelTextures(forwardHandle ,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])); - } + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); } + 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))); - if(GLERROR("models end")) { + if (GLERROR("models end")) { continue; } } } } +} + +void DrawFinalPass::DrawToDepthBuffer(std::list>& jobs, RenderScene& scene) +{ + + + for (auto &job : jobs) { + auto modelJob = std::dynamic_pointer_cast(job); + + if(modelJob->Model->IsSkinned()) { + m_FillDepthBufferSkinnedProgram->Bind(); + GLuint shaderHandle = m_FillDepthBufferSkinnedProgram->GetHandle(); + 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())); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); + + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + + } else { + m_FillDepthBufferProgram->Bind(); + GLuint shaderHandle = m_FillDepthBufferProgram->GetHandle(); + 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())); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); + } + + + //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))); + if (GLERROR("models end")) { + continue; + } + } + +} + + +void DrawFinalPass::DrawSprites(std::list>&jobs, RenderScene& scene) +{ + m_SpriteProgram->Bind(); + + GLuint shaderHandle = m_SpriteProgram->GetHandle(); + + for(auto& job : jobs) { + auto spriteJob = std::dynamic_pointer_cast(job); + RenderState jobState; + + if (spriteJob) { + if(spriteJob->Depth == 0) { + jobState.Disable(GL_DEPTH_TEST); + } + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(spriteJob->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())); + glUniform3fv(glGetUniformLocation(shaderHandle, "CameraPos"), 1, glm::value_ptr(scene.Camera->Position())); + glUniform4fv(glGetUniformLocation(shaderHandle, "Color"), 1, glm::value_ptr(spriteJob->Color)); + glUniform4fv(glGetUniformLocation(shaderHandle, "FillColor"), 1, glm::value_ptr(spriteJob->FillColor)); + glUniform1f(glGetUniformLocation(shaderHandle, "FillPercentage"), spriteJob->FillPercentage); + + glActiveTexture(GL_TEXTURE1); + if (spriteJob->DiffuseTexture != nullptr) { + glBindTexture(GL_TEXTURE_2D, spriteJob->DiffuseTexture->m_Texture); + } else { + glBindTexture(GL_TEXTURE_2D, m_ErrorTexture->m_Texture); + } + + glActiveTexture(GL_TEXTURE2); + if (spriteJob->IncandescenceTexture != nullptr) { + glBindTexture(GL_TEXTURE_2D, spriteJob->IncandescenceTexture->m_Texture); + } else { + glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture); + } + + + glBindVertexArray(spriteJob->Model->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, spriteJob->Model->ElementBuffer); + glDrawElements(GL_TRIANGLES, spriteJob->EndIndex - spriteJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(spriteJob->StartIndex*sizeof(unsigned int))); + } + } + // m_SpriteProgram->Unbind(); } void DrawFinalPass::BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene) { + GLERROR("Bind 1 uniform"); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(job->Matrix)); + GLERROR("Bind 2 uniform"); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); + GLERROR("Bind 3 uniform"); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); + GLERROR("Bind 4 uniform"); - glUniform2f(glGetUniformLocation(shaderHandle, "ScreenDimensions"), m_Renderer->Resolution().Width, m_Renderer->Resolution().Height); + glUniform2f(glGetUniformLocation(shaderHandle, "ScreenDimensions"), m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + GLERROR("Bind 5 uniform"); glUniform3fv(glGetUniformLocation(shaderHandle, "ExplosionOrigin"), 1, glm::value_ptr(job->ExplosionOrigin)); + GLERROR("Bind 6 uniform"); glUniform1f(glGetUniformLocation(shaderHandle, "TimeSinceDeath"), job->TimeSinceDeath); + GLERROR("Bind 7 uniform"); glUniform1f(glGetUniformLocation(shaderHandle, "ExplosionDuration"), job->ExplosionDuration); + GLERROR("Bind 8 uniform"); glUniform4fv(glGetUniformLocation(shaderHandle, "EndColor"), 1, glm::value_ptr(job->EndColor)); + GLERROR("Bind 9 uniform"); glUniform1i(glGetUniformLocation(shaderHandle, "Randomness"), job->Randomness); + GLERROR("Bind 10 uniform"); glUniform1fv(glGetUniformLocation(shaderHandle, "RandomNumbers"), 50, job->RandomNumbers.data()); + GLERROR("Bind 11 uniform"); glUniform1f(glGetUniformLocation(shaderHandle, "RandomnessScalar"), job->RandomnessScalar); + GLERROR("Bind 12 uniform"); glUniform2fv(glGetUniformLocation(shaderHandle, "Velocity"), 1, glm::value_ptr(job->Velocity)); + GLERROR("Bind 13 uniform"); glUniform1i(glGetUniformLocation(shaderHandle, "ColorByDistance"), job->ColorByDistance); + GLERROR("Bind 14 uniform"); glUniform1i(glGetUniformLocation(shaderHandle, "ExponentialAccelaration"), job->ExponentialAccelaration); + GLERROR("Bind 15 uniform"); glUniform4fv(glGetUniformLocation(shaderHandle, "Color"), 1, glm::value_ptr(job->Color)); + GLERROR("Bind 16 uniform"); glUniform4fv(glGetUniformLocation(shaderHandle, "DiffuseColor"), 1, glm::value_ptr(job->DiffuseColor)); + GLERROR("Bind 17 uniform"); glUniform4fv(glGetUniformLocation(shaderHandle, "FillColor"), 1, glm::value_ptr(job->FillColor)); + GLERROR("Bind 18 uniform"); glUniform1f(glGetUniformLocation(shaderHandle, "FillPercentage"), job->FillPercentage); + GLERROR("Bind 19 uniform"); glUniform4fv(glGetUniformLocation(shaderHandle, "AmbientColor"), 1, glm::value_ptr(scene.AmbientColor)); - - //Shadow + GLERROR("Bind 20 uniform"); + glUniform1f(glGetUniformLocation(shaderHandle, "GlowIntensity"), job->GlowIntensity); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "LightP"), MAX_SPLITS, GL_FALSE, glm::value_ptr(*m_ShadowPass->LightP().data())); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "LightV"), MAX_SPLITS, GL_FALSE, glm::value_ptr(*m_ShadowPass->LightV().data())); glUniform1fv(glGetUniformLocation(shaderHandle, "FarDistance"), MAX_SPLITS, m_ShadowPass->FarDistance().data()); @@ -237,87 +806,281 @@ void DrawFinalPass::BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene) { - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(job->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())); + GLERROR("Bind 1 uniform"); + GLint Location_M = glGetUniformLocation(shaderHandle, "M"); + glUniformMatrix4fv(Location_M, 1, GL_FALSE, glm::value_ptr(job->Matrix)); + GLERROR("Bind 2 uniform"); + GLint Location_V = glGetUniformLocation(shaderHandle, "V"); + glUniformMatrix4fv(Location_V, 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); + GLERROR("Bind 3 uniform"); + GLint Location_P = glGetUniformLocation(shaderHandle, "P"); + glUniformMatrix4fv(Location_P, 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); + GLERROR("Bind 4 uniform"); - glUniform2f(glGetUniformLocation(shaderHandle, "ScreenDimensions"), m_Renderer->Resolution().Width, m_Renderer->Resolution().Height); + GLint Location_ScreenDimensions = glGetUniformLocation(shaderHandle, "ScreenDimensions"); + glUniform2f(Location_ScreenDimensions, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + GLERROR("Bind 5 uniform"); - 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); - glUniform4fv(glGetUniformLocation(shaderHandle, "AmbientColor"), 1, glm::value_ptr(scene.AmbientColor)); + GLint Location_FillPercentage = glGetUniformLocation(shaderHandle, "FillPercentage"); + glUniform1f(Location_FillPercentage, job->FillPercentage); + GLERROR("Bind 6 uniform"); + GLint Location_DiffuseColor = glGetUniformLocation(shaderHandle, "DiffuseColor"); + glUniform4fv(Location_DiffuseColor, 1, glm::value_ptr(job->DiffuseColor)); + GLERROR("Bind 7 uniform"); + GLint Location_FillColor = glGetUniformLocation(shaderHandle, "FillColor"); + glUniform4fv(Location_FillColor, 1, glm::value_ptr(job->FillColor)); + GLERROR("Bind 8 uniform"); + GLint Location_Color = glGetUniformLocation(shaderHandle, "Color"); + glUniform4fv(Location_Color, 1, glm::value_ptr(job->Color)); + GLERROR("Bind 9 uniform"); + GLint Location_AmbientColor = glGetUniformLocation(shaderHandle, "AmbientColor"); + glUniform4fv(Location_AmbientColor, 1, glm::value_ptr(scene.AmbientColor)); + + GLERROR("Bind 10 uniform"); + GLint Location_GlowIntensity = glGetUniformLocation(shaderHandle, "GlowIntensity"); + + glUniform1f(Location_GlowIntensity, job->GlowIntensity); //Shadow glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "LightP"), MAX_SPLITS, GL_FALSE, glm::value_ptr(*m_ShadowPass->LightP().data())); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "LightV"), MAX_SPLITS, GL_FALSE, glm::value_ptr(*m_ShadowPass->LightV().data())); glUniform1fv(glGetUniformLocation(shaderHandle, "FarDistance"), MAX_SPLITS, m_ShadowPass->FarDistance().data()); - GLERROR("END"); + GLERROR("END"); } - -void DrawFinalPass::BindExplosionTextures(std::shared_ptr& job) +void DrawFinalPass::BindExplosionTextures(GLuint shaderHandle, 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); - } + switch (job->Type) { + case RawModel::MaterialType::SingleTextures: + case RawModel::MaterialType::Basic: + { + glActiveTexture(GL_TEXTURE1); + if (job->DiffuseTexture.size() > 0 && job->DiffuseTexture[0]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[0]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "DiffuseUVRepeat"), 1, glm::value_ptr(job->DiffuseTexture[0]->UVRepeat)); + } + else { + glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "DiffuseUVRepeat"), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); + } - glActiveTexture(GL_TEXTURE3); - if (job->IncandescenceTexture != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture->m_Texture); - } else { - glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture); - } + glActiveTexture(GL_TEXTURE2); + if (job->NormalTexture.size() > 0 && job->NormalTexture[0]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->NormalTexture[0]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "NormalUVRepeat"), 1, glm::value_ptr(job->NormalTexture[0]->UVRepeat)); + } + else { + glBindTexture(GL_TEXTURE_2D, m_NeutralNormalTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "NormalUVRepeat"), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); + } + + glActiveTexture(GL_TEXTURE3); + if (job->SpecularTexture.size() > 0 && job->SpecularTexture[0]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[0]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "SpecularUVRepeat"), 1, glm::value_ptr(job->SpecularTexture[0]->UVRepeat)); + } + else { + glBindTexture(GL_TEXTURE_2D, m_GreyTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "SpecularUVRepeat"), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); + } + + glActiveTexture(GL_TEXTURE4); + if (job->IncandescenceTexture.size() > 0 && job->IncandescenceTexture[0]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[0]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "GlowUVRepeat"), 1, glm::value_ptr(job->IncandescenceTexture[0]->UVRepeat)); + } + else { + glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "GlowUVRepeat"), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); + } + break; + } + case RawModel::MaterialType::SplatMapping: + { + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_2D, job->SplatMap->Texture->m_Texture); + + int texturePosition = GL_TEXTURE1; + + //Bind 5 diffuse textures + std::string UniformName = "DiffuseUVRepeat"; + for (unsigned int i = 0; i < 5; i++) { + glActiveTexture(texturePosition); + if (job->DiffuseTexture.size() > i && job->DiffuseTexture[i]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[i]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(job->DiffuseTexture[i]->UVRepeat)); + } + else { + glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); + } + texturePosition++; + } + + //Bind 5 Normal textures + UniformName = "NormalUVRepeat"; + for (unsigned int i = 0; i < 5; i++) { + glActiveTexture(texturePosition); + if (job->NormalTexture.size() > i && job->NormalTexture[i]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->NormalTexture[i]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(job->NormalTexture[i]->UVRepeat)); + } + else { + glBindTexture(GL_TEXTURE_2D, m_NeutralNormalTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); + } + texturePosition++; + } + + //Bind 5 Specular textures + UniformName = "SpecularUVRepeat"; + for (unsigned int i = 0; i < 5; i++) { + glActiveTexture(texturePosition); + if (job->SpecularTexture.size() > i && job->SpecularTexture[i]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[i]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(job->SpecularTexture[i]->UVRepeat)); + } + else { + glBindTexture(GL_TEXTURE_2D, m_GreyTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); + } + texturePosition++; + } + + //Bind 5 Incandescence textures + UniformName = "GlowUVRepeat"; + for (unsigned int i = 0; i < 5; i++) { + glActiveTexture(texturePosition); + if (job->IncandescenceTexture.size() > i && job->IncandescenceTexture[i]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[i]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(job->IncandescenceTexture[i]->UVRepeat)); + } + else { + glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); + } + texturePosition++; + } + break; + } + } } -void DrawFinalPass::BindModelTextures(std::shared_ptr& job) +void DrawFinalPass::BindModelTextures(GLuint shaderHandle, 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); - } + switch (job->Type) { + case RawModel::MaterialType::SingleTextures: + case RawModel::MaterialType::Basic: + { + glActiveTexture(GL_TEXTURE1); + if (job->DiffuseTexture.size() > 0 && job->DiffuseTexture[0]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[0]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "DiffuseUVRepeat"), 1, glm::value_ptr(job->DiffuseTexture[0]->UVRepeat)); + } + else { + glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "DiffuseUVRepeat"), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); + } - 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->NormalTexture.size() > 0 && job->NormalTexture[0]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->NormalTexture[0]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "NormalUVRepeat"), 1, glm::value_ptr(job->NormalTexture[0]->UVRepeat)); + } + else { + glBindTexture(GL_TEXTURE_2D, m_NeutralNormalTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "NormalUVRepeat"), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); + } - 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->SpecularTexture.size() > 0 && job->SpecularTexture[0]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[0]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "SpecularUVRepeat"), 1, glm::value_ptr(job->SpecularTexture[0]->UVRepeat)); + } + else { + glBindTexture(GL_TEXTURE_2D, m_GreyTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "SpecularUVRepeat"), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); + } - glActiveTexture(GL_TEXTURE3); - if (job->IncandescenceTexture != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture->m_Texture); - } else { - glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture); - } + glActiveTexture(GL_TEXTURE4); + if (job->IncandescenceTexture.size() > 0 && job->IncandescenceTexture[0]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[0]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "GlowUVRepeat"), 1, glm::value_ptr(job->IncandescenceTexture[0]->UVRepeat)); + } + else { + glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "GlowUVRepeat"), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); + } + break; + } + case RawModel::MaterialType::SplatMapping: + { + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_2D, job->SplatMap->Texture->m_Texture); + + int texturePosition = GL_TEXTURE2; + + //Bind 5 diffuse textures + std::string UniformName = "DiffuseUVRepeat"; + for (unsigned int i = 0; i < 3; i++) { + glActiveTexture(texturePosition); + if (job->DiffuseTexture.size() > i && job->DiffuseTexture[i]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[i]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(job->DiffuseTexture[i]->UVRepeat)); + } else { + glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); + } + texturePosition++; + } + + //Bind 5 Normal textures + UniformName = "NormalUVRepeat"; + for (unsigned int i = 0; i < 3; i++) { + glActiveTexture(texturePosition); + if (job->NormalTexture.size() > i && job->NormalTexture[i]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->NormalTexture[i]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(job->NormalTexture[i]->UVRepeat)); + } else { + glBindTexture(GL_TEXTURE_2D, m_NeutralNormalTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); + } + texturePosition++; + } + + //Bind 5 Specular textures + UniformName = "SpecularUVRepeat"; + for (unsigned int i = 0; i < 3; i++) { + glActiveTexture(texturePosition); + if (job->SpecularTexture.size() > i && job->SpecularTexture[i]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[i]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(job->SpecularTexture[i]->UVRepeat)); + } else { + glBindTexture(GL_TEXTURE_2D, m_GreyTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); + } + texturePosition++; + } + + //Bind 5 Incandescence textures + UniformName = "GlowUVRepeat"; + for (unsigned int i = 0; i < 3; i++) { + glActiveTexture(texturePosition); + if (job->IncandescenceTexture.size() > i && job->IncandescenceTexture[i]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[i]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(job->IncandescenceTexture[i]->UVRepeat)); + } else { + glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); + } + texturePosition++; + } + break; + } + } glActiveTexture(GL_TEXTURE4); if (m_ShadowPass->DepthMap() != NULL) { diff --git a/src/Engine/Rendering/DrawFinalPassState.cpp b/src/Engine/Rendering/DrawFinalPassState.cpp index 3ebe320d..8b5ddc8b 100644 --- a/src/Engine/Rendering/DrawFinalPassState.cpp +++ b/src/Engine/Rendering/DrawFinalPassState.cpp @@ -1,6 +1,7 @@ #include "Rendering/DrawFinalPassState.h" + DrawFinalPassState::DrawFinalPassState(GLuint frameBuffer) { BindFramebuffer(frameBuffer); @@ -8,6 +9,10 @@ DrawFinalPassState::DrawFinalPassState(GLuint frameBuffer) BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); Enable(GL_DEPTH_TEST); Enable(GL_CULL_FACE); + Enable(GL_STENCIL_TEST); + StencilFunc(GL_NOTEQUAL, 1, 0xFF); + StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); + StencilMask(0xFF); ClearColor(glm::vec4(0.f, 0.f, 0.f, 0.f)); } @@ -15,3 +20,20 @@ DrawFinalPassState::~DrawFinalPassState() { } + +DrawStencilState::DrawStencilState(GLuint frameBuffer) +{ + BindFramebuffer(frameBuffer); + Enable(GL_STENCIL_TEST); + StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); + StencilFunc(GL_ALWAYS, 1, 0xFF); + StencilMask(0xFF); + Enable(GL_DEPTH_TEST); + ClearColor(glm::vec4(0.f)); +} + +DrawStencilState::~DrawStencilState() +{ + +} + diff --git a/src/Engine/Rendering/DrawScreenQuadPass.cpp b/src/Engine/Rendering/DrawScreenQuadPass.cpp index b17f5e29..7a522b72 100644 --- a/src/Engine/Rendering/DrawScreenQuadPass.cpp +++ b/src/Engine/Rendering/DrawScreenQuadPass.cpp @@ -32,6 +32,6 @@ void DrawScreenQuadPass::Draw(GLuint texture) glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); - glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].EndIndex - m_ScreenQuad->MaterialGroups()[0].StartIndex +1 - , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].StartIndex); + glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1 + , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); } diff --git a/src/Engine/Rendering/FrameBuffer.cpp b/src/Engine/Rendering/FrameBuffer.cpp index cc563600..e0dd9b2d 100644 --- a/src/Engine/Rendering/FrameBuffer.cpp +++ b/src/Engine/Rendering/FrameBuffer.cpp @@ -53,10 +53,13 @@ void FrameBuffer::AddResource(std::shared_ptr resource) void FrameBuffer::Generate() { + GLERROR("PRE"); + std::vector attachments; glGenFramebuffers(1, &m_BufferHandle); glBindFramebuffer(GL_FRAMEBUFFER, m_BufferHandle); + GLERROR("1"); for (auto it = m_Resources.begin(); it != m_Resources.end(); it++) { switch ((*it)->m_ResourceType) { @@ -75,17 +78,28 @@ void FrameBuffer::Generate() GLERROR("FrameBuffer generate: GL_TEXTURE_2D_ARRAY"); break; } - + GLERROR("2"); + + if ((*it)->m_Attachment != GL_DEPTH_ATTACHMENT && (*it)->m_Attachment != GL_STENCIL_ATTACHMENT && (*it)->m_Attachment != GL_DEPTH_STENCIL_ATTACHMENT) { + GLERROR("Attachment"); } - + GLERROR("3"); + + GLenum* bufferTextures = &attachments[0]; glDrawBuffers(attachments.size(), bufferTextures); + if (GLERROR("GLBufferAttachement error")) { + printf(": AttachmentSize %i", attachments.size()); + } if (GLenum frameBufferStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { - LOG_ERROR("FrameBuffer incomplete: 0x%x\n", frameBufferStatus); + GLERROR("Framebuffer incomplete"); + //LOG_ERROR("FrameBuffer incomplete: 0x%x\n", frameBufferStatus); exit(EXIT_FAILURE); } + GLERROR("END"); + } void FrameBuffer::Bind() diff --git a/src/Engine/Rendering/LightCullingPass.cpp b/src/Engine/Rendering/LightCullingPass.cpp index 5e6da64d..1ce1f88c 100644 --- a/src/Engine/Rendering/LightCullingPass.cpp +++ b/src/Engine/Rendering/LightCullingPass.cpp @@ -16,7 +16,7 @@ LightCullingPass::~LightCullingPass() void LightCullingPass::GenerateNewFrustum(RenderScene& scene) { - if (scene.PointLightJobs.size() == 0) + if (scene.Jobs.PointLight.size() == 0) return; GLERROR("CalculateFrustum Error: Pre"); @@ -83,7 +83,7 @@ void LightCullingPass::FillLightList(RenderScene& scene) { m_LightSources.clear(); - for(auto &job : scene.PointLightJobs) { + for(auto &job : scene.Jobs.PointLight) { auto pointLightjob = std::dynamic_pointer_cast(job); if (pointLightjob) { LightSource p; @@ -97,7 +97,7 @@ void LightCullingPass::FillLightList(RenderScene& scene) m_LightSources.push_back(p); } } - for(auto &job : scene.DirectionalLightJobs) { + for(auto &job : scene.Jobs.DirectionalLight) { auto directionalLightJob = std::dynamic_pointer_cast(job); if(directionalLightJob) { LightSource p; @@ -110,6 +110,34 @@ void LightCullingPass::FillLightList(RenderScene& scene) } } + +void LightCullingPass::OnWindowResize() +{ + SetSSBOSizes(); + + glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_FrustumSSBO); + glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(Frustum)*m_NumberOfTiles, nullptr, GL_DYNAMIC_COPY); + GLERROR("m_FrustumSSBO"); + + glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightSSBO); + glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(LightSource) * 200, nullptr, GL_DYNAMIC_COPY); + GLERROR("m_LightSSBO"); + + glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightGridSSBO); + glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(LightGrid)*m_NumberOfTiles, nullptr, GL_DYNAMIC_COPY); + GLERROR("m_LightGridSSBO"); + + glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightOffsetSSBO); + glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(m_LightOffset), &m_LightOffset, GL_DYNAMIC_COPY); + GLERROR("m_LightOffsetSSBO"); + + glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightIndexSSBO); + glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(float)*m_NumberOfTiles*MAX_LIGHTS_PER_TILE, m_LightIndex, GL_DYNAMIC_COPY); + GLERROR("m_LightIndexSSBO"); + + glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); +} + void LightCullingPass::InitializeSSBOs() { glGenBuffers(1, &m_FrustumSSBO); diff --git a/src/Engine/Rendering/Model.cpp b/src/Engine/Rendering/Model.cpp index cf4923a3..3f8e20e1 100644 --- a/src/Engine/Rendering/Model.cpp +++ b/src/Engine/Rendering/Model.cpp @@ -5,26 +5,48 @@ Model::Model(std::string fileName) //Try loading the model asyncronously, if it throws any exceptions then let it propagate back to caller. m_RawModel = ResourceManager::Load(fileName); - for (auto& group : m_RawModel->MaterialGroups) { - if (!group.TexturePath.empty()) { - group.Texture = std::shared_ptr(ResourceManager::Load(group.TexturePath)); - } - if (!group.NormalMapPath.empty()) { - group.NormalMap = std::shared_ptr(ResourceManager::Load(group.NormalMapPath)); - } - if (!group.SpecularMapPath.empty()) { - group.SpecularMap = std::shared_ptr(ResourceManager::Load(group.SpecularMapPath)); - } - if (!group.IncandescenceMapPath.empty()) { - group.IncandescenceMap = std::shared_ptr(ResourceManager::Load(group.IncandescenceMapPath)); - } + for (auto& materialProperty : m_RawModel->m_Materials) { + switch (materialProperty.type) { + case RawModel::MaterialType::SingleTextures: + { + RawModel::MaterialSingleTextures* materialSingleTexture = static_cast(materialProperty.material); + materialSingleTexture->ColorMap.Texture = CommonFunctions::LoadTexture(materialSingleTexture->ColorMap.TexturePath, false); + materialSingleTexture->NormalMap.Texture = CommonFunctions::LoadTexture(materialSingleTexture->NormalMap.TexturePath, false); + materialSingleTexture->SpecularMap.Texture = CommonFunctions::LoadTexture(materialSingleTexture->SpecularMap.TexturePath, false); + materialSingleTexture->IncandescenceMap.Texture = CommonFunctions::LoadTexture(materialSingleTexture->IncandescenceMap.TexturePath, false); + } + break; + case RawModel::MaterialType::SplatMapping: + { + RawModel::MaterialSplatMapping* materialSplatMapping = static_cast(materialProperty.material); + materialSplatMapping->SplatMap.Texture = CommonFunctions::LoadTexture(materialSplatMapping->SplatMap.TexturePath, false); + for (auto& texture : materialSplatMapping->ColorMaps) + { + texture.Texture = CommonFunctions::LoadTexture(texture.TexturePath, false); + } + for (auto& texture : materialSplatMapping->NormalMaps) + { + texture.Texture = CommonFunctions::LoadTexture(texture.TexturePath, false); + } + for (auto& texture : materialSplatMapping->SpecularMaps) + { + texture.Texture = CommonFunctions::LoadTexture(texture.TexturePath, false); + } + for (auto& texture : materialSplatMapping->IncandescenceMaps) + { + texture.Texture = CommonFunctions::LoadTexture(texture.TexturePath, false); + } + } + break; + } } // Generate GL buffers GLuint buffer; glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); - glBufferData(GL_ARRAY_BUFFER, m_RawModel->m_Vertices.size() * sizeof(RawModel::Vertex), &m_RawModel->m_Vertices[0], GL_STATIC_DRAW); + + glBufferData(GL_ARRAY_BUFFER, m_RawModel->NumVertices() * m_RawModel->VertexSize(), m_RawModel->Vertices(), GL_STATIC_DRAW); glGenBuffers(1, &ElementBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ElementBuffer); @@ -35,7 +57,13 @@ Model::Model(std::string fileName) GLERROR("GLEW: BufferFail4"); glBindBuffer(GL_ARRAY_BUFFER, buffer); - std::vector structSizes = { 3, 3, 3, 3, 2, 4, 4 }; + std::vector structSizes; + if (m_RawModel->IsSkinned()) { + structSizes = { 3, 3, 3, 3, 2, 4, 4 }; + } else { + structSizes = { 3, 3, 3, 3, 2 }; + } + int stride = 0; for (int size : structSizes) { stride += size; @@ -49,8 +77,10 @@ Model::Model(std::string fileName) glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++; glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++; glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++; - glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++; - glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++; + if (m_RawModel->IsSkinned()) { + glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++; + glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++; + } } GLERROR("GLEW: BufferFail5"); @@ -59,11 +89,24 @@ Model::Model(std::string fileName) glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); glEnableVertexAttribArray(4); - glEnableVertexAttribArray(5); - glEnableVertexAttribArray(6); + if (m_RawModel->IsSkinned()) { + glEnableVertexAttribArray(5); + glEnableVertexAttribArray(6); + } GLERROR("GLEW: BufferFail5"); //CreateBuffers(); + + glm::vec3 mini(INFINITY); + glm::vec3 maxi(-INFINITY); + + for (unsigned int i = 0; i < m_RawModel->NumVertices(); i++) { + const auto& v = m_RawModel->Vertices()[i]; + mini = glm::min(mini, v.Position); + maxi = glm::max(maxi, v.Position); + } + + m_Box = AABB(mini, maxi); } Model::~Model() diff --git a/src/Engine/Rendering/PNG.cpp b/src/Engine/Rendering/PNG.cpp index 7ffd5c20..409da9b1 100644 --- a/src/Engine/Rendering/PNG.cpp +++ b/src/Engine/Rendering/PNG.cpp @@ -4,40 +4,35 @@ PNG::PNG(std::string path) { FILE* file = fopen(path.c_str(), "rb"); if (!file) { - LOG_ERROR("Failed to open texture file \"%s\": %s", path.c_str(), const_cast(strerror(errno))); - return; + throw Resource::FailedLoadingException("Failed to open texture file."); } png_byte header[8]; fread(header, 1, 8, file); bool isPNG = !png_sig_cmp(header, 0, 8); if (!isPNG) { - LOG_ERROR("Failed to load texture file \"%s\": File isn't PNG", path.c_str()); fclose(file); - return; + throw Resource::FailedLoadingException("File is not PNG."); } // Initialize libpng png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, (png_error_ptr)&PNG::pngErrorFunction, (png_error_ptr)&PNG::pngErrorFunction); if (!png_ptr) { - LOG_ERROR("libpng: Failed to initialze png_struct"); png_destroy_read_struct(&png_ptr, nullptr, nullptr); fclose(file); - return; + throw Resource::FailedLoadingException("Failed to initialze png_struct."); } png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { - LOG_ERROR("libpng: Failed to initialze png_info"); png_destroy_read_struct(&png_ptr, nullptr, nullptr); fclose(file); - return; + throw Resource::FailedLoadingException("Failed to initialze png_info."); } png_infop info_end_ptr = png_create_info_struct(png_ptr); if (!info_end_ptr) { - LOG_ERROR("libpng: Failed to initialze second png_info"); png_destroy_read_struct(&png_ptr, &info_ptr, nullptr); fclose(file); - return; + throw Resource::FailedLoadingException("Failed to initialze second png_info."); } png_init_io(png_ptr, file); @@ -51,8 +46,8 @@ PNG::PNG(std::string path) unsigned int width, height; png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, NULL, NULL, NULL); if (bit_depth != 8) { - LOG_ERROR("libpng: Unsupported bit depth \"%i\" of image \"%s\", must be 8", bit_depth, path.c_str()); - return; + throw Resource::FailedLoadingException("Unsupported bit depth. Must be 8"); + } switch (color_type) { case PNG_COLOR_TYPE_RGB: @@ -60,8 +55,7 @@ PNG::PNG(std::string path) Format = Image::ImageFormat::RGBA; break; default: - LOG_ERROR("libpng: Unsupported color format \"%i\" of image \"%s\"", color_type, path.c_str()); - return; + throw Resource::FailedLoadingException("Unsupported color format."); } // Convert RGB to RGBA, since DirectX rather treat them all the same way diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index abc79f2e..1eab9939 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -15,19 +15,20 @@ PickingPass::~PickingPass() } + + void PickingPass::InitializeTextures() { GenerateTexture(&m_PickingTexture, GL_CLAMP_TO_BORDER, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RG8, GL_RG, GL_UNSIGNED_BYTE); + + GenerateTexture(&m_DepthBuffer, GL_CLAMP_TO_BORDER, GL_NEAREST, + glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8); } void PickingPass::InitializeFrameBuffers() { - glGenRenderbuffers(1, &m_DepthBuffer); - glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); - - m_PickingBuffer.AddResource(std::shared_ptr(new RenderBuffer(&m_DepthBuffer, GL_DEPTH_ATTACHMENT))); + m_PickingBuffer.AddResource(std::shared_ptr(new Texture2D(&m_DepthBuffer, GL_DEPTH_ATTACHMENT))); m_PickingBuffer.AddResource(std::shared_ptr(new Texture2D(&m_PickingTexture, GL_COLOR_ATTACHMENT0))); m_PickingBuffer.Generate(); } @@ -41,22 +42,34 @@ void PickingPass::InitializeShaderPrograms() m_PickingProgram->Compile(); m_PickingProgram->BindFragDataLocation(0, "TextureFragment"); m_PickingProgram->Link(); + + m_PickingSkinnedProgram = ResourceManager::Load("#PickingSkinnedProgram"); + + m_PickingSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/PickingSkinned.vert.glsl"))); + m_PickingSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/Picking.frag.glsl"))); + m_PickingSkinnedProgram->Compile(); + m_PickingSkinnedProgram->BindFragDataLocation(0, "TextureFragment"); + m_PickingSkinnedProgram->Link(); } void PickingPass::Draw(RenderScene& scene) { + GLERROR("PRE"); PickingPassState* state = new PickingPassState(m_PickingBuffer.GetHandle()); - + //TODO: Render: Add code for more jobs than modeljobs. GLuint shaderHandle = m_PickingProgram->GetHandle(); + GLuint shaderSkinnedHandle = m_PickingSkinnedProgram->GetHandle(); m_PickingProgram->Bind(); if (scene.ClearDepth) { - glClear(GL_DEPTH_BUFFER_BIT); + //glClear(GL_DEPTH_BUFFER_BIT); + state->Disable(GL_DEPTH_TEST); + state->DepthMask(GL_FALSE); } m_Camera = scene.Camera; - for (auto &job : scene.OpaqueObjects) { + for (auto &job : scene.Jobs.OpaqueObjects) { auto modelJob = std::dynamic_pointer_cast(job); if (modelJob) { @@ -83,17 +96,29 @@ void PickingPass::Draw(RenderScene& scene) 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->IsSkinned()) { + m_PickingSkinnedProgram->Bind(); + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); + glUniform2fv(glGetUniformLocation(shaderSkinnedHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); - if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { + 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])); + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } + } else { + m_PickingProgram->Bind(); + 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]))); } glBindVertexArray(modelJob->Model->VAO); @@ -102,7 +127,62 @@ void PickingPass::Draw(RenderScene& scene) } } - for (auto &job : scene.TransparentObjects) { + /* for (auto &job : scene.Jobs.TransparentObjects) { + auto modelJob = std::dynamic_pointer_cast(job); + + 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] += 1; + } else { + m_ColorCounter[0] += 1; + } + } + + m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; + + if (modelJob) { + if (modelJob->Model->IsSkinned()) { + m_PickingSkinnedProgram->Bind(); + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); + glUniform2fv(glGetUniformLocation(shaderSkinnedHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); + + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } else { + m_PickingProgram->Bind(); + 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]))); + } + + 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))); + } + }*/ + + for (auto &job : scene.Jobs.OpaqueShieldedObjects) { auto modelJob = std::dynamic_pointer_cast(job); if (modelJob) { @@ -129,17 +209,27 @@ void PickingPass::Draw(RenderScene& scene) 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->IsSkinned()) { + m_PickingSkinnedProgram->Bind(); + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); + glUniform2fv(glGetUniformLocation(shaderSkinnedHandle, "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])); + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); } + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + + } else { + m_PickingProgram->Bind(); + 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]))); } glBindVertexArray(modelJob->Model->VAO); @@ -147,26 +237,145 @@ 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.Jobs.SpriteJob) { + auto spriteJob = std::dynamic_pointer_cast(job); + if (!spriteJob->Pickable) { + continue; + } + RenderState jobState; + + if (spriteJob) { + if (spriteJob->Depth == 0) { + jobState.Disable(GL_DEPTH_TEST); + } + int pickColor[2] = { m_ColorCounter[0], m_ColorCounter[1] }; + + PickingInfo pickInfo; + pickInfo.Entity = spriteJob->Entity; + pickInfo.World = spriteJob->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] += 1; + } else { + m_ColorCounter[0] += 1; + } + } + + m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; + + m_PickingProgram->Bind(); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(spriteJob->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]))); + + glBindVertexArray(spriteJob->Model->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, spriteJob->Model->ElementBuffer); + glDrawElements(GL_TRIANGLES, spriteJob->EndIndex - spriteJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(spriteJob->StartIndex * sizeof(unsigned int))); + } + } + + /* for (auto &job : scene.Jobs.TransparentShieldedObjects) { + 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] += 1; + } else { + m_ColorCounter[0] += 1; + } + } + + m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; + + if (modelJob->Model->IsSkinned()) { + m_PickingSkinnedProgram->Bind(); + + + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); + glUniform2fv(glGetUniformLocation(shaderSkinnedHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); + + if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { + + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + + } + } else { + m_PickingProgram->Bind(); + + 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]))); + } + + + + + 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"); delete state; } - - void PickingPass::ClearPicking() { + GLERROR("PRE"); m_PickingColorsToEntity.clear(); m_EntityColors.clear(); - m_ColorCounter[0] = 1; - m_ColorCounter[1] = 0; + m_ColorCounter[0] = 0; + m_ColorCounter[1] = 1; m_PickingBuffer.Bind(); glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_PickingBuffer.Unbind(); + GLERROR("END"); +} + + +void PickingPass::OnWindowResize() +{ + InitializeTextures(); + m_PickingBuffer.Generate(); } PickData PickingPass::Pick(glm::vec2 screenCoord) diff --git a/src/Engine/Rendering/PickingPassState.cpp b/src/Engine/Rendering/PickingPassState.cpp index 0c4f4aca..f2d42bff 100644 --- a/src/Engine/Rendering/PickingPassState.cpp +++ b/src/Engine/Rendering/PickingPassState.cpp @@ -3,9 +3,9 @@ PickingPassState::PickingPassState(GLuint frameBuffer) { - GLERROR("---2"); + GLERROR("PRE"); BindFramebuffer(frameBuffer); - GLERROR("---3"); + GLERROR("Bind Framebuffer"); Enable(GL_DEPTH_TEST); Enable(GL_CULL_FACE); Disable(GL_BLEND); @@ -13,6 +13,7 @@ PickingPassState::PickingPassState(GLuint frameBuffer) glm::vec4 clearColor = glm::vec4(0.f); //ClearColor(clearColor); //Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + GLERROR("END"); } PickingPassState::~PickingPassState() diff --git a/src/Engine/Rendering/RawModelAssimp.cpp b/src/Engine/Rendering/RawModelAssimp.cpp index 7bf72a22..6b970f70 100644 --- a/src/Engine/Rendering/RawModelAssimp.cpp +++ b/src/Engine/Rendering/RawModelAssimp.cpp @@ -271,7 +271,7 @@ RawModelAssimp::RawModelAssimp(std::string fileName) skelAnim.Keyframes.push_back(animationFrame); } - m_Skeleton->Animations[animationName] = skelAnim; + m_Skeleton->Animations[animationName1] = skelAnim; } } diff --git a/src/Engine/Rendering/RawModelCustom.cpp b/src/Engine/Rendering/RawModelCustom.cpp index 59634625..dd6a96de 100644 --- a/src/Engine/Rendering/RawModelCustom.cpp +++ b/src/Engine/Rendering/RawModelCustom.cpp @@ -34,13 +34,20 @@ void RawModelCustom::ReadMeshFile(std::string filePath) ReadMeshFileHeader(offset, fileData); ReadMesh(offset, fileData, fileByteSize); } - delete fileData; + delete[] fileData; } void RawModelCustom::ReadMeshFileHeader(std::size_t& offset, char* fileData) { #ifdef BOOST_LITTLE_ENDIAN - m_Vertices.resize(static_cast(*(unsigned int*)(fileData + offset))); + hasSkin = *(bool*)(fileData + offset); + offset += sizeof(bool); + if (hasSkin) { + m_SkinedVertices.resize(static_cast(*(unsigned int*)(fileData + offset))); + } + else { + m_Vertices.resize(static_cast(*(unsigned int*)(fileData + offset))); + } offset += sizeof(unsigned int); m_Indices.resize(static_cast(*(unsigned int*)(fileData + offset))); offset += sizeof(unsigned int); @@ -57,12 +64,19 @@ void RawModelCustom::ReadMesh(std::size_t& offset, char* fileData, const unsigne void RawModelCustom::ReadVertices(std::size_t& offset, char* fileData, const unsigned int& fileByteSize) { #ifdef BOOST_LITTLE_ENDIAN - if (offset + m_Vertices.size() * sizeof(Vertex) > fileByteSize) { - throw Resource::FailedLoadingException("Reading vertices failed"); - } - - memcpy(&m_Vertices[0], fileData + offset, m_Vertices.size() * sizeof(Vertex)); - offset += m_Vertices.size() * sizeof(Vertex); + if (hasSkin) { + if (offset + m_SkinedVertices.size() * sizeof(SkinedVertex) > fileByteSize) { + throw Resource::FailedLoadingException("Reading skined vertices failed"); + } + memcpy(&m_SkinedVertices[0], fileData + offset, m_SkinedVertices.size() * sizeof(SkinedVertex)); + offset += m_SkinedVertices.size() * sizeof(SkinedVertex); + } else { + if (offset + m_Vertices.size() * sizeof(Vertex) > fileByteSize) { + throw Resource::FailedLoadingException("Reading vertices failed"); + } + memcpy(&m_Vertices[0], fileData + offset, m_Vertices.size() * sizeof(Vertex)); + offset += m_Vertices.size() * sizeof(Vertex); + } #else #endif } @@ -102,14 +116,14 @@ void RawModelCustom::ReadMaterialFile(std::string filePath) if (fileByteSize > 0) { ReadMaterials(offset, fileData, fileByteSize); } - delete fileData; + delete[] fileData; } void RawModelCustom::ReadMaterials(std::size_t& offset, char* fileData, const unsigned int& fileByteSize) { #ifdef BOOST_LITTLE_ENDIAN unsigned int* numMaterials = (unsigned int*)(fileData); - MaterialGroups.reserve(*numMaterials); + m_Materials.reserve(*numMaterials); offset += sizeof(unsigned int); for (unsigned int i = 0; i < *numMaterials; i++) { @@ -121,83 +135,150 @@ void RawModelCustom::ReadMaterials(std::size_t& offset, char* fileData, const un void RawModelCustom::ReadMaterialSingle(std::size_t& offset, char* fileData, const unsigned int& fileByteSize) { - MaterialGroup newMaterial; - + MaterialProperties newMaterialProperty; #ifdef BOOST_LITTLE_ENDIAN - if (offset + sizeof(unsigned int) * 4 > fileByteSize) { - throw Resource::FailedLoadingException("Reading Material texture names length failed"); - } + if (offset + sizeof(MaterialType) > fileByteSize) { + throw Resource::FailedLoadingException("Reading Material Type failed"); + } + MaterialType type = *(MaterialType*)(fileData + offset); + offset += sizeof(MaterialType); - unsigned int* nameLengths = (unsigned int*)(fileData + offset); - offset += sizeof(unsigned int) * 4; + switch (type) { + case MaterialType::Basic: + newMaterialProperty.material = new MaterialBasic(); + ReadMaterialBasic(newMaterialProperty.material, offset, fileData, fileByteSize); + break; + case MaterialType::SplatMapping: + newMaterialProperty.material = new MaterialSplatMapping(); + ReadMaterialSplatMapping(static_cast(newMaterialProperty.material), offset, fileData, fileByteSize); + break; + case MaterialType::SingleTextures: + newMaterialProperty.material = new MaterialSingleTextures(); + ReadMaterialSingleTexture(static_cast(newMaterialProperty.material), offset, fileData, fileByteSize); + break; + default: + throw Resource::FailedLoadingException("Material contains an unknown MaterialType"); + }; - if (offset + sizeof(float) * 11 + sizeof(unsigned int) * 2 > fileByteSize) { - throw Resource::FailedLoadingException("Reading Material specular, reflection, color and start and end index values failed"); - } - - newMaterial.SpecularExponent = *(float*)(fileData + offset); - offset += sizeof(float); - newMaterial.ReflectionFactor = *(float*)(fileData + offset); - offset += sizeof(float); - - memcpy(&newMaterial.DiffuseColor[0], fileData + offset, sizeof(float) * 3); - offset += sizeof(float) * 3; - memcpy(&newMaterial.SpecularColor[0], fileData + offset, sizeof(float) * 3); - offset += sizeof(float) * 3; - memcpy(&newMaterial.IncandescenceColor[0], fileData + offset, sizeof(float) * 3); - offset += sizeof(float) * 3; - - newMaterial.StartIndex = *(unsigned int*)(fileData + offset); - offset += sizeof(unsigned int); - newMaterial.EndIndex = *(unsigned int*)(fileData + offset); - offset += sizeof(unsigned int); - - if (nameLengths[0] > 0) { - if (offset + nameLengths[0] > fileByteSize) { - throw Resource::FailedLoadingException("Reading Material texture path failed"); - } - - newMaterial.TexturePath = "Textures/"; - newMaterial.TexturePath += (fileData + offset); - newMaterial.TexturePath += ".png"; - offset += nameLengths[0]; - } - - if (nameLengths[1] > 0) { - if (offset + nameLengths[1] > fileByteSize) { - throw Resource::FailedLoadingException("Reading Material NormalMap path failed"); - } - newMaterial.NormalMapPath = "Textures/"; - newMaterial.NormalMapPath += (fileData + offset); - newMaterial.NormalMapPath += ".png"; - offset += nameLengths[1]; - } - - if (nameLengths[2] > 0) { - if (offset + nameLengths[2] > fileByteSize) { - throw Resource::FailedLoadingException("Reading Material SpecularMap path failed"); - } - newMaterial.SpecularMapPath = "Textures/"; - newMaterial.SpecularMapPath += (fileData + offset); - newMaterial.SpecularMapPath += ".png"; - offset += nameLengths[2]; - } - - if (nameLengths[3] > 0) { - if (offset + nameLengths[3] > fileByteSize) { - throw Resource::FailedLoadingException("Reading Material IncandescenceMap path failed"); - } - newMaterial.IncandescenceMapPath = "Textures/"; - newMaterial.IncandescenceMapPath += (fileData + offset); - newMaterial.IncandescenceMapPath += ".png"; - offset += nameLengths[3]; - } + newMaterialProperty.type = type; #else #endif - MaterialGroups.push_back(newMaterial); + m_Materials.push_back(newMaterialProperty); +} + +void RawModelCustom::ReadMaterialBasic(RawModelCustom::MaterialBasic* newMaterial, std::size_t& offset, char* fileData, const unsigned int& fileByteSize) +{ + if (offset + sizeof(float) * 11 + sizeof(unsigned int) * 2 > fileByteSize) { + throw Resource::FailedLoadingException("Reading Material specular, reflection, color and start and end index values failed"); + } + + newMaterial->SpecularExponent = *(float*)(fileData + offset); + offset += sizeof(float); + newMaterial->ReflectionFactor = *(float*)(fileData + offset); + offset += sizeof(float); + + memcpy(&newMaterial->DiffuseColor[0], fileData + offset, sizeof(float) * 3); + offset += sizeof(float) * 3; + memcpy(&newMaterial->SpecularColor[0], fileData + offset, sizeof(float) * 3); + offset += sizeof(float) * 3; + memcpy(&newMaterial->IncandescenceColor[0], fileData + offset, sizeof(float) * 3); + offset += sizeof(float) * 3; + + newMaterial->StartIndex = *(unsigned int*)(fileData + offset); + offset += sizeof(unsigned int); + newMaterial->EndIndex = *(unsigned int*)(fileData + offset); + offset += sizeof(unsigned int); +} + +void RawModelCustom::ReadMaterialSingleTexture(RawModelCustom::MaterialSingleTextures* newMaterial, std::size_t& offset, char* fileData, const unsigned int& fileByteSize) +{ + ReadMaterialBasic(newMaterial, offset, fileData, fileByteSize); + if (offset + sizeof(unsigned char) * 4 > fileByteSize) { + throw Resource::FailedLoadingException("Reading Material NumOfMaps failed"); + } + unsigned char numberOfMaps[4]; + memcpy(numberOfMaps, fileData + offset, sizeof(unsigned char) * 4); + offset += sizeof(unsigned char) * 4; + + if (numberOfMaps[0] > 0) + { + ReadMaterialTextureProperties(newMaterial->ColorMap, offset, fileData, fileByteSize); + } + + if (numberOfMaps[1] > 0) + { + ReadMaterialTextureProperties(newMaterial->SpecularMap, offset, fileData, fileByteSize); + } + + if (numberOfMaps[2] > 0) + { + ReadMaterialTextureProperties(newMaterial->NormalMap, offset, fileData, fileByteSize); + } + + if (numberOfMaps[3] > 0) + { + ReadMaterialTextureProperties(newMaterial->IncandescenceMap, offset, fileData, fileByteSize); + } +} + +void RawModelCustom::ReadMaterialSplatMapping(RawModelCustom::MaterialSplatMapping* newMaterial, std::size_t& offset, char* fileData, const unsigned int& fileByteSize) +{ + ReadMaterialBasic(newMaterial, offset, fileData, fileByteSize); + ReadMaterialTextureProperties(newMaterial->SplatMap, offset, fileData, fileByteSize); + if (offset + sizeof(unsigned char) * 4 > fileByteSize) { + throw Resource::FailedLoadingException("Reading Material NumOfMaps failed"); + } + + unsigned char numberOfMaps[4]; + memcpy(numberOfMaps, fileData + offset, sizeof(unsigned char) * 4); + offset += sizeof(unsigned char) * 4; + + newMaterial->ColorMaps.resize(numberOfMaps[0]); + for (unsigned char i = 0; i < numberOfMaps[0]; i++) + { + ReadMaterialTextureProperties(newMaterial->ColorMaps[i], offset, fileData, fileByteSize); + } + + newMaterial->SpecularMaps.resize(numberOfMaps[1]); + for (unsigned char i = 0; i < numberOfMaps[1]; i++) + { + ReadMaterialTextureProperties(newMaterial->SpecularMaps[i], offset, fileData, fileByteSize); + } + + newMaterial->NormalMaps.resize(numberOfMaps[2]); + for (unsigned char i = 0; i < numberOfMaps[2]; i++) + { + ReadMaterialTextureProperties(newMaterial->NormalMaps[i], offset, fileData, fileByteSize); + } + + newMaterial->IncandescenceMaps.resize(numberOfMaps[3]); + for (unsigned char i = 0; i < numberOfMaps[3]; i++) + { + ReadMaterialTextureProperties(newMaterial->IncandescenceMaps[i], offset, fileData, fileByteSize); + } +} + +void RawModelCustom::ReadMaterialTextureProperties(RawModelCustom::TextureProperties& texture, std::size_t& offset, char* fileData, const unsigned int& fileByteSize) { + unsigned int nameLength = *(unsigned int*)(fileData + offset); + offset += sizeof(unsigned int); + + if (nameLength > 0) { + if (offset + nameLength > fileByteSize) { + throw Resource::FailedLoadingException("Reading Material texture path failed"); + } + texture.TexturePath = "Textures/"; + texture.TexturePath += (fileData + offset); + texture.TexturePath += ".png"; + offset += nameLength; + if (offset + sizeof(glm::vec2) > fileByteSize) { + throw Resource::FailedLoadingException("Reading Material texture UVTiling failed"); + } + memcpy(&texture.UVRepeat[0], fileData + offset, sizeof(glm::vec2)); + } + offset += sizeof(glm::vec2); } void RawModelCustom::ReadAnimationFile(std::string filePath) @@ -207,7 +288,9 @@ void RawModelCustom::ReadAnimationFile(std::string filePath) std::ifstream in(filePath.c_str(), std::ios_base::binary | std::ios_base::ate); if (!in.is_open()) { - //throw Resource::FailedLoadingException("Open animation file failed"); + if (hasSkin) { + throw Resource::FailedLoadingException("Open animation file for a skinned mesh failed, unknown stuff will happen"); + } return; } @@ -233,7 +316,7 @@ void RawModelCustom::ReadAnimationFile(std::string filePath) ReadAnimationBindPoses(offset, fileData, fileByteSize); ReadAnimationClips(offset, fileData, fileByteSize, numAnimations); } - delete fileData; + delete[] fileData; } void RawModelCustom::ReadAnimationBindPoses(std::size_t& offset, char* fileData, const unsigned int& fileByteSize) @@ -318,32 +401,43 @@ void RawModelCustom::ReadAnimationClipSingle(std::size_t& offset, char* fileData if (offset + sizeof(float) > fileByteSize) { throw Resource::FailedLoadingException("Reading AnimationClip duration failed"); } - newAnimation.Duration = *(float*)(fileData + offset); offset += sizeof(float); if (offset + sizeof(unsigned int) > fileByteSize) { - throw Resource::FailedLoadingException("Reading AnimationClip NrOfKeyframes failed"); + throw Resource::FailedLoadingException("Reading AnimationClip numberOfJointFrames failed"); } - unsigned int nrOfKeyframes = *(unsigned int*)(fileData + offset); + unsigned int numberOfJointFrames = *(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); + for (unsigned int i = 0; i < numberOfJointFrames; i++) { + if (offset + sizeof(unsigned int) > fileByteSize) { + throw Resource::FailedLoadingException("Reading AnimationClip JointID failed"); + } + int jointID = *(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); + if (offset + sizeof(unsigned int) > fileByteSize) { + throw Resource::FailedLoadingException("Reading AnimationClip numberOFKeyFrames failed"); + } + unsigned int numberOFKeyFrames = *(unsigned int*)(fileData + offset); + offset += sizeof(unsigned int); + + if (numberOFKeyFrames > 0) { + newAnimation.JointAnimations[jointID].reserve(numberOFKeyFrames); + + for (unsigned int j = 0; j < numberOFKeyFrames; j++) { + ReadAnimationKeyFrame(offset, fileData, fileByteSize, newAnimation.JointAnimations[jointID]); + } + } } m_Skeleton->Animations[newAnimation.Name] = newAnimation; + //m_Skeleton->Animations[newAnimation.Name].KeyFrameAmount = nrOfKeyframes; #else #endif } -void RawModelCustom::ReadAnimationKeyFrame(std::size_t& offset, char* fileData, const unsigned int& fileByteSize, unsigned int numberOfJoints, Skeleton::Animation& animation) +void RawModelCustom::ReadAnimationKeyFrame(std::size_t& offset, char* fileData, const unsigned int& fileByteSize, std::vector& animation) { Skeleton::Animation::Keyframe newKeyFrame; @@ -359,17 +453,27 @@ void RawModelCustom::ReadAnimationKeyFrame(std::size_t& offset, char* fileData, newKeyFrame.Time = *(float*)(fileData + offset); offset += sizeof(float); - if (offset + sizeof(Skeleton::Animation::Keyframe::BoneProperty) * numberOfJoints> fileByteSize) { - throw Resource::FailedLoadingException("Reading AnimationKeyFrame joints failed"); + if (offset + sizeof(float) * 3 > fileByteSize) { + throw Resource::FailedLoadingException("Reading AnimationKeyFrame Position failed"); } + memcpy(&newKeyFrame.BoneProperties.Position[0], fileData + offset, sizeof(float) * 3); + offset += sizeof(float) * 3; - Skeleton::Animation::Keyframe::BoneProperty newBone; - for (unsigned int i = 0; i < numberOfJoints; i++) { - memcpy(&newBone, (fileData + offset), sizeof(Skeleton::Animation::Keyframe::BoneProperty)); - offset += sizeof(Skeleton::Animation::Keyframe::BoneProperty); - newKeyFrame.BoneProperties[newBone.ID] = newBone; + if (offset + sizeof(float) * 4 > fileByteSize) { + throw Resource::FailedLoadingException("Reading AnimationKeyFrame Rotation failed"); } - animation.Keyframes.push_back(newKeyFrame); + memcpy(&newKeyFrame.BoneProperties.Rotation[0], fileData + offset, sizeof(float) * 4); + offset += sizeof(float) * 4; + + if (offset + sizeof(float) * 3 > fileByteSize) { + throw Resource::FailedLoadingException("Reading AnimationKeyFrame Scale failed"); + } + memcpy(&newKeyFrame.BoneProperties.Scale[0], fileData + offset, sizeof(float) * 3); + offset += sizeof(float) * 3; + + + animation.push_back(newKeyFrame); + } RawModelCustom::~RawModelCustom() @@ -377,6 +481,9 @@ RawModelCustom::~RawModelCustom() if (m_Skeleton != nullptr) { delete m_Skeleton; } + for (auto material : m_Materials) { + delete material.material; + } } #endif \ No newline at end of file diff --git a/src/Engine/Rendering/RenderState.cpp b/src/Engine/Rendering/RenderState.cpp index 1da2f0b1..26ba18a1 100644 --- a/src/Engine/Rendering/RenderState.cpp +++ b/src/Engine/Rendering/RenderState.cpp @@ -6,9 +6,10 @@ bool RenderState::Enable(GLenum cap) //LOG_WARNING("Trying to enable somthing that is already enabled."); return false; } + m_ResetFunctions.push_back(std::bind(glDisable, cap)); glEnable(cap); - return !GLERROR("RenderState::Enable"); + return !GLERROR("Enable"); } bool RenderState::Disable(GLenum cap) @@ -16,9 +17,10 @@ bool RenderState::Disable(GLenum cap) if (!glIsEnabled(cap)) { return false; } + m_ResetFunctions.push_back(std::bind(glEnable, cap)); glDisable(cap); - return !GLERROR("RenderState::Disable"); + return !GLERROR("Disable"); } bool RenderState::CullFace(GLenum mode) @@ -32,7 +34,7 @@ bool RenderState::CullFace(GLenum mode) glGetIntegerv(GL_CULL_FACE_MODE, &original); m_ResetFunctions.push_back(std::bind(glCullFace, original)); glCullFace(mode); - return !GLERROR("RenderState::CullFace"); + return !GLERROR("CullFace"); } bool RenderState::ClearColor(glm::vec4 color) @@ -41,7 +43,7 @@ bool RenderState::ClearColor(glm::vec4 color) glGetFloatv(GL_COLOR_CLEAR_VALUE, &original[0]); m_ResetFunctions.push_back(std::bind(glClearColor, original[0], original[1], original[2], original[3])); glClearColor(color.r, color.g, color.b, color.a); - return !GLERROR("RenderState::ClearColor"); + return !GLERROR("ClearColor"); } bool RenderState::BindFramebuffer(GLint framebuffer) @@ -55,7 +57,7 @@ bool RenderState::BindFramebuffer(GLint framebuffer) glBindFramebuffer(GL_DRAW_FRAMEBUFFER, originalDraw); }); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); - return !GLERROR("RenderState::BindBuffer"); + return !GLERROR("BindBuffer"); } @@ -67,7 +69,7 @@ bool RenderState::BlendEquation(GLenum mode) glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &originalAlpha); m_ResetFunctions.push_back(std::bind(glBlendEquationSeparate, originalRGB, originalAlpha)); glBlendEquation(mode); - return !GLERROR("RenderState::BlendEquation"); + return !GLERROR("BlendEquation"); } bool RenderState::BlendFunc(GLenum sfactor, GLenum dfactor) @@ -82,7 +84,46 @@ bool RenderState::BlendFunc(GLenum sfactor, GLenum dfactor) glGetIntegerv(GL_BLEND_DST_ALPHA, &originalDestAlpha); m_ResetFunctions.push_back(std::bind(glBlendFuncSeparate, originalSrcRGB, originalSrcAlpha, originalDestRGB, originalDestAlpha)); glBlendFunc(sfactor, dfactor); - return !GLERROR("RenderState::BlendFunc"); + return !GLERROR("BlendFunc"); +} + + +bool RenderState::StencilOp(GLenum sfail, GLenum dpfail, GLenum dppass) +{ + GLint originalSFail; + glGetIntegerv(GL_STENCIL_FAIL, &originalSFail); + GLint originalDPFail; + glGetIntegerv(GL_STENCIL_PASS_DEPTH_FAIL, &originalDPFail); + GLint originalDPPass; + glGetIntegerv(GL_STENCIL_PASS_DEPTH_PASS, &originalDPPass); + m_ResetFunctions.push_back(std::bind(glStencilOp, originalSFail, originalDPFail, originalDPPass)); + glStencilOp(sfail, dpfail, dppass); + return !GLERROR("StencilOp"); +} + + +bool RenderState::StencilFunc(GLenum func, GLint ref, GLuint mask) +{ + GLint originalFunc; + glGetIntegerv(GL_STENCIL_FUNC, &originalFunc); + GLint originalRef; + glGetIntegerv(GL_STENCIL_REF, &originalRef); + GLint originalMask; + glGetIntegerv(GL_STENCIL_VALUE_MASK, &originalMask); + m_ResetFunctions.push_back(std::bind(glStencilFunc, originalFunc, originalRef, originalMask)); + glStencilFunc(func, ref, mask); + return !GLERROR("StencilFunc"); +} + + + +bool RenderState::StencilMask(GLuint mask) +{ + GLint originalMask; + glGetIntegerv(GL_STENCIL_WRITEMASK, &originalMask); + m_ResetFunctions.push_back(std::bind(glStencilMask, mask)); + glStencilMask(mask); + return !GLERROR("StencilMask"); } bool RenderState::DepthMask(GLboolean flag) @@ -91,12 +132,12 @@ bool RenderState::DepthMask(GLboolean flag) glGetBooleanv(GL_DEPTH_WRITEMASK, &original); m_ResetFunctions.push_back(std::bind(glDepthMask, original)); glDepthMask(flag); - return !GLERROR("RenderState::DepthMask"); + return !GLERROR("DepthMask"); } RenderState::~RenderState() { - for (auto& f : m_ResetFunctions) { + for (auto& f : boost::adaptors::reverse(m_ResetFunctions)) { f(); } } diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index 03613842..6035a011 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -1,10 +1,12 @@ #include "Rendering/RenderSystem.h" +#include "Collision/Collision.h" +#include "Core/Frustum.h" -RenderSystem::RenderSystem(World* world, EventBroker* eventBroker, const IRenderer* renderer, RenderFrame* renderFrame) - : System(world, eventBroker) +RenderSystem::RenderSystem(SystemParams params, const IRenderer* renderer, RenderFrame* renderFrame, Octree* frustumCullOctree) + : System(params) , m_Renderer(renderer) , m_RenderFrame(renderFrame) - , m_World(world) + , m_Octree(frustumCullOctree) { EVENT_SUBSCRIBE_MEMBER(m_ESetCamera, &RenderSystem::OnSetCamera); EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &RenderSystem::OnInputCommand); @@ -31,6 +33,160 @@ bool RenderSystem::OnSetCamera(Events::SetCamera& e) return true; } + +void RenderSystem::fillSprites(std::list>& jobs, World* world) +{ + auto sprites = world->GetComponents("Sprite"); + if (sprites == nullptr) { + return; + } + + for (auto& cSprite : *sprites) { + bool visible = cSprite["Visible"]; + if (!visible) { + continue; + } + + EntityWrapper entity(world, cSprite.EntityID); + if (!isEntityVisible(entity)) { + continue; + } + + glm::mat4 modelMatrix; + + // See a sprite is an SpriteIndicator + bool isIndicator = false; + if (world->HasComponent(entity.ID, "SpriteIndicator")) + { + auto indicator = entity["SpriteIndicator"]; + + float minScale = (float)(double)indicator["MinScale"]; + bool hasTeam = indicator["VisibleForSingleTeamOnly"]; + isIndicator = true; + glm::vec3 pos = Transform::AbsolutePosition(entity); + + + EntityWrapper entityTeam; + if (hasTeam && (entity.HasComponent("Team") || entity.FirstParentWithComponent("Team").Valid()) && m_LocalPlayer.World != nullptr) { + if (!entity.HasComponent("Team")) { + entityTeam = entity.FirstParentWithComponent("Team"); + } + else { + entityTeam = entity; + } + + ComponentWrapper& entityTeamComponent = entityTeam["Team"]; + ComponentWrapper& localComponent = m_LocalPlayer["Team"]; + int entityTeamInt = entityTeamComponent["Team"]; + int localComponentInt = localComponent["Team"]; + int SpectatorInt = localComponent["Team"].Enum("Spectator"); + if (entityTeamInt != localComponentInt && localComponentInt != SpectatorInt) { + continue; + } + } + + // Code for check if sprite is inside or outside of screen + //glm::vec4 projectedPos = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix() * glm::vec4(pos, 1.0f); + //projectedPos /= projectedPos.w; + //// Check if inside of outside of screen. + //if (projectedPos.x < -1.0f || projectedPos.x > 1.0f || projectedPos.y < -1.0f || projectedPos.y > 1.0f) { + // // is outside of screen + //} else { + // // is inside of screen + //} + + + glm::vec3 zAxis = glm::vec3(0.0f, 1.0f, 0.0f); + glm::vec3 normal = pos - m_Camera->Position(); + + //float distance = glm::length(normal); + //if (distance < minDistance) { + // pos = pos - glm::normalize(normal) * (distance - minDistance); + //} else if (distance > maxDistance) { + // pos = pos - glm::normalize(normal) * (distance - maxDistance); + //} + normal.y = 0; + normal = glm::normalize(normal); + glm::vec3 right = glm::cross(normal, zAxis); + glm::vec3 up = glm::cross(right, normal); + + modelMatrix[0][0] = right.x; + modelMatrix[0][1] = right.y; + modelMatrix[0][2] = right.z; + modelMatrix[0][3] = 0.0f; + + modelMatrix[1][0] = zAxis.x; + modelMatrix[1][1] = zAxis.y; + modelMatrix[1][2] = zAxis.z; + modelMatrix[1][3] = 0.0f; + + modelMatrix[2][0] = normal.x; + modelMatrix[2][1] = normal.y; + modelMatrix[2][2] = normal.z; + modelMatrix[2][3] = 0.0f; + + modelMatrix[3][0] = pos.x; + modelMatrix[3][1] = pos.y; + modelMatrix[3][2] = pos.z; + modelMatrix[3][3] = 1.0f; + + glm::mat4 tranformationMatrix = modelMatrix * glm::scale(Transform::AbsoluteScale(entity)); + glm::vec4 tmp = tranformationMatrix * glm::vec4(glm::vec3(0.5, 0.5, 0), 1.0f); + glm::vec2 projectedTopRight = m_Camera->WorldToScreen(glm::vec3(tmp), m_Renderer->GetViewportSize()); + tmp = tranformationMatrix * glm::vec4(glm::vec3(-0.5, -0.5, 0), 1.0f); + glm::vec2 projectedBottomLeft = m_Camera->WorldToScreen(glm::vec3(tmp), m_Renderer->GetViewportSize()); + + float diag = glm::length(projectedBottomLeft - projectedTopRight); + if (diag < minScale) { + tranformationMatrix = tranformationMatrix * glm::scale(glm::vec3(minScale / diag, minScale / diag, minScale / diag)); + } + modelMatrix = tranformationMatrix; + } + else { + modelMatrix = Transform::ModelMatrix(entity.ID, world); + } + + + std::string diffuseResource = cSprite["DiffuseTexture"]; + std::string glowResource = cSprite["GlowMap"]; + bool depthSorted = cSprite["DepthSort"]; + if (diffuseResource.empty() && glowResource.empty()) { + continue; + } + + float fillPercentage = 0.f; + glm::vec4 fillColor = glm::vec4(0); + if (world->HasComponent(entity.ID, "Fill")) { + auto fillComponent = world->GetComponent(entity.ID, "Fill"); + fillPercentage = (float)(double)fillComponent["Percentage"]; + fillColor = (glm::vec4)fillComponent["Color"]; + } + + std::shared_ptr spriteJob = std::shared_ptr(new SpriteJob(cSprite, m_Camera, modelMatrix, world, fillColor, fillPercentage, depthSorted, isIndicator)); + + jobs.push_back(spriteJob); + } +} + +bool RenderSystem::isEntityVisible(EntityWrapper& entity) +{ + // Only render children of a camera if that camera is currently active + if (isChildOfACamera(entity) && !isChildOfCurrentCamera(entity)) { + return false; + } + + // Hide things parented to local player if they have the HiddenFromLocalPlayer component + bool outOfBodyExperience = ResourceManager::Load("Config.ini")->Get("Debug.OutOfBodyExperience", false); + if ( + (entity.HasComponent("HiddenForLocalPlayer") || entity.FirstParentWithComponent("HiddenForLocalPlayer").Valid()) + && (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer)) + && !outOfBodyExperience + ) { + return false; + } + return true; +} + bool RenderSystem::isChildOfACamera(EntityWrapper entity) { return entity.FirstParentWithComponent("Camera").Valid(); @@ -40,14 +196,15 @@ bool RenderSystem::isChildOfCurrentCamera(EntityWrapper entity) return entity == m_CurrentCamera || entity.IsChildOf(m_CurrentCamera); } -void RenderSystem::fillModels(std::list>& opaqueJobs, std::list>& transparentJobs) +void RenderSystem::fillModels(RenderScene::Queues &Jobs) { - auto models = m_World->GetComponents("Model"); - if (models == nullptr) { - return; - } + Frustum frustum(m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix()); + std::vector seenEntities; + m_Octree->ObjectsInFrustum(frustum, seenEntities); - for (auto& cModel : *models) { + for (auto& seenEntity : seenEntities) { + EntityWrapper entity = seenEntity.Entity; + ComponentWrapper cModel = entity["Model"]; bool visible = cModel["Visible"]; if (!visible) { continue; @@ -57,15 +214,7 @@ void RenderSystem::fillModels(std::list>& opaqueJobs, continue; } - EntityWrapper entity(m_World, cModel.EntityID); - - // Only render children of a camera if that camera is currently active - if (isChildOfACamera(entity) && !isChildOfCurrentCamera(entity)) { - continue; - } - - // Hide things parented to local player if they have the HiddenFromLocalPlayer component - if (entity.HasComponent("HiddenForLocalPlayer") && (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer))) { + if (!isEntityVisible(entity)) { continue; } @@ -92,7 +241,9 @@ void RenderSystem::fillModels(std::list>& opaqueJobs, } glm::mat4 modelMatrix = Transform::ModelMatrix(cModel.EntityID, m_World); + //Loop through all materialgroups of a model for (auto matGroup : model->MaterialGroups()) { + //If the model has an explosioneffect component, we will add an explosioneffectjob if (m_World->HasComponent(cModel.EntityID, "ExplosionEffect")) { auto explosionEffectComponent = m_World->GetComponent(cModel.EntityID, "ExplosionEffect"); std::shared_ptr explosionEffectJob = std::shared_ptr(new ExplosionEffectJob( @@ -106,14 +257,33 @@ void RenderSystem::fillModels(std::list>& opaqueJobs, fillColor, fillPercentage )); - if(explosionEffectJob->Color.a != 1.f || explosionEffectJob->EndColor.a != 1.f || explosionEffectJob->DiffuseColor.a != 1.f) { - cModel["Transparent"] = true; - } + if (m_World->HasComponent(cModel.EntityID, "Shield")){ + explosionEffectJob->CalculateHash(); + Jobs.ShieldObjects.push_back(explosionEffectJob); + } else if (m_World->HasComponent(cModel.EntityID, "Shielded") + || m_World->HasComponent(cModel.EntityID, "Player")) { - if (cModel["Transparent"]) { - transparentJobs.push_back(explosionEffectJob); + if (explosionEffectJob->Color.a != 1.f || explosionEffectJob->EndColor.a != 1.f || explosionEffectJob->DiffuseColor.a != 1.f) { + cModel["Transparent"] = true; + } + + if (cModel["Transparent"]) { + Jobs.TransparentShieldedObjects.push_back(explosionEffectJob); + } else { + explosionEffectJob->CalculateHash(); + Jobs.OpaqueShieldedObjects.push_back(explosionEffectJob); + } } else { - opaqueJobs.push_back(explosionEffectJob); + if (explosionEffectJob->Color.a != 1.f || explosionEffectJob->EndColor.a != 1.f || explosionEffectJob->DiffuseColor.a != 1.f) { + cModel["Transparent"] = true; + } + + if (cModel["Transparent"]) { + Jobs.TransparentObjects.push_back(explosionEffectJob); + } else { + explosionEffectJob->CalculateHash(); + Jobs.OpaqueObjects.push_back(explosionEffectJob); + } } } else { std::shared_ptr modelJob = std::shared_ptr(new ModelJob( @@ -126,13 +296,33 @@ void RenderSystem::fillModels(std::list>& opaqueJobs, fillColor, fillPercentage )); - if (modelJob->Color.a != 1.f || modelJob->DiffuseColor.a != 1.f) { - cModel["Transparent"] = true; - } - if (cModel["Transparent"]) { - transparentJobs.push_back(modelJob); + if (m_World->HasComponent(cModel.EntityID, "Shield")) { + modelJob->CalculateHash(); + Jobs.ShieldObjects.push_back(modelJob); + } else if (m_World->HasComponent(cModel.EntityID, "Shielded") + || m_World->HasComponent(cModel.EntityID, "Player")) { + + if (modelJob->Color.a != 1.f || modelJob->DiffuseColor.a != 1.f) { + cModel["Transparent"] = true; + } + + if (cModel["Transparent"]) { + Jobs.TransparentShieldedObjects.push_back(modelJob); + } else { + modelJob->CalculateHash(); + Jobs.OpaqueShieldedObjects.push_back(modelJob); + } } else { - opaqueJobs.push_back(modelJob); + if (modelJob->Color.a != 1.f || modelJob->DiffuseColor.a != 1.f) { + cModel["Transparent"] = true; + } + + if (cModel["Transparent"]) { + Jobs.TransparentObjects.push_back(modelJob); + } else { + modelJob->CalculateHash(); + Jobs.OpaqueObjects.push_back(modelJob); + } } } } @@ -167,7 +357,6 @@ void RenderSystem::fillPointLights(std::list>& jobs, } } - void RenderSystem::fillDirectionalLights(std::list>& jobs, World* world) { auto directionalLights = world->GetComponents("DirectionalLight"); @@ -189,14 +378,13 @@ void RenderSystem::fillDirectionalLights(std::list>& } } - void RenderSystem::fillText(std::list>& jobs, World* world) { auto texts = world->GetComponents("Text"); if (texts == nullptr) { return; } - + for (auto& textComponent : *texts) { bool visible = textComponent["Visible"]; if (!visible) { @@ -207,6 +395,11 @@ void RenderSystem::fillText(std::list>& jobs, World* continue; } + EntityWrapper entity(world, textComponent.EntityID); + if (!isEntityVisible(entity)) { + continue; + } + Font* font; try { font = ResourceManager::Load(resource); @@ -251,10 +444,13 @@ void RenderSystem::Update(double dt) scene.AmbientColor = (glm::vec4)(*cSceneLight->begin())["AmbientColor"]; } - fillModels(scene.OpaqueObjects, scene.TransparentObjects); - fillPointLights(scene.PointLightJobs, m_World); - fillDirectionalLights(scene.DirectionalLightJobs, m_World); - fillText(scene.TextJobs, m_World); + fillModels(scene.Jobs); + fillPointLights(scene.Jobs.PointLight, m_World); + //TODO: Make sure all objects needed are also sorted. + scene.Jobs.OpaqueObjects.sort(); + fillSprites(scene.Jobs.SpriteJob, m_World); + fillDirectionalLights(scene.Jobs.DirectionalLight, m_World); + fillText(scene.Jobs.Text, m_World); m_RenderFrame->Add(scene); } \ No newline at end of file diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index cdbd5786..7c2555d6 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -1,5 +1,7 @@ #include "Rendering/Renderer.h" +std::unordered_map Renderer::m_WindowToRenderer; + void Renderer::Initialize() { InitializeWindow(); @@ -12,7 +14,6 @@ void Renderer::Initialize() m_TextPass = new TextPass(); m_TextPass->Initialize(); - /* m_ScreenQuad = ResourceManager::Load("Models/Core/ScreenQuad.obj"); m_UnitQuad = ResourceManager::Load("Models/Core/UnitQuad.obj"); m_UnitSphere = ResourceManager::Load("Models/Core/UnitSphere.obj");*/ @@ -20,6 +21,18 @@ void Renderer::Initialize() m_ImGuiRenderPass = new ImGuiRenderPass(this, m_EventBroker); } +void Renderer::glfwFrameBufferCallback(GLFWwindow* window, int width, int height) +{ + glViewport(0, 0, width, height); + Renderer* currentRenderer = m_WindowToRenderer[window]; + currentRenderer->m_ViewportSize = Rectangle(width, height); + currentRenderer->m_DrawFinalPass->OnWindowResize(); + currentRenderer->m_LightCullingPass->OnWindowResize(); + currentRenderer->m_PickingPass->OnWindowResize(); + currentRenderer->m_DrawBloomPass->OnWindowResize(); + currentRenderer->m_SSAOPass->OnWindowResize(); +} + void Renderer::InitializeWindow() { // Initialize GLFW @@ -39,6 +52,7 @@ void Renderer::InitializeWindow() LOG_ERROR("GLFW: Failed to create window"); exit(EXIT_FAILURE); } + glfwSetFramebufferSizeCallback(m_Window, &glfwFrameBufferCallback); glfwMakeContextCurrent(m_Window); // GL version info @@ -51,7 +65,7 @@ void Renderer::InitializeWindow() ss << " DEBUG"; #endif LOG_INFO(ss.str().c_str()); - glfwSetWindowTitle(m_Window, ss.str().c_str()); + SetWindowTitle(ss.str()); // Initialize GLEW if (glewInit() != GLEW_OK) { @@ -59,8 +73,10 @@ void Renderer::InitializeWindow() exit(EXIT_FAILURE); } + m_WindowToRenderer[m_Window] = this; + int windowSize[2]; - glfwGetWindowSize(m_Window, &windowSize[0], &windowSize[1]); + glfwGetFramebufferSize(m_Window, &windowSize[0], &windowSize[1]); m_ViewportSize = Rectangle(windowSize[0], windowSize[1]); } @@ -85,37 +101,83 @@ void Renderer::Update(double dt) void Renderer::Draw(RenderFrame& frame) { - ImGui::Combo("Draw textures", &m_DebugTextureToDraw, "Final\0Scene\0Bloom\0Gaussian\0Picking"); + GLERROR("PRE"); + ImGui::Combo("Draw textures", &m_DebugTextureToDraw, "Final\0Scene\0Bloom\0SceneLowRes\0BloomLowRes\0Gaussian\0Picking\0Ambient Occlusion"); + ImGui::Combo("CubeMap", &m_CubeMapTexture, "Nevada(512)\0Sky(1024)"); + if(m_CubeMapTexture == 0) { + m_CubeMapPass->LoadTextures("Nevada"); + } else if (m_CubeMapTexture == 1) { + m_CubeMapPass->LoadTextures("Sky"); + } + + ImGui::SliderFloat("SSAO sample radius", &m_SSAO_Radius, 0.01f, 5.0f); + ImGui::SliderFloat("SSAO bias", &m_SSAO_Bias, 0.0f, 0.1f); + ImGui::SliderFloat("SSAO contrast", &m_SSAO_Contrast, 0.0f, 10.0f); + ImGui::SliderFloat("SSAO IntensityScale", &m_SSAO_IntensityScale, 0.0f, 10.0f); + ImGui::SliderInt("SSAO Number of Samples", &m_SSAO_NumOfSamples, 2, 100); + ImGui::SliderInt("SSAO Number of Turns", &m_SSAO_NumOfTurns, 0, 50); + m_SSAOPass->Setting(m_SSAO_Radius, m_SSAO_Bias, m_SSAO_Contrast, m_SSAO_IntensityScale, m_SSAO_NumOfSamples, m_SSAO_NumOfTurns); + GLERROR("SSAO Settings"); //clear buffer 0 glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //Clear other buffers + PerformanceTimer::StartTimer("Renderer-ClearBuffers"); m_PickingPass->ClearPicking(); m_DrawFinalPass->ClearBuffer(); m_DrawBloomPass->ClearBuffer(); m_ShadowPass->ClearBuffer(); - + m_SSAOPass->ClearBuffer(); + PerformanceTimer::StopTimer("Renderer-ClearBuffers"); + GLERROR("ClearBuffers"); + for (auto scene : frame.RenderScenes) { + PerformanceTimer::StartTimer("Renderer-Depth"); + m_PickingPass->Draw(*scene); + GLERROR("Drawing pickingpass"); + PerformanceTimer::StopTimer("Renderer-Depth"); + } + PerformanceTimer::StartTimer("AO generation"); + m_SSAOPass->Draw(m_PickingPass->DepthBuffer(), frame.RenderScenes.front()->Camera); + GLuint ao = m_SSAOPass->SSAOTexture(); + PerformanceTimer::StopTimer("AO generation"); for (auto scene : frame.RenderScenes){ + PerformanceTimer::StartTimer("Renderer-Drawing PickingPass"); SortRenderJobsByDepth(*scene); - m_PickingPass->Draw(*scene); + GLERROR("SortByDepth"); m_ShadowPass->Draw(*scene); + PerformanceTimer::StartTimerAndStopPrevious("Renderer-Generate Frustrums"); m_LightCullingPass->GenerateNewFrustum(*scene); + GLERROR("Generate frustums"); + PerformanceTimer::StartTimerAndStopPrevious("Renderer-Filling Light List"); m_LightCullingPass->FillLightList(*scene); + GLERROR("Filling light list"); + PerformanceTimer::StartTimerAndStopPrevious("Renderer-Light Culling"); m_LightCullingPass->CullLights(*scene); - m_DrawFinalPass->Draw(*scene); + GLERROR("LightCulling"); + m_DrawFinalPass->Draw(*scene, ao); + PerformanceTimer::StartTimerAndStopPrevious("Renderer-Draw Geometry+Light"); + GLERROR("Draw Geometry+Light"); //m_DrawScenePass->Draw(*scene); - GLERROR("Renderer::Draw m_DrawScenePass->Draw"); - + PerformanceTimer::StartTimerAndStopPrevious("Renderer-Draw Text"); m_TextPass->Draw(*scene, *m_DrawFinalPass->FinalPassFrameBuffer()); + GLERROR("Draw Text"); + PerformanceTimer::StopTimer("Renderer-Draw Text"); + } - } + PerformanceTimer::StartTimer("Renderer-Draw Bloom"); m_DrawBloomPass->Draw(m_DrawFinalPass->BloomTexture()); + PerformanceTimer::StopTimer("Renderer-Draw Bloom"); + if (m_DebugTextureToDraw == 0) { - m_DrawColorCorrectionPass->Draw(m_DrawFinalPass->SceneTexture(), m_DrawBloomPass->GaussianTexture(), frame.Gamma, frame.Exposure); + PerformanceTimer::StartTimer("Renderer-Color Correction Pass"); + m_DrawColorCorrectionPass->Draw(m_DrawFinalPass->SceneTexture(), m_DrawBloomPass->GaussianTexture(), m_DrawFinalPass->SceneTextureLowRes(), m_DrawFinalPass->BloomTextureLowRes(), frame.Gamma, frame.Exposure); + PerformanceTimer::StopTimer("Renderer-Color Correction Pass"); } + + PerformanceTimer::StartTimer("Renderer-Misc Debug Draws"); if (m_DebugTextureToDraw == 1) { m_DrawScreenQuadPass->Draw(m_DrawFinalPass->SceneTexture()); } @@ -123,14 +185,27 @@ void Renderer::Draw(RenderFrame& frame) m_DrawScreenQuadPass->Draw(m_DrawFinalPass->BloomTexture()); } if (m_DebugTextureToDraw == 3) { - m_DrawScreenQuadPass->Draw(m_DrawBloomPass->GaussianTexture()); + m_DrawScreenQuadPass->Draw(m_DrawFinalPass->SceneTextureLowRes()); } if (m_DebugTextureToDraw == 4) { + m_DrawScreenQuadPass->Draw(m_DrawFinalPass->BloomTextureLowRes()); + } + if (m_DebugTextureToDraw == 5) { + m_DrawScreenQuadPass->Draw(m_DrawBloomPass->GaussianTexture()); + } + if (m_DebugTextureToDraw == 6) { m_DrawScreenQuadPass->Draw(m_PickingPass->PickingTexture()); } + if (m_DebugTextureToDraw == 7) { + m_DrawScreenQuadPass->Draw(m_SSAOPass->SSAOTexture()); + } + PerformanceTimer::StopTimer("Renderer-Misc Debug Draws"); + PerformanceTimer::StartTimer("Renderer-ImGuiRenderPass"); m_ImGuiRenderPass->Draw(); - glfwSwapBuffers(m_Window); + GLERROR("Imgui draw"); + glfwSwapBuffers(m_Window); + PerformanceTimer::StopTimer("Renderer-ImGuiRenderPass"); } PickData Renderer::Pick(glm::vec2 screenCoord) @@ -140,15 +215,17 @@ PickData Renderer::Pick(glm::vec2 screenCoord) void Renderer::InitializeTextures() { - m_ErrorTexture = ResourceManager::Load("Textures/Core/ErrorTexture.png"); - m_WhiteTexture = ResourceManager::Load("Textures/Core/White.png"); + m_ErrorTexture = CommonFunctions::LoadTexture("Textures/Core/ErrorTexture.png", false); + m_WhiteTexture = CommonFunctions::LoadTexture("Textures/Core/White.png", false); } void Renderer::SortRenderJobsByDepth(RenderScene &scene) { //Sort all forward jobs so transparency is good. - scene.TransparentObjects.sort(Renderer::DepthSort); + scene.Jobs.TransparentObjects.sort(Renderer::DepthSort); + scene.Jobs.SpriteJob.sort(Renderer::DepthSort); + scene.Jobs.Text.sort(Renderer::DepthSort); } void Renderer::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) @@ -168,8 +245,10 @@ void Renderer::InitializeRenderPasses() m_PickingPass = new PickingPass(this, m_EventBroker); m_LightCullingPass = new LightCullingPass(this); m_ShadowPass = new ShadowPass(this); - m_DrawFinalPass = new DrawFinalPass(this, m_LightCullingPass, m_ShadowPass); + m_CubeMapPass = new CubeMapPass(this); + m_DrawFinalPass = new DrawFinalPass(this, m_LightCullingPass, m_CubeMapPass, m_ShadowPass); m_DrawScreenQuadPass = new DrawScreenQuadPass(this); m_DrawBloomPass = new DrawBloomPass(this); m_DrawColorCorrectionPass = new DrawColorCorrectionPass(this); + m_SSAOPass = new SSAOPass(this); } diff --git a/src/Engine/Rendering/SSAOPass.cpp b/src/Engine/Rendering/SSAOPass.cpp new file mode 100644 index 00000000..d4cdcb19 --- /dev/null +++ b/src/Engine/Rendering/SSAOPass.cpp @@ -0,0 +1,145 @@ +#include "Rendering/SSAOPass.h" + +SSAOPass::SSAOPass(IRenderer* renderer) +{ + m_Renderer = renderer; + + m_ScreenQuad = ResourceManager::Load("Models/Core/ScreenQuad.mesh"); + + InitializeTexture(); + InitializeBuffer(); + InitializeShaderProgram(); + Setting(0.1f, 0.012f, 1.0f, 1.0f, 13, 7); + + m_DrawBloomPass = new DrawBloomPass(renderer); +} + +void SSAOPass::InitializeShaderProgram() +{ + m_SSAOProgram = ResourceManager::Load("##SSAOProgram"); + m_SSAOProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/SSAO.vert.glsl"))); + m_SSAOProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/SSAO.frag.glsl"))); + m_SSAOProgram->Compile(); + m_SSAOProgram->Link(); + + m_SSAOViewSpaceZProgram = ResourceManager::Load("##SSAOViewSpaceZProgram"); + m_SSAOViewSpaceZProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/SSAO.vert.glsl"))); + m_SSAOViewSpaceZProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/SSAOViewSpaceZ.frag.glsl"))); + m_SSAOViewSpaceZProgram->Compile(); + m_SSAOViewSpaceZProgram->Link(); +} + +void SSAOPass::InitializeTexture() { + GenerateTexture(&m_SSAOTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_R8, GL_RED, GL_FLOAT); + GenerateTexture(&m_SSAOViewSpaceZTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_R32F, GL_RED, GL_FLOAT); +} + +void SSAOPass::InitializeBuffer() +{ + m_SSAOFramBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SSAOTexture, GL_COLOR_ATTACHMENT0))); + m_SSAOFramBuffer.Generate(); + + m_SSAOViewSpaceZFramBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SSAOViewSpaceZTexture, GL_COLOR_ATTACHMENT0))); + m_SSAOViewSpaceZFramBuffer.Generate(); +} + +void SSAOPass::ClearBuffer() +{ + m_SSAOFramBuffer.Bind(); + glClearColor(1.f, 1.f, 1.f, 1.f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + m_SSAOFramBuffer.Unbind(); + + m_SSAOViewSpaceZFramBuffer.Bind(); + glClearColor(1.f, 1.f, 1.f, 1.f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + m_SSAOViewSpaceZFramBuffer.Unbind(); +} + +void SSAOPass::Setting(float radius, float bias, float contrast, float intensityScale, int numOfSamples, int NumOfTurns) { + m_Radius = radius; + m_Bias = bias; + m_Contrast = contrast; + m_IntensityScale = intensityScale; + m_NumOfSamples = numOfSamples; + m_NumOfTurns = NumOfTurns; +} + +void SSAOPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const +{ + glGenTextures(1, texture); + glBindTexture(GL_TEXTURE_2D, *texture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering); + glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, dimensions.x, dimensions.y, 0, format, type, nullptr); + GLERROR("Texture initialization failed"); +} + +void SSAOPass::Draw(GLuint depthBuffer, Camera* camera) +{ + SSAOPassState state; + GLuint viewSpaceZPShaderHandle = m_SSAOViewSpaceZProgram->GetHandle(); + GLuint SSAOShaderHandle = m_SSAOProgram->GetHandle(); + + m_SSAOViewSpaceZFramBuffer.Bind(); + m_SSAOViewSpaceZProgram->Bind(); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, depthBuffer); + glm::vec3 clipInfo = glm::vec3( + (camera->NearClip() * camera->FarClip()), + (camera->NearClip() - camera->FarClip()), + (camera->FarClip()) + ); + /*glm::vec3 clipInfo = glm::vec3( + (camera->NearClip()), + (-1.0f), + (+1.0f) + );*/ + glUniform3fv(glGetUniformLocation(viewSpaceZPShaderHandle, "ClipInfo"), 1, glm::value_ptr(clipInfo)); + + glBindVertexArray(m_ScreenQuad->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); + glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex + 1 + , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); + + glm::vec4 projInfo = glm::vec4( + ((1.0 - camera->ProjectionMatrix()[0][2]) / camera->ProjectionMatrix()[0][0]), + (-2.0 / (m_Renderer->GetViewportSize().Width * camera->ProjectionMatrix()[0][0])), + ((1.0 + camera->ProjectionMatrix()[1][2]) / camera->ProjectionMatrix()[1][1]), + (-2.0 / (m_Renderer->GetViewportSize().Height * camera->ProjectionMatrix()[1][1])) + ); + + + m_SSAOFramBuffer.Bind(); + m_SSAOProgram->Bind(); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, m_SSAOViewSpaceZTexture); + + // How many pixel there are in a 1m long object 1m away from the camera + glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uProjScale"), m_Renderer->GetViewportSize().Height / (-2.0f * glm::tan(camera->FOV() * 0.5f))); + + glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uRadius"), m_Radius); + glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uBias"), m_Bias); + glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uContrast"), m_Contrast); + glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uIntensityScale"), m_IntensityScale); + glUniform1i(glGetUniformLocation(SSAOShaderHandle, "uNumOfSamples"), m_NumOfSamples); + glUniform1i(glGetUniformLocation(SSAOShaderHandle, "uNumOfTurns"), m_NumOfTurns);; + + glUniform4fv(glGetUniformLocation(SSAOShaderHandle, "uProjInfo"), 1, glm::value_ptr(projInfo)); + glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex + 1 + , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); + + m_DrawBloomPass->ClearBuffer(); + m_DrawBloomPass->Draw(m_SSAOTexture); +} + +void SSAOPass::OnWindowResize() { + m_DrawBloomPass->OnWindowResize(); + InitializeTexture(); + m_SSAOFramBuffer.Generate(); + m_SSAOViewSpaceZFramBuffer.Generate(); +} \ No newline at end of file diff --git a/src/Engine/Rendering/SSAOPassState.cpp b/src/Engine/Rendering/SSAOPassState.cpp new file mode 100644 index 00000000..7dd49841 --- /dev/null +++ b/src/Engine/Rendering/SSAOPassState.cpp @@ -0,0 +1,16 @@ +#include "Rendering/SSAOPassState.h" + + +SSAOPassState::SSAOPassState() +{ + //BindFramebuffer(0); + Disable(GL_BLEND); + Disable(GL_DEPTH_TEST); + Disable(GL_CULL_FACE); +} + +SSAOPassState::~SSAOPassState() +{ + +} + diff --git a/src/Engine/Rendering/ShaderProgram.cpp b/src/Engine/Rendering/ShaderProgram.cpp index 9c26c15c..ae536bc0 100644 --- a/src/Engine/Rendering/ShaderProgram.cpp +++ b/src/Engine/Rendering/ShaderProgram.cpp @@ -98,8 +98,7 @@ void ShaderProgram::AddShader(std::shared_ptr shader) void ShaderProgram::Compile() { - if (m_ShaderProgramHandle == 0) - { + if (m_ShaderProgramHandle == 0) { m_ShaderProgramHandle = glCreateProgram(); } diff --git a/src/Engine/Rendering/Skeleton.cpp b/src/Engine/Rendering/Skeleton.cpp index 851408a4..2957b1b6 100644 --- a/src/Engine/Rendering/Skeleton.cpp +++ b/src/Engine/Rendering/Skeleton.cpp @@ -29,6 +29,8 @@ Skeleton::~Skeleton() } } + + const Skeleton::Animation* Skeleton::GetAnimation(std::string name) { auto it = Animations.find(name); @@ -39,66 +41,649 @@ const Skeleton::Animation* Skeleton::GetAnimation(std::string name) } } -std::vector Skeleton::GetFrameBones(const Animation& animation, double time, bool noRootMotion /*= false*/) +std::vector Skeleton::GetFrameBones(std::vector animations, bool noRootMotion /*= false*/) { - // HACK: Animation wrap-around - while (time < 0) { - time += animation.Duration; - } - while (time > animation.Duration) { - time -= animation.Duration; - } + if (animations.size() <= 0) { + std::vector finalMatrices; + for (auto& b : Bones) { + finalMatrices.push_back(glm::mat4(1));//b.second->OffsetMatrix); + } + return finalMatrices; + } - int currentKeyframeIndex = GetKeyframe(animation, time); + std::map frameBones; + AccumulateBoneTransforms(true, animations, frameBones, RootBone, glm::mat4(1)); - const Animation::Keyframe& currentFrame = animation.Keyframes[currentKeyframeIndex]; - const Animation::Keyframe& nextFrame = animation.Keyframes[(currentKeyframeIndex + 1) % animation.Keyframes.size()]; - double alpha = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); - - //auto animationFrame = Animations[""].Keyframes[frame]; - std::map frameBones; - AccumulateBoneTransforms(noRootMotion, currentFrame, nextFrame, static_cast(alpha), frameBones, RootBone, glm::mat4(1)); - - std::vector finalMatrices; - for (auto &kv : frameBones) { - finalMatrices.push_back(kv.second); - } - return finalMatrices; + std::vector finalMatrices; + for (auto &kv : frameBones) { + finalMatrices.push_back(kv.second); + } + return finalMatrices; } -void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation::Keyframe ¤tFrame, const Animation::Keyframe &nextFrame, float progress, std::map &boneMatrices, const Bone* bone, glm::mat4 parentMatrix) +std::vector Skeleton::GetFrameBones(std::vector animations, AnimationOffset animationOffset, bool noRootMotion /*= false*/) +{ + if (animations.size() <= 0 || animationOffset.animation == nullptr) { + std::vector finalMatrices; + for (auto& b : Bones) { + finalMatrices.push_back(glm::mat4(1));//b.second->OffsetMatrix); + } + return finalMatrices; + } + + + std::map frameBones; + AccumulateBoneTransforms(true, animations, animationOffset, frameBones, RootBone, glm::mat4(1)); + + std::vector finalMatrices; + for (auto &kv : frameBones) { + finalMatrices.push_back(kv.second); + } + return finalMatrices; +} + +void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vector animations, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix) +{ + glm::mat4 boneMatrix; + std::vector JointTransforms; + + for (const AnimationData animationData : animations) { + const Animation* animation = animationData.animation; + const float time = animationData.time; + + JointFrameTransform jointTransform; + jointTransform.Weight = animationData.weight;; + + if (animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) { + std::vector boneKeyFrames = animation->JointAnimations.at(bone->ID); + + Animation::Keyframe currentFrame; + Animation::Keyframe nextFrame; + + if (boneKeyFrames.size() > 1) { // 2+ keyframes for the current bone + for (int index = boneKeyFrames.size()-1; index >= 0; index--) { // find the bone keyframes that surrounds the current frame + if (time >= boneKeyFrames.at(index).Time) { + currentFrame = boneKeyFrames.at(index); + nextFrame = boneKeyFrames.at((index + 1) % boneKeyFrames.size()); + break; + } + } + + float progress; + + if (nextFrame.Index == 0) { + nextFrame = currentFrame; + progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time); + } else { + progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); + + } + + + if (progress > 1.0f || progress < 0.0f) { + progress = glm::clamp(progress, 0.0f, 1.0f); + } + Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; + Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties; + + jointTransform.PositionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; + jointTransform.RotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); + jointTransform.ScaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; + + // Flag for no root motion + if (bone == RootBone && noRootMotion) { + jointTransform.PositionInterp.x = 0; + jointTransform.PositionInterp.z = 0; + } + + JointTransforms.push_back(jointTransform); + + } else { // 1 keyframes for the current bone + currentFrame = boneKeyFrames.at(0); + jointTransform.PositionInterp = currentFrame.BoneProperties.Position; + jointTransform.RotationInterp = currentFrame.BoneProperties.Rotation; + jointTransform.ScaleInterp = currentFrame.BoneProperties.Scale; + JointTransforms.push_back(jointTransform); + + } + } else { // 0 keyframes for the current bone + + } + + } + + if (JointTransforms.size() <= 0) { + if (bone->Parent) { + boneMatrix = parentMatrix * glm::inverse(bone->OffsetMatrix) * bone->Parent->OffsetMatrix; + boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; + } else { + boneMatrix = glm::inverse(bone->OffsetMatrix); + boneMatrices[bone->ID] = parentMatrix; + } + } else if (JointTransforms.size() == 1) { + boneMatrix = parentMatrix *(glm::translate(JointTransforms.at(0).PositionInterp) * glm::toMat4(JointTransforms.at(0).RotationInterp) * glm::scale(JointTransforms.at(0).ScaleInterp)); + boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; + } else { + + glm::vec3 finalPosInterp; + glm::quat finalRotInterp; + glm::vec3 finalScaleInterp; + float totalWeight = 0; + + for (JointFrameTransform jointTransform : JointTransforms) { + totalWeight += jointTransform.Weight; + } + + + for (JointFrameTransform jointTransform : JointTransforms) { + if (jointTransform.Weight == 1.0f) { + finalPosInterp = jointTransform.PositionInterp; + finalRotInterp = jointTransform.RotationInterp; + finalScaleInterp = jointTransform.ScaleInterp; + break; + } else { + finalPosInterp += jointTransform.PositionInterp * (jointTransform.Weight/totalWeight); + finalRotInterp *= glm::slerp(glm::quat(), jointTransform.RotationInterp, (jointTransform.Weight/totalWeight)); + finalScaleInterp += jointTransform.ScaleInterp * (jointTransform.Weight/totalWeight); + } + + } + + boneMatrix = parentMatrix *(glm::translate(finalPosInterp) * glm::toMat4(finalRotInterp) * glm::scale(finalScaleInterp)); + boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; + } + + + + for (auto &child : bone->Children) { + AccumulateBoneTransforms(noRootMotion, animations, boneMatrices, child, boneMatrix); + } +} + +void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vector animations, AnimationOffset animationOffset, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix) { glm::mat4 boneMatrix; - if (currentFrame.BoneProperties.find(bone->ID) != currentFrame.BoneProperties.end() || nextFrame.BoneProperties.find(bone->ID) != nextFrame.BoneProperties.end()) { - Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties.at(bone->ID); - Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties.at(bone->ID); + std::vector JointTransforms; - glm::vec3 positionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; - glm::quat rotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); - glm::vec3 scaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; + for (const AnimationData animationData : animations) { + const Animation* animation = animationData.animation; + const float time = animationData.time; - // Flag for no root motion - if (bone == RootBone && noRootMotion) { - positionInterp.x = 0; - positionInterp.z = 0; - } + JointFrameTransform jointTransform; + jointTransform.Weight = animationData.weight;; + + if (animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) { + std::vector boneKeyFrames = animation->JointAnimations.at(bone->ID); + + Animation::Keyframe currentFrame; + Animation::Keyframe nextFrame; + + if (boneKeyFrames.size() > 1) { // 2+ keyframes for the current bone + for (int index = boneKeyFrames.size()-1; index >= 0; index--) { // find the bone keyframes that surrounds the current frame + if (time >= boneKeyFrames.at(index).Time) { + currentFrame = boneKeyFrames.at(index); + nextFrame = boneKeyFrames.at((index + 1) % boneKeyFrames.size()); + break; + } + } + + float progress; + + if (nextFrame.Index == 0) { + nextFrame = currentFrame; + progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time); + } else { + progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); + + } - boneMatrix = parentMatrix * (glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp)); - boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; - } else { - if (bone->Parent) { - boneMatrix = parentMatrix; // * glm::inverse(bone->OffsetMatrix); + if (progress > 1.0f || progress < 0.0f) { + progress = glm::clamp(progress, 0.0f, 1.0f); + } + Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; + Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties; + + jointTransform.PositionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; + jointTransform.RotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); + jointTransform.ScaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; + + // Flag for no root motion + if (bone == RootBone && noRootMotion) { + jointTransform.PositionInterp.x = 0; + jointTransform.PositionInterp.z = 0; + } + + JointTransforms.push_back(jointTransform); + + } else { // 1 keyframes for the current bone + currentFrame = boneKeyFrames.at(0); + jointTransform.PositionInterp = currentFrame.BoneProperties.Position; + jointTransform.RotationInterp = currentFrame.BoneProperties.Rotation; + jointTransform.ScaleInterp = currentFrame.BoneProperties.Scale; + JointTransforms.push_back(jointTransform); + + } + } else { // 0 keyframes for the current bone + } - boneMatrices[bone->ID] = boneMatrix; // * bone->OffsetMatrix; - } - for (auto &child : bone->Children) { - std::string name = child->Name; - AccumulateBoneTransforms(noRootMotion, currentFrame, nextFrame, progress, boneMatrices, child, boneMatrix); - } + } + + glm::mat4 offset = GetOffsetTransform(bone, animationOffset); + + if (JointTransforms.size() == 0) { + if (bone->Parent) { + if (offset != glm::mat4(1)) { + boneMatrix = parentMatrix * offset;// *((glm::inverse(bone->OffsetMatrix) * bone->Parent->OffsetMatrix)); + } else { + boneMatrix = parentMatrix *((glm::inverse(bone->OffsetMatrix) * bone->Parent->OffsetMatrix)); + + } + boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; + } else { + boneMatrix = offset * glm::inverse(bone->OffsetMatrix); + boneMatrices[bone->ID] = parentMatrix; + } + } else { + + glm::vec3 finalPosInterp; + glm::quat finalRotInterp; + glm::vec3 finalScaleInterp; + float totalWeight = 0; + + for (JointFrameTransform jointTransform : JointTransforms) { + totalWeight += jointTransform.Weight; + } + + + for (JointFrameTransform jointTransform : JointTransforms) { + if (jointTransform.Weight == 1.0f) { + finalPosInterp = jointTransform.PositionInterp; + finalRotInterp = jointTransform.RotationInterp; + finalScaleInterp = jointTransform.ScaleInterp; + break; + } else { + finalPosInterp += jointTransform.PositionInterp * (jointTransform.Weight/totalWeight); + finalRotInterp *= glm::slerp(glm::quat(), jointTransform.RotationInterp, (jointTransform.Weight/totalWeight)); + finalScaleInterp += jointTransform.ScaleInterp * (jointTransform.Weight/totalWeight); + } + + } + + + + if (offset != glm::mat4(1)) { + boneMatrix = parentMatrix * ((glm::translate(finalPosInterp) * glm::toMat4(finalRotInterp) * glm::scale(finalScaleInterp)) + offset); + } else { + boneMatrix = parentMatrix * (glm::translate(finalPosInterp) * glm::toMat4(finalRotInterp) * glm::scale(finalScaleInterp)); + } + + boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; + } + + for (auto &child : bone->Children) { + AccumulateBoneTransforms(noRootMotion, animations, animationOffset, boneMatrices, child, boneMatrix); + } +} + +glm::mat4 Skeleton::GetOffsetTransform(const Bone* bone, AnimationOffset animationOffset) +{ + const Animation* animation = animationOffset.animation; + float time = animationOffset.time; + + glm::vec3 position = glm::vec3(0); + glm::quat rotation = glm::quat(); + glm::vec3 scale = glm::vec3(1); + + if (animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) { + std::vector boneKeyFrames = animation->JointAnimations.at(bone->ID); + + Animation::Keyframe currentFrame; + Animation::Keyframe nextFrame; + + if (boneKeyFrames.size() > 1) { // 2+ keyframes for the current bone + for (int index = boneKeyFrames.size()-1; index >= 0; index--) { // find the bone keyframes that surrounds the current frame + if (time >= boneKeyFrames.at(index).Time) { + currentFrame = boneKeyFrames.at(index); + nextFrame = boneKeyFrames.at((index + 1) % boneKeyFrames.size()); + break; + } + } + + float progress; + + if (nextFrame.Index == 0) { + nextFrame = currentFrame; + progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time); + } else { + progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); + + } + + progress = glm::clamp(progress, 0.0f, 1.0f); + + Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; + Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties; + + position = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; + rotation = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); + scale = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; + + + } else { // 1 keyframes for the current bone + currentFrame = boneKeyFrames.at(0); + position = currentFrame.BoneProperties.Position; + rotation = currentFrame.BoneProperties.Rotation; + scale = currentFrame.BoneProperties.Scale; + } + } + + return (glm::translate(position) * glm::toMat4(rotation) * glm::scale(scale)); +} + + +glm::mat4 Skeleton::GetBoneTransform(const Bone* bone, const Animation* animation, float time, glm::mat4 childMatrix) +{ + glm::mat4 boneMatrix; + + Animation::Keyframe currentFrame; + Animation::Keyframe nextFrame; + + if (animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) { + std::vector boneKeyFrames = animation->JointAnimations.at(bone->ID); + + if (boneKeyFrames.size() > 1) { // 2+ keyframes for the current bone + for (int index = boneKeyFrames.size()-1; index >= 0; index--) { // find the bone keyframes that surrounds the current frame + if (time >= boneKeyFrames.at(index).Time) { + currentFrame = boneKeyFrames.at(index); + nextFrame = boneKeyFrames.at((index + 1) % boneKeyFrames.size()); + break; + } + } + + float progress; + + if (nextFrame.Index == 0) { + nextFrame = currentFrame; + progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time); + } else { + progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); + } + + if (progress > 1.0f || progress < 0.0f) { + LOG_INFO("Progress %f", progress); + progress = glm::clamp(progress, 0.0f, 1.0f); + } + Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; + Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties; + + glm::vec3 positionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; + glm::quat rotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); + glm::vec3 scaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; + + boneMatrix = (glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp)) * childMatrix; + + } else { // 1 keyframes for the current bone + currentFrame = boneKeyFrames.at(0); + boneMatrix = (glm::translate(currentFrame.BoneProperties.Position) * glm::toMat4(currentFrame.BoneProperties.Rotation) * glm::scale(currentFrame.BoneProperties.Scale)) * childMatrix; + + } + } else { // 0 keyframes for the current bone + if (bone->Parent) { + boneMatrix = bone->Parent->OffsetMatrix * glm::inverse(bone->OffsetMatrix) * childMatrix; + } else { + boneMatrix = glm::inverse(bone->OffsetMatrix) * childMatrix; + } + } + + if (bone->Parent) { + return GetBoneTransform(bone->Parent, animation, time, boneMatrix); + } else { + return boneMatrix; + } +} + + +glm::mat4 Skeleton::GetBoneTransform(bool noRootMotion, const Bone* bone, std::vector animations, AnimationOffset animationOffset, glm::mat4 childMatrix) +{ + glm::mat4 boneMatrix; + + std::vector JointTransforms; + + for (const AnimationData animationData : animations) { + const Animation* animation = animationData.animation; + const float time = animationData.time; + + JointFrameTransform jointTransform; + jointTransform.Weight = animationData.weight;; + + if (animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) { + std::vector boneKeyFrames = animation->JointAnimations.at(bone->ID); + + Animation::Keyframe currentFrame; + Animation::Keyframe nextFrame; + + if (boneKeyFrames.size() > 1) { // 2+ keyframes for the current bone + for (int index = boneKeyFrames.size()-1; index >= 0; index--) { // find the bone keyframes that surrounds the current frame + if (time >= boneKeyFrames.at(index).Time) { + currentFrame = boneKeyFrames.at(index); + nextFrame = boneKeyFrames.at((index + 1) % boneKeyFrames.size()); + break; + } + } + + float progress; + + if (nextFrame.Index == 0) { + nextFrame = currentFrame; + progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time); + } else { + progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); + + } + + + if (progress > 1.0f || progress < 0.0f) { + progress = glm::clamp(progress, 0.0f, 1.0f); + } + Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; + Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties; + + jointTransform.PositionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; + jointTransform.RotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); + jointTransform.ScaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; + + // Flag for no root motion + if (bone == RootBone && noRootMotion) { + jointTransform.PositionInterp.x = 0; + jointTransform.PositionInterp.z = 0; + } + + JointTransforms.push_back(jointTransform); + + } else { // 1 keyframes for the current bone + currentFrame = boneKeyFrames.at(0); + jointTransform.PositionInterp = currentFrame.BoneProperties.Position; + jointTransform.RotationInterp = currentFrame.BoneProperties.Rotation; + jointTransform.ScaleInterp = currentFrame.BoneProperties.Scale; + JointTransforms.push_back(jointTransform); + + } + } else { // 0 keyframes for the current bone + + } + + } + + + glm::mat4 offset = GetOffsetTransform(bone, animationOffset); + + if (JointTransforms.size() == 0) { + if (bone->Parent) { + if (offset != glm::mat4(1)) { + boneMatrix = offset * childMatrix;// *((glm::inverse(bone->OffsetMatrix) * bone->Parent->OffsetMatrix)); + } else { + boneMatrix = ((glm::inverse(bone->OffsetMatrix) * bone->Parent->OffsetMatrix)) * childMatrix; + } + } else { + boneMatrix = offset * glm::inverse(bone->OffsetMatrix); + } + } else { + + glm::vec3 finalPosInterp; + glm::quat finalRotInterp; + glm::vec3 finalScaleInterp; + float totalWeight = 0; + + for (JointFrameTransform jointTransform : JointTransforms) { + totalWeight += jointTransform.Weight; + } + + + for (JointFrameTransform jointTransform : JointTransforms) { + if (jointTransform.Weight == 1.0f) { + finalPosInterp = jointTransform.PositionInterp; + finalRotInterp = jointTransform.RotationInterp; + finalScaleInterp = jointTransform.ScaleInterp; + break; + } else { + finalPosInterp += jointTransform.PositionInterp * (jointTransform.Weight/totalWeight); + finalRotInterp *= glm::slerp(glm::quat(), jointTransform.RotationInterp, (jointTransform.Weight/totalWeight)); + finalScaleInterp += jointTransform.ScaleInterp * (jointTransform.Weight/totalWeight); + } + + } + + if (offset != glm::mat4(1)) { + boneMatrix = ((glm::translate(finalPosInterp) * glm::toMat4(finalRotInterp) * glm::scale(finalScaleInterp)) + offset) * childMatrix; + } else { + boneMatrix = (glm::translate(finalPosInterp) * glm::toMat4(finalRotInterp) * glm::scale(finalScaleInterp)) * childMatrix; + } + } + + if (bone->Parent != nullptr) { + return GetBoneTransform(noRootMotion, bone->Parent, animations, animationOffset, boneMatrix); + } else { + return boneMatrix; + } +} + + +glm::mat4 Skeleton::GetBoneTransform(bool noRootMotion, const Bone* bone, std::vector animations, glm::mat4 childMatrix) +{ + glm::mat4 boneMatrix; + std::vector JointTransforms; + + for (const AnimationData animationData : animations) { + const Animation* animation = animationData.animation; + const float time = animationData.time; + + JointFrameTransform jointTransform; + jointTransform.Weight = animationData.weight;; + + if (animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) { + std::vector boneKeyFrames = animation->JointAnimations.at(bone->ID); + + Animation::Keyframe currentFrame; + Animation::Keyframe nextFrame; + + if (boneKeyFrames.size() > 1) { // 2+ keyframes for the current bone + for (int index = boneKeyFrames.size()-1; index >= 0; index--) { // find the bone keyframes that surrounds the current frame + if (time >= boneKeyFrames.at(index).Time) { + currentFrame = boneKeyFrames.at(index); + nextFrame = boneKeyFrames.at((index + 1) % boneKeyFrames.size()); + break; + } + } + + float progress; + + if (nextFrame.Index == 0) { + nextFrame = currentFrame; + progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time); + } else { + progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); + } + + + if (progress > 1.0f || progress < 0.0f) { + progress = glm::clamp(progress, 0.0f, 1.0f); + } + Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; + Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties; + + jointTransform.PositionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; + jointTransform.RotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); + jointTransform.ScaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; + + // Flag for no root motion + if (bone == RootBone && noRootMotion) { + jointTransform.PositionInterp.x = 0; + jointTransform.PositionInterp.z = 0; + } + + JointTransforms.push_back(jointTransform); + + } else { // 1 keyframes for the current bone + currentFrame = boneKeyFrames.at(0); + jointTransform.PositionInterp = currentFrame.BoneProperties.Position; + jointTransform.RotationInterp = currentFrame.BoneProperties.Rotation; + jointTransform.ScaleInterp = currentFrame.BoneProperties.Scale; + JointTransforms.push_back(jointTransform); + + } + } else { // 0 keyframes for the current bone + + } + + } + + if (JointTransforms.size() <= 0) { + if (bone->Parent) { + boneMatrix = glm::inverse(bone->OffsetMatrix) * bone->Parent->OffsetMatrix * childMatrix; + } else { + boneMatrix = glm::inverse(bone->OffsetMatrix) * childMatrix; + } + } else if (JointTransforms.size() == 1) { + boneMatrix = (glm::translate(JointTransforms.at(0).PositionInterp) * glm::toMat4(JointTransforms.at(0).RotationInterp) * glm::scale(JointTransforms.at(0).ScaleInterp)) * childMatrix; + } else { + + glm::vec3 finalPosInterp; + glm::quat finalRotInterp; + glm::vec3 finalScaleInterp; + float totalWeight = 0; + + for (JointFrameTransform jointTransform : JointTransforms) { + totalWeight += jointTransform.Weight; + } + + + for (JointFrameTransform jointTransform : JointTransforms) { + if (jointTransform.Weight == 1.0f) { + finalPosInterp = jointTransform.PositionInterp; + finalRotInterp = jointTransform.RotationInterp; + finalScaleInterp = jointTransform.ScaleInterp; + break; + } else { + finalPosInterp += jointTransform.PositionInterp * (jointTransform.Weight/totalWeight); + finalRotInterp *= glm::slerp(glm::quat(), jointTransform.RotationInterp, (jointTransform.Weight/totalWeight)); + finalScaleInterp += jointTransform.ScaleInterp * (jointTransform.Weight/totalWeight); + } + } + + boneMatrix = (glm::translate(finalPosInterp) * glm::toMat4(finalRotInterp) * glm::scale(finalScaleInterp)) * childMatrix; + } + + + + if (bone->Parent != nullptr) { + return GetBoneTransform(noRootMotion, bone->Parent, animations, boneMatrix); + } else { + return boneMatrix; + } } int Skeleton::GetBoneID(std::string name) @@ -134,11 +719,13 @@ void Skeleton::PrintSkeleton(const Bone* bone, int depthCount) int Skeleton::GetKeyframe(const Animation& animation, double time) { + +/* if (time < 0) { time = 0; } if (time >= animation.Duration) { - return animation.Keyframes.size() - 1; + return animation..size() - 1; } for (int keyframe = 0; keyframe < animation.Keyframes.size(); ++keyframe) { @@ -146,6 +733,8 @@ int Skeleton::GetKeyframe(const Animation& animation, double time) return (keyframe - 1) % animation.Keyframes.size(); } } +*/ + return 0; } diff --git a/src/Engine/Rendering/TextPass.cpp b/src/Engine/Rendering/TextPass.cpp index 1e3d5941..9583fcfd 100644 --- a/src/Engine/Rendering/TextPass.cpp +++ b/src/Engine/Rendering/TextPass.cpp @@ -35,7 +35,7 @@ void TextPass::Draw(RenderScene& scene, FrameBuffer& frameBuffer) { GLERROR("Derp1"); TextPassState* state = new TextPassState(frameBuffer.GetHandle()); - for (auto &job : scene.TextJobs) { + for (auto &job : scene.Jobs.Text) { auto textJob = std::dynamic_pointer_cast(job); if (textJob) { diff --git a/src/Engine/Rendering/Texture.cpp b/src/Engine/Rendering/Texture.cpp index 57f3ca36..03347044 100644 --- a/src/Engine/Rendering/Texture.cpp +++ b/src/Engine/Rendering/Texture.cpp @@ -2,21 +2,26 @@ Texture::Texture(std::string path) { - PNG image(path); + PNG* img = ResourceManager::Load(path); //TODO: Make this threaded. Catch exeptions in all other load places. - if (image.Width == 0 && image.Height == 0 || image.Format == Image::ImageFormat::Unknown) { - image = PNG("Textures/Core/ErrorTexture.png"); - if (image.Width == 0 && image.Height == 0 || image.Format == Image::ImageFormat::Unknown) { - LOG_ERROR("Couldn't even load the error texture. This is a dark day indeed."); - return; - } - } + //PNG image(path); - this->Width = image.Width; - this->Height = image.Height; + //if (img->Width == 0 && img->Height == 0 || img->Format == Image::ImageFormat::Unknown) { + // //image = PNG("Textures/Core/ErrorTexture.png"); + // //return; // Temporary fix to remove crash + + // if (img->Width == 0 && img->Height == 0 || img->Format == Image::ImageFormat::Unknown) { + // LOG_ERROR("Couldn't even load the error texture. This is a dark day indeed."); + // return; + // } + //} + + this->Width = img->Width; + this->Height = img->Height; + this->Data = img->Data; GLint format; - switch (image.Format) { + switch (img->Format) { case Image::ImageFormat::RGB: format = GL_RGB; break; @@ -24,15 +29,17 @@ Texture::Texture(std::string path) format = GL_RGBA; break; } + // Construct the OpenGL texture glGenTextures(1, &m_Texture); glBindTexture(GL_TEXTURE_2D, m_Texture); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - glTexImage2D(GL_TEXTURE_2D, 0, format, image.Width, image.Height, 0, format, GL_UNSIGNED_BYTE, image.Data); + glTexImage2D(GL_TEXTURE_2D, 0, format, img->Width, img->Height, 0, format, GL_UNSIGNED_BYTE, img->Data); + glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); GLERROR("Texture load"); } diff --git a/src/Engine/Rendering/Util/CommonFunctions.cpp b/src/Engine/Rendering/Util/CommonFunctions.cpp index 3c81de66..382cb790 100644 --- a/src/Engine/Rendering/Util/CommonFunctions.cpp +++ b/src/Engine/Rendering/Util/CommonFunctions.cpp @@ -1,2 +1,19 @@ #include "Rendering/Util/CommonFunctions.h" +Texture* CommonFunctions::LoadTexture(std::string path, bool threaded) +{ + Texture* img; + try { + if(threaded) { + img = ResourceManager::Load(path); + } else { + img = ResourceManager::Load(path); + } + } catch (const Resource::StillLoadingException&) { + img = ResourceManager::Load("Textures/Core/ErrorTexture.png"); + } catch (const std::exception&) { + img = nullptr; + } + + return img; +} diff --git a/src/Engine/Sound/SoundManager.cpp b/src/Engine/Sound/SoundManager.cpp new file mode 100644 index 00000000..8e103d5c --- /dev/null +++ b/src/Engine/Sound/SoundManager.cpp @@ -0,0 +1,374 @@ +#include "Sound/SoundManager.h" + +SoundManager::SoundManager(World* world, EventBroker* eventBroker) +{ + ConfigFile* config = ResourceManager::Load("Config.ini"); + m_EventBroker = eventBroker; + m_World = world; + m_BGMVolumeChannel = config->Get("Sound.BGMVolume", 1.f); + m_SFXVolumeChannel = config->Get("Sound.SFXVolume", 1.f); + + initOpenAL(); + alSpeedOfSound(340.29f); + alDistanceModel(AL_LINEAR_DISTANCE); + alDopplerFactor(1); + + EVENT_SUBSCRIBE_MEMBER(m_EPlaySoundOnEntity, &SoundManager::OnPlaySoundOnEntity); + EVENT_SUBSCRIBE_MEMBER(m_EPlaySoundOnPosition, &SoundManager::OnPlaySoundOnPosition); + EVENT_SUBSCRIBE_MEMBER(m_EPlayBackgroundMusic, &SoundManager::OnPlayBackgroundMusic); + EVENT_SUBSCRIBE_MEMBER(m_EStopSound, &SoundManager::OnStopSound); + EVENT_SUBSCRIBE_MEMBER(m_EPauseSound, &SoundManager::OnPauseSound); + EVENT_SUBSCRIBE_MEMBER(m_EContinueSound, &SoundManager::OnContinueSound); + EVENT_SUBSCRIBE_MEMBER(m_ESetBGMGain, &SoundManager::OnSetBGMGain); + EVENT_SUBSCRIBE_MEMBER(m_ESetSFXGain, &SoundManager::OnSetSFXGain); + EVENT_SUBSCRIBE_MEMBER(m_EPause, &SoundManager::OnPause); + EVENT_SUBSCRIBE_MEMBER(m_EResume, &SoundManager::OnResume); + EVENT_SUBSCRIBE_MEMBER(m_EComponentAttached, &SoundManager::OnComponentAttached); + EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &SoundManager::OnPlayerSpawned); + EVENT_SUBSCRIBE_MEMBER(m_EPlayQueueOnEntity, &SoundManager::OnPlayQueueOnEntity); +} + +SoundManager::~SoundManager() +{ + stopEmitters(); // Stopps emitters + deleteInactiveEmitters(); // Deletes stopped emitters + // Delete entities + std::unordered_map::iterator it; + for (it = m_Sources.begin(); it != m_Sources.end(); it++) { + m_World->DeleteEntity((*it).first); + } + m_Sources.clear(); + + alcDestroyContext(m_ALCcontext); + alcCloseDevice(m_ALCdevice); +} + +void SoundManager::stopEmitters() +{ + std::unordered_map::iterator it; + for (it = m_Sources.begin(); it != m_Sources.end(); it++) { + if (getSourceState(it->second->ALsource) == AL_PLAYING) { + stopSound(it->second); + } + } +} + +void SoundManager::Update(double dt) +{ + m_EventBroker->Process(); + deleteInactiveEmitters(); // can be optimized with "EEntityDeleted" + updateEmitters(dt); + updateListener(dt); + + // Editor debug info + ImGui::SliderFloat("BGM", &m_BGMVolumeChannel, 0.0f, 1.0f, "%.3f", 1.0f); + ImGui::SliderFloat("SFX", &m_SFXVolumeChannel, 0.0f, 1.0f, "%.3f", 1.0f); +} + +void SoundManager::deleteInactiveEmitters() +{ + std::unordered_map::iterator it; + for (it = m_Sources.begin(); it != m_Sources.end();) { + if (m_World->ValidEntity(it->first) + && m_World->HasComponent(it->first, "SoundEmitter")) { + if (getSourceState(it->second->ALsource) != AL_STOPPED) { + // Nothing to see here, move along + it++; + continue; + } else { + // Sound has been stopped / finished playing. + alDeleteBuffers(1, &it->second->ALsource); + alDeleteSources(1, &it->second->ALsource); + m_World->DeleteEntity(it->first); + delete it->second; + it = m_Sources.erase(it); + } + } else { + // Entity / Component has been removed + stopSound(it->second); + alDeleteBuffers(1, &it->second->ALsource); + alDeleteSources(1, &it->second->ALsource); + delete it->second; + it = m_Sources.erase(it); + } + } +} + +void SoundManager::updateEmitters(double dt) +{ + std::unordered_map::iterator it; + for (it = m_Sources.begin(); it != m_Sources.end(); it++) { + // Get previous pos + if (!m_World->ValidEntity(it->first)) { + return; + } + if (!m_World->HasComponent(it->first, "SoundEmitter")) + return; + + glm::vec3 previousPos; + alGetSource3f(it->second->ALsource, AL_POSITION, &previousPos.x, &previousPos.y, &previousPos.z); + // Get next pos + if (!m_World->HasComponent(it->first, "Transform")) + return; + if (!m_World->ValidEntity(m_World->GetParent(it->first))) { + return; + } + glm::vec3 nextPos = Transform::AbsolutePosition(m_World, it->first); + // Calculate velocity + glm::vec3 velocity = glm::vec3(nextPos - previousPos) / (float)dt; + setSourcePos(it->second->ALsource, nextPos); + setSourceVel(it->second->ALsource, velocity); + + auto emitter = m_World->GetComponent(it->first, "SoundEmitter"); + setSoundProperties(it->second, &emitter); + + // Path changed + if (it->second->SoundResource->Path() != (std::string)emitter["FilePath"]) { + it->second->SoundResource = ResourceManager::Load((std::string)emitter["FilePath"]); + if (it->second->SoundResource->Buffer() != 0) { + playSound(it->second); + } + } + } +} + +void SoundManager::updateListener(double dt) +{ + // Should only be one listener. + auto listenerComponents = m_World->GetComponents("Listener"); + if (listenerComponents == nullptr || !m_LocalPlayer.Valid()) { + return; + } + for (auto it = listenerComponents->begin(); it != listenerComponents->end(); it++) { + EntityWrapper listener(m_World, (*it).EntityID); + if (!listener.Valid()) { + break; + } + if (listener.IsChildOf(m_LocalPlayer) || listener == m_LocalPlayer) { + glm::vec3 previousPos; + alGetListener3f(AL_POSITION, &previousPos.x, &previousPos.y, &previousPos.z); // Get previous pos + glm::vec3 nextPos = Transform::AbsolutePosition(listener); // Get next (current) pos + glm::vec3 velocity = glm::vec3(nextPos - previousPos) / (float)dt; // Calculate velocity + setListenerPos(nextPos); + setListenerVel(velocity); + setListenerOri(glm::eulerAngles(Transform::AbsoluteOrientation(listener))); + break; + } + } +} + +Source* SoundManager::createSource(std::string filePath) +{ + ALuint alSource; + alGenSources((ALuint)1, &alSource); + alSourcef(alSource, AL_REFERENCE_DISTANCE, 1.0); + alSourcef(alSource, AL_MAX_DISTANCE, FLT_MAX); + Source* source = new Source(); + source->ALsource = alSource; + source->SoundResource = ResourceManager::Load(filePath); + return source; +} + +void SoundManager::playSound(Source* source) +{ + alSourcei(source->ALsource, AL_BUFFER, source->SoundResource->Buffer()); + alSourcePlay(source->ALsource); +} + +void SoundManager::playQueue(QueuedBuffers qb) +{ + for (int i = 0; i < qb.second.size(); i++) { + alSourceQueueBuffers(qb.first, 1, &qb.second[i]); + } + alSourcePlay(qb.first); +} + +void SoundManager::stopSound(Source* source) +{ + alSourceStop(source->ALsource); +} + +bool SoundManager::OnPlaySoundOnEntity(const Events::PlaySoundOnEntity & e) +{ + Source* source = createSource(e.FilePath); + source->Type = SoundType::SFX; + EntityID child = m_World->CreateEntity(e.EmitterID); + m_World->AttachComponent(child, "Transform"); + m_World->AttachComponent(child, "SoundEmitter"); + m_Sources[child] = source; + playSound(source); + return false; +} + +bool SoundManager::OnPlaySoundOnPosition(const Events::PlaySoundOnPosition & e) +{ + Source* source = createSource(e.FilePath); + auto emitterID = m_World->CreateEntity(); + auto transform = m_World->AttachComponent(emitterID, "Transform"); + (glm::vec3&)transform["Position"] = e.Position; + auto emitter = m_World->AttachComponent(emitterID, "SoundEmitter"); + (float&)(double)emitter["Gain"] = e.Gain; + (float&)(double)emitter["Pitch"] = e.Pitch; + (bool&)emitter["Loop"] = e.Loop; + (float&)(double)emitter["MaxDistance"] = e.MaxDistance; + (float&)(double)emitter["RollOffFactor"] = e.RollOffFactor; + (float&)(double)emitter["ReferenceDistance"] = e.ReferenceDistance; + source->Type = SoundType::SFX; + m_Sources[emitterID] = source; + playSound(source); + return true; +} + +bool SoundManager::OnPauseSound(const Events::PauseSound & e) +{ + alSourcePause(m_Sources[e.EmitterID]->ALsource); + return true; +} + +bool SoundManager::OnStopSound(const Events::StopSound & e) +{ + alSourceStop(m_Sources[e.EmitterID]->ALsource); + return true; +} + +bool SoundManager::OnContinueSound(const Events::ContinueSound & e) +{ + alSourcePlay(m_Sources[e.EmitterID]->ALsource); + return true; +} + +bool SoundManager::OnPlayBackgroundMusic(const Events::PlayBackgroundMusic & e) +{ + auto listenerComponents = m_World->GetComponents("Listener"); + for (auto it = listenerComponents->begin(); it != listenerComponents->end(); it++) { + if ((*it).EntityID != m_LocalPlayer.ID) { + break; + } + auto emitterChild = m_World->CreateEntity((*it).EntityID); + auto emitter = m_World->AttachComponent(emitterChild, "SoundEmitter"); + (bool&)emitter["Loop"] = true; + (std::string&)emitter["FilePath"] = e.FilePath; + m_World->AttachComponent(emitterChild, "Transform"); + Source* source = createSource(e.FilePath); + source->Type = SoundType::BGM; + setSoundProperties(source, &emitter); + m_Sources[emitterChild] = source; + playSound(source); + } + return true; +} + +bool SoundManager::OnSetBGMGain(const Events::SetBGMGain & e) +{ + m_BGMVolumeChannel = e.Gain; + return true; +} + +bool SoundManager::OnSetSFXGain(const Events::SetSFXGain & e) +{ + m_SFXVolumeChannel = e.Gain; + return true; +} + +bool SoundManager::OnComponentAttached(const Events::ComponentAttached & e) +{ + if (e.Component.Info.Name == "SoundEmitter") { + auto component = m_World->GetComponent(e.Entity.ID, "SoundEmitter"); + Source* source = createSource(component["FilePath"]); + m_Sources[e.Entity.ID] = source; + } + return false; +} + +bool SoundManager::OnPause(const Events::Pause & e) +{ + for (auto it = m_Sources.begin(); it != m_Sources.end(); it++) { + alSourcePause(it->second->ALsource); + } + return false; +} + +bool SoundManager::OnResume(const Events::Resume &e) +{ + for (auto it = m_Sources.begin(); it != m_Sources.end(); it++) { + alSourcePlay(it->second->ALsource); + } + return false; +} + + +bool SoundManager::OnPlayerSpawned(const Events::PlayerSpawned &e) +{ + if (e.PlayerID == -1) { // Local player + m_LocalPlayer = e.Player; + return true; + } + return false; +} + + +bool SoundManager::OnPlayQueueOnEntity(const Events::PlayQueueOnEntity &e) +{ + Source* source = createSource(*e.FilePaths.begin()); + std::vector buffers; + buffers.push_back(source->SoundResource->Buffer()); + source->Type = SoundType::BGM; + std::vector::const_iterator it; + for (it = e.FilePaths.begin() + 1; it != e.FilePaths.end(); it++) { + buffers.push_back(ResourceManager::Load(*it)->Buffer()); + } + playQueue(QueuedBuffers(source->ALsource, buffers)); + return true; +} + +ALenum SoundManager::getSourceState(ALuint source) +{ + ALenum state; + alGetSourcei(source, AL_SOURCE_STATE, &state); + return state; +} + +void SoundManager::setGain(Source * source, float gain) +{ + alSourcef(source->ALsource, AL_GAIN, gain); +} + +void SoundManager::setSoundProperties(Source* source, ComponentWrapper* soundComponent) +{ + float gain = (source->Type == SoundType::SFX) ? m_SFXVolumeChannel : m_BGMVolumeChannel; + alSourcef(source->ALsource, AL_GAIN, (float)(double)(*soundComponent)["Gain"] * gain); + alSourcef(source->ALsource, AL_PITCH, (float)(double)(*soundComponent)["Pitch"]); + alSourcei(source->ALsource, AL_LOOPING, (int)(bool)(*soundComponent)["Loop"]); // YOLO + alSourcef(source->ALsource, AL_MAX_DISTANCE, (float)(double)(*soundComponent)["MaxDistance"]); + alSourcef(source->ALsource, AL_ROLLOFF_FACTOR, (float)(double)(*soundComponent)["RollOffFactor"]); + alSourcef(source->ALsource, AL_REFERENCE_DISTANCE, (float)(double)(*soundComponent)["ReferenceDistance"]); +} + +void SoundManager::initOpenAL() +{ + // Initialize OpenAL + m_ALCdevice = alcOpenDevice(nullptr); + if (m_ALCdevice != nullptr) { + m_ALCcontext = alcCreateContext(m_ALCdevice, nullptr); + alcMakeContextCurrent(m_ALCcontext); + } else { + LOG_ERROR("OpenAL failed to initialize."); + } +} + +void SoundManager::setListenerOri(glm::vec3 ori) +{ + // Calculate forward and up vector. + glm::vec3 forward = glm::vec3(0.0, 0.0, -1.0); + forward = glm::rotateX(forward, ori.x); + forward = glm::rotateY(forward, ori.y); + forward = glm::rotateZ(forward, ori.z); + glm::normalize(forward); + glm::vec3 up = glm::vec3(0.0, 1.0, 0.0); + up = glm::rotateX(up, ori.x); + up = glm::rotateY(up, ori.y); + up = glm::rotateZ(up, ori.z); + glm::normalize(up); + ALfloat lOri[6] = { forward.x, forward.y, forward.z, up.x, up.y, up.z }; + alListenerfv(AL_ORIENTATION, lOri); +} \ No newline at end of file diff --git a/src/Engine/Sound/SoundSystem.cpp b/src/Engine/Sound/SoundSystem.cpp deleted file mode 100644 index cd83d9c6..00000000 --- a/src/Engine/Sound/SoundSystem.cpp +++ /dev/null @@ -1,308 +0,0 @@ -#include "Sound/SoundSystem.h" - -SoundSystem::SoundSystem(World* world, EventBroker* eventBroker, bool editorMode) -{ - m_EventBroker = eventBroker; - m_World = world; - m_EditorEnabled = editorMode; - - initOpenAL(); - - alSpeedOfSound(340.29f); - alDistanceModel(AL_LINEAR_DISTANCE); - alDopplerFactor(1); - - EVENT_SUBSCRIBE_MEMBER(m_EPlaySoundOnEntity, &SoundSystem::OnPlaySoundOnEntity); - EVENT_SUBSCRIBE_MEMBER(m_EPlaySoundOnPosition, &SoundSystem::OnPlaySoundOnPosition); - EVENT_SUBSCRIBE_MEMBER(m_EPlayBackgroundMusic, &SoundSystem::OnPlayBackgroundMusic); - EVENT_SUBSCRIBE_MEMBER(m_EStopSound, &SoundSystem::OnStopSound); - EVENT_SUBSCRIBE_MEMBER(m_EPauseSound, &SoundSystem::OnPauseSound); - EVENT_SUBSCRIBE_MEMBER(m_EContinueSound, &SoundSystem::OnContinueSound); - EVENT_SUBSCRIBE_MEMBER(m_ESetBGMGain, &SoundSystem::OnSetBGMGain); - EVENT_SUBSCRIBE_MEMBER(m_ESetSFXGain, &SoundSystem::OnSetSFXGain); -} - -SoundSystem::~SoundSystem() -{ - stopEmitters(); // Stopps emitters - deleteInactiveEmitters(); // Deletes stopped emitters - // Delete entities - std::unordered_map::iterator it; - for (it = m_Sources.begin(); it != m_Sources.end(); it++) { - m_World->DeleteEntity((*it).first); - } - m_Sources.clear(); - - alcDestroyContext(m_ALCcontext); - alcCloseDevice(m_ALCdevice); -} - -void SoundSystem::stopEmitters() -{ - std::unordered_map::iterator it; - for (it = m_Sources.begin(); it != m_Sources.end(); it++) { - if (getSourceState(it->second->ALsource) == AL_PLAYING) { - stopSound(it->second); - } - } -} - -void SoundSystem::Update(double dt) -{ - m_EventBroker->Process(); - addNewEmitters(dt); // can be optimized with "EEntityCreated" - deleteInactiveEmitters(); // can be optimized with "EEntityDeleted" - updateEmitters( dt); - updateListener( dt); -} - -void SoundSystem::deleteInactiveEmitters() -{ - std::unordered_map::iterator it; - for (it = m_Sources.begin(); it != m_Sources.end();) { - if (m_World->ValidEntity(it->first) - && m_World->HasComponent(it->first, "SoundEmitter")) { - if (getSourceState(it->second->ALsource) != AL_STOPPED) { - // Nothing to see here, move along - it++; - continue; - } else { - // Sound has been stopped / finished playing. - alDeleteBuffers(1, &it->second->ALsource); - alDeleteSources(1, &it->second->ALsource); - m_World->DeleteEntity(it->first); - delete it->second; - it = m_Sources.erase(it); - } - } else { - // Entity / Component has been removed - stopSound((*it).second); - alDeleteBuffers(1, &it->second->ALsource); - alDeleteSources(1, &it->second->ALsource); - delete it->second; - it = m_Sources.erase(it); - } - } -} - -void SoundSystem::addNewEmitters(double dt) -{ - auto emitterComponents = m_World->GetComponents("SoundEmitter"); - if (emitterComponents == nullptr) { - return; - } - for (auto it = emitterComponents->begin(); it != emitterComponents->end(); it++) { - EntityID emitter = (*it).EntityID; - std::unordered_map::iterator source; - source = m_Sources.find(emitter); - if (source == m_Sources.end()) { // Did not exist, add it - Source* source = createSource((std::string)(*it)["FilePath"]); - m_Sources[emitter] = source; - } - } -} - -void SoundSystem::updateEmitters(double dt) -{ - std::unordered_map::iterator it; - for (it = m_Sources.begin(); it != m_Sources.end(); it++) { - // Get previous pos - glm::vec3 previousPos; - alGetSource3f(it->second->ALsource, AL_POSITION, &previousPos.x, &previousPos.y, &previousPos.z); - // Get next pos - glm::vec3 nextPos = Transform::AbsolutePosition(m_World, it->first); - // Calculate velocity - glm::vec3 velocity = glm::vec3(nextPos - previousPos) / (float)dt; - setSourcePos(it->second->ALsource, nextPos); - setSourceVel(it->second->ALsource, velocity); - float gain; - if (it->second->Type == SoundType::SFX) { - gain = m_SFXVolumeChannel; - } else if (it->second->Type == SoundType::BGM) { - gain = m_BGMVolumeChannel; - } - auto emitter = m_World->GetComponent(it->first, "SoundEmitter"); - setSoundProperties(it->second->ALsource, &emitter); - - // To make an emitter play when spawned in editor mode - if (m_EditorEnabled) { - // Path changed - if (it->second->SoundResource->Path() != (std::string)emitter["FilePath"]) { - it->second->SoundResource = ResourceManager::Load((std::string)emitter["FilePath"]); - if (it->second->SoundResource->Buffer() != 0) { - playSound(it->second); - } - } - } - } -} - -void SoundSystem::updateListener(double dt) -{ - // Should only be one listener. - auto listenerComponents = m_World->GetComponents("Listener"); - if (listenerComponents == nullptr) { - return; - } - for (auto it = listenerComponents->begin(); it != listenerComponents->end(); it++) { - EntityID listener = (*it).EntityID; - glm::vec3 previousPos; - alGetListener3f(AL_POSITION, &previousPos.x, &previousPos.y, &previousPos.z); // Get previous pos - glm::vec3 nextPos = Transform::AbsolutePosition(m_World, listener); // Get next (current) pos - glm::vec3 velocity = glm::vec3(nextPos - previousPos) / (float)dt; // Calculate velocity - setListenerPos(nextPos); - setListenerVel(velocity); - setListenerOri(glm::eulerAngles(Transform::AbsoluteOrientation(m_World, listener))); - } -} - -Source* SoundSystem::createSource(std::string filePath) -{ - ALuint alSource; - alGenSources((ALuint)1, &alSource); - alSourcef(alSource, AL_REFERENCE_DISTANCE, 1.0); - alSourcef(alSource, AL_MAX_DISTANCE, FLT_MAX); - Source* source = new Source(); - source->ALsource = alSource; - source->SoundResource = ResourceManager::Load(filePath); - return source; -} - -void SoundSystem::playSound(Source* source) -{ - alSourcei(source->ALsource, AL_BUFFER, source->SoundResource->Buffer()); - alSourcePlay(source->ALsource); -} - -void SoundSystem::stopSound(Source* source) -{ - alSourceStop(source->ALsource); -} - -bool SoundSystem::OnPlaySoundOnEntity(const Events::PlaySoundOnEntity & e) -{ - Source* source = createSource(e.FilePath); - source->Type = SoundType::SFX; - m_Sources[e.EmitterID] = source; - playSound(source); - return false; -} - -bool SoundSystem::OnPlaySoundOnPosition(const Events::PlaySoundOnPosition & e) -{ - Source* source = createSource(e.FilePath); - auto emitterID = m_World->CreateEntity(); - auto transform = m_World->AttachComponent(emitterID, "Transform"); - (glm::vec3&)transform["Position"] = e.Position; - auto emitter = m_World->AttachComponent(emitterID, "SoundEmitter"); - (float&)(double)emitter["Gain"] = e.Gain; - (float&)(double)emitter["Pitch"] = e.Pitch; - (bool&)emitter["Loop"] = e.Loop; - (float&)(double)emitter["MaxDistance"] = e.MaxDistance; - (float&)(double)emitter["RollOffFactor"] = e.RollOffFactor; - (float&)(double)emitter["ReferenceDistance"] = e.ReferenceDistance; - auto model = m_World->AttachComponent(emitterID, "Model"); - (std::string&)model["Resource"] = "Models/Core/UnitCube.mesh"; // 360NoScope UnitCube - source->Type = SoundType::SFX; - m_Sources[emitterID] = source; - playSound(source); - return true; -} - -bool SoundSystem::OnPauseSound(const Events::PauseSound & e) -{ - alSourcePause(m_Sources[e.EmitterID]->ALsource); - return true; -} - -bool SoundSystem::OnStopSound(const Events::StopSound & e) -{ - alSourceStop(m_Sources[e.EmitterID]->ALsource); - return true; -} - -bool SoundSystem::OnContinueSound(const Events::ContinueSound & e) -{ - alSourcePlay(m_Sources[e.EmitterID]->ALsource); - return true; -} - -bool SoundSystem::OnPlayBackgroundMusic(const Events::PlayBackgroundMusic & e) -{ - auto listenerComponents = m_World->GetComponents("Listener"); - for (auto it = listenerComponents->begin(); it != listenerComponents->end(); it++) { - auto emitterChild = m_World->CreateEntity((*it).EntityID); - auto emitter = m_World->AttachComponent(emitterChild, "SoundEmitter"); - (bool&)emitter["Loop"] = true; - (std::string&)emitter["FilePath"] = e.FilePath; - m_World->AttachComponent(emitterChild, "Transform"); - Source* source = createSource(e.FilePath); - source->Type = SoundType::BGM; - m_Sources[emitterChild] = source; - playSound(source); - } - return true; -} - -bool SoundSystem::OnSetBGMGain(const Events::SetBGMGain & e) -{ - m_BGMVolumeChannel = e.Gain; - return true; -} - -bool SoundSystem::OnSetSFXGain(const Events::SetSFXGain & e) -{ - m_SFXVolumeChannel = e.Gain; - return true; -} - -void SoundSystem::setListenerOri(glm::vec3 ori) -{ - // Calculate forward and up vector. - glm::vec3 forward = glm::vec3(0.0, 0.0, -1.0); - forward = glm::rotateX(forward, ori.x); - forward = glm::rotateY(forward, ori.y); - forward = glm::rotateZ(forward, ori.z); - glm::normalize(forward); - glm::vec3 up = glm::vec3(0.0, 1.0, 0.0); - up = glm::rotateX(up, ori.x); - up = glm::rotateY(up, ori.y); - up = glm::rotateZ(up, ori.z); - glm::normalize(up); - ALfloat lOri[6] = { forward.x, forward.y, forward.z, up.x, up.y, up.z }; - alListenerfv(AL_ORIENTATION, lOri); -} - -ALenum SoundSystem::getSourceState(ALuint source) -{ - ALenum state; - alGetSourcei(source, AL_SOURCE_STATE, &state); - return state; -} - -void SoundSystem::setGain(Source * source, float gain) -{ - alSourcef(source->ALsource, AL_GAIN, gain); -} - -void SoundSystem::setSoundProperties(ALuint source, ComponentWrapper* soundComponent) -{ - alSourcef(source, AL_GAIN, (float)(double)(*soundComponent)["Gain"]); - alSourcef(source, AL_PITCH, (float)(double)(*soundComponent)["Pitch"]); - alSourcei(source, AL_LOOPING, (int)(bool)(*soundComponent)["Loop"]); // YOLO - alSourcef(source, AL_MAX_DISTANCE, (float)(double)(*soundComponent)["MaxDistance"]); - alSourcef(source, AL_ROLLOFF_FACTOR, (float)(double)(*soundComponent)["RollOffFactor"]); - alSourcef(source, AL_REFERENCE_DISTANCE, (float)(double)(*soundComponent)["ReferenceDistance"]); -} - -void SoundSystem::initOpenAL() -{ - // Initialize OpenAL - m_ALCdevice = alcOpenDevice(nullptr); - if (m_ALCdevice != nullptr) { - m_ALCcontext = alcCreateContext(m_ALCdevice, nullptr); - alcMakeContextCurrent(m_ALCcontext); - } else { - LOG_ERROR("OpenAL failed to initialize."); - } -} \ No newline at end of file diff --git a/src/Game/CMakeLists.txt b/src/Game/CMakeLists.txt index 157af23c..d8ba8599 100644 --- a/src/Game/CMakeLists.txt +++ b/src/Game/CMakeLists.txt @@ -1,6 +1,6 @@ project(TacticalZ-Game) -find_package(Boost REQUIRED COMPONENTS system filesystem thread chrono) +find_package(Boost REQUIRED COMPONENTS system filesystem thread chrono program_options) set(INCLUDE_PATH ${CMAKE_SOURCE_DIR}/include/Game) include_directories( @@ -16,19 +16,31 @@ file(GLOB SOURCE_FILES_Systems ) source_group(Systems FILES ${SOURCE_FILES_Systems}) +file(GLOB SOURCE_FILES_Systems_Weapon + "${INCLUDE_PATH}/Systems/Weapon/*.h" + "Systems/Weapon/*.cpp" +) +source_group(Systems\\Weapon FILES ${SOURCE_FILES_Systems_Weapon}) + file(GLOB SOURCE_FILES_Events "${INCLUDE_PATH}/Events/*.h" "Events/*.cpp" ) source_group(Events FILES ${SOURCE_FILES_Events}) +file(GLOB SOURCE_FILES_Network + "${INCLUDE_PATH}/Network/*.h" + "Network/*.cpp" +) +source_group(Network FILES ${SOURCE_FILES_Network}) set(SOURCE_FILES ${SOURCE_FILES} "Game.cpp" + "MiniDump.cpp" ${SOURCE_FILES_Systems} + ${SOURCE_FILES_Systems_Weapon} ${SOURCE_FILES_Events} - - + ${SOURCE_FILES_Network} ) set(LIBRARIES diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index f5afcaeb..24b7cd1e 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -1,5 +1,6 @@ #include "Game.h" -#include "Collision/CollidableOctreeSystem.h" +#include "Collision/FillOctreeSystem.h" +#include "Collision/FillFrustumOctreeSystem.h" #include "Collision/EntityAABB.h" #include "Collision/TriggerSystem.h" #include "Collision/CollisionSystem.h" @@ -8,20 +9,37 @@ #include "Systems/PlayerMovementSystem.h" #include "Systems/SpawnerSystem.h" #include "Systems/PlayerSpawnSystem.h" +#include "Systems/PlayerDeathSystem.h" #include "Core/EntityFileWriter.h" #include "Game/Systems/CapturePointSystem.h" -#include "Game/Systems/WeaponSystem.h" -#include "Game/Systems/PlayerHUD.h" +#include "Game/Systems/CapturePointHUDSystem.h" +#include "Game/Systems/PickupSpawnSystem.h" +#include "Game/Systems/AmmoPickupSystem.h" +#include "Game/Systems/DamageIndicatorSystem.h" +#include "Game/Systems/Weapon/WeaponSystem.h" +#include "Rendering/AnimationSystem.h" +#include "Game/Systems/HealthHUDSystem.h" +#include "Rendering/BoneAttachmentSystem.h" #include "Game/Systems/LifetimeSystem.h" -#include "../Engine/Rendering/AnimationSystem.h" +#include "../Engine/Core/UniformScaleSystem.h" +#include "Rendering/AnimationSystem.h" +#include "Network/MultiplayerSnapshotFilter.h" +#include "Game/Systems/AmmunitionHUDSystem.h" +#include "Game/Systems/KillFeedSystem.h" +#include "GUI/ButtonSystem.h" +#include "GUI/MainMenuSystem.h" + Game::Game(int argc, char* argv[]) { + parseArgs(argc, argv); + ResourceManager::RegisterType("ConfigFile"); ResourceManager::RegisterType("Sound"); ResourceManager::RegisterType("Model"); ResourceManager::RegisterType("RawModel"); ResourceManager::RegisterType("Texture"); + ResourceManager::RegisterType("Png"); ResourceManager::RegisterType("ShaderProgram"); ResourceManager::RegisterType("EntityFile"); ResourceManager::RegisterType("FontFile"); @@ -30,6 +48,7 @@ Game::Game(int argc, char* argv[]) ResourceManager::UseThreading = m_Config->Get("Multithreading.ResourceLoading", true); DisableMemoryPool::Value = m_Config->Get("Debug.DisableMemoryPool", false); LOG_LEVEL = static_cast<_LOG_LEVEL>(m_Config->Get("Debug.LogLevel", 1)); + PlayerSpawnSystem::SetRespawnTime(m_Config->Get("Debug.RespawnTime", 15.0f)); // Create the core event broker m_EventBroker = new EventBroker(); @@ -55,11 +74,6 @@ Game::Game(int argc, char* argv[]) m_InputProxy->AddHandler(); m_InputProxy->LoadBindings("Input.ini"); - // Create the root level GUI frame - m_FrameStack = new GUI::Frame(m_EventBroker); - m_FrameStack->Width = m_Renderer->Resolution().Width; - m_FrameStack->Height = m_Renderer->Resolution().Height; - // Create a world m_World = new World(m_EventBroker); std::string mapToLoad = m_Config->Get("Debug.LoadMap", ""); @@ -71,63 +85,88 @@ Game::Game(int argc, char* argv[]) fp.MergeEntities(m_World); } + // Create the sound manager + m_SoundManager = new SoundManager(m_World, m_EventBroker); + + // Initialize network + if (m_Config->Get("Networking.StartNetwork", false)) { + if (m_IsServer) { + m_NetworkServer = new Server(m_World, m_EventBroker, m_NetworkPort); + m_Renderer->SetWindowTitle(m_Renderer->WindowTitle() + " SERVER"); + } else if (m_IsClient) { + m_NetworkClient = new Client(m_World, m_EventBroker, std::make_unique(m_EventBroker)); + m_NetworkClient->Connect(m_NetworkAddress, m_NetworkPort); + m_Renderer->SetWindowTitle(m_Renderer->WindowTitle() + " CLIENT"); + } + } // Create Octrees - m_OctreeCollision = new Octree(AABB(glm::vec3(-100), glm::vec3(100)), 4); - m_OctreeTrigger = new Octree(AABB(glm::vec3(-100), glm::vec3(100)), 4); - m_OctreeFrustrumCulling = new Octree(AABB(glm::vec3(-100), glm::vec3(100)), 4); + // TODO: Perhaps the world bounds should be set in some non-arbitrary way instead of this. + AABB boxContainingTheWorld(glm::vec3(-300), glm::vec3(300)); + m_OctreeCollision = new Octree(boxContainingTheWorld, 4); + m_OctreeTrigger = new Octree(boxContainingTheWorld, 4); + m_OctreeFrustrumCulling = new Octree(boxContainingTheWorld, 4); // Create system pipeline - m_SystemPipeline = new SystemPipeline(m_World, m_EventBroker); + m_SystemPipeline = new SystemPipeline(m_World, m_EventBroker, m_IsClient, m_IsServer); // All systems with orderlevel 0 will be updated first. unsigned int updateOrderLevel = 0; + m_SystemPipeline->AddSystem(updateOrderLevel); + ++updateOrderLevel; + m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); - m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); - m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer); + m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_OctreeCollision); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer); + m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer); // Populate Octree with collidables ++updateOrderLevel; - m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision, "Collidable"); - m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeTrigger, "Player"); - m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision, "Collidable"); + m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeTrigger, "Player"); + m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeFrustrumCulling); m_SystemPipeline->AddSystem(updateOrderLevel); - + m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel); // Collision and TriggerSystem should update after player. ++updateOrderLevel; + m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeTrigger); ++updateOrderLevel; - m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_RenderFrame); + m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_RenderFrame, m_OctreeFrustrumCulling); ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_RenderFrame); - // Invoke network - if (m_Config->Get("Networking.StartNetwork", false)) { - //boost::thread workerThread(&Game::networkFunction, this); - networkFunction(); - } - - // Invoke sound system - m_SoundSystem = new SoundSystem(m_World, m_EventBroker, m_Config->Get("Debug.EditorEnabled", false)); - m_LastTime = glfwGetTime(); } Game::~Game() { delete m_SystemPipeline; - delete m_SoundSystem; delete m_OctreeFrustrumCulling; delete m_OctreeCollision; delete m_OctreeTrigger; + delete m_SoundManager; + if (m_NetworkClient != nullptr) { + delete m_NetworkClient; + } + if (m_NetworkServer != nullptr) { + delete m_NetworkServer; + } delete m_World; - delete m_FrameStack; delete m_InputProxy; delete m_InputManager; delete m_RenderFrame; @@ -146,47 +185,74 @@ void Game::Tick() // Handle input in a weird looking but responsive way m_EventBroker->Process(); m_EventBroker->Swap(); + PerformanceTimer::StartTimer("InputManager"); m_InputManager->Update(dt); m_EventBroker->Swap(); + PerformanceTimer::StartTimerAndStopPrevious("InputProxy"); m_InputProxy->Update(dt); m_EventBroker->Swap(); m_InputProxy->Process(); m_EventBroker->Swap(); + PerformanceTimer::StartTimerAndStopPrevious("SoundManager"); + m_SoundManager->Update(dt); + // Update network - if (m_IsClientOrServer) { - m_ClientOrServer->Update(); + PerformanceTimer::StartTimerAndStopPrevious("Network"); + m_EventBroker->Process(); + if (m_NetworkClient != nullptr) { + m_NetworkClient->Update(); } + if (m_NetworkServer != nullptr) { + m_NetworkServer->Update(); + } + //m_SoundManager->Update(dt); + // Iterate through systems and update world! + PerformanceTimer::StartTimerAndStopPrevious("SystemPipeline"); m_EventBroker->Process(); m_SystemPipeline->Update(dt); - debugTick(dt); + PerformanceTimer::StartTimerAndStopPrevious("RendererUpdate"); m_Renderer->Update(dt); - m_SoundSystem->Update(dt); - GLERROR("Game::Tick m_RenderQueueFactory->Update"); + PerformanceTimer::StartTimerAndStopPrevious("RendererDraw"); m_Renderer->Draw(*m_RenderFrame); + PerformanceTimer::StopTimer("RendererDraw"); m_RenderFrame->Clear(); - GLERROR("Game::Tick m_Renderer->Draw"); m_EventBroker->Swap(); m_EventBroker->Clear(); } -void Game::debugTick(double dt) +int Game::parseArgs(int argc, char* argv[]) { - m_EventBroker->Process(); + namespace po = boost::program_options; + + po::options_description desc("Options"); + desc.add_options() + ("help", "Help") + ("server,s", po::bool_switch(&m_IsServer), "Launch game in server mode") + ("connect", po::value(&m_NetworkAddress)->default_value(""), "Connect to this address in client mode") + ("port,p", po::value(&m_NetworkPort), "Port to listen on or connect to"); + ; + + po::variables_map vm; + try { + po::store(po::parse_command_line(argc, argv, desc), vm); + po::notify(vm); + } catch (std::exception& e) { + LOG_ERROR(e.what()); + return 1; + } + + if (vm.count("help")) { + std::cout << desc << std::endl; + exit(1); + } + + // HACK: Right now, client and server are mutually exclusive + m_IsClient = true; + if (m_IsServer) { + m_IsClient = false; + } + + return 0; } - -void Game::networkFunction() -{ - bool isServer = m_Config->Get("Networking.IsServer", false); - if (!isServer) { - m_IsClientOrServer = true; - m_ClientOrServer = new Client(m_Config); - } - if (isServer) { - m_IsClientOrServer = true; - m_ClientOrServer = new Server(); - } - m_ClientOrServer->Start(m_World, m_EventBroker); - -} \ No newline at end of file diff --git a/src/Game/MiniDump.cpp b/src/Game/MiniDump.cpp new file mode 100644 index 00000000..bd8ee2de --- /dev/null +++ b/src/Game/MiniDump.cpp @@ -0,0 +1,110 @@ +/* + Author: Vladimir Sedach. + + Purpose: demo of Call Stack creation by our own means, + and with MiniDumpWriteDump() function of DbgHelp.dll. +*/ + +#include +#include + +#include +#include +//#include "dbghelp.h" + +//#define DEBUG_DPRINTF 1 //allow d() +//#include "wfun.h" + +#pragma optimize("y", off) //generate stack frame pointers for all functions - same as /Oy- in the project +#pragma warning(disable: 4200) //nonstandard extension used : zero-sized array in struct/union +#pragma warning(disable: 4100) //unreferenced formal parameter + +// In case you don't have dbghelp.h. +#ifndef _DBGHELP_ + +typedef struct _MINIDUMP_EXCEPTION_INFORMATION { + DWORD ThreadId; + PEXCEPTION_POINTERS ExceptionPointers; + BOOL ClientPointers; +} MINIDUMP_EXCEPTION_INFORMATION, *PMINIDUMP_EXCEPTION_INFORMATION; + +typedef enum _MINIDUMP_TYPE { + MiniDumpNormal = 0x00000000, + MiniDumpWithDataSegs = 0x00000001, +} MINIDUMP_TYPE; + +typedef BOOL (WINAPI * MINIDUMP_WRITE_DUMP)( + IN HANDLE hProcess, + IN DWORD ProcessId, + IN HANDLE hFile, + IN MINIDUMP_TYPE DumpType, + IN CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, OPTIONAL + IN PVOID UserStreamParam, OPTIONAL + IN PVOID CallbackParam OPTIONAL + ); + +#else + +typedef BOOL (WINAPI * MINIDUMP_WRITE_DUMP)( + IN HANDLE hProcess, + IN DWORD ProcessId, + IN HANDLE hFile, + IN MINIDUMP_TYPE DumpType, + IN CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, OPTIONAL + IN PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, OPTIONAL + IN PMINIDUMP_CALLBACK_INFORMATION CallbackParam OPTIONAL + ); +#endif //#ifndef _DBGHELP_ + +HMODULE hDbgHelp; +MINIDUMP_WRITE_DUMP MiniDumpWriteDump_; + +// Tool Help functions. +typedef HANDLE (WINAPI * CREATE_TOOL_HELP32_SNAPSHOT)(DWORD dwFlags, DWORD th32ProcessID); + +//************************************************************************************* +void WINAPI Create_Dump(PEXCEPTION_POINTERS pException, BOOL File_Flag, BOOL Show_Flag) +//************************************************************************************* +// Create dump. +// pException can be either GetExceptionInformation() or NULL. +// If File_Flag = TRUE - write dump files (.dmz and .dmp) with the name of the current process. +// If Show_Flag = TRUE - show message with Get_Exception_Info() dump. +{ + // Try to get MiniDumpWriteDump() address. + hDbgHelp = LoadLibrary("DBGHELP.DLL"); + MiniDumpWriteDump_ = (MINIDUMP_WRITE_DUMP)GetProcAddress(hDbgHelp, "MiniDumpWriteDump"); + + // If MiniDumpWriteDump() of DbgHelp.dll available. + if (MiniDumpWriteDump_) + { + HANDLE hDump_File; + CHAR Dump_Path[MAX_PATH]; + + GetModuleFileName(NULL, Dump_Path, sizeof(Dump_Path)); //path of current process + std::time_t t = std::time(NULL); + char tStr[16]; + std::strftime(tStr, 32, " %a %H-%M-%S", std::localtime(&t)); + std::string time(tStr); + std::string path(Dump_Path); + path = path.substr(0, path.length() - 4); + path += time + ".dmp"; + + MINIDUMP_EXCEPTION_INFORMATION M; + M.ThreadId = GetCurrentThreadId(); + M.ExceptionPointers = pException; + M.ClientPointers = 0; + + hDump_File = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + + MiniDumpWriteDump_(GetCurrentProcess(), GetCurrentProcessId(), hDump_File, + MiniDumpNormal, (pException) ? &M : NULL, NULL, NULL); + + CloseHandle(hDump_File); + + std::cout << "Memory dumped to: \"" << path.c_str() << "\""; + MessageBox(NULL, ("Application crashed, memory dumped to: " + path).c_str(), "MiniDump", MB_ICONHAND | MB_OK); + } else { + MessageBox(NULL, "Application crashed, memory dump failed.", "MiniDump", MB_ICONHAND | MB_OK); + } +} + diff --git a/src/Game/Network/MultiplayerSnapshotFilter.cpp b/src/Game/Network/MultiplayerSnapshotFilter.cpp new file mode 100644 index 00000000..69b7f282 --- /dev/null +++ b/src/Game/Network/MultiplayerSnapshotFilter.cpp @@ -0,0 +1,42 @@ +#include "Network/MultiplayerSnapshotFilter.h" + +MultiplayerSnapshotFilter::MultiplayerSnapshotFilter(EventBroker* eventBroker) + : m_EventBroker(eventBroker) +{ + EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &MultiplayerSnapshotFilter::OnPlayerSpawned); +} + +bool MultiplayerSnapshotFilter::FilterComponent(EntityWrapper entity, SharedComponentWrapper& component) +{ + if (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer)) { + if ( + component.Info.Name == "Transform" + || component.Info.Name == "Physics" + || component.Info.Name == "AssaultWeapon" + || component.Info.Name == "Animation" + || component.Info.Name == "AnimationOffset" + || entity.Name() == "PlayerName" + ) { + return false; + } + } + + if (component.Info.Name == "Physics") { + return false; + } + + if (component.Info.Name == "Transform" || component.Info.Name == "Physics") { + m_EventBroker->Publish(Events::Interpolate(entity, component)); + return false; + } + + return true; +} + +bool MultiplayerSnapshotFilter::OnPlayerSpawned(Events::PlayerSpawned ePlayerSpawned) +{ + if (ePlayerSpawned.PlayerID == -1) { + m_LocalPlayer = ePlayerSpawned.Player; + } + return true; +} \ No newline at end of file diff --git a/src/Game/Systems/AmmoPickupSystem.cpp b/src/Game/Systems/AmmoPickupSystem.cpp new file mode 100644 index 00000000..250fa494 --- /dev/null +++ b/src/Game/Systems/AmmoPickupSystem.cpp @@ -0,0 +1,79 @@ +#include "Systems/AmmoPickupSystem.h" + +AmmoPickupSystem::AmmoPickupSystem(SystemParams params) + : System(params) +{ + EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &AmmoPickupSystem::OnTriggerTouch); +} + +void AmmoPickupSystem::Update(double dt) +{ + for (auto it = m_ETriggerTouchVector.begin(); it != m_ETriggerTouchVector.end(); ++it) + { + auto& ammoPickupPosition = *it; + //set the double timer value (value 3) + ammoPickupPosition.DecreaseThisRespawnTimer -= dt; + if (ammoPickupPosition.DecreaseThisRespawnTimer < 0.0) { + //spawn and delete the vector item + auto entityFile = ResourceManager::Load("Schema/Entities/AmmoPickup.xml"); + EntityFileParser parser(entityFile); + EntityID ammoPickupID = parser.MergeEntities(m_World); + + //let the world know a pickup has spawned (graphics effects, etc) + Events::PickupSpawned ePickupSpawned; + ePickupSpawned.Pickup = EntityWrapper(m_World, ammoPickupID); + m_EventBroker->Publish(ePickupSpawned); + + //set values from the old entity to the new entity + auto& newAmmoPickupEntity = EntityWrapper(m_World, ammoPickupID); + newAmmoPickupEntity["Transform"]["Position"] = ammoPickupPosition.Pos; + newAmmoPickupEntity["AmmoPickup"]["AmmoGain"] = ammoPickupPosition.AmmoGain; + newAmmoPickupEntity["AmmoPickup"]["RespawnTimer"] = ammoPickupPosition.RespawnTimer; + m_World->SetParent(newAmmoPickupEntity.ID, ammoPickupPosition.parentID); + + //erase the current element (AmmoPickupPosition) + m_ETriggerTouchVector.erase(it); + break; + } + } +} + + +bool AmmoPickupSystem::OnTriggerTouch(Events::TriggerTouch& e) +{ + if (e.Entity != LocalPlayer) { + return false; + } + //TODO: add other weapontypes + if (!e.Entity.HasComponent("AssaultWeapon")) { + return false; + } + if (!e.Trigger.HasComponent("AmmoPickup")) { + return false; + } + int maxWeaponAmmo = (int)e.Entity["AssaultWeapon"]["MaxAmmo"]; + int& currentAmmo = (int)e.Entity["AssaultWeapon"]["Ammo"]; + + int ammoGiven = 0.01*(double)e.Trigger["AmmoPickup"]["AmmoGain"] * maxWeaponAmmo; + //cant pick up ammopacks if you are already at MaxAmmo + if (currentAmmo >= maxWeaponAmmo) { + return false; + } + + //personEntered = e.Entity, thingEntered = e.Trigger + Events::AmmoPickup ePlayerAmmoPickup; + ePlayerAmmoPickup.AmmoGain = ammoGiven; + ePlayerAmmoPickup.Player = e.Entity; + m_EventBroker->Publish(ePlayerAmmoPickup); + //immediately give the player the ammo + currentAmmo = std::min(currentAmmo + ammoGiven, maxWeaponAmmo); + + //copy position, ammogain, respawntimer (twice since one of the values will be counted down to 0, the other will be set in the new object) + //we need to copy all values since each value can be different for each ammoPickup + m_ETriggerTouchVector.push_back({ e.Trigger["Transform"]["Position"], e.Trigger["AmmoPickup"]["AmmoGain"], + e.Trigger["AmmoPickup"]["RespawnTimer"], e.Trigger["AmmoPickup"]["RespawnTimer"], m_World->GetParent(e.Trigger.ID) }); + + //delete the ammopickup + m_World->DeleteEntity(e.Trigger.ID); + return true; +} diff --git a/src/Game/Systems/AmmunitionHUDSystem.cpp b/src/Game/Systems/AmmunitionHUDSystem.cpp new file mode 100644 index 00000000..c9d87072 --- /dev/null +++ b/src/Game/Systems/AmmunitionHUDSystem.cpp @@ -0,0 +1,36 @@ +#include "Game/Systems/AmmunitionHUDSystem.h" + +void AmmunitionHUDSystem::Update(double dt) +{ + //Hud element for tracking ammunition from parent with AssaultWeapon component.Child with the name "MagazineAmmo" tracks clip ammunition.Child with the name "Ammo" tracks ammo. + + auto ammunitionHUDs = m_World->GetComponents("AmmunitionHUD"); + if (ammunitionHUDs == nullptr) { + return; + } + + for (auto& ammunitionHUDComponent : *ammunitionHUDs) { + EntityWrapper entity = EntityWrapper(m_World, ammunitionHUDComponent.EntityID); + + EntityWrapper playerEntity = entity.FirstParentWithComponent("AssaultWeapon"); + + if (!playerEntity.Valid()) { + return; + } + + + EntityWrapper magazineAmmo = entity.FirstChildByName("MagazineAmmo"); + if(magazineAmmo.Valid()) { + if(magazineAmmo.HasComponent("Text")) { + (std::string&)magazineAmmo["Text"]["Content"] = std::to_string((int)playerEntity["AssaultWeapon"]["MagazineAmmo"]); + } + } + + EntityWrapper ammo = entity.FirstChildByName("Ammo"); + if (ammo.Valid()) { + if (ammo.HasComponent("Text")) { + (std::string&)ammo["Text"]["Content"] = std::to_string((int)playerEntity["AssaultWeapon"]["Ammo"]); + } + } + } +} diff --git a/src/Game/Systems/CapturePointHUDSystem.cpp b/src/Game/Systems/CapturePointHUDSystem.cpp new file mode 100644 index 00000000..6f1392e0 --- /dev/null +++ b/src/Game/Systems/CapturePointHUDSystem.cpp @@ -0,0 +1,59 @@ +#include "Systems/CapturePointHUDSystem.h" + +CapturePointHUDSystem::CapturePointHUDSystem(SystemParams params) + : System(params) + , ImpureSystem() +{ +} + + +void CapturePointHUDSystem::Update(double dt) +{ + bool LoadCheck = true; + int redTeam; + int blueTeam; + int spectatorTeam; + + auto CapturePointHUDElements = m_World->GetComponents("CapturePointHUD"); + auto CapturePoints = m_World->GetComponents("CapturePoint"); + if (CapturePointHUDElements == nullptr) { + return; + } + + if(!CapturePointHUDElements) { + return; + } + + for (auto& cCapturePointHUD : *CapturePointHUDElements) { + int HUD_ID = cCapturePointHUD["CapturePointNumber"]; + EntityWrapper entityHUD = EntityWrapper(m_World, cCapturePointHUD.EntityID); + EntityWrapper entityHUDparent = entityHUD.Parent(); + + for (auto& cCapturePoint : *CapturePoints) { + EntityWrapper entityCP = EntityWrapper(m_World, cCapturePoint.EntityID); + + //Check if the HUD corresponds to the Capture Point Number + if (HUD_ID == (int)entityCP["CapturePoint"]["CapturePointNumber"]) { + ComponentWrapper& teamComponent = entityCP["Team"]; + if (LoadCheck) { + redTeam = (int)teamComponent["Team"].Enum("Red"); + blueTeam = (int)teamComponent["Team"].Enum("Blue"); + spectatorTeam = (int)teamComponent["Team"].Enum("Spectator"); + LoadCheck = false; + } + //Color hud with team color + auto capturePointTeam = (int)teamComponent["Team"]; + entityHUDparent["Sprite"]["Color"] = capturePointTeam == blueTeam ? glm::vec4(0, 0.2f, 1, 0.7f) : capturePointTeam == redTeam ? glm::vec4(1, 0.0f, 0, 0.7f) : glm::vec4(1, 1, 1, 0.3f); + + //Progress is scaled with time + double currentCaptureTime = (double)entityCP["CapturePoint"]["CaptureTimer"]; + double progress = glm::abs(currentCaptureTime)/15.0; + int currentCapturingTeam = currentCaptureTime > 0 ? redTeam : currentCaptureTime < 0 ? blueTeam : spectatorTeam; + ((glm::vec3&)entityHUD["Transform"]["Orientation"]).z = currentCapturingTeam == redTeam ? glm::half_pi()+glm::pi() : glm::half_pi(); + glm::vec4 fillColor = currentCapturingTeam == redTeam ? glm::vec4(1, 0.f, 0, 0.7f) : glm::vec4(0, 0.2f, 1, 0.7f); + entityHUD["Fill"]["Color"] = fillColor; + entityHUD["Fill"]["Percentage"] = progress; + } + } + } +} \ No newline at end of file diff --git a/src/Game/Systems/CapturePointSystem.cpp b/src/Game/Systems/CapturePointSystem.cpp index d26dde5f..c99a36a6 100644 --- a/src/Game/Systems/CapturePointSystem.cpp +++ b/src/Game/Systems/CapturePointSystem.cpp @@ -1,26 +1,39 @@ #include "Systems/CapturePointSystem.h" #include -CapturePointSystem::CapturePointSystem(World* world, EventBroker* eventBroker) - : System(world, eventBroker) +CapturePointSystem::CapturePointSystem(SystemParams params) + : System(params) , PureSystem("CapturePoint") { //subscribe/listenTo playerdamage,healthpickup events (using the eventBroker) - EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &CapturePointSystem::OnTriggerTouch); - EVENT_SUBSCRIBE_MEMBER(m_ETriggerLeave, &CapturePointSystem::OnTriggerLeave); - EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &CapturePointSystem::OnCaptured); + if (!IsClient) { + EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &CapturePointSystem::OnTriggerTouch); + EVENT_SUBSCRIBE_MEMBER(m_ETriggerLeave, &CapturePointSystem::OnTriggerLeave); + EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &CapturePointSystem::OnCaptured); + } + } //here all capturepoints will update their component //NOTE: needs to run each frame, since we're possibly modifying the captureTimer for the capturePoints by dt void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, ComponentWrapper& cCapturePoint, double dt) { + if (IsClient) { + return; + } if (m_WinnerWasFound) { return; } const int capturePointNumber = cCapturePoint["CapturePointNumber"]; const bool hasTeamComponent = capturePointEntity.HasComponent("Team"); + if (m_NumberOfCapturePoints != 0) { + if (!m_CapturePointNumberToEntityMap[0].HasComponent("CapturePoint")) { + //if map has changed, the capturepoints has changed, now have to redo them + m_NumberOfCapturePoints = 0; + m_CapturePointNumberToEntityMap.clear(); + } + } //if point doesnt have a teamComponent yet, add one. since: //what if capture point has no team -> we cant get/use the team enum from it... if (!hasTeamComponent) { @@ -32,6 +45,7 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp const int redTeam = (int)teamComponent["Team"].Enum("Red"); const int blueTeam = (int)teamComponent["Team"].Enum("Blue"); const int spectatorTeam = (int)teamComponent["Team"].Enum("Spectator"); + const double captureTimeToTakeOver = (double)cCapturePoint["CapturePointMaxTimer"]; int homePointForTeam = (int)cCapturePoint["HomePointForTeam"]; if (m_NumberOfCapturePoints == 0 && capturePointNumber != 0 && (homePointForTeam == redTeam || homePointForTeam == blueTeam)) { @@ -57,15 +71,14 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp int blueTeamPlayersStandingInside = 0; if (capturePointEntity.HasComponent("Model")) { //Now sets team color to the capturepoint, or white if it is uncaptured. - 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); + capturePointEntity["Model"]["Color"] = ownedBy == blueTeam ? glm::vec4(0, 0.0f, 1, 0.3) : ownedBy == redTeam ? glm::vec4(1, 0.0f, 0, 0.3) : glm::vec4(1, 1, 1, 0.3); } //calculate next possible capturePoint for both teams std::map nextPossibleCapturePoint; nextPossibleCapturePoint["Red"] = -1; nextPossibleCapturePoint["Blue"] = -1; - for (int i = 0; i < m_NumberOfCapturePoints; i++) - { + for (int i = 0; i < m_NumberOfCapturePoints; i++) { if (!m_CapturePointNumberToEntityMap[i].HasComponent("Team")) { continue; } @@ -77,8 +90,7 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp nextPossibleCapturePoint["Blue"] = i + 1; } } - for (int i = m_NumberOfCapturePoints - 1; i >= 0; i--) - { + for (int i = m_NumberOfCapturePoints - 1; i >= 0; i--) { if (!m_CapturePointNumberToEntityMap[i].HasComponent("Team")) { continue; } @@ -93,28 +105,22 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp //reset timers and reset the bool that triggers this if (m_ResetTimers) { - for (int i = 0; i < m_NumberOfCapturePoints; i++) - { + for (int i = 0; i < m_NumberOfCapturePoints; i++) { ComponentWrapper& capturePoint = m_CapturePointNumberToEntityMap[i]["CapturePoint"]; if ((int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Red"] && (int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Blue"]) { - capturePoint["CaptureTimer"] = 0.0; + //RED = +, BLUE = -, NONE + auto teamOwners = (int)m_CapturePointNumberToEntityMap[i]["Team"]["Team"]; + if (teamOwners == redTeam || teamOwners == blueTeam) { + capturePoint["CaptureTimer"] = teamOwners == blueTeam ? -captureTimeToTakeOver : captureTimeToTakeOver; + } } } m_ResetTimers = false; } - //colorize next possible capturepoint - if (nextPossibleCapturePoint["Red"] == capturePointNumber) { - capturePointEntity["Model"]["Color"] = glm::vec4(1, 1, 0, 1); - } - if (nextPossibleCapturePoint["Blue"] == capturePointNumber) { - 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--) - { + for (size_t i = m_ETriggerTouchVector.size(); i > 0; i--) { auto triggerTouched = m_ETriggerTouchVector[i - 1]; if (std::get<1>(triggerTouched) == capturePointEntity) { //some player has touched this - lets figure out: what team, health @@ -170,22 +176,18 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp //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)cCapturePoint["CaptureTimer"]) < 0.001f) { - LOG_DEBUG("Point is being captured by team %i", currentTeam); //Remove when we tested sufficiently. - } cCapturePoint["CaptureTimer"] = (double)cCapturePoint["CaptureTimer"] + timerDeltaChange; } //if capturePoint is owned by the team, and the other team has been trying to take it, then increase/decrease the timer towards 0.0 - if ((ownedBy == currentTeam && currentTeam == redTeam && (double)cCapturePoint["CaptureTimer"] < 0.0) || - (ownedBy == currentTeam && currentTeam == blueTeam && (double)cCapturePoint["CaptureTimer"] > 0.0)) { + if ((ownedBy == currentTeam && currentTeam == redTeam && (double)cCapturePoint["CaptureTimer"] < captureTimeToTakeOver) || + (ownedBy == currentTeam && currentTeam == blueTeam && (double)cCapturePoint["CaptureTimer"] > -captureTimeToTakeOver)) { cCapturePoint["CaptureTimer"] = (double)cCapturePoint["CaptureTimer"] + timerDeltaChange; } - //check if captureTimer > m_CaptureTimeToTakeOver and if so change owner and publish the eCaptured event - if (abs((double)cCapturePoint["CaptureTimer"]) > abs(m_CaptureTimeToTakeOver) && canCapture) { + //check if captureTimer > captureTimeToTakeOver and if so change owner and publish the eCaptured event + if (abs((double)cCapturePoint["CaptureTimer"]) > captureTimeToTakeOver && canCapture) { teamComponent["Team"] = currentTeam; - cCapturePoint["CaptureTimer"] = 0.0; + cCapturePoint["CaptureTimer"] = glm::sign((double)cCapturePoint["CaptureTimer"])*captureTimeToTakeOver; //publish Captured event - LOG_DEBUG("Point is captured by team %i!", currentTeam); //Remove when we tested sufficiently. Events::Captured e; e.CapturePointID = cCapturePoint.EntityID; e.TeamNumberThatCapturedCapturePoint = currentTeam; @@ -196,17 +198,14 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp //check for possible winCondition = check if the homebase is owned by the other team bool checkForWinner = false; - if (capturePointNumber == m_RedTeamHomeCapturePoint && ownedBy != redTeam) - { + if (capturePointNumber == m_RedTeamHomeCapturePoint && ownedBy != redTeam) { checkForWinner = true; } - if (capturePointNumber == m_BlueTeamHomeCapturePoint && ownedBy != blueTeam) - { + if (capturePointNumber == m_BlueTeamHomeCapturePoint && ownedBy != blueTeam) { checkForWinner = true; } - if (checkForWinner && !m_WinnerWasFound) - { + if (checkForWinner && !m_WinnerWasFound) { //publish Win event Events::Win e; e.TeamThatWon = ownedBy; @@ -225,8 +224,7 @@ bool CapturePointSystem::OnTriggerTouch(const Events::TriggerTouch& e) bool CapturePointSystem::OnTriggerLeave(const Events::TriggerLeave& e) { - for (size_t i = 0; i < m_ETriggerTouchVector.size(); i++) - { + for (size_t i = 0; i < m_ETriggerTouchVector.size(); i++) { auto triggerTouched = m_ETriggerTouchVector[i]; if (std::get<0>(triggerTouched) == e.Entity && std::get<1>(triggerTouched) == e.Trigger) { m_ETriggerTouchVector.erase(m_ETriggerTouchVector.begin() + i); diff --git a/src/Game/Systems/DamageIndicatorSystem.cpp b/src/Game/Systems/DamageIndicatorSystem.cpp new file mode 100644 index 00000000..92fbe607 --- /dev/null +++ b/src/Game/Systems/DamageIndicatorSystem.cpp @@ -0,0 +1,149 @@ +#include "Systems/DamageIndicatorSystem.h" + +DamageIndicatorSystem::DamageIndicatorSystem(SystemParams params) + : System(params) +{ + EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &DamageIndicatorSystem::OnPlayerDamage); + //current camera + EVENT_SUBSCRIBE_MEMBER(m_ESetCamera, &DamageIndicatorSystem::OnSetCamera); + + //load texture to cache + auto texture = CommonFunctions::LoadTexture("Textures/DamageIndicator.png", false); + auto entityFile = ResourceManager::Load("Schema/Entities/DamageIndicator.xml"); +} + +void DamageIndicatorSystem::Update(double dt) { + if (!IsServer) { + for (auto& iter = updateDamageIndicatorVector.begin(); iter != updateDamageIndicatorVector.end(); iter++) { + if (!iter->spriteEntity.Valid()) { + updateDamageIndicatorVector.erase(iter); + break; + } + auto angleBetweenVectors = CalculateAngle(LocalPlayer, iter->enemyPosition); + //simply set the rotation z-wise to the angleBetweenVectors + iter->spriteEntity["Transform"]["Orientation"] = glm::vec3(0, 0, angleBetweenVectors); + } + } +} + +bool DamageIndicatorSystem::OnPlayerDamage(Events::PlayerDamage& e) +{ + if (m_CurrentCamera == EntityID_Invalid) { + return false; + } + + if (e.Victim.Valid() && e.Victim != LocalPlayer && !e.Victim.IsChildOf(LocalPlayer)) { + return false; + } + + if (!e.Inflictor.Valid() || !e.Victim.Valid()) { + return false; + } + + glm::vec3 inflictorPos = e.Inflictor["Transform"]["Position"]; + //if testing +#ifdef INDICATOR_TEST + inflictorPos = DamageIndicatorTest(e.Victim); +#endif + + float angleBetweenVectors = CalculateAngle(e.Victim, inflictorPos); + + //load & set the "2d" sprite + auto entityFile = ResourceManager::Load("Schema/Entities/DamageIndicator.xml"); + EntityFileParser parser(entityFile); + EntityID spriteID = parser.MergeEntities(m_World); + m_World->SetParent(spriteID, m_CurrentCamera); + auto spriteWrapper = EntityWrapper(m_World, spriteID); + //simply set the rotation z-wise to the angleBetweenVectors + spriteWrapper["Transform"]["Orientation"] = glm::vec3(0, 0, angleBetweenVectors); + + if (!IsServer) { + updateDamageIndicatorVector.emplace_back(spriteWrapper, inflictorPos); + } + + return true; +} + +bool DamageIndicatorSystem::OnSetCamera(const Events::SetCamera& e) { + m_CurrentCamera = e.CameraEntity.ID; + return true; +} + +float DamageIndicatorSystem::CalculateAngle(EntityWrapper player, glm::vec3 enemyPos) { + //grab players direction + auto playerOrientation = glm::quat((glm::vec3)player["Transform"]["Orientation"]); + + //get the position vectors, but ignore the y-height + auto enemyPosition = enemyPos; + auto playerPosition = (glm::vec3)player["Transform"]["Position"]; + enemyPosition.y = 0.0f; + playerPosition.y = 0.0f; + + //calculate the enemy to player vector + auto enemyPlayerVector = glm::normalize(playerPosition - enemyPosition); + + //get the rotationvector relative to the z-axis + auto rotationVectorVec3 = glm::vec3(glm::toMat4(Transform::AbsoluteOrientation(player))*glm::vec4(0, 0, 1, 0)); + //rotate the direction-vector 90 degrees to get the players side-vector + auto playerSideVector = glm::vec3(glm::rotateY(rotationVectorVec3, 1.57f)); + + //dot product of players direction-vector and enemys-to-playervector will give the cos of the angle between the vectors + auto playerRotationDot = glm::dot(rotationVectorVec3, enemyPlayerVector); + //to get the angle between the vectors just do cos-inverse + auto angleBetweenVectors = glm::acos(playerRotationDot); + + //dot of sidevector positive = enemy is on the right side, dot sidevector negative = left side + auto playerSideVectorDot = glm::dot(playerSideVector, enemyPlayerVector); + if (playerSideVectorDot < 0) { + angleBetweenVectors = -angleBetweenVectors; + } + + return angleBetweenVectors; +} +#ifdef INDICATOR_TEST +glm::vec3 DamageIndicatorSystem::DamageIndicatorTest(EntityWrapper player) { + auto currentPos = (glm::vec3)player["Transform"]["Position"]; + + auto testVar = 1; + auto testVar2 = 1; + if (m_TestVar % 4 == 0) { + testVar = -1; + testVar2 = 1; + } + if (m_TestVar % 4 == 1) { + testVar = 1; + testVar2 = 1; + } + if (m_TestVar % 4 == 2) { + testVar *= -1; + testVar2 = -1; + } + if (m_TestVar % 4 == 3) { + testVar = 1; + testVar2 = -1; + } + m_TestVar++; + + auto inflictorPos = glm::vec3(currentPos.x + testVar*6.0f, currentPos.y, currentPos.z + testVar2*6.0f); + + //load the explosioneffect XML + auto deathEffect = ResourceManager::Load("Schema/Entities/PlayerDeathExplosionWithCamera.xml"); + EntityFileParser parser(deathEffect); + EntityID deathEffectID = parser.MergeEntities(m_World); + EntityWrapper deathEffectEW = EntityWrapper(m_World, deathEffectID); + + //components that we need from player + auto playerModel = player.FirstChildByName("PlayerModel"); + auto playerEntityModel = playerModel["Model"]; + auto playerEntityAnimation = playerModel["Animation"]; + + //copy the data from player to explosioneffectmodel + playerEntityModel.Copy(deathEffectEW["Model"]); + playerEntityAnimation.Copy(deathEffectEW["Animation"]); + + //copy the models position,orientation + deathEffectEW["Transform"]["Position"] = inflictorPos; + deathEffectEW["Transform"]["Orientation"] = (glm::vec3)player["Transform"]["Orientation"]; + return inflictorPos; +} +#endif \ No newline at end of file diff --git a/src/Game/Systems/ExplosionEffectSystem.cpp b/src/Game/Systems/ExplosionEffectSystem.cpp new file mode 100644 index 00000000..2704d2da --- /dev/null +++ b/src/Game/Systems/ExplosionEffectSystem.cpp @@ -0,0 +1,14 @@ +#include "Systems/ExplosionEffectSystem.h" + +void ExplosionEffectSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) +{ + 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; + //} +} + diff --git a/src/Game/Systems/PlayerHUD.cpp b/src/Game/Systems/HealthHUDSystem.cpp similarity index 76% rename from src/Game/Systems/PlayerHUD.cpp rename to src/Game/Systems/HealthHUDSystem.cpp index 55d0c3f1..74258d6e 100644 --- a/src/Game/Systems/PlayerHUD.cpp +++ b/src/Game/Systems/HealthHUDSystem.cpp @@ -1,21 +1,6 @@ -#include "Game/Systems/PlayerHUD.h" +#include "Game/Systems/HealthHUDSystem.h" -PlayerHUD::PlayerHUD(World* world, EventBroker* eventBrokerer) - :System(world, eventBrokerer) - , m_World(world) - , m_EventBroker(eventBrokerer) -{ - - -} - -PlayerHUD::~PlayerHUD() -{ - - -} - -void PlayerHUD::Update(double dt) +void HealthHUDSystem::Update(double dt) { auto healthHUDs = m_World->GetComponents("HealthHUD"); if (healthHUDs == nullptr) { @@ -42,13 +27,13 @@ void PlayerHUD::Update(double dt) s = s + "/"; s = s + std::to_string((int)(double)entityIDParent["Health"]["MaxHealth"]); float healthPercentage = (double)entityIDParent["Health"]["Health"]/(double)entityIDParent["Health"]["MaxHealth"]; - (glm::vec4&)entity["Text"]["Color"] = glm::vec4(1.0 - healthPercentage, 0.f, healthPercentage, 1.f); + //(glm::vec4&)entity["Text"]["Color"] = glm::vec4(1.0 - healthPercentage, 0.f, healthPercentage, glm::vec4(entity["Text"]["Color"]).a); entity["Text"]["Content"] = s; } if(entity.HasComponent("Fill")) { float healthPercentage = (double)entityIDParent["Health"]["Health"]/(double)entityIDParent["Health"]["MaxHealth"]; - (glm::vec4&)entity["Fill"]["Color"] = glm::vec4(1.0 - healthPercentage, 0.f, healthPercentage, 0.f); + (glm::vec4&)entity["Fill"]["Color"] = glm::vec4(1.0 - healthPercentage, 0.f, healthPercentage, glm::vec4(entity["Fill"]["Color"]).a); (double&)entity["Fill"]["Percentage"] = healthPercentage; } diff --git a/src/Game/Systems/HealthSystem.cpp b/src/Game/Systems/HealthSystem.cpp index 9e118070..94f23c67 100644 --- a/src/Game/Systems/HealthSystem.cpp +++ b/src/Game/Systems/HealthSystem.cpp @@ -1,67 +1,59 @@ #include "Systems/HealthSystem.h" -HealthSystem::HealthSystem(World* m_World, EventBroker* eventBroker) - : System(m_World, eventBroker) +HealthSystem::HealthSystem(SystemParams params) + : System(params) , PureSystem("Health") { //subscribe/listenTo playerdamage,healthpickup events (using the eventBroker) EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &HealthSystem::OnPlayerDamaged); EVENT_SUBSCRIBE_MEMBER(m_EPlayerHealthPickup, &HealthSystem::OnPlayerHealthPickup); + EVENT_SUBSCRIBE_MEMBER(m_InputCommand, &HealthSystem::OnInputCommand); + m_NetworkEnabled = ResourceManager::Load("Config.ini")->Get("Networking.StartNetwork", false); } -void HealthSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) +void HealthSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cHealth, double dt) { - //if entityID of health is 9 then the players ID is also 9 (player,health are connected to the same entity) - double maxHealth = (double)component["MaxHealth"]; - - //process the DeltaHealthVector and change the entitys health accordingly - for (size_t i = m_DeltaHealthVector.size(); i > 0; i--) - { - auto deltaHP = m_DeltaHealthVector[i - 1]; - //if we have a healthchange for the current player and health is greater than 0, then apply it - if (std::get<0>(deltaHP) == component.EntityID && (double)component["Health"] > 0.0f) { - //get the deltaHP value from the tuple and make sure you dont get more than maxHealth - double newHealth = std::min((double)component["Health"] + (double)std::get<1>(deltaHP), maxHealth); - component["Health"] = newHealth; - m_DeltaHealthVector.erase(m_DeltaHealthVector.begin() + i - 1); - //check if health is <= 0 - if ((double)component["Health"] <= 0.0f) { - component["Health"] = 0.0; - //publish death event - Events::PlayerDeath e; - e.PlayerID = component.EntityID; - m_EventBroker->Publish(e); - //clear the remaining hpDeltas for the dead player - for (size_t j = m_DeltaHealthVector.size(); j > 0; j--) - { - if (std::get<0>(m_DeltaHealthVector[j - 1]) == component.EntityID) - m_DeltaHealthVector.erase(m_DeltaHealthVector.begin() + j - 1); - } - //delete the player and break the loop - m_World->DeleteEntity(entity.ID); - break; - } - } + double& health = cHealth["Health"]; + if (health <= 0.0) { + Events::PlayerDeath ePlayerDeath; + ePlayerDeath.Player = entity; + m_EventBroker->Publish(ePlayerDeath); + //Note: we will delete the entity in PlayerDeathSystem } } bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e) { - ComponentWrapper cHealth = e.Player["Health"]; - double& health = cHealth["Health"]; - health -= e.Damage; - - if (health <= 0.0) { - m_World->DeleteEntity(e.Player.ID); + if (!IsServer && m_NetworkEnabled || !e.Victim.Valid()) { + return false; } + ComponentWrapper cHealth = e.Victim["Health"]; + double& health = cHealth["Health"]; + health -= e.Damage; + return true; } -bool HealthSystem::OnPlayerHealthPickup(const Events::PlayerHealthPickup& e) +bool HealthSystem::OnInputCommand(Events::InputCommand& e) { - //save the changed HP to a vector. it will be taken care of in UpdateComponent - m_DeltaHealthVector.push_back(std::make_tuple(e.PlayerHealedID, e.HealthAmount)); + if (e.Command == "TakeDamage" && e.Value > 0 && LocalPlayer.Valid()) { + Events::PlayerDamage ev; + ev.Inflictor = LocalPlayer; + ev.Victim = LocalPlayer; + ev.Damage = e.Value; + m_EventBroker->Publish(ev); + } + return true; +} + +bool HealthSystem::OnPlayerHealthPickup(Events::PlayerHealthPickup& e) +{ + ComponentWrapper cHealth = e.Player["Health"]; + double& health = cHealth["Health"]; + health += e.HealthAmount; + health = std::min(health, (double)cHealth["MaxHealth"]); + return true; } diff --git a/src/Game/Systems/InterpolationSystem.cpp b/src/Game/Systems/InterpolationSystem.cpp index f2de710d..430c01c1 100644 --- a/src/Game/Systems/InterpolationSystem.cpp +++ b/src/Game/Systems/InterpolationSystem.cpp @@ -1,84 +1,98 @@ #include "Systems/InterpolationSystem.h" -InterpolationSystem::InterpolationSystem(World* world, EventBroker* eventBroker) - : System(world, eventBroker) - , PureSystem("Transform") +InterpolationSystem::InterpolationSystem(SystemParams params) + : System(params) { ConfigFile* config = ResourceManager::Load("Config.ini"); m_SnapshotInterval = config->Get("Networking.SnapshotInterval", 0.05f); EVENT_SUBSCRIBE_MEMBER(m_EInterpolate, &InterpolationSystem::OnInterpolate); - EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &InterpolationSystem::OnPlayerSpawned); } -void InterpolationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& transform, double dt) +void InterpolationSystem::Update(double dt) { - // Don't interpolate entities that might already have been removed - if (!entity.Valid()) { - return; + // Position + for (auto& kv : m_InterpolatePosition) { + EntityWrapper entity = kv.first; + if (!entity.Valid()) { + continue; + } + auto& iPosition = kv.second; + glm::vec3& position = iPosition.Component[iPosition.Field]; + + iPosition.Alpha += dt; + float alpha = glm::min(iPosition.Alpha / m_SnapshotInterval, 1.0); + position = iPosition.Start + ((iPosition.Goal - iPosition.Start) * alpha); } - if (m_NextTransform.find(transform.EntityID) != m_NextTransform.end()) { // Exists in map - m_NextTransform[transform.EntityID].interpolationTime += static_cast(dt); - Transform sTransform = m_NextTransform[transform.EntityID]; - float time = sTransform.interpolationTime; - if (time > m_SnapshotInterval) { - if (m_LastReceivedTransform.find(transform.EntityID) != m_LastReceivedTransform.end()) { - m_NextTransform[transform.EntityID] = m_LastReceivedTransform[transform.EntityID]; - m_NextTransform[transform.EntityID].interpolationTime = time - m_SnapshotInterval; - sTransform = m_NextTransform[transform.EntityID]; - m_LastReceivedTransform.erase(transform.EntityID); - } else { - m_NextTransform.erase(transform.EntityID); - } + // Orientation + for (auto& kv : m_InterpolateOrientation) { + EntityWrapper entity = kv.first; + if (!entity.Valid()) { + continue; } - if (transform.Info.Name == "Transform") { - bool isLocalPlayer = entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer); - // Position - glm::vec3 nextPosition = sTransform.Position; - glm::vec3 currentPosition = static_cast(transform["Position"]); - // HACK: Don't force position for players - if (!isLocalPlayer) { - (glm::vec3&)transform["Position"] += vectorInterpolation(currentPosition, nextPosition, sTransform.interpolationTime); - } - // Orientation - // Don't force orientation for players - if (!isLocalPlayer) { - glm::quat nextOrientation = sTransform.Orientation; - glm::quat currentOrientation = glm::quat(static_cast(transform["Orientation"])); - (glm::vec3&)transform["Orientation"] = glm::eulerAngles(glm::slerp(currentOrientation, nextOrientation, sTransform.interpolationTime / m_SnapshotInterval)); - } - // Scale - glm::vec3 nextScale = sTransform.Scale; - glm::vec3 currentScale = static_cast(transform["Scale"]); - (glm::vec3&)transform["Scale"] += vectorInterpolation(currentScale, nextScale, sTransform.interpolationTime); + auto& iOrientation = kv.second; + glm::vec3& orientation = iOrientation.Component[iOrientation.Field]; + + iOrientation.Alpha += dt / m_SnapshotInterval; + iOrientation.Alpha = glm::min(iOrientation.Alpha, 1.0); + orientation = glm::eulerAngles(glm::slerp(iOrientation.Start, iOrientation.Goal, (float)iOrientation.Alpha)); + } + + // Velocity + for (auto& kv : m_InterpolateVelocity) { + EntityWrapper entity = kv.first; + if (!entity.Valid()) { + continue; } + auto& iVelocity = kv.second; + glm::vec3& position = iVelocity.Component[iVelocity.Field]; + + iVelocity.Alpha += dt; + float alpha = glm::min(iVelocity.Alpha / m_SnapshotInterval, 1.0); + position = iVelocity.Start + ((iVelocity.Goal - iVelocity.Start) * alpha); } } -bool InterpolationSystem::OnPlayerSpawned(Events::PlayerSpawned& e) +bool InterpolationSystem::OnInterpolate(Events::Interpolate& e) { - m_LocalPlayer = e.Player; + if (e.Component.Info.Name == "Transform") { + auto cTransform = e.Entity["Transform"]; + + // Position + Interpolation iPosition( + cTransform, + "Position", + cTransform["Position"], + e.Component["Position"] + ); + m_InterpolatePosition.erase(e.Entity); + m_InterpolatePosition.insert(std::make_pair(e.Entity, iPosition)); + + // Orientation + Interpolation iOrientation( + cTransform, + "Orientation", + glm::quat((glm::vec3&)cTransform["Orientation"]), + glm::quat((glm::vec3&)e.Component["Orientation"]) + ); + m_InterpolateOrientation.erase(e.Entity); + m_InterpolateOrientation.insert(std::make_pair(e.Entity, iOrientation)); + } else if (e.Component.Info.Name == "Physics") { + auto cPhysics = e.Entity["Physics"]; + if (!e.Entity.HasComponent("Player")) { + return false; + } + + // Velocity + Interpolation iVelocity( + cPhysics, + "Velocity", + cPhysics["Velocity"], + e.Component["Velocity"] + ); + m_InterpolateVelocity.erase(e.Entity); + m_InterpolateVelocity.insert(std::make_pair(e.Entity, iVelocity)); + } + return true; } - -bool InterpolationSystem::OnInterpolate(const Events::Interpolate & e) -{ - Transform transform; - int offset = 0; - // Read the data - memcpy(&transform.Position, e.DataArray.get() + offset, sizeof(glm::vec3)); - offset += sizeof(glm::vec3); - glm::vec3 tempOrientation; - memcpy(&tempOrientation, e.DataArray.get() + offset, sizeof(glm::vec3)); - transform.Orientation = glm::quat(tempOrientation); - offset += sizeof(glm::vec3); - memcpy(&transform.Scale, e.DataArray.get() + offset, sizeof(glm::vec3)); - transform.interpolationTime = 0.0f; - - if (m_NextTransform.find(e.Entity) != m_NextTransform.end()) { // Did exist - m_LastReceivedTransform[e.Entity] = transform; - } else { // Did not - m_NextTransform[e.Entity] = transform; - } - return false; -} diff --git a/src/Game/Systems/KillFeedSystem.cpp b/src/Game/Systems/KillFeedSystem.cpp new file mode 100644 index 00000000..8a16d708 --- /dev/null +++ b/src/Game/Systems/KillFeedSystem.cpp @@ -0,0 +1,80 @@ +#include "Game/Systems/KillFeedSystem.h" + +void KillFeedSystem::Update(double dt) +{ + auto killFeeds = m_World->GetComponents("KillFeed"); + if (killFeeds == nullptr) { + return; + } + + for (auto& killFeedComponent : *killFeeds) { + EntityWrapper entity = EntityWrapper(m_World, killFeedComponent.EntityID); + + for (int i = 1; i <= 3; i++) { + EntityWrapper child = entity.FirstChildByName("KillFeed" + std::to_string(i)); + if (child.HasComponent("Text")) { + (std::string&)child["Text"]["Content"] = ""; + } + } + + + + + int feedIndex = 1; + for (auto it = m_DeathQueue.begin(); it != m_DeathQueue.end(); ) { + bool remove = false; + + EntityWrapper child = entity.FirstChildByName("KillFeed" + std::to_string(feedIndex)); + + if (child.HasComponent("Text")) { + (std::string&)child["Text"]["Content"] = (*it).Content; + (glm::vec4&)child["Text"]["Color"] = (*it).Color; + + (*it).TimeToLive -= dt; + + if ((*it).TimeToLive <= 0.f) { + (std::string&)child["Text"]["Content"] = ""; + (glm::vec4&)child["Text"]["Color"] = (*it).Color; + remove = true; + } + } + feedIndex++; + if(feedIndex > 3) { + break; + } + + if(remove) { + it = m_DeathQueue.erase(it); + } else { + it++; + } + } + } +} + +bool KillFeedSystem::OnPlayerDeath(Events::PlayerDeath& e) +{ + KillFeedInfo kfInfo; + + if (e.Player.HasComponent("Team")) { + int red = e.Player["Team"].Enum("Team", "Red"); + int blue = e.Player["Team"].Enum("Team", "Blue"); + + if ((int)e.Player["Team"]["Team"] == red) { + kfInfo.Content = "Blue Player killed Red Player"; + kfInfo.Color = glm::vec4(0.f, 0.2f, 1.f, 0.8f); + m_DeathQueue.push_back(kfInfo); + } else if ((int)e.Player["Team"]["Team"] == blue) { + kfInfo.Content = "Red Player killed blue Player"; + kfInfo.Color = glm::vec4(1.f, 0.f, 0.f, 0.8f); + m_DeathQueue.push_back(kfInfo); + } + } + + + if(m_DeathQueue.size() > 3) { + m_DeathQueue.pop_front(); + } + + return true; +} diff --git a/src/Game/Systems/PickupSpawnSystem.cpp b/src/Game/Systems/PickupSpawnSystem.cpp new file mode 100644 index 00000000..abf59007 --- /dev/null +++ b/src/Game/Systems/PickupSpawnSystem.cpp @@ -0,0 +1,67 @@ +#include "Systems/PickupSpawnSystem.h" + +PickupSpawnSystem::PickupSpawnSystem(SystemParams params) + : System(params) +{ + EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &PickupSpawnSystem::OnTriggerTouch); +} + +void PickupSpawnSystem::Update(double dt) +{ + for (auto it = m_ETriggerTouchVector.begin(); it != m_ETriggerTouchVector.end(); ++it) + { + auto& healthPickupPosition = *it; + //set the double timer value (value 3) + healthPickupPosition.DecreaseThisRespawnTimer -= dt; + if (healthPickupPosition.DecreaseThisRespawnTimer < 0) { + //spawn and delete the vector item + auto entityFile = ResourceManager::Load("Schema/Entities/HealthPickup.xml"); + EntityFileParser parser(entityFile); + EntityID healthPickupID = parser.MergeEntities(m_World); + + //let the world know a pickup has spawned (graphics effects, etc) + Events::PickupSpawned ePickupSpawned; + ePickupSpawned.Pickup = EntityWrapper(m_World, healthPickupID); + m_EventBroker->Publish(ePickupSpawned); + + //set values from the old entity to the new entity + auto& newHealthPickupEntity = EntityWrapper(m_World, healthPickupID); + newHealthPickupEntity["Transform"]["Position"] = healthPickupPosition.Pos; + newHealthPickupEntity["HealthPickup"]["HealthGain"] = healthPickupPosition.HealthGain; + newHealthPickupEntity["HealthPickup"]["RespawnTimer"] = healthPickupPosition.RespawnTimer; + m_World->SetParent(newHealthPickupEntity.ID, healthPickupPosition.parentID); + + //erase the current element (healthPickupPosition) + m_ETriggerTouchVector.erase(it); + break; + } + } +} + + +bool PickupSpawnSystem::OnTriggerTouch(Events::TriggerTouch& e) +{ + if (!e.Trigger.HasComponent("HealthPickup")) { + return false; + } + double healthGiven = 0.01*(double)e.Trigger["HealthPickup"]["HealthGain"] * (double)e.Entity["Health"]["MaxHealth"]; + //cant pick up healthpacks if you are already at MaxHealth + if ((double)e.Entity["Health"]["Health"] >= (double)e.Entity["Health"]["MaxHealth"]) { + return false; + } + + //personEntered = e.Entity, thingEntered = e.Trigger + Events::PlayerHealthPickup ePlayerHealthPickup; + ePlayerHealthPickup.HealthAmount = healthGiven; + ePlayerHealthPickup.Player = e.Entity; + m_EventBroker->Publish(ePlayerHealthPickup); + + //copy position, healthgain, respawntimer (twice since one of the values will be counted down to 0, the other will be set in the new object) + //we need to copy all values since each value can be different for each healthPickup + m_ETriggerTouchVector.push_back({ (glm::vec3)e.Trigger["Transform"]["Position"] ,e.Trigger["HealthPickup"]["HealthGain"], + e.Trigger["HealthPickup"]["RespawnTimer"],e.Trigger["HealthPickup"]["RespawnTimer"], m_World->GetParent(e.Trigger.ID) }); + + //delete the healthpickup + m_World->DeleteEntity(e.Trigger.ID); + return true; +} diff --git a/src/Game/Systems/PlayerDeathSystem.cpp b/src/Game/Systems/PlayerDeathSystem.cpp new file mode 100644 index 00000000..844d2ed1 --- /dev/null +++ b/src/Game/Systems/PlayerDeathSystem.cpp @@ -0,0 +1,67 @@ +#include "Systems/PlayerDeathSystem.h" + +PlayerDeathSystem::PlayerDeathSystem(SystemParams params) + : System(params) +{ + EVENT_SUBSCRIBE_MEMBER(m_OnPlayerDeath, &PlayerDeathSystem::OnPlayerDeath); +} + +void PlayerDeathSystem::Update(double dt) +{ +} + +bool PlayerDeathSystem::OnPlayerDeath(Events::PlayerDeath& e) +{ + if (!e.Player.Valid()) { + return false; + } + + createDeathEffect(e.Player); + + // Delete player + m_World->DeleteEntity(e.Player.ID); + + return true; +} + +void PlayerDeathSystem::createDeathEffect(EntityWrapper player) +{ + //load the explosioneffect XML + auto deathEffect = ResourceManager::Load("Schema/Entities/PlayerDeathExplosionWithCamera.xml"); + EntityFileParser parser(deathEffect); + EntityID deathEffectID = parser.MergeEntities(m_World); + EntityWrapper deathEffectEW = EntityWrapper(m_World, deathEffectID); + + //components that we need from player + auto playerModel = player.FirstChildByName("PlayerModel"); + if (!playerModel.Valid()) { + return; + } + if (!playerModel.HasComponent("Model") || !playerModel.HasComponent("Animation")) { + return; + } + auto playerEntityModel = playerModel["Model"]; + auto playerEntityAnimation = playerModel["Animation"]; + + //copy the data from player to explosioneffectmodel + playerEntityModel.Copy(deathEffectEW["Model"]); + playerEntityAnimation.Copy(deathEffectEW["Animation"]); + //freeze the animation + deathEffectEW["Animation"]["Speed1"] = 0.0; + deathEffectEW["Animation"]["Speed2"] = 0.0; + deathEffectEW["Animation"]["Speed3"] = 0.0; + + //copy the models position,orientation + deathEffectEW["Transform"]["Position"] = (glm::vec3)player["Transform"]["Position"]; + deathEffectEW["Transform"]["Orientation"] = (glm::vec3)player["Transform"]["Orientation"]; + //effect,camera is relative to playersPosition + //deathEffectEW["ExplosionEffect"]["ExplosionOrigin"] = glm::vec3(0, 0, 0); + + //camera (with lifetime) behind the player + if (player == LocalPlayer) { + auto cam = deathEffectEW.FirstChildByName("Camera"); + Events::SetCamera eSetCamera; + eSetCamera.CameraEntity = cam; + m_EventBroker->Publish(eSetCamera); + } +} diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 72900d7a..2e2502ec 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -1,10 +1,10 @@ #include "Systems/PlayerMovementSystem.h" -PlayerMovementSystem::PlayerMovementSystem(World* world, EventBroker* eventBroker) - : System(world, eventBroker) - , PureSystem("Player") +PlayerMovementSystem::PlayerMovementSystem(SystemParams params) + : System(params) { EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &PlayerMovementSystem::OnPlayerSpawned); + EVENT_SUBSCRIBE_MEMBER(m_EDoubleJump, &PlayerMovementSystem::OnDoubleJump); } PlayerMovementSystem::~PlayerMovementSystem() @@ -15,6 +15,20 @@ PlayerMovementSystem::~PlayerMovementSystem() } void PlayerMovementSystem::Update(double dt) +{ + updateMovementControllers(dt); + if (IsServer) { + for (auto& kv : m_PlayerInputControllers) { + updateVelocity(kv.first, dt); + } + } else { + if (LocalPlayer.Valid()) { + updateVelocity(LocalPlayer, dt); + } + } +} + +void PlayerMovementSystem::updateMovementControllers(double dt) { for (auto& kv : m_PlayerInputControllers) { EntityWrapper player = kv.first; @@ -23,13 +37,21 @@ void PlayerMovementSystem::Update(double dt) if (!player.Valid()) { continue; } - + // Aim pitch EntityWrapper cameraEntity = player.FirstChildByName("Camera"); if (cameraEntity.Valid()) { glm::vec3& cameraOrientation = cameraEntity["Transform"]["Orientation"]; cameraOrientation.x += controller->Rotation().x; // Limit camera pitch so we don't break our necks cameraOrientation.x = glm::clamp(cameraOrientation.x, -glm::half_pi(), glm::half_pi()); + // Set third person model aim pitch + EntityWrapper playerModel = player.FirstChildByName("PlayerModel"); + if (playerModel.Valid()) { + ComponentWrapper cAnimationOffset = playerModel["AnimationOffset"]; + float pitch = cameraOrientation.x + 0.2; + double time = (pitch + glm::half_pi()) / glm::pi(); + cAnimationOffset["Time"] = time; + } } ComponentWrapper& cTransform = player["Transform"]; @@ -38,52 +60,80 @@ void PlayerMovementSystem::Update(double dt) float playerMovementSpeed = player["Player"]["MovementSpeed"]; float playerCrouchSpeed = player["Player"]["CrouchSpeed"]; + glm::vec3& wishDirection = player["Player"]["CurrentWishDirection"]; if (player.HasComponent("Physics")) { ComponentWrapper cPhysics = player["Physics"]; - - glm::vec3 wishDirection = controller->Movement() * glm::inverse(glm::quat(ori)); + //Assault Dash Check + if (player.HasComponent("DashAbility")) { + controller->AssaultDashCheck(dt, ((glm::vec3)cPhysics["Velocity"]).y != 0.0f, player["DashAbility"]["CoolDownMaxTimer"]); + } + wishDirection = controller->Movement() * glm::inverse(glm::quat(ori)); + //this makes sure you can only dash in the 4 directions: forw,backw,left,right + if (controller->AssaultDashDoubleTapped() && controller->Movement().z != 0 && controller->Movement().x != 0) { + wishDirection = glm::vec3(controller->Movement().x, 0, 0)* glm::inverse(glm::quat(ori)); + } float wishSpeed; if (controller->Crouching()) { wishSpeed = playerCrouchSpeed; } else { wishSpeed = playerMovementSpeed; } + if (player.ID == m_LocalPlayer.ID) { + if (glm::length(wishDirection) == 0) { + // If no key is pressed, reset the distance moved since last step. + m_DistanceMoved = 0; + } + } glm::vec3& velocity = cPhysics["Velocity"]; - ImGui::Text("velocity: (%f, %f, %f)", velocity.x, velocity.y, velocity.z); + bool isOnGround = (bool)cPhysics["IsOnGround"]; + //ImGui::Text(isOnGround ? "On ground" : "In air"); + //ImGui::Text("velocity: (%f, %f, %f) |%f|", velocity.x, velocity.y, velocity.z, glm::length(velocity)); glm::vec3 groundVelocity(0.f, 0.f, 0.f); - groundVelocity.x = glm::dot(velocity, glm::vec3(1.f, 0.f, 0.f)); - groundVelocity.z = glm::dot(velocity, glm::vec3(0.f, 0.f, 1.f)); - ImGui::Text("groundVelocity: (%f, %f, %f) |%f|", groundVelocity.x, groundVelocity.y, groundVelocity.z, glm::length(wishDirection)); - ImGui::Text("wishDirection: (%f, %f, %f) |%f|", wishDirection.x, wishDirection.y, wishDirection.z, glm::length(wishDirection)); + groundVelocity.x = velocity.x; + groundVelocity.z = velocity.z; + //ImGui::Text("groundVelocity: (%f, %f, %f) |%f|", groundVelocity.x, groundVelocity.y, groundVelocity.z, glm::length(groundVelocity)); + //ImGui::Text("wishDirection: (%f, %f, %f) |%f|", wishDirection.x, wishDirection.y, wishDirection.z, glm::length(wishDirection)); float currentSpeedProj = glm::dot(groundVelocity, wishDirection); float addSpeed = wishSpeed - currentSpeedProj; - ImGui::Text("currentSpeedProj: %f", currentSpeedProj); - ImGui::Text("wishSpeed: %f", wishSpeed); - ImGui::Text("addSpeed: %f", addSpeed); + //ImGui::Text("currentSpeedProj: %f", currentSpeedProj); + //ImGui::Text("wishSpeed: %f", wishSpeed); + //ImGui::Text("addSpeed: %f", addSpeed); if (addSpeed > 0) { static float accel = 15.f; ImGui::InputFloat("accel", &accel); static float airAccel = 0.5f; ImGui::InputFloat("airAccel", &airAccel); - float actualAccel = (velocity.y != 0) ? airAccel : accel; + float actualAccel = isOnGround ? accel : airAccel; static float surfaceFriction = 5.f; ImGui::InputFloat("surfaceFriction", &surfaceFriction); float accelerationSpeed = actualAccel * (float)dt * wishSpeed * surfaceFriction; - accelerationSpeed = glm::min(accelerationSpeed, addSpeed); + //if doubleTapped do Assault Dash - but only boost maximum 50.0f + float doubleTapDashBoost = controller->AssaultDashDoubleTapped() ? 40.0f : 1.0f; + accelerationSpeed = glm::min(doubleTapDashBoost*glm::min(accelerationSpeed, addSpeed), 50.0f); velocity += accelerationSpeed * wishDirection; ImGui::Text("velocity: (%f, %f, %f) |%f|", velocity.x, velocity.y, velocity.z, glm::length(velocity)); } - if (controller->Jumping() && !controller->Crouching() && (velocity.y == 0.f || !controller->DoubleJumping())) { - if (velocity.y == 0.f) { + //you cant jump and dash at the same time - since there is no friction in the air and we would thus dash much further in the air + if (!controller->PlayerIsDashing() && controller->Jumping() && !controller->Crouching() && (isOnGround || !controller->DoubleJumping())) { + (bool)cPhysics["IsOnGround"] = false; + if (isOnGround) { controller->SetDoubleJumping(false); + } else { + // If IsServer and network is off this will not work + if (IsClient) { + //put a hexagon at the players feet + spawnHexagon(player); + controller->SetDoubleJumping(true); + // Publish event for client to listen to + Events::DoubleJump e; + e.entityID = player.ID; + m_EventBroker->Publish(e); + } } - else { - controller->SetDoubleJumping(true); - } - velocity.y += 4.f; + velocity.y = 4.f; } if (player.HasComponent("AABB")) { @@ -99,23 +149,74 @@ void PlayerMovementSystem::Update(double dt) EntityWrapper playerModel = player.FirstChildByName("PlayerModel"); if (playerModel.Valid()) { ComponentWrapper cAnimation = playerModel["Animation"]; + std::string& animationName1 = cAnimation["AnimationName1"]; + std::string& animationName2 = cAnimation["AnimationName2"]; + double& animationTime1 = cAnimation["Time1"]; + double& animationTime2 = cAnimation["Time2"]; + double& animationSpeed1 = cAnimation["Speed1"]; + double& animationSpeed2 = cAnimation["Speed2"]; + double& animationWeight1 = cAnimation["Weight1"]; + double& animationWeight2 = cAnimation["Weight2"]; float movementLength = glm::length(groundVelocity); + //TODO: add assault dash animation here if (glm::length(controller->Movement()) > 0.f) { - if (controller->Crouching()) { - cAnimation["Name"] = "Crouch Walk"; - (double&)cAnimation["Speed"] = 1.f * -glm::sign(controller->Movement().z); + double forwardMovement = controller->Movement().z; + double strafeMovement = controller->Movement().x; + + if (controller->Crouching() && animationName1 != "CrouchWalk") { + animationName1 = "CrouchWalk"; + animationSpeed1 = 1.0 * -glm::sign(controller->Movement().z); } else { - cAnimation["Name"] = "Run"; - (double&)cAnimation["Speed"] = 2.f * -glm::sign(controller->Movement().z); + if (glm::abs(forwardMovement) > 0) { + if (animationName1 != "Run") { + animationName1 = "Run"; + if (animationName2 == "StrafeLeft" || animationName2 == "StrafeRight") { + animationTime1 = animationTime2; + } else { + animationTime1 = 0.0; + } + } + animationSpeed1 = 2.f * -glm::sign(forwardMovement); + } + + if (glm::abs(strafeMovement) > 0) { + if (animationName2 != "StrafeLeft" && animationName2 != "StrafeRight") { + if (strafeMovement < 0) { + animationName2 = "StrafeLeft"; + } + if (strafeMovement > 0) { + animationName2 = "StrafeRight"; + } + if (animationName1 == "Run") { + animationTime2 = animationTime1; + } else { + animationTime2 = 0.0; + } + } + animationSpeed2 = 2.f * glm::abs(strafeMovement); + } + + double strafeWeight = glm::abs(strafeMovement) / (glm::abs(forwardMovement) + glm::abs(strafeMovement)); + animationWeight2 = strafeWeight; + animationWeight1 = 1.0 - strafeWeight; } } else { if (controller->Crouching()) { - cAnimation["Name"] = "Crouch"; - (double&)cAnimation["Speed"] = 1.f; + animationName1 = "Crouch"; + animationName2 = ""; + animationSpeed1 = 1.0; + animationSpeed2 = 0.0; + animationWeight1 = 1.0; + animationWeight2 = 0.0; } else { - cAnimation["Name"] = "Hold Pos"; - (double&)cAnimation["Speed"] = 1.f; + animationName1 = "Idle"; + animationName2 = ""; + animationSpeed1 = 1.f; + animationSpeed2 = 0.0; + animationWeight1 = 1.0; + animationWeight2 = 0.0; + //cAnimation["AnimationName2"] = "Idle"; } } } @@ -123,25 +224,26 @@ void PlayerMovementSystem::Update(double dt) controller->Reset(); } + playerStep(dt); } -void PlayerMovementSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) -{ - ComponentWrapper& cTransform = entity["Transform"]; - if (!entity.HasComponent("Physics")) { - return; - } - ComponentWrapper& cPhysics = entity["Physics"]; +void PlayerMovementSystem::updateVelocity(EntityWrapper player, double dt) +{ + // Only apply velocity to local player + ComponentWrapper& cTransform = player["Transform"]; + ComponentWrapper& cPhysics = player["Physics"]; glm::vec3& velocity = cPhysics["Velocity"]; + bool isOnGround = (bool)cPhysics["IsOnGround"]; // Ground friction float speed = glm::length(velocity); static float groundFriction = 7.f; ImGui::InputFloat("groundFriction", &groundFriction); - static float airFriction = 0.f; + static float airFriction = 2.f; + ImGui::InputFloat("airFriction", &airFriction); - float friction = (velocity.y != 0) ? airFriction : groundFriction; + float friction = isOnGround ? groundFriction : airFriction; if (speed > 0) { float drop = speed * friction * (float)dt; float multiplier = glm::max(speed - drop, 0.f) / speed; @@ -149,6 +251,7 @@ void PlayerMovementSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapp velocity.z *= multiplier; } + // Gravity if (cPhysics["Gravity"]) { velocity.y -= 9.82f * (float)dt; } @@ -157,10 +260,60 @@ void PlayerMovementSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapp position += velocity * (float)dt; } +void PlayerMovementSystem::playerStep(double dt) +{ + if (!m_LocalPlayer.Valid()) { + return; + } + // Position of the local player, used see how far a player has moved. + glm::vec3 pos = (glm::vec3)m_World->GetComponent(m_LocalPlayer.ID, "Transform")["Position"]; + // Used to see if a player is airborne. + bool grounded = (bool)m_World->GetComponent(m_LocalPlayer.ID, "Physics")["IsOnGround"]; + m_DistanceMoved += glm::length(pos - m_LastPosition); + // Set the last position for next iteration + m_LastPosition = pos; + if (m_DistanceMoved > m_PlayerStepLength && grounded) { + // Player moved a step's distance + // Create footstep sound + Events::PlaySoundOnEntity e; + e.EmitterID = m_LocalPlayer.ID; + e.FilePath = m_LeftFoot ? "Audio/footstep/footstep2.wav" : "Audio/footstep/footstep3.wav"; + m_LeftFoot = !m_LeftFoot; + m_EventBroker->Publish(e); + m_DistanceMoved = 0.f; + } +} + bool PlayerMovementSystem::OnPlayerSpawned(Events::PlayerSpawned& e) { // When a player spawns, create an input controller for them m_PlayerInputControllers[e.Player] = new FirstPersonInputController(m_EventBroker, e.PlayerID); - + if (e.PlayerID == -1) { + // Keep track of the local player + m_LocalPlayer = e.Player; + } return true; } + +bool PlayerMovementSystem::OnDoubleJump(Events::DoubleJump & e) +{ + // If entity does not exist, exit + if (!EntityWrapper(m_World, e.entityID).Valid()) { + return false; + } + // If entity IsLocalPlayer, exit + if (e.entityID == m_LocalPlayer.ID) { + return false; + } + spawnHexagon(EntityWrapper(m_World, e.entityID)); +} + +void PlayerMovementSystem::spawnHexagon(EntityWrapper target) +{ + //put a hexagon at the entitys... feet? + auto hexagonEffect = ResourceManager::Load("Schema/Entities/DoubleJumpHexagon.xml"); + EntityFileParser parser(hexagonEffect); + EntityID hexagonEffectID = parser.MergeEntities(m_World); + EntityWrapper hexagonEW = EntityWrapper(m_World, hexagonEffectID); + hexagonEW["Transform"]["Position"] = (glm::vec3)target["Transform"]["Position"]; +} \ No newline at end of file diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index 7db6e8ff..6254c674 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -1,20 +1,39 @@ #include "Systems/PlayerSpawnSystem.h" -PlayerSpawnSystem::PlayerSpawnSystem(World* m_World, EventBroker* eventBroker) - : System(m_World, eventBroker) +//This should be set by the config anyway. +float PlayerSpawnSystem::m_RespawnTime = 15.0f; + +PlayerSpawnSystem::PlayerSpawnSystem(SystemParams params) + : System(params) + , m_Timer(0.f) { EVENT_SUBSCRIBE_MEMBER(m_OnInputCommand, &PlayerSpawnSystem::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_OnPlayerSpawnerd, &PlayerSpawnSystem::OnPlayerSpawned); + EVENT_SUBSCRIBE_MEMBER(m_OnPlayerDeath, &PlayerSpawnSystem::OnPlayerDeath); m_NetworkEnabled = ResourceManager::Load("Config.ini")->Get("Networking.StartNetwork", false); } void PlayerSpawnSystem::Update(double dt) { + //Increase timer. + m_Timer += dt; + if (m_Timer < m_RespawnTime) { + return; + } + //If respawn time has passed, we spawn all players that have requested to be spawned. + m_Timer = 0.f; + + //If there are no spawn requests, return immediately, if we are client the SpawnRequests should always be empty. + if (m_SpawnRequests.size() == 0) { + return; + } + auto playerSpawns = m_World->GetComponents("PlayerSpawn"); if (playerSpawns == nullptr) { return; } + int numSpawnedPlayers = 0; for (auto& req : m_SpawnRequests) { for (auto& cPlayerSpawn : *playerSpawns) { EntityWrapper spawner(m_World, cPlayerSpawn.EntityID); @@ -30,7 +49,7 @@ void PlayerSpawnSystem::Update(double dt) } // Spawn the player! - EntityWrapper player = SpawnerSystem::Spawn(spawner); + EntityWrapper player = SpawnerSystem::Spawn(spawner, EntityWrapper::Invalid, "Player"); // Set the player team affiliation player["Team"]["Team"] = req.Team; @@ -40,29 +59,61 @@ void PlayerSpawnSystem::Update(double dt) e.Player = player; e.Spawner = spawner; m_EventBroker->Publish(e); - + ++numSpawnedPlayers; + break; } } + if (numSpawnedPlayers != (int)m_SpawnRequests.size()) { + LOG_DEBUG("%i players were supposed to be spawned, but %i was spawned.", (int)m_SpawnRequests.size(), numSpawnedPlayers); + } else { + LOG_DEBUG("%i players were spawned.", numSpawnedPlayers); + } m_SpawnRequests.clear(); } -bool PlayerSpawnSystem::OnInputCommand(const Events::InputCommand& e) +bool PlayerSpawnSystem::OnInputCommand(Events::InputCommand& e) { if (e.Command != "PickTeam") { return false; } // Team picks should be processed ONLY server-side! - // Don't make a spawn request if PlayerID is -1, i.e. we're the client. - if (e.PlayerID == -1 && m_NetworkEnabled) { + // Don't make a spawn request if we're the client. + if (!IsServer && m_NetworkEnabled) { return false; } - if (e.Value != 0) { + if (e.Value == 0) { + return false; + } + + //TODO: Spectating? + //Right now, return if someone picks spectator. + //1 signifies spectator here, could not get Playerteam component since it may be invalid or without team comp. + if ((ComponentInfo::EnumType)e.Value == 1) { + return false; + } + + //Check if the player already requested spawn. + auto iter = m_SpawnRequests.begin(); + for (; iter != m_SpawnRequests.end(); ++iter) { + if (iter->PlayerID == e.PlayerID) { + break; + } + } + + if (iter != m_SpawnRequests.end()) { + //If player is in queue to spawn, then change their team affiliation in the request. + iter->Team = (ComponentInfo::EnumType)e.Value; + } else if (m_PlayerEntities.count(e.PlayerID) == 0 || !m_PlayerEntities[e.PlayerID].Valid()) { + //If player is not in queue to spawn, then create a spawn request, + //but only if they are spectating and/or just connected. SpawnRequest req; req.PlayerID = e.PlayerID; req.Team = (ComponentInfo::EnumType)e.Value; m_SpawnRequests.push_back(req); + } else { + return false; } return true; @@ -70,20 +121,27 @@ bool PlayerSpawnSystem::OnInputCommand(const Events::InputCommand& e) bool PlayerSpawnSystem::OnPlayerSpawned(Events::PlayerSpawned& e) { - // When a player is actually spawned (since the actual spawning is handled on the server) - - // Check if a player already exists - if (m_PlayerEntities.count(e.PlayerID) != 0) { - // TODO: Disallow infinite respawning here - m_World->DeleteEntity(m_PlayerEntities[e.PlayerID].ID); - } - // Store the player for future reference m_PlayerEntities[e.PlayerID] = e.Player; + m_PlayerIDs[e.Player.ID] = e.PlayerID; + + // When a player is actually spawned (since the actual spawning is handled on the server) + // Hack should be moved. + + // TODO: Set the player name to whatever + EntityWrapper playerName = e.Player.FirstChildByName("PlayerName"); + if (playerName.Valid()) { + playerName["Text"]["Content"] = e.PlayerName; + } + + if (!IsClient) { + return false; + } // Set the camera to the correct entity EntityWrapper cameraEntity = e.Player.FirstChildByName("Camera"); - if (cameraEntity.Valid()) { + bool outOfBodyExperience = ResourceManager::Load("Config.ini")->Get("Debug.OutOfBodyExperience", false); + if (cameraEntity.Valid() && !outOfBodyExperience) { Events::SetCamera e; e.CameraEntity = cameraEntity; m_EventBroker->Publish(e); @@ -101,11 +159,32 @@ bool PlayerSpawnSystem::OnPlayerSpawned(Events::PlayerSpawned& e) } } - // TODO: Set the player name to whatever - EntityWrapper playerName = e.Player.FirstChildByName("PlayerName"); - if (playerName.Valid()) { - playerName["Text"]["Content"] = e.PlayerName; + return true; +} + +bool PlayerSpawnSystem::OnPlayerDeath(Events::PlayerDeath& e) +{ + //Only spawn request if network is disabled or we are server. + if (!IsServer && m_NetworkEnabled) { + return false; + } + if (!e.Player.HasComponent("Team")) { + return false; + } + ComponentWrapper cTeam = e.Player["Team"]; + //A spectator can't die anyway + if ((ComponentInfo::EnumType)cTeam["Team"] == cTeam["Team"].Enum("Spectator")) { + return false; } + if (m_PlayerIDs.count(e.Player.ID) == 0) { + return false; + } + + SpawnRequest req; + req.PlayerID = m_PlayerIDs.at(e.Player.ID); + req.Team = cTeam["Team"]; + m_SpawnRequests.push_back(req); + return true; -} \ No newline at end of file +} diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp new file mode 100644 index 00000000..b4a37ad0 --- /dev/null +++ b/src/Game/Systems/SoundSystem.cpp @@ -0,0 +1,197 @@ +#include "Game/Systems/SoundSystem.h" + +SoundSystem::SoundSystem(SystemParams params) + : System(params) + , PureSystem("SoundEmitter") +{ + ConfigFile* config = ResourceManager::Load("Config.ini"); + m_Announcer = ResourceManager::Load("Config.ini")->Get("Sound.Announcer", "female"); + if (IsClient) { + EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &SoundSystem::OnPlayerSpawned); + EVENT_SUBSCRIBE_MEMBER(m_InputCommand, &SoundSystem::OnInputCommand); + EVENT_SUBSCRIBE_MEMBER(m_EDoubleJump, &SoundSystem::OnDoubleJump); + EVENT_SUBSCRIBE_MEMBER(m_EDashAbility, &SoundSystem::OnDashAbility); + EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &SoundSystem::OnPlayerDamage); + EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &SoundSystem::OnCaptured); + EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &SoundSystem::OnTriggerTouch); + EVENT_SUBSCRIBE_MEMBER(m_EPlayerDeath, &SoundSystem::OnPlayerDeath); + } +} + +void SoundSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cComponent, double dt) +{ } + +void SoundSystem::Update(double dt) +{ + if (!IsClient) { + return; + } + + // Temp for play test. + if (m_DrumsIsPlaying) { + m_DrumsIsPlaying = !drumTimer(dt); + } +} + +bool SoundSystem::OnPlayerSpawned(const Events::PlayerSpawned &e) +{ + if (e.PlayerID == -1) { // Local player + m_World->AttachComponent(e.Player.ID, "Listener"); + Events::PlaySoundOnEntity go; + go.EmitterID = LocalPlayer.ID; + go.FilePath = "Audio/announcer/" + m_Announcer + "/go.wav"; + m_EventBroker->Publish(go); + // TEMP: starts bgm + { + Events::PlayBackgroundMusic ev; + ev.FilePath = "Audio/bgm/ambient.wav"; + m_EventBroker->Publish(ev); + } + } + return true; +} + +bool SoundSystem::OnInputCommand(const Events::InputCommand & e) +{ + if (e.Command == "Jump" && e.Value > 0) { + if (e.PlayerID == -1) { // local player + playerJumps(); + return true; + } + } + + return false; +} + +void SoundSystem::playerJumps() +{ + if (!LocalPlayer.Valid()) { + return; + } + + bool grounded = (bool)m_World->GetComponent(LocalPlayer.ID, "Physics")["IsOnGround"]; + if (grounded) { + Events::PlaySoundOnEntity e; + e.EmitterID = LocalPlayer.ID; + e.FilePath = "Audio/jump/jump1.wav"; + m_EventBroker->Publish(e); + } +} + +bool SoundSystem::drumTimer(double dt) +{ + m_DrumTimer += dt; + if (m_DrumTimer > 15) { + m_DrumTimer = 0.0; + return true; + } else { + return false; + } +} + +bool SoundSystem::OnCaptured(const Events::Captured & e) +{ + if (!LocalPlayer.Valid()) { + return false; + } + int homeTeam = (int)m_World->GetComponent(e.CapturePointID, "Team")["Team"]; + int team = (int)m_World->GetComponent(LocalPlayer.ID, "Team")["Team"]; + Events::PlaySoundOnEntity ev; + if (team == homeTeam) { + ev.FilePath = "Audio/announcer/" + m_Announcer + "/objective_achieved.wav"; + } else { + ev.FilePath = "Audio/announcer/" + m_Announcer + "/objective_failed.wav"; // have not been tested + } + ev.EmitterID = LocalPlayer.ID; + m_EventBroker->Publish(ev); + // Temp for play test. + m_DrumsIsPlaying = false; + return false; +} + +// Testing purposes atm... +bool SoundSystem::OnPlayerDamage(const Events::PlayerDamage & e) +{ + if (!IsClient) { // Only play for clients + return false; + } + if (LocalPlayer.ID = e.Victim.ID) { // You're local player was the one who took dmg + return false; + } + std::uniform_int_distribution dist(1, 12); + int rand = dist(generator); + std::vector paths; + paths.push_back("Audio/hurt/hurt" + std::to_string(rand) + ".wav"); + + // // Breathe + // int ammountOfbreaths = (static_cast(e.Damage) / 10) + 2; // TEMP: Idk something stupid like this shit + // for (int i = 0; i < ammountOfbreaths; i++) { + // paths.push_back("Audio/exhausted/breath.wav"); + // } + Events::PlayQueueOnEntity ev; + ev.Emitter = LocalPlayer; + ev.FilePaths = paths; + m_EventBroker->Publish(ev); + return false; +} + +bool SoundSystem::OnPlayerDeath(const Events::PlayerDeath & e) +{ + if (e.Player.ID != LocalPlayer.ID) { + return false; + } + if (!IsClient) { + return false; + } + // The local player is dead. The local player might be invalid? + // Play the sound from the listener. + // TODO: We might want to hear other players die. + Events::PlayBackgroundMusic ev; + ev.FilePath = "Audio/die/die2.wav"; + m_EventBroker->Publish(ev); + return false; +} + +bool SoundSystem::OnPlayerHealthPickup(const Events::PlayerHealthPickup & e) +{ + Events::PlaySoundOnEntity ev; + ev.EmitterID = LocalPlayer.ID; + ev.FilePath = "Audio/pickup/pickup2.wav"; + m_EventBroker->Publish(ev); + return false; +} + +bool SoundSystem::OnTriggerTouch(const Events::TriggerTouch & e) +{ + // Temp for play test. + if (m_DrumsIsPlaying) { + return false; + } + if (m_World->HasComponent(e.Trigger.ID, "CapturePoint")) { + Events::PlaySoundOnEntity ev; // should be BGM + ev.EmitterID = LocalPlayer.ID; + ev.FilePath = "Audio/bgm/drumstest.wav"; + m_EventBroker->Publish(ev); + // Temp for play test. + m_DrumsIsPlaying = true; + } + return false; +} + +bool SoundSystem::OnDoubleJump(const Events::DoubleJump & e) +{ + Events::PlaySoundOnEntity ev; + ev.EmitterID = LocalPlayer.ID; + ev.FilePath = "Audio/jump/jump2.wav"; + m_EventBroker->Publish(ev); + return false; +} + +bool SoundSystem::OnDashAbility(const Events::DashAbility &e) +{ + Events::PlaySoundOnEntity ev; + ev.EmitterID = LocalPlayer.ID; + ev.FilePath = "Audio/jump/dash1.wav"; + m_EventBroker->Publish(ev); + return false; +} \ No newline at end of file diff --git a/src/Game/Systems/SpawnerSystem.cpp b/src/Game/Systems/SpawnerSystem.cpp index 7a0a13c9..6500460f 100644 --- a/src/Game/Systems/SpawnerSystem.cpp +++ b/src/Game/Systems/SpawnerSystem.cpp @@ -1,12 +1,13 @@ #include "Systems/SpawnerSystem.h" +#include "Collision/Collision.h" -SpawnerSystem::SpawnerSystem(World* world, EventBroker* eventBroker) - : System(world, eventBroker) +SpawnerSystem::SpawnerSystem(SystemParams params) + : System(params) { EVENT_SUBSCRIBE_MEMBER(m_OnSpawnerSpawn, &SpawnerSystem::OnSpawnerSpawn); } -EntityWrapper SpawnerSystem::Spawn(EntityWrapper spawner, EntityWrapper parent /*= EntityWrapper::Invalid*/) +EntityWrapper SpawnerSystem::Spawn(EntityWrapper spawner, EntityWrapper parent /*= EntityWrapper::Invalid*/, const std::string& dontCollideComponent) { // Spawn the entity in the parent's world if it exists, otherwise in the spawner's world World* world = parent.World; @@ -14,17 +15,41 @@ EntityWrapper SpawnerSystem::Spawn(EntityWrapper spawner, EntityWrapper parent / world = spawner.World; } + // Load the entity file and parse it + const std::string& entityFilePath = spawner["Spawner"]["EntityFile"]; + auto entityFile = ResourceManager::Load(entityFilePath); + if (entityFile == nullptr) { + return EntityWrapper::Invalid; + } + EntityFileParser parser(entityFile); + EntityWrapper spawnedEntity(world, parser.MergeEntities(world, parent.ID)); + + //If the spawned entity is collideable, then we must not spawn it where it collides with something that + //has a dontCollideComponent attached. + bool spawnOnCollidable = dontCollideComponent.empty() || !spawnedEntity.HasComponent("Collidable"); + if (!spawnOnCollidable) { + boost::optional optBox = Collision::EntityAbsoluteAABB(spawnedEntity); + //If we can't calculate the box for some reason, then just spawn somewhere anyway. + if (!optBox) { + spawnOnCollidable = true; + } + } + // Find any SpawnPoints existing as children of spawner - auto children = spawner.World->GetChildren(spawner.ID); + auto children = spawner.World->GetDirectChildren(spawner.ID); std::vector spawnPoints; for (auto kv = children.first; kv != children.second; ++kv) { const EntityID& child = kv->second; if (spawner.World->HasComponent(child, "SpawnPoint")) { - spawnPoints.push_back(EntityWrapper(spawner.World, child)); + EntityWrapper spawnPoint = EntityWrapper(spawner.World, child); + if (spawnOnCollidable || !spawnedEntityIsColliding(spawnedEntity, spawnPoint, dontCollideComponent)) { + spawnPoints.push_back(spawnPoint); + } } } // Choose a random SpawnPoint + // If there are no children, or if they are all blocked, then the entity will be spawned at the spawner itself. EntityWrapper spawnPoint = spawner; if (!spawnPoints.empty()) { if (spawnPoints.size() > 1) { @@ -39,21 +64,59 @@ EntityWrapper SpawnerSystem::Spawn(EntityWrapper spawner, EntityWrapper parent / } } - // Load the entity file and parse it - const std::string& entityFilePath = spawner["Spawner"]["EntityFile"]; - auto entityFile = ResourceManager::Load(entityFilePath); - if (entityFile == nullptr) { - return EntityWrapper::Invalid; + if (spawnPoint != parent) { + transformEntityToSpawnPoint(spawnedEntity, spawnPoint); } - EntityFileParser parser(entityFile); - EntityWrapper spawnedEntity(world, parser.MergeEntities(world, parent.ID)); + return spawnedEntity; +} + +void SpawnerSystem::transformEntityToSpawnPoint(EntityWrapper spawnedEntity, EntityWrapper spawnPoint) +{ // Set its position and orientation to that of the SpawnPoint spawnedEntity["Transform"]["Position"] = Transform::AbsolutePosition(spawnPoint.World, spawnPoint.ID); // TODO: Quaternions, bitch - //spawnedEntity["Transform"]["Orientation"] = glm::eulerAngles(Transform::AbsoluteOrientation(spawnPoint.World, spawnPoint.ID)); + spawnedEntity["Transform"]["Orientation"] = glm::eulerAngles(Transform::AbsoluteOrientation(spawnPoint)); +} - return spawnedEntity; +bool SpawnerSystem::spawnedEntityIsColliding(EntityWrapper spawnedEntity, EntityWrapper spawnPoint, const std::string& dontCollideComponent) +{ + transformEntityToSpawnPoint(spawnedEntity, spawnPoint); + //Check if the spawned entity collides with anything, and if so, continue to the next spawnpoint. + EntityAABB spawnedBox = *Collision::EntityAbsoluteAABB(spawnedEntity); + const ComponentPool* otherSpawnedEntities = spawnPoint.World->GetComponents(dontCollideComponent); + for (const auto& obj : *otherSpawnedEntities) { + if (spawnedEntity.ID == obj.EntityID) { + continue; + } + EntityWrapper otherEntity = EntityWrapper(spawnPoint.World, obj.EntityID); + if (!otherEntity.HasComponent("Collidable")) { + continue; + } + auto otherBox = Collision::EntityAbsoluteAABB(otherEntity); + if (!otherBox) { + continue; + } + if (Collision::AABBVsAABB(spawnedBox, *otherBox)) { + if (!spawnedBox.Entity.HasComponent("Model")) { + return true; + } + RawModel* model = nullptr; + try { + model = ResourceManager::Load(otherEntity["Model"]["Resource"]); + } catch (const std::exception&) { + } + + if (model != nullptr && Collision::AABBvsTriangles( + spawnedBox, + model->Vertices(), + model->m_Indices, + Transform::ModelMatrix(otherEntity))) { + return true; + } + } + } + return false; } bool SpawnerSystem::OnSpawnerSpawn(Events::SpawnerSpawn& e) diff --git a/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp b/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp new file mode 100644 index 00000000..84d3ccd4 --- /dev/null +++ b/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp @@ -0,0 +1,413 @@ +#include "Systems/Weapon/AssaultWeaponBehaviour.h" + +AssaultWeaponBehaviour::AssaultWeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree, EntityWrapper player) + : WeaponBehaviour(systemParams, renderer, collisionOctree, player) +{ + m_FirstPersonModel = m_Player.FirstChildByName("Hands"); + m_ThirdPersonModel = m_Player.FirstChildByName("PlayerModel"); + EVENT_SUBSCRIBE_MEMBER(m_EAnimationComplete, &AssaultWeaponBehaviour::OnAnimationComplete); +} + +void AssaultWeaponBehaviour::Fire() +{ + m_TimeSinceLastFire = 0.0; + m_Firing = true; + fireRound(); +} + +void AssaultWeaponBehaviour::CeaseFire() +{ + m_Firing = false; +} + +void AssaultWeaponBehaviour::Reload() +{ + if (m_Reloading) { + return; + } + + ComponentWrapper& cAssaultWeapon = m_Player["AssaultWeapon"]; + int magAmmo = cAssaultWeapon["MagazineAmmo"]; + int magSize = cAssaultWeapon["MagazineSize"]; + int ammo = cAssaultWeapon["Ammo"]; + + // Don't reload if we're already fully loaded + if (magAmmo == magSize) { + return; + } + + // Don't reload if we're completly out of ammo + if (ammo == 0) { + playEmptySound(); + m_TimeSinceLastFire = -0.0f; // HACK: To make empty sound play with interval + return; + } + + m_Reloading = true; + m_ReloadTimer = cAssaultWeapon["ReloadTime"]; + playReloadAnimation(); + Events::PlaySoundOnEntity e; + e.EmitterID = cAssaultWeapon.EntityID; + e.FilePath = "Audio/weapon/reload.wav"; + m_EventBroker->Publish(e); +} + +void AssaultWeaponBehaviour::Update(double dt) +{ + if (m_Reloading) { + m_ReloadTimer -= dt; + // Re-enable glow on reload impersonator half-way through the animation + if (IsClient) { + if (m_ReloadTimer <= (double)m_Player["AssaultWeapon"]["ReloadTime"] / 2.0) { + if (m_FirstPersonReloadImpersonator.Valid()) { + m_FirstPersonReloadImpersonator["Model"]["GlowMap"] = true; + } + if (m_ThirdPersonReloadImpersonator.Valid()) { + m_ThirdPersonReloadImpersonator["Model"]["GlowMap"] = true; + } + } + } + if (m_ReloadTimer <= 0) { + finishReload(); + } + } + + if (m_Firing && !m_Reloading) { + m_TimeSinceLastFire += dt; + ComponentWrapper& cAssaultWeapon = m_Player["AssaultWeapon"]; + if (m_TimeSinceLastFire >= 1.0 / ((double)cAssaultWeapon["RPM"] / 60.0)) { + fireRound(); + } + } + + if (!m_Firing && !m_Reloading) { + if (IsClient) { + playIdleAnimation(); + } + } + + // Disable glow map on weapon if it's out of ammo + // Make real first person weapon model visible again + if (IsClient) { + EntityWrapper firstPersonWeaponModel = m_Player.FirstChildByName("WeaponModel"); + if (firstPersonWeaponModel.Valid()) { + firstPersonWeaponModel["Model"]["GlowMap"] = hasAmmo(); + } + } +} + +bool AssaultWeaponBehaviour::OnAnimationComplete(Events::AnimationComplete& e) +{ + if (e.Entity != m_FirstPersonModel) { + return false; + } + + //if (e.Name == "ShootRifle") { + // if (!m_Firing) { + // playIdleAnimation(); + // } + //} + + return true; +} + +bool AssaultWeaponBehaviour::hasAmmo() +{ + ComponentWrapper& cAssaultWeapon = m_Player["AssaultWeapon"]; + int& magAmmo = cAssaultWeapon["MagazineAmmo"]; + return magAmmo > 0; +} + +void AssaultWeaponBehaviour::fireRound() +{ + if (m_Reloading) { + return; + } + + ComponentWrapper& cAssaultWeapon = m_Player["AssaultWeapon"]; + + int& magAmmo = cAssaultWeapon["MagazineAmmo"]; + int ammo = cAssaultWeapon["Ammo"]; + + // Reload if our magazine is empty + if (magAmmo <= 0) { + Reload(); + return; + } + + // Fire + magAmmo -= 1; + m_TimeSinceLastFire = 0.0; + + // Effects + if (IsClient) { + spawnTracer(); + playFireSound(); + viewPunch(); + playShootAnimation(); + bool hit = shoot(cAssaultWeapon["BaseDamage"]); + if (hit) { + showHitMarker(); + } + } +} + +void AssaultWeaponBehaviour::spawnTracer() +{ + if (!IsClient) { + return; + } + + EntityWrapper spawner; + bool outOfBodyExperience = ResourceManager::Load("Config.ini")->Get("Debug.OutOfBodyExperience", false); + if (m_Player == LocalPlayer && !outOfBodyExperience) { + spawner = m_Player.FirstChildByName("WeaponMuzzle"); + } else { + spawner = m_Player.FirstChildByName("ThirdPersonWeaponMuzzle"); + } + + if (!spawner.Valid()) { + return; + } + + float distance = traceRayDistance(Transform::AbsolutePosition(spawner), Transform::AbsoluteOrientation(spawner) * glm::vec3(0, 0, -1)); + EntityWrapper ray = SpawnerSystem::Spawn(spawner); + ((glm::vec3&)ray["Transform"]["Scale"]).z = (distance / 100.f); +} + +float AssaultWeaponBehaviour::traceRayDistance(glm::vec3 origin, glm::vec3 direction) +{ + // TODO: Cast a ray and size tracer appropriately + float distance; + glm::vec3 pos; + auto entity = Collision::EntityFirstHitByRay(Ray(origin, direction), m_CollisionOctree, distance, pos); + if (entity) { + return distance; + } else { + return 100.f; + } +} + +void AssaultWeaponBehaviour::playFireSound() +{ + if (!IsClient) { + return; + } + + Events::PlaySoundOnEntity e; + e.EmitterID = m_Player.ID; + e.FilePath = "Audio/laser/laser1.wav"; + m_EventBroker->Publish(e); +} + + +void AssaultWeaponBehaviour::playEmptySound() +{ + if (!IsClient) { + return; + } + + Events::PlaySoundOnEntity e; + e.EmitterID = m_Player.ID; + e.FilePath = "Audio/weapon/zeroAmmo.wav"; + m_EventBroker->Publish(e); +} + +void AssaultWeaponBehaviour::viewPunch() +{ + EntityWrapper playerCamera = m_Player.FirstChildByName("Camera"); + if (!playerCamera.Valid()) { + return; + } + float viewPunch = m_Player["AssaultWeapon"]["ViewPunch"]; + ComponentWrapper cTransform = playerCamera["Transform"]; + glm::vec3& orientation = cTransform["Orientation"]; + orientation.x += viewPunch; +} + +void AssaultWeaponBehaviour::finishReload() +{ + ComponentWrapper& cAssaultWeapon = m_Player["AssaultWeapon"]; + int& magAmmo = cAssaultWeapon["MagazineAmmo"]; + int magSize = cAssaultWeapon["MagazineSize"]; + int& ammo = cAssaultWeapon["Ammo"]; + + // Throw away rounds in magazine to incentivise ammo sharing + int toLoad = glm::min(magSize, ammo); + magAmmo = toLoad; + ammo -= toLoad; + + // Make real first person weapon model visible again + EntityWrapper firstPersonWeaponModel = m_Player.FirstChildByName("WeaponModel"); + if (firstPersonWeaponModel.Valid()) { + firstPersonWeaponModel["Model"]["Visible"] = true; + } + EntityWrapper thirdPersonWeaponModel = m_Player.FirstChildByName("ThirdPersonWeaponModel"); + if (thirdPersonWeaponModel.Valid()) { + thirdPersonWeaponModel["Model"]["Visible"] = true; + } + + m_Reloading = false; +} + +void AssaultWeaponBehaviour::playShootAnimation() +{ + ComponentWrapper cAnimation = m_FirstPersonModel["Animation"]; + if (cAnimation["AnimationName1"] != "ShootRifle") { + cAnimation["AnimationName1"] = "ShootRifle"; + cAnimation["Weight1"] = 1.0; + cAnimation["Time1"] = 0.0; + cAnimation["Speed1"] = 1.0; + cAnimation["Loop1"] = true; + } +} + +void AssaultWeaponBehaviour::playIdleAnimation() +{ + if (!m_FirstPersonModel.Valid()) { + return; + } + + ComponentWrapper cAnimation = m_FirstPersonModel["Animation"]; + std::string& animationName1 = cAnimation["AnimationName1"]; + double& animationSpeed1 = cAnimation["Speed1"]; + + std::string animationToPlay = "Idle"; + double speedToSet = 1.0; + + ComponentWrapper cPlayer = m_Player["Player"]; + glm::vec3 movementDirection = cPlayer["CurrentWishDirection"]; + if (glm::length2(movementDirection) > 0) { + animationToPlay = "Run"; + ComponentWrapper cPhysics = m_Player["Physics"]; + speedToSet = glm::length((glm::vec3)cPhysics["Velocity"]) / (float)cPlayer["MovementSpeed"]; + } + + if (animationName1 != animationToPlay) { + cAnimation["AnimationName1"] = animationToPlay; + cAnimation["Weight1"] = 1.0; + cAnimation["Time1"] = 0.0; + cAnimation["Loop1"] = true; + } + + if (animationSpeed1 != speedToSet) { + cAnimation["Speed1"] = speedToSet; + } +} + +void AssaultWeaponBehaviour::playReloadAnimation() +{ + // Play animation + // First person + if (IsClient) + { + ComponentWrapper cAnimation = m_FirstPersonModel["Animation"]; + cAnimation["AnimationName1"] = "ReloadSwitch"; + cAnimation["Weight1"] = 1.0; + cAnimation["Time1"] = 0.0; + cAnimation["Speed1"] = 0.5; + cAnimation["Loop1"] = true; + } + // TODO: Third person + //{ + // ComponentWrapper cAnimation = m_ThirdPersonModel["Animation"]; + // cAnimation["AnimationName1"] = "ReloadSwitch"; + // cAnimation["Weight1"] = 1.0; + // cAnimation["Time1"] = 0.0; + // cAnimation["Speed1"] = 0.5; + // cAnimation["Loop1"] = true; + //} + + // Hide weapon model and spawn the exploding version + { + EntityWrapper firstPersonWeaponModel = m_Player.FirstChildByName("WeaponModel"); + EntityWrapper reloadSpawner = m_Player.FirstChildByName("FirstPersonReloadSpawner"); + if (IsClient) { + m_FirstPersonReloadImpersonator = SpawnerSystem::Spawn(reloadSpawner, reloadSpawner); + firstPersonWeaponModel["Model"].Copy(m_FirstPersonReloadImpersonator["Model"]); + } + firstPersonWeaponModel["Model"]["Visible"] = false; + } + { + EntityWrapper thirdPersonWeaponModel = m_Player.FirstChildByName("ThirdPersonWeaponModel"); + EntityWrapper reloadSpawner = m_Player.FirstChildByName("ThirdPersonReloadSpawner"); + if (IsClient) { + m_ThirdPersonReloadImpersonator = SpawnerSystem::Spawn(reloadSpawner, reloadSpawner); + thirdPersonWeaponModel["Model"].Copy(m_ThirdPersonReloadImpersonator["Model"]); + } + thirdPersonWeaponModel["Model"]["Visible"] = false; + } +} + +bool AssaultWeaponBehaviour::shoot(double damage) +{ + // Only do shooting clientside + if (!IsClient) { + return false; + } + + // Only handle shooting for the local player + if (m_Player != LocalPlayer) { + return false; + } + + // Make sure the player isn't shooting from the grave + if (!m_Player.Valid()) { + return false; + } + + // Screen center, based on current resolution! + Rectangle screenResolution = m_Renderer->GetViewportSize(); + glm::vec2 centerScreen = glm::vec2(screenResolution.Width / 2, screenResolution.Height / 2); + + // Pick middle of screen + PickData pickData = m_Renderer->Pick(centerScreen); + if (pickData.Entity == EntityID_Invalid) { + return false; + } + + EntityWrapper victim(m_World, pickData.Entity); + if (!victim.Valid()) { + return false; + } + + // Don't let us shoot ourselves in the foot + if (victim == LocalPlayer) { + return false; + } + + // Only care about players being hit + if (!victim.HasComponent("Player")) { + victim = victim.FirstParentWithComponent("Player"); + } + if (!victim.Valid()) { + return false; + } + + // Check for friendly fire + if ((ComponentInfo::EnumType)victim["Team"]["Team"] == (ComponentInfo::EnumType)m_Player["Team"]["Team"]) { + return false; + } + + // Deal damage! + Events::PlayerDamage ePlayerDamage; + ePlayerDamage.Inflictor = m_Player; + ePlayerDamage.Victim = victim; + ePlayerDamage.Damage = damage; + m_EventBroker->Publish(ePlayerDamage); + + return true; +} + +void AssaultWeaponBehaviour::showHitMarker() +{ + // Show hit marker + EntityWrapper hitMarkerSpawner = m_Player.FirstChildByName("HitMarkerSpawner"); + if (hitMarkerSpawner.Valid()) { + SpawnerSystem::Spawn(hitMarkerSpawner, hitMarkerSpawner); + Events::PlaySoundOnEntity e; + e.EmitterID = m_Player.ID; + e.FilePath = "Audio/weapon/hitclick.wav"; + m_EventBroker->Publish(e); + } +} diff --git a/src/Game/Systems/Weapon/WeaponSystem.cpp b/src/Game/Systems/Weapon/WeaponSystem.cpp new file mode 100644 index 00000000..3a49ae90 --- /dev/null +++ b/src/Game/Systems/Weapon/WeaponSystem.cpp @@ -0,0 +1,96 @@ +#include "Systems/Weapon/WeaponSystem.h" + +WeaponSystem::WeaponSystem(SystemParams params, IRenderer* renderer, Octree* collisionOctree) + : System(params) + , PureSystem("Player") + , m_SystemParams(params) + , m_Renderer(renderer) + , m_CollisionOctree(collisionOctree) +{ + EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &WeaponSystem::OnInputCommand); + EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &WeaponSystem::OnPlayerSpawned); +} + +void WeaponSystem::Update(double dt) +{ + +} + +void WeaponSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cPlayer, double dt) +{ + // Update potential weapon behaviour for player + auto it = m_ActiveWeapons.find(entity); + if (it == m_ActiveWeapons.end()) { + selectWeapon(entity, 1); + } + + m_EventBroker->Process(); + m_ActiveWeapons.at(entity)->Update(dt); +} + +bool WeaponSystem::OnInputCommand(Events::InputCommand& e) +{ + EntityWrapper player = e.Player; + if (e.PlayerID == -1) { + player = LocalPlayer; + } + + // Make sure player is alive + if (!player.Valid()) { + return false; + } + + // Weapon selection + if (e.Command == "SelectWeapon") { + if (e.Value != 0) { + //selectWeapon(player, static_cast(e.Value)); + } + } + + // Fire + if (e.Command == "PrimaryFire") { + if (m_ActiveWeapons.find(player) != m_ActiveWeapons.end()) { + auto weapon = m_ActiveWeapons.at(player); + if (e.Value > 0) { + weapon->Fire(); + } else { + weapon->CeaseFire(); + } + } + } + + // Reload + if (e.Command == "Reload" && e.Value != 0) { + if (m_ActiveWeapons.find(player) != m_ActiveWeapons.end()) { + auto weapon = m_ActiveWeapons.at(player); + weapon->Reload(); + } + } + + return true; +} + +void WeaponSystem::selectWeapon(EntityWrapper player, ComponentInfo::EnumType slot) +{ + // Primary + if (slot == 1) { + // TODO: if class... + if (m_ActiveWeapons.count(player) == 0) { + m_ActiveWeapons.insert(std::make_pair(player, std::make_shared(m_SystemParams, m_Renderer, m_CollisionOctree, player))); + } else { + //m_ActiveWeapons.erase(player); + } + } + + // Secondary + if (slot == 2) { + //m_ActiveWeapons[player] = std::make_shared(); + } +} + +bool WeaponSystem::OnPlayerSpawned(Events::PlayerSpawned& e) +{ + // Select primary weapon on player spawn + // TODO: Select the active one specified by player component + return true; +} \ No newline at end of file diff --git a/src/Game/Systems/WeaponSystem.cpp b/src/Game/Systems/WeaponSystem.cpp deleted file mode 100644 index 1613cb7a..00000000 --- a/src/Game/Systems/WeaponSystem.cpp +++ /dev/null @@ -1,141 +0,0 @@ -#include "Systems/WeaponSystem.h" - -WeaponSystem::WeaponSystem(World* world, EventBroker* eventBroker, IRenderer* renderer) - : System(world, eventBroker) - , ImpureSystem() - , m_Renderer(renderer) -{ - EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &WeaponSystem::OnPlayerSpawned); - EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &WeaponSystem::OnInputCommand); - EVENT_SUBSCRIBE_MEMBER(m_EShoot, &WeaponSystem::OnShoot); -} - -void WeaponSystem::Update(double dt) -{ - -} - -bool WeaponSystem::OnPlayerSpawned(const Events::PlayerSpawned& e) -{ - if (e.PlayerID == -1) { - m_LocalPlayer = e.Player; - } - return true; -} - -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) { - eShoot.Player = m_LocalPlayer; - } else { - eShoot.Player = e.Player; - } - m_EventBroker->Publish(eShoot); - } - - return true; -} - -bool WeaponSystem::OnShoot(Events::Shoot& eShoot) -{ - if (!eShoot.Player.Valid()) { - return false; - } - - // TODO: Weapon firing effects here - - auto rayRed = ResourceManager::Load("Schema/Entities/RayRed.xml"); - auto rayBlue = ResourceManager::Load("Schema/Entities/RayBlue.xml"); - - EntityWrapper weapon = eShoot.Player.FirstChildByName("WeaponMuzzle"); - if (weapon.Valid()) { - EntityWrapper ray; - if ((ComponentInfo::EnumType)eShoot.Player["Team"]["Team"] == eShoot.Player["Team"]["Team"].Enum("Red")) { - EntityFileParser parser(rayRed); - EntityID rayID = parser.MergeEntities(m_World); - ray = EntityWrapper(m_World, rayID); - } else { - EntityFileParser parser(rayBlue); - EntityID rayID = parser.MergeEntities(m_World); - ray = EntityWrapper(m_World, rayID); - } - - glm::mat4 transformation = Transform::AbsoluteTransformation(weapon); - glm::vec3 scale; - glm::vec3 translation; - glm::quat orientation; - glm::vec3 skew; - glm::vec4 perspective; - glm::decompose(transformation, scale, orientation, translation, skew, perspective); - - // Matrix to euler angles - glm::vec3 euler; - euler.y = glm::asin(-transformation[0][2]); - if (cos(euler.y) != 0) { - euler.x = atan2(transformation[1][2], transformation[2][2]); - euler.z = atan2(transformation[0][1], transformation[0][0]); - } else { - euler.x = atan2(-transformation[2][0], transformation[1][1]); - euler.z = 0; - } - - //LOG_DEBUG("rotation: %f %f %f", euler.x, euler.y, euler.z); - (glm::vec3&)ray["Transform"]["Position"] = translation; - (glm::vec3&)ray["Transform"]["Orientation"] = euler; - //(glm::vec3&)ray["Transform"]["Orientation"] = Transform::AbsoluteOrientationEuler(weapon); - } - - // Only run further picking code client-side! - if (eShoot.Player != m_LocalPlayer) { - return false; - } - - // 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->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 - - // Pick middle of screen - PickData pickData = m_Renderer->Pick(centerScreen); - if (pickData.Entity == EntityID_Invalid) { - return false; - } - - EntityWrapper player(m_World, pickData.Entity); - - // Only care about players being hit - if (!player.HasComponent("Player")) { - player = player.FirstParentWithComponent("Player"); - } - if (!player.Valid()) { - return false; - } - - // Check for friendly fire - EntityWrapper shooter = eShoot.Player; - if ((ComponentInfo::EnumType)player["Team"]["Team"] == (ComponentInfo::EnumType)shooter["Team"]["Team"]) { - return false; - } - - // TODO: Weapon damage calculations etc - Events::PlayerDamage ePlayerDamage; - ePlayerDamage.Player = player; - ePlayerDamage.Damage = 100; - m_EventBroker->Publish(ePlayerDamage); - - return true; -} diff --git a/src/Game/main.cpp b/src/Game/main.cpp index 613165dd..dd2a5a84 100644 --- a/src/Game/main.cpp +++ b/src/Game/main.cpp @@ -1,11 +1,25 @@ #include "Game.h" +#include "MiniDump.h" + +LONG WINAPI CrashHandler(EXCEPTION_POINTERS* pException); int main(int argc, char* argv[]) { - Game game(argc, argv); - while (game.Running()) { - game.Tick(); - } + ::SetUnhandledExceptionFilter(CrashHandler); + + Game game(argc, argv); + while (game.Running()) { + game.Tick(); + } return 0; +} + +LONG WINAPI CrashHandler(EXCEPTION_POINTERS* pException) +{ + //Take minidump. path should be bin/TacticalZ.dmp + //Then show MessageBox, and exit application. + Create_Dump(pException, 1, 1); + + return EXCEPTION_EXECUTE_HANDLER;// EXCEPTION_CONTINUE_SEARCH } \ No newline at end of file diff --git a/src/Tests/CapturePointTest.cpp b/src/Tests/CapturePointTest.cpp index ffb01030..8a9baf40 100644 --- a/src/Tests/CapturePointTest.cpp +++ b/src/Tests/CapturePointTest.cpp @@ -94,7 +94,7 @@ CapturePointTest::CapturePointTest(int runTestNumber) m_World = new World(); // Create system pipeline - m_SystemPipeline = new SystemPipeline(m_World,m_EventBroker); + m_SystemPipeline = new SystemPipeline(m_World,m_EventBroker, true, false); m_SystemPipeline->AddSystem(0); m_SystemPipeline->AddSystem(1); @@ -255,14 +255,14 @@ void CapturePointTest::TestSetup8() } void CapturePointTest::DoTouchEvent(EntityID whoDidSomething, EntityID onWhatObject) { Events::TriggerTouch touchEvent; - touchEvent.Entity = whoDidSomething; - touchEvent.Trigger = onWhatObject; + touchEvent.Entity = EntityWrapper(m_World, whoDidSomething); + touchEvent.Trigger = EntityWrapper(m_World, onWhatObject); m_EventBroker->Publish(touchEvent); } void CapturePointTest::DoLeaveEvent(EntityID whoDidSomething, EntityID onWhatObject) { Events::TriggerLeave leaveEvent; - leaveEvent.Entity = whoDidSomething; - leaveEvent.Trigger = onWhatObject; + leaveEvent.Entity = EntityWrapper(m_World, whoDidSomething); + leaveEvent.Trigger = EntityWrapper(m_World, onWhatObject); m_EventBroker->Publish(leaveEvent); } void CapturePointTest::TestSuccess1() { diff --git a/src/Tests/CollisionTest.cpp b/src/Tests/CollisionTest.cpp index 67b6ce19..b5ba8245 100644 --- a/src/Tests/CollisionTest.cpp +++ b/src/Tests/CollisionTest.cpp @@ -29,14 +29,14 @@ void RayTest(std::string fileName) { Ray ray(glm::vec3(-50, 0, 0), glm::vec3(1, 0, 0)); //using a - here, else we have to init the renderingsystem + //here, else we have to init the renderingsystem ResourceManager::RegisterType("RawModel"); auto unitBox = ResourceManager::Load(fileName); BOOST_REQUIRE(unitBox != nullptr); - bool hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices); + bool hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); BOOST_CHECK(hit); ray.SetDirection(glm::vec3(-1, 0, 0)); - hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices); + hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); BOOST_CHECK(!hit); } @@ -146,12 +146,12 @@ BOOST_AUTO_TEST_CASE(rayVsModelTest2) z = Collision::RayVsAABB(ray, someAABB); if (z) { //hit - bool hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices); + bool hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices,glm::mat4(1)); if (!hit) { //if rayvsaabb hit but rayvvmodel didnt hit, we get to here - glm::vec3 outtttttttt; - hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices, outtttttttt); - hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices); + glm::mat4 outtttttttt; + hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); + hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); } else { hit = hit; @@ -163,7 +163,7 @@ BOOST_AUTO_TEST_CASE(rayVsModelTest2) // z = z; //} // - bool hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices); + bool hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); ////breakpoint test //if (!hit) { // hit = hit; @@ -175,8 +175,8 @@ BOOST_AUTO_TEST_CASE(rayVsModelTest2) //if rayvsmodel hit but rayvsaabb didnt hit then we get to here z = Collision::RayVsAABB(ray, someAABB); glm::vec3 outtttttttt; - hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices, outtttttttt); - hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices); + hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); + hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); } else { z = z; diff --git a/src/Tests/HealthSystemTest.cpp b/src/Tests/HealthSystemTest.cpp index bdd9ba4b..bf2650a3 100644 --- a/src/Tests/HealthSystemTest.cpp +++ b/src/Tests/HealthSystemTest.cpp @@ -48,42 +48,33 @@ GameHealthSystemTest::GameHealthSystemTest() fp.MergeEntities(m_World); // Create system pipeline - m_SystemPipeline = new SystemPipeline(m_World,m_EventBroker); + m_SystemPipeline = new SystemPipeline(m_World, m_EventBroker, false, false); m_SystemPipeline->AddSystem(0); //The Test //create entity which has transform,player,model,health in it. i.e. is a player EntityID playerID = m_World->CreateEntity(); - ComponentWrapper transform = m_World->AttachComponent(playerID, "Transform"); - ComponentWrapper model = m_World->AttachComponent(playerID, "Model"); - model["Resource"] = "Models/Core/UnitSphere.mesh"; // 360NoScope UnitSphere ComponentWrapper player = m_World->AttachComponent(playerID, "Player"); - ComponentWrapper health = m_World->AttachComponent(playerID, "Health"); - healthsID = playerID; - double currentHealth = (double)m_World->GetComponent(healthsID, "Health")["Health"]; + ComponentWrapper& health = m_World->AttachComponent(playerID, "Health"); + health["Health"] = 100.0; + m_PlayersID = playerID; + + EntityID playerID2 = m_World->CreateEntity(); + ComponentWrapper player2 = m_World->AttachComponent(playerID2, "Player"); + ComponentWrapper health2 = m_World->AttachComponent(playerID2, "Health"); - //heal player with 40 - Events::PlayerHealthPickup e3; - e3.HealthAmount = 40.0f; - e3.PlayerHealedID = healthsID; - m_EventBroker->Publish(e3); //damage player with 50 Events::PlayerDamage e; - e.DamageAmount = 50.0f; - e.PlayerDamagedID = healthsID; + e.Damage = 50.0f; + e.Victim = EntityWrapper(m_World, player.EntityID); m_EventBroker->Publish(e); + //heal some other player with 40 Events::PlayerHealthPickup e2; e2.HealthAmount = 40.0f; - e2.PlayerHealedID = healthsID + 1; + e2.Player = EntityWrapper(m_World, player2.EntityID); m_EventBroker->Publish(e2); - EntityID playerID2 = m_World->CreateEntity(); - ComponentWrapper transform2 = m_World->AttachComponent(playerID2, "Transform"); - ComponentWrapper model2 = m_World->AttachComponent(playerID2, "Model"); - model2["Resource"] = "Models/Core/UnitSphere.mesh"; // 360NoScope UnitSphere - ComponentWrapper player2 = m_World->AttachComponent(playerID2, "Player"); - ComponentWrapper health2 = m_World->AttachComponent(playerID2, "Health"); //END TEST } @@ -107,9 +98,18 @@ void GameHealthSystemTest::Tick() m_EventBroker->Swap(); m_EventBroker->Clear(); - - //if health reaches 90 then we know the test has succeeded (start with 100hp, remove 50hp, add 40hp) - double currentHealth = (double)m_World->GetComponent(healthsID, "Health")["Health"]; - if (currentHealth == 90) + + double currentHealth = (double)m_World->GetComponent(m_PlayersID, "Health")["Health"]; + //if players health reach 50 means he got damaged by 50 + if (currentHealth == 50.0) { + m_TestStage1Success = true; + //heal player with 40 + Events::PlayerHealthPickup e3; + e3.HealthAmount = 40.0f; + e3.Player = EntityWrapper(m_World, m_PlayersID); + m_EventBroker->Publish(e3); + } + if (m_TestStage1Success && currentHealth == 90.0f) { TestSucceeded = true; + } } diff --git a/src/Tests/HealthSystemTest.h b/src/Tests/HealthSystemTest.h index 62c5f55b..275558d2 100644 --- a/src/Tests/HealthSystemTest.h +++ b/src/Tests/HealthSystemTest.h @@ -6,7 +6,6 @@ #include "Core/EventBroker.h" #include "Rendering/Renderer.h" #include "Core/InputManager.h" -#include "GUI/Frame.h" #include "Core/World.h" #include "Input/InputProxy.h" #include "Input/KeyboardInputHandler.h" @@ -31,7 +30,9 @@ private: EventBroker* m_EventBroker; World* m_World; SystemPipeline* m_SystemPipeline; - int healthsID; + int m_PlayersID; + bool m_TestStage1Success = false; + }; #endif diff --git a/src/Tests/PickupSpawnTest.cpp b/src/Tests/PickupSpawnTest.cpp new file mode 100644 index 00000000..4acd897e --- /dev/null +++ b/src/Tests/PickupSpawnTest.cpp @@ -0,0 +1,214 @@ +#include +using boost::unit_test_framework::test_suite; +using boost::unit_test_framework::test_case; + +#include "PickupSpawnTest.h" + +BOOST_AUTO_TEST_SUITE(PickupSpawnTestSuite) + +//dont use the same name as the classname in test cases... +BOOST_AUTO_TEST_CASE(PickupSpawnTest_HealthPickupRespawns_PlayerHealthPickupEventTriggers) +{ + PickupSpawnTest game(1); + bool success = game.Game_Loop_OneHundredTimes(); + BOOST_TEST(success); +} +BOOST_AUTO_TEST_CASE(PickupSpawnTest_APlayerAtMaxHealth_CantTakeHealthPickup) +{ + PickupSpawnTest game(2); + bool success = game.Game_Loop_OneHundredTimes(); + BOOST_TEST(success); +} +BOOST_AUTO_TEST_CASE(PickupSpawnTest_APickupCanRespawnSlowly) +{ + PickupSpawnTest game(3); + bool success = game.Game_Loop_OneHundredTimes(); + BOOST_TEST(success); +} +BOOST_AUTO_TEST_SUITE_END() + +PickupSpawnTest::PickupSpawnTest(int runTestNumber) +{ + ResourceManager::RegisterType("ConfigFile"); + ResourceManager::RegisterType("EntityFile"); + + m_Config = ResourceManager::Load("Config.ini"); + LOG_LEVEL = static_cast<_LOG_LEVEL>(m_Config->Get("Debug.LogLevel", 1)); + + m_EventBroker = new EventBroker(); + m_World = new World(); + + // Create system pipeline + m_SystemPipeline = new SystemPipeline(m_World, m_EventBroker, false, false); + m_SystemPipeline->AddSystem(0); + m_SystemPipeline->AddSystem(1); + + //must register components (Components.xsd), else you cant create entities. Easiest done by loading a test xsd file + auto file = ResourceManager::Load("Schema/Entities/HealthPickup.xml"); + EntityFilePreprocessor fpp(file); + fpp.RegisterComponents(m_World); + EntityFileParser fp(file); + //connect the healthpickup to the world + m_HealthPickupID = fp.MergeEntities(m_World); + + //create a player + m_PlayerID = m_World->CreateEntity(); + auto& player = m_World->AttachComponent(m_PlayerID, "Player"); + + m_RunTestNumber = runTestNumber; + + //further testsetups + TestSetup(m_RunTestNumber); + + //init glfw so dt works + glfwInit(); + + //listen to the 2 events that are related to PickupSpawn + EVENT_SUBSCRIBE_MEMBER(m_HP, &PickupSpawnTest::OnHealthPickup); + EVENT_SUBSCRIBE_MEMBER(m_PS, &PickupSpawnTest::OnPickupSpawned); +} + +bool PickupSpawnTest::OnHealthPickup(Events::PlayerHealthPickup& e) { + switch (m_RunTestNumber) + { + case 1: + //verify that the event has the correct healthgain number and playerid + if (e.HealthAmount == 22.0 && e.Player.ID == m_PlayerID) { + m_TestStage1Success = true; + } + break; + case 2: + m_TestStage1Success = false; + break; + case 3: + //verify that the event has the correct healthgain number and playerid + if (e.HealthAmount == 50.0 && e.Player.ID == m_PlayerID) { + m_TestStage1Success = true; + } + break; + } + return true; +} +bool PickupSpawnTest::OnPickupSpawned(Events::PickupSpawned& e) { + switch (m_RunTestNumber) + { + case 1: + //verify that the newly spawned pickup has the same variable values as the original one + if ((double)e.Pickup["HealthPickup"]["HealthGain"] == 22.0 && (double)e.Pickup["HealthPickup"]["RespawnTimer"] == 2.0) { + m_TestStage2Success = true; + } + break; + case 2: + m_TestStage2Success = false; + break; + case 3: + m_TestStage2Success = false; + break; + } + return true; +} + +void PickupSpawnTest::TestSetup(int testNumber) +{ + switch (m_RunTestNumber) + { + case 1: + { + //PickupSpawnTest_HealthPickupRespawns_PlayerHealthPickupEventTriggers + auto& healthPickupEW = EntityWrapper(m_World, m_HealthPickupID); + healthPickupEW["HealthPickup"]["RespawnTimer"] = 2.0; + healthPickupEW["HealthPickup"]["HealthGain"] = 22.0; + + //create a player + auto& health = m_World->AttachComponent(m_PlayerID, "Health"); + health["Health"] = 20.0; + health["MaxHealth"] = 100.0; + } + break; + case 2: + { + //PickupSpawnTest_APlayerAtMaxHealth_CantTakeHealthPickup + auto& healthPickupEW = EntityWrapper(m_World, m_HealthPickupID); + healthPickupEW["HealthPickup"]["RespawnTimer"] = 1.0; + healthPickupEW["HealthPickup"]["HealthGain"] = 50.0; + + //create a player at max health + auto& health = m_World->AttachComponent(m_PlayerID, "Health"); + health["Health"] = 100.0; + health["MaxHealth"] = 100.0; + } + break; + case 3: + { + //PickupSpawnTest_APickupCanRespawnSlowly + auto& healthPickupEW = EntityWrapper(m_World, m_HealthPickupID); + healthPickupEW["HealthPickup"]["RespawnTimer"] = 100.0; + healthPickupEW["HealthPickup"]["HealthGain"] = 50.0; + + //create a player + auto& health = m_World->AttachComponent(m_PlayerID, "Health"); + health["Health"] = 1.0; + health["MaxHealth"] = 100.0; + } + break; + default: + break; + } + //do the triggerTouch event to get the pickupSpawnTest started + Events::TriggerTouch eTriggerTouch; + DoTouchEvent(m_PlayerID, m_HealthPickupID); +} + +//generic stuff +void PickupSpawnTest::Tick() +{ + glfwPollEvents(); + + //just set dt to 1.0 since we want fast testing + double dt = 1.0; + + // Iterate through systems and update world! + m_SystemPipeline->Update(dt); + + m_EventBroker->Swap(); + m_EventBroker->Clear(); + + //verify that healthgain event has been published and pickup has respawned + if (m_RunTestNumber == 1 && m_TestStage1Success && m_TestStage2Success) { + m_TestSucceeded = true; + } + //verify that no healthgain event has been published and that no pickup has respawned + if (m_NumLoops > 90 && m_RunTestNumber == 2 && !m_TestStage1Success && !m_TestStage2Success) { + m_TestSucceeded = true; + } + //3: verify that the pickup hasnt spawned + if (m_NumLoops > 90 && m_RunTestNumber == 3 && m_TestStage1Success && !m_TestStage2Success) { + m_TestSucceeded = true; + } +} +bool PickupSpawnTest::Game_Loop_OneHundredTimes() { + //100 loops will be more than enough to do the test + int loops = 100; + bool success = false; + while (loops > 0) { + Tick(); + m_NumLoops++; + if (m_TestSucceeded) { + success = true; + break; + } + loops--; + } + return success; +} +PickupSpawnTest::~PickupSpawnTest() +{ + delete m_SystemPipeline; + delete m_World; +} +void PickupSpawnTest::DoTouchEvent(EntityID whoDidSomething, EntityID onWhatObject) { + Events::TriggerTouch touchEvent; + touchEvent.Entity = EntityWrapper(m_World, whoDidSomething); + touchEvent.Trigger = EntityWrapper(m_World, onWhatObject); + m_EventBroker->Publish(touchEvent); +} diff --git a/src/Tests/PickupSpawnTest.h b/src/Tests/PickupSpawnTest.h new file mode 100644 index 00000000..b9d5483a --- /dev/null +++ b/src/Tests/PickupSpawnTest.h @@ -0,0 +1,72 @@ +#ifndef PickupSpawnTest_h__ +#define PickupSpawnTest_h__ + +#include "Core/ResourceManager.h" +#include "Core/ConfigFile.h" +#include "Core/EventBroker.h" +#include "Core/World.h" +#include "Input/InputProxy.h" +#include "Input/KeyboardInputHandler.h" +#include "Input/MouseInputHandler.h" +#include "Core/EKeyDown.h" +#include "Core/EntityFile.h" +#include "Core/SystemPipeline.h" + +#include "Core/EntityFilePreprocessor.h" +#include "Core/EntityFileParser.h" +#include "Core/EntityFileWriter.h" + +#include "Engine/Collision/ETrigger.h" + +//#include "Core/System.h" +//#include "Core/Transform.h" +//#include "Core/ResourceManager.h" +//#include "Core/EntityFileParser.h" +//#include "Core/EPickupSpawned.h" +//#include "Core/EPlayerHealthPickup.h" +#include "Engine/Collision/ETrigger.h" +//#include "Common.h" +//#include +#include "Collision/TriggerSystem.h" +#include "Collision/CollisionSystem.h" +#include "Core/EntityFileWriter.h" +#include "Game/Systems/HealthSystem.h" +#include "Game/Systems/PickupSpawnSystem.h" + +#include "Core/ResourceManager.h" + +class PickupSpawnTest +{ +public: + PickupSpawnTest(int runTestNumber); + ~PickupSpawnTest(); + + void Tick(); + + bool Game_Loop_OneHundredTimes(); + void TestSetup(int testNumber); + void DoTouchEvent(EntityID whoDidSomething, EntityID onWhatObject); + +private: + double m_LastTime; + ConfigFile* m_Config = nullptr; + EventBroker* m_EventBroker; + World* m_World; + SystemPipeline* m_SystemPipeline; + EntityID m_PlayerID, m_HealthPickupID; + int m_RunTestNumber; + + EventRelay m_HP; + bool OnHealthPickup(Events::PlayerHealthPickup& e); + EventRelay m_PS; + bool OnPickupSpawned(Events::PickupSpawned& e); + + bool m_TestStage1Success = false; + bool m_TestStage2Success = false; + + bool m_TestSucceeded = false; + int m_NumLoops = 0; + +}; + +#endif diff --git a/src/Tests/WorldTest.cpp b/src/Tests/WorldTest.cpp index 03008562..633e617a 100644 --- a/src/Tests/WorldTest.cpp +++ b/src/Tests/WorldTest.cpp @@ -69,3 +69,47 @@ BOOST_AUTO_TEST_CASE(WorldTestMultipleAllocations, * utf::tolerance(0.00001)) i++; } } + +BOOST_AUTO_TEST_CASE(WorldCopy, *utf::tolerance(0.00001)) +{ + World w1; + + // Create a test component + auto testComponent = ComponentWrapperFactory("Test", 2); + testComponent.AddProperty("TestInteger", 1337); + testComponent.AddProperty("TestDouble", 13.37); + testComponent.AddProperty("TestString", std::string("DefaultString")); + testComponent.AddProperty("TestVec3", glm::vec3(1.f, 2.f, 3.f)); + w1.RegisterComponent(testComponent); + + // Create a test entity + EntityID w1_e1 = w1.CreateEntity(); + auto w1_c1 = w1.AttachComponent(w1_e1, "Test"); + + // Create a child + EntityID w1_e2 = w1.CreateEntity(w1_e1); + auto w1_c2 = w1.AttachComponent(w1_e2, "Test"); + w1_c2["TestString"] = "NonDefaultString"; + + // Copy the world! + World w2 = w1; + + // Fetch the components + auto w2_c1 = w2.GetComponent(w1_e1, "Test"); + auto w2_c2 = w2.GetComponent(w1_e2, "Test"); + + // Check that built-in types are copied but don't reside in the same memory + BOOST_CHECK((int)w1_c1["TestInteger"] == (int)w2_c1["TestInteger"]); + BOOST_CHECK(&(int&)w1_c1["TestInteger"] != &(int&)w2_c1["TestInteger"]); + BOOST_CHECK((double)w1_c1["TestDouble"] == (double)w2_c1["TestDouble"]); + BOOST_CHECK(&(int&)w1_c1["TestDouble"] != &(int&)w2_c1["TestDouble"]); + BOOST_CHECK((int)w1_c2["TestInteger"] == (int)w2_c2["TestInteger"]); + BOOST_CHECK(&(int&)w1_c2["TestInteger"] != &(int&)w2_c2["TestInteger"]); + BOOST_CHECK((double)w1_c2["TestDouble"] == (double)w2_c2["TestDouble"]); + BOOST_CHECK(&(int&)w1_c2["TestDouble"] != &(int&)w2_c2["TestDouble"]); + // Check that specially handled strings are fine + BOOST_CHECK((std::string)w1_c1["TestString"] == (std::string)w2_c1["TestString"]); + BOOST_CHECK(&(std::string&)w1_c1["TestString"] != &(std::string&)w2_c1["TestString"]); + BOOST_CHECK((std::string)w1_c2["TestString"] == (std::string)w2_c2["TestString"]); + BOOST_CHECK(&(std::string&)w1_c2["TestString"] != &(std::string&)w2_c2["TestString"]); +} diff --git a/tools/MayaExporter/MayaExporter/Export.cpp b/tools/MayaExporter/MayaExporter/Export.cpp index d8f1abd4..3497fd04 100644 --- a/tools/MayaExporter/MayaExporter/Export.cpp +++ b/tools/MayaExporter/MayaExporter/Export.cpp @@ -47,13 +47,24 @@ bool Export::Meshes(std::string pathName, bool selectedOnly) for (unsigned int i = 0; i < connections.length(); i++) { if (connections[i].node().apiType() == MFn::kSkinClusterFilter) { - MGlobal::select(shape.parent(i), MGlobal::kReplaceList); - MGlobal::displayInfo(MString() + "Moving " + thisNode.name() + " to bindPose."); + shape.parent(0, &status); + if (status != MS::kSuccess) { + MGlobal::displayError(MString() + "shape.parent(0, &status) failed with: " + status.errorString()); + } + status = MGlobal::select(shape.parent(0), MGlobal::kReplaceList); + if (status != MS::kSuccess) { + MGlobal::displayError(MString() + "Parent to " + thisNode.name() + " failed"); + } + + MFnDependencyNode tmp(shape.parent(0)); + MGlobal::displayInfo(MString() + "Moving " + tmp.name() + " to bindPose."); + status = MGlobal::executeCommand("GoToBindPose;"); if (status != MS::kSuccess) { MGlobal::displayError(MString() + "GoToBindPose: " + status.errorString()); } - MGlobal::displayInfo(MString() + "Has moved " + thisNode.name() + " to bindPose."); + + MGlobal::displayInfo(MString() + "Has moved " + tmp.name() + " to bindPose."); } } } @@ -109,6 +120,8 @@ bool Export::Materials(std::string pathName) bool Export::Animations(std::string pathName, std::vector animInfo) { + allAnimations.clear(); + allBindPoses.clear(); if (MAnimControl::currentTime().unit() != MTime::kNTSCField) { MGlobal::displayError(MString() + "Please change to 60 FPS under Preferences/Settings!"); diff --git a/tools/MayaExporter/MayaExporter/Material.cpp b/tools/MayaExporter/MayaExporter/Material.cpp index 03521231..a5717aa6 100644 --- a/tools/MayaExporter/MayaExporter/Material.cpp +++ b/tools/MayaExporter/MayaExporter/Material.cpp @@ -82,16 +82,36 @@ bool Material::findColorTexture(MaterialNode& material_node, MFnDependencyNode& workspace); FullPath = FullPath.substr(workspace.length()); FullPath = FullPath.substr(FullPath.find_first_of("/") + 1); - material_node.ColorMapFile = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); - material_node.ColorMapFileLength = material_node.ColorMapFile.length() + 1; - // Test - MGlobal::displayInfo(MString() + "getAbsolutePathToResources: " + workspace); - MGlobal::displayInfo(MString() + "Texture file: " + FullPath.c_str()); + MaterialNode::Texture newTexture; + + newTexture.FileName = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); + newTexture.FileNameLength = newTexture.FileName.length() + 1; + + MPlug uvRepeatFile = TextureNode.findPlug("repeatUV"); + + uvRepeatFile.connectedTo(AllConnections, true, false); + + for (int i = 0; i < AllConnections.length(); i++) { + if (AllConnections[i].node().hasFn(MFn::kPlace2dTexture)) { + MFnDependencyNode place2DTexture(AllConnections[i].node()); + MPlug uvRepeat = place2DTexture.findPlug("repeatUV"); + + newTexture.UVTiling[0] = uvRepeat.child(0).asFloat(); + newTexture.UVTiling[1] = uvRepeat.child(1).asFloat(); + } + } + + material_node.ColorMaps.push_back(newTexture); + if(material_node.type == MaterialNode::MaterialType::Basic) + material_node.type = MaterialNode::MaterialType::SingleTextures; return true; + + } else if (AllConnections[i].node().hasFn(MFn::kLayeredTexture)) { + MGlobal::displayInfo(MString() + "find splat map"); + return findSplatTextures(material_node, material_node.ColorMaps, MFnDependencyNode(AllConnections[i].node())); } } - return false; } @@ -120,9 +140,31 @@ bool Material::findNormalTexture(MaterialNode& material_node, MFnDependencyNode& workspace); FullPath = FullPath.substr(workspace.length()); FullPath = FullPath.substr(FullPath.find_first_of("/") + 1); - material_node.NormalMapFile = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); - material_node.NormalMapFileLength = material_node.NormalMapFile.length() + 1; + + MaterialNode::Texture newTexture; + + newTexture.FileName = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); + newTexture.FileNameLength = newTexture.FileName.length() + 1; + + MPlug uvRepeatFile = TextureNode.findPlug("repeatUV"); + + uvRepeatFile.connectedTo(AllConnections, true, false); + + for (int i = 0; i < AllConnections.length(); i++) { + if (AllConnections[i].node().hasFn(MFn::kPlace2dTexture)) { + MFnDependencyNode place2DTexture(AllConnections[i].node()); + MPlug uvRepeat = place2DTexture.findPlug("repeatUV"); + + newTexture.UVTiling[0] = uvRepeat.child(0).asFloat(); + newTexture.UVTiling[1] = uvRepeat.child(1).asFloat(); + } + } + + material_node.NormalMaps.push_back(newTexture); return true; + } else if (AllConnections[i].node().hasFn(MFn::kLayeredTexture)) { + MGlobal::displayInfo(MString() + "find splat map"); + return findSplatTextures(material_node, material_node.NormalMaps, MFnDependencyNode(AllConnections[i].node())); } } } @@ -150,9 +192,34 @@ bool Material::findSpecularTexture(MaterialNode& material_node, MFnDependencyNod workspace); FullPath = FullPath.substr(workspace.length()); FullPath = FullPath.substr(FullPath.find_first_of("/") + 1); - material_node.SpecularMapFile = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); - material_node.SpecularMapFileLength = material_node.SpecularMapFile.length() + 1; + + MaterialNode::Texture newTexture; + + newTexture.FileName = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); + newTexture.FileNameLength = newTexture.FileName.length() + 1; + + MPlug uvRepeatFile = TextureNode.findPlug("repeatUV"); + + uvRepeatFile.connectedTo(AllConnections, true, false); + + for (int i = 0; i < AllConnections.length(); i++) { + if (AllConnections[i].node().hasFn(MFn::kPlace2dTexture)) { + //C:\Users\kamisama\Desktop\TacticalZ\assets\test + MFnDependencyNode place2DTexture(AllConnections[i].node()); + MPlug uvRepeat = place2DTexture.findPlug("repeatUV"); + + newTexture.UVTiling[0] = uvRepeat.child(0).asFloat(); + newTexture.UVTiling[1] = uvRepeat.child(1).asFloat(); + } + } + + material_node.SpecularMaps.push_back(newTexture); + if (material_node.type == MaterialNode::MaterialType::Basic) + material_node.type = MaterialNode::MaterialType::SingleTextures; return true; + } else if (AllConnections[i].node().hasFn(MFn::kLayeredTexture)) { + MGlobal::displayInfo(MString() + "find splat map"); + return findSplatTextures(material_node, material_node.SpecularMaps, MFnDependencyNode(AllConnections[i].node())); } } return false; @@ -168,7 +235,7 @@ bool Material::findIncandescenceTexture(MaterialNode& material_node, MFnDependen for (int i = 0; i < AllConnections.length(); i++) { if (AllConnections[i].node().hasFn(MFn::kFileTexture)) { MFnDependencyNode TextureNode(AllConnections[i].node()); - + std::string FullPath = TextureNode.findPlug("ftn").asString().asChar(); m_TexturePaths.push_back(FullPath); @@ -177,14 +244,141 @@ bool Material::findIncandescenceTexture(MaterialNode& material_node, MFnDependen workspace); FullPath = FullPath.substr(workspace.length()); FullPath = FullPath.substr(FullPath.find_first_of("/") + 1); - material_node.IncandescenceMapFile = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); - material_node.IncandescenceMapFileLength = material_node.IncandescenceMapFile.length() + 1; + + MaterialNode::Texture newTexture; + + newTexture.FileName = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); + newTexture.FileNameLength = newTexture.FileName.length() + 1; + + MPlug uvRepeatFile = TextureNode.findPlug("repeatUV"); + + uvRepeatFile.connectedTo(AllConnections, true, false); + + for (int i = 0; i < AllConnections.length(); i++) { + if (AllConnections[i].node().hasFn(MFn::kPlace2dTexture)) { + MFnDependencyNode place2DTexture(AllConnections[i].node()); + MPlug uvRepeat = place2DTexture.findPlug("repeatUV"); + + newTexture.UVTiling[0] = uvRepeat.child(0).asFloat(); + newTexture.UVTiling[1] = uvRepeat.child(1).asFloat(); + } + } + + material_node.IncandescenceMaps.push_back(newTexture); + if (material_node.type == MaterialNode::MaterialType::Basic) + material_node.type = MaterialNode::MaterialType::SingleTextures; return true; + + } else if (AllConnections[i].node().hasFn(MFn::kLayeredTexture)) { + MGlobal::displayInfo(MString() + "find splat map"); + return findSplatTextures(material_node, material_node.IncandescenceMaps, MFnDependencyNode(AllConnections[i].node())); } } return false; } +//C:\Users\kamisama\Desktop\TacticalZ\assets\test + +bool Material::findSplatTextures(MaterialNode& material_node, std::vector& textureVector, MFnDependencyNode& node) { + //Get all Inputs in LayeredTexture + MPlug inputs = node.findPlug("inputs"); + MGlobal::displayInfo(MString() + "inputs.numElements(): " + inputs.numElements()); + + MPlugArray AllConnections; + MStatus test; + //Try to find splat texture if using custom splatmap build up. + inputs[0].child(1).connectedTo(AllConnections, true, false); + for (int i = 0; i < AllConnections.length(); i++) { + if (AllConnections[i].node().hasFn(MFn::kMultiplyDivide)) { + MGlobal::displayInfo(MString() + "found kMultiplyDivide"); + MFnDependencyNode multiplyDivide(AllConnections[i].node()); + multiplyDivide.findPlug("input1", &test).child(0).connectedTo(AllConnections, true, false);; + for (int i = 0; i < AllConnections.length(); i++) { + if (AllConnections[i].node().hasFn(MFn::kFileTexture)) { + MFnDependencyNode TextureNode(AllConnections[i].node()); + + std::string FullPath = TextureNode.findPlug("ftn").asString().asChar(); + m_TexturePaths.push_back(FullPath); + + MString workspace; + MStatus status = MGlobal::executeCommand(MString("workspace -q -rd;"), + workspace); + FullPath = FullPath.substr(workspace.length()); + FullPath = FullPath.substr(FullPath.find_first_of("/") + 1); + + MaterialNode::Texture newTexture; + + newTexture.FileName = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); + newTexture.FileNameLength = newTexture.FileName.length() + 1; + + MPlug uvRepeatFile = TextureNode.findPlug("repeatUV"); + + uvRepeatFile.connectedTo(AllConnections, true, false); + + for (int i = 0; i < AllConnections.length(); i++) { + if (AllConnections[i].node().hasFn(MFn::kPlace2dTexture)) { + MFnDependencyNode place2DTexture(AllConnections[i].node()); + MPlug uvRepeat = place2DTexture.findPlug("repeatUV"); + + newTexture.UVTiling[0] = uvRepeat.child(0).asFloat(); + newTexture.UVTiling[1] = uvRepeat.child(1).asFloat(); + } + } + material_node.SplatMap = newTexture; + material_node.type = MaterialNode::MaterialType::SplatMapping; + } + } + } + } + + for (unsigned int i = 0; i < inputs.numElements(); i++) { + //Get connections to color in input[i] + inputs[i].child(0).connectedTo(AllConnections, true, false); + + for (int i = 0; i < AllConnections.length(); i++) { + if (AllConnections[i].node().hasFn(MFn::kFileTexture)) { + MFnDependencyNode TextureNode(AllConnections[i].node()); + + std::string FullPath = TextureNode.findPlug("ftn").asString().asChar(); + m_TexturePaths.push_back(FullPath); + + MString workspace; + MStatus status = MGlobal::executeCommand(MString("workspace -q -rd;"), + workspace); + FullPath = FullPath.substr(workspace.length()); + FullPath = FullPath.substr(FullPath.find_first_of("/") + 1); + + MaterialNode::Texture newTexture; + + newTexture.FileName = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); + newTexture.FileNameLength = newTexture.FileName.length() + 1; + + MPlug uvRepeatFile = TextureNode.findPlug("repeatUV"); + + uvRepeatFile.connectedTo(AllConnections, true, false); + + for (int i = 0; i < AllConnections.length(); i++) { + if (AllConnections[i].node().hasFn(MFn::kPlace2dTexture)) { + MFnDependencyNode place2DTexture(AllConnections[i].node()); + MPlug uvRepeat = place2DTexture.findPlug("repeatUV"); + + newTexture.UVTiling[0] = uvRepeat.child(0).asFloat(); + newTexture.UVTiling[1] = uvRepeat.child(1).asFloat(); + } + } + textureVector.push_back(newTexture); + break; + } + } + if (AllConnections.length() == 0) { + MaterialNode::Texture newTexture; + newTexture.FileNameLength = 0; + textureVector.push_back(newTexture); + } + } + return true; +} + // Returns the absolute path for all textures. Use for copying texture files. std::vector* Material::TexturePaths() { @@ -209,7 +403,6 @@ std::vector* Material::DoIt(Mesh mesh) meshHasMaterial = true; MaterialStorage.IndexStart = totalIndices; MaterialStorage.IndexEnd = totalIndices + aMeshMaterial.second.size() - 1; - break; } totalIndices += aMeshMaterial.second.size(); } @@ -226,7 +419,10 @@ std::vector* Material::DoIt(Mesh mesh) MaterialStorage.ReflectionFactor = 0.0f; MaterialStorage.SpecularExponent = 0.0f; } - + MaterialStorage.NumColorMaps = MaterialStorage.ColorMaps.size(); + MaterialStorage.NumNormalMaps = MaterialStorage.NormalMaps.size(); + MaterialStorage.NumSpecularMaps = MaterialStorage.SpecularMaps.size(); + MaterialStorage.NumIncandescenceMaps = MaterialStorage.IncandescenceMaps.size(); m_AllMaterials.push_back(MaterialStorage); } matIt.next(); diff --git a/tools/MayaExporter/MayaExporter/Material.h b/tools/MayaExporter/MayaExporter/Material.h index e405dd07..d70a6399 100644 --- a/tools/MayaExporter/MayaExporter/Material.h +++ b/tools/MayaExporter/MayaExporter/Material.h @@ -11,62 +11,123 @@ #include "OutputData.h" #include "Mesh.h" + +//#define ColorMapSplat 1 +//#define SpecularMapSplat 1 << 1 +//#define NormalMapSplat 1 << 2 +//#define IncandescenceMapSplat 1 << 3 + + + class MaterialNode : public OutputData { public: + class Texture : public OutputData { + public: + unsigned int FileNameLength = 0; + std::string FileName; + float UVTiling[2]{ 1.0f, 1.0f }; + + virtual void WriteBinary(std::ostream& out) + { + out.write((char*)&FileNameLength, sizeof(unsigned int)); + out.write(FileName.c_str(), FileNameLength); + out.write((char*)&UVTiling, sizeof(float) * 2); + } + + virtual void WriteASCII(std::ostream& out) const + { + out << "FileNameLength: " << FileNameLength << endl; + out << "FileName: " << FileName << endl; + out << "UV tiling: " << UVTiling[0] << " " << UVTiling[1] << endl; + } + }; + + enum class MaterialType { Basic = 1, SplatMapping, SingleTextures }; + + MaterialType type = MaterialType::Basic; + std::string Name; float ReflectionFactor; float SpecularExponent; - float DiffuseColor[3]{ 1.0f, 1.0f, 1.0f }; - unsigned int ColorMapFileLength = 0; - std::string ColorMapFile; + float DiffuseColor[3]{ 1.0f, 1.0f, 1.0f }; + float SpecularColor[3]{ 1.0f, 1.0f, 1.0f }; + float IncandescenceColor[3]{ 1.0f, 1.0f, 1.0f }; - float SpecularColor[3]{ 1.0f, 1.0f, 1.0f }; - unsigned int SpecularMapFileLength = 0; - std::string SpecularMapFile; + unsigned int IndexStart; + unsigned int IndexEnd; - unsigned int NormalMapFileLength = 0; - std::string NormalMapFile; - - float IncandescenceColor[3]{ 1.0f, 1.0f, 1.0f }; - unsigned int IncandescenceMapFileLength = 0; - std::string IncandescenceMapFile; - - unsigned int IndexStart; - unsigned int IndexEnd; + unsigned char NumColorMaps = 0; + unsigned char NumSpecularMaps = 0; + unsigned char NumNormalMaps = 0; + unsigned char NumIncandescenceMaps = 0; + Texture SplatMap; + std::vector ColorMaps; + std::vector SpecularMaps; + std::vector NormalMaps; + std::vector IncandescenceMaps; virtual void WriteBinary(std::ostream& out) { - out.write((char*)&ColorMapFileLength, sizeof(unsigned int)); - out.write((char*)&NormalMapFileLength, sizeof(unsigned int)); - out.write((char*)&SpecularMapFileLength, sizeof(unsigned int)); - out.write((char*)&IncandescenceMapFileLength, sizeof(unsigned int)); - + + out.write((char*)&type, sizeof(MaterialType)); out.write((char*)&SpecularExponent, sizeof(float)); out.write((char*)&ReflectionFactor, sizeof(float)); + out.write((char*)&DiffuseColor, sizeof(float) * 3); out.write((char*)&SpecularColor, sizeof(float) * 3); out.write((char*)&IncandescenceColor, sizeof(float) * 3); + out.write((char*)&IndexStart, sizeof(unsigned int)); out.write((char*)&IndexEnd, sizeof(unsigned int)); + if (type != MaterialType::Basic) { + if (type == MaterialType::SplatMapping) { + SplatMap.WriteBinary(out); + } + out.write((char*)&NumColorMaps, sizeof(unsigned char)); + out.write((char*)&NumSpecularMaps, sizeof(unsigned char)); + out.write((char*)&NumNormalMaps, sizeof(unsigned char)); + out.write((char*)&NumIncandescenceMaps, sizeof(unsigned char)); + } - out.write(ColorMapFile.c_str(), ColorMapFileLength); - out.write(NormalMapFile.c_str(), NormalMapFileLength); - out.write(SpecularMapFile.c_str(), SpecularMapFileLength); - out.write(IncandescenceMapFile.c_str(), IncandescenceMapFileLength); + if (type != MaterialType::Basic) { + for (auto aTexture : ColorMaps) { + aTexture.WriteBinary(out); + } + for (auto aTexture : SpecularMaps) { + aTexture.WriteBinary(out); + } + for (auto aTexture : NormalMaps) { + aTexture.WriteBinary(out); + } + for (auto aTexture : IncandescenceMaps) { + aTexture.WriteBinary(out); + } + } } virtual void WriteASCII(std::ostream& out) const { out << "New Material _ not in binary" << endl; - out << "number of indices: " << Name << " _ not in binary" << endl; - out << "ColorMapFile length: " << ColorMapFileLength << endl; - out << "NormalMapFile length: " << NormalMapFileLength << endl; - out << "SpecularMapFile length: " << SpecularMapFileLength << endl; - out << "IncandescenceMapFile length: " << IncandescenceMapFileLength << endl; + out << "MaterialType(enum): "; + switch (type) { + case MaterialType::Basic: + out << "Basic"; + break; + case MaterialType::SplatMapping: + out << "SplatMapping"; + break; + case MaterialType::SingleTextures: + out << "SingleTextures"; + break; + }; + + out << endl; + + out << "Material Name: " << Name << " _ not in binary" << endl; out << "SpecularExponent: " << SpecularExponent << endl; out << "ReflectionFactor: " << ReflectionFactor << endl; @@ -76,17 +137,38 @@ public: out << "IndexStart: " << IndexStart << endl; out << "IndexEnd: " << IndexEnd << endl; - if (ColorMapFileLength > 0) - out << "ColorMapFile: " << ColorMapFile << endl; + switch (type) { + case MaterialType::SplatMapping: + out << "SplatMap _ not in binary " << endl; + SplatMap.WriteASCII(out); + //Intended fall trought + case MaterialType::SingleTextures: + out << "NumColormaps (is unsigned char in Binary): " << ((unsigned int)NumColorMaps) << endl; + out << "NumSpecularMap (is unsigned char in Binary): " << ((unsigned int)NumSpecularMaps) << endl; + out << "NumNormalMap (is unsigned char in Binary): " << ((unsigned int)NumNormalMaps) << endl; + out << "NumIncandescenceMap (is unsigned char in Binary): " << ((unsigned int)NumIncandescenceMaps )<< endl; - if (NormalMapFileLength > 0) - out << "NormalMapFile: " << NormalMapFile << endl; - - if (SpecularMapFileLength > 0) - out << "SpecularMapFile: " << SpecularMapFile << endl; - - if (IncandescenceMapFileLength > 0) - out << "IncandescenceMapFile: " << IncandescenceMapFile << endl; + out << "ColorMaps _ not in binary " << endl; + for (auto aTexture : ColorMaps) { + aTexture.WriteASCII(out); + } + + out << "SpecularMaps _ not in binary " << endl; + for (auto aTexture : SpecularMaps) { + aTexture.WriteASCII(out); + } + + out << "NormalMaps _ not in binary " << endl; + for (auto aTexture : NormalMaps) { + aTexture.WriteASCII(out); + } + + out << "IncandescenceMaps _ not in binary " << endl; + for (auto aTexture : IncandescenceMaps) { + aTexture.WriteASCII(out); + } + break; + }; } }; @@ -107,6 +189,7 @@ private: bool findNormalTexture(MaterialNode& material_node, MFnDependencyNode& node); bool findSpecularTexture(MaterialNode& material_node, MFnDependencyNode& node); bool findIncandescenceTexture(MaterialNode& material_node, MFnDependencyNode& node); + bool findSplatTextures(MaterialNode& material_node, std::vector& textureVector, MFnDependencyNode& node); void grabLambertProperties(MaterialNode& material_node, MFnDependencyNode& node); void grabBlinnProperties(MaterialNode& material_node, MFnDependencyNode& node); void grabPhongProperties(MaterialNode& material_node, MFnDependencyNode& node); diff --git a/tools/MayaExporter/MayaExporter/MayaExporter.vcxproj b/tools/MayaExporter/MayaExporter/MayaExporter.vcxproj index 4a7ac07e..b9384a45 100644 --- a/tools/MayaExporter/MayaExporter/MayaExporter.vcxproj +++ b/tools/MayaExporter/MayaExporter/MayaExporter.vcxproj @@ -40,8 +40,9 @@ v140 - Application + DynamicLibrary v140 + Unicode @@ -77,6 +78,7 @@ $(SolutionDir)$(Platform)\$(Configuration)\ + .mll @@ -135,7 +137,7 @@ NDEBUG;QT_DLL;QT_NO_DEBUG;QT_NO_IMPORT_QT47_QML;UNICODE;WIN32;%(PreprocessorDefinitions) - .\GeneratedFiles;.;$(QTDIR)\include;.\GeneratedFiles\$(ConfigurationName);%(AdditionalIncludeDirectories) + C:\Program Files\Autodesk\Maya2016\include;.\GeneratedFiles;.\GeneratedFiles\$(ConfigurationName);%(AdditionalIncludeDirectories) MultiThreadedDLL @@ -144,7 +146,7 @@ Windows - $(OutDir)\$(ProjectName).exe + $(OutDir)$(TargetName)$(TargetExt) $(QTDIR)\lib;%(AdditionalLibraryDirectories) false qtmain.lib;%(AdditionalDependencies) diff --git a/tools/MayaExporter/MayaExporter/Menu.cpp b/tools/MayaExporter/MayaExporter/Menu.cpp index 9cc6de91..02810018 100644 --- a/tools/MayaExporter/MayaExporter/Menu.cpp +++ b/tools/MayaExporter/MayaExporter/Menu.cpp @@ -60,8 +60,6 @@ Menu::Menu(QDialog* dialog) m_ExportPath = new QLineEdit; m_FileDialog = new QFileDialog; - QString tmpPath("C:/Users/Nickelodion/Desktop/workspace/tacticalZ/assets/models/"); - m_ExportPath->setText(tmpPath); QLabel* exportLabel = new QLabel; exportLabel->setText("Export Path:"); QLabel* nameLabel = new QLabel; diff --git a/tools/MayaExporter/MayaExporter/Mesh.cpp b/tools/MayaExporter/MayaExporter/Mesh.cpp index 6af8a557..ee5a6022 100644 --- a/tools/MayaExporter/MayaExporter/Mesh.cpp +++ b/tools/MayaExporter/MayaExporter/Mesh.cpp @@ -8,95 +8,91 @@ MeshClass::MeshClass() } -std::map MeshClass::GetWeightData() -{ - MS status; - map weightMap; - - MItDependencyNodes it(MFn::kSkinClusterFilter); - - while (!it.isDone()) { - - MObject object = it.thisNode(&status); - if (status != MS::kSuccess) { - MGlobal::displayError(MString() + " it.thisNode() ERROR: " + status.errorString()); - break; - } - MFnSkinCluster skinCluster(object, &status); - if (status != MS::kSuccess) { - MGlobal::displayError(MString() + "skinCluster() ERROR: " + status.errorString()); - break; - } - MDagPathArray influences; - - unsigned int nrOfInfluences = skinCluster.influenceObjects(influences,&status); - if (status != MS::kSuccess) { - MGlobal::displayError(MString() + "skinCluster.influenceObjects() ERROR: " + status.errorString()); - break; - } - - unsigned int index; - index = skinCluster.indexForOutputConnection(0,&status); - if (status != MS::kSuccess) { - MGlobal::displayError(MString() + "skinCluster.indexForOutputConnection() ERROR: " + status.errorString()); - break; - } - MDagPath skinPath; - status = skinCluster.getPathAtIndex(index, skinPath); - if (status != MS::kSuccess) { - MGlobal::displayError(MString() + "skinCluster.getPathAtIndex() ERROR: " + status.errorString()); - break; - } - - MItGeometry geomIter(skinPath); - //for (unsigned int i = 0; i < nrOfInfluences; i++) { - // MGlobal::displayInfo(MString() + " Influence object name: " + influences[i].partialPathName().asChar()); - //} - WeightInfo weightInfo; - - while (!geomIter.isDone()) { - MObject comp = geomIter.component(&status); - if (status != MS::kSuccess) { - MGlobal::displayError(MString() + "geomIter.component() ERROR: " + status.errorString()); - break; - } - MFloatArray weights; - unsigned int influenceCount; - status = skinCluster.getWeights(skinPath, comp, weights, influenceCount); - if (status != MS::kSuccess) { - MGlobal::displayError(MString() + "skinCluster.getWeights() ERROR: " + status.errorString()); - break; - } - MFnDependencyNode test(comp); - unsigned int nrOfWeights = 0; - - for (unsigned int j = 0; j < weights.length() && nrOfWeights != 4; j++) { - if (weights[j] > 0.00001) { - weightInfo.BoneWeights[nrOfWeights] = weights[j]; - weightInfo.BoneIndices[nrOfWeights] = j; - nrOfWeights++; - } - } - - float totalWeight = 0.0f; - for (unsigned int i = 0; i < 4; i++) { - totalWeight += weightInfo.BoneWeights[i]; - } - for (unsigned int i = 0; i < 4; i++) { - weightInfo.BoneWeights[i] /= totalWeight; - } - weightMap[geomIter.index()] = weightInfo; - - - for (unsigned int k = 0; k!=nrOfWeights; k++) { - MGlobal::displayInfo(MString() + "influence: " + weightInfo.BoneIndices[k] + " weight: " + weightInfo.BoneWeights[k]); - } - geomIter.next(); - } - it.next(); - } - return weightMap; -} +//std::map MeshClass::GetWeightData() +//{ +// MS status; +// map weightMap; +// +// MItDependencyNodes it(MFn::kSkinClusterFilter); +// +// while (!it.isDone()) { +// +// MObject object = it.thisNode(&status); +// if (status != MS::kSuccess) { +// MGlobal::displayError(MString() + " it.thisNode() ERROR: " + status.errorString()); +// break; +// } +// MFnSkinCluster skinCluster(object, &status); +// if (status != MS::kSuccess) { +// MGlobal::displayError(MString() + "skinCluster() ERROR: " + status.errorString()); +// break; +// } +// MDagPathArray influences; +// +// unsigned int nrOfInfluences = skinCluster.influenceObjects(influences,&status); +// if (status != MS::kSuccess) { +// MGlobal::displayError(MString() + "skinCluster.influenceObjects() ERROR: " + status.errorString()); +// break; +// } +// +// unsigned int index; +// index = skinCluster.indexForOutputConnection(0,&status); +// if (status != MS::kSuccess) { +// MGlobal::displayError(MString() + "skinCluster.indexForOutputConnection() ERROR: " + status.errorString()); +// break; +// } +// MDagPath skinPath; +// status = skinCluster.getPathAtIndex(index, skinPath); +// if (status != MS::kSuccess) { +// MGlobal::displayError(MString() + "skinCluster.getPathAtIndex() ERROR: " + status.errorString()); +// break; +// } +// +// MItGeometry geomIter(skinPath); +// //for (unsigned int i = 0; i < nrOfInfluences; i++) { +// // MGlobal::displayInfo(MString() + " Influence object name: " + influences[i].partialPathName().asChar()); +// //} +// WeightInfo weightInfo; +// +// while (!geomIter.isDone()) { +// MObject comp = geomIter.component(&status); +// if (status != MS::kSuccess) { +// MGlobal::displayError(MString() + "geomIter.component() ERROR: " + status.errorString()); +// break; +// } +// MFloatArray weights; +// unsigned int influenceCount; +// status = skinCluster.getWeights(skinPath, comp, weights, influenceCount); +// if (status != MS::kSuccess) { +// MGlobal::displayError(MString() + "skinCluster.getWeights() ERROR: " + status.errorString()); +// break; +// } +// MFnDependencyNode test(comp); +// unsigned int nrOfWeights = 0; +// +// for (unsigned int j = 0; j < weights.length() && nrOfWeights != 4; j++) { +// if (weights[j] > 0.00001) { +// weightInfo.BoneWeights[nrOfWeights] = weights[j]; +// weightInfo.BoneIndices[nrOfWeights] = j; +// nrOfWeights++; +// } +// } +// +// float totalWeight = 0.0f; +// for (unsigned int i = 0; i < 4; i++) { +// totalWeight += weightInfo.BoneWeights[i]; +// } +// for (unsigned int i = 0; i < 4; i++) { +// weightInfo.BoneWeights[i] /= totalWeight; +// } +// weightMap[geomIter.index()] = weightInfo; +// +// geomIter.next(); +// } +// it.next(); +// } +// return weightMap; +//} Mesh MeshClass::GetMeshData(MObjectArray object) { @@ -112,8 +108,6 @@ Mesh MeshClass::GetMeshData(MObjectArray object) MFnDependencyNode thisNode(node); MPlugArray connections; thisNode.findPlug("inMesh").connectedTo(connections, true, true); - MGlobal::displayInfo(MString() + "inMesh"); - bool hasSkin = false; MPlug weightList, weights; MObject weightListObject; for (unsigned int i = 0; i < connections.length(); i++) { @@ -122,7 +116,7 @@ Mesh MeshClass::GetMeshData(MObjectArray object) weightList = skinCluster.findPlug("weightList", &status); weightListObject = weightList.attribute(); weights = skinCluster.findPlug("weights"); - hasSkin = true; + newMesh.hasSkin = true; break; } } @@ -138,7 +132,6 @@ Mesh MeshClass::GetMeshData(MObjectArray object) } for (int pathID = 0; pathID < dagPaths.length(); pathID++) { - MGlobal::displayInfo(dagPaths[pathID].fullPathName()); MDagPath thisMeshPath(dagPaths[pathID]); MMatrix transformMatrix = thisMeshPath.inclusiveMatrix(&status); @@ -173,8 +166,7 @@ Mesh MeshClass::GetMeshData(MObjectArray object) break; } map> materialFaceIDs; - MGlobal::displayInfo(MString() + "shaderIndexList: " + shaderIndexList.length()); - MGlobal::displayInfo(MString() + "shaderList: " + shaderList.length()); + MPlugArray plugArray; for (int i = 0; i < shaderIndexList.length(); i++) { MFnDependencyNode shader(shaderList[shaderIndexList[i]]); @@ -261,43 +253,33 @@ Mesh MeshClass::GetMeshData(MObjectArray object) //mesh.getPoint(vertexIndex, pos, MSpace::kPostTransform); pos = positions[vertexIndex]; pos = pos * transformMatrix; - if (abs(pos.x) > 0.0001) - thisVertex.Pos[0] = pos.x; - if (abs(pos.y) > 0.0001) - thisVertex.Pos[1] = pos.y; - if (abs(pos.z) > 0.0001) - thisVertex.Pos[2] = pos.z; + + thisVertex.Pos[0] = pos.x; + thisVertex.Pos[1] = pos.y; + thisVertex.Pos[2] = pos.z; status = faceVert.getNormal(normal, MSpace::kObject); if (status != MS::kSuccess) { MGlobal::displayError(MString() + "faceVert.getNormal() ERROR: " + status.errorString() + "for local vertex " + i + " in " + faceID + " in mesh " + thisMeshPath.fullPathName()); break; } - if (abs(normal[0]) > 0.0001) - thisVertex.Normal[0] = normal[0]; - if (abs(normal[1]) > 0.0001) - thisVertex.Normal[1] = normal[1]; - if (abs(normal[2]) > 0.0001) - thisVertex.Normal[2] = normal[2]; + + thisVertex.Normal[0] = normal[0]; + thisVertex.Normal[1] = normal[1]; + thisVertex.Normal[2] = normal[2]; MFloatVector Tangent = Tangents[faceVert.tangentId()]; //MVector tmp = faceVert.getTangent(MSpace::kObject, NULL); //tmp.get(biTangent); - if (abs(Tangent[0]) > 0.0001) - thisVertex.Tangent[0] = Tangent[0]; - if (abs(Tangent[1]) > 0.0001) - thisVertex.Tangent[1] = Tangent[1]; - if (abs(Tangent[2]) > 0.0001) - thisVertex.Tangent[2] = Tangent[2]; + thisVertex.Tangent[0] = Tangent[0]; + thisVertex.Tangent[1] = Tangent[1]; + thisVertex.Tangent[2] = Tangent[2]; MFloatVector biNormal = biNormals[faceVert.tangentId()]; //faceVert.getBinormal().get(biNormal); - if (abs(biNormal[0]) > 0.0001) - thisVertex.BiNormal[0] = biNormal[0]; - if (abs(biNormal[1]) > 0.0001) - thisVertex.BiNormal[1] = biNormal[1]; - if (abs(biNormal[2]) > 0.0001) - thisVertex.BiNormal[2] = biNormal[2]; + thisVertex.BiNormal[0] = biNormal[0]; + thisVertex.BiNormal[1] = biNormal[1]; + thisVertex.BiNormal[2] = biNormal[2]; status = faceVert.getUV(UV); if (status != MS::kSuccess) { @@ -308,7 +290,8 @@ Mesh MeshClass::GetMeshData(MObjectArray object) thisVertex.Uv[1] = UV[1]; - if (hasSkin) { + if (newMesh.hasSkin) { + thisVertex.useWeights = true; float totalWeight = 0.0f; unsigned int totalBones = 0; MIntArray jointIDs /* ??? */; @@ -324,9 +307,11 @@ Mesh MeshClass::GetMeshData(MObjectArray object) } for (unsigned int i = 0; i < 4; i++) { - thisVertex.BoneWeights[i] = thisVertex.BoneWeights[i] / totalWeight; + //thisVertex.BoneWeights[i] = thisVertex.BoneWeights[i] / totalWeight; } - } + } else { + thisVertex.useWeights = false; + } //float totalWeight = thisVertex.BoneWeights[0] + thisVertex.BoneWeights[1] + thisVertex.BoneWeights[2] + thisVertex.BoneWeights[3]; //if (totalWeight > 0.0001f) { diff --git a/tools/MayaExporter/MayaExporter/Mesh.h b/tools/MayaExporter/MayaExporter/Mesh.h index 11f6bcf8..affc4320 100644 --- a/tools/MayaExporter/MayaExporter/Mesh.h +++ b/tools/MayaExporter/MayaExporter/Mesh.h @@ -11,6 +11,7 @@ class VertexLayout : public OutputData { public: + bool useWeights = true; float Pos[3]{ 0 }; float Normal[3]{ 0 }; float Tangent[3]{ 0 }; @@ -26,8 +27,10 @@ public: out.write((char*)&Tangent, sizeof(float) * 3); out.write((char*)&BiNormal, sizeof(float) * 3); out.write((char*)&Uv, sizeof(float) * 2); - out.write((char*)&BoneIndices, sizeof(float) * 4); - out.write((char*)&BoneWeights, sizeof(float) * 4); + if (useWeights) { + out.write((char*)&BoneIndices, sizeof(float) * 4); + out.write((char*)&BoneWeights, sizeof(float) * 4); + } } virtual void WriteASCII(std::ostream& out) const @@ -37,8 +40,10 @@ public: out << Tangent[0] << " " << Tangent[1] << " " << Tangent[2] << endl; out << BiNormal[0] << " " << BiNormal[1] << " " << BiNormal[2] << endl; out << Uv[0] << " " << Uv[1] << endl; - out << BoneIndices[0] << " " << BoneIndices[1] << " " << BoneIndices[2] << " " << BoneIndices[3] << endl; - out << BoneWeights[0] << " " << BoneWeights[1] << " " << BoneWeights[2] << " " << BoneWeights[3] << endl; + if (useWeights) { + out << BoneIndices[0] << " " << BoneIndices[1] << " " << BoneIndices[2] << " " << BoneIndices[3] << endl; + out << BoneWeights[0] << " " << BoneWeights[1] << " " << BoneWeights[2] << " " << BoneWeights[3] << endl; + } } bool operator==(const VertexLayout& right) @@ -57,6 +62,7 @@ public: class Mesh : public OutputData { public: + bool hasSkin = false; unsigned int NumVertices; unsigned int NumIndices; std::vector Vertices; @@ -64,6 +70,7 @@ public: virtual void WriteBinary(std::ostream& out) { + out.write((char*)&hasSkin, sizeof(bool)); out.write((char*)&NumVertices, sizeof(int)); out.write((char*)&NumIndices, sizeof(int)); for (auto aVertex : Vertices) { @@ -79,6 +86,11 @@ public: virtual void WriteASCII(std::ostream& out) const { out << "New Mesh _ not in binary" << endl; + out << "hasSkin: "; + if(hasSkin) + out << "true" << endl; + else + out << "false" << endl; out << "Number of vertices: " << NumVertices << endl; out << "number of indices: " << NumIndices << endl; int vertexNumber = 0; diff --git a/tools/MayaExporter/MayaExporter/Skeleton.cpp b/tools/MayaExporter/MayaExporter/Skeleton.cpp index c30311b8..2e432476 100644 --- a/tools/MayaExporter/MayaExporter/Skeleton.cpp +++ b/tools/MayaExporter/MayaExporter/Skeleton.cpp @@ -60,7 +60,7 @@ // // return m_AllSkeletons; //} -std::string attr[9] = { "scaleX", "scaleY", "scaleZ", "translateX", "translateY", "translateZ", "rotateX", "rotateY", "rotateZ" }; +static std::string attr[9] = { "scaleX", "scaleY", "scaleZ", "translateX", "translateY", "translateZ", "rotateX", "rotateY", "rotateZ" }; Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int endFrame) { @@ -68,100 +68,294 @@ 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; - MItDag jointIt(MItDag::TraversalType::kDepthFirst, MFn::kJoint); - while (!jointIt.isDone()) - { - m_Hierarchy.push_back(jointIt.item()); + std::map, 4>> joinCheckMap; + std::map exportJoint; - MFnDependencyNode depNode(jointIt.item()); - for (int i = 0; i < 9; i++) - { - MStatus tmp; - MPlug plug = depNode.findPlug(attr[i].c_str(), &tmp); + //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()); - MPlugArray connections; - plug.connectedTo(connections, true, false, 0); - for (int j = 0; j != connections.length(); j++) { - MObject connected = connections[j].node(); + // MFnTransform MayaJoint(jointIt.item()); + // MMatrix transformationMatrix = MayaJoint.transformationMatrix(); - if (connected.hasFn(MFn::kAnimCurve)) { + // if (i == startFrame) + // { + // double doubleMat[4][4]; + // transformationMatrix.get(doubleMat); - MFnAnimCurve jointAnim(connected); + // 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]; - unsigned int startKeyFrameIndex = jointAnim.findClosest(MTime(startFrame, MTime::kNTSCField), &tmp); + // exportJoint[MayaJoint.name().asChar()] = false; + // } + // else if(!exportJoint[MayaJoint.name().asChar()])//!exportJoint[MayaJoint.name().asChar()]) + // { + // double doubleMat[4][4]; - if (tmp == MStatus::kFailure) - MGlobal::displayInfo(MString() + "Fail :c"); + // 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]; - if (startFrame * oneDivSixty <= jointAnim.time(startKeyFrameIndex).value() && jointAnim.time(startKeyFrameIndex).value() <= endFrame * oneDivSixty) { - animatedJoints.push_back(jointIt.item()); - i = 9; - break; - } + // MMatrix tmp(doubleMat); + // if (!tmp.isEquivalent(transformationMatrix)) { + // MGlobal::displayInfo(MString() + MayaJoint.name() + " is exported"); + // exportJoint[MayaJoint.name().asChar()] = true; + // animatedJoints.push_back(MayaJoint.object()); + // } + // } - unsigned int endKeyFrameIndex = jointAnim.findClosest(MTime(endFrame, MTime::kNTSCField)); - MGlobal::displayInfo(MString() + startKeyFrameIndex + " " + endKeyFrameIndex); + /*for (int i = 0; i < 9; i++) + { + MStatus tmp; + MPlug plug = depNode.findPlug(attr[i].c_str(), &tmp); - if (startFrame * oneDivSixty <= jointAnim.time(endKeyFrameIndex).value() && jointAnim.time(endKeyFrameIndex).value() <= endFrame * oneDivSixty || endKeyFrameIndex - startKeyFrameIndex > 0) { - animatedJoints.push_back(jointIt.item()); - i = 9; - break; - } + MPlugArray connections; + plug.connectedTo(connections, true, false, 0); + for (int j = 0; j != connections.length(); j++) { + MObject connected = connections[j].node(); - MFnTransform MayaJoint(jointIt.item()); + if (connected.hasFn(MFn::kAnimCurve)) { - MPlug BindPose = MayaJoint.findPlug("bindPose"); - MDataHandle DataHandle; - BindPose.getValue(DataHandle); - MFnMatrixData MartixFn(DataHandle.data()); - MMatrix BindPoseMatrix = MartixFn.matrix(); + MFnAnimCurve jointAnim(connected); - 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"); - } - } - } - } + //MGlobal::displayInfo(MString() + "curve : " + jointAnim.name()); + //MGlobal::displayInfo(MString() + "curve keys : " + jointAnim.numKeys()); + //MGlobal::displayInfo(MString() + "curve keyframes : " + jointAnim.numKeyframes()); + //MGlobal::displayInfo(MString() + "startFrame : " + startFrame); + //MGlobal::displayInfo(MString() + "endFrame : " + endFrame); - jointIt.next(); - } + unsigned int startKeyFrameIndex = jointAnim.findClosest(MTime(startFrame, MTime::kNTSCField), &tmp); - int currentFrame = startFrame; - while (currentFrame != endFrame + 1) { // ANDREAS - Animation::Keyframe thisKeyFrame; - thisKeyFrame.Index = currentFrame - startFrame; - thisKeyFrame.Time = thisKeyFrame.Index * oneDivSixty; + if (tmp == MStatus::kFailure) + MGlobal::displayInfo(MString() + "Fail :c"); - MAnimControl::setCurrentTime(MTime(currentFrame, MTime::kNTSCField)); - MTime time = MAnimControl::currentTime(); + if (startFrame * oneDivSixty <= jointAnim.time(startKeyFrameIndex).value() && jointAnim.time(startKeyFrameIndex).value() <= endFrame * oneDivSixty) { + //MGlobal::displayInfo(MString() + "Start key time : " + jointAnim.time(startKeyFrameIndex).value()); - for (auto aJoint : animatedJoints){ - MFnTransform thisJoint(aJoint); - Animation::Keyframe::JointProperty joint; - 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(); - MPlug BindPose = thisJoint.findPlug("bindPose"); - MDataHandle DataHandle; - BindPose.getValue(DataHandle); - MFnMatrixData MartixFn(DataHandle.data()); - MMatrix BindPoseMatrix = MartixFn.matrix(); - Matrix = Matrix.asMatrix(); - + 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); + MGlobal::displayInfo(MString() + "Fail!!!!!!!!!!!!!!!!!!!!!!!!!"); + + 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 + ".");*/ + + /*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()); + + 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"); + } + } + } + } + + } // end of int i loop*/ + /* jointIt.next(); + } + jointIt.reset(); + }*/ + + MItDag jointIt(MItDag::TraversalType::kDepthFirst, MFn::kJoint); + unsigned int jointID = 0; + + while (!jointIt.isDone()) { + int currentFrame = startFrame; + Animation::JointAnimation thisJointAnimation; + bool haxBool = false; + while (currentFrame < endFrame) { + Animation::JointAnimation::KeyFrame thisKeyFrame; + //thisKeyFrame.Index = currentFrame - startFrame; + //thisKeyFrame.Time = thisKeyFrame.Index * oneDivSixty; + + MAnimControl::setCurrentTime(MTime(currentFrame, MTime::kNTSCField)); + MTime time = MAnimControl::currentTime(); + + MFnTransform thisJoint(jointIt.currentItem()); + MTransformationMatrix transformationMatrix = thisJoint.transformationMatrix(); + + double doubleMat[4][4]; + + if (currentFrame != startFrame) { + //Animation::JointAnimation 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.asMatrix())) { + //jointID++; + //jointIt.next(); + currentFrame++; + haxBool = false; + continue; + } else if(!haxBool){ + haxBool = true; + MTransformationMatrix LastJointTransformationMatrix = LastJointMatrix; + MObject jointOrientObj = thisJoint.attribute("jointOrient"); + MFnNumericAttribute jointOrient(jointOrientObj); + double jointOrientDouble[3]; + jointOrient.getDefault(jointOrientDouble[0], jointOrientDouble[1], jointOrientDouble[2]); + //MGlobal::displayError(MString() + "Joint Matrix: "); + //MGlobal::displayError(MString() + Matrix.asMatrix()[0][0] + " " + Matrix.asMatrix()[0][1] + " " + Matrix.asMatrix()[0][2] + " " + Matrix.asMatrix()[0][3]); + //MGlobal::displayError(MString() + Matrix.asMatrix()[1][0] + " " + Matrix.asMatrix()[1][1] + " " + Matrix.asMatrix()[1][2] + " " + Matrix.asMatrix()[1][3]); + //MGlobal::displayError(MString() + Matrix.asMatrix()[2][0] + " " + Matrix.asMatrix()[2][1] + " " + Matrix.asMatrix()[2][2] + " " + Matrix.asMatrix()[2][3]); + //MGlobal::displayError(MString() + Matrix.asMatrix()[3][0] + " " + Matrix.asMatrix()[3][1] + " " + Matrix.asMatrix()[3][2] + " " + Matrix.asMatrix()[3][3]); + + MEulerRotation joEuler(jointOrientDouble[0], jointOrientDouble[1], jointOrientDouble[2]); + MQuaternion jo = joEuler.asQuaternion(); + + double tmp[4]; + LastJointTransformationMatrix.getRotationQuaternion(tmp[0], tmp[1], tmp[2], tmp[3]); + MQuaternion rotation(tmp); + + rotation = rotation * jo; + rotation.get(tmp); + + //Animation::JointAnimation::KeyFrame keyframe; + Animation::JointAnimation::KeyFrame previousKeyFrame; + previousKeyFrame.Index = currentFrame - startFrame - 1; + previousKeyFrame.Time = previousKeyFrame.Index * oneDivSixty; + + previousKeyFrame.Rotation[0] = tmp[0]; + previousKeyFrame.Rotation[1] = tmp[1]; + previousKeyFrame.Rotation[2] = tmp[2]; + previousKeyFrame.Rotation[3] = tmp[3]; + LastJointTransformationMatrix.getTranslation(MSpace::kTransform).get(tmp); + previousKeyFrame.Position[0] = tmp[0]; + previousKeyFrame.Position[1] = tmp[1]; + previousKeyFrame.Position[2] = tmp[2]; + LastJointTransformationMatrix.getScale(tmp, MSpace::kTransform); + previousKeyFrame.Scale[0] = tmp[0]; + previousKeyFrame.Scale[1] = tmp[1]; + previousKeyFrame.Scale[2] = tmp[2]; + + thisJointAnimation.m_KeyFrames.push_back(previousKeyFrame); + } + } + + transformationMatrix.asMatrix().get(doubleMat); + + //Save transformationMatrix to joinCheckMap + 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]; + + if (currentFrame == startFrame) { + MPlug thisJointBindPose = thisJoint.findPlug("bindPose"); + MDataHandle DataHandle; + thisJointBindPose.getValue(DataHandle); + MFnMatrixData MartixFn(DataHandle.data()); + MMatrix thisJointBindPoseMatrix = MartixFn.matrix(); + + MFnTransform Parent(thisJoint.parent(0), &status); + if (status == MS::kSuccess && thisJoint.parent(0).apiType() == MFn::kJoint) { + MTransformationMatrix Matrix = Parent.transformation(); + MPlug parentBindPose = Parent.findPlug("bindPose"); + MDataHandle DataHandle; + parentBindPose.getValue(DataHandle); + MFnMatrixData MartixFn(DataHandle.data()); + MMatrix parentBindPoseMatrix = MartixFn.matrix(); + + thisJointBindPoseMatrix = thisJointBindPoseMatrix * parentBindPoseMatrix.inverse(); + } + + if (thisJointBindPoseMatrix.isEquivalent(transformationMatrix.asMatrix())) { + //jointID++; + //jointIt.next(); + currentFrame++; + MGlobal::displayError(MString() + thisJoint.name() + " is in bindPose"); + continue; + } + haxBool = true; + } + MObject jointOrientObj = thisJoint.attribute("jointOrient"); MFnNumericAttribute jointOrient(jointOrientObj); double jointOrientDouble[3]; @@ -175,95 +369,97 @@ 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]; - Matrix.getRotationQuaternion(tmp[0], tmp[1], tmp[2], tmp[3]); + double tmp[4]; + transformationMatrix.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::JointAnimation::KeyFrame keyframe; + thisKeyFrame.Index = currentFrame - startFrame; + thisKeyFrame.Time = thisKeyFrame.Index * oneDivSixty; - thisKeyFrame.JointProperties.push_back(joint); - } - returnData.Keyframes.push_back(thisKeyFrame); - currentFrame++; - } + thisKeyFrame.Rotation[0] = tmp[0]; + thisKeyFrame.Rotation[1] = tmp[1]; + thisKeyFrame.Rotation[2] = tmp[2]; + thisKeyFrame.Rotation[3] = tmp[3]; + transformationMatrix.getTranslation(MSpace::kTransform).get(tmp); + thisKeyFrame.Position[0] = tmp[0]; + thisKeyFrame.Position[1] = tmp[1]; + thisKeyFrame.Position[2] = tmp[2]; + transformationMatrix.getScale(tmp, MSpace::kTransform); + thisKeyFrame.Scale[0] = tmp[0]; + thisKeyFrame.Scale[1] = tmp[1]; + thisKeyFrame.Scale[2] = tmp[2]; - returnData.NumKeyFrames = returnData.Keyframes.size(); - returnData.NumberOfJoints = animatedJoints.size(); + thisJointAnimation.m_KeyFrames.push_back(thisKeyFrame); - return returnData; + currentFrame++; + } + //thisKeyFrame.NumberOfJoints = thisKeyFrame.JointProperties.size(); + thisJointAnimation.numberOFKeyFrames = thisJointAnimation.m_KeyFrames.size(); + returnData.JointsFrameMap[jointID] = (thisJointAnimation); + + jointID++; + jointIt.next(); + } + returnData.NumOfJointFrames = returnData.JointsFrameMap.size(); + 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)).name() == "world") { - 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); - MGlobal::displayError(MString() + "translation befor: " + tmp[0] + " " + tmp[1] + " " + tmp[2]); //Matrix[3][0] *= -1; //Matrix[3][2] *= -1; //Matrix[3][1] *= -1; double test[3]; MayaJoint.transformation().getScale(test, MSpace::kObject); - MGlobal::displayError(MString() + "scale: " + test[0] + " " + test[1] + " " + test[2]); MTransformationMatrix::RotationOrder order = MTransformationMatrix::RotationOrder::kXYZ; MayaJoint.transformation().getRotation(test, order); - MGlobal::displayError(MString() + "rotation: " + test[0] + " " + test[1] + " " + test[2]); - + //----- test @@ -310,33 +506,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 6a288c8a..3dfbe8a5 100644 --- a/tools/MayaExporter/MayaExporter/Skeleton.h +++ b/tools/MayaExporter/MayaExporter/Skeleton.h @@ -3,50 +3,63 @@ #include #include +#include #include #include "MayaIncludes.h" #include "OutputData.h" class Animation : public OutputData { public: - struct Keyframe - { - struct JointProperty - { - int ID = 0; + //struct Keyframe + //{ + // struct JointProperty + // { + // int ID = 0; + // float Position[3]{ 0 }; + // float Rotation[4]{ 0 }; + // float Scale[3]{ 0 }; + // }; + + // int Index = 0; + // float Time = 0; + // int NumberOfJoints; + // std::vector JointProperties; + //}; + + struct JointAnimation { + struct KeyFrame { + int Index = 0; + float Time = 0; float Position[3]{ 0 }; float Rotation[4]{ 0 }; float Scale[3]{ 0 }; - }; - - int Index = 0; - float Time = 0; - std::vector JointProperties; - }; + }; + unsigned int numberOFKeyFrames = 0; + std::vector m_KeyFrames; + }; std::string Name; int nameLength = 0; float Duration = 0; - int NumKeyFrames = 0; - int NumberOfJoints = 0; - std::vector Keyframes; + int NumOfJointFrames = 0; + std::map JointsFrameMap; virtual void WriteBinary(std::ostream& out) { out.write((char*)&nameLength, sizeof(int)); 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)); + out.write((char*)&NumOfJointFrames, 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)); - for (auto aJoint : aKeyframe.JointProperties) { - out.write((char*)&aJoint.ID, sizeof(int)); - out.write((char*)aJoint.Position, sizeof(float) * 3); - out.write((char*)aJoint.Rotation, sizeof(float) * 4); - out.write((char*)aJoint.Scale, sizeof(float) * 3); + for (auto aJointAnimation : JointsFrameMap) { + out.write((char*)&aJointAnimation.first, sizeof(int)); + out.write((char*)&aJointAnimation.second.numberOFKeyFrames, sizeof(int)); + for (auto aJointKeyFrame : aJointAnimation.second.m_KeyFrames) { + out.write((char*)&aJointKeyFrame.Index, sizeof(int)); + out.write((char*)&aJointKeyFrame.Time, sizeof(float)); + out.write((char*)&aJointKeyFrame.Position, sizeof(float) * 3); + out.write((char*)&aJointKeyFrame.Rotation, sizeof(float) * 4); + out.write((char*)&aJointKeyFrame.Scale, sizeof(float) * 3); } } } @@ -55,16 +68,17 @@ public: { out << "Animation Name: " << Name << endl; out << "Duration: " << Duration << endl; - out << "Number of KeyFrames: " << NumKeyFrames << endl; - out << "Number of Joints: " << NumberOfJoints << endl; - for (auto aKeyframe : Keyframes) { - out << "Frame: " << aKeyframe.Index << endl; - out << "Time: " << aKeyframe.Time << endl; - for (auto aJoint : aKeyframe.JointProperties) { - out << "Joint ID: " << aJoint.ID << endl; - out << aJoint.Position[0] << " " << aJoint.Position[1] << " " << aJoint.Position[2] << endl; - out << aJoint.Rotation[0] << " " << aJoint.Rotation[1] << " " << aJoint.Rotation[2] << " " << aJoint.Rotation[3] << endl; - out << aJoint.Scale[0] << " " << aJoint.Scale[1] << " " << aJoint.Scale[2] << endl; + out << "Number of KeyFrames: " << NumOfJointFrames << endl; + for (auto aJointAnimation : JointsFrameMap) { + out << "Bone: " << aJointAnimation.first << endl; + //out << "Time: " << aJointAnimation.Time << endl; + //out << "Number of Joints: " << aKeyframe.NumberOfJoints << endl; + for (auto aJointKeyFrame : aJointAnimation.second.m_KeyFrames) { + //out << "Joint ID: " << aJoint.ID << endl; + out << "Time: " << aJointKeyFrame.Time << endl; + out << aJointKeyFrame.Position[0] << " " << aJointKeyFrame.Position[1] << " " << aJointKeyFrame.Position[2] << endl; + out << aJointKeyFrame.Rotation[0] << " " << aJointKeyFrame.Rotation[1] << " " << aJointKeyFrame.Rotation[2] << " " << aJointKeyFrame.Rotation[3] << endl; + out << aJointKeyFrame.Scale[0] << " " << aJointKeyFrame.Scale[1] << " " << aJointKeyFrame.Scale[2] << endl; } } diff --git a/tools/deploy.bat b/tools/deploy.bat index 29dc9e62..cd7a44bc 100755 --- a/tools/deploy.bat +++ b/tools/deploy.bat @@ -22,7 +22,9 @@ MKLINK "%DeployLocation%\Schema\" "resources\Schema" /J RMDIR /S /Q "%DeployLocation%\Shaders" MKLINK "%DeployLocation%\Shaders\" "resources\Shaders" /J :: Configuration files +DEL "%DeployLocation%\DefaultConfig.ini" MKLINK "%DeployLocation%\DefaultConfig.ini" "resources\DefaultConfig.ini" /H +DEL "%DeployLocation%\DefaultInput.ini" MKLINK "%DeployLocation%\DefaultInput.ini" "resources\DefaultInput.ini" /H :: Platform specific binaries