diff --git a/.gitignore b/.gitignore index 85a515095..7bdc61c6c 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,9 @@ build/config.lua # Nazara libraries lib/* +# Nazara plugin libraries +plugins/lib/* + # Nazara package package/* diff --git a/.travis.yml b/.travis.yml index d1ed3ec6d..4fcb85c55 100644 --- a/.travis.yml +++ b/.travis.yml @@ -34,8 +34,13 @@ compiler: - clang env: - - COMPILER=clang++-3.7 CONFIG=debug - - COMPILER=clang++-3.7 CONFIG=release + global: + - COMPILER=clang++-3.7 + - CFLAGS="-Wall -Wextra" + - CXXFLAGS="-Wall -Wextra" + matrix: + - CONFIG=debug + - CONFIG=release script: - cd build && diff --git a/SDK/include/NDK/Application.inl b/SDK/include/NDK/Application.inl index 2c74acb19..d26a2daa8 100644 --- a/SDK/include/NDK/Application.inl +++ b/SDK/include/NDK/Application.inl @@ -374,8 +374,8 @@ namespace Ndk } inline Application::WindowInfo::WindowInfo(std::unique_ptr&& window) : - window(std::move(window)), - renderTarget(nullptr) + renderTarget(nullptr), + window(std::move(window)) { } #endif diff --git a/SDK/include/NDK/BaseSystem.inl b/SDK/include/NDK/BaseSystem.inl index 1afc242c0..31a0c314e 100644 --- a/SDK/include/NDK/BaseSystem.inl +++ b/SDK/include/NDK/BaseSystem.inl @@ -15,8 +15,8 @@ namespace Ndk */ inline BaseSystem::BaseSystem(SystemIndex systemId) : - m_updateEnabled(true), - m_systemIndex(systemId) + m_systemIndex(systemId), + m_updateEnabled(true) { SetUpdateRate(30); } diff --git a/SDK/include/NDK/Components.hpp b/SDK/include/NDK/Components.hpp index 79bc196f7..3338e5f52 100644 --- a/SDK/include/NDK/Components.hpp +++ b/SDK/include/NDK/Components.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 30 Jul 2016 at 15:29:16 +// This file was automatically generated #pragma once @@ -6,14 +6,14 @@ #define NDK_COMPONENTS_GLOBAL_HPP #include -#include +#include #include #include #include #include #include #include -#include +#include #include #endif // NDK_COMPONENTS_GLOBAL_HPP diff --git a/SDK/include/NDK/Components/CollisionComponent.hpp b/SDK/include/NDK/Components/CollisionComponent3D.hpp similarity index 51% rename from SDK/include/NDK/Components/CollisionComponent.hpp rename to SDK/include/NDK/Components/CollisionComponent3D.hpp index e0af0d09b..f6a07ede6 100644 --- a/SDK/include/NDK/Components/CollisionComponent.hpp +++ b/SDK/include/NDK/Components/CollisionComponent3D.hpp @@ -7,53 +7,53 @@ #ifndef NDK_COMPONENTS_COLLISIONCOMPONENT_HPP #define NDK_COMPONENTS_COLLISIONCOMPONENT_HPP -#include +#include #include #include namespace Nz { - class PhysObject; + class RigidBody3D; } namespace Ndk { class Entity; - class NDK_API CollisionComponent : public Component + class NDK_API CollisionComponent3D : public Component { - friend class PhysicsSystem; + friend class PhysicsSystem3D; friend class StaticCollisionSystem; public: - CollisionComponent(Nz::PhysGeomRef geom = Nz::PhysGeomRef()); - CollisionComponent(const CollisionComponent& collision); - ~CollisionComponent() = default; + CollisionComponent3D(Nz::Collider3DRef geom = Nz::Collider3DRef()); + CollisionComponent3D(const CollisionComponent3D& collision); + ~CollisionComponent3D() = default; - const Nz::PhysGeomRef& GetGeom() const; + const Nz::Collider3DRef& GetGeom() const; - void SetGeom(Nz::PhysGeomRef geom); + void SetGeom(Nz::Collider3DRef geom); - CollisionComponent& operator=(Nz::PhysGeomRef geom); - CollisionComponent& operator=(CollisionComponent&& collision) = default; + CollisionComponent3D& operator=(Nz::Collider3DRef geom); + CollisionComponent3D& operator=(CollisionComponent3D&& collision) = default; static ComponentIndex componentIndex; private: void InitializeStaticBody(); - Nz::PhysObject* GetStaticBody(); + Nz::RigidBody3D* GetStaticBody(); void OnAttached() override; void OnComponentAttached(BaseComponent& component) override; void OnComponentDetached(BaseComponent& component) override; void OnDetached() override; - std::unique_ptr m_staticBody; - Nz::PhysGeomRef m_geom; + std::unique_ptr m_staticBody; + Nz::Collider3DRef m_geom; bool m_bodyUpdated; }; } -#include +#include #endif // NDK_COMPONENTS_COLLISIONCOMPONENT_HPP diff --git a/SDK/include/NDK/Components/CollisionComponent.inl b/SDK/include/NDK/Components/CollisionComponent3D.inl similarity index 57% rename from SDK/include/NDK/Components/CollisionComponent.inl rename to SDK/include/NDK/Components/CollisionComponent3D.inl index b08e7054e..d5dfeaacc 100644 --- a/SDK/include/NDK/Components/CollisionComponent.inl +++ b/SDK/include/NDK/Components/CollisionComponent3D.inl @@ -4,30 +4,30 @@ #include #include -#include -#include +#include +#include namespace Ndk { /*! - * \brief Constructs a CollisionComponent object with a geometry + * \brief Constructs a CollisionComponent3D object with a geometry * * \param geom Reference to a geometry symbolizing the entity */ - inline CollisionComponent::CollisionComponent(Nz::PhysGeomRef geom) : + inline CollisionComponent3D::CollisionComponent3D(Nz::Collider3DRef geom) : m_geom(std::move(geom)), m_bodyUpdated(false) { } /*! - * \brief Constructs a CollisionComponent object by copy semantic + * \brief Constructs a CollisionComponent3D object by copy semantic * - * \param collision CollisionComponent to copy + * \param collision CollisionComponent3D to copy */ - inline CollisionComponent::CollisionComponent(const CollisionComponent& collision) : + inline CollisionComponent3D::CollisionComponent3D(const CollisionComponent3D& collision) : m_geom(collision.m_geom), m_bodyUpdated(false) { @@ -38,7 +38,7 @@ namespace Ndk * \return A constant reference to the physics geometry */ - inline const Nz::PhysGeomRef& CollisionComponent::GetGeom() const + inline const Nz::Collider3DRef& CollisionComponent3D::GetGeom() const { return m_geom; } @@ -50,7 +50,7 @@ namespace Ndk * \param geom Reference to a geometry symbolizing the entity */ - inline CollisionComponent& CollisionComponent::operator=(Nz::PhysGeomRef geom) + inline CollisionComponent3D& CollisionComponent3D::operator=(Nz::Collider3DRef geom) { SetGeom(geom); @@ -62,7 +62,7 @@ namespace Ndk * \return A pointer to the entity */ - inline Nz::PhysObject* CollisionComponent::GetStaticBody() + inline Nz::RigidBody3D* CollisionComponent3D::GetStaticBody() { return m_staticBody.get(); } diff --git a/SDK/include/NDK/Components/GraphicsComponent.hpp b/SDK/include/NDK/Components/GraphicsComponent.hpp index b792cfd69..b536fc154 100644 --- a/SDK/include/NDK/Components/GraphicsComponent.hpp +++ b/SDK/include/NDK/Components/GraphicsComponent.hpp @@ -74,11 +74,11 @@ namespace Ndk } Renderable(Renderable&& renderable) noexcept : + renderableInvalidationSlot(std::move(renderable.renderableInvalidationSlot)), + renderableReleaseSlot(std::move(renderable.renderableReleaseSlot)), data(std::move(renderable.data)), renderable(std::move(renderable.renderable)), - dataUpdated(renderable.dataUpdated), - renderableInvalidationSlot(std::move(renderable.renderableInvalidationSlot)), - renderableReleaseSlot(std::move(renderable.renderableReleaseSlot)) + dataUpdated(renderable.dataUpdated) { } diff --git a/SDK/include/NDK/Components/PhysicsComponent.hpp b/SDK/include/NDK/Components/PhysicsComponent3D.hpp similarity index 74% rename from SDK/include/NDK/Components/PhysicsComponent.hpp rename to SDK/include/NDK/Components/PhysicsComponent3D.hpp index 9c5618785..fc1367d84 100644 --- a/SDK/include/NDK/Components/PhysicsComponent.hpp +++ b/SDK/include/NDK/Components/PhysicsComponent3D.hpp @@ -4,10 +4,10 @@ #pragma once -#ifndef NDK_COMPONENTS_PHYSICSCOMPONENT_HPP -#define NDK_COMPONENTS_PHYSICSCOMPONENT_HPP +#ifndef NDK_COMPONENTS_PHYSICSCOMPONENT3D_HPP +#define NDK_COMPONENTS_PHYSICSCOMPONENT3D_HPP -#include +#include #include #include @@ -15,15 +15,15 @@ namespace Ndk { class Entity; - class NDK_API PhysicsComponent : public Component + class NDK_API PhysicsComponent3D : public Component { - friend class CollisionComponent; - friend class PhysicsSystem; + friend class CollisionComponent3D; + friend class PhysicsSystem3D; public: - PhysicsComponent() = default; - PhysicsComponent(const PhysicsComponent& physics); - ~PhysicsComponent() = default; + PhysicsComponent3D() = default; + PhysicsComponent3D(const PhysicsComponent3D& physics); + ~PhysicsComponent3D() = default; void AddForce(const Nz::Vector3f& force, Nz::CoordSys coordSys = Nz::CoordSys_Global); void AddForce(const Nz::Vector3f& force, const Nz::Vector3f& point, Nz::CoordSys coordSys = Nz::CoordSys_Global); @@ -56,17 +56,17 @@ namespace Ndk static ComponentIndex componentIndex; private: - Nz::PhysObject& GetPhysObject(); + Nz::RigidBody3D& GetPhysObject(); void OnAttached() override; void OnComponentAttached(BaseComponent& component) override; void OnComponentDetached(BaseComponent& component) override; void OnDetached() override; - std::unique_ptr m_object; + std::unique_ptr m_object; }; } -#include +#include -#endif // NDK_COMPONENTS_PHYSICSCOMPONENT_HPP +#endif // NDK_COMPONENTS_PHYSICSCOMPONENT3D_HPP diff --git a/SDK/include/NDK/Components/PhysicsComponent.inl b/SDK/include/NDK/Components/PhysicsComponent3D.inl similarity index 79% rename from SDK/include/NDK/Components/PhysicsComponent.inl rename to SDK/include/NDK/Components/PhysicsComponent3D.inl index 5682603e0..84bc36db7 100644 --- a/SDK/include/NDK/Components/PhysicsComponent.inl +++ b/SDK/include/NDK/Components/PhysicsComponent3D.inl @@ -7,12 +7,12 @@ namespace Ndk { /*! - * \brief Constructs a PhysicsComponent object by copy semantic + * \brief Constructs a PhysicsComponent3D object by copy semantic * - * \param physics PhysicsComponent to copy + * \param physics PhysicsComponent3D to copy */ - inline PhysicsComponent::PhysicsComponent(const PhysicsComponent& physics) + inline PhysicsComponent3D::PhysicsComponent3D(const PhysicsComponent3D& physics) { // No copy of physical object (because we only create it when attached to an entity) NazaraUnused(physics); @@ -27,7 +27,7 @@ namespace Ndk * \remark Produces a NazaraAssert if the physics object is invalid */ - inline void PhysicsComponent::AddForce(const Nz::Vector3f& force, Nz::CoordSys coordSys) + inline void PhysicsComponent3D::AddForce(const Nz::Vector3f& force, Nz::CoordSys coordSys) { NazaraAssert(m_object, "Invalid physics object"); @@ -44,7 +44,7 @@ namespace Ndk * \remark Produces a NazaraAssert if the physics object is invalid */ - inline void PhysicsComponent::AddForce(const Nz::Vector3f& force, const Nz::Vector3f& point, Nz::CoordSys coordSys) + inline void PhysicsComponent3D::AddForce(const Nz::Vector3f& force, const Nz::Vector3f& point, Nz::CoordSys coordSys) { NazaraAssert(m_object, "Invalid physics object"); @@ -60,7 +60,7 @@ namespace Ndk * \remark Produces a NazaraAssert if the physics object is invalid */ - inline void PhysicsComponent::AddTorque(const Nz::Vector3f& torque, Nz::CoordSys coordSys) + inline void PhysicsComponent3D::AddTorque(const Nz::Vector3f& torque, Nz::CoordSys coordSys) { NazaraAssert(m_object, "Invalid physics object"); @@ -75,7 +75,7 @@ namespace Ndk * \remark Produces a NazaraAssert if the physics object is invalid */ - inline void PhysicsComponent::EnableAutoSleep(bool autoSleep) + inline void PhysicsComponent3D::EnableAutoSleep(bool autoSleep) { NazaraAssert(m_object, "Invalid physics object"); @@ -89,7 +89,7 @@ namespace Ndk * \remark Produces a NazaraAssert if the physics object is invalid */ - inline Nz::Boxf PhysicsComponent::GetAABB() const + inline Nz::Boxf PhysicsComponent3D::GetAABB() const { NazaraAssert(m_object, "Invalid physics object"); @@ -103,7 +103,7 @@ namespace Ndk * \remark Produces a NazaraAssert if the physics object is invalid */ - inline Nz::Vector3f PhysicsComponent::GetAngularVelocity() const + inline Nz::Vector3f PhysicsComponent3D::GetAngularVelocity() const { NazaraAssert(m_object, "Invalid physics object"); @@ -117,7 +117,7 @@ namespace Ndk * \remark Produces a NazaraAssert if the physics object is invalid */ - inline float PhysicsComponent::GetGravityFactor() const + inline float PhysicsComponent3D::GetGravityFactor() const { NazaraAssert(m_object, "Invalid physics object"); @@ -131,7 +131,7 @@ namespace Ndk * \remark Produces a NazaraAssert if the physics object is invalid */ - inline float PhysicsComponent::GetMass() const + inline float PhysicsComponent3D::GetMass() const { NazaraAssert(m_object, "Invalid physics object"); @@ -147,7 +147,7 @@ namespace Ndk * \remark Produces a NazaraAssert if the physics object is invalid */ - inline Nz::Vector3f PhysicsComponent::GetMassCenter(Nz::CoordSys coordSys) const + inline Nz::Vector3f PhysicsComponent3D::GetMassCenter(Nz::CoordSys coordSys) const { NazaraAssert(m_object, "Invalid physics object"); @@ -161,7 +161,7 @@ namespace Ndk * \remark Produces a NazaraAssert if the physics object is invalid */ - inline const Nz::Matrix4f& PhysicsComponent::GetMatrix() const + inline const Nz::Matrix4f& PhysicsComponent3D::GetMatrix() const { NazaraAssert(m_object, "Invalid physics object"); @@ -175,7 +175,7 @@ namespace Ndk * \remark Produces a NazaraAssert if the physics object is invalid */ - inline Nz::Vector3f PhysicsComponent::GetPosition() const + inline Nz::Vector3f PhysicsComponent3D::GetPosition() const { NazaraAssert(m_object, "Invalid physics object"); @@ -189,7 +189,7 @@ namespace Ndk * \remark Produces a NazaraAssert if the physics object is invalid */ - inline Nz::Quaternionf PhysicsComponent::GetRotation() const + inline Nz::Quaternionf PhysicsComponent3D::GetRotation() const { NazaraAssert(m_object, "Invalid physics object"); @@ -203,7 +203,7 @@ namespace Ndk * \remark Produces a NazaraAssert if the physics object is invalid */ - inline Nz::Vector3f PhysicsComponent::GetVelocity() const + inline Nz::Vector3f PhysicsComponent3D::GetVelocity() const { NazaraAssert(m_object, "Invalid physics object"); @@ -217,7 +217,7 @@ namespace Ndk * \remark Produces a NazaraAssert if the physics object is invalid */ - inline bool PhysicsComponent::IsAutoSleepEnabled() const + inline bool PhysicsComponent3D::IsAutoSleepEnabled() const { NazaraAssert(m_object, "Invalid physics object"); @@ -231,7 +231,7 @@ namespace Ndk * \remark Produces a NazaraAssert if the physics object is invalid */ - inline bool PhysicsComponent::IsSleeping() const + inline bool PhysicsComponent3D::IsSleeping() const { NazaraAssert(m_object, "Invalid physics object"); @@ -246,7 +246,7 @@ namespace Ndk * \remark Produces a NazaraAssert if the physics object is invalid */ - inline void PhysicsComponent::SetAngularVelocity(const Nz::Vector3f& angularVelocity) + inline void PhysicsComponent3D::SetAngularVelocity(const Nz::Vector3f& angularVelocity) { NazaraAssert(m_object, "Invalid physics object"); @@ -261,7 +261,7 @@ namespace Ndk * \remark Produces a NazaraAssert if the physics object is invalid */ - inline void PhysicsComponent::SetGravityFactor(float gravityFactor) + inline void PhysicsComponent3D::SetGravityFactor(float gravityFactor) { NazaraAssert(m_object, "Invalid physics object"); @@ -277,7 +277,7 @@ namespace Ndk * \remark Produces a NazaraAssert if the mass is negative */ - inline void PhysicsComponent::SetMass(float mass) + inline void PhysicsComponent3D::SetMass(float mass) { NazaraAssert(m_object, "Invalid physics object"); NazaraAssert(mass > 0.f, "Mass should be positive"); @@ -293,7 +293,7 @@ namespace Ndk * \remark Produces a NazaraAssert if the physics object is invalid */ - inline void PhysicsComponent::SetMassCenter(const Nz::Vector3f& center) + inline void PhysicsComponent3D::SetMassCenter(const Nz::Vector3f& center) { NazaraAssert(m_object, "Invalid physics object"); @@ -308,7 +308,7 @@ namespace Ndk * \remark Produces a NazaraAssert if the physics object is invalid */ - inline void PhysicsComponent::SetPosition(const Nz::Vector3f& position) + inline void PhysicsComponent3D::SetPosition(const Nz::Vector3f& position) { NazaraAssert(m_object, "Invalid physics object"); @@ -323,7 +323,7 @@ namespace Ndk * \remark Produces a NazaraAssert if the physics object is invalid */ - inline void PhysicsComponent::SetRotation(const Nz::Quaternionf& rotation) + inline void PhysicsComponent3D::SetRotation(const Nz::Quaternionf& rotation) { NazaraAssert(m_object, "Invalid physics object"); @@ -338,7 +338,7 @@ namespace Ndk * \remark Produces a NazaraAssert if the physics object is invalid */ - inline void PhysicsComponent::SetVelocity(const Nz::Vector3f& velocity) + inline void PhysicsComponent3D::SetVelocity(const Nz::Vector3f& velocity) { NazaraAssert(m_object, "Invalid physics object"); @@ -350,7 +350,7 @@ namespace Ndk * \return A reference to the physics object */ - inline Nz::PhysObject& PhysicsComponent::GetPhysObject() + inline Nz::RigidBody3D& PhysicsComponent3D::GetPhysObject() { return *m_object.get(); } diff --git a/SDK/include/NDK/Components/VelocityComponent.hpp b/SDK/include/NDK/Components/VelocityComponent.hpp index 33d97b030..909adf4d4 100644 --- a/SDK/include/NDK/Components/VelocityComponent.hpp +++ b/SDK/include/NDK/Components/VelocityComponent.hpp @@ -12,7 +12,6 @@ namespace Ndk { - class Entity; class VelocityComponent; using VelocityComponentHandle = Nz::ObjectHandle; diff --git a/SDK/include/NDK/LuaAPI.hpp b/SDK/include/NDK/LuaAPI.hpp index e19458d3f..bc4631e47 100644 --- a/SDK/include/NDK/LuaAPI.hpp +++ b/SDK/include/NDK/LuaAPI.hpp @@ -24,7 +24,7 @@ namespace Ndk LuaAPI() = delete; ~LuaAPI() = delete; - static inline LuaBinding* GetBinding(); + static LuaBinding* GetBinding(); static bool Initialize(); diff --git a/SDK/include/NDK/LuaAPI.inl b/SDK/include/NDK/LuaAPI.inl index 6f1b73234..1ae2ddd43 100644 --- a/SDK/include/NDK/LuaAPI.inl +++ b/SDK/include/NDK/LuaAPI.inl @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -21,22 +22,10 @@ #include #include #include +#include #include #endif -namespace Ndk -{ - /*! - * \brief Gets the internal binding for Lua - * \return A pointer to the binding - */ - - inline LuaBinding* LuaAPI::GetBinding() - { - return s_binding; - } -} - namespace Nz { /*! @@ -143,6 +132,104 @@ namespace Nz return 1; } + /*! + * \brief Queries arguments for Lua + * \return 1 in case of success + * + * \param instance Lua instance to interact with + * \param index Index type + * \param params Resulting parameters for an image + */ + inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, ImageParams* params, TypeTag) + { + instance.CheckType(index, Nz::LuaType_Table); + + params->levelCount = instance.CheckField("LevelCount"); + params->loadFormat = instance.CheckField("LoadFormat"); + + return 1; + } + + /*! + * \brief Queries arguments for Lua + * \return 1 in case of success + * + * \param instance Lua instance to interact with + * \param index Index type + * \param address Resulting IP address + */ + + inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, IpAddress* address, TypeTag) + { + switch (instance.GetType(index)) + { + case Nz::LuaType_String: + address->BuildFromAddress(instance.CheckString(index)); + return 1; + + default: + *address = *static_cast(instance.CheckUserdata(index, "IpAddress")); + return 1; + } + } + + /*! + * \brief Queries arguments for Lua + * \return 1 in case of success + * + * \param instance Lua instance to interact with + * \param index Index type + * \param quat Resulting quaternion + */ + + inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Matrix4d* mat, TypeTag) + { + switch (instance.GetType(index)) + { + case Nz::LuaType_Table: + { + double values[16]; + for (std::size_t i = 0; i < 16; ++i) + { + instance.PushInteger(i + 1); + instance.GetTable(); + + values[i] = instance.CheckNumber(-1); + instance.Pop(); + } + + mat->Set(values); + return 1; + } + + default: + { + if (instance.IsOfType(index, "Matrix4")) + mat->Set(*static_cast(instance.ToUserdata(index))); + + return 1; + } + } + } + + /*! + * \brief Queries arguments for Lua + * \return 1 in case of success + * + * \param instance Lua instance to interact with + * \param index Index type + * \param quat Resulting quaternion + */ + + inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Matrix4f* mat, TypeTag) + { + Matrix4d matDouble; + unsigned int ret = LuaImplQueryArg(instance, index, &matDouble, TypeTag()); + + mat->Set(matDouble); + return ret; + } + /*! * \brief Queries arguments for Lua * \return 1 in case of success @@ -156,15 +243,62 @@ namespace Nz { instance.CheckType(index, Nz::LuaType_Table); - params->animated = instance.CheckField("Animated", params->animated); - params->center = instance.CheckField("Center", params->center); - params->flipUVs = instance.CheckField("FlipUVs", params->flipUVs); - //params->matrix = instance.CheckField("Matrix", params->matrix); + params->animated = instance.CheckField("Animated", params->animated); + params->center = instance.CheckField("Center", params->center); + params->flipUVs = instance.CheckField("FlipUVs", params->flipUVs); + params->matrix = instance.CheckField("Matrix", params->matrix); params->optimizeIndexBuffers = instance.CheckField("OptimizeIndexBuffers", params->optimizeIndexBuffers); return 1; } + /*! + * \brief Queries arguments for Lua + * \return 1 in case of success + * + * \param instance Lua instance to interact with + * \param index Index type + * \param quat Resulting quaternion + */ + + inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Quaterniond* quat, TypeTag) + { + switch (instance.GetType(index)) + { + case Nz::LuaType_Table: + quat->Set(instance.CheckField("w", index), instance.CheckField("x", index), instance.CheckField("y", index), instance.CheckField("z", index)); + return 1; + + default: + { + if (instance.IsOfType(index, "EulerAngles")) + quat->Set(*static_cast(instance.ToUserdata(index))); + else + quat->Set(*static_cast(instance.CheckUserdata(index, "Quaternion"))); + + return 1; + } + } + } + + /*! + * \brief Queries arguments for Lua + * \return 1 in case of success + * + * \param instance Lua instance to interact with + * \param index Index type + * \param quat Resulting quaternion + */ + + inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Quaternionf* quat, TypeTag) + { + Quaterniond quatDouble; + unsigned int ret = LuaImplQueryArg(instance, index, &quatDouble, TypeTag()); + + quat->Set(quatDouble); + return ret; + } + /*! * \brief Queries arguments for Lua * \return 1 in case of success @@ -222,76 +356,6 @@ namespace Nz return ret; } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param quat Resulting quaternion - */ - - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Quaterniond* quat, TypeTag) - { - switch (instance.GetType(index)) - { - case Nz::LuaType_Table: - quat->Set(instance.CheckField("w", index), instance.CheckField("x", index), instance.CheckField("y", index), instance.CheckField("z", index)); - return 1; - - default: - { - if (instance.IsOfType(index, "EulerAngles")) - quat->Set(*static_cast(instance.ToUserdata(index))); - else - quat->Set(*static_cast(instance.CheckUserdata(index, "Quaternion"))); - - return 1; - } - } - } - - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param quat Resulting quaternion - */ - - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Quaternionf* quat, TypeTag) - { - Quaterniond quatDouble; - unsigned int ret = LuaImplQueryArg(instance, index, &quatDouble, TypeTag()); - - quat->Set(quatDouble); - return ret; - } - - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param address Resulting IP address - */ - - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, IpAddress* address, TypeTag) - { - switch (instance.GetType(index)) - { - case Nz::LuaType_String: - address->BuildFromAddress(instance.CheckString(index)); - return 1; - - default: - *address = *static_cast(instance.CheckUserdata(index, "IpAddress")); - return 1; - } - } - /*! * \brief Queries arguments for Lua * \return 1 in case of success @@ -469,10 +533,31 @@ namespace Nz inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, InstancedRenderableRef* renderable, TypeTag) { - if (instance.IsOfType(index, "InstancedRenderable")) - *renderable = *static_cast(instance.CheckUserdata(index, "InstancedRenderable")); + if (instance.IsOfType(index, "InstancedRenderable") || + instance.IsOfType(index, "Model") || + instance.IsOfType(index, "Sprite")) + { + *renderable = *static_cast(instance.ToUserdata(index)); + } else - *renderable = *static_cast(instance.CheckUserdata(index, "Model")); + instance.ArgError(index, "is not a InstancedRenderable instance"); + + return 1; + } + + /*! + * \brief Queries arguments for Lua + * \return 1 in case of success + * + * \param instance Lua instance to interact with + * \param index Index type + * \param renderable Resulting reference to a material + */ + + inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MaterialRef* materialRef, TypeTag) + { + *materialRef = *static_cast(instance.CheckUserdata(index, "Material")); + return 1; } @@ -495,6 +580,7 @@ namespace Nz params->loadHeightMap = instance.CheckField("LoadHeightMap", params->loadHeightMap); params->loadNormalMap = instance.CheckField("LoadNormalMap", params->loadNormalMap); params->loadSpecularMap = instance.CheckField("LoadSpecularMap", params->loadSpecularMap); + params->shaderName = instance.CheckField("ShaderName", params->shaderName); return 1; } @@ -556,8 +642,59 @@ namespace Nz return 1; } + /*! + * \brief Queries arguments for Lua + * \return 1 in case of success + * + * \param instance Lua instance to interact with + * \param index Index type + * \param renderable Resulting reference to a sprite + */ + + inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, SpriteRef* spriteRef, TypeTag) + { + *spriteRef = *static_cast(instance.CheckUserdata(index, "Sprite")); + + return 1; + } + + /*! + * \brief Queries arguments for Lua + * \return 1 in case of success + * + * \param instance Lua instance to interact with + * \param index Index type + * \param fontRef Resulting reference to a font + */ + + inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, TextureRef* textureRef, TypeTag) + { + *textureRef = *static_cast(instance.CheckUserdata(index, "Texture")); + + return 1; + } + #endif + /*! + * \brief Replies by value for Lua + * \return 1 in case of success + * + * \param instance Lua instance to interact with + * \param val Resulting color + */ + + inline int LuaImplReplyVal(const LuaInstance& instance, Color&& val, TypeTag) + { + instance.PushTable(); + instance.PushField("r", val.r); + instance.PushField("g", val.g); + instance.PushField("b", val.b); + instance.PushField("a", val.a); + + return 1; + } + /*! * \brief Replies by value for Lua * \return 1 in case of success @@ -619,6 +756,65 @@ namespace Nz return 1; } + /*! + * \brief Replies by value for Lua + * \return 1 in case of success + * + * \param instance Lua instance to interact with + * \param val Resulting ImageParams + */ + + inline int LuaImplReplyVal(const LuaInstance& instance, ImageParams&& val, TypeTag) + { + instance.PushTable(0, 2); + instance.PushField("LevelCount", val.levelCount); + instance.PushField("LoadFormat", val.loadFormat); + + return 1; + } + + /*! + * \brief Replies by value for Lua + * \return 1 in case of success + * + * \param instance Lua instance to interact with + * \param val Resulting IP address + */ + + inline int LuaImplReplyVal(const LuaInstance& instance, IpAddress&& val, TypeTag) + { + instance.PushInstance("IpAddress", val); + return 1; + } + + /*! + * \brief Replies by value for Lua + * \return 1 in case of success + * + * \param instance Lua instance to interact with + * \param val Resulting rectangle + */ + + inline int LuaImplReplyVal(const LuaInstance& instance, Matrix4d&& val, TypeTag) + { + instance.PushInstance("Matrix4", val); + return 1; + } + + /*! + * \brief Replies by value for Lua + * \return 1 in case of success + * + * \param instance Lua instance to interact with + * \param val Resulting rectangle + */ + + inline int LuaImplReplyVal(const LuaInstance& instance, Matrix4f&& val, TypeTag) + { + instance.PushInstance("Matrix4", val); + return 1; + } + /*! * \brief Replies by value for Lua * \return 1 in case of success @@ -647,20 +843,6 @@ namespace Nz return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param val Resulting IP address - */ - - inline int LuaImplReplyVal(const LuaInstance& instance, IpAddress&& val, TypeTag) - { - instance.PushInstance("IpAddress", val); - return 1; - } - /*! * \brief Replies by value for Lua * \return 1 in case of success @@ -669,7 +851,7 @@ namespace Nz * \param val Resulting rectangle */ - inline int LuaImplReplyVal(const LuaInstance& instance, Rectd&& val, TypeTag) + inline int LuaImplReplyVal(const LuaInstance& instance, Rectd&& val, TypeTag) { instance.PushInstance("Rect", val); return 1; @@ -887,6 +1069,62 @@ namespace Nz #ifndef NDK_SERVER + /*! + * \brief Replies by value for Lua + * \return 1 in case of success + * + * \param instance Lua instance to interact with + * \param handle Resulting material + */ + + inline int LuaImplReplyVal(const LuaInstance& instance, MaterialRef&& handle, TypeTag) + { + instance.PushInstance("Material", handle); + return 1; + } + + /*! + * \brief Replies by value for Lua + * \return 1 in case of success + * + * \param instance Lua instance to interact with + * \param val Resulting sound buffer + */ + + inline int LuaImplReplyVal(const LuaInstance& instance, const SoundBuffer* val, TypeTag) + { + instance.PushInstance("SoundBuffer", val); + return 1; + } + + /*! + * \brief Replies by value for Lua + * \return 1 in case of success + * + * \param instance Lua instance to interact with + * \param handle Resulting sprite + */ + + inline int LuaImplReplyVal(const LuaInstance& instance, SpriteRef&& handle, TypeTag) + { + instance.PushInstance("Sprite", handle); + return 1; + } + + /*! + * \brief Replies by value for Lua + * \return 1 in case of success + * + * \param instance Lua instance to interact with + * \param handle Resulting texture + */ + + inline int LuaImplReplyVal(const LuaInstance& instance, TextureRef&& handle, TypeTag) + { + instance.PushInstance("Texture", handle); + return 1; + } + /*! * \brief Replies by value for Lua * \return 1 in case of success @@ -914,21 +1152,6 @@ namespace Nz instance.PushInstance("GraphicsComponent", handle); return 1; } - - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param val Resulting sound buffer - */ - - inline int LuaImplReplyVal(const LuaInstance& instance, const SoundBuffer* val, TypeTag) - { - instance.PushInstance("SoundBuffer", val); - return 1; - } - #endif } diff --git a/SDK/include/NDK/LuaBinding.hpp b/SDK/include/NDK/LuaBinding.hpp index cb4fc24e5..0eb083162 100644 --- a/SDK/include/NDK/LuaBinding.hpp +++ b/SDK/include/NDK/LuaBinding.hpp @@ -38,47 +38,56 @@ namespace Ndk void RegisterClasses(Nz::LuaInstance& instance); // Core - Nz::LuaClass clockClass; - Nz::LuaClass directoryClass; - Nz::LuaClass fileClass; - Nz::LuaClass streamClass; + Nz::LuaClass clock; + Nz::LuaClass directory; + Nz::LuaClass file; + Nz::LuaClass stream; // Math - Nz::LuaClass eulerAnglesClass; - Nz::LuaClass quaternionClass; - Nz::LuaClass rectClass; - Nz::LuaClass vector2dClass; - Nz::LuaClass vector3dClass; + Nz::LuaClass eulerAngles; + Nz::LuaClass matrix4d; + Nz::LuaClass quaternion; + Nz::LuaClass rect; + Nz::LuaClass vector2d; + Nz::LuaClass vector3d; // Network - Nz::LuaClass abstractSocketClass; - Nz::LuaClass ipAddressClass; + Nz::LuaClass abstractSocket; + Nz::LuaClass ipAddress; // Utility - Nz::LuaClass abstractImage; - Nz::LuaClass fontClass; - Nz::LuaClass nodeClass; + Nz::LuaClass abstractImage; + Nz::LuaClass font; + Nz::LuaClass node; // SDK Nz::LuaClass application; - Nz::LuaClass entityClass; + Nz::LuaClass entity; Nz::LuaClass nodeComponent; Nz::LuaClass velocityComponent; - Nz::LuaClass worldClass; + Nz::LuaClass world; #ifndef NDK_SERVER // Audio - Nz::LuaClass musicClass; - Nz::LuaClass soundClass; + Nz::LuaClass music; + Nz::LuaClass sound; Nz::LuaClass soundBuffer; Nz::LuaClass soundEmitter; // Graphics Nz::LuaClass instancedRenderable; - Nz::LuaClass modelClass; + Nz::LuaClass material; + Nz::LuaClass model; + Nz::LuaClass sprite; + Nz::LuaClass spriteLibrary; + Nz::LuaClass textureLibrary; + Nz::LuaClass textureManager; + + // Renderer + Nz::LuaClass texture; // SDK - Nz::LuaClass consoleClass; + Nz::LuaClass console; Nz::LuaClass graphicsComponent; #endif @@ -117,7 +126,7 @@ namespace Ndk Nz::String name; }; - ComponentBinding* QueryComponentIndex(Nz::LuaInstance& lua, int argIndex = 1); + ComponentBinding* QueryComponentIndex(Nz::LuaInstance& lua, int argIndex = 2); std::vector m_componentBinding; std::unordered_map m_componentBindingByName; diff --git a/SDK/include/NDK/Systems.hpp b/SDK/include/NDK/Systems.hpp index 269bead6f..45a79bc6c 100644 --- a/SDK/include/NDK/Systems.hpp +++ b/SDK/include/NDK/Systems.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 30 Jul 2016 at 15:29:16 +// This file was automatically generated #pragma once @@ -7,7 +7,7 @@ #include #include -#include +#include #include #include diff --git a/SDK/include/NDK/Systems/PhysicsSystem.hpp b/SDK/include/NDK/Systems/PhysicsSystem.hpp deleted file mode 100644 index a5b0b9fcc..000000000 --- a/SDK/include/NDK/Systems/PhysicsSystem.hpp +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequesites.hpp - -#pragma once - -#ifndef NDK_SYSTEMS_PHYSICSSYSTEM_HPP -#define NDK_SYSTEMS_PHYSICSSYSTEM_HPP - -#include -#include -#include - -namespace Ndk -{ - class NDK_API PhysicsSystem : public System - { - public: - PhysicsSystem(); - PhysicsSystem(const PhysicsSystem& system); - ~PhysicsSystem() = default; - - Nz::PhysWorld& GetWorld(); - const Nz::PhysWorld& GetWorld() const; - - static SystemIndex systemIndex; - - private: - void OnEntityValidation(Entity* entity, bool justAdded) override; - void OnUpdate(float elapsedTime) override; - - EntityList m_dynamicObjects; - EntityList m_staticObjects; - Nz::PhysWorld m_world; - }; -} - -#include - -#endif // NDK_SYSTEMS_PHYSICSSYSTEM_HPP diff --git a/SDK/include/NDK/Systems/PhysicsSystem3D.hpp b/SDK/include/NDK/Systems/PhysicsSystem3D.hpp new file mode 100644 index 000000000..35194b7c8 --- /dev/null +++ b/SDK/include/NDK/Systems/PhysicsSystem3D.hpp @@ -0,0 +1,42 @@ +// Copyright (C) 2015 Jérôme Leclercq +// This file is part of the "Nazara Development Kit" +// For conditions of distribution and use, see copyright notice in Prerequesites.hpp + +#pragma once + +#ifndef NDK_SYSTEMS_PHYSICSSYSTEM3D_HPP +#define NDK_SYSTEMS_PHYSICSSYSTEM3D_HPP + +#include +#include +#include +#include + +namespace Ndk +{ + class NDK_API PhysicsSystem3D : public System + { + public: + PhysicsSystem3D(); + PhysicsSystem3D(const PhysicsSystem3D& system); + ~PhysicsSystem3D() = default; + + Nz::PhysWorld3D& GetWorld(); + const Nz::PhysWorld3D& GetWorld() const; + + static SystemIndex systemIndex; + + private: + void CreatePhysWorld() const; + void OnEntityValidation(Entity* entity, bool justAdded) override; + void OnUpdate(float elapsedTime) override; + + EntityList m_dynamicObjects; + EntityList m_staticObjects; + mutable std::unique_ptr m_world; ///TODO: std::optional (Should I make a Nz::Optional class?) + }; +} + +#include + +#endif // NDK_SYSTEMS_PHYSICSSYSTEM3D_HPP diff --git a/SDK/include/NDK/Systems/PhysicsSystem.inl b/SDK/include/NDK/Systems/PhysicsSystem3D.inl similarity index 62% rename from SDK/include/NDK/Systems/PhysicsSystem.inl rename to SDK/include/NDK/Systems/PhysicsSystem3D.inl index bfe886cb1..b6b1cbb03 100644 --- a/SDK/include/NDK/Systems/PhysicsSystem.inl +++ b/SDK/include/NDK/Systems/PhysicsSystem3D.inl @@ -9,9 +9,12 @@ namespace Ndk * \return A reference to the physical world */ - inline Nz::PhysWorld& PhysicsSystem::GetWorld() + inline Nz::PhysWorld3D& PhysicsSystem3D::GetWorld() { - return m_world; + if (!m_world) + CreatePhysWorld(); + + return *m_world; } /*! @@ -19,8 +22,11 @@ namespace Ndk * \return A constant reference to the physical world */ - inline const Nz::PhysWorld& PhysicsSystem::GetWorld() const + inline const Nz::PhysWorld3D& PhysicsSystem3D::GetWorld() const { - return m_world; + if (!m_world) + CreatePhysWorld(); + + return *m_world; } } diff --git a/SDK/src/NDK/Application.cpp b/SDK/src/NDK/Application.cpp index 46e1db13d..f184d5b0b 100644 --- a/SDK/src/NDK/Application.cpp +++ b/SDK/src/NDK/Application.cpp @@ -98,9 +98,7 @@ namespace Ndk ++it; } - #endif - #ifndef NDK_SERVER if (m_exitOnClosedWindows && !hasAtLeastOneActiveWindow) return false; #endif diff --git a/SDK/src/NDK/Components/CollisionComponent.cpp b/SDK/src/NDK/Components/CollisionComponent3D.cpp similarity index 61% rename from SDK/src/NDK/Components/CollisionComponent.cpp rename to SDK/src/NDK/Components/CollisionComponent3D.cpp index 0f812e73b..423b06cb4 100644 --- a/SDK/src/NDK/Components/CollisionComponent.cpp +++ b/SDK/src/NDK/Components/CollisionComponent3D.cpp @@ -2,18 +2,18 @@ // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp -#include -#include +#include +#include #include #include -#include -#include +#include +#include namespace Ndk { /*! * \ingroup NDK - * \class Ndk::CollisionComponent + * \class Ndk::CollisionComponent3D * \brief NDK class that represents the component for collision (meant for static objects) */ @@ -25,14 +25,14 @@ namespace Ndk * \remark Produces a NazaraAssert if the entity has no physics component and has no static body */ - void CollisionComponent::SetGeom(Nz::PhysGeomRef geom) + void CollisionComponent3D::SetGeom(Nz::Collider3DRef geom) { m_geom = std::move(geom); - if (m_entity->HasComponent()) + if (m_entity->HasComponent()) { - // We update the geometry of the PhysiscsObject linked to the PhysicsComponent - PhysicsComponent& physComponent = m_entity->GetComponent(); + // We update the geometry of the PhysiscsObject linked to the PhysicsComponent3D + PhysicsComponent3D& physComponent = m_entity->GetComponent(); physComponent.GetPhysObject().SetGeom(m_geom); } else @@ -49,16 +49,16 @@ namespace Ndk * \remark Produces a NazaraAssert if entity is not linked to a world, or the world has no physics system */ - void CollisionComponent::InitializeStaticBody() + void CollisionComponent3D::InitializeStaticBody() { NazaraAssert(m_entity, "Invalid entity"); World* entityWorld = m_entity->GetWorld(); NazaraAssert(entityWorld, "Entity must have world"); - NazaraAssert(entityWorld->HasSystem(), "World must have a physics system"); - Nz::PhysWorld& physWorld = entityWorld->GetSystem().GetWorld(); + NazaraAssert(entityWorld->HasSystem(), "World must have a physics system"); + Nz::PhysWorld3D& physWorld = entityWorld->GetSystem().GetWorld(); - m_staticBody.reset(new Nz::PhysObject(&physWorld, m_geom)); + m_staticBody.reset(new Nz::RigidBody3D(&physWorld, m_geom)); m_staticBody->EnableAutoSleep(false); } @@ -66,9 +66,9 @@ namespace Ndk * \brief Operation to perform when component is attached to an entity */ - void CollisionComponent::OnAttached() + void CollisionComponent3D::OnAttached() { - if (!m_entity->HasComponent()) + if (!m_entity->HasComponent()) InitializeStaticBody(); } @@ -78,9 +78,9 @@ namespace Ndk * \param component Component being attached */ - void CollisionComponent::OnComponentAttached(BaseComponent& component) + void CollisionComponent3D::OnComponentAttached(BaseComponent& component) { - if (IsComponent(component)) + if (IsComponent(component)) m_staticBody.reset(); } @@ -90,9 +90,9 @@ namespace Ndk * \param component Component being detached */ - void CollisionComponent::OnComponentDetached(BaseComponent& component) + void CollisionComponent3D::OnComponentDetached(BaseComponent& component) { - if (IsComponent(component)) + if (IsComponent(component)) InitializeStaticBody(); } @@ -100,10 +100,10 @@ namespace Ndk * \brief Operation to perform when component is detached from an entity */ - void CollisionComponent::OnDetached() + void CollisionComponent3D::OnDetached() { m_staticBody.reset(); } - ComponentIndex CollisionComponent::componentIndex; + ComponentIndex CollisionComponent3D::componentIndex; } diff --git a/SDK/src/NDK/Components/GraphicsComponent.cpp b/SDK/src/NDK/Components/GraphicsComponent.cpp index e06890c97..954dd2de2 100644 --- a/SDK/src/NDK/Components/GraphicsComponent.cpp +++ b/SDK/src/NDK/Components/GraphicsComponent.cpp @@ -131,8 +131,6 @@ namespace Ndk { NazaraAssert(m_entity && m_entity->HasComponent(), "GraphicsComponent requires NodeComponent"); - Ndk::RenderSystem& renderSystem = m_entity->GetWorld()->GetSystem(); - m_transformMatrix = m_entity->GetComponent().GetTransformMatrix(); m_transformMatrixUpdated = true; } diff --git a/SDK/src/NDK/Components/PhysicsComponent.cpp b/SDK/src/NDK/Components/PhysicsComponent3D.cpp similarity index 56% rename from SDK/src/NDK/Components/PhysicsComponent.cpp rename to SDK/src/NDK/Components/PhysicsComponent3D.cpp index 6cfd1077d..7dfffab85 100644 --- a/SDK/src/NDK/Components/PhysicsComponent.cpp +++ b/SDK/src/NDK/Components/PhysicsComponent3D.cpp @@ -2,19 +2,19 @@ // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp -#include -#include +#include +#include #include #include -#include +#include #include -#include +#include namespace Ndk { /*! * \ingroup NDK - * \class Ndk::PhysicsComponent + * \class Ndk::PhysicsComponent3D * \brief NDK class that represents the component for physics (meant for dynamic objects) */ @@ -24,16 +24,16 @@ namespace Ndk * \remark Produces a NazaraAssert if the world does not have a physics system */ - void PhysicsComponent::OnAttached() + void PhysicsComponent3D::OnAttached() { World* entityWorld = m_entity->GetWorld(); - NazaraAssert(entityWorld->HasSystem(), "World must have a physics system"); + NazaraAssert(entityWorld->HasSystem(), "World must have a physics system"); - Nz::PhysWorld& world = entityWorld->GetSystem().GetWorld(); + Nz::PhysWorld3D& world = entityWorld->GetSystem().GetWorld(); - Nz::PhysGeomRef geom; - if (m_entity->HasComponent()) - geom = m_entity->GetComponent().GetGeom(); + Nz::Collider3DRef geom; + if (m_entity->HasComponent()) + geom = m_entity->GetComponent().GetGeom(); Nz::Matrix4f matrix; if (m_entity->HasComponent()) @@ -41,7 +41,7 @@ namespace Ndk else matrix.MakeIdentity(); - m_object.reset(new Nz::PhysObject(&world, geom, matrix)); + m_object.reset(new Nz::RigidBody3D(&world, geom, matrix)); m_object->SetMass(1.f); } @@ -53,12 +53,12 @@ namespace Ndk * \remark Produces a NazaraAssert if physical object is invalid */ - void PhysicsComponent::OnComponentAttached(BaseComponent& component) + void PhysicsComponent3D::OnComponentAttached(BaseComponent& component) { - if (IsComponent(component)) + if (IsComponent(component)) { NazaraAssert(m_object, "Invalid object"); - m_object->SetGeom(static_cast(component).GetGeom()); + m_object->SetGeom(static_cast(component).GetGeom()); } } @@ -70,12 +70,12 @@ namespace Ndk * \remark Produces a NazaraAssert if physical object is invalid */ - void PhysicsComponent::OnComponentDetached(BaseComponent& component) + void PhysicsComponent3D::OnComponentDetached(BaseComponent& component) { - if (IsComponent(component)) + if (IsComponent(component)) { NazaraAssert(m_object, "Invalid object"); - m_object->SetGeom(Nz::NullGeom::New()); + m_object->SetGeom(Nz::NullCollider3D::New()); } } @@ -83,10 +83,10 @@ namespace Ndk * \brief Operation to perform when component is detached from an entity */ - void PhysicsComponent::OnDetached() + void PhysicsComponent3D::OnDetached() { m_object.reset(); } - ComponentIndex PhysicsComponent::componentIndex; + ComponentIndex PhysicsComponent3D::componentIndex; } diff --git a/SDK/src/NDK/LuaAPI.cpp b/SDK/src/NDK/LuaAPI.cpp index 1bf4eec35..fba28b2b3 100644 --- a/SDK/src/NDK/LuaAPI.cpp +++ b/SDK/src/NDK/LuaAPI.cpp @@ -1,6 +1,7 @@ // This file was automatically generated on 26 May 2014 at 01:05:31 #include +#include #include namespace Ndk @@ -11,6 +12,21 @@ namespace Ndk * \brief NDK class that represents the api used for Lua */ + /*! + * \brief Gets the internal binding for Lua + * \return A pointer to the binding + */ + LuaBinding* LuaAPI::GetBinding() + { + if (!s_binding && !Initialize()) + { + NazaraError("Failed to initialize binding"); + return nullptr; + } + + return s_binding; + } + /*! * \brief Initializes the LuaAPI module * \return true if initialization is successful @@ -30,13 +46,8 @@ namespace Ndk void LuaAPI::RegisterClasses(Nz::LuaInstance& instance) { - if (!s_binding && !Initialize()) - { - NazaraError("Failed to initialize binding"); - return; - } - - s_binding->RegisterClasses(instance); + Nz::ErrorFlags errFlags(Nz::ErrorFlag_ThrowException, true); + GetBinding()->RegisterClasses(instance); } /*! diff --git a/SDK/src/NDK/LuaBinding.cpp b/SDK/src/NDK/LuaBinding.cpp index 822654a39..789427f26 100644 --- a/SDK/src/NDK/LuaBinding.cpp +++ b/SDK/src/NDK/LuaBinding.cpp @@ -16,49 +16,58 @@ namespace Ndk LuaBinding::LuaBinding() : // Core - clockClass("Clock"), - directoryClass("Directory"), - fileClass("File"), - streamClass("Stream"), + clock("Clock"), + directory("Directory"), + file("File"), + stream("Stream"), // Math - eulerAnglesClass("EulerAngles"), - quaternionClass("Quaternion"), - rectClass("Rect"), - vector2dClass("Vector2"), - vector3dClass("Vector3"), + eulerAngles("EulerAngles"), + matrix4d("Matrix4"), + quaternion("Quaternion"), + rect("Rect"), + vector2d("Vector2"), + vector3d("Vector3"), // Network - abstractSocketClass("AbstractSocket"), - ipAddressClass("IpAddress"), + abstractSocket("AbstractSocket"), + ipAddress("IpAddress"), // Utility abstractImage("AbstractImage"), - fontClass("Font"), - nodeClass("Node"), + font("Font"), + node("Node"), // SDK application("Application"), - entityClass("Entity"), + entity("Entity"), nodeComponent("NodeComponent"), velocityComponent("VelocityComponent"), - worldClass("World") + world("World") #ifndef NDK_SERVER , // Audio - musicClass("Music"), - soundClass("Sound"), + music("Music"), + sound("Sound"), soundBuffer("SoundBuffer"), soundEmitter("SoundEmitter"), // Graphics instancedRenderable("InstancedRenderable"), - modelClass("Model"), + material("Material"), + model("Model"), + sprite("Sprite"), + spriteLibrary("SpriteLibrary"), + textureLibrary("TextureLibrary"), + textureManager("TextureManager"), + + // Renderer + texture("Texture"), // SDK - consoleClass("Console"), + console("Console"), graphicsComponent("GraphicsComponent") #endif { diff --git a/SDK/src/NDK/LuaBinding_Audio.cpp b/SDK/src/NDK/LuaBinding_Audio.cpp index ed1538a78..46791b6c7 100644 --- a/SDK/src/NDK/LuaBinding_Audio.cpp +++ b/SDK/src/NDK/LuaBinding_Audio.cpp @@ -13,35 +13,35 @@ namespace Ndk void LuaBinding::BindAudio() { /*********************************** Nz::Music **********************************/ - musicClass.Inherit(soundEmitter); + music.Inherit(soundEmitter); - musicClass.BindDefaultConstructor(); + music.BindDefaultConstructor(); //musicClass.SetMethod("Create", &Nz::Music::Create); //musicClass.SetMethod("Destroy", &Nz::Music::Destroy); - musicClass.BindMethod("EnableLooping", &Nz::Music::EnableLooping); + music.BindMethod("EnableLooping", &Nz::Music::EnableLooping); - musicClass.BindMethod("GetDuration", &Nz::Music::GetDuration); - musicClass.BindMethod("GetFormat", &Nz::Music::GetFormat); - musicClass.BindMethod("GetPlayingOffset", &Nz::Music::GetPlayingOffset); - musicClass.BindMethod("GetSampleCount", &Nz::Music::GetSampleCount); - musicClass.BindMethod("GetSampleRate", &Nz::Music::GetSampleRate); - musicClass.BindMethod("GetStatus", &Nz::Music::GetStatus); + music.BindMethod("GetDuration", &Nz::Music::GetDuration); + music.BindMethod("GetFormat", &Nz::Music::GetFormat); + music.BindMethod("GetPlayingOffset", &Nz::Music::GetPlayingOffset); + music.BindMethod("GetSampleCount", &Nz::Music::GetSampleCount); + music.BindMethod("GetSampleRate", &Nz::Music::GetSampleRate); + music.BindMethod("GetStatus", &Nz::Music::GetStatus); - musicClass.BindMethod("IsLooping", &Nz::Music::IsLooping); + music.BindMethod("IsLooping", &Nz::Music::IsLooping); - musicClass.BindMethod("OpenFromFile", &Nz::Music::OpenFromFile, Nz::MusicParams()); + music.BindMethod("OpenFromFile", &Nz::Music::OpenFromFile, Nz::MusicParams()); - musicClass.BindMethod("Pause", &Nz::Music::Pause); - musicClass.BindMethod("Play", &Nz::Music::Play); + music.BindMethod("Pause", &Nz::Music::Pause); + music.BindMethod("Play", &Nz::Music::Play); - musicClass.BindMethod("SetPlayingOffset", &Nz::Music::SetPlayingOffset); + music.BindMethod("SetPlayingOffset", &Nz::Music::SetPlayingOffset); - musicClass.BindMethod("Stop", &Nz::Music::Stop); + music.BindMethod("Stop", &Nz::Music::Stop); // Manual - musicClass.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Music& music) -> int + music.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Music& music, std::size_t /*argumentCount*/) -> int { Nz::StringStream stream("Music("); stream << music.GetFilePath() << ')'; @@ -51,21 +51,21 @@ namespace Ndk }); /*********************************** Nz::Sound **********************************/ - soundClass.Inherit(soundEmitter); + sound.Inherit(soundEmitter); - soundClass.BindDefaultConstructor(); + sound.BindDefaultConstructor(); - soundClass.BindMethod("GetBuffer", &Nz::Sound::GetBuffer); + sound.BindMethod("GetBuffer", &Nz::Sound::GetBuffer); - soundClass.BindMethod("IsPlayable", &Nz::Sound::IsPlayable); - soundClass.BindMethod("IsPlaying", &Nz::Sound::IsPlaying); + sound.BindMethod("IsPlayable", &Nz::Sound::IsPlayable); + sound.BindMethod("IsPlaying", &Nz::Sound::IsPlaying); - soundClass.BindMethod("LoadFromFile", &Nz::Sound::LoadFromFile, Nz::SoundBufferParams()); + sound.BindMethod("LoadFromFile", &Nz::Sound::LoadFromFile, Nz::SoundBufferParams()); - soundClass.BindMethod("SetPlayingOffset", &Nz::Sound::SetPlayingOffset); + sound.BindMethod("SetPlayingOffset", &Nz::Sound::SetPlayingOffset); // Manual - soundClass.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Sound& sound) -> int + sound.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Sound& sound, std::size_t /*argumentCount*/) -> int { Nz::StringStream stream("Sound("); if (const Nz::SoundBuffer* buffer = sound.GetBuffer()) @@ -101,9 +101,9 @@ namespace Ndk soundBuffer.BindStaticMethod("IsFormatSupported", &Nz::SoundBuffer::IsFormatSupported); // Manual - soundBuffer.BindMethod("Create", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance) -> int + soundBuffer.BindMethod("Create", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int { - int index = 1; + int index = 2; Nz::AudioFormat format = lua.Check(&index); unsigned int sampleCount = lua.Check(&index); unsigned int sampleRate = lua.Check(&index); @@ -116,13 +116,13 @@ namespace Ndk return 1; }); - soundBuffer.BindMethod("GetSamples", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance) -> int + soundBuffer.BindMethod("GetSamples", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int { lua.PushString(reinterpret_cast(instance->GetSamples()), instance->GetSampleCount() * sizeof(Nz::Int16)); return 1; }); - soundBuffer.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance) -> int + soundBuffer.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int { Nz::StringStream stream("SoundBuffer("); if (instance->IsValid()) @@ -177,8 +177,8 @@ namespace Ndk void LuaBinding::RegisterAudio(Nz::LuaInstance& instance) { - musicClass.Register(instance); - soundClass.Register(instance); + music.Register(instance); + sound.Register(instance); soundBuffer.Register(instance); soundEmitter.Register(instance); } diff --git a/SDK/src/NDK/LuaBinding_Core.cpp b/SDK/src/NDK/LuaBinding_Core.cpp index d111a0266..dc149e3d0 100644 --- a/SDK/src/NDK/LuaBinding_Core.cpp +++ b/SDK/src/NDK/LuaBinding_Core.cpp @@ -13,9 +13,9 @@ namespace Ndk void LuaBinding::BindCore() { /*********************************** Nz::Clock **********************************/ - clockClass.SetConstructor([](Nz::LuaInstance& lua, Nz::Clock* clock, std::size_t argumentCount) + clock.SetConstructor([](Nz::LuaInstance& lua, Nz::Clock* clock, std::size_t /*argumentCount*/) { - int argIndex = 1; + int argIndex = 2; Nz::Int64 startingValue = lua.Check(&argIndex, 0); bool paused = lua.Check(&argIndex, false); @@ -23,16 +23,16 @@ namespace Ndk return true; }); - clockClass.BindMethod("GetMicroseconds", &Nz::Clock::GetMicroseconds); - clockClass.BindMethod("GetMilliseconds", &Nz::Clock::GetMilliseconds); - clockClass.BindMethod("GetSeconds", &Nz::Clock::GetSeconds); - clockClass.BindMethod("IsPaused", &Nz::Clock::IsPaused); - clockClass.BindMethod("Pause", &Nz::Clock::Pause); - clockClass.BindMethod("Restart", &Nz::Clock::Restart); - clockClass.BindMethod("Unpause", &Nz::Clock::Unpause); + clock.BindMethod("GetMicroseconds", &Nz::Clock::GetMicroseconds); + clock.BindMethod("GetMilliseconds", &Nz::Clock::GetMilliseconds); + clock.BindMethod("GetSeconds", &Nz::Clock::GetSeconds); + clock.BindMethod("IsPaused", &Nz::Clock::IsPaused); + clock.BindMethod("Pause", &Nz::Clock::Pause); + clock.BindMethod("Restart", &Nz::Clock::Restart); + clock.BindMethod("Unpause", &Nz::Clock::Unpause); // Manual - clockClass.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Clock& clock) -> int { + clock.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Clock& clock, std::size_t /*argumentCount*/) -> int { Nz::StringStream stream("Clock(Elapsed: "); stream << clock.GetSeconds(); stream << "s, Paused: "; @@ -44,11 +44,11 @@ namespace Ndk }); /********************************* Nz::Directory ********************************/ - directoryClass.SetConstructor([](Nz::LuaInstance& lua, Nz::Directory* directory, std::size_t argumentCount) + directory.SetConstructor([](Nz::LuaInstance& lua, Nz::Directory* directory, std::size_t argumentCount) { std::size_t argCount = std::min(argumentCount, 1U); - int argIndex = 1; + int argIndex = 2; switch (argCount) { case 0: @@ -63,29 +63,29 @@ namespace Ndk return false; }); - directoryClass.BindMethod("Close", &Nz::Directory::Close); - directoryClass.BindMethod("Exists", &Nz::Directory::Exists); - directoryClass.BindMethod("GetPath", &Nz::Directory::GetPath); - directoryClass.BindMethod("GetPattern", &Nz::Directory::GetPattern); - directoryClass.BindMethod("GetResultName", &Nz::Directory::GetResultName); - directoryClass.BindMethod("GetResultPath", &Nz::Directory::GetResultPath); - directoryClass.BindMethod("GetResultSize", &Nz::Directory::GetResultSize); - directoryClass.BindMethod("IsOpen", &Nz::Directory::IsOpen); - directoryClass.BindMethod("IsResultDirectory", &Nz::Directory::IsResultDirectory); - directoryClass.BindMethod("NextResult", &Nz::Directory::NextResult, true); - directoryClass.BindMethod("Open", &Nz::Directory::Open); - directoryClass.BindMethod("SetPath", &Nz::Directory::SetPath); - directoryClass.BindMethod("SetPattern", &Nz::Directory::SetPattern); + directory.BindMethod("Close", &Nz::Directory::Close); + directory.BindMethod("Exists", &Nz::Directory::Exists); + directory.BindMethod("GetPath", &Nz::Directory::GetPath); + directory.BindMethod("GetPattern", &Nz::Directory::GetPattern); + directory.BindMethod("GetResultName", &Nz::Directory::GetResultName); + directory.BindMethod("GetResultPath", &Nz::Directory::GetResultPath); + directory.BindMethod("GetResultSize", &Nz::Directory::GetResultSize); + directory.BindMethod("IsOpen", &Nz::Directory::IsOpen); + directory.BindMethod("IsResultDirectory", &Nz::Directory::IsResultDirectory); + directory.BindMethod("NextResult", &Nz::Directory::NextResult, true); + directory.BindMethod("Open", &Nz::Directory::Open); + directory.BindMethod("SetPath", &Nz::Directory::SetPath); + directory.BindMethod("SetPattern", &Nz::Directory::SetPattern); - directoryClass.BindStaticMethod("Copy", Nz::Directory::Copy); - directoryClass.BindStaticMethod("Create", Nz::Directory::Create); - directoryClass.BindStaticMethod("Exists", Nz::Directory::Exists); - directoryClass.BindStaticMethod("GetCurrent", Nz::Directory::GetCurrent); - directoryClass.BindStaticMethod("Remove", Nz::Directory::Remove); - directoryClass.BindStaticMethod("SetCurrent", Nz::Directory::SetCurrent); + directory.BindStaticMethod("Copy", Nz::Directory::Copy); + directory.BindStaticMethod("Create", Nz::Directory::Create); + directory.BindStaticMethod("Exists", Nz::Directory::Exists); + directory.BindStaticMethod("GetCurrent", Nz::Directory::GetCurrent); + directory.BindStaticMethod("Remove", Nz::Directory::Remove); + directory.BindStaticMethod("SetCurrent", Nz::Directory::SetCurrent); // Manual - directoryClass.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Directory& directory) -> int { + directory.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Directory& directory, std::size_t /*argumentCount*/) -> int { Nz::StringStream stream("Directory("); stream << directory.GetPath(); stream << ')'; @@ -95,23 +95,23 @@ namespace Ndk }); /*********************************** Nz::Stream ***********************************/ - streamClass.BindMethod("EnableTextMode", &Nz::Stream::EnableTextMode); - streamClass.BindMethod("Flush", &Nz::Stream::Flush); - streamClass.BindMethod("GetCursorPos", &Nz::Stream::GetCursorPos); - streamClass.BindMethod("GetDirectory", &Nz::Stream::GetDirectory); - streamClass.BindMethod("GetPath", &Nz::Stream::GetPath); - streamClass.BindMethod("GetOpenMode", &Nz::Stream::GetOpenMode); - streamClass.BindMethod("GetStreamOptions", &Nz::Stream::GetStreamOptions); - streamClass.BindMethod("GetSize", &Nz::Stream::GetSize); - streamClass.BindMethod("ReadLine", &Nz::Stream::ReadLine, 0U); - streamClass.BindMethod("IsReadable", &Nz::Stream::IsReadable); - streamClass.BindMethod("IsSequential", &Nz::Stream::IsSequential); - streamClass.BindMethod("IsTextModeEnabled", &Nz::Stream::IsTextModeEnabled); - streamClass.BindMethod("IsWritable", &Nz::Stream::IsWritable); - streamClass.BindMethod("SetCursorPos", &Nz::Stream::SetCursorPos); + stream.BindMethod("EnableTextMode", &Nz::Stream::EnableTextMode); + stream.BindMethod("Flush", &Nz::Stream::Flush); + stream.BindMethod("GetCursorPos", &Nz::Stream::GetCursorPos); + stream.BindMethod("GetDirectory", &Nz::Stream::GetDirectory); + stream.BindMethod("GetPath", &Nz::Stream::GetPath); + stream.BindMethod("GetOpenMode", &Nz::Stream::GetOpenMode); + stream.BindMethod("GetStreamOptions", &Nz::Stream::GetStreamOptions); + stream.BindMethod("GetSize", &Nz::Stream::GetSize); + stream.BindMethod("ReadLine", &Nz::Stream::ReadLine, 0U); + stream.BindMethod("IsReadable", &Nz::Stream::IsReadable); + stream.BindMethod("IsSequential", &Nz::Stream::IsSequential); + stream.BindMethod("IsTextModeEnabled", &Nz::Stream::IsTextModeEnabled); + stream.BindMethod("IsWritable", &Nz::Stream::IsWritable); + stream.BindMethod("SetCursorPos", &Nz::Stream::SetCursorPos); - streamClass.BindMethod("Read", [] (Nz::LuaInstance& lua, Nz::Stream& stream) -> int { - int argIndex = 1; + stream.BindMethod("Read", [] (Nz::LuaInstance& lua, Nz::Stream& stream, std::size_t /*argumentCount*/) -> int { + int argIndex = 2; std::size_t length = lua.Check(&argIndex); @@ -122,8 +122,8 @@ namespace Ndk return 1; }); - streamClass.BindMethod("Write", [] (Nz::LuaInstance& lua, Nz::Stream& stream) -> int { - int argIndex = 1; + stream.BindMethod("Write", [] (Nz::LuaInstance& lua, Nz::Stream& stream, std::size_t /*argumentCount*/) -> int { + int argIndex = 2; std::size_t bufferSize = 0; const char* buffer = lua.CheckString(argIndex, &bufferSize); @@ -136,13 +136,13 @@ namespace Ndk }); /*********************************** Nz::File ***********************************/ - fileClass.Inherit(streamClass); + file.Inherit(stream); - fileClass.SetConstructor([] (Nz::LuaInstance& lua, Nz::File* file, std::size_t argumentCount) + file.SetConstructor([] (Nz::LuaInstance& lua, Nz::File* file, std::size_t argumentCount) { std::size_t argCount = std::min(argumentCount, 1U); - int argIndex = 1; + int argIndex = 2; switch (argCount) { case 0: @@ -171,41 +171,41 @@ namespace Ndk return false; }); - fileClass.BindMethod("Close", &Nz::File::Close); - fileClass.BindMethod("Copy", &Nz::File::Copy); - fileClass.BindMethod("Delete", &Nz::File::Delete); - fileClass.BindMethod("EndOfFile", &Nz::File::EndOfFile); - fileClass.BindMethod("Exists", &Nz::File::Exists); - fileClass.BindMethod("GetCreationTime", &Nz::File::GetCreationTime); - fileClass.BindMethod("GetFileName", &Nz::File::GetFileName); - fileClass.BindMethod("GetLastAccessTime", &Nz::File::GetLastAccessTime); - fileClass.BindMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime); - fileClass.BindMethod("IsOpen", &Nz::File::IsOpen); - fileClass.BindMethod("Rename", &Nz::File::GetLastWriteTime); - fileClass.BindMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime); - fileClass.BindMethod("SetFile", &Nz::File::GetLastWriteTime); + file.BindMethod("Close", &Nz::File::Close); + file.BindMethod("Copy", &Nz::File::Copy); + file.BindMethod("Delete", &Nz::File::Delete); + file.BindMethod("EndOfFile", &Nz::File::EndOfFile); + file.BindMethod("Exists", &Nz::File::Exists); + file.BindMethod("GetCreationTime", &Nz::File::GetCreationTime); + file.BindMethod("GetFileName", &Nz::File::GetFileName); + file.BindMethod("GetLastAccessTime", &Nz::File::GetLastAccessTime); + file.BindMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime); + file.BindMethod("IsOpen", &Nz::File::IsOpen); + file.BindMethod("Rename", &Nz::File::GetLastWriteTime); + file.BindMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime); + file.BindMethod("SetFile", &Nz::File::GetLastWriteTime); - fileClass.BindStaticMethod("AbsolutePath", &Nz::File::AbsolutePath); - fileClass.BindStaticMethod("ComputeHash", (Nz::ByteArray (*)(Nz::HashType, const Nz::String&)) &Nz::File::ComputeHash); - fileClass.BindStaticMethod("Copy", &Nz::File::Copy); - fileClass.BindStaticMethod("Delete", &Nz::File::Delete); - fileClass.BindStaticMethod("Exists", &Nz::File::Exists); + file.BindStaticMethod("AbsolutePath", &Nz::File::AbsolutePath); + file.BindStaticMethod("ComputeHash", (Nz::ByteArray (*)(Nz::HashType, const Nz::String&)) &Nz::File::ComputeHash); + file.BindStaticMethod("Copy", &Nz::File::Copy); + file.BindStaticMethod("Delete", &Nz::File::Delete); + file.BindStaticMethod("Exists", &Nz::File::Exists); //fileClass.SetStaticMethod("GetCreationTime", &Nz::File::GetCreationTime); - fileClass.BindStaticMethod("GetDirectory", &Nz::File::GetDirectory); + file.BindStaticMethod("GetDirectory", &Nz::File::GetDirectory); //fileClass.SetStaticMethod("GetLastAccessTime", &Nz::File::GetLastAccessTime); //fileClass.SetStaticMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime); - fileClass.BindStaticMethod("GetSize", &Nz::File::GetSize); - fileClass.BindStaticMethod("IsAbsolute", &Nz::File::IsAbsolute); - fileClass.BindStaticMethod("NormalizePath", &Nz::File::NormalizePath); - fileClass.BindStaticMethod("NormalizeSeparators", &Nz::File::NormalizeSeparators); - fileClass.BindStaticMethod("Rename", &Nz::File::Rename); + file.BindStaticMethod("GetSize", &Nz::File::GetSize); + file.BindStaticMethod("IsAbsolute", &Nz::File::IsAbsolute); + file.BindStaticMethod("NormalizePath", &Nz::File::NormalizePath); + file.BindStaticMethod("NormalizeSeparators", &Nz::File::NormalizeSeparators); + file.BindStaticMethod("Rename", &Nz::File::Rename); // Manual - fileClass.BindMethod("Open", [] (Nz::LuaInstance& lua, Nz::File& file) -> int + file.BindMethod("Open", [] (Nz::LuaInstance& lua, Nz::File& file, std::size_t argumentCount) -> int { - unsigned int argCount = std::min(lua.GetStackTop(), 2U); + std::size_t argCount = std::min(argumentCount, 2U); - int argIndex = 1; + int argIndex = 2; switch (argCount) { case 0: @@ -224,11 +224,11 @@ namespace Ndk return 0; }); - fileClass.BindMethod("SetCursorPos", [] (Nz::LuaInstance& lua, Nz::File& file) -> int + file.BindMethod("SetCursorPos", [] (Nz::LuaInstance& lua, Nz::File& file, std::size_t argumentCount) -> int { - unsigned int argCount = std::min(lua.GetStackTop(), 2U); + std::size_t argCount = std::min(argumentCount, 2U); - int argIndex = 1; + int argIndex = 2; switch (argCount) { case 1: @@ -246,7 +246,7 @@ namespace Ndk return 0; }); - fileClass.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::File& file) -> int { + file.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::File& file, std::size_t /*argumentCount*/) -> int { Nz::StringStream stream("File("); if (file.IsOpen()) stream << "Path: " << file.GetPath(); @@ -267,10 +267,10 @@ namespace Ndk void LuaBinding::RegisterCore(Nz::LuaInstance& instance) { // Classes - clockClass.Register(instance); - directoryClass.Register(instance); - fileClass.Register(instance); - streamClass.Register(instance); + clock.Register(instance); + directory.Register(instance); + file.Register(instance); + stream.Register(instance); // Enums diff --git a/SDK/src/NDK/LuaBinding_Graphics.cpp b/SDK/src/NDK/LuaBinding_Graphics.cpp index 7505c1d9a..4a2b53422 100644 --- a/SDK/src/NDK/LuaBinding_Graphics.cpp +++ b/SDK/src/NDK/LuaBinding_Graphics.cpp @@ -14,36 +14,305 @@ namespace Ndk { /*********************************** Nz::InstancedRenderable ***********************************/ + /*********************************** Nz::Material ***********************************/ + material.SetConstructor([] (Nz::LuaInstance& lua, Nz::MaterialRef* instance, std::size_t argumentCount) + { + switch (argumentCount) + { + case 0: + Nz::PlacementNew(instance, Nz::Material::New()); + return true; + + case 1: + { + int argIndex = 1; + if (lua.IsOfType(argIndex, "MaterialPipeline")) + { + Nz::PlacementNew(instance, Nz::Material::New(*static_cast(lua.ToUserdata(argIndex)))); + return true; + } + else if (lua.IsOfType(argIndex, "Material")) + { + Nz::PlacementNew(instance, Nz::Material::New(**static_cast(lua.ToUserdata(argIndex)))); + return true; + } + else + { + Nz::PlacementNew(instance, Nz::Material::New(lua.Check(&argIndex))); + return true; + } + } + } + + lua.Error("No matching overload for constructor"); + return false; + }); + + material.BindMethod("Configure", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int + { + int argIndex = 2; + if (lua.IsOfType(argIndex, "MaterialPipeline")) + { + instance->Configure(*static_cast(lua.ToUserdata(argIndex))); + return 0; + } + else + { + lua.Push(instance->Configure(lua.Check(&argIndex))); + return 1; + } + }); + + material.BindMethod("EnableAlphaTest", &Nz::Material::EnableAlphaTest); + material.BindMethod("EnableBlending", &Nz::Material::EnableBlending); + material.BindMethod("EnableColorWrite", &Nz::Material::EnableColorWrite); + material.BindMethod("EnableDepthBuffer", &Nz::Material::EnableDepthBuffer); + material.BindMethod("EnableDepthSorting", &Nz::Material::EnableDepthSorting); + material.BindMethod("EnableDepthWrite", &Nz::Material::EnableDepthWrite); + material.BindMethod("EnableFaceCulling", &Nz::Material::EnableFaceCulling); + material.BindMethod("EnableScissorTest", &Nz::Material::EnableScissorTest); + material.BindMethod("EnableShadowCasting", &Nz::Material::EnableShadowCasting); + material.BindMethod("EnableShadowReceive", &Nz::Material::EnableShadowReceive); + material.BindMethod("EnableStencilTest", &Nz::Material::EnableStencilTest); + + material.BindMethod("EnsurePipelineUpdate", &Nz::Material::EnsurePipelineUpdate); + + material.BindMethod("GetAlphaMap", &Nz::Material::GetAlphaMap); + material.BindMethod("GetAlphaThreshold", &Nz::Material::GetAlphaThreshold); + material.BindMethod("GetAmbientColor", &Nz::Material::GetAmbientColor); + material.BindMethod("GetDepthFunc", &Nz::Material::GetDepthFunc); + material.BindMethod("GetDepthMaterial", &Nz::Material::GetDepthMaterial); + material.BindMethod("GetDiffuseColor", &Nz::Material::GetDiffuseColor); + material.BindMethod("GetDiffuseMap", &Nz::Material::GetDiffuseMap); + //material.BindMethod("GetDiffuseSampler", &Nz::Material::GetDiffuseSampler); + material.BindMethod("GetDstBlend", &Nz::Material::GetDstBlend); + material.BindMethod("GetEmissiveMap", &Nz::Material::GetEmissiveMap); + material.BindMethod("GetFaceCulling", &Nz::Material::GetFaceCulling); + material.BindMethod("GetFaceFilling", &Nz::Material::GetFaceFilling); + material.BindMethod("GetHeightMap", &Nz::Material::GetHeightMap); + material.BindMethod("GetLineWidth", &Nz::Material::GetLineWidth); + material.BindMethod("GetNormalMap", &Nz::Material::GetNormalMap); + //material.BindMethod("GetPipeline", &Nz::Material::GetPipeline); + //material.BindMethod("GetPipelineInfo", &Nz::Material::GetPipelineInfo); + material.BindMethod("GetPointSize", &Nz::Material::GetPointSize); + //material.BindMethod("GetShader", &Nz::Material::GetShader); + material.BindMethod("GetShininess", &Nz::Material::GetShininess); + material.BindMethod("GetSpecularColor", &Nz::Material::GetSpecularColor); + material.BindMethod("GetSpecularMap", &Nz::Material::GetSpecularMap); + //material.BindMethod("GetSpecularSampler", &Nz::Material::GetSpecularSampler); + material.BindMethod("GetSrcBlend", &Nz::Material::GetSrcBlend); + + material.BindMethod("HasAlphaMap", &Nz::Material::HasAlphaMap); + material.BindMethod("HasDepthMaterial", &Nz::Material::HasDepthMaterial); + material.BindMethod("HasDiffuseMap", &Nz::Material::HasDiffuseMap); + material.BindMethod("HasEmissiveMap", &Nz::Material::HasEmissiveMap); + material.BindMethod("HasHeightMap", &Nz::Material::HasHeightMap); + material.BindMethod("HasNormalMap", &Nz::Material::HasNormalMap); + material.BindMethod("HasSpecularMap", &Nz::Material::HasSpecularMap); + + material.BindMethod("IsAlphaTestEnabled", &Nz::Material::IsAlphaTestEnabled); + material.BindMethod("IsBlendingEnabled", &Nz::Material::IsBlendingEnabled); + material.BindMethod("IsColorWriteEnabled", &Nz::Material::IsColorWriteEnabled); + material.BindMethod("IsDepthBufferEnabled", &Nz::Material::IsDepthBufferEnabled); + material.BindMethod("IsDepthSortingEnabled", &Nz::Material::IsDepthSortingEnabled); + material.BindMethod("IsDepthWriteEnabled", &Nz::Material::IsDepthWriteEnabled); + material.BindMethod("IsFaceCullingEnabled", &Nz::Material::IsFaceCullingEnabled); + material.BindMethod("IsScissorTestEnabled", &Nz::Material::IsScissorTestEnabled); + material.BindMethod("IsStencilTestEnabled", &Nz::Material::IsStencilTestEnabled); + material.BindMethod("IsShadowCastingEnabled", &Nz::Material::IsShadowCastingEnabled); + material.BindMethod("IsShadowReceiveEnabled", &Nz::Material::IsShadowReceiveEnabled); + + material.BindMethod("LoadFromFile", &Nz::Material::LoadFromFile); + + material.BindMethod("Reset", &Nz::Material::Reset); + + material.BindMethod("SetAlphaThreshold", &Nz::Material::SetAlphaThreshold); + material.BindMethod("SetAmbientColor", &Nz::Material::SetAmbientColor); + material.BindMethod("SetDepthFunc", &Nz::Material::SetDepthFunc); + material.BindMethod("SetDepthFunc", &Nz::Material::SetDepthFunc); + material.BindMethod("SetDepthMaterial", &Nz::Material::SetDepthMaterial); + material.BindMethod("SetDiffuseColor", &Nz::Material::SetDiffuseColor); + //material.BindMethod("SetDiffuseSampler", &Nz::Material::SetDiffuseSampler); + material.BindMethod("SetDstBlend", &Nz::Material::SetDstBlend); + material.BindMethod("SetFaceCulling", &Nz::Material::SetFaceCulling); + material.BindMethod("SetFaceFilling", &Nz::Material::SetFaceFilling); + material.BindMethod("SetLineWidth", &Nz::Material::SetLineWidth); + material.BindMethod("SetPointSize", &Nz::Material::SetPointSize); + material.BindMethod("SetShininess", &Nz::Material::SetShininess); + material.BindMethod("SetSpecularColor", &Nz::Material::SetSpecularColor); + material.BindMethod("SetSpecularColor", &Nz::Material::SetSpecularColor); + //material.BindMethod("SetSpecularSampler", &Nz::Material::SetSpecularSampler); + material.BindMethod("SetSrcBlend", &Nz::Material::SetSrcBlend); + + material.BindStaticMethod("GetDefault", &Nz::Material::GetDefault); + + material.BindMethod("SetAlphaMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int + { + int argIndex = 2; + if (lua.IsOfType(argIndex, "Texture")) + { + instance->SetAlphaMap(*static_cast(lua.ToUserdata(argIndex))); + return 0; + } + else + return lua.Push(instance->SetAlphaMap(lua.Check(&argIndex))); + }); + + material.BindMethod("SetDiffuseMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int + { + int argIndex = 2; + if (lua.IsOfType(argIndex, "Texture")) + { + instance->SetDiffuseMap(*static_cast(lua.ToUserdata(argIndex))); + return 0; + } + else + return lua.Push(instance->SetDiffuseMap(lua.Check(&argIndex))); + }); + + material.BindMethod("SetEmissiveMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int + { + int argIndex = 2; + if (lua.IsOfType(argIndex, "Texture")) + { + instance->SetEmissiveMap(*static_cast(lua.ToUserdata(argIndex))); + return 0; + } + else + return lua.Push(instance->SetEmissiveMap(lua.Check(&argIndex))); + }); + + material.BindMethod("SetHeightMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int + { + int argIndex = 2; + if (lua.IsOfType(argIndex, "Texture")) + { + instance->SetHeightMap(*static_cast(lua.ToUserdata(argIndex))); + return 0; + } + else + return lua.Push(instance->SetHeightMap(lua.Check(&argIndex))); + }); + + material.BindMethod("SetNormalMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int + { + int argIndex = 2; + if (lua.IsOfType(argIndex, "Texture")) + { + instance->SetNormalMap(*static_cast(lua.ToUserdata(argIndex))); + return 0; + } + else + return lua.Push(instance->SetNormalMap(lua.Check(&argIndex))); + }); + + material.BindMethod("SetShader", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int + { + int argIndex = 2; + if (lua.IsOfType(argIndex, "UberShader")) + { + instance->SetShader(*static_cast(lua.ToUserdata(argIndex))); + return 0; + } + else + return lua.Push(instance->SetShader(lua.Check(&argIndex))); + }); + + material.BindMethod("SetSpecularMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int + { + int argIndex = 2; + if (lua.IsOfType(argIndex, "Texture")) + { + instance->SetSpecularMap(*static_cast(lua.ToUserdata(argIndex))); + return 0; + } + else + return lua.Push(instance->SetSpecularMap(lua.Check(&argIndex))); + }); + /*********************************** Nz::Model ***********************************/ - modelClass.Inherit(instancedRenderable, [] (Nz::ModelRef* model) -> Nz::InstancedRenderableRef* + model.Inherit(instancedRenderable, [] (Nz::ModelRef* model) -> Nz::InstancedRenderableRef* { return reinterpret_cast(model); //TODO: Make a ObjectRefCast }); - modelClass.SetConstructor([] (Nz::LuaInstance& lua, Nz::ModelRef* model, std::size_t argumentCount) + model.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::ModelRef* model, std::size_t /*argumentCount*/) { - NazaraUnused(argumentCount); - Nz::PlacementNew(model, Nz::Model::New()); return true; }); - //modelClass.SetMethod("GetMaterial", &Nz::Model::GetMaterial); - modelClass.BindMethod("GetMaterialCount", &Nz::Model::GetMaterialCount); + //model.BindMethod("GetMaterial", &Nz::Model::GetMaterial); + model.BindMethod("GetMaterialCount", &Nz::Model::GetMaterialCount); //modelClass.SetMethod("GetMesh", &Nz::Model::GetMesh); - modelClass.BindMethod("GetSkin", &Nz::Model::GetSkin); - modelClass.BindMethod("GetSkinCount", &Nz::Model::GetSkinCount); + model.BindMethod("GetSkin", &Nz::Model::GetSkin); + model.BindMethod("GetSkinCount", &Nz::Model::GetSkinCount); - modelClass.BindMethod("IsAnimated", &Nz::Model::IsAnimated); - modelClass.BindMethod("LoadFromFile", &Nz::Model::LoadFromFile, Nz::ModelParameters()); + model.BindMethod("IsAnimated", &Nz::Model::IsAnimated); + model.BindMethod("LoadFromFile", &Nz::Model::LoadFromFile, Nz::ModelParameters()); - modelClass.BindMethod("Reset", &Nz::Model::Reset); + model.BindMethod("Reset", &Nz::Model::Reset); - //modelClass.SetMethod("SetMaterial", &Nz::Model::SetMaterial); + //model.BindMethod("SetMaterial", &Nz::Model::SetMaterial); //modelClass.SetMethod("SetMesh", &Nz::Model::SetMesh); //modelClass.SetMethod("SetSequence", &Nz::Model::SetSequence); - modelClass.BindMethod("SetSkin", &Nz::Model::SetSkin); - modelClass.BindMethod("SetSkinCount", &Nz::Model::SetSkinCount); + model.BindMethod("SetSkin", &Nz::Model::SetSkin); + model.BindMethod("SetSkinCount", &Nz::Model::SetSkinCount); + + /*********************************** Nz::Sprite ***********************************/ + sprite.Inherit(instancedRenderable, [] (Nz::SpriteRef* sprite) -> Nz::InstancedRenderableRef* + { + return reinterpret_cast(sprite); //TODO: Make a ObjectRefCast + }); + + sprite.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::SpriteRef* sprite, std::size_t /*argumentCount*/) + { + Nz::PlacementNew(sprite, Nz::Sprite::New()); + return true; + }); + + sprite.BindMethod("GetColor", &Nz::Sprite::GetColor); + sprite.BindMethod("GetCornerColor", &Nz::Sprite::GetCornerColor); + sprite.BindMethod("GetMaterial", &Nz::Sprite::GetMaterial); + sprite.BindMethod("GetOrigin", &Nz::Sprite::GetOrigin); + sprite.BindMethod("GetSize", &Nz::Sprite::GetSize); + sprite.BindMethod("GetTextureCoords", &Nz::Sprite::GetTextureCoords); + + sprite.BindMethod("SetColor", &Nz::Sprite::SetColor); + sprite.BindMethod("SetCornerColor", &Nz::Sprite::SetCornerColor); + sprite.BindMethod("SetDefaultMaterial", &Nz::Sprite::SetDefaultMaterial); + sprite.BindMethod("SetMaterial", &Nz::Sprite::SetMaterial, true); + sprite.BindMethod("SetOrigin", &Nz::Sprite::SetOrigin); + sprite.BindMethod("SetSize", (void(Nz::Sprite::*)(const Nz::Vector2f&)) &Nz::Sprite::SetSize); + sprite.BindMethod("SetTexture", &Nz::Sprite::SetTexture, true); + sprite.BindMethod("SetTextureCoords", &Nz::Sprite::SetTextureCoords); + sprite.BindMethod("SetTextureRect", &Nz::Sprite::SetTextureRect); + + /*********************************** Nz::SpriteLibrary ***********************************/ + + spriteLibrary.BindStaticMethod("Get", &Nz::SpriteLibrary::Get); + spriteLibrary.BindStaticMethod("Has", &Nz::SpriteLibrary::Has); + spriteLibrary.BindStaticMethod("Register", &Nz::SpriteLibrary::Register); + spriteLibrary.BindStaticMethod("Query", &Nz::SpriteLibrary::Query); + spriteLibrary.BindStaticMethod("Unregister", &Nz::SpriteLibrary::Unregister); + + /*********************************** Nz::TextureLibrary ***********************************/ + + textureLibrary.BindStaticMethod("Get", &Nz::TextureLibrary::Get); + textureLibrary.BindStaticMethod("Has", &Nz::TextureLibrary::Has); + textureLibrary.BindStaticMethod("Register", &Nz::TextureLibrary::Register); + textureLibrary.BindStaticMethod("Query", &Nz::TextureLibrary::Query); + textureLibrary.BindStaticMethod("Unregister", &Nz::TextureLibrary::Unregister); + + /*********************************** Nz::TextureManager ***********************************/ + + textureManager.BindStaticMethod("Clear", &Nz::TextureManager::Clear); + textureManager.BindStaticMethod("Get", &Nz::TextureManager::Get); + textureManager.BindStaticMethod("GetDefaultParameters", &Nz::TextureManager::GetDefaultParameters); + textureManager.BindStaticMethod("Purge", &Nz::TextureManager::Purge); + textureManager.BindStaticMethod("Register", &Nz::TextureManager::Register); + textureManager.BindStaticMethod("SetDefaultParameters", &Nz::TextureManager::SetDefaultParameters); + textureManager.BindStaticMethod("Unregister", &Nz::TextureManager::Unregister); } /*! @@ -55,6 +324,11 @@ namespace Ndk void LuaBinding::RegisterGraphics(Nz::LuaInstance& instance) { instancedRenderable.Register(instance); - modelClass.Register(instance); + material.Register(instance); + model.Register(instance); + sprite.Register(instance); + spriteLibrary.Register(instance); + textureLibrary.Register(instance); + textureManager.Register(instance); } -} \ No newline at end of file +} diff --git a/SDK/src/NDK/LuaBinding_Math.cpp b/SDK/src/NDK/LuaBinding_Math.cpp index f65259f50..51a510238 100644 --- a/SDK/src/NDK/LuaBinding_Math.cpp +++ b/SDK/src/NDK/LuaBinding_Math.cpp @@ -14,7 +14,7 @@ namespace Ndk void LuaBinding::BindMath() { /*********************************** Nz::EulerAngles **********************************/ - eulerAnglesClass.SetConstructor([] (Nz::LuaInstance& lua, Nz::EulerAnglesd* angles, std::size_t argumentCount) + eulerAngles.SetConstructor([] (Nz::LuaInstance& lua, Nz::EulerAnglesd* angles, std::size_t argumentCount) { std::size_t argCount = std::min(argumentCount, 1U); @@ -37,12 +37,12 @@ namespace Ndk return false; }); - eulerAnglesClass.BindMethod("__tostring", &Nz::EulerAnglesd::ToString); + eulerAngles.BindMethod("__tostring", &Nz::EulerAnglesd::ToString); - eulerAnglesClass.SetGetter([] (Nz::LuaInstance& lua, Nz::EulerAnglesd& instance) + eulerAngles.SetGetter([] (Nz::LuaInstance& lua, Nz::EulerAnglesd& instance) { std::size_t length; - const char* ypr = lua.CheckString(1, &length); + const char* ypr = lua.CheckString(2, &length); switch (length) { @@ -96,11 +96,11 @@ namespace Ndk return false; }); - eulerAnglesClass.SetSetter([] (Nz::LuaInstance& lua, Nz::EulerAnglesd& instance) + eulerAngles.SetSetter([] (Nz::LuaInstance& lua, Nz::EulerAnglesd& instance) { std::size_t length; - const char* ypr = lua.CheckString(1, &length); - double value = lua.CheckNumber(2); + const char* ypr = lua.CheckString(2, &length); + double value = lua.CheckNumber(3); switch (length) { @@ -154,8 +154,213 @@ namespace Ndk return false; }); + + /*********************************** Nz::Matrix4 **********************************/ + matrix4d.SetConstructor([] (Nz::LuaInstance& lua, Nz::Matrix4d* matrix, std::size_t argumentCount) + { + std::size_t argCount = std::min(argumentCount, 3U); + + switch (argCount) + { + case 0: + Nz::PlacementNew(matrix, Nz::Matrix4d::Zero()); + return true; + + case 1: + if (lua.IsOfType(1, "Matrix4")) + Nz::PlacementNew(matrix, *static_cast(lua.ToUserdata(1))); + break; + + case 16: + { + double values[16]; + for (std::size_t i = 0; i < 16; ++i) + values[i] = lua.CheckNumber(i); + + Nz::PlacementNew(matrix, values); + + return true; + } + } + + lua.Error("No matching overload for constructor"); + return false; + }); + + matrix4d.BindMethod("ApplyRotation", &Nz::Matrix4d::ApplyRotation); + matrix4d.BindMethod("ApplyScale", &Nz::Matrix4d::ApplyScale); + matrix4d.BindMethod("ApplyTranslation", &Nz::Matrix4d::ApplyTranslation); + + matrix4d.BindMethod("Concatenate", &Nz::Matrix4d::Concatenate); + matrix4d.BindMethod("ConcatenateAffine", &Nz::Matrix4d::ConcatenateAffine); + + //matrix4d.BindMethod("GetColumn", &Nz::Matrix4d::GetColumn); + matrix4d.BindMethod("GetDeterminant", &Nz::Matrix4d::GetDeterminant); + matrix4d.BindMethod("GetDeterminantAffine", &Nz::Matrix4d::GetDeterminantAffine); + + matrix4d.BindMethod("GetInverse", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int + { + Nz::Matrix4d result; + if (instance.GetInverse(&result)) + return lua.Push(true, result); + else + return lua.Push(false); + }); + + matrix4d.BindMethod("GetInverseAffine", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int + { + Nz::Matrix4d result; + if (instance.GetInverseAffine(&result)) + return lua.Push(true, result); + else + return lua.Push(false); + }); + + matrix4d.BindMethod("GetRotation", &Nz::Matrix4d::GetRotation); + + //matrix4d.BindMethod("GetRow", &Nz::Matrix4d::GetRow); + matrix4d.BindMethod("GetScale", &Nz::Matrix4d::GetScale); + matrix4d.BindMethod("GetSquaredScale", &Nz::Matrix4d::GetSquaredScale); + matrix4d.BindMethod("GetTranslation", &Nz::Matrix4d::GetTranslation); + + matrix4d.BindMethod("GetTransposed", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int + { + Nz::Matrix4d result; + instance.GetTransposed(&result); + + return lua.Push(result); + }); + + matrix4d.BindMethod("HasNegativeScale", &Nz::Matrix4d::HasNegativeScale); + matrix4d.BindMethod("HasScale", &Nz::Matrix4d::HasScale); + + matrix4d.BindMethod("Inverse", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int + { + bool succeeded; + instance.Inverse(&succeeded); + + return lua.Push(succeeded); + }); + + matrix4d.BindMethod("InverseAffine", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int + { + bool succeeded; + instance.InverseAffine(&succeeded); + + return lua.Push(succeeded); + }); + + matrix4d.BindMethod("IsAffine", &Nz::Matrix4d::IsAffine); + matrix4d.BindMethod("IsIdentity", &Nz::Matrix4d::IsIdentity); + + matrix4d.BindMethod("MakeIdentity", &Nz::Matrix4d::MakeIdentity); + matrix4d.BindMethod("MakeLookAt", &Nz::Matrix4d::MakeLookAt, Nz::Vector3d::Up()); + matrix4d.BindMethod("MakeOrtho", &Nz::Matrix4d::MakeOrtho, -1.0, 1.0); + matrix4d.BindMethod("MakePerspective", &Nz::Matrix4d::MakePerspective); + matrix4d.BindMethod("MakeRotation", &Nz::Matrix4d::MakeRotation); + matrix4d.BindMethod("MakeScale", &Nz::Matrix4d::MakeScale); + matrix4d.BindMethod("MakeTranslation", &Nz::Matrix4d::MakeTranslation); + matrix4d.BindMethod("MakeTransform", (Nz::Matrix4d&(Nz::Matrix4d::*)(const Nz::Vector3d&, const Nz::Quaterniond&, const Nz::Vector3d&)) &Nz::Matrix4d::MakeTransform, Nz::Vector3d::Unit()); + matrix4d.BindMethod("MakeViewMatrix", &Nz::Matrix4d::MakeViewMatrix); + matrix4d.BindMethod("MakeZero", &Nz::Matrix4d::MakeZero); + + matrix4d.BindMethod("Set", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t argumentCount) -> int + { + std::size_t argCount = std::min(argumentCount, 3U); + + int argIndex = 2; + switch (argCount) + { + case 1: + if (lua.IsOfType(argIndex, "Matrix4")) + instance.Set(*static_cast(lua.ToUserdata(argIndex))); + break; + + case 16: + { + double values[16]; + for (std::size_t i = 0; i < 16; ++i) + values[i] = lua.CheckNumber(argIndex++); + + instance.Set(values); + + return 0; + } + } + + lua.Error("No matching overload for method Set"); + return 0; + }); + + matrix4d.BindMethod("SetRotation", &Nz::Matrix4d::SetRotation); + matrix4d.BindMethod("SetScale", &Nz::Matrix4d::SetScale); + matrix4d.BindMethod("SetTranslation", &Nz::Matrix4d::SetTranslation); + + matrix4d.BindMethod("Transform", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int + { + int argIndex = 2; + if (lua.IsOfType(argIndex, "Vector2")) + { + double z(lua.CheckNumber(argIndex+1, 0.0)); + double w(lua.CheckNumber(argIndex+2, 1.0)); + + return lua.Push(instance.Transform(*static_cast(lua.ToUserdata(argIndex)), z, w)); + } + else if (lua.IsOfType(argIndex, "Vector3")) + { + double w(lua.CheckNumber(argIndex+1, 1.0)); + + return lua.Push(instance.Transform(*static_cast(lua.ToUserdata(argIndex)), w)); + } + //else if (lua.IsOfType(2, "Vector4")) + // return lua.Push(instance.Transform(*static_cast(lua.ToUserdata(1)))); + + lua.Error("No matching overload for method Transform"); + return 0; + }); + + matrix4d.BindMethod("Transpose", &Nz::Matrix4d::Transpose); + + matrix4d.BindMethod("__tostring", &Nz::Matrix4d::ToString); + + matrix4d.BindStaticMethod("Concatenate", &Nz::Matrix4d::Concatenate); + matrix4d.BindStaticMethod("ConcatenateAffine", &Nz::Matrix4d::ConcatenateAffine); + matrix4d.BindStaticMethod("Identity", &Nz::Matrix4d::Identity); + matrix4d.BindStaticMethod("LookAt", &Nz::Matrix4d::LookAt, Nz::Vector3d::Up()); + matrix4d.BindStaticMethod("Ortho", &Nz::Matrix4d::Ortho, -1.0, 1.0); + matrix4d.BindStaticMethod("Perspective", &Nz::Matrix4d::Perspective); + matrix4d.BindStaticMethod("Rotate", &Nz::Matrix4d::Rotate); + matrix4d.BindStaticMethod("Scale", &Nz::Matrix4d::Scale); + matrix4d.BindStaticMethod("Translate", &Nz::Matrix4d::Translate); + matrix4d.BindStaticMethod("Transform", (Nz::Matrix4d(*)(const Nz::Vector3d&, const Nz::Quaterniond&, const Nz::Vector3d&)) &Nz::Matrix4d::Transform, Nz::Vector3d::Unit()); + matrix4d.BindStaticMethod("ViewMatrix", &Nz::Matrix4d::ViewMatrix); + matrix4d.BindStaticMethod("Zero", &Nz::Matrix4d::Zero); + + matrix4d.SetGetter([] (Nz::LuaInstance& lua, Nz::Matrix4d& instance) + { + bool succeeded = false; + std::size_t index = static_cast(lua.ToInteger(2, &succeeded)); + if (!succeeded || index < 1 || index > 16) + return false; + + lua.Push(instance[index - 1]); + return true; + }); + + matrix4d.SetSetter([] (Nz::LuaInstance& lua, Nz::Matrix4d& instance) + { + bool succeeded = false; + std::size_t index = static_cast(lua.ToInteger(2, &succeeded)); + if (!succeeded || index < 1 || index > 16) + return false; + + instance[index - 1] = lua.CheckNumber(3); + + return true; + }); + /*********************************** Nz::Rect **********************************/ - rectClass.SetConstructor([] (Nz::LuaInstance& lua, Nz::Rectd* rect, std::size_t argumentCount) + rect.SetConstructor([] (Nz::LuaInstance& lua, Nz::Rectd* rect, std::size_t argumentCount) { std::size_t argCount = std::min(argumentCount, 4U); @@ -203,15 +408,15 @@ namespace Ndk return false; }); - rectClass.BindMethod("__tostring", &Nz::Rectd::ToString); + rect.BindMethod("__tostring", &Nz::Rectd::ToString); - rectClass.SetGetter([] (Nz::LuaInstance& lua, Nz::Rectd& instance) + rect.SetGetter([] (Nz::LuaInstance& lua, Nz::Rectd& instance) { - switch (lua.GetType(1)) + switch (lua.GetType(2)) { case Nz::LuaType_Number: { - auto index = lua.CheckBoundInteger(1); + auto index = lua.CheckBoundInteger(2); if (index < 1 || index > 4) return false; @@ -222,7 +427,7 @@ namespace Ndk case Nz::LuaType_String: { std::size_t length; - const char* xywh = lua.CheckString(1, &length); + const char* xywh = lua.CheckString(2, &length); if (length != 1) break; @@ -258,13 +463,13 @@ namespace Ndk return false; }); - rectClass.SetSetter([] (Nz::LuaInstance& lua, Nz::Rectd& instance) + rect.SetSetter([] (Nz::LuaInstance& lua, Nz::Rectd& instance) { - switch (lua.GetType(1)) + switch (lua.GetType(2)) { case Nz::LuaType_Number: { - auto index = lua.CheckBoundInteger(1); + auto index = lua.CheckBoundInteger(2); if (index < 1 || index > 4) return false; @@ -275,12 +480,12 @@ namespace Ndk case Nz::LuaType_String: { std::size_t length; - const char* xywh = lua.CheckString(1, &length); + const char* xywh = lua.CheckString(2, &length); if (length != 1) break; - double value = lua.CheckNumber(2); + double value = lua.CheckNumber(3); switch (xywh[0]) { @@ -311,7 +516,7 @@ namespace Ndk }); /*********************************** Nz::Quaternion **********************************/ - quaternionClass.SetConstructor([] (Nz::LuaInstance& lua, Nz::Quaterniond* quaternion, std::size_t argumentCount) + quaternion.SetConstructor([] (Nz::LuaInstance& lua, Nz::Quaterniond* quaternion, std::size_t argumentCount) { std::size_t argCount = std::min(argumentCount, 4U); @@ -349,12 +554,12 @@ namespace Ndk return false; }); - quaternionClass.BindMethod("__tostring", &Nz::Quaterniond::ToString); + quaternion.BindMethod("__tostring", &Nz::Quaterniond::ToString); - quaternionClass.SetGetter([] (Nz::LuaInstance& lua, Nz::Quaterniond& instance) + quaternion.SetGetter([] (Nz::LuaInstance& lua, Nz::Quaterniond& instance) { std::size_t length; - const char* wxyz = lua.CheckString(1, &length); + const char* wxyz = lua.CheckString(2, &length); if (length != 1) return false; @@ -381,15 +586,15 @@ namespace Ndk return false; }); - quaternionClass.SetSetter([] (Nz::LuaInstance& lua, Nz::Quaterniond& instance) + quaternion.SetSetter([] (Nz::LuaInstance& lua, Nz::Quaterniond& instance) { std::size_t length; - const char* wxyz = lua.CheckString(1, &length); + const char* wxyz = lua.CheckString(2, &length); if (length != 1) return false; - double value = lua.CheckNumber(2); + double value = lua.CheckNumber(3); switch (wxyz[0]) { @@ -417,7 +622,7 @@ namespace Ndk }); /*********************************** Nz::Vector2 **********************************/ - vector2dClass.SetConstructor([] (Nz::LuaInstance& lua, Nz::Vector2d* vector, std::size_t argumentCount) + vector2d.SetConstructor([] (Nz::LuaInstance& lua, Nz::Vector2d* vector, std::size_t argumentCount) { std::size_t argCount = std::min(argumentCount, 2U); @@ -445,15 +650,15 @@ namespace Ndk return false; }); - vector2dClass.BindMethod("__tostring", &Nz::Vector2d::ToString); + vector2d.BindMethod("__tostring", &Nz::Vector2d::ToString); - vector2dClass.SetGetter([](Nz::LuaInstance& lua, Nz::Vector2d& instance) + vector2d.SetGetter([](Nz::LuaInstance& lua, Nz::Vector2d& instance) { - switch (lua.GetType(1)) + switch (lua.GetType(2)) { case Nz::LuaType_Number: { - long long index = lua.CheckInteger(1); + long long index = lua.CheckInteger(2); if (index < 1 || index > 2) return false; @@ -464,7 +669,7 @@ namespace Ndk case Nz::LuaType_String: { std::size_t length; - const char* xy = lua.CheckString(1, &length); + const char* xy = lua.CheckString(2, &length); if (length != 1) break; @@ -492,29 +697,29 @@ namespace Ndk return false; }); - vector2dClass.SetSetter([](Nz::LuaInstance& lua, Nz::Vector2d& instance) + vector2d.SetSetter([](Nz::LuaInstance& lua, Nz::Vector2d& instance) { - switch (lua.GetType(1)) + switch (lua.GetType(2)) { case Nz::LuaType_Number: { - long long index = lua.CheckInteger(1); + long long index = lua.CheckInteger(2); if (index < 1 || index > 2) return false; - instance[index - 1] = lua.CheckNumber(2); + instance[index - 1] = lua.CheckNumber(3); return true; } case Nz::LuaType_String: { std::size_t length; - const char* xy = lua.CheckString(1, &length); + const char* xy = lua.CheckString(2, &length); if (length != 1) break; - double value = lua.CheckNumber(2); + double value = lua.CheckNumber(3); switch (xy[0]) { @@ -540,7 +745,7 @@ namespace Ndk }); /*********************************** Nz::Vector3 **********************************/ - vector3dClass.SetConstructor([] (Nz::LuaInstance& lua, Nz::Vector3d* vector, std::size_t argumentCount) + vector3d.SetConstructor([] (Nz::LuaInstance& lua, Nz::Vector3d* vector, std::size_t argumentCount) { std::size_t argCount = std::min(argumentCount, 3U); @@ -582,15 +787,15 @@ namespace Ndk return false; }); - vector3dClass.BindMethod("__tostring", &Nz::Vector3d::ToString); + vector3d.BindMethod("__tostring", &Nz::Vector3d::ToString); - vector3dClass.SetGetter([] (Nz::LuaInstance& lua, Nz::Vector3d& instance) + vector3d.SetGetter([] (Nz::LuaInstance& lua, Nz::Vector3d& instance) { - switch (lua.GetType(1)) + switch (lua.GetType(2)) { case Nz::LuaType_Number: { - long long index = lua.CheckInteger(1); + long long index = lua.CheckInteger(2); if (index < 1 || index > 3) return false; @@ -601,7 +806,7 @@ namespace Ndk case Nz::LuaType_String: { std::size_t length; - const char* xyz = lua.CheckString(1, &length); + const char* xyz = lua.CheckString(2, &length); if (length != 1) break; @@ -633,29 +838,29 @@ namespace Ndk return false; }); - vector3dClass.SetSetter([] (Nz::LuaInstance& lua, Nz::Vector3d& instance) + vector3d.SetSetter([] (Nz::LuaInstance& lua, Nz::Vector3d& instance) { - switch (lua.GetType(1)) + switch (lua.GetType(2)) { case Nz::LuaType_Number: { - long long index = lua.CheckInteger(1); + long long index = lua.CheckInteger(2); if (index < 1 || index > 3) return false; - instance[index - 1] = lua.CheckNumber(2); + instance[index - 1] = lua.CheckNumber(3); return true; } case Nz::LuaType_String: { std::size_t length; - const char* xyz = lua.CheckString(1, &length); + const char* xyz = lua.CheckString(2, &length); if (length != 1) break; - double value = lua.CheckNumber(2); + double value = lua.CheckNumber(3); switch (xyz[0]) { @@ -693,10 +898,11 @@ namespace Ndk void LuaBinding::RegisterMath(Nz::LuaInstance& instance) { - eulerAnglesClass.Register(instance); - quaternionClass.Register(instance); - rectClass.Register(instance); - vector2dClass.Register(instance); - vector3dClass.Register(instance); + eulerAngles.Register(instance); + matrix4d.Register(instance); + quaternion.Register(instance); + rect.Register(instance); + vector2d.Register(instance); + vector3d.Register(instance); } } diff --git a/SDK/src/NDK/LuaBinding_Network.cpp b/SDK/src/NDK/LuaBinding_Network.cpp index 689fc2d1d..bd1105962 100644 --- a/SDK/src/NDK/LuaBinding_Network.cpp +++ b/SDK/src/NDK/LuaBinding_Network.cpp @@ -12,20 +12,20 @@ namespace Ndk void LuaBinding::BindNetwork() { /*********************************** Nz::AbstractSocket **********************************/ - abstractSocketClass.BindMethod("Close", &Nz::AbstractSocket::Close); - abstractSocketClass.BindMethod("EnableBlocking", &Nz::AbstractSocket::EnableBlocking); - abstractSocketClass.BindMethod("GetLastError", &Nz::AbstractSocket::GetLastError); - abstractSocketClass.BindMethod("GetState", &Nz::AbstractSocket::GetState); - abstractSocketClass.BindMethod("GetType", &Nz::AbstractSocket::GetType); - abstractSocketClass.BindMethod("IsBlockingEnabled", &Nz::AbstractSocket::IsBlockingEnabled); - abstractSocketClass.BindMethod("QueryAvailableBytes", &Nz::AbstractSocket::QueryAvailableBytes); + abstractSocket.BindMethod("Close", &Nz::AbstractSocket::Close); + abstractSocket.BindMethod("EnableBlocking", &Nz::AbstractSocket::EnableBlocking); + abstractSocket.BindMethod("GetLastError", &Nz::AbstractSocket::GetLastError); + abstractSocket.BindMethod("GetState", &Nz::AbstractSocket::GetState); + abstractSocket.BindMethod("GetType", &Nz::AbstractSocket::GetType); + abstractSocket.BindMethod("IsBlockingEnabled", &Nz::AbstractSocket::IsBlockingEnabled); + abstractSocket.BindMethod("QueryAvailableBytes", &Nz::AbstractSocket::QueryAvailableBytes); /*********************************** Nz::IpAddress **********************************/ - ipAddressClass.SetConstructor([] (Nz::LuaInstance& lua, Nz::IpAddress* address, std::size_t argumentCount) + ipAddress.SetConstructor([] (Nz::LuaInstance& lua, Nz::IpAddress* address, std::size_t argumentCount) { std::size_t argCount = std::min(argumentCount, 9U); - int argIndex = 1; + int argIndex = 2; switch (argCount) { case 0: @@ -71,19 +71,19 @@ namespace Ndk return false; }); - ipAddressClass.BindMethod("GetPort", &Nz::IpAddress::GetPort); - ipAddressClass.BindMethod("GetProtocol", &Nz::IpAddress::GetProtocol); - ipAddressClass.BindMethod("IsLoopback", &Nz::IpAddress::IsLoopback); - ipAddressClass.BindMethod("IsValid", &Nz::IpAddress::IsValid); - ipAddressClass.BindMethod("ToUInt32", &Nz::IpAddress::ToUInt32); - ipAddressClass.BindMethod("__tostring", &Nz::IpAddress::ToString); + ipAddress.BindMethod("GetPort", &Nz::IpAddress::GetPort); + ipAddress.BindMethod("GetProtocol", &Nz::IpAddress::GetProtocol); + ipAddress.BindMethod("IsLoopback", &Nz::IpAddress::IsLoopback); + ipAddress.BindMethod("IsValid", &Nz::IpAddress::IsValid); + ipAddress.BindMethod("ToUInt32", &Nz::IpAddress::ToUInt32); + ipAddress.BindMethod("__tostring", &Nz::IpAddress::ToString); - ipAddressClass.BindStaticMethod("ResolveAddress", [] (Nz::LuaInstance& instance) -> int + ipAddress.BindStaticMethod("ResolveAddress", [] (Nz::LuaInstance& instance) -> int { Nz::String service; Nz::ResolveError error = Nz::ResolveError_Unknown; - int argIndex = 1; + int argIndex = 2; Nz::String hostName = Nz::IpAddress::ResolveAddress(instance.Check(&argIndex), &service, &error); if (error == Nz::ResolveError_NoError) @@ -100,11 +100,11 @@ namespace Ndk } }); - ipAddressClass.BindStaticMethod("ResolveHostname", [] (Nz::LuaInstance& instance) -> int + ipAddress.BindStaticMethod("ResolveHostname", [] (Nz::LuaInstance& instance) -> int { Nz::ResolveError error = Nz::ResolveError_Unknown; - int argIndex = 1; + int argIndex = 2; Nz::NetProtocol protocol = instance.Check(&argIndex); Nz::String hostname = instance.Check(&argIndex); Nz::String service = instance.Check(&argIndex, "http"); @@ -145,8 +145,8 @@ namespace Ndk void LuaBinding::RegisterNetwork(Nz::LuaInstance& instance) { // Classes - abstractSocketClass.Register(instance); - ipAddressClass.Register(instance); + abstractSocket.Register(instance); + ipAddress.Register(instance); // Enums diff --git a/SDK/src/NDK/LuaBinding_Renderer.cpp b/SDK/src/NDK/LuaBinding_Renderer.cpp index 79f1780a3..8ffe76c69 100644 --- a/SDK/src/NDK/LuaBinding_Renderer.cpp +++ b/SDK/src/NDK/LuaBinding_Renderer.cpp @@ -10,9 +10,58 @@ namespace Ndk /*! * \brief Binds Renderer module to Lua */ - void LuaBinding::BindRenderer() { + /*********************************** Nz::Texture ***********************************/ + texture.Inherit(abstractImage, [] (Nz::TextureRef* texture) -> Nz::AbstractImageRef* + { + return reinterpret_cast(texture); //TODO: Make a ObjectRefCast + }); + + texture.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::TextureRef* texture, std::size_t /*argumentCount*/) + { + Nz::PlacementNew(texture, Nz::Texture::New()); + return true; + }); + + texture.BindMethod("Create", &Nz::Texture::Create, static_cast(1), 1U); + texture.BindMethod("Destroy", &Nz::Texture::Destroy); + + //texture.BindMethod("Download", &Nz::Texture::Download); + + texture.BindMethod("EnableMipmapping", &Nz::Texture::EnableMipmapping); + texture.BindMethod("EnsureMipmapsUpdate", &Nz::Texture::EnsureMipmapsUpdate); + texture.BindMethod("HasMipmaps", &Nz::Texture::HasMipmaps); + texture.BindMethod("InvalidateMipmaps", &Nz::Texture::InvalidateMipmaps); + texture.BindMethod("IsValid", &Nz::Texture::IsValid); + + texture.BindMethod("LoadFromFile", &Nz::Texture::LoadFromFile, true, Nz::ImageParams()); + //bool LoadFromImage(const Image& image, bool generateMipmaps = true); + //bool LoadFromMemory(const void* data, std::size_t size, const ImageParams& params = ImageParams(), bool generateMipmaps = true); + //bool LoadFromStream(Stream& stream, const ImageParams& params = ImageParams(), bool generateMipmaps = true); + + texture.BindMethod("LoadArrayFromFile", &Nz::Texture::LoadArrayFromFile, Nz::Vector2ui(2, 2), true, Nz::ImageParams()); + //bool LoadArrayFromImage(const Image& image, bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2)); + //bool LoadArrayFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2)); + //bool LoadArrayFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2)); + + //bool LoadCubemapFromFile(const String& filePath, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams()); + //bool LoadCubemapFromImage(const Image& image, bool generateMipmaps = true, const CubemapParams& params = CubemapParams()); + //bool LoadCubemapFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams()); + //bool LoadCubemapFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams()); + + texture.BindMethod("LoadFaceFromFile", &Nz::Texture::LoadFaceFromFile, Nz::ImageParams()); + //bool LoadFaceFromMemory(CubemapFace face, const void* data, std::size_t size, const ImageParams& params = ImageParams()); + //bool LoadFaceFromStream(CubemapFace face, Stream& stream, const ImageParams& params = ImageParams()); + + texture.BindMethod("SaveToFile", &Nz::Texture::SaveToFile, Nz::ImageParams()); + //bool SaveToStream(Stream& stream, const String& format, const ImageParams& params = ImageParams()); + + texture.BindMethod("SetMipmapRange", &Nz::Texture::SetMipmapRange); + + texture.BindStaticMethod("IsFormatSupported", &Nz::Texture::IsFormatSupported); + texture.BindStaticMethod("IsMipmappingSupported", &Nz::Texture::IsMipmappingSupported); + texture.BindStaticMethod("IsTypeSupported", &Nz::Texture::IsTypeSupported); } /*! @@ -20,8 +69,8 @@ namespace Ndk * * \param instance Lua instance that will interact with the Renderer classes */ - void LuaBinding::RegisterRenderer(Nz::LuaInstance& instance) { + texture.Register(instance); } } \ No newline at end of file diff --git a/SDK/src/NDK/LuaBinding_SDK.cpp b/SDK/src/NDK/LuaBinding_SDK.cpp index af5cca5a8..3046f2483 100644 --- a/SDK/src/NDK/LuaBinding_SDK.cpp +++ b/SDK/src/NDK/LuaBinding_SDK.cpp @@ -25,7 +25,7 @@ namespace Ndk application.BindMethod("IsFPSCounterEnabled", &Application::IsFPSCounterEnabled); #endif - application.BindMethod("AddWorld", [] (Nz::LuaInstance& instance, Application* application) -> int + application.BindMethod("AddWorld", [] (Nz::LuaInstance& instance, Application* application, std::size_t /*argumentCount*/) -> int { instance.Push(application->AddWorld().CreateHandle()); return 1; @@ -36,58 +36,58 @@ namespace Ndk /*********************************** Ndk::Console **********************************/ #ifndef NDK_SERVER - consoleClass.Inherit(nodeClass, [] (ConsoleHandle* handle) -> Nz::Node* + console.Inherit(node, [] (ConsoleHandle* handle) -> Nz::Node* { return handle->GetObject(); }); - consoleClass.BindMethod("AddLine", &Console::AddLine, Nz::Color::White); - consoleClass.BindMethod("Clear", &Console::Clear); - consoleClass.BindMethod("GetCharacterSize", &Console::GetCharacterSize); - consoleClass.BindMethod("GetHistory", &Console::GetHistory); - consoleClass.BindMethod("GetHistoryBackground", &Console::GetHistoryBackground); - consoleClass.BindMethod("GetInput", &Console::GetInput); - consoleClass.BindMethod("GetInputBackground", &Console::GetInputBackground); - consoleClass.BindMethod("GetSize", &Console::GetSize); - consoleClass.BindMethod("GetTextFont", &Console::GetTextFont); + console.BindMethod("AddLine", &Console::AddLine, Nz::Color::White); + console.BindMethod("Clear", &Console::Clear); + console.BindMethod("GetCharacterSize", &Console::GetCharacterSize); + console.BindMethod("GetHistory", &Console::GetHistory); + console.BindMethod("GetHistoryBackground", &Console::GetHistoryBackground); + console.BindMethod("GetInput", &Console::GetInput); + console.BindMethod("GetInputBackground", &Console::GetInputBackground); + console.BindMethod("GetSize", &Console::GetSize); + console.BindMethod("GetTextFont", &Console::GetTextFont); - consoleClass.BindMethod("IsVisible", &Console::IsVisible); + console.BindMethod("IsVisible", &Console::IsVisible); - consoleClass.BindMethod("SendCharacter", &Console::SendCharacter); + console.BindMethod("SendCharacter", &Console::SendCharacter); //consoleClass.SetMethod("SendEvent", &Console::SendEvent); - consoleClass.BindMethod("SetCharacterSize", &Console::SetCharacterSize); - consoleClass.BindMethod("SetSize", &Console::SetSize); - consoleClass.BindMethod("SetTextFont", &Console::SetTextFont); + console.BindMethod("SetCharacterSize", &Console::SetCharacterSize); + console.BindMethod("SetSize", &Console::SetSize); + console.BindMethod("SetTextFont", &Console::SetTextFont); - consoleClass.BindMethod("Show", &Console::Show, true); + console.BindMethod("Show", &Console::Show, true); #endif /*********************************** Ndk::Entity **********************************/ - entityClass.BindMethod("Enable", &Entity::Enable, true); - entityClass.BindMethod("GetId", &Entity::GetId); - entityClass.BindMethod("GetWorld", &Entity::GetWorld); - entityClass.BindMethod("Kill", &Entity::Kill); - entityClass.BindMethod("IsEnabled", &Entity::IsEnabled); - entityClass.BindMethod("IsValid", &Entity::IsValid); - entityClass.BindMethod("RemoveAllComponents", &Entity::RemoveAllComponents); - entityClass.BindMethod("__tostring", &EntityHandle::ToString); + entity.BindMethod("Enable", &Entity::Enable, true); + entity.BindMethod("GetId", &Entity::GetId); + entity.BindMethod("GetWorld", &Entity::GetWorld); + entity.BindMethod("Kill", &Entity::Kill); + entity.BindMethod("IsEnabled", &Entity::IsEnabled); + entity.BindMethod("IsValid", &Entity::IsValid); + entity.BindMethod("RemoveAllComponents", &Entity::RemoveAllComponents); + entity.BindMethod("__tostring", &EntityHandle::ToString); - entityClass.BindMethod("AddComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int + entity.BindMethod("AddComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle, std::size_t /*argumentCount*/) -> int { ComponentBinding* binding = QueryComponentIndex(instance); return binding->adder(instance, handle); }); - entityClass.BindMethod("GetComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int + entity.BindMethod("GetComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle, std::size_t /*argumentCount*/) -> int { ComponentBinding* binding = QueryComponentIndex(instance); return binding->getter(instance, handle->GetComponent(binding->index)); }); - entityClass.BindMethod("RemoveComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int + entity.BindMethod("RemoveComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle, std::size_t /*argumentCount*/) -> int { ComponentBinding* binding = QueryComponentIndex(instance); @@ -96,7 +96,7 @@ namespace Ndk }); /*********************************** Ndk::NodeComponent **********************************/ - nodeComponent.Inherit(nodeClass, [] (NodeComponentHandle* handle) -> Nz::Node* + nodeComponent.Inherit(node, [] (NodeComponentHandle* handle) -> Nz::Node* { return handle->GetObject(); }); @@ -105,7 +105,7 @@ namespace Ndk velocityComponent.SetGetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance) { std::size_t length; - const char* member = lua.CheckString(1, &length); + const char* member = lua.CheckString(2, &length); if (std::strcmp(member, "Linear") == 0) { @@ -119,9 +119,9 @@ namespace Ndk velocityComponent.SetSetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance) { std::size_t length; - const char* member = lua.CheckString(1, &length); + const char* member = lua.CheckString(2, &length); - int argIndex = 2; + int argIndex = 3; if (std::strcmp(member, "Linear") == 0) { instance->linearVelocity = lua.Check(&argIndex); @@ -132,14 +132,69 @@ namespace Ndk }); /*********************************** Ndk::World **********************************/ - worldClass.BindMethod("CreateEntity", &World::CreateEntity); - worldClass.BindMethod("CreateEntities", &World::CreateEntities); - worldClass.BindMethod("Clear", &World::Clear); + world.BindMethod("CreateEntity", &World::CreateEntity); + world.BindMethod("CreateEntities", &World::CreateEntities); + world.BindMethod("Clear", &World::Clear); #ifndef NDK_SERVER /*********************************** Ndk::GraphicsComponent **********************************/ - graphicsComponent.BindMethod("Attach", (void(Ndk::GraphicsComponent::*)(Nz::InstancedRenderableRef, int)) &GraphicsComponent::Attach, 0); + graphicsComponent.BindMethod("Attach", [] (Nz::LuaInstance& lua, Ndk::GraphicsComponent *gfxComponent, std::size_t argumentCount) -> int + { + /* + void Attach(Nz::InstancedRenderableRef renderable, int renderOrder = 0); + void Attach(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& localMatrix, int renderOrder = 0); + */ + + std::size_t argCount = std::min(argumentCount, 3U); + + switch (argCount) + { + case 1: + { + int argIndex = 2; + gfxComponent->Attach(lua.Check(&argIndex)); + return 0; + } + + case 2: + { + int argIndex = 2; + Nz::InstancedRenderableRef renderable = lua.Check(&argIndex); + + if (lua.IsOfType(argIndex, Nz::LuaType_Number)) + { + int renderOrder = lua.Check(&argIndex); + + gfxComponent->Attach(renderable, renderOrder); + } + else if (lua.IsOfType(argIndex, "Matrix4")) + { + Nz::Matrix4f localMatrix = lua.Check(&argIndex); + + gfxComponent->Attach(renderable, localMatrix); + } + else + break; + + return 0; + } + + case 3: + { + int argIndex = 2; + Nz::InstancedRenderableRef renderable = lua.Check(&argIndex); + Nz::Matrix4f localMatrix = lua.Check(&argIndex); + int renderOrder = lua.Check(&argIndex); + + gfxComponent->Attach(renderable, localMatrix, renderOrder); + return 0; + } + } + + lua.Error("No matching overload for method GetMemoryUsage"); + return 0; + }); #endif @@ -164,13 +219,13 @@ namespace Ndk { // Classes application.Register(instance); - entityClass.Register(instance); + entity.Register(instance); nodeComponent.Register(instance); velocityComponent.Register(instance); - worldClass.Register(instance); + world.Register(instance); #ifndef NDK_SERVER - consoleClass.Register(instance); + console.Register(instance); graphicsComponent.Register(instance); #endif diff --git a/SDK/src/NDK/LuaBinding_Utility.cpp b/SDK/src/NDK/LuaBinding_Utility.cpp index 3d8dbdc18..5ae37f669 100644 --- a/SDK/src/NDK/LuaBinding_Utility.cpp +++ b/SDK/src/NDK/LuaBinding_Utility.cpp @@ -25,9 +25,9 @@ namespace Ndk abstractImage.BindMethod("IsCompressed", &Nz::AbstractImage::IsCompressed); abstractImage.BindMethod("IsCubemap", &Nz::AbstractImage::IsCubemap); - abstractImage.BindMethod("GetMemoryUsage", [] (Nz::LuaInstance& lua, Nz::AbstractImage* abstractImage) -> int + abstractImage.BindMethod("GetMemoryUsage", [] (Nz::LuaInstance& lua, Nz::AbstractImage* abstractImage, std::size_t argumentCount) -> int { - unsigned int argCount = std::min(lua.GetStackTop(), 1U); + std::size_t argCount = std::min(argumentCount, 1U); switch (argCount) { case 0: @@ -35,8 +35,8 @@ namespace Ndk case 1: { - int index = 1; - Nz::UInt8 level(lua.Check(&index)); + int argIndex = 2; + Nz::UInt8 level(lua.Check(&argIndex)); return lua.Push(abstractImage->GetMemoryUsage(level)); } @@ -46,10 +46,10 @@ namespace Ndk return 0; }); - abstractImage.BindMethod("Update", [] (Nz::LuaInstance& lua, Nz::AbstractImage* abstractImage) -> int + abstractImage.BindMethod("Update", [] (Nz::LuaInstance& lua, Nz::AbstractImage* abstractImage, std::size_t argumentCount) -> int { - unsigned int argCount = std::min(lua.GetStackTop(), 6U); - int argIndex = 1; + std::size_t argCount = std::min(argumentCount, 6U); + int argIndex = 2; std::size_t bufferSize = 0; const Nz::UInt8* pixels = reinterpret_cast(lua.CheckString(argIndex++, &bufferSize)); @@ -93,25 +93,23 @@ namespace Ndk }); /*********************************** Nz::Font **********************************/ - fontClass.SetConstructor([] (Nz::LuaInstance& lua, Nz::FontRef* font, std::size_t argumentCount) + font.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::FontRef* font, std::size_t /*argumentCount*/) { - NazaraUnused(argumentCount); - Nz::PlacementNew(font, Nz::Font::New()); return true; }); - fontClass.BindMethod("ClearGlyphCache", &Nz::Font::ClearGlyphCache); - fontClass.BindMethod("ClearKerningCache", &Nz::Font::ClearKerningCache); - fontClass.BindMethod("ClearSizeInfoCache", &Nz::Font::ClearSizeInfoCache); + font.BindMethod("ClearGlyphCache", &Nz::Font::ClearGlyphCache); + font.BindMethod("ClearKerningCache", &Nz::Font::ClearKerningCache); + font.BindMethod("ClearSizeInfoCache", &Nz::Font::ClearSizeInfoCache); - fontClass.BindMethod("Destroy", &Nz::Font::Destroy); + font.BindMethod("Destroy", &Nz::Font::Destroy); - fontClass.BindMethod("GetCachedGlyphCount", [] (Nz::LuaInstance& lua, Nz::FontRef& instance) -> int + font.BindMethod("GetCachedGlyphCount", [] (Nz::LuaInstance& lua, Nz::FontRef& instance, std::size_t argumentCount) -> int { - unsigned int argCount = std::min(lua.GetStackTop(), 2U); + std::size_t argCount = std::min(argumentCount, 2U); - int argIndex = 1; + int argIndex = 2; switch (argCount) { case 0: @@ -132,78 +130,78 @@ namespace Ndk return 0; }); - fontClass.BindMethod("GetFamilyName", &Nz::Font::GetFamilyName); - fontClass.BindMethod("GetKerning", &Nz::Font::GetKerning); - fontClass.BindMethod("GetGlyphBorder", &Nz::Font::GetGlyphBorder); - fontClass.BindMethod("GetMinimumStepSize", &Nz::Font::GetMinimumStepSize); - fontClass.BindMethod("GetSizeInfo", &Nz::Font::GetSizeInfo); - fontClass.BindMethod("GetStyleName", &Nz::Font::GetStyleName); + font.BindMethod("GetFamilyName", &Nz::Font::GetFamilyName); + font.BindMethod("GetKerning", &Nz::Font::GetKerning); + font.BindMethod("GetGlyphBorder", &Nz::Font::GetGlyphBorder); + font.BindMethod("GetMinimumStepSize", &Nz::Font::GetMinimumStepSize); + font.BindMethod("GetSizeInfo", &Nz::Font::GetSizeInfo); + font.BindMethod("GetStyleName", &Nz::Font::GetStyleName); - fontClass.BindMethod("IsValid", &Nz::Font::IsValid); + font.BindMethod("IsValid", &Nz::Font::IsValid); - fontClass.BindMethod("Precache", (bool(Nz::Font::*)(unsigned int, Nz::UInt32, const Nz::String&) const) &Nz::Font::Precache); + font.BindMethod("Precache", (bool(Nz::Font::*)(unsigned int, Nz::UInt32, const Nz::String&) const) &Nz::Font::Precache); - fontClass.BindMethod("OpenFromFile", &Nz::Font::OpenFromFile, Nz::FontParams()); + font.BindMethod("OpenFromFile", &Nz::Font::OpenFromFile, Nz::FontParams()); - fontClass.BindMethod("SetGlyphBorder", &Nz::Font::SetGlyphBorder); - fontClass.BindMethod("SetMinimumStepSize", &Nz::Font::SetMinimumStepSize); + font.BindMethod("SetGlyphBorder", &Nz::Font::SetGlyphBorder); + font.BindMethod("SetMinimumStepSize", &Nz::Font::SetMinimumStepSize); - fontClass.BindStaticMethod("GetDefault", &Nz::Font::GetDefault); - fontClass.BindStaticMethod("GetDefaultGlyphBorder", &Nz::Font::GetDefaultGlyphBorder); - fontClass.BindStaticMethod("GetDefaultMinimumStepSize", &Nz::Font::GetDefaultMinimumStepSize); + font.BindStaticMethod("GetDefault", &Nz::Font::GetDefault); + font.BindStaticMethod("GetDefaultGlyphBorder", &Nz::Font::GetDefaultGlyphBorder); + font.BindStaticMethod("GetDefaultMinimumStepSize", &Nz::Font::GetDefaultMinimumStepSize); - fontClass.BindStaticMethod("SetDefaultGlyphBorder", &Nz::Font::SetDefaultGlyphBorder); - fontClass.BindStaticMethod("SetDefaultMinimumStepSize", &Nz::Font::SetDefaultMinimumStepSize); + font.BindStaticMethod("SetDefaultGlyphBorder", &Nz::Font::SetDefaultGlyphBorder); + font.BindStaticMethod("SetDefaultMinimumStepSize", &Nz::Font::SetDefaultMinimumStepSize); /*********************************** Nz::Node **********************************/ - nodeClass.BindMethod("GetBackward", &Nz::Node::GetBackward); + node.BindMethod("GetBackward", &Nz::Node::GetBackward); //nodeClass.SetMethod("GetChilds", &Nz::Node::GetChilds); - nodeClass.BindMethod("GetDown", &Nz::Node::GetDown); - nodeClass.BindMethod("GetForward", &Nz::Node::GetForward); - nodeClass.BindMethod("GetInheritPosition", &Nz::Node::GetInheritPosition); - nodeClass.BindMethod("GetInheritRotation", &Nz::Node::GetInheritRotation); - nodeClass.BindMethod("GetInheritScale", &Nz::Node::GetInheritScale); - nodeClass.BindMethod("GetInitialPosition", &Nz::Node::GetInitialPosition); + node.BindMethod("GetDown", &Nz::Node::GetDown); + node.BindMethod("GetForward", &Nz::Node::GetForward); + node.BindMethod("GetInheritPosition", &Nz::Node::GetInheritPosition); + node.BindMethod("GetInheritRotation", &Nz::Node::GetInheritRotation); + node.BindMethod("GetInheritScale", &Nz::Node::GetInheritScale); + node.BindMethod("GetInitialPosition", &Nz::Node::GetInitialPosition); //nodeClass.SetMethod("GetInitialRotation", &Nz::Node::GetInitialRotation); - nodeClass.BindMethod("GetInitialScale", &Nz::Node::GetInitialScale); - nodeClass.BindMethod("GetLeft", &Nz::Node::GetLeft); - nodeClass.BindMethod("GetNodeType", &Nz::Node::GetNodeType); + node.BindMethod("GetInitialScale", &Nz::Node::GetInitialScale); + node.BindMethod("GetLeft", &Nz::Node::GetLeft); + node.BindMethod("GetNodeType", &Nz::Node::GetNodeType); //nodeClass.SetMethod("GetParent", &Nz::Node::GetParent); - nodeClass.BindMethod("GetPosition", &Nz::Node::GetPosition, Nz::CoordSys_Global); - nodeClass.BindMethod("GetRight", &Nz::Node::GetRight); + node.BindMethod("GetPosition", &Nz::Node::GetPosition, Nz::CoordSys_Global); + node.BindMethod("GetRight", &Nz::Node::GetRight); //nodeClass.SetMethod("GetRotation", &Nz::Node::GetRotation, Nz::CoordSys_Global); - nodeClass.BindMethod("GetScale", &Nz::Node::GetScale, Nz::CoordSys_Global); + node.BindMethod("GetScale", &Nz::Node::GetScale, Nz::CoordSys_Global); //nodeClass.SetMethod("GetTransformMatrix", &Nz::Node::GetTransformMatrix); - nodeClass.BindMethod("GetUp", &Nz::Node::GetUp); + node.BindMethod("GetUp", &Nz::Node::GetUp); - nodeClass.BindMethod("HasChilds", &Nz::Node::HasChilds); + node.BindMethod("HasChilds", &Nz::Node::HasChilds); - nodeClass.BindMethod("GetBackward", &Nz::Node::GetBackward); - nodeClass.BindMethod("GetDown", &Nz::Node::GetDown); - nodeClass.BindMethod("GetForward", &Nz::Node::GetForward); - nodeClass.BindMethod("GetInheritPosition", &Nz::Node::GetInheritPosition); - nodeClass.BindMethod("GetInheritRotation", &Nz::Node::GetInheritRotation); - nodeClass.BindMethod("GetInheritScale", &Nz::Node::GetInheritScale); - nodeClass.BindMethod("GetInitialPosition", &Nz::Node::GetInitialPosition); - nodeClass.BindMethod("GetInitialRotation", &Nz::Node::GetInitialRotation); - nodeClass.BindMethod("GetInitialScale", &Nz::Node::GetInitialScale); - nodeClass.BindMethod("GetLeft", &Nz::Node::GetLeft); - nodeClass.BindMethod("GetNodeType", &Nz::Node::GetNodeType); - nodeClass.BindMethod("GetPosition", &Nz::Node::GetPosition, Nz::CoordSys_Global); - nodeClass.BindMethod("GetRight", &Nz::Node::GetRight); - nodeClass.BindMethod("GetRotation", &Nz::Node::GetRotation, Nz::CoordSys_Global); - nodeClass.BindMethod("GetScale", &Nz::Node::GetScale, Nz::CoordSys_Global); - nodeClass.BindMethod("GetUp", &Nz::Node::GetUp); + node.BindMethod("GetBackward", &Nz::Node::GetBackward); + node.BindMethod("GetDown", &Nz::Node::GetDown); + node.BindMethod("GetForward", &Nz::Node::GetForward); + node.BindMethod("GetInheritPosition", &Nz::Node::GetInheritPosition); + node.BindMethod("GetInheritRotation", &Nz::Node::GetInheritRotation); + node.BindMethod("GetInheritScale", &Nz::Node::GetInheritScale); + node.BindMethod("GetInitialPosition", &Nz::Node::GetInitialPosition); + node.BindMethod("GetInitialRotation", &Nz::Node::GetInitialRotation); + node.BindMethod("GetInitialScale", &Nz::Node::GetInitialScale); + node.BindMethod("GetLeft", &Nz::Node::GetLeft); + node.BindMethod("GetNodeType", &Nz::Node::GetNodeType); + node.BindMethod("GetPosition", &Nz::Node::GetPosition, Nz::CoordSys_Global); + node.BindMethod("GetRight", &Nz::Node::GetRight); + node.BindMethod("GetRotation", &Nz::Node::GetRotation, Nz::CoordSys_Global); + node.BindMethod("GetScale", &Nz::Node::GetScale, Nz::CoordSys_Global); + node.BindMethod("GetUp", &Nz::Node::GetUp); - nodeClass.BindMethod("SetInitialPosition", (void(Nz::Node::*)(const Nz::Vector3f&)) &Nz::Node::SetInitialPosition); - nodeClass.BindMethod("SetInitialRotation", (void(Nz::Node::*)(const Nz::Quaternionf&)) &Nz::Node::SetInitialRotation); + node.BindMethod("SetInitialPosition", (void(Nz::Node::*)(const Nz::Vector3f&)) &Nz::Node::SetInitialPosition); + node.BindMethod("SetInitialRotation", (void(Nz::Node::*)(const Nz::Quaternionf&)) &Nz::Node::SetInitialRotation); - nodeClass.BindMethod("SetPosition", (void(Nz::Node::*)(const Nz::Vector3f&, Nz::CoordSys)) &Nz::Node::SetPosition, Nz::CoordSys_Local); - nodeClass.BindMethod("SetRotation", (void(Nz::Node::*)(const Nz::Quaternionf&, Nz::CoordSys)) &Nz::Node::SetRotation, Nz::CoordSys_Local); + node.BindMethod("SetPosition", (void(Nz::Node::*)(const Nz::Vector3f&, Nz::CoordSys)) &Nz::Node::SetPosition, Nz::CoordSys_Local); + node.BindMethod("SetRotation", (void(Nz::Node::*)(const Nz::Quaternionf&, Nz::CoordSys)) &Nz::Node::SetRotation, Nz::CoordSys_Local); - nodeClass.BindMethod("Move", [] (Nz::LuaInstance& lua, Nz::Node& node) -> int + node.BindMethod("Move", [] (Nz::LuaInstance& lua, Nz::Node& node, std::size_t /*argumentCount*/) -> int { - int argIndex = 1; + int argIndex = 2; Nz::Vector3f offset = lua.Check(&argIndex); Nz::CoordSys coordSys = lua.Check(&argIndex, Nz::CoordSys_Local); @@ -212,9 +210,9 @@ namespace Ndk return 0; }); - nodeClass.BindMethod("Rotate", [] (Nz::LuaInstance& lua, Nz::Node& node) -> int + node.BindMethod("Rotate", [] (Nz::LuaInstance& lua, Nz::Node& node, std::size_t /*argumentCount*/) -> int { - int argIndex = 1; + int argIndex = 2; Nz::Quaternionf rotation = lua.Check(&argIndex); Nz::CoordSys coordSys = lua.Check(&argIndex, Nz::CoordSys_Local); @@ -223,11 +221,11 @@ namespace Ndk return 0; }); - nodeClass.BindMethod("Scale", [] (Nz::LuaInstance& lua, Nz::Node& node) -> int + node.BindMethod("Scale", [] (Nz::LuaInstance& lua, Nz::Node& node, std::size_t argumentCount) -> int { - unsigned int argCount = std::min(lua.GetStackTop(), 4U); + std::size_t argCount = std::min(argumentCount, 4U); - int argIndex = 1; + int argIndex = 2; switch (argCount) { case 1: @@ -249,11 +247,11 @@ namespace Ndk return 0; }); - nodeClass.BindMethod("SetScale", [] (Nz::LuaInstance& lua, Nz::Node& node) -> int + node.BindMethod("SetScale", [] (Nz::LuaInstance& lua, Nz::Node& node, std::size_t argumentCount) -> int { - unsigned int argCount = std::min(lua.GetStackTop(), 4U); + std::size_t argCount = std::min(argumentCount, 4U); - int argIndex = 1; + int argIndex = 2; switch (argCount) { case 1: @@ -286,11 +284,11 @@ namespace Ndk return 0; }); - nodeClass.BindMethod("SetInitialScale", [] (Nz::LuaInstance& lua, Nz::Node& node) -> int + node.BindMethod("SetInitialScale", [] (Nz::LuaInstance& lua, Nz::Node& node, std::size_t argumentCount) -> int { - unsigned int argCount = std::min(lua.GetStackTop(), 4U); + std::size_t argCount = std::min(argumentCount, 4U); - int argIndex = 1; + int argIndex = 2; switch (argCount) { case 1: @@ -323,7 +321,7 @@ namespace Ndk void LuaBinding::RegisterUtility(Nz::LuaInstance& instance) { abstractImage.Register(instance); - fontClass.Register(instance); - nodeClass.Register(instance); + font.Register(instance); + node.Register(instance); } } \ No newline at end of file diff --git a/SDK/src/NDK/Sdk.cpp b/SDK/src/NDK/Sdk.cpp index 326eec502..36283ada3 100644 --- a/SDK/src/NDK/Sdk.cpp +++ b/SDK/src/NDK/Sdk.cpp @@ -9,15 +9,15 @@ #include #include #include -#include +#include #include #include #include -#include +#include #include -#include +#include #include -#include +#include #include #ifndef NDK_SERVER @@ -68,7 +68,7 @@ namespace Ndk Nz::Lua::Initialize(); Nz::Noise::Initialize(); - Nz::Physics::Initialize(); + Nz::Physics3D::Initialize(); Nz::Utility::Initialize(); #ifndef NDK_SERVER @@ -83,9 +83,9 @@ namespace Ndk BaseComponent::Initialize(); // Shared components - InitializeComponent("NdkColli"); + InitializeComponent("NdkColli"); InitializeComponent("NdkNode"); - InitializeComponent("NdkPhys"); + InitializeComponent("NdkPhys"); InitializeComponent("NdkVeloc"); #ifndef NDK_SERVER @@ -103,7 +103,7 @@ namespace Ndk BaseSystem::Initialize(); // Shared systems - InitializeSystem(); + InitializeSystem(); InitializeSystem(); #ifndef NDK_SERVER @@ -161,7 +161,7 @@ namespace Ndk // Shared modules Nz::Lua::Uninitialize(); Nz::Noise::Uninitialize(); - Nz::Physics::Uninitialize(); + Nz::Physics3D::Uninitialize(); Nz::Utility::Uninitialize(); NazaraNotice("Uninitialized: SDK"); diff --git a/SDK/src/NDK/Systems/PhysicsSystem.cpp b/SDK/src/NDK/Systems/PhysicsSystem3D.cpp similarity index 64% rename from SDK/src/NDK/Systems/PhysicsSystem.cpp rename to SDK/src/NDK/Systems/PhysicsSystem3D.cpp index 442784c22..fd5e05d66 100644 --- a/SDK/src/NDK/Systems/PhysicsSystem.cpp +++ b/SDK/src/NDK/Systems/PhysicsSystem3D.cpp @@ -2,11 +2,11 @@ // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp -#include -#include -#include +#include +#include +#include #include -#include +#include namespace Ndk { @@ -15,7 +15,7 @@ namespace Ndk * \class Ndk::PhysicsSystem * \brief NDK class that represents the physics system * - * \remark This system is enabled if the entity has the trait: NodeComponent and any of these two: CollisionComponent or PhysicsComponent + * \remark This system is enabled if the entity has the trait: NodeComponent and any of these two: CollisionComponent3D or PhysicsComponent3D * \remark Static objects do not have a velocity specified by the physical engine */ @@ -23,10 +23,10 @@ namespace Ndk * \brief Constructs an PhysicsSystem object by default */ - PhysicsSystem::PhysicsSystem() + PhysicsSystem3D::PhysicsSystem3D() { Requires(); - RequiresAny(); + RequiresAny(); } /*! @@ -35,12 +35,19 @@ namespace Ndk * \param system PhysicsSystem to copy */ - PhysicsSystem::PhysicsSystem(const PhysicsSystem& system) : + PhysicsSystem3D::PhysicsSystem3D(const PhysicsSystem3D& system) : System(system), m_world() { } + void PhysicsSystem3D::CreatePhysWorld() const + { + NazaraAssert(!m_world, "Physics world should not be created twice"); + + m_world = std::make_unique(); + } + /*! * \brief Operation to perform when entity is validated for the system * @@ -48,18 +55,21 @@ namespace Ndk * \param justAdded Is the entity newly added */ - void PhysicsSystem::OnEntityValidation(Entity* entity, bool justAdded) + void PhysicsSystem3D::OnEntityValidation(Entity* entity, bool justAdded) { - // If entity has not been just added to the system, it is possible that it does not own to the right array + // It's possible our entity got revalidated because of the addition/removal of a PhysicsComponent3D if (!justAdded) { - // We take the inverted array from which the entity should belong to - auto& entities = (entity->HasComponent()) ? m_staticObjects : m_dynamicObjects; + // We take the opposite array from which the entity should belong to + auto& entities = (entity->HasComponent()) ? m_staticObjects : m_dynamicObjects; entities.Remove(entity); } - auto& entities = (entity->HasComponent()) ? m_dynamicObjects : m_staticObjects; + auto& entities = (entity->HasComponent()) ? m_dynamicObjects : m_staticObjects; entities.Insert(entity); + + if (!m_world) + CreatePhysWorld(); } /*! @@ -68,16 +78,19 @@ namespace Ndk * \param elapsedTime Delta time used for the update */ - void PhysicsSystem::OnUpdate(float elapsedTime) + void PhysicsSystem3D::OnUpdate(float elapsedTime) { - m_world.Step(elapsedTime); + if (!m_world) + return; + + m_world->Step(elapsedTime); for (const Ndk::EntityHandle& entity : m_dynamicObjects) { NodeComponent& node = entity->GetComponent(); - PhysicsComponent& phys = entity->GetComponent(); + PhysicsComponent3D& phys = entity->GetComponent(); - Nz::PhysObject& physObj = phys.GetPhysObject(); + Nz::RigidBody3D& physObj = phys.GetPhysObject(); node.SetRotation(physObj.GetRotation(), Nz::CoordSys_Global); node.SetPosition(physObj.GetPosition(), Nz::CoordSys_Global); } @@ -85,10 +98,10 @@ namespace Ndk float invElapsedTime = 1.f / elapsedTime; for (const Ndk::EntityHandle& entity : m_staticObjects) { - CollisionComponent& collision = entity->GetComponent(); + CollisionComponent3D& collision = entity->GetComponent(); NodeComponent& node = entity->GetComponent(); - Nz::PhysObject* physObj = collision.GetStaticBody(); + Nz::RigidBody3D* physObj = collision.GetStaticBody(); Nz::Quaternionf oldRotation = physObj->GetRotation(); Nz::Vector3f oldPosition = physObj->GetPosition(); @@ -121,5 +134,5 @@ namespace Ndk } } - SystemIndex PhysicsSystem::systemIndex; + SystemIndex PhysicsSystem3D::systemIndex; } diff --git a/SDK/src/NDK/Systems/RenderSystem.cpp b/SDK/src/NDK/Systems/RenderSystem.cpp index 107676206..fbc2d3e08 100644 --- a/SDK/src/NDK/Systems/RenderSystem.cpp +++ b/SDK/src/NDK/Systems/RenderSystem.cpp @@ -147,7 +147,6 @@ namespace Ndk for (const Ndk::EntityHandle& drawable : m_drawables) { GraphicsComponent& graphicsComponent = drawable->GetComponent(); - NodeComponent& drawableNode = drawable->GetComponent(); graphicsComponent.AddToRenderQueue(renderQueue); } @@ -186,7 +185,7 @@ namespace Ndk * \param viewer Viewer of the scene */ - void RenderSystem::UpdateDirectionalShadowMaps(const Nz::AbstractViewer& viewer) + void RenderSystem::UpdateDirectionalShadowMaps(const Nz::AbstractViewer& /*viewer*/) { if (!m_shadowRT.IsValid()) m_shadowRT.Create(); @@ -217,7 +216,6 @@ namespace Ndk for (const Ndk::EntityHandle& drawable : m_drawables) { GraphicsComponent& graphicsComponent = drawable->GetComponent(); - NodeComponent& drawableNode = drawable->GetComponent(); graphicsComponent.AddToRenderQueue(renderQueue); } @@ -290,7 +288,6 @@ namespace Ndk for (const Ndk::EntityHandle& drawable : m_drawables) { GraphicsComponent& graphicsComponent = drawable->GetComponent(); - NodeComponent& drawableNode = drawable->GetComponent(); graphicsComponent.AddToRenderQueue(renderQueue); } @@ -318,7 +315,6 @@ namespace Ndk for (const Ndk::EntityHandle& drawable : m_drawables) { GraphicsComponent& graphicsComponent = drawable->GetComponent(); - NodeComponent& drawableNode = drawable->GetComponent(); graphicsComponent.AddToRenderQueue(renderQueue); } diff --git a/SDK/src/NDK/Systems/VelocitySystem.cpp b/SDK/src/NDK/Systems/VelocitySystem.cpp index e8cfe2f23..c1298bde3 100644 --- a/SDK/src/NDK/Systems/VelocitySystem.cpp +++ b/SDK/src/NDK/Systems/VelocitySystem.cpp @@ -4,7 +4,7 @@ #include #include -#include +#include #include namespace Ndk @@ -15,7 +15,7 @@ namespace Ndk * \brief NDK class that represents the velocity system * * \remark This system is enabled if the entity owns the trait: NodeComponent and VelocityComponent - * but it's disabled with the trait: PhysicsComponent + * but it's disabled with the trait: PhysicsComponent3D */ /*! @@ -25,7 +25,7 @@ namespace Ndk VelocitySystem::VelocitySystem() { Requires(); - Excludes(); + Excludes(); } /*! diff --git a/SDK/src/NDK/World.cpp b/SDK/src/NDK/World.cpp index 938722feb..6ba110aee 100644 --- a/SDK/src/NDK/World.cpp +++ b/SDK/src/NDK/World.cpp @@ -5,7 +5,7 @@ #include #include #include -#include +#include #include #ifndef NDK_SERVER @@ -40,7 +40,7 @@ namespace Ndk void World::AddDefaultSystems() { - AddSystem(); + AddSystem(); AddSystem(); #ifndef NDK_SERVER diff --git a/build/scripts/actions/generateheaders.lua b/build/scripts/actions/generateheaders.lua index 943919a90..6bbd5782c 100644 --- a/build/scripts/actions/generateheaders.lua +++ b/build/scripts/actions/generateheaders.lua @@ -67,7 +67,7 @@ ACTION.Function = function () error("Failed to create header file (" .. v.Target .. "): " .. err) end - header:write("// This file was automatically generated on " .. os.date("%d %b %Y at %X") .. "\n\n") + header:write("// This file was automatically generated\n\n") if (v.Header) then header:write(v.Header) end diff --git a/build/scripts/common.lua b/build/scripts/common.lua index 30272acfd..423ebad0d 100644 --- a/build/scripts/common.lua +++ b/build/scripts/common.lua @@ -312,7 +312,7 @@ function NazaraBuild:Execute() if (toolTable.Kind == "library") then targetdir(toolTable.TargetDirectory .. "/" .. makeLibDir .. "/x86") elseif (toolTable.Kind == "plugin") then - targetdir("../plugins/" .. toolTable.Name .. "/lib/" .. makeLibDir .. "/x86") + targetdir("../plugins/lib/" .. makeLibDir .. "/x86") end configuration({"codeblocks or codelite or gmake", "x64"}) @@ -321,7 +321,7 @@ function NazaraBuild:Execute() if (toolTable.Kind == "library") then targetdir(toolTable.TargetDirectory .. "/" .. makeLibDir .. "/x64") elseif (toolTable.Kind == "plugin") then - targetdir("../plugins/" .. toolTable.Name .. "/lib/" .. makeLibDir .. "/x64") + targetdir("../plugins/lib/" .. makeLibDir .. "/x64") end configuration({"vs*", "x32"}) @@ -330,7 +330,7 @@ function NazaraBuild:Execute() if (toolTable.Kind == "library") then targetdir(toolTable.TargetDirectory .. "/msvc/x86") elseif (toolTable.Kind == "plugin") then - targetdir("../plugins/" .. toolTable.Name .. "/lib/msvc/x86") + targetdir("../plugins/lib/msvc/x86") end configuration({"vs*", "x64"}) @@ -339,7 +339,7 @@ function NazaraBuild:Execute() if (toolTable.Kind == "library") then targetdir(toolTable.TargetDirectory .. "/msvc/x64") elseif (toolTable.Kind == "plugin") then - targetdir("../plugins/" .. toolTable.Name .. "/lib/msvc/x64") + targetdir("../plugins/lib/msvc/x64") end configuration({"xcode3 or xcode4", "x32"}) @@ -348,7 +348,7 @@ function NazaraBuild:Execute() if (toolTable.Kind == "library") then targetdir(toolTable.TargetDirectory .. "/xcode/x86") elseif (toolTable.Kind == "plugin") then - targetdir("../plugins/" .. toolTable.Name .. "/lib/xcode/x86") + targetdir("../plugins/lib/xcode/x86") end configuration({"xcode3 or xcode4", "x64"}) @@ -357,7 +357,7 @@ function NazaraBuild:Execute() if (toolTable.Kind == "library") then targetdir(toolTable.TargetDirectory .. "/xcode/x64") elseif (toolTable.Kind == "plugin") then - targetdir("../plugins/" .. toolTable.Name .. "/lib/xcode/x64") + targetdir("../plugins/lib/xcode/x64") end configuration("*Static") @@ -403,7 +403,7 @@ function NazaraBuild:Execute() for k, exampleTable in ipairs(self.OrderedExamples) do local destPath = "../examples/bin" - + project("Demo" .. exampleTable.Name) location(_ACTION .. "/examples") diff --git a/build/scripts/modules/physics2d.lua b/build/scripts/modules/physics2d.lua new file mode 100644 index 000000000..a7514b8cd --- /dev/null +++ b/build/scripts/modules/physics2d.lua @@ -0,0 +1,6 @@ +MODULE.Name = "Physics2D" + +MODULE.Libraries = { + "NazaraCore", + "chipmunk-s" +} diff --git a/build/scripts/modules/physics.lua b/build/scripts/modules/physics3d.lua similarity index 73% rename from build/scripts/modules/physics.lua rename to build/scripts/modules/physics3d.lua index 0796c46fd..d98a6f645 100644 --- a/build/scripts/modules/physics.lua +++ b/build/scripts/modules/physics3d.lua @@ -1,4 +1,4 @@ -MODULE.Name = "Physics" +MODULE.Name = "Physics3D" MODULE.Libraries = { "NazaraCore", diff --git a/build/scripts/tools/ndk.lua b/build/scripts/tools/ndk.lua index 66dcf9a17..6c98029ef 100644 --- a/build/scripts/tools/ndk.lua +++ b/build/scripts/tools/ndk.lua @@ -26,6 +26,6 @@ TOOL.Libraries = function() for k,v in pairs(NazaraBuild.Modules) do table.insert(libraries, "Nazara" .. v.Name) end - + return libraries end \ No newline at end of file diff --git a/build/scripts/tools/ndk_server.lua b/build/scripts/tools/ndk_server.lua index cebd158c6..841aa6e4e 100644 --- a/build/scripts/tools/ndk_server.lua +++ b/build/scripts/tools/ndk_server.lua @@ -44,6 +44,7 @@ TOOL.Libraries = { "NazaraLua", "NazaraNetwork", "NazaraNoise", - "NazaraPhysics", + "NazaraPhysics2D", + "NazaraPhysics3D", "NazaraUtility" } diff --git a/build/scripts/tools/unittests.lua b/build/scripts/tools/unittests.lua index 5dcf6e215..6c44540a3 100644 --- a/build/scripts/tools/unittests.lua +++ b/build/scripts/tools/unittests.lua @@ -14,7 +14,9 @@ TOOL.Includes = { TOOL.Files = { "../tests/main.cpp", + "../tests/Engine/**.hpp", "../tests/Engine/**.cpp", + "../tests/SDK/**.hpp", "../tests/SDK/**.cpp" } diff --git a/build/scripts/tools/unittests_server.lua b/build/scripts/tools/unittests_server.lua index b3eab27c0..c94a54d6d 100644 --- a/build/scripts/tools/unittests_server.lua +++ b/build/scripts/tools/unittests_server.lua @@ -15,7 +15,9 @@ TOOL.Includes = { TOOL.Files = { "../tests/main.cpp", + "../tests/Engine/**.hpp", "../tests/Engine/**.cpp", + "../tests/SDK/**.hpp", "../tests/SDK/**.cpp" } @@ -23,6 +25,7 @@ TOOL.Files = { TOOL.FilesExcluded = { "../tests/Engine/Audio/**", "../tests/Engine/Graphics/**", + "../tests/Engine/Utility/**", "../tests/SDK/NDK/Application.cpp", "../tests/SDK/NDK/Systems/ListenerSystem.cpp", "../tests/SDK/NDK/Systems/RenderSystem.cpp" diff --git a/examples/Tut00/build.lua b/examples/Tut00/build.lua index ed5ea5995..678aa3394 100644 --- a/examples/Tut00/build.lua +++ b/examples/Tut00/build.lua @@ -13,7 +13,8 @@ EXAMPLE.Libraries = { "NazaraLua", "NazaraNetwork", "NazaraNoise", - "NazaraPhysics", + "NazaraPhysics2D", + "NazaraPhysics3D", "NazaraRenderer", "NazaraUtility", "NazaraSDK" diff --git a/examples/Tut00/main.cpp b/examples/Tut00/main.cpp index cfffa4c59..a1029eb99 100644 --- a/examples/Tut00/main.cpp +++ b/examples/Tut00/main.cpp @@ -4,7 +4,8 @@ #include #include #include -#include +#include +#include #include #include #include @@ -19,4 +20,4 @@ int main(int argc, char* argv[]) // Do what you want here return EXIT_SUCCESS; -} \ No newline at end of file +} diff --git a/include/Nazara/Audio.hpp b/include/Nazara/Audio.hpp index d0fd17d6f..5becbb066 100644 --- a/include/Nazara/Audio.hpp +++ b/include/Nazara/Audio.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 24 Jun 2015 at 13:55:50 +// This file was automatically generated /* Nazara Engine - Audio module diff --git a/include/Nazara/Core.hpp b/include/Nazara/Core.hpp index 5f3c85c4c..419ddaae9 100644 --- a/include/Nazara/Core.hpp +++ b/include/Nazara/Core.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 09 May 2016 at 17:07:09 +// This file was automatically generated /* Nazara Engine - Core module diff --git a/include/Nazara/Core/AbstractLogger.hpp b/include/Nazara/Core/AbstractLogger.hpp index d4cd772f5..fbe61c080 100644 --- a/include/Nazara/Core/AbstractLogger.hpp +++ b/include/Nazara/Core/AbstractLogger.hpp @@ -21,7 +21,7 @@ namespace Nz virtual void EnableStdReplication(bool enable) = 0; - virtual bool IsStdReplicationEnabled() = 0; + virtual bool IsStdReplicationEnabled() const = 0; virtual void Write(const String& string) = 0; virtual void WriteError(ErrorType type, const String& error, unsigned int line = 0, const char* file = nullptr, const char* function = nullptr); diff --git a/include/Nazara/Core/Algorithm.hpp b/include/Nazara/Core/Algorithm.hpp index be25f4773..5bb461f26 100644 --- a/include/Nazara/Core/Algorithm.hpp +++ b/include/Nazara/Core/Algorithm.hpp @@ -20,8 +20,8 @@ namespace Nz class AbstractHash; class ByteArray; - template auto Apply(F&& fn, Tuple&& t); - template auto Apply(O& object, F&& fn, Tuple&& t); + template decltype(auto) Apply(F&& fn, Tuple&& t); + template decltype(auto) Apply(O& object, F&& fn, Tuple&& t); template ByteArray ComputeHash(HashType hash, const T& v); template ByteArray ComputeHash(AbstractHash* hash, const T& v); template constexpr std::size_t CountOf(T(&name)[N]) noexcept; diff --git a/include/Nazara/Core/Algorithm.inl b/include/Nazara/Core/Algorithm.inl index 4008f8860..b02924446 100644 --- a/include/Nazara/Core/Algorithm.inl +++ b/include/Nazara/Core/Algorithm.inl @@ -19,13 +19,13 @@ namespace Nz { // http://www.cppsamples.com/common-tasks/apply-tuple-to-function.html template - auto ApplyImplFunc(F&& fn, Tuple&& t, std::index_sequence) + decltype(auto) ApplyImplFunc(F&& fn, Tuple&& t, std::index_sequence) { return std::forward(fn)(std::get(std::forward(t))...); } template - auto ApplyImplMethod(O& object, F&& fn, Tuple&& t, std::index_sequence) + decltype(auto) ApplyImplMethod(O& object, F&& fn, Tuple&& t, std::index_sequence) { return (object .* std::forward(fn))(std::get(std::forward(t))...); } @@ -44,7 +44,7 @@ namespace Nz * \see Apply */ template - auto Apply(F&& fn, Tuple&& t) + decltype(auto) Apply(F&& fn, Tuple&& t) { constexpr std::size_t tSize = std::tuple_size::type>::value; @@ -63,7 +63,7 @@ namespace Nz * \see Apply */ template - auto Apply(O& object, F&& fn, Tuple&& t) + decltype(auto) Apply(O& object, F&& fn, Tuple&& t) { constexpr std::size_t tSize = std::tuple_size::type>::value; @@ -123,9 +123,8 @@ namespace Nz * \see CountOf */ template - constexpr std::size_t CountOf(T(&name)[N]) noexcept + constexpr std::size_t CountOf(T(&)[N]) noexcept { - // NazaraUnused(name); //< Because "body of function is not a return-statement" >.> return N; } diff --git a/include/Nazara/Core/FileLogger.hpp b/include/Nazara/Core/FileLogger.hpp index d0e4fe2aa..d7b1d8f14 100644 --- a/include/Nazara/Core/FileLogger.hpp +++ b/include/Nazara/Core/FileLogger.hpp @@ -25,8 +25,8 @@ namespace Nz void EnableTimeLogging(bool enable); void EnableStdReplication(bool enable) override; - bool IsStdReplicationEnabled() override; - bool IsTimeLoggingEnabled(); + bool IsStdReplicationEnabled() const override; + bool IsTimeLoggingEnabled() const; void Write(const String& string) override; void WriteError(ErrorType type, const String& error, unsigned int line = 0, const char* file = nullptr, const char* function = nullptr) override; diff --git a/include/Nazara/Core/HandledObject.inl b/include/Nazara/Core/HandledObject.inl index 6b4d64c45..43feebcd3 100644 --- a/include/Nazara/Core/HandledObject.inl +++ b/include/Nazara/Core/HandledObject.inl @@ -71,6 +71,8 @@ namespace Nz template HandledObject& HandledObject::operator=(const HandledObject& object) { + NazaraUnused(object); + // Nothing to do return *this; } diff --git a/include/Nazara/Core/ObjectRef.hpp b/include/Nazara/Core/ObjectRef.hpp index d1cd13ec0..6a69a22ee 100644 --- a/include/Nazara/Core/ObjectRef.hpp +++ b/include/Nazara/Core/ObjectRef.hpp @@ -56,7 +56,7 @@ namespace Nz template bool operator<(const T& lhs, const ObjectRef& rhs); template bool operator<(const ObjectRef& lhs, const T& rhs); - template bool operator<=(const ObjectRef, const ObjectRef& rhs); + template bool operator<=(const ObjectRef& lhs, const ObjectRef& rhs); template bool operator<=(const T& lhs, const ObjectRef& rhs); template bool operator<=(const ObjectRef& lhs, const T& rhs); diff --git a/include/Nazara/Core/ResourceManager.inl b/include/Nazara/Core/ResourceManager.inl index edc85068b..6fec2aae0 100644 --- a/include/Nazara/Core/ResourceManager.inl +++ b/include/Nazara/Core/ResourceManager.inl @@ -78,7 +78,7 @@ namespace Nz while (it != Type::s_managerMap.end()) { const ObjectRef& ref = it->second; - if (ref.GetReferenceCount() == 1) // Are we the only ones to own the resource ? + if (ref->GetReferenceCount() == 1) // Are we the only ones to own the resource ? { NazaraDebug("Purging resource from file " + ref->GetFilePath()); Type::s_managerMap.erase(it++); // Then we erase it diff --git a/include/Nazara/Core/StdLogger.hpp b/include/Nazara/Core/StdLogger.hpp index 430b5a7af..16fd0bb47 100644 --- a/include/Nazara/Core/StdLogger.hpp +++ b/include/Nazara/Core/StdLogger.hpp @@ -22,7 +22,7 @@ namespace Nz void EnableStdReplication(bool enable) override; - bool IsStdReplicationEnabled() override; + bool IsStdReplicationEnabled() const override; void Write(const String& string) override; void WriteError(ErrorType type, const String& error, unsigned int line = 0, const char* file = nullptr, const char* function = nullptr) override; diff --git a/include/Nazara/Graphics.hpp b/include/Nazara/Graphics.hpp index c317001a1..252110d9d 100644 --- a/include/Nazara/Graphics.hpp +++ b/include/Nazara/Graphics.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 15 Sep 2016 at 00:43:26 +// This file was automatically generated /* Nazara Engine - Graphics module @@ -72,7 +72,6 @@ #include #include #include -#include #include #include #include diff --git a/include/Nazara/Graphics/TextSprite.hpp b/include/Nazara/Graphics/TextSprite.hpp index 8e0afa93e..3e05c2795 100644 --- a/include/Nazara/Graphics/TextSprite.hpp +++ b/include/Nazara/Graphics/TextSprite.hpp @@ -78,7 +78,6 @@ namespace Nz Color m_color; MaterialRef m_material; Recti m_localBounds; - mutable bool m_verticesUpdated; float m_scale; static TextSpriteLibrary::LibraryMap s_library; diff --git a/include/Nazara/Lua.hpp b/include/Nazara/Lua.hpp index f73541cb8..a0e68204c 100644 --- a/include/Nazara/Lua.hpp +++ b/include/Nazara/Lua.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 24 Jun 2015 at 13:55:50 +// This file was automatically generated /* Nazara Engine - Lua scripting module diff --git a/include/Nazara/Lua/LuaClass.hpp b/include/Nazara/Lua/LuaClass.hpp index 567c3de7c..3085aed0f 100644 --- a/include/Nazara/Lua/LuaClass.hpp +++ b/include/Nazara/Lua/LuaClass.hpp @@ -26,7 +26,7 @@ namespace Nz friend class LuaClass; public: - using ClassFunc = std::function; + using ClassFunc = std::function; using ClassIndexFunc = std::function; using ConstructorFunc = std::function; template using ConvertToParent = std::function; @@ -34,6 +34,7 @@ namespace Nz using StaticIndexFunc = std::function; using StaticFunc = std::function; + LuaClass() = default; LuaClass(const String& name); void BindDefaultConstructor(); @@ -50,6 +51,9 @@ namespace Nz template void Inherit(LuaClass

& parent); template void Inherit(LuaClass

& parent, ConvertToParent

convertFunc); + void Reset(); + void Reset(const String& name); + void Register(LuaInstance& lua); void PushGlobalTable(LuaInstance& lua); @@ -62,6 +66,19 @@ namespace Nz void SetStaticSetter(StaticIndexFunc getter); private: + template + friend struct LuaClassImplFinalizerSetupProxy; + + void PushClassInfo(LuaInstance& lua); + void SetupConstructor(LuaInstance& lua); + void SetupDefaultToString(LuaInstance& lua); + void SetupFinalizer(LuaInstance& lua); + void SetupGetter(LuaInstance& lua, LuaCFunction proxy); + void SetupGlobalTable(LuaInstance& lua); + void SetupMetatable(LuaInstance& lua); + void SetupMethod(LuaInstance& lua, LuaCFunction proxy, const String& name, std::size_t methodIndex); + void SetupSetter(LuaInstance& lua, LuaCFunction proxy); + using ParentFunc = std::function; using InstanceGetter = std::function; diff --git a/include/Nazara/Lua/LuaClass.inl b/include/Nazara/Lua/LuaClass.inl index ea53cf0cd..daf7a632a 100644 --- a/include/Nazara/Lua/LuaClass.inl +++ b/include/Nazara/Lua/LuaClass.inl @@ -2,6 +2,7 @@ // This file is part of the "Nazara Engine - Lua scripting module" // For conditions of distribution and use, see copyright notice in Config.hpp +#include #include #include #include @@ -10,10 +11,9 @@ namespace Nz { template - LuaClass::LuaClass(const String& name) : - m_info(new ClassInfo) + LuaClass::LuaClass(const String& name) { - m_info->name = name; + Reset(name); } template @@ -58,147 +58,37 @@ namespace Nz }); } + + template + void LuaClass::Reset() + { + m_info.reset(); + } + + template + void LuaClass::Reset(const String& name) + { + m_info = std::make_shared(); + m_info->name = name; + + m_info->instanceGetters[m_info->name] = [info = m_info] (LuaInstance& instance) + { + return static_cast(instance.CheckUserdata(1, info->name)); + }; + } + template void LuaClass::Register(LuaInstance& lua) { - // Le ClassInfo doit rester en vie jusqu'à la fin du script - // Obliger l'instance de LuaClass à rester en vie dans cette fin serait contraignant pour l'utilisateur - // J'utilise donc une astuce, la stocker dans une UserData associée avec chaque fonction de la metatable du type, - // cette UserData disposera d'un finalizer qui libérera le ClassInfo - // Ainsi c'est Lua qui va s'occuper de la destruction pour nous :-) - // De même, l'utilisation d'un shared_ptr permet de garder la structure en vie même si l'instance est libérée avant le LuaClass - std::shared_ptr* info = static_cast*>(lua.PushUserdata(sizeof(std::shared_ptr))); - PlacementNew(info, m_info); + PushClassInfo(lua); - // On créé la table qui contiendra une méthode (Le finalizer) pour libérer le ClassInfo - lua.PushTable(0, 1); - lua.PushLightUserdata(info); - lua.PushCFunction(InfoDestructor, 1); - lua.SetField("__gc"); - lua.SetMetatable(-2); // La table devient la metatable de l'UserData + // Let's create the metatable which will be associated with every instance. + SetupMetatable(lua); - // Maintenant, nous allons associer l'UserData avec chaque fonction, de sorte qu'il reste en vie - // aussi longtemps que nécessaire, et que le pointeur soit transmis à chaque méthode + if (m_info->constructor || m_info->staticGetter || m_info->staticSetter || !m_staticMethods.empty()) + SetupGlobalTable(lua); - if (!lua.NewMetatable(m_info->name)) - NazaraWarning("Class \"" + m_info->name + "\" already registred in this instance"); - { - // Set the type in a __type field - lua.PushString(m_info->name); - lua.SetField("__type"); - - // In case a __tostring method is missing, add a default implementation returning the type - if (m_methods.find("__tostring") == m_methods.end()) - { - // Define the Finalizer - lua.PushValue(1); // shared_ptr on UserData - lua.PushCFunction(ToStringProxy, 1); - lua.SetField("__tostring"); - } - - // Define the Finalizer - lua.PushValue(1); - lua.PushCFunction(FinalizerProxy, 1); - lua.SetField("__gc"); - - if (m_info->getter || !m_info->parentGetters.empty()) - { - lua.PushValue(1); // shared_ptr on UserData - lua.PushValue(-2); // Metatable - lua.PushCFunction(GetterProxy, 2); - } - else - // Optimisation, plutôt que de rediriger vers une fonction C qui ne fera rien d'autre que rechercher - // dans la table, nous envoyons directement la table, de sorte que Lua fasse directement la recherche - // Ceci n'est possible que si nous n'avons ni getter, ni parent - lua.PushValue(-1); // Metatable - - lua.SetField("__index"); // Getter - - if (m_info->setter) - { - lua.PushValue(1); // shared_ptr on UserData - lua.PushCFunction(SetterProxy, 1); - lua.SetField("__newindex"); // Setter - } - - m_info->methods.reserve(m_methods.size()); - for (auto& pair : m_methods) - { - std::size_t methodIndex = m_info->methods.size(); - m_info->methods.push_back(pair.second); - - lua.PushValue(1); // shared_ptr on UserData - lua.PushInteger(methodIndex); - - lua.PushCFunction(MethodProxy, 2); - lua.SetField(pair.first); // Method name - } - - m_info->instanceGetters[m_info->name] = [info = m_info] (LuaInstance& instance) - { - return static_cast(instance.CheckUserdata(1, info->name)); - }; - } - lua.Pop(); // On pop la metatable - - if (m_info->constructor || m_info->staticGetter || m_info->staticSetter || !m_info->staticMethods.empty()) - { - // Création de l'instance globale - lua.PushTable(); // Class = {} - - // Création de la metatable associée à la table globale - lua.PushTable(); // ClassMeta = {} - - if (m_info->constructor) - { - lua.PushValue(1); // ClassInfo - lua.PushCFunction(ConstructorProxy, 1); - lua.SetField("__call"); // ClassMeta.__call = ConstructorProxy - } - - if (m_info->staticGetter) - { - lua.PushValue(1); // shared_ptr on UserData - lua.PushValue(-2); // ClassMeta - lua.PushCFunction(StaticGetterProxy, 2); - } - else - // Optimisation, plutôt que de rediriger vers une fonction C qui ne fera rien d'autre que rechercher - // dans la table, nous envoyons directement la table, de sorte que Lua fasse directement la recherche - // Ceci n'est possible que si nous n'avons ni getter, ni parent - lua.PushValue(-1); // ClassMeta - - lua.SetField("__index"); // ClassMeta.__index = StaticGetterProxy/ClassMeta - - if (m_info->staticSetter) - { - lua.PushValue(1); // shared_ptr on UserData - lua.PushCFunction(StaticSetterProxy, 1); - lua.SetField("__newindex"); // ClassMeta.__newindex = StaticSetterProxy - } - - m_info->staticMethods.reserve(m_staticMethods.size()); - for (auto& pair : m_staticMethods) - { - std::size_t methodIndex = m_info->staticMethods.size(); - m_info->staticMethods.push_back(pair.second); - - lua.PushValue(1); // shared_ptr on UserData - lua.PushInteger(methodIndex); - - lua.PushCFunction(StaticMethodProxy, 2); - lua.SetField(pair.first); // ClassMeta.method = StaticMethodProxy - } - - lua.SetMetatable(-2); // setmetatable(Class, ClassMeta) - - lua.PushValue(-1); // Copie - lua.SetGlobal(m_info->name); // Class - - m_info->globalTableRef = lua.CreateReference(); - } - lua.Pop(); // On pop l'Userdata (contenant nos informations) + lua.Pop(); // Pop our ClassInfo, which is now referenced by all our functions } template @@ -237,7 +127,7 @@ namespace Nz { typename LuaImplMethodProxy::template Impl handler(std::forward(defArgs)...); - BindMethod(name, [func, handler] (LuaInstance& lua, T& object) -> int + BindMethod(name, [func, handler] (LuaInstance& lua, T& object, std::size_t /*argumentCount*/) -> int { handler.ProcessArgs(lua); @@ -251,7 +141,7 @@ namespace Nz { typename LuaImplMethodProxy::template Impl handler(std::forward(defArgs)...); - BindMethod(name, [func, handler] (LuaInstance& lua, T& object) -> int + BindMethod(name, [func, handler] (LuaInstance& lua, T& object, std::size_t /*argumentCount*/) -> int { handler.ProcessArgs(lua); @@ -265,7 +155,7 @@ namespace Nz { typename LuaImplMethodProxy::template Impl handler(std::forward(defArgs)...); - BindMethod(name, [func, handler] (LuaInstance& lua, T& object) -> int + BindMethod(name, [func, handler] (LuaInstance& lua, T& object, std::size_t /*argumentCount*/) -> int { handler.ProcessArgs(lua); @@ -279,7 +169,7 @@ namespace Nz { typename LuaImplMethodProxy::template Impl handler(std::forward(defArgs)...); - BindMethod(name, [func, handler] (LuaInstance& lua, T& object) -> int + BindMethod(name, [func, handler] (LuaInstance& lua, T& object, std::size_t /*argumentCount*/) -> int { handler.ProcessArgs(lua); @@ -325,6 +215,176 @@ namespace Nz m_info->staticSetter = setter; } + template + void LuaClass::PushClassInfo(LuaInstance& lua) + { + // Our ClassInfo has to outlive the LuaClass, because we don't want to force the user to keep the LuaClass alive + // To do that, each Registration creates a tiny shared_ptr wrapper whose life is directly managed by Lua. + // This shared_ptr object gets pushed as a up-value for every proxy function set in the metatable. + // This way, there is no way our ClassInfo gets freed before any instance and the global class gets destroyed. + std::shared_ptr* info = static_cast*>(lua.PushUserdata(sizeof(std::shared_ptr))); + PlacementNew(info, m_info); + + // Setup a tiny metatable to let Lua know how to destroy our ClassInfo + lua.PushTable(0, 1); + lua.PushLightUserdata(info); + lua.PushCFunction(InfoDestructor, 1); + lua.SetField("__gc"); + lua.SetMetatable(-2); + } + + template + void LuaClass::SetupConstructor(LuaInstance& lua) + { + lua.PushValue(1); // ClassInfo + lua.PushCFunction(ConstructorProxy, 1); + lua.SetField("__call"); // ClassMeta.__call = ConstructorProxy + } + + template + void LuaClass::SetupDefaultToString(LuaInstance& lua) + { + lua.PushValue(1); // shared_ptr on UserData + lua.PushCFunction(ToStringProxy, 1); + lua.SetField("__tostring"); + } + + template + struct LuaClassImplFinalizerSetupProxy; + + template + struct LuaClassImplFinalizerSetupProxy + { + static void Setup(LuaInstance& lua) + { + lua.PushValue(1); // ClassInfo + lua.PushCFunction(LuaClass::FinalizerProxy, 1); + lua.SetField("__gc"); + } + }; + + template + struct LuaClassImplFinalizerSetupProxy + { + static void Setup(LuaInstance&) + { + } + }; + + template + void LuaClass::SetupFinalizer(LuaInstance& lua) + { + LuaClassImplFinalizerSetupProxy::value>::Setup(lua); + } + + template + void LuaClass::SetupGetter(LuaInstance& lua, LuaCFunction proxy) + { + lua.PushValue(1); // ClassInfo + lua.PushValue(-2); // Metatable + lua.PushCFunction(proxy, 2); + + lua.SetField("__index"); // Getter + } + + template + void LuaClass::SetupGlobalTable(LuaInstance& lua) + { + // Create the global table + lua.PushTable(); // Class = {} + + // Create a metatable which will be used for our global table + lua.PushTable(); // ClassMeta = {} + + if (m_info->constructor) + SetupConstructor(lua); + + if (m_info->staticGetter) + SetupGetter(lua, StaticGetterProxy); + else + { + // Optimize by assigning the metatable instead of a search function + lua.PushValue(-1); // Metatable + lua.SetField("__index"); + } + + if (m_info->staticSetter) + SetupSetter(lua, StaticSetterProxy); + + m_info->staticMethods.reserve(m_staticMethods.size()); + for (auto& pair : m_staticMethods) + { + std::size_t methodIndex = m_info->staticMethods.size(); + m_info->staticMethods.push_back(pair.second); + + SetupMethod(lua, StaticMethodProxy, pair.first, methodIndex); + } + + lua.SetMetatable(-2); // setmetatable(Class, ClassMeta), pops ClassMeta + + lua.PushValue(-1); // As CreateReference() pops the table, push a copy + m_info->globalTableRef = lua.CreateReference(); + + lua.SetGlobal(m_info->name); // _G["Class"] = Class + } + + template + void LuaClass::SetupMetatable(LuaInstance& lua) + { + if (!lua.NewMetatable(m_info->name)) + NazaraWarning("Class \"" + m_info->name + "\" already registred in this instance"); + { + SetupFinalizer(lua); + + if (m_info->getter || !m_info->parentGetters.empty()) + SetupGetter(lua, GetterProxy); + else + { + // Optimize by assigning the metatable instead of a search function + // This is only possible if we have no custom getter nor parent + lua.PushValue(-1); // Metatable + lua.SetField("__index"); + } + + if (m_info->setter) + SetupSetter(lua, SetterProxy); + + // In case a __tostring method is missing, add a default implementation returning the class name + if (m_methods.find("__tostring") == m_methods.end()) + SetupDefaultToString(lua); + + m_info->methods.reserve(m_methods.size()); + for (auto& pair : m_methods) + { + std::size_t methodIndex = m_info->methods.size(); + m_info->methods.push_back(pair.second); + + SetupMethod(lua, MethodProxy, pair.first, methodIndex); + } + } + lua.Pop(); //< Pops the metatable, it won't be collected before it's referenced by the Lua registry. + } + + template + void LuaClass::SetupMethod(LuaInstance& lua, LuaCFunction proxy, const String& name, std::size_t methodIndex) + { + lua.PushValue(1); // ClassInfo + lua.PushInteger(methodIndex); + lua.PushCFunction(proxy, 2); + + lua.SetField(name); // Method name + } + + template + void LuaClass::SetupSetter(LuaInstance& lua, LuaCFunction proxy) + { + lua.PushValue(1); // ClassInfo + lua.PushCFunction(proxy, 1); + + lua.SetField("__newindex"); // Setter + } + + template int LuaClass::ConstructorProxy(lua_State* state) { @@ -389,7 +449,7 @@ namespace Nz { // Query from the metatable lua.GetMetatable(info->name); //< Metatable - lua.PushValue(1); //< Field + lua.PushValue(2); //< Field lua.GetTable(); // Metatable[Field] lua.Remove(-2); // Remove Metatable @@ -416,7 +476,6 @@ namespace Nz std::shared_ptr& info = *static_cast*>(lua.ToUserdata(lua.GetIndexOfUpValue(1))); T* instance = static_cast(lua.CheckUserdata(1, info->name)); - lua.Remove(1); //< Remove the instance from the Lua stack Get(info, lua, instance); return 1; @@ -432,7 +491,7 @@ namespace Nz T* instance = nullptr; if (lua.GetMetatable(1)) { - LuaType type = lua.GetField("__type"); + LuaType type = lua.GetField("__name"); if (type == LuaType_String) { String name = lua.ToString(-1); @@ -441,8 +500,6 @@ namespace Nz instance = it->second(lua); } lua.Pop(2); - - lua.Remove(1); //< Remove the instance from the Lua stack } if (!instance) @@ -451,9 +508,11 @@ namespace Nz return 0; } + std::size_t argCount = lua.GetStackTop() - 1U; + unsigned int index = static_cast(lua.ToInteger(lua.GetIndexOfUpValue(2))); const ClassFunc& method = info->methods[index]; - return method(lua, *instance); + return method(lua, *instance, argCount); } template @@ -465,7 +524,6 @@ namespace Nz const ClassIndexFunc& setter = info->setter; T& instance = *static_cast(lua.CheckUserdata(1, info->name)); - lua.Remove(1); //< Remove the instance from the Lua stack if (!setter(lua, instance)) { diff --git a/include/Nazara/Lua/LuaInstance.hpp b/include/Nazara/Lua/LuaInstance.hpp index c6d7c6385..34a09d11a 100644 --- a/include/Nazara/Lua/LuaInstance.hpp +++ b/include/Nazara/Lua/LuaInstance.hpp @@ -34,10 +34,10 @@ namespace Nz inline LuaInstance(LuaInstance&& instance) noexcept; ~LuaInstance(); - void ArgCheck(bool condition, unsigned int argNum, const char* error); - void ArgCheck(bool condition, unsigned int argNum, const String& error); - int ArgError(unsigned int argNum, const char* error); - int ArgError(unsigned int argNum, const String& error); + void ArgCheck(bool condition, unsigned int argNum, const char* error) const; + void ArgCheck(bool condition, unsigned int argNum, const String& error) const; + int ArgError(unsigned int argNum, const char* error) const; + int ArgError(unsigned int argNum, const String& error) const; bool Call(unsigned int argCount); bool Call(unsigned int argCount, unsigned int resultCount); @@ -123,6 +123,7 @@ namespace Nz void Pop(unsigned int n = 1U) const; template int Push(T arg) const; + template int Push(T firstArg, T2 secondArg, Args... args) const; void PushBoolean(bool value) const; void PushCFunction(LuaCFunction func, unsigned int upvalueCount = 0) const; template void PushField(const char* name, T&& arg, int tableIndex = -2) const; diff --git a/include/Nazara/Lua/LuaInstance.inl b/include/Nazara/Lua/LuaInstance.inl index c5cdc3b6b..25f193675 100644 --- a/include/Nazara/Lua/LuaInstance.inl +++ b/include/Nazara/Lua/LuaInstance.inl @@ -209,6 +209,24 @@ namespace Nz return LuaImplReplyVal(instance, val, TypeTag()); } + template + std::enable_if_t::value && !std::is_enum::value, int> LuaImplReplyVal(const LuaInstance& instance, T val, TypeTag) + { + return LuaImplReplyVal(instance, std::move(val), TypeTag()); + } + + template + std::enable_if_t::value && !std::is_enum::value, int> LuaImplReplyVal(const LuaInstance& instance, T val, TypeTag) + { + return LuaImplReplyVal(instance, std::move(val), TypeTag()); + } + + template + int LuaImplReplyVal(const LuaInstance& instance, T&& val, TypeTag) + { + return LuaImplReplyVal(instance, std::forward(val), TypeTag()); + } + inline int LuaImplReplyVal(const LuaInstance& instance, std::string&& val, TypeTag) { instance.PushString(val.c_str(), val.size()); @@ -266,7 +284,7 @@ namespace Nz template static unsigned int Process(const LuaInstance& instance, unsigned int argIndex, ArgContainer& args, DefArgContainer& defArgs) { - return LuaImplQueryArg(instance, argIndex, &std::get(args), std::get() - N + FirstDefArg - 1>(defArgs), TypeTag()); + return LuaImplQueryArg(instance, argIndex, &std::get(args), std::get() - N - 1>(defArgs), TypeTag()); } }; @@ -375,7 +393,7 @@ namespace Nz void ProcessArgs(const LuaInstance& instance) const { - m_index = 1; + m_index = 2; //< 1 being the instance ProcessArgs<0, Args...>(instance); } @@ -394,6 +412,19 @@ namespace Nz return LuaImplReplyVal(instance, std::move(Apply(object, func, m_args)), TypeTag()); } + template + std::enable_if_t::value, int> Invoke(const LuaInstance& instance, T& object, T&(P::*func)(Args...)) const + { + T& r = Apply(object, func, m_args); + if (&r == &object) + { + instance.PushValue(1); //< Userdata + return 1; + } + else + return LuaImplReplyVal(instance, r, TypeTag()); + } + template std::enable_if_t::value, int> Invoke(const LuaInstance& instance, const T& object, void(P::*func)(Args...) const) const { @@ -409,11 +440,22 @@ namespace Nz return LuaImplReplyVal(instance, std::move(Apply(object, func, m_args)), TypeTag()); } + template + std::enable_if_t::value, int> Invoke(const LuaInstance& instance, const T& object, const T&(P::*func)(Args...) const) const + { + const T& r = Apply(object, func, m_args); + if (&r == &object) + { + instance.PushValue(1); //< Userdata + return 1; + } + else + return LuaImplReplyVal(instance, r, TypeTag()); + } + template std::enable_if_t::type>::value, int> Invoke(const LuaInstance& instance, T& object, void(P::*func)(Args...)) const { - NazaraUnused(instance); - if (!object) { instance.Error("Invalid object"); @@ -436,11 +478,28 @@ namespace Nz return LuaImplReplyVal(instance, std::move(Apply(*object, func, m_args)), TypeTag()); } + template + std::enable_if_t::type>::value, int> Invoke(const LuaInstance& instance, T& object, typename PointedType::type&(P::*func)(Args...) const) const + { + if (!object) + { + instance.Error("Invalid object"); + return 0; + } + + const typename PointedType::type& r = Apply(*object, func, m_args); + if (&r == &*object) + { + instance.PushValue(1); //< Userdata + return 1; + } + else + return LuaImplReplyVal(instance, r, TypeTag()); + } + template std::enable_if_t::type>::value, int> Invoke(const LuaInstance& instance, const T& object, void(P::*func)(Args...) const) const { - NazaraUnused(instance); - if (!object) { instance.Error("Invalid object"); @@ -463,6 +522,25 @@ namespace Nz return LuaImplReplyVal(instance, std::move(Apply(*object, func, m_args)), TypeTag()); } + template + std::enable_if_t::type>::value, int> Invoke(const LuaInstance& instance, const T& object, const typename PointedType::type&(P::*func)(Args...) const) const + { + if (!object) + { + instance.Error("Invalid object"); + return 0; + } + + const typename PointedType::type& r = Apply(*object, func, m_args); + if (&r == &*object) + { + instance.PushValue(1); //< Userdata + return 1; + } + else + return LuaImplReplyVal(instance, r, TypeTag()); + } + private: using ArgContainer = std::tuple>...>; using DefArgContainer = std::tuple>...>; @@ -606,6 +684,16 @@ namespace Nz return LuaImplReplyVal(*this, std::move(arg), TypeTag()); } + template + int LuaInstance::Push(T firstArg, T2 secondArg, Args... args) const + { + int valCount = 0; + valCount += Push(std::move(firstArg)); + valCount += Push(secondArg, std::forward(args)...); + + return valCount; + } + template void LuaInstance::PushField(const char* name, T&& arg, int tableIndex) const { @@ -648,7 +736,7 @@ namespace Nz template void LuaInstance::PushInstance(const char* tname, const T& instance) const { - T* userdata = static_cast(PushUserdata(sizeof(T*))); + T* userdata = static_cast(PushUserdata(sizeof(T))); PlacementNew(userdata, instance); SetMetatable(tname); @@ -657,7 +745,7 @@ namespace Nz template void LuaInstance::PushInstance(const char* tname, T&& instance) const { - T* userdata = static_cast(PushUserdata(sizeof(T*))); + T* userdata = static_cast(PushUserdata(sizeof(T))); PlacementNew(userdata, std::move(instance)); SetMetatable(tname); @@ -666,7 +754,7 @@ namespace Nz template void LuaInstance::PushInstance(const char* tname, Args&&... args) const { - T* userdata = static_cast(PushUserdata(sizeof(T*))); + T* userdata = static_cast(PushUserdata(sizeof(T))); PlacementNew(userdata, std::forward(args)...); SetMetatable(tname); diff --git a/include/Nazara/Math.hpp b/include/Nazara/Math.hpp index fd0239a61..9ee9a2351 100644 --- a/include/Nazara/Math.hpp +++ b/include/Nazara/Math.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 24 Jun 2015 at 13:55:50 +// This file was automatically generated /* Nazara Engine - Mathematics module diff --git a/include/Nazara/Math/Matrix4.inl b/include/Nazara/Math/Matrix4.inl index 4cf2eaa6e..021cb6378 100644 --- a/include/Nazara/Math/Matrix4.inl +++ b/include/Nazara/Math/Matrix4.inl @@ -242,7 +242,7 @@ namespace Nz } #endif - T* ptr = (&m11) + column*4; + const T* ptr = (&m11) + column*4; return Vector4(ptr); } @@ -636,7 +636,7 @@ namespace Nz } #endif - T* ptr = &m11; + const T* ptr = &m11; return Vector4(ptr[row], ptr[row+4], ptr[row+8], ptr[row+12]); } diff --git a/include/Nazara/Math/Quaternion.inl b/include/Nazara/Math/Quaternion.inl index bc672cd81..5c7df28cd 100644 --- a/include/Nazara/Math/Quaternion.inl +++ b/include/Nazara/Math/Quaternion.inl @@ -553,9 +553,9 @@ namespace Nz template Vector3 Quaternion::operator*(const Vector3& vec) const { - Vector3f quatVec(x, y, z); - Vector3f uv = quatVec.CrossProduct(vec); - Vector3f uuv = quatVec.CrossProduct(uv); + Vector3 quatVec(x, y, z); + Vector3 uv = quatVec.CrossProduct(vec); + Vector3 uuv = quatVec.CrossProduct(uv); uv *= F(2.0) * w; uuv *= F(2.0); diff --git a/include/Nazara/Math/Vector2.hpp b/include/Nazara/Math/Vector2.hpp index e0ac1d68d..49890b06f 100644 --- a/include/Nazara/Math/Vector2.hpp +++ b/include/Nazara/Math/Vector2.hpp @@ -8,6 +8,7 @@ #define NAZARA_VECTOR2_HPP #include +#include namespace Nz { @@ -119,6 +120,11 @@ template std::ostream& operator<<(std::ostream& out, const Nz::Vecto template Nz::Vector2 operator*(T scale, const Nz::Vector2& vec); template Nz::Vector2 operator/(T scale, const Nz::Vector2& vec); +namespace std +{ + template struct hash>; +} + #include #endif // NAZARA_VECTOR2_HPP diff --git a/include/Nazara/Math/Vector2.inl b/include/Nazara/Math/Vector2.inl index 80e588ba4..8ca023843 100644 --- a/include/Nazara/Math/Vector2.inl +++ b/include/Nazara/Math/Vector2.inl @@ -1057,6 +1057,29 @@ Nz::Vector2 operator/(T scale, const Nz::Vector2& vec) return Nz::Vector2(scale / vec.x, scale / vec.y); } +namespace std +{ + template + struct hash> + { + /*! + * \brief Specialisation of std to hash + * \return Result of the hash + * + * \param v Vector2 to hash + */ + std::size_t operator()(const Nz::Vector2& v) const + { + std::size_t seed {}; + + Nz::HashCombine(seed, v.x); + Nz::HashCombine(seed, v.y); + + return seed; + } + }; +} + #undef F #include diff --git a/include/Nazara/Math/Vector3.hpp b/include/Nazara/Math/Vector3.hpp index 4e6da14ec..27681683f 100644 --- a/include/Nazara/Math/Vector3.hpp +++ b/include/Nazara/Math/Vector3.hpp @@ -8,6 +8,7 @@ #define NAZARA_VECTOR3_HPP #include +#include namespace Nz { @@ -141,6 +142,11 @@ template std::ostream& operator<<(std::ostream& out, const Nz::Vecto template Nz::Vector3 operator*(T scale, const Nz::Vector3& vec); template Nz::Vector3 operator/(T scale, const Nz::Vector3& vec); +namespace std +{ + template struct hash>; +} + #include #endif // NAZARA_VECTOR3_HPP diff --git a/include/Nazara/Math/Vector3.inl b/include/Nazara/Math/Vector3.inl index c5a0155c7..555286024 100644 --- a/include/Nazara/Math/Vector3.inl +++ b/include/Nazara/Math/Vector3.inl @@ -1347,6 +1347,31 @@ Nz::Vector3 operator/(T scale, const Nz::Vector3& vec) return Nz::Vector3(scale / vec.x, scale / vec.y, scale / vec.z); } +namespace std +{ + template + struct hash> + { + /*! + * \brief Specialisation of std to hash + * \return Result of the hash + * + * \param v Vector3 to hash + */ + + std::size_t operator()(const Nz::Vector3& v) const + { + std::size_t seed {}; + + Nz::HashCombine(seed, v.x); + Nz::HashCombine(seed, v.y); + Nz::HashCombine(seed, v.z); + + return seed; + } + }; +} + #undef F #include diff --git a/include/Nazara/Math/Vector4.hpp b/include/Nazara/Math/Vector4.hpp index 0f8e907fc..d878c2ea5 100644 --- a/include/Nazara/Math/Vector4.hpp +++ b/include/Nazara/Math/Vector4.hpp @@ -8,6 +8,7 @@ #define NAZARA_VECTOR4_HPP #include +#include namespace Nz { @@ -117,6 +118,11 @@ template std::ostream& operator<<(std::ostream& out, const Nz::Vecto template Nz::Vector4 operator*(T scale, const Nz::Vector4& vec); template Nz::Vector4 operator/(T scale, const Nz::Vector4& vec); +namespace std +{ + template struct hash>; +} + #include #endif // NAZARA_VECTOR4_HPP diff --git a/include/Nazara/Math/Vector4.inl b/include/Nazara/Math/Vector4.inl index 73a9a0802..190d31b99 100644 --- a/include/Nazara/Math/Vector4.inl +++ b/include/Nazara/Math/Vector4.inl @@ -1120,6 +1120,31 @@ Nz::Vector4 operator/(T scale, const Nz::Vector4& vec) return Nz::Vector4(scale / vec.x, scale / vec.y, scale / vec.z, scale / vec.w); } +namespace std +{ + template + struct hash> + { + /*! + * \brief Specialisation of std to hash + * \return Result of the hash + * + * \param v Vector4 to hash + */ + std::size_t operator()(const Nz::Vector4& v) const + { + std::size_t seed {}; + + Nz::HashCombine(seed, v.x); + Nz::HashCombine(seed, v.y); + Nz::HashCombine(seed, v.z); + Nz::HashCombine(seed, v.w); + + return seed; + } + }; +} + #undef F #include diff --git a/include/Nazara/Network.hpp b/include/Nazara/Network.hpp index 72565a17f..41b7fce71 100644 --- a/include/Nazara/Network.hpp +++ b/include/Nazara/Network.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 03 Feb 2016 at 00:06:56 +// This file was automatically generated /* Nazara Engine - Network module @@ -36,7 +36,10 @@ #include #include #include +#include +#include #include +#include #include #include #include diff --git a/include/Nazara/Network/IpAddress.inl b/include/Nazara/Network/IpAddress.inl index 2fc9ac2bd..1eaef4341 100644 --- a/include/Nazara/Network/IpAddress.inl +++ b/include/Nazara/Network/IpAddress.inl @@ -56,7 +56,7 @@ namespace Nz */ inline IpAddress::IpAddress(const UInt8& a, const UInt8& b, const UInt8& c, const UInt8& d, UInt16 port) : - IpAddress(IPv4{a, b, c, d}, port) + IpAddress(IPv4{{a, b, c, d}}, port) { } @@ -68,7 +68,7 @@ namespace Nz */ inline IpAddress::IpAddress(const UInt16& a, const UInt16& b, const UInt16& c, const UInt16& d, const UInt16& e, const UInt16& f, const UInt16& g, const UInt16& h, UInt16 port) : - IpAddress(IPv6{a, b, c, d, e, f, g, h}, port) + IpAddress(IPv6{{a, b, c, d, e, f, g, h}}, port) { } diff --git a/include/Nazara/Network/TcpClient.hpp b/include/Nazara/Network/TcpClient.hpp index fda4671f9..0fcedcf39 100644 --- a/include/Nazara/Network/TcpClient.hpp +++ b/include/Nazara/Network/TcpClient.hpp @@ -79,8 +79,8 @@ namespace Nz PendingPacket m_pendingPacket; UInt64 m_keepAliveInterval; UInt64 m_keepAliveTime; - bool m_isLowDelayEnabled; bool m_isKeepAliveEnabled; + bool m_isLowDelayEnabled; }; } diff --git a/include/Nazara/Noise.hpp b/include/Nazara/Noise.hpp index e1d14460e..f8ecfb82e 100644 --- a/include/Nazara/Noise.hpp +++ b/include/Nazara/Noise.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 12 Jul 2016 at 17:44:43 +// This file was automatically generated /* Nazara Engine - Noise module diff --git a/include/Nazara/Noise/HybridMultiFractal.hpp b/include/Nazara/Noise/HybridMultiFractal.hpp index c73dafc73..cbb80ef65 100644 --- a/include/Nazara/Noise/HybridMultiFractal.hpp +++ b/include/Nazara/Noise/HybridMultiFractal.hpp @@ -25,11 +25,6 @@ namespace Nz private: const NoiseBase& m_source; - float m_value; - float m_remainder; - float m_offset; - float m_weight; - float m_signal; }; } diff --git a/include/Nazara/Physics/Enums.hpp b/include/Nazara/Physics/Enums.hpp deleted file mode 100644 index 1951d3eda..000000000 --- a/include/Nazara/Physics/Enums.hpp +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Physics module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_ENUMS_PHYSICS_HPP -#define NAZARA_ENUMS_PHYSICS_HPP - -enum GeomType -{ - GeomType_Box, - GeomType_Capsule, - GeomType_Cone, - GeomType_Compound, - GeomType_ConvexHull, - GeomType_Cylinder, - GeomType_Heightfield, - GeomType_Null, - GeomType_Scene, - GeomType_Sphere, - GeomType_Tree, - - GeomType_Max = GeomType_Tree -}; - -#endif // NAZARA_ENUMS_PHYSICS_HPP diff --git a/include/Nazara/Physics/Geom.hpp b/include/Nazara/Physics/Geom.hpp deleted file mode 100644 index e228c3d07..000000000 --- a/include/Nazara/Physics/Geom.hpp +++ /dev/null @@ -1,273 +0,0 @@ -// Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Physics module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_GEOM_HPP -#define NAZARA_GEOM_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -class NewtonCollision; - -namespace Nz -{ - ///TODO: CollisionModifier - ///TODO: HeightfieldGeom - ///TODO: PlaneGeom ? - ///TODO: SceneGeom - ///TODO: TreeGeom - - class PhysGeom; - class PhysWorld; - - using PhysGeomConstRef = ObjectRef; - using PhysGeomLibrary = ObjectLibrary; - using PhysGeomRef = ObjectRef; - - class NAZARA_PHYSICS_API PhysGeom : public RefCounted - { - friend PhysGeomLibrary; - friend class Physics; - - public: - PhysGeom() = default; - PhysGeom(const PhysGeom&) = delete; - PhysGeom(PhysGeom&&) = delete; - virtual ~PhysGeom(); - - Boxf ComputeAABB(const Vector3f& translation, const Quaternionf& rotation, const Vector3f& scale) const; - virtual Boxf ComputeAABB(const Matrix4f& offsetMatrix = Matrix4f::Identity(), const Vector3f& scale = Vector3f::Unit()) const; - virtual void ComputeInertialMatrix(Vector3f* inertia, Vector3f* center) const; - virtual float ComputeVolume() const; - - NewtonCollision* GetHandle(PhysWorld* world) const; - virtual GeomType GetType() const = 0; - - PhysGeom& operator=(const PhysGeom&) = delete; - PhysGeom& operator=(PhysGeom&&) = delete; - - static PhysGeomRef Build(const PrimitiveList& list); - - // Signals: - NazaraSignal(OnPhysGeomRelease, const PhysGeom* /*physGeom*/); - - protected: - virtual NewtonCollision* CreateHandle(PhysWorld* world) const = 0; - - static bool Initialize(); - static void Uninitialize(); - - mutable std::unordered_map m_handles; - - static PhysGeomLibrary::LibraryMap s_library; - }; - - class BoxGeom; - - using BoxGeomConstRef = ObjectRef; - using BoxGeomRef = ObjectRef; - - class NAZARA_PHYSICS_API BoxGeom : public PhysGeom - { - public: - BoxGeom(const Vector3f& lengths, const Matrix4f& transformMatrix = Matrix4f::Identity()); - BoxGeom(const Vector3f& lengths, const Vector3f& translation, const Quaternionf& rotation = Quaternionf::Identity()); - - Boxf ComputeAABB(const Matrix4f& offsetMatrix = Matrix4f::Identity(), const Vector3f& scale = Vector3f::Unit()) const override; - float ComputeVolume() const override; - - Vector3f GetLengths() const; - GeomType GetType() const override; - - template static BoxGeomRef New(Args&&... args); - - private: - NewtonCollision* CreateHandle(PhysWorld* world) const override; - - Matrix4f m_matrix; - Vector3f m_lengths; - }; - - class CapsuleGeom; - - using CapsuleGeomConstRef = ObjectRef; - using CapsuleGeomRef = ObjectRef; - - class NAZARA_PHYSICS_API CapsuleGeom : public PhysGeom - { - public: - CapsuleGeom(float length, float radius, const Matrix4f& transformMatrix = Matrix4f::Identity()); - CapsuleGeom(float length, float radius, const Vector3f& translation, const Quaternionf& rotation = Quaternionf::Identity()); - - float GetLength() const; - float GetRadius() const; - GeomType GetType() const override; - - template static CapsuleGeomRef New(Args&&... args); - - private: - NewtonCollision* CreateHandle(PhysWorld* world) const override; - - Matrix4f m_matrix; - float m_length; - float m_radius; - }; - - class CompoundGeom; - - using CompoundGeomConstRef = ObjectRef; - using CompoundGeomRef = ObjectRef; - - class NAZARA_PHYSICS_API CompoundGeom : public PhysGeom - { - public: - CompoundGeom(PhysGeom** geoms, std::size_t geomCount); - - const std::vector& GetGeoms() const; - GeomType GetType() const override; - - template static CompoundGeomRef New(Args&&... args); - - private: - NewtonCollision* CreateHandle(PhysWorld* world) const override; - - std::vector m_geoms; - }; - - class ConeGeom; - - using ConeGeomConstRef = ObjectRef; - using ConeGeomRef = ObjectRef; - - class NAZARA_PHYSICS_API ConeGeom : public PhysGeom - { - public: - ConeGeom(float length, float radius, const Matrix4f& transformMatrix = Matrix4f::Identity()); - ConeGeom(float length, float radius, const Vector3f& translation, const Quaternionf& rotation = Quaternionf::Identity()); - - float GetLength() const; - float GetRadius() const; - GeomType GetType() const override; - - template static ConeGeomRef New(Args&&... args); - - private: - NewtonCollision* CreateHandle(PhysWorld* world) const override; - - Matrix4f m_matrix; - float m_length; - float m_radius; - }; - - class ConvexHullGeom; - - using ConvexHullGeomConstRef = ObjectRef; - using ConvexHullGeomRef = ObjectRef; - - class NAZARA_PHYSICS_API ConvexHullGeom : public PhysGeom - { - public: - ConvexHullGeom(const void* vertices, unsigned int vertexCount, unsigned int stride = sizeof(Vector3f), float tolerance = 0.002f, const Matrix4f& transformMatrix = Matrix4f::Identity()); - ConvexHullGeom(const void* vertices, unsigned int vertexCount, unsigned int stride, float tolerance, const Vector3f& translation, const Quaternionf& rotation = Quaternionf::Identity()); - - GeomType GetType() const override; - - template static ConvexHullGeomRef New(Args&&... args); - - private: - NewtonCollision* CreateHandle(PhysWorld* world) const override; - - std::vector m_vertices; - Matrix4f m_matrix; - float m_tolerance; - unsigned int m_vertexStride; - }; - - class CylinderGeom; - - using CylinderGeomConstRef = ObjectRef; - using CylinderGeomRef = ObjectRef; - - class NAZARA_PHYSICS_API CylinderGeom : public PhysGeom - { - public: - CylinderGeom(float length, float radius, const Matrix4f& transformMatrix = Matrix4f::Identity()); - CylinderGeom(float length, float radius, const Vector3f& translation, const Quaternionf& rotation = Quaternionf::Identity()); - - float GetLength() const; - float GetRadius() const; - GeomType GetType() const override; - - template static CylinderGeomRef New(Args&&... args); - - private: - NewtonCollision* CreateHandle(PhysWorld* world) const override; - - Matrix4f m_matrix; - float m_length; - float m_radius; - }; - - class NullGeom; - - using NullGeomConstRef = ObjectRef; - using NullGeomRef = ObjectRef; - - class NAZARA_PHYSICS_API NullGeom : public PhysGeom - { - public: - NullGeom(); - - void ComputeInertialMatrix(Vector3f* inertia, Vector3f* center) const override; - - GeomType GetType() const override; - - template static NullGeomRef New(Args&&... args); - - private: - NewtonCollision* CreateHandle(PhysWorld* world) const override; - }; - - class SphereGeom; - - using SphereGeomConstRef = ObjectRef; - using SphereGeomRef = ObjectRef; - - class NAZARA_PHYSICS_API SphereGeom : public PhysGeom - { - public: - SphereGeom(float radius, const Matrix4f& transformMatrix = Matrix4f::Identity()); - SphereGeom(float radius, const Vector3f& translation, const Quaternionf& rotation = Quaternionf::Identity()); - - Boxf ComputeAABB(const Matrix4f& offsetMatrix = Matrix4f::Identity(), const Vector3f& scale = Vector3f::Unit()) const override; - float ComputeVolume() const override; - - float GetRadius() const; - GeomType GetType() const override; - - template static SphereGeomRef New(Args&&... args); - - private: - NewtonCollision* CreateHandle(PhysWorld* world) const override; - - Vector3f m_position; - float m_radius; - }; -} - -#include - -#endif // NAZARA_PHYSWORLD_HPP diff --git a/include/Nazara/Physics/Geom.inl b/include/Nazara/Physics/Geom.inl deleted file mode 100644 index 9699cac96..000000000 --- a/include/Nazara/Physics/Geom.inl +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Physics module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz -{ - template - BoxGeomRef BoxGeom::New(Args&&... args) - { - std::unique_ptr object(new BoxGeom(std::forward(args)...)); - object->SetPersistent(false); - - return object.release(); - } - - template - CapsuleGeomRef CapsuleGeom::New(Args&&... args) - { - std::unique_ptr object(new CapsuleGeom(std::forward(args)...)); - object->SetPersistent(false); - - return object.release(); - } - - template - CompoundGeomRef CompoundGeom::New(Args&&... args) - { - std::unique_ptr object(new CompoundGeom(std::forward(args)...)); - object->SetPersistent(false); - - return object.release(); - } - - template - ConeGeomRef ConeGeom::New(Args&&... args) - { - std::unique_ptr object(new ConeGeom(std::forward(args)...)); - object->SetPersistent(false); - - return object.release(); - } - - template - ConvexHullGeomRef ConvexHullGeom::New(Args&&... args) - { - std::unique_ptr object(new ConvexHullGeom(std::forward(args)...)); - object->SetPersistent(false); - - return object.release(); - } - - template - CylinderGeomRef CylinderGeom::New(Args&&... args) - { - std::unique_ptr object(new CylinderGeom(std::forward(args)...)); - object->SetPersistent(false); - - return object.release(); - } - - template - NullGeomRef NullGeom::New(Args&&... args) - { - std::unique_ptr object(new NullGeom(std::forward(args)...)); - object->SetPersistent(false); - - return object.release(); - } - - template - SphereGeomRef SphereGeom::New(Args&&... args) - { - std::unique_ptr object(new SphereGeom(std::forward(args)...)); - object->SetPersistent(false); - - return object.release(); - } -} - -#include diff --git a/include/Nazara/Physics.hpp b/include/Nazara/Physics2D.hpp similarity index 72% rename from include/Nazara/Physics.hpp rename to include/Nazara/Physics2D.hpp index a4fcfc768..2c908ca79 100644 --- a/include/Nazara/Physics.hpp +++ b/include/Nazara/Physics2D.hpp @@ -1,7 +1,7 @@ -// This file was automatically generated on 24 Jun 2015 at 13:55:50 +// This file was automatically generated /* - Nazara Engine - Physics module + Nazara Engine - Physics 2D module Copyright (C) 2015 Jérôme "Lynix" Leclercq (Lynix680@gmail.com) @@ -26,14 +26,14 @@ #pragma once -#ifndef NAZARA_GLOBAL_PHYSICS_HPP -#define NAZARA_GLOBAL_PHYSICS_HPP +#ifndef NAZARA_GLOBAL_PHYSICS2D_HPP +#define NAZARA_GLOBAL_PHYSICS2D_HPP -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include -#endif // NAZARA_GLOBAL_PHYSICS_HPP +#endif // NAZARA_GLOBAL_PHYSICS2D_HPP diff --git a/include/Nazara/Physics2D/Collider2D.hpp b/include/Nazara/Physics2D/Collider2D.hpp new file mode 100644 index 000000000..f8cd7d6af --- /dev/null +++ b/include/Nazara/Physics2D/Collider2D.hpp @@ -0,0 +1,132 @@ +// Copyright (C) 2015 Jérôme Leclercq +// This file is part of the "Nazara Engine - Physics 2D module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#pragma once + +#ifndef NAZARA_COLLIDER2D_HPP +#define NAZARA_COLLIDER2D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct cpShape; +struct cpSpace; + +namespace Nz +{ + class Collider2D; + class RigidBody2D; + + using Collider2DConstRef = ObjectRef; + using Collider2DLibrary = ObjectLibrary; + using Collider2DRef = ObjectRef; + + class NAZARA_PHYSICS2D_API Collider2D : public RefCounted + { + friend Collider2DLibrary; + friend RigidBody2D; + + public: + Collider2D() = default; + Collider2D(const Collider2D&) = delete; + Collider2D(Collider2D&&) = delete; + virtual ~Collider2D(); + + virtual float ComputeInertialMatrix(float mass) const = 0; + + virtual ColliderType2D GetType() const = 0; + + Collider2D& operator=(const Collider2D&) = delete; + Collider2D& operator=(Collider2D&&) = delete; + + // Signals: + NazaraSignal(OnColliderRelease, const Collider2D* /*collider*/); + + protected: + virtual std::vector CreateShapes(RigidBody2D* body) const = 0; + + static Collider2DLibrary::LibraryMap s_library; + }; + + class BoxCollider2D; + + using BoxCollider2DConstRef = ObjectRef; + using BoxCollider2DRef = ObjectRef; + + class NAZARA_PHYSICS2D_API BoxCollider2D : public Collider2D + { + public: + BoxCollider2D(const Vector2f& size, float radius = 0.f); + BoxCollider2D(const Rectf& rect, float radius = 0.f); + + float ComputeInertialMatrix(float mass) const override; + + inline const Rectf& GetRect() const; + inline Vector2f GetSize() const; + ColliderType2D GetType() const override; + + template static BoxCollider2DRef New(Args&&... args); + + private: + std::vector CreateShapes(RigidBody2D* body) const override; + + Rectf m_rect; + float m_radius; + }; + + class CircleCollider2D; + + using CircleCollider2DConstRef = ObjectRef; + using CircleCollider2DRef = ObjectRef; + + class NAZARA_PHYSICS2D_API CircleCollider2D : public Collider2D + { + public: + CircleCollider2D(float radius, const Vector2f& offset = Vector2f::Zero()); + + float ComputeInertialMatrix(float mass) const override; + + inline float GetRadius() const; + ColliderType2D GetType() const override; + + template static CircleCollider2DRef New(Args&&... args); + + private: + std::vector CreateShapes(RigidBody2D* body) const override; + + Vector2f m_offset; + float m_radius; + }; + + class NullCollider2D; + + using NullCollider2DConstRef = ObjectRef; + using NullCollider2DRef = ObjectRef; + + class NAZARA_PHYSICS2D_API NullCollider2D : public Collider2D + { + public: + NullCollider2D() = default; + + float ComputeInertialMatrix(float mass) const override; + + ColliderType2D GetType() const override; + + template static NullCollider2DRef New(Args&&... args); + + private: + std::vector CreateShapes(RigidBody2D* body) const override; + }; +} + +#include + +#endif // NAZARA_COLLIDER2D_HPP diff --git a/include/Nazara/Physics2D/Collider2D.inl b/include/Nazara/Physics2D/Collider2D.inl new file mode 100644 index 000000000..2cd44d326 --- /dev/null +++ b/include/Nazara/Physics2D/Collider2D.inl @@ -0,0 +1,54 @@ +// Copyright (C) 2015 Jérôme Leclercq +// This file is part of the "Nazara Engine - Physics 2D module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#include +#include + +namespace Nz +{ + inline const Rectf& BoxCollider2D::GetRect() const + { + return m_rect; + } + + inline Vector2f BoxCollider2D::GetSize() const + { + return m_rect.GetLengths(); + } + + template + BoxCollider2DRef BoxCollider2D::New(Args&&... args) + { + std::unique_ptr object(new BoxCollider2D(std::forward(args)...)); + object->SetPersistent(false); + + return object.release(); + } + + inline float CircleCollider2D::GetRadius() const + { + return m_radius; + } + + template + CircleCollider2DRef CircleCollider2D::New(Args&&... args) + { + std::unique_ptr object(new CircleCollider2D(std::forward(args)...)); + object->SetPersistent(false); + + return object.release(); + } + + template + NullCollider2DRef NullCollider2D::New(Args&&... args) + { + std::unique_ptr object(new NullCollider2D(std::forward(args)...)); + object->SetPersistent(false); + + return object.release(); + } + +} + +#include diff --git a/include/Nazara/Physics/Config.hpp b/include/Nazara/Physics2D/Config.hpp similarity index 79% rename from include/Nazara/Physics/Config.hpp rename to include/Nazara/Physics2D/Config.hpp index b57e39378..e356e1009 100644 --- a/include/Nazara/Physics/Config.hpp +++ b/include/Nazara/Physics2D/Config.hpp @@ -1,5 +1,5 @@ /* - Nazara Engine - Physics module + Nazara Engine - Physics 2D module Copyright (C) 2015 Jérôme "Lynix" Leclercq (Lynix680@gmail.com) @@ -24,28 +24,28 @@ #pragma once -#ifndef NAZARA_CONFIG_PHYSICS_HPP -#define NAZARA_CONFIG_PHYSICS_HPP +#ifndef NAZARA_CONFIG_PHYSICS2D_HPP +#define NAZARA_CONFIG_PHYSICS2D_HPP /// Chaque modification d'un paramètre du module nécessite une recompilation de celui-ci // Utilise un manager de mémoire pour gérer les allocations dynamiques (détecte les leaks au prix d'allocations/libérations dynamiques plus lentes) -#define NAZARA_PHYSICS_MANAGE_MEMORY 0 +#define NAZARA_PHYSICS2D_MANAGE_MEMORY 0 // Active les tests de sécurité basés sur le code (Conseillé pour le développement) -#define NAZARA_PHYSICS_SAFE 1 +#define NAZARA_PHYSICS2D_SAFE 1 /// Vérification des valeurs et types de certaines constantes -#include +#include #if defined(NAZARA_STATIC) - #define NAZARA_PHYSICS_API + #define NAZARA_PHYSICS2D_API #else - #ifdef NAZARA_PHYSICS_BUILD - #define NAZARA_PHYSICS_API NAZARA_EXPORT + #ifdef NAZARA_PHYSICS2D_BUILD + #define NAZARA_PHYSICS2D_API NAZARA_EXPORT #else - #define NAZARA_PHYSICS_API NAZARA_IMPORT + #define NAZARA_PHYSICS2D_API NAZARA_IMPORT #endif #endif -#endif // NAZARA_CONFIG_PHYSICS_HPP +#endif // NAZARA_CONFIG_PHYSICS3D_HPP diff --git a/include/Nazara/Physics/ConfigCheck.hpp b/include/Nazara/Physics2D/ConfigCheck.hpp similarity index 82% rename from include/Nazara/Physics/ConfigCheck.hpp rename to include/Nazara/Physics2D/ConfigCheck.hpp index 5721e2660..4689d6e68 100644 --- a/include/Nazara/Physics/ConfigCheck.hpp +++ b/include/Nazara/Physics2D/ConfigCheck.hpp @@ -1,5 +1,5 @@ // Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Physics module" +// This file is part of the "Nazara Engine - Physics 2D module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once @@ -12,7 +12,7 @@ // On force la valeur de MANAGE_MEMORY en mode debug #if defined(NAZARA_DEBUG) && !NAZARA_PHYSICS_MANAGE_MEMORY #undef NAZARA_PHYSICS_MANAGE_MEMORY - #define NAZARA_PHYSICS_MANAGE_MEMORY 0 + #define NAZARA_PHYSICS3D_MANAGE_MEMORY 0 #endif #endif // NAZARA_CONFIG_CHECK_PHYSICS_HPP diff --git a/include/Nazara/Physics/Debug.hpp b/include/Nazara/Physics2D/Debug.hpp similarity index 66% rename from include/Nazara/Physics/Debug.hpp rename to include/Nazara/Physics2D/Debug.hpp index 3f3d8fe41..f9cebc624 100644 --- a/include/Nazara/Physics/Debug.hpp +++ b/include/Nazara/Physics2D/Debug.hpp @@ -1,8 +1,8 @@ // Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Physics module" +// This file is part of the "Nazara Engine - Physics 2D module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include +#include #if NAZARA_PHYSICS_MANAGE_MEMORY #include #endif diff --git a/include/Nazara/Physics/DebugOff.hpp b/include/Nazara/Physics2D/DebugOff.hpp similarity index 80% rename from include/Nazara/Physics/DebugOff.hpp rename to include/Nazara/Physics2D/DebugOff.hpp index 4ea033e46..dd95ffe34 100644 --- a/include/Nazara/Physics/DebugOff.hpp +++ b/include/Nazara/Physics2D/DebugOff.hpp @@ -1,5 +1,5 @@ // Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Physics module" +// This file is part of the "Nazara Engine - Physics 2D module" // For conditions of distribution and use, see copyright notice in Config.hpp // On suppose que Debug.hpp a déjà été inclus, tout comme Config.hpp diff --git a/include/Nazara/Physics2D/Enums.hpp b/include/Nazara/Physics2D/Enums.hpp new file mode 100644 index 000000000..529af6f6c --- /dev/null +++ b/include/Nazara/Physics2D/Enums.hpp @@ -0,0 +1,24 @@ +// Copyright (C) 2015 Jérôme Leclercq +// This file is part of the "Nazara Engine - Physics 2D module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#pragma once + +#ifndef NAZARA_ENUMS_PHYSICS2D_HPP +#define NAZARA_ENUMS_PHYSICS2D_HPP + +namespace Nz +{ + enum ColliderType2D + { + ColliderType2D_Box, + ColliderType2D_Convex, + ColliderType2D_Circle, + ColliderType2D_Null, + ColliderType2D_Segment, + + ColliderType2D_Max = ColliderType2D_Segment + }; +} + +#endif // NAZARA_ENUMS_PHYSICS2D_HPP diff --git a/include/Nazara/Physics2D/PhysWorld2D.hpp b/include/Nazara/Physics2D/PhysWorld2D.hpp new file mode 100644 index 000000000..e194f89d2 --- /dev/null +++ b/include/Nazara/Physics2D/PhysWorld2D.hpp @@ -0,0 +1,46 @@ +// Copyright (C) 2015 Jérôme Leclercq +// This file is part of the "Nazara Engine - Physics 2D module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#pragma once + +#ifndef NAZARA_PHYSWORLD2D_HPP +#define NAZARA_PHYSWORLD2D_HPP + +#include +#include +#include + +struct cpSpace; + +namespace Nz +{ + class NAZARA_PHYSICS2D_API PhysWorld2D + { + public: + PhysWorld2D(); + PhysWorld2D(const PhysWorld2D&) = delete; + PhysWorld2D(PhysWorld2D&&) = delete; ///TODO + ~PhysWorld2D(); + + Vector2f GetGravity() const; + cpSpace* GetHandle() const; + float GetStepSize() const; + + void SetGravity(const Vector2f& gravity); + void SetSolverModel(unsigned int model); + void SetStepSize(float stepSize); + + void Step(float timestep); + + PhysWorld2D& operator=(const PhysWorld2D&) = delete; + PhysWorld2D& operator=(PhysWorld2D&&) = delete; ///TODO + + private: + cpSpace* m_handle; + float m_stepSize; + float m_timestepAccumulator; + }; +} + +#endif // NAZARA_PHYSWORLD2D_HPP diff --git a/include/Nazara/Physics2D/Physics2D.hpp b/include/Nazara/Physics2D/Physics2D.hpp new file mode 100644 index 000000000..27fdf3128 --- /dev/null +++ b/include/Nazara/Physics2D/Physics2D.hpp @@ -0,0 +1,33 @@ +// Copyright (C) 2015 Jérôme Leclercq +// This file is part of the "Nazara Engine - Physics 2D module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#pragma once + +#ifndef NAZARA_PHYSICS2D_HPP +#define NAZARA_PHYSICS2D_HPP + +#include +#include +#include + +namespace Nz +{ + class NAZARA_PHYSICS2D_API Physics2D + { + public: + Physics2D() = delete; + ~Physics2D() = delete; + + static bool Initialize(); + + static bool IsInitialized(); + + static void Uninitialize(); + + private: + static unsigned int s_moduleReferenceCounter; + }; +} + +#endif // NAZARA_PHYSICS2D_HPP diff --git a/include/Nazara/Physics2D/RigidBody2D.hpp b/include/Nazara/Physics2D/RigidBody2D.hpp new file mode 100644 index 000000000..7d521fbe6 --- /dev/null +++ b/include/Nazara/Physics2D/RigidBody2D.hpp @@ -0,0 +1,74 @@ +// Copyright (C) 2015 Jérôme Leclercq +// This file is part of the "Nazara Engine - Physics 2D module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#pragma once + +#ifndef NAZARA_RIGIDBODY2D_HPP +#define NAZARA_RIGIDBODY2D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include + +struct cpBody; + +namespace Nz +{ + class PhysWorld2D; + + class NAZARA_PHYSICS2D_API RigidBody2D + { + public: + RigidBody2D(PhysWorld2D* world, float mass); + RigidBody2D(PhysWorld2D* world, float mass, Collider2DRef geom); + RigidBody2D(const RigidBody2D& object); + RigidBody2D(RigidBody2D&& object); + ~RigidBody2D(); + + void AddForce(const Vector2f& force, CoordSys coordSys = CoordSys_Global); + void AddForce(const Vector2f& force, const Vector2f& point, CoordSys coordSys = CoordSys_Global); + void AddTorque(float torque); + + Rectf GetAABB() const; + float GetAngularVelocity() const; + Vector2f GetCenterOfGravity(CoordSys coordSys = CoordSys_Local) const; + const Collider2DRef& GetGeom() const; + cpBody* GetHandle() const; + float GetMass() const; + Vector2f GetPosition() const; + float GetRotation() const; + Vector2f GetVelocity() const; + + bool IsMoveable() const; + bool IsSleeping() const; + + void SetAngularVelocity(float angularVelocity); + void SetMass(float mass); + void SetMassCenter(const Vector2f& center); + void SetPosition(const Vector2f& position); + void SetRotation(float rotation); + void SetVelocity(const Vector2f& velocity); + + RigidBody2D& operator=(const RigidBody2D& object); + RigidBody2D& operator=(RigidBody2D&& object); + + private: + void Destroy(); + void SetGeom(Collider2DRef geom); + + std::vector m_shapes; + Collider2DRef m_geom; + cpBody* m_handle; + PhysWorld2D* m_world; + float m_gravityFactor; + float m_mass; + }; +} + +#endif // NAZARA_RIGIDBODY3D_HPP diff --git a/include/Nazara/Physics3D.hpp b/include/Nazara/Physics3D.hpp new file mode 100644 index 000000000..a40c40b9c --- /dev/null +++ b/include/Nazara/Physics3D.hpp @@ -0,0 +1,39 @@ +// This file was automatically generated + +/* + Nazara Engine - Physics 3D module + + Copyright (C) 2015 Jérôme "Lynix" Leclercq (Lynix680@gmail.com) + + Permission is hereby granted, free of charge, to any person obtaining a copy of + this software and associated documentation files (the "Software"), to deal in + the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do + so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ + +#pragma once + +#ifndef NAZARA_GLOBAL_PHYSICS3D_HPP +#define NAZARA_GLOBAL_PHYSICS3D_HPP + +#include +#include +#include +#include +#include +#include + +#endif // NAZARA_GLOBAL_PHYSICS3D_HPP diff --git a/include/Nazara/Physics3D/Collider3D.hpp b/include/Nazara/Physics3D/Collider3D.hpp new file mode 100644 index 000000000..89e0a4879 --- /dev/null +++ b/include/Nazara/Physics3D/Collider3D.hpp @@ -0,0 +1,273 @@ +// Copyright (C) 2015 Jérôme Leclercq +// This file is part of the "Nazara Engine - Physics 3D module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#pragma once + +#ifndef NAZARA_COLLIDER3D_HPP +#define NAZARA_COLLIDER3D_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class NewtonCollision; + +namespace Nz +{ + ///TODO: CollisionModifier + ///TODO: HeightfieldGeom + ///TODO: PlaneGeom ? + ///TODO: SceneGeom + ///TODO: TreeGeom + + class Collider3D; + class PhysWorld3D; + + using Collider3DConstRef = ObjectRef; + using Collider3DLibrary = ObjectLibrary; + using Collider3DRef = ObjectRef; + + class NAZARA_PHYSICS3D_API Collider3D : public RefCounted + { + friend Collider3DLibrary; + friend class Physics3D; + + public: + Collider3D() = default; + Collider3D(const Collider3D&) = delete; + Collider3D(Collider3D&&) = delete; + virtual ~Collider3D(); + + Boxf ComputeAABB(const Vector3f& translation, const Quaternionf& rotation, const Vector3f& scale) const; + virtual Boxf ComputeAABB(const Matrix4f& offsetMatrix = Matrix4f::Identity(), const Vector3f& scale = Vector3f::Unit()) const; + virtual void ComputeInertialMatrix(Vector3f* inertia, Vector3f* center) const; + virtual float ComputeVolume() const; + + NewtonCollision* GetHandle(PhysWorld3D* world) const; + virtual ColliderType3D GetType() const = 0; + + Collider3D& operator=(const Collider3D&) = delete; + Collider3D& operator=(Collider3D&&) = delete; + + static Collider3DRef Build(const PrimitiveList& list); + + // Signals: + NazaraSignal(OnColliderRelease, const Collider3D* /*collider*/); + + protected: + virtual NewtonCollision* CreateHandle(PhysWorld3D* world) const = 0; + + static bool Initialize(); + static void Uninitialize(); + + mutable std::unordered_map m_handles; + + static Collider3DLibrary::LibraryMap s_library; + }; + + class BoxCollider3D; + + using BoxCollider3DConstRef = ObjectRef; + using BoxCollider3DRef = ObjectRef; + + class NAZARA_PHYSICS3D_API BoxCollider3D : public Collider3D + { + public: + BoxCollider3D(const Vector3f& lengths, const Matrix4f& transformMatrix = Matrix4f::Identity()); + BoxCollider3D(const Vector3f& lengths, const Vector3f& translation, const Quaternionf& rotation = Quaternionf::Identity()); + + Boxf ComputeAABB(const Matrix4f& offsetMatrix = Matrix4f::Identity(), const Vector3f& scale = Vector3f::Unit()) const override; + float ComputeVolume() const override; + + Vector3f GetLengths() const; + ColliderType3D GetType() const override; + + template static BoxCollider3DRef New(Args&&... args); + + private: + NewtonCollision* CreateHandle(PhysWorld3D* world) const override; + + Matrix4f m_matrix; + Vector3f m_lengths; + }; + + class CapsuleCollider3D; + + using CapsuleCollider3DConstRef = ObjectRef; + using CapsuleCollider3DRef = ObjectRef; + + class NAZARA_PHYSICS3D_API CapsuleCollider3D : public Collider3D + { + public: + CapsuleCollider3D(float length, float radius, const Matrix4f& transformMatrix = Matrix4f::Identity()); + CapsuleCollider3D(float length, float radius, const Vector3f& translation, const Quaternionf& rotation = Quaternionf::Identity()); + + float GetLength() const; + float GetRadius() const; + ColliderType3D GetType() const override; + + template static CapsuleCollider3DRef New(Args&&... args); + + private: + NewtonCollision* CreateHandle(PhysWorld3D* world) const override; + + Matrix4f m_matrix; + float m_length; + float m_radius; + }; + + class CompoundCollider3D; + + using CompoundCollider3DConstRef = ObjectRef; + using CompoundCollider3DRef = ObjectRef; + + class NAZARA_PHYSICS3D_API CompoundCollider3D : public Collider3D + { + public: + CompoundCollider3D(Collider3D** geoms, std::size_t geomCount); + + const std::vector& GetGeoms() const; + ColliderType3D GetType() const override; + + template static CompoundCollider3DRef New(Args&&... args); + + private: + NewtonCollision* CreateHandle(PhysWorld3D* world) const override; + + std::vector m_geoms; + }; + + class ConeCollider3D; + + using ConeCollider3DConstRef = ObjectRef; + using ConeCollider3DRef = ObjectRef; + + class NAZARA_PHYSICS3D_API ConeCollider3D : public Collider3D + { + public: + ConeCollider3D(float length, float radius, const Matrix4f& transformMatrix = Matrix4f::Identity()); + ConeCollider3D(float length, float radius, const Vector3f& translation, const Quaternionf& rotation = Quaternionf::Identity()); + + float GetLength() const; + float GetRadius() const; + ColliderType3D GetType() const override; + + template static ConeCollider3DRef New(Args&&... args); + + private: + NewtonCollision* CreateHandle(PhysWorld3D* world) const override; + + Matrix4f m_matrix; + float m_length; + float m_radius; + }; + + class ConvexCollider3D; + + using ConvexCollider3DConstRef = ObjectRef; + using ConvexCollider3DRef = ObjectRef; + + class NAZARA_PHYSICS3D_API ConvexCollider3D : public Collider3D + { + public: + ConvexCollider3D(SparsePtr vertices, unsigned int vertexCount, float tolerance = 0.002f, const Matrix4f& transformMatrix = Matrix4f::Identity()); + ConvexCollider3D(SparsePtr vertices, unsigned int vertexCount, float tolerance, const Vector3f& translation, const Quaternionf& rotation = Quaternionf::Identity()); + + ColliderType3D GetType() const override; + + template static ConvexCollider3DRef New(Args&&... args); + + private: + NewtonCollision* CreateHandle(PhysWorld3D* world) const override; + + std::vector m_vertices; + Matrix4f m_matrix; + float m_tolerance; + }; + + class CylinderCollider3D; + + using CylinderCollider3DConstRef = ObjectRef; + using CylinderCollider3DRef = ObjectRef; + + class NAZARA_PHYSICS3D_API CylinderCollider3D : public Collider3D + { + public: + CylinderCollider3D(float length, float radius, const Matrix4f& transformMatrix = Matrix4f::Identity()); + CylinderCollider3D(float length, float radius, const Vector3f& translation, const Quaternionf& rotation = Quaternionf::Identity()); + + float GetLength() const; + float GetRadius() const; + ColliderType3D GetType() const override; + + template static CylinderCollider3DRef New(Args&&... args); + + private: + NewtonCollision* CreateHandle(PhysWorld3D* world) const override; + + Matrix4f m_matrix; + float m_length; + float m_radius; + }; + + class NullCollider3D; + + using NullCollider3DConstRef = ObjectRef; + using NullCollider3DRef = ObjectRef; + + class NAZARA_PHYSICS3D_API NullCollider3D : public Collider3D + { + public: + NullCollider3D(); + + void ComputeInertialMatrix(Vector3f* inertia, Vector3f* center) const override; + + ColliderType3D GetType() const override; + + template static NullCollider3DRef New(Args&&... args); + + private: + NewtonCollision* CreateHandle(PhysWorld3D* world) const override; + }; + + class SphereCollider3D; + + using SphereCollider3DConstRef = ObjectRef; + using SphereCollider3DRef = ObjectRef; + + class NAZARA_PHYSICS3D_API SphereCollider3D : public Collider3D + { + public: + SphereCollider3D(float radius, const Matrix4f& transformMatrix = Matrix4f::Identity()); + SphereCollider3D(float radius, const Vector3f& translation, const Quaternionf& rotation = Quaternionf::Identity()); + + Boxf ComputeAABB(const Matrix4f& offsetMatrix = Matrix4f::Identity(), const Vector3f& scale = Vector3f::Unit()) const override; + float ComputeVolume() const override; + + float GetRadius() const; + ColliderType3D GetType() const override; + + template static SphereCollider3DRef New(Args&&... args); + + private: + NewtonCollision* CreateHandle(PhysWorld3D* world) const override; + + Vector3f m_position; + float m_radius; + }; +} + +#include + +#endif // NAZARA_COLLIDER3D_HPP diff --git a/include/Nazara/Physics3D/Collider3D.inl b/include/Nazara/Physics3D/Collider3D.inl new file mode 100644 index 000000000..aeb7073d8 --- /dev/null +++ b/include/Nazara/Physics3D/Collider3D.inl @@ -0,0 +1,83 @@ +// Copyright (C) 2015 Jérôme Leclercq +// This file is part of the "Nazara Engine - Physics 3D module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#include +#include + +namespace Nz +{ + template + BoxCollider3DRef BoxCollider3D::New(Args&&... args) + { + std::unique_ptr object(new BoxCollider3D(std::forward(args)...)); + object->SetPersistent(false); + + return object.release(); + } + + template + CapsuleCollider3DRef CapsuleCollider3D::New(Args&&... args) + { + std::unique_ptr object(new CapsuleCollider3D(std::forward(args)...)); + object->SetPersistent(false); + + return object.release(); + } + + template + CompoundCollider3DRef CompoundCollider3D::New(Args&&... args) + { + std::unique_ptr object(new CompoundCollider3D(std::forward(args)...)); + object->SetPersistent(false); + + return object.release(); + } + + template + ConeCollider3DRef ConeCollider3D::New(Args&&... args) + { + std::unique_ptr object(new ConeCollider3D(std::forward(args)...)); + object->SetPersistent(false); + + return object.release(); + } + + template + ConvexCollider3DRef ConvexCollider3D::New(Args&&... args) + { + std::unique_ptr object(new ConvexCollider3D(std::forward(args)...)); + object->SetPersistent(false); + + return object.release(); + } + + template + CylinderCollider3DRef CylinderCollider3D::New(Args&&... args) + { + std::unique_ptr object(new CylinderCollider3D(std::forward(args)...)); + object->SetPersistent(false); + + return object.release(); + } + + template + NullCollider3DRef NullCollider3D::New(Args&&... args) + { + std::unique_ptr object(new NullCollider3D(std::forward(args)...)); + object->SetPersistent(false); + + return object.release(); + } + + template + SphereCollider3DRef SphereCollider3D::New(Args&&... args) + { + std::unique_ptr object(new SphereCollider3D(std::forward(args)...)); + object->SetPersistent(false); + + return object.release(); + } +} + +#include diff --git a/include/Nazara/Physics3D/Config.hpp b/include/Nazara/Physics3D/Config.hpp new file mode 100644 index 000000000..91ecec8e3 --- /dev/null +++ b/include/Nazara/Physics3D/Config.hpp @@ -0,0 +1,51 @@ +/* + Nazara Engine - Physics 3D module + + Copyright (C) 2015 Jérôme "Lynix" Leclercq (Lynix680@gmail.com) + + Permission is hereby granted, free of charge, to any person obtaining a copy of + this software and associated documentation files (the "Software"), to deal in + the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do + so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ + +#pragma once + +#ifndef NAZARA_CONFIG_PHYSICS3D_HPP +#define NAZARA_CONFIG_PHYSICS3D_HPP + +/// Chaque modification d'un paramètre du module nécessite une recompilation de celui-ci + +// Utilise un manager de mémoire pour gérer les allocations dynamiques (détecte les leaks au prix d'allocations/libérations dynamiques plus lentes) +#define NAZARA_PHYSICS3D_MANAGE_MEMORY 0 + +// Active les tests de sécurité basés sur le code (Conseillé pour le développement) +#define NAZARA_PHYSICS3D_SAFE 1 + +/// Vérification des valeurs et types de certaines constantes +#include + +#if defined(NAZARA_STATIC) + #define NAZARA_PHYSICS3D_API +#else + #ifdef NAZARA_PHYSICS3D_BUILD + #define NAZARA_PHYSICS3D_API NAZARA_EXPORT + #else + #define NAZARA_PHYSICS3D_API NAZARA_IMPORT + #endif +#endif + +#endif // NAZARA_CONFIG_PHYSICS3D_HPP diff --git a/include/Nazara/Physics3D/ConfigCheck.hpp b/include/Nazara/Physics3D/ConfigCheck.hpp new file mode 100644 index 000000000..6b1c82073 --- /dev/null +++ b/include/Nazara/Physics3D/ConfigCheck.hpp @@ -0,0 +1,18 @@ +// Copyright (C) 2015 Jérôme Leclercq +// This file is part of the "Nazara Engine - Physics 3D module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#pragma once + +#ifndef NAZARA_CONFIG_CHECK_PHYSICS_HPP +#define NAZARA_CONFIG_CHECK_PHYSICS_HPP + +/// Ce fichier sert à vérifier la valeur des constantes du fichier Config.hpp + +// On force la valeur de MANAGE_MEMORY en mode debug +#if defined(NAZARA_DEBUG) && !NAZARA_PHYSICS_MANAGE_MEMORY + #undef NAZARA_PHYSICS_MANAGE_MEMORY + #define NAZARA_PHYSICS3D_MANAGE_MEMORY 0 +#endif + +#endif // NAZARA_CONFIG_CHECK_PHYSICS_HPP diff --git a/include/Nazara/Physics3D/Debug.hpp b/include/Nazara/Physics3D/Debug.hpp new file mode 100644 index 000000000..f70a8b570 --- /dev/null +++ b/include/Nazara/Physics3D/Debug.hpp @@ -0,0 +1,8 @@ +// Copyright (C) 2015 Jérôme Leclercq +// This file is part of the "Nazara Engine - Physics 3D module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#include +#if NAZARA_PHYSICS_MANAGE_MEMORY + #include +#endif diff --git a/include/Nazara/Physics3D/DebugOff.hpp b/include/Nazara/Physics3D/DebugOff.hpp new file mode 100644 index 000000000..595f0ad94 --- /dev/null +++ b/include/Nazara/Physics3D/DebugOff.hpp @@ -0,0 +1,9 @@ +// Copyright (C) 2015 Jérôme Leclercq +// This file is part of the "Nazara Engine - Physics 3D module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +// On suppose que Debug.hpp a déjà été inclus, tout comme Config.hpp +#if NAZARA_PHYSICS_MANAGE_MEMORY + #undef delete + #undef new +#endif diff --git a/include/Nazara/Physics3D/Enums.hpp b/include/Nazara/Physics3D/Enums.hpp new file mode 100644 index 000000000..1b8920cbc --- /dev/null +++ b/include/Nazara/Physics3D/Enums.hpp @@ -0,0 +1,30 @@ +// Copyright (C) 2015 Jérôme Leclercq +// This file is part of the "Nazara Engine - Physics 3D module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#pragma once + +#ifndef NAZARA_ENUMS_PHYSICS3D_HPP +#define NAZARA_ENUMS_PHYSICS3D_HPP + +namespace Nz +{ + enum ColliderType3D + { + ColliderType3D_Box, + ColliderType3D_Capsule, + ColliderType3D_Cone, + ColliderType3D_Compound, + ColliderType3D_ConvexHull, + ColliderType3D_Cylinder, + ColliderType3D_Heightfield, + ColliderType3D_Null, + ColliderType3D_Scene, + ColliderType3D_Sphere, + ColliderType3D_Tree, + + ColliderType3D_Max = ColliderType3D_Tree + }; +}; + +#endif // NAZARA_ENUMS_PHYSICS3D_HPP diff --git a/include/Nazara/Physics/PhysWorld.hpp b/include/Nazara/Physics3D/PhysWorld3D.hpp similarity index 65% rename from include/Nazara/Physics/PhysWorld.hpp rename to include/Nazara/Physics3D/PhysWorld3D.hpp index 0300048b5..ea84aa931 100644 --- a/include/Nazara/Physics/PhysWorld.hpp +++ b/include/Nazara/Physics3D/PhysWorld3D.hpp @@ -1,5 +1,5 @@ // Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Physics module" +// This file is part of the "Nazara Engine - Physics 3D module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once @@ -10,19 +10,19 @@ #include #include #include -#include +#include class NewtonWorld; namespace Nz { - class NAZARA_PHYSICS_API PhysWorld + class NAZARA_PHYSICS3D_API PhysWorld3D { public: - PhysWorld(); - PhysWorld(const PhysWorld&) = delete; - PhysWorld(PhysWorld&&) = delete; ///TODO - ~PhysWorld(); + PhysWorld3D(); + PhysWorld3D(const PhysWorld3D&) = delete; + PhysWorld3D(PhysWorld3D&&) = delete; ///TODO + ~PhysWorld3D(); Vector3f GetGravity() const; NewtonWorld* GetHandle() const; @@ -34,8 +34,8 @@ namespace Nz void Step(float timestep); - PhysWorld& operator=(const PhysWorld&) = delete; - PhysWorld& operator=(PhysWorld&&) = delete; ///TODO + PhysWorld3D& operator=(const PhysWorld3D&) = delete; + PhysWorld3D& operator=(PhysWorld3D&&) = delete; ///TODO private: Vector3f m_gravity; diff --git a/include/Nazara/Physics/Physics.hpp b/include/Nazara/Physics3D/Physics3D.hpp similarity index 61% rename from include/Nazara/Physics/Physics.hpp rename to include/Nazara/Physics3D/Physics3D.hpp index 3bb6ebde3..949301002 100644 --- a/include/Nazara/Physics/Physics.hpp +++ b/include/Nazara/Physics3D/Physics3D.hpp @@ -1,23 +1,23 @@ // Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Physics module" +// This file is part of the "Nazara Engine - Physics 3D module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once -#ifndef NAZARA_PHYSICS_HPP -#define NAZARA_PHYSICS_HPP +#ifndef NAZARA_PHYSICS3D_HPP +#define NAZARA_PHYSICS3D_HPP #include #include -#include +#include namespace Nz { - class NAZARA_PHYSICS_API Physics + class NAZARA_PHYSICS3D_API Physics3D { public: - Physics() = delete; - ~Physics() = delete; + Physics3D() = delete; + ~Physics3D() = delete; static unsigned int GetMemoryUsed(); @@ -32,4 +32,4 @@ namespace Nz }; } -#endif // NAZARA_PHYSICS_HPP +#endif // NAZARA_PHYSICS3D_HPP diff --git a/include/Nazara/Physics/PhysObject.hpp b/include/Nazara/Physics3D/RigidBody3D.hpp similarity index 69% rename from include/Nazara/Physics/PhysObject.hpp rename to include/Nazara/Physics3D/RigidBody3D.hpp index d4d9c61b7..d895e9040 100644 --- a/include/Nazara/Physics/PhysObject.hpp +++ b/include/Nazara/Physics3D/RigidBody3D.hpp @@ -1,34 +1,34 @@ // Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Physics module" +// This file is part of the "Nazara Engine - Physics 3D module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once -#ifndef NAZARA_PHYSOBJECT_HPP -#define NAZARA_PHYSOBJECT_HPP +#ifndef NAZARA_RIGIDBODY3D_HPP +#define NAZARA_RIGIDBODY3D_HPP #include #include #include #include #include -#include -#include +#include +#include class NewtonBody; namespace Nz { - class PhysWorld; + class PhysWorld3D; - class NAZARA_PHYSICS_API PhysObject + class NAZARA_PHYSICS3D_API RigidBody3D { public: - PhysObject(PhysWorld* world, const Matrix4f& mat = Matrix4f::Identity()); - PhysObject(PhysWorld* world, PhysGeomRef geom, const Matrix4f& mat = Matrix4f::Identity()); - PhysObject(const PhysObject& object); - PhysObject(PhysObject&& object); - ~PhysObject(); + RigidBody3D(PhysWorld3D* world, const Matrix4f& mat = Matrix4f::Identity()); + RigidBody3D(PhysWorld3D* world, Collider3DRef geom, const Matrix4f& mat = Matrix4f::Identity()); + RigidBody3D(const RigidBody3D& object); + RigidBody3D(RigidBody3D&& object); + ~RigidBody3D(); void AddForce(const Vector3f& force, CoordSys coordSys = CoordSys_Global); void AddForce(const Vector3f& force, const Vector3f& point, CoordSys coordSys = CoordSys_Global); @@ -38,7 +38,7 @@ namespace Nz Boxf GetAABB() const; Vector3f GetAngularVelocity() const; - const PhysGeomRef& GetGeom() const; + const Collider3DRef& GetGeom() const; float GetGravityFactor() const; NewtonBody* GetHandle() const; float GetMass() const; @@ -53,7 +53,7 @@ namespace Nz bool IsSleeping() const; void SetAngularVelocity(const Vector3f& angularVelocity); - void SetGeom(PhysGeomRef geom); + void SetGeom(Collider3DRef geom); void SetGravityFactor(float gravityFactor); void SetMass(float mass); void SetMassCenter(const Vector3f& center); @@ -61,23 +61,23 @@ namespace Nz void SetRotation(const Quaternionf& rotation); void SetVelocity(const Vector3f& velocity); - PhysObject& operator=(const PhysObject& object); - PhysObject& operator=(PhysObject&& object); + RigidBody3D& operator=(const RigidBody3D& object); + RigidBody3D& operator=(RigidBody3D&& object); private: void UpdateBody(); static void ForceAndTorqueCallback(const NewtonBody* body, float timeStep, int threadIndex); static void TransformCallback(const NewtonBody* body, const float* matrix, int threadIndex); + Collider3DRef m_geom; Matrix4f m_matrix; - PhysGeomRef m_geom; Vector3f m_forceAccumulator; Vector3f m_torqueAccumulator; NewtonBody* m_body; - PhysWorld* m_world; + PhysWorld3D* m_world; float m_gravityFactor; float m_mass; }; } -#endif // NAZARA_PHYSOBJECT_HPP +#endif // NAZARA_RIGIDBODY3D_HPP diff --git a/include/Nazara/Renderer.hpp b/include/Nazara/Renderer.hpp index 52519d374..b7262434a 100644 --- a/include/Nazara/Renderer.hpp +++ b/include/Nazara/Renderer.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 15 Sep 2016 at 00:43:26 +// This file was automatically generated /* Nazara Engine - Renderer module @@ -34,6 +34,7 @@ #include #include #include +#include #include #include #include diff --git a/include/Nazara/Utility.hpp b/include/Nazara/Utility.hpp index d7676277e..3734b919e 100644 --- a/include/Nazara/Utility.hpp +++ b/include/Nazara/Utility.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 12 Jul 2016 at 17:44:43 +// This file was automatically generated /* Nazara Engine - Utility module @@ -42,6 +42,7 @@ #include #include #include +#include #include #include #include diff --git a/include/Nazara/Utility/AbstractImage.hpp b/include/Nazara/Utility/AbstractImage.hpp index 93821e105..ffeacbca4 100644 --- a/include/Nazara/Utility/AbstractImage.hpp +++ b/include/Nazara/Utility/AbstractImage.hpp @@ -8,6 +8,7 @@ #define NAZARA_ABSTRACTIMAGE_HPP #include +#include #include #include #include @@ -16,10 +17,16 @@ namespace Nz { - class NAZARA_UTILITY_API AbstractImage + class AbstractImage; + + using AbstractImageConstRef = ObjectRef; + using AbstractImageRef = ObjectRef; + + class NAZARA_UTILITY_API AbstractImage : public RefCounted { public: AbstractImage() = default; + inline AbstractImage(const AbstractImage& image); virtual ~AbstractImage(); UInt8 GetBytesPerPixel() const; @@ -43,4 +50,6 @@ namespace Nz }; } +#include + #endif // NAZARA_IMAGE_HPP diff --git a/include/Nazara/Utility/AbstractImage.inl b/include/Nazara/Utility/AbstractImage.inl new file mode 100644 index 000000000..b3e5fc417 --- /dev/null +++ b/include/Nazara/Utility/AbstractImage.inl @@ -0,0 +1,16 @@ +// Copyright (C) 2015 Jérôme Leclercq +// This file is part of the "Nazara Engine - Utility module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#include +#include + +namespace Nz +{ + inline AbstractImage::AbstractImage(const AbstractImage&) : + RefCounted() + { + } +} + +#include diff --git a/include/Nazara/Utility/Formats/MTLParser.hpp b/include/Nazara/Utility/Formats/MTLParser.hpp index 9c5b49828..708e30685 100644 --- a/include/Nazara/Utility/Formats/MTLParser.hpp +++ b/include/Nazara/Utility/Formats/MTLParser.hpp @@ -71,7 +71,6 @@ namespace Nz mutable StringStream m_outputStream; bool m_keepLastLine; unsigned int m_lineCount; - unsigned int m_streamFlags; }; } diff --git a/include/Nazara/Utility/Image.hpp b/include/Nazara/Utility/Image.hpp index d936ee4d8..029157885 100644 --- a/include/Nazara/Utility/Image.hpp +++ b/include/Nazara/Utility/Image.hpp @@ -10,7 +10,6 @@ #include #include #include -#include #include #include #include @@ -47,7 +46,7 @@ namespace Nz using ImageRef = ObjectRef; using ImageSaver = ResourceSaver; - class NAZARA_UTILITY_API Image : public AbstractImage, public RefCounted, public Resource + class NAZARA_UTILITY_API Image : public AbstractImage, public Resource { friend ImageLibrary; friend ImageLoader; diff --git a/include/Nazara/Utility/PixelFormat.inl b/include/Nazara/Utility/PixelFormat.inl index bf827c4c0..4d8676916 100644 --- a/include/Nazara/Utility/PixelFormat.inl +++ b/include/Nazara/Utility/PixelFormat.inl @@ -111,8 +111,8 @@ namespace Nz if (content <= PixelFormatContent_Undefined || content > PixelFormatContent_Max) return false; - std::array*, 4> masks = {&redMask, &greenMask, &blueMask, &alphaMask}; - std::array types = {redType, greenType, blueType, alphaType}; + std::array*, 4> masks = { {&redMask, &greenMask, &blueMask, &alphaMask} }; + std::array types = { {redType, greenType, blueType, alphaType} }; for (unsigned int i = 0; i < 4; ++i) { diff --git a/include/Nazara/VulkanRenderer.hpp b/include/Nazara/VulkanRenderer.hpp index 13874e658..dba9f55e3 100644 --- a/include/Nazara/VulkanRenderer.hpp +++ b/include/Nazara/VulkanRenderer.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 15 Sep 2016 at 00:43:26 +// This file was automatically generated /* Nazara Engine - Vulkan @@ -30,6 +30,7 @@ #define NAZARA_GLOBAL_VULKANRENDERER_HPP #include +#include #include #include #include diff --git a/plugins/Assimp/CustomStream.cpp b/plugins/Assimp/CustomStream.cpp index 9a010b0b2..643a5b13f 100644 --- a/plugins/Assimp/CustomStream.cpp +++ b/plugins/Assimp/CustomStream.cpp @@ -40,6 +40,9 @@ aiReturn StreamSeek(aiFile* file, size_t offset, aiOrigin origin) case aiOrigin_SET: return (stream->SetCursorPos(offset)) ? aiReturn_SUCCESS : aiReturn_FAILURE; + + case _AI_ORIGIN_ENFORCE_ENUM_SIZE: // To prevent a warning + break; } NazaraWarning("Unhandled aiOrigin enum (value: 0x" + String(origin, 16) + ')'); diff --git a/plugins/Assimp/Plugin.cpp b/plugins/Assimp/Plugin.cpp index d1d0ace26..a668ec634 100644 --- a/plugins/Assimp/Plugin.cpp +++ b/plugins/Assimp/Plugin.cpp @@ -72,11 +72,11 @@ bool IsSupported(const String& extension) return (aiIsExtensionSupported(dotExt.GetConstBuffer()) == AI_TRUE); } -Ternary Check(Stream& stream, const MeshParams& parameters) +Ternary Check(Stream& /*stream*/, const MeshParams& parameters) { - bool skip; - if (parameters.custom.GetBooleanParameter("SkipAssimpLoader", &skip) && skip) - return Ternary_False; + bool skip; + if (parameters.custom.GetBooleanParameter("SkipAssimpLoader", &skip) && skip) + return Ternary_False; return Ternary_Unknown; } diff --git a/src/Nazara/Core/FileLogger.cpp b/src/Nazara/Core/FileLogger.cpp index bac0cb099..f08bd1b31 100644 --- a/src/Nazara/Core/FileLogger.cpp +++ b/src/Nazara/Core/FileLogger.cpp @@ -65,7 +65,7 @@ namespace Nz * \return true If replication is enabled */ - bool FileLogger::IsStdReplicationEnabled() + bool FileLogger::IsStdReplicationEnabled() const { return m_stdReplicationEnabled; } @@ -75,7 +75,7 @@ namespace Nz * \return true If logging of the time is enabled */ - bool FileLogger::IsTimeLoggingEnabled() + bool FileLogger::IsTimeLoggingEnabled() const { return m_timeLoggingEnabled; } @@ -147,14 +147,6 @@ namespace Nz void FileLogger::WriteError(ErrorType type, const String& error, unsigned int line, const char* file, const char* function) { - if (m_forceStdOutput || m_stdReplicationEnabled) - { - m_stdLogger.WriteError(type, error, line, file, function); - - if (m_forceStdOutput) - return; - } - AbstractLogger::WriteError(type, error, line, file, function); m_outputFile.Flush(); } diff --git a/src/Nazara/Core/Log.cpp b/src/Nazara/Core/Log.cpp index 9e6b13353..1ff1ea373 100644 --- a/src/Nazara/Core/Log.cpp +++ b/src/Nazara/Core/Log.cpp @@ -111,7 +111,9 @@ namespace Nz bool Log::Initialize() { - SetLogger(new FileLogger()); + if (s_logger == &s_stdLogger) + SetLogger(new FileLogger()); + return true; } diff --git a/src/Nazara/Core/Posix/FileImpl.cpp b/src/Nazara/Core/Posix/FileImpl.cpp index b9a6b0a31..037d795f0 100644 --- a/src/Nazara/Core/Posix/FileImpl.cpp +++ b/src/Nazara/Core/Posix/FileImpl.cpp @@ -208,8 +208,9 @@ namespace Nz time_t FileImpl::GetCreationTime(const String& filePath) { - NazaraWarning("Posix has no creation time information"); + NazaraUnused(filePath); + NazaraWarning("Posix has no creation time information"); return 0; } diff --git a/src/Nazara/Core/StdLogger.cpp b/src/Nazara/Core/StdLogger.cpp index e38daa077..c8dfc60bb 100644 --- a/src/Nazara/Core/StdLogger.cpp +++ b/src/Nazara/Core/StdLogger.cpp @@ -47,7 +47,7 @@ namespace Nz * \return Always returns true */ - bool StdLogger::IsStdReplicationEnabled() + bool StdLogger::IsStdReplicationEnabled() const { return true; } diff --git a/src/Nazara/Graphics/DeferredGeometryPass.cpp b/src/Nazara/Graphics/DeferredGeometryPass.cpp index dbdb95f5a..79e651926 100644 --- a/src/Nazara/Graphics/DeferredGeometryPass.cpp +++ b/src/Nazara/Graphics/DeferredGeometryPass.cpp @@ -82,7 +82,7 @@ namespace Nz if (pipelineEntry.maxInstanceCount > 0) { - bool instancing = (pipelineEntry.maxInstanceCount > NAZARA_GRAPHICS_INSTANCING_MIN_INSTANCES_COUNT); + bool instancing = instancingEnabled && (pipelineEntry.maxInstanceCount > NAZARA_GRAPHICS_INSTANCING_MIN_INSTANCES_COUNT); UInt32 flags = ShaderFlags_Deferred; if (instancing) diff --git a/src/Nazara/Graphics/DeferredRenderQueue.cpp b/src/Nazara/Graphics/DeferredRenderQueue.cpp index b240edcd7..6aecb8a5a 100644 --- a/src/Nazara/Graphics/DeferredRenderQueue.cpp +++ b/src/Nazara/Graphics/DeferredRenderQueue.cpp @@ -282,7 +282,6 @@ namespace Nz { for (auto& pipelinePair : layer.opaqueModels) { - const MaterialPipeline* pipeline = pipelinePair.first; auto& pipelineEntry = pipelinePair.second; if (pipelineEntry.maxInstanceCount > 0) diff --git a/src/Nazara/Graphics/DepthRenderTechnique.cpp b/src/Nazara/Graphics/DepthRenderTechnique.cpp index 46b1c3407..bcae2eb57 100644 --- a/src/Nazara/Graphics/DepthRenderTechnique.cpp +++ b/src/Nazara/Graphics/DepthRenderTechnique.cpp @@ -52,7 +52,7 @@ namespace Nz { ErrorFlags flags(ErrorFlag_ThrowException, true); - std::array whitePixel = {255, 255, 255, 255}; + std::array whitePixel = { {255, 255, 255, 255} }; m_whiteTexture.Create(ImageType_2D, PixelFormatType_RGBA8, 1, 1); m_whiteTexture.Update(whitePixel.data()); @@ -431,7 +431,6 @@ namespace Nz for (auto& matIt : pipelinePair.second.materialMap) { - const Material* material = matIt.first; auto& entry = matIt.second; auto& billboardVector = entry.billboards; @@ -551,9 +550,7 @@ namespace Nz const MeshData& meshData = meshIt.first; auto& meshEntry = meshIt.second; - const Spheref& squaredBoundingSphere = meshEntry.squaredBoundingSphere; std::vector& instances = meshEntry.instances; - if (!instances.empty()) { const IndexBuffer* indexBuffer = meshData.indexBuffer; diff --git a/src/Nazara/Graphics/ForwardRenderQueue.cpp b/src/Nazara/Graphics/ForwardRenderQueue.cpp index 2de6b66e4..b74ffa732 100644 --- a/src/Nazara/Graphics/ForwardRenderQueue.cpp +++ b/src/Nazara/Graphics/ForwardRenderQueue.cpp @@ -542,9 +542,7 @@ namespace Nz auto& overlayMap = matEntry.overlayMap; for (auto& overlayIt : overlayMap) { - const Texture* overlay = overlayIt.first; auto& spriteChainVector = overlayIt.second.spriteChains; - spriteChainVector.clear(); } @@ -563,9 +561,7 @@ namespace Nz { for (auto& materialPair : pipelineEntry.materialMap) { - const Material* material = materialPair.first; auto& matEntry = materialPair.second; - if (matEntry.enabled) { MeshInstanceContainer& meshInstances = matEntry.meshMap; @@ -573,7 +569,6 @@ namespace Nz for (auto& meshIt : meshInstances) { auto& meshEntry = meshIt.second; - meshEntry.instances.clear(); } matEntry.enabled = false; diff --git a/src/Nazara/Graphics/ForwardRenderTechnique.cpp b/src/Nazara/Graphics/ForwardRenderTechnique.cpp index 959ef2f03..699ae416a 100644 --- a/src/Nazara/Graphics/ForwardRenderTechnique.cpp +++ b/src/Nazara/Graphics/ForwardRenderTechnique.cpp @@ -53,7 +53,7 @@ namespace Nz { ErrorFlags flags(ErrorFlag_ThrowException, true); - std::array whitePixel = {255, 255, 255, 255}; + std::array whitePixel = { {255, 255, 255, 255} }; m_whiteTexture.Create(ImageType_2D, PixelFormatType_RGBA8, 1, 1); m_whiteTexture.Update(whitePixel.data()); @@ -412,7 +412,7 @@ namespace Nz const Shader* lastShader = nullptr; const ShaderUniforms* shaderUniforms = nullptr; - if (Renderer::HasCapability(RendererCap_Instancing)) + if (m_instancingEnabled && Renderer::HasCapability(RendererCap_Instancing)) { VertexBuffer* instanceBuffer = Renderer::GetInstanceBuffer(); instanceBuffer->SetVertexDeclaration(&s_billboardInstanceDeclaration); @@ -508,7 +508,6 @@ namespace Nz for (auto& matIt : pipelinePair.second.materialMap) { - const Material* material = matIt.first; auto& entry = matIt.second; auto& billboardVector = entry.billboards; @@ -593,7 +592,7 @@ namespace Nz if (pipelineEntry.maxInstanceCount > 0) { - bool instancing = (pipelineEntry.maxInstanceCount > NAZARA_GRAPHICS_INSTANCING_MIN_INSTANCES_COUNT); + bool instancing = m_instancingEnabled && (pipelineEntry.maxInstanceCount > NAZARA_GRAPHICS_INSTANCING_MIN_INSTANCES_COUNT); const MaterialPipeline::Instance& pipelineInstance = pipeline->Apply((instancing) ? ShaderFlags_Instancing : 0); const Shader* shader = pipelineInstance.uberInstance->GetShader(); diff --git a/src/Nazara/Lua/LuaInstance.cpp b/src/Nazara/Lua/LuaInstance.cpp index f73c4a207..5162645b2 100644 --- a/src/Nazara/Lua/LuaInstance.cpp +++ b/src/Nazara/Lua/LuaInstance.cpp @@ -149,22 +149,22 @@ namespace Nz lua_close(m_state); } - void LuaInstance::ArgCheck(bool condition, unsigned int argNum, const char* error) + void LuaInstance::ArgCheck(bool condition, unsigned int argNum, const char* error) const { luaL_argcheck(m_state, condition, argNum, error); } - void LuaInstance::ArgCheck(bool condition, unsigned int argNum, const String& error) + void LuaInstance::ArgCheck(bool condition, unsigned int argNum, const String& error) const { luaL_argcheck(m_state, condition, argNum, error.GetConstBuffer()); } - int LuaInstance::ArgError(unsigned int argNum, const char* error) + int LuaInstance::ArgError(unsigned int argNum, const char* error) const { return luaL_argerror(m_state, argNum, error); } - int LuaInstance::ArgError(unsigned int argNum, const String& error) + int LuaInstance::ArgError(unsigned int argNum, const String& error) const { return luaL_argerror(m_state, argNum, error.GetConstBuffer()); } diff --git a/src/Nazara/Network/Linux/SocketPollerImpl.cpp b/src/Nazara/Network/Linux/SocketPollerImpl.cpp index ec6b8235e..c839d7352 100644 --- a/src/Nazara/Network/Linux/SocketPollerImpl.cpp +++ b/src/Nazara/Network/Linux/SocketPollerImpl.cpp @@ -85,7 +85,7 @@ namespace Nz } m_activeSockets.clear(); - if (activeSockets > 0U) + if (activeSockets > 0) { int socketCount = activeSockets; for (int i = 0; i < socketCount; ++i) diff --git a/src/Nazara/Network/Posix/IpAddressImpl.cpp b/src/Nazara/Network/Posix/IpAddressImpl.cpp index 1e4f6a89e..13eb10c31 100644 --- a/src/Nazara/Network/Posix/IpAddressImpl.cpp +++ b/src/Nazara/Network/Posix/IpAddressImpl.cpp @@ -54,7 +54,7 @@ namespace Nz byteToInt hostOrder; hostOrder.i = ntohl(addr.s_addr); - return { hostOrder.b[3], hostOrder.b[2], hostOrder.b[1], hostOrder.b[0] }; + return { {hostOrder.b[3], hostOrder.b[2], hostOrder.b[1], hostOrder.b[0]} }; } IpAddress::IPv6 convertSockaddr6ToIPv6(const in6_addr& addr) diff --git a/src/Nazara/Network/Posix/SocketPollerImpl.cpp b/src/Nazara/Network/Posix/SocketPollerImpl.cpp index 4242e79a9..5d2a6c317 100644 --- a/src/Nazara/Network/Posix/SocketPollerImpl.cpp +++ b/src/Nazara/Network/Posix/SocketPollerImpl.cpp @@ -74,7 +74,7 @@ namespace Nz activeSockets = SocketImpl::Poll(m_sockets.data(), m_sockets.size(), static_cast(msTimeout), error); m_activeSockets.clear(); - if (activeSockets > 0U) + if (activeSockets > 0) { int socketRemaining = activeSockets; for (PollSocket& entry : m_sockets) diff --git a/src/Nazara/Noise/Simplex.cpp b/src/Nazara/Noise/Simplex.cpp index 8d4748bff..b1a2bd0b6 100644 --- a/src/Nazara/Noise/Simplex.cpp +++ b/src/Nazara/Noise/Simplex.cpp @@ -51,11 +51,12 @@ namespace Nz d[2] = d[0] + Vector2f(1.f - 2.f * s_UnskewCoeff2D); Vector2i offset(skewedCubeOrigin.x & 255, skewedCubeOrigin.y & 255); - std::array gi = - { - m_permutations[offset.x + m_permutations[offset.y]] & 7, - m_permutations[offset.x + off1.x + m_permutations[offset.y + off1.y]] & 7, - m_permutations[offset.x + 1 + m_permutations[offset.y + 1]] & 7 + std::array gi = { + { + m_permutations[offset.x + m_permutations[offset.y]] & 7, + m_permutations[offset.x + off1.x + m_permutations[offset.y + off1.y]] & 7, + m_permutations[offset.x + 1 + m_permutations[offset.y + 1]] & 7 + } }; float n = 0.f; diff --git a/src/Nazara/Noise/Worley.cpp b/src/Nazara/Noise/Worley.cpp index cc98fa378..4f2aa90f7 100644 --- a/src/Nazara/Noise/Worley.cpp +++ b/src/Nazara/Noise/Worley.cpp @@ -12,12 +12,13 @@ namespace Nz { namespace { - static constexpr std::array m_functionScales = - { - 1.f / float(M_SQRT2), - 0.5f / float(M_SQRT2), - 0.5f / float(M_SQRT2), - 0.5f / float(M_SQRT2) + static constexpr std::array m_functionScales = { + { + 1.f / float(M_SQRT2), + 0.5f / float(M_SQRT2), + 0.5f / float(M_SQRT2), + 0.5f / float(M_SQRT2) + } }; } Worley::Worley() : @@ -109,12 +110,12 @@ namespace Nz return it->first * m_functionScales[functionIndex]; } - float Worley::Get(float x, float y, float z, float scale) const + float Worley::Get(float /*x*/, float /*y*/, float /*z*/, float /*scale*/) const { throw std::runtime_error("Worley 3D not available yet."); } - float Worley::Get(float x, float y, float z, float w, float scale) const + float Worley::Get(float /*x*/, float /*y*/, float /*z*/, float /*w*/, float /*scale*/) const { throw std::runtime_error("Worley 4D not available yet."); } diff --git a/src/Nazara/Physics/Geom.cpp b/src/Nazara/Physics/Geom.cpp deleted file mode 100644 index 48d6f0090..000000000 --- a/src/Nazara/Physics/Geom.cpp +++ /dev/null @@ -1,448 +0,0 @@ -// Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Physics module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include - -namespace Nz -{ - namespace - { - PhysGeomRef CreateGeomFromPrimitive(const Primitive& primitive) - { - switch (primitive.type) - { - case PrimitiveType_Box: - return BoxGeom::New(primitive.box.lengths, primitive.matrix); - - case PrimitiveType_Cone: - return ConeGeom::New(primitive.cone.length, primitive.cone.radius, primitive.matrix); - - case PrimitiveType_Plane: - return BoxGeom::New(Vector3f(primitive.plane.size.x, 0.01f, primitive.plane.size.y), primitive.matrix); - ///TODO: PlaneGeom? - - case PrimitiveType_Sphere: - return SphereGeom::New(primitive.sphere.size, primitive.matrix.GetTranslation()); - } - - NazaraError("Primitive type not handled (0x" + String::Number(primitive.type, 16) + ')'); - return PhysGeomRef(); - } - } - - PhysGeom::~PhysGeom() - { - for (auto& pair : m_handles) - NewtonDestroyCollision(pair.second); - } - - Boxf PhysGeom::ComputeAABB(const Vector3f& translation, const Quaternionf& rotation, const Vector3f& scale) const - { - return ComputeAABB(Matrix4f::Transform(translation, rotation), scale); - } - - Boxf PhysGeom::ComputeAABB(const Matrix4f& offsetMatrix, const Vector3f& scale) const - { - Vector3f min, max; - - // Si nous n'avons aucune instance, nous en créons une temporaire - if (m_handles.empty()) - { - PhysWorld world; - - NewtonCollision* collision = CreateHandle(&world); - { - NewtonCollisionCalculateAABB(collision, offsetMatrix, min, max); - } - NewtonDestroyCollision(collision); - } - else // Sinon on utilise une instance au hasard (elles sont toutes identiques de toute façon) - NewtonCollisionCalculateAABB(m_handles.begin()->second, offsetMatrix, min, max); - - return Boxf(scale * min, scale * max); - } - - void PhysGeom::ComputeInertialMatrix(Vector3f* inertia, Vector3f* center) const - { - float inertiaMatrix[3]; - float origin[3]; - - // Si nous n'avons aucune instance, nous en créons une temporaire - if (m_handles.empty()) - { - PhysWorld world; - - NewtonCollision* collision = CreateHandle(&world); - { - NewtonConvexCollisionCalculateInertialMatrix(collision, inertiaMatrix, origin); - } - NewtonDestroyCollision(collision); - } - else // Sinon on utilise une instance au hasard (elles sont toutes identiques de toute façon) - NewtonConvexCollisionCalculateInertialMatrix(m_handles.begin()->second, inertiaMatrix, origin); - - if (inertia) - inertia->Set(inertiaMatrix); - - if (center) - center->Set(origin); - } - - float PhysGeom::ComputeVolume() const - { - float volume; - - // Si nous n'avons aucune instance, nous en créons une temporaire - if (m_handles.empty()) - { - PhysWorld world; - - NewtonCollision* collision = CreateHandle(&world); - { - volume = NewtonConvexCollisionCalculateVolume(collision); - } - NewtonDestroyCollision(collision); - } - else // Sinon on utilise une instance au hasard (elles sont toutes identiques de toute façon) - volume = NewtonConvexCollisionCalculateVolume(m_handles.begin()->second); - - return volume; - } - - NewtonCollision* PhysGeom::GetHandle(PhysWorld* world) const - { - auto it = m_handles.find(world); - if (it == m_handles.end()) - it = m_handles.insert(std::make_pair(world, CreateHandle(world))).first; - - return it->second; - } - - PhysGeomRef PhysGeom::Build(const PrimitiveList& list) - { - std::size_t primitiveCount = list.GetSize(); - if (primitiveCount > 1) - { - std::vector geoms(primitiveCount); - - for (unsigned int i = 0; i < primitiveCount; ++i) - geoms[i] = CreateGeomFromPrimitive(list.GetPrimitive(i)); - - return CompoundGeom::New(&geoms[0], primitiveCount); - } - else if (primitiveCount > 0) - return CreateGeomFromPrimitive(list.GetPrimitive(0)); - else - return NullGeom::New(); - } - - bool PhysGeom::Initialize() - { - if (!PhysGeomLibrary::Initialize()) - { - NazaraError("Failed to initialise library"); - return false; - } - - return true; - } - - void PhysGeom::Uninitialize() - { - PhysGeomLibrary::Uninitialize(); - } - - PhysGeomLibrary::LibraryMap PhysGeom::s_library; - - /********************************** BoxGeom **********************************/ - - BoxGeom::BoxGeom(const Vector3f& lengths, const Matrix4f& transformMatrix) : - m_matrix(transformMatrix), - m_lengths(lengths) - { - } - - BoxGeom::BoxGeom(const Vector3f& lengths, const Vector3f& translation, const Quaternionf& rotation) : - BoxGeom(lengths, Matrix4f::Transform(translation, rotation)) - { - } - - Boxf BoxGeom::ComputeAABB(const Matrix4f& offsetMatrix, const Vector3f& scale) const - { - Vector3f halfLengths(m_lengths * 0.5f); - - Boxf aabb(-halfLengths.x, -halfLengths.y, -halfLengths.z, m_lengths.x, m_lengths.y, m_lengths.z); - aabb.Transform(offsetMatrix, true); - aabb *= scale; - - return aabb; - } - - float BoxGeom::ComputeVolume() const - { - return m_lengths.x * m_lengths.y * m_lengths.z; - } - - Vector3f BoxGeom::GetLengths() const - { - return m_lengths; - } - - GeomType BoxGeom::GetType() const - { - return GeomType_Box; - } - - NewtonCollision* BoxGeom::CreateHandle(PhysWorld* world) const - { - return NewtonCreateBox(world->GetHandle(), m_lengths.x, m_lengths.y, m_lengths.z, 0, m_matrix); - } - - /******************************** CapsuleGeom ********************************/ - - CapsuleGeom::CapsuleGeom(float length, float radius, const Matrix4f& transformMatrix) : - m_matrix(transformMatrix), - m_length(length), - m_radius(radius) - { - } - - CapsuleGeom::CapsuleGeom(float length, float radius, const Vector3f& translation, const Quaternionf& rotation) : - CapsuleGeom(length, radius, Matrix4f::Transform(translation, rotation)) - { - } - - float CapsuleGeom::GetLength() const - { - return m_length; - } - - float CapsuleGeom::GetRadius() const - { - return m_radius; - } - - GeomType CapsuleGeom::GetType() const - { - return GeomType_Capsule; - } - - NewtonCollision* CapsuleGeom::CreateHandle(PhysWorld* world) const - { - return NewtonCreateCapsule(world->GetHandle(), m_radius, m_length, 0, m_matrix); - } - - /******************************* CompoundGeom ********************************/ - - CompoundGeom::CompoundGeom(PhysGeom** geoms, std::size_t geomCount) - { - m_geoms.reserve(geomCount); - for (std::size_t i = 0; i < geomCount; ++i) - m_geoms.emplace_back(geoms[i]); - } - - const std::vector& CompoundGeom::GetGeoms() const - { - return m_geoms; - } - - GeomType CompoundGeom::GetType() const - { - return GeomType_Compound; - } - - NewtonCollision* CompoundGeom::CreateHandle(PhysWorld* world) const - { - NewtonCollision* compoundCollision = NewtonCreateCompoundCollision(world->GetHandle(), 0); - - NewtonCompoundCollisionBeginAddRemove(compoundCollision); - for (const PhysGeomRef& geom : m_geoms) - { - if (geom->GetType() == GeomType_Compound) - { - CompoundGeom* compoundGeom = static_cast(geom.Get()); - for (const PhysGeomRef& piece : compoundGeom->GetGeoms()) - NewtonCompoundCollisionAddSubCollision(compoundCollision, piece->GetHandle(world)); - } - else - NewtonCompoundCollisionAddSubCollision(compoundCollision, geom->GetHandle(world)); - } - NewtonCompoundCollisionEndAddRemove(compoundCollision); - - return compoundCollision; - } - - /********************************* ConeGeom **********************************/ - - ConeGeom::ConeGeom(float length, float radius, const Matrix4f& transformMatrix) : - m_matrix(transformMatrix), - m_length(length), - m_radius(radius) - { - } - - ConeGeom::ConeGeom(float length, float radius, const Vector3f& translation, const Quaternionf& rotation) : - ConeGeom(length, radius, Matrix4f::Transform(translation, rotation)) - { - } - - float ConeGeom::GetLength() const - { - return m_length; - } - - float ConeGeom::GetRadius() const - { - return m_radius; - } - - GeomType ConeGeom::GetType() const - { - return GeomType_Cone; - } - - NewtonCollision* ConeGeom::CreateHandle(PhysWorld* world) const - { - return NewtonCreateCone(world->GetHandle(), m_radius, m_length, 0, m_matrix); - } - - /****************************** ConvexHullGeom *******************************/ - - ConvexHullGeom::ConvexHullGeom(const void* vertices, unsigned int vertexCount, unsigned int stride, float tolerance, const Matrix4f& transformMatrix) : - m_matrix(transformMatrix), - m_tolerance(tolerance), - m_vertexStride(stride) - { - const UInt8* ptr = static_cast(vertices); - - m_vertices.resize(vertexCount); - if (stride != sizeof(Vector3f)) - { - for (unsigned int i = 0; i < vertexCount; ++i) - m_vertices[i] = *reinterpret_cast(ptr + stride*i); - } - else // Fast path - std::memcpy(m_vertices.data(), vertices, vertexCount*sizeof(Vector3f)); - } - - ConvexHullGeom::ConvexHullGeom(const void* vertices, unsigned int vertexCount, unsigned int stride, float tolerance, const Vector3f& translation, const Quaternionf& rotation) : - ConvexHullGeom(vertices, vertexCount, stride, tolerance, Matrix4f::Transform(translation, rotation)) - { - } - - GeomType ConvexHullGeom::GetType() const - { - return GeomType_Compound; - } - - NewtonCollision* ConvexHullGeom::CreateHandle(PhysWorld* world) const - { - return NewtonCreateConvexHull(world->GetHandle(), static_cast(m_vertices.size()), reinterpret_cast(m_vertices.data()), sizeof(Vector3f), m_tolerance, 0, m_matrix); - } - - /******************************* CylinderGeom ********************************/ - - CylinderGeom::CylinderGeom(float length, float radius, const Matrix4f& transformMatrix) : - m_matrix(transformMatrix), - m_length(length), - m_radius(radius) - { - } - - CylinderGeom::CylinderGeom(float length, float radius, const Vector3f& translation, const Quaternionf& rotation) : - CylinderGeom(length, radius, Matrix4f::Transform(translation, rotation)) - { - } - - float CylinderGeom::GetLength() const - { - return m_length; - } - - float CylinderGeom::GetRadius() const - { - return m_radius; - } - - GeomType CylinderGeom::GetType() const - { - return GeomType_Cylinder; - } - - NewtonCollision* CylinderGeom::CreateHandle(PhysWorld* world) const - { - return NewtonCreateCylinder(world->GetHandle(), m_radius, m_length, 0, m_matrix); - } - - /********************************* NullGeom **********************************/ - - NullGeom::NullGeom() - { - } - - GeomType NullGeom::GetType() const - { - return GeomType_Null; - } - - void NullGeom::ComputeInertialMatrix(Vector3f* inertia, Vector3f* center) const - { - if (inertia) - inertia->MakeUnit(); - - if (center) - center->MakeZero(); - } - - NewtonCollision* NullGeom::CreateHandle(PhysWorld* world) const - { - return NewtonCreateNull(world->GetHandle()); - } - - /******************************** SphereGeom *********************************/ - - SphereGeom::SphereGeom(float radius, const Matrix4f& transformMatrix) : - SphereGeom(radius, transformMatrix.GetTranslation()) - { - } - - SphereGeom::SphereGeom(float radius, const Vector3f& translation, const Quaternionf& rotation) : - m_position(translation), - m_radius(radius) - { - NazaraUnused(rotation); - } - - Boxf SphereGeom::ComputeAABB(const Matrix4f& offsetMatrix, const Vector3f& scale) const - { - Vector3f size(m_radius * NazaraSuffixMacro(M_SQRT3, f) * scale); - Vector3f position(offsetMatrix.GetTranslation()); - - return Boxf(position - size, position + size); - } - - float SphereGeom::ComputeVolume() const - { - return float(M_PI) * m_radius * m_radius * m_radius / 3.f; - } - - float SphereGeom::GetRadius() const - { - return m_radius; - } - - GeomType SphereGeom::GetType() const - { - return GeomType_Sphere; - } - - NewtonCollision* SphereGeom::CreateHandle(PhysWorld* world) const - { - return NewtonCreateSphere(world->GetHandle(), m_radius, 0, Matrix4f::Translate(m_position)); - } -} diff --git a/src/Nazara/Physics2D/Collider2D.cpp b/src/Nazara/Physics2D/Collider2D.cpp new file mode 100644 index 000000000..a840393e8 --- /dev/null +++ b/src/Nazara/Physics2D/Collider2D.cpp @@ -0,0 +1,87 @@ +// Copyright (C) 2015 Jérôme Leclercq +// This file is part of the "Nazara Engine - Physics 2D module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#include +#include +#include +#include + +namespace Nz +{ + Collider2D::~Collider2D() = default; + + /******************************** BoxCollider2D *********************************/ + + BoxCollider2D::BoxCollider2D(const Vector2f& size, float radius) : + BoxCollider2D(Rectf(-size.x / 2.f, -size.y / 2.f, size.x / 2.f, size.y / 2.f), radius) + { + } + + BoxCollider2D::BoxCollider2D(const Rectf& rect, float radius) : + m_rect(rect), + m_radius(radius) + { + } + + float BoxCollider2D::ComputeInertialMatrix(float mass) const + { + return static_cast(cpMomentForBox2(mass, cpBBNew(m_rect.x, m_rect.y + m_rect.height, m_rect.x + m_rect.width, m_rect.y))); + } + + ColliderType2D BoxCollider2D::GetType() const + { + return ColliderType2D_Box; + } + + std::vector BoxCollider2D::CreateShapes(RigidBody2D* body) const + { + std::vector shapes; + shapes.push_back(cpBoxShapeNew2(body->GetHandle(), cpBBNew(m_rect.x, m_rect.y + m_rect.height, m_rect.x + m_rect.width, m_rect.y), m_radius)); + + return shapes; + } + + /******************************** CircleCollider2D *********************************/ + + CircleCollider2D::CircleCollider2D(float radius, const Vector2f& offset) : + m_offset(offset), + m_radius(radius) + { + } + + float CircleCollider2D::ComputeInertialMatrix(float mass) const + { + return static_cast(cpMomentForCircle(mass, 0.f, m_radius, cpv(m_offset.x, m_offset.y))); + } + + ColliderType2D CircleCollider2D::GetType() const + { + return ColliderType2D_Circle; + } + + std::vector CircleCollider2D::CreateShapes(RigidBody2D* body) const + { + std::vector shapes; + shapes.push_back(cpCircleShapeNew(body->GetHandle(), m_radius, cpv(m_offset.x, m_offset.y))); + + return shapes; + } + + /********************************* NullCollider2D **********************************/ + + ColliderType2D NullCollider2D::GetType() const + { + return ColliderType2D_Null; + } + + float NullCollider2D::ComputeInertialMatrix(float /*mass*/) const + { + return 0.f; + } + + std::vector NullCollider2D::CreateShapes(RigidBody2D* /*body*/) const + { + return std::vector(); + } +} diff --git a/src/Nazara/Physics/Debug/NewOverload.cpp b/src/Nazara/Physics2D/Debug/NewOverload.cpp similarity index 86% rename from src/Nazara/Physics/Debug/NewOverload.cpp rename to src/Nazara/Physics2D/Debug/NewOverload.cpp index b7ca2c243..bd3153d1d 100644 --- a/src/Nazara/Physics/Debug/NewOverload.cpp +++ b/src/Nazara/Physics2D/Debug/NewOverload.cpp @@ -1,8 +1,8 @@ // Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Physics module" +// This file is part of the "Nazara Engine - Physics 2D module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include +#include #if NAZARA_PHYSICS_MANAGE_MEMORY #include diff --git a/src/Nazara/Physics2D/PhysWorld2D.cpp b/src/Nazara/Physics2D/PhysWorld2D.cpp new file mode 100644 index 000000000..5290abfcd --- /dev/null +++ b/src/Nazara/Physics2D/PhysWorld2D.cpp @@ -0,0 +1,60 @@ +// Copyright (C) 2015 Jérôme Leclercq +// This file is part of the "Nazara Engine - Physics 2D module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#include +#include +#include + +namespace Nz +{ + PhysWorld2D::PhysWorld2D() : + m_stepSize(0.005f), + m_timestepAccumulator(0.f) + { + m_handle = cpSpaceNew(); + cpSpaceSetUserData(m_handle, this); + } + + PhysWorld2D::~PhysWorld2D() + { + cpSpaceFree(m_handle); + } + + Vector2f PhysWorld2D::GetGravity() const + { + cpVect gravity = cpSpaceGetGravity(m_handle); + return Vector2f(gravity.x, gravity.y); + } + + cpSpace* PhysWorld2D::GetHandle() const + { + return m_handle; + } + + float PhysWorld2D::GetStepSize() const + { + return m_stepSize; + } + + void PhysWorld2D::SetGravity(const Vector2f& gravity) + { + cpSpaceSetGravity(m_handle, cpv(gravity.x, gravity.y)); + } + + void PhysWorld2D::SetStepSize(float stepSize) + { + m_stepSize = stepSize; + } + + void PhysWorld2D::Step(float timestep) + { + m_timestepAccumulator += timestep; + + while (m_timestepAccumulator >= m_stepSize) + { + cpSpaceStep(m_handle, m_stepSize); + m_timestepAccumulator -= m_stepSize; + } + } +} diff --git a/src/Nazara/Physics2D/Physics2D.cpp b/src/Nazara/Physics2D/Physics2D.cpp new file mode 100644 index 000000000..840b14755 --- /dev/null +++ b/src/Nazara/Physics2D/Physics2D.cpp @@ -0,0 +1,59 @@ +// Copyright (C) 2015 Jérôme Leclercq +// This file is part of the "Nazara Engine - Physics 2D module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#include +#include +#include +#include + +namespace Nz +{ + bool Physics2D::Initialize() + { + if (s_moduleReferenceCounter > 0) + { + s_moduleReferenceCounter++; + return true; // Déjà initialisé + } + + // Initialisation des dépendances + if (!Core::Initialize()) + { + NazaraError("Failed to initialize core module"); + return false; + } + + s_moduleReferenceCounter++; + + NazaraNotice("Initialized: Physics2D module"); + return true; + } + + bool Physics2D::IsInitialized() + { + return s_moduleReferenceCounter != 0; + } + + void Physics2D::Uninitialize() + { + if (s_moduleReferenceCounter != 1) + { + // Le module est soit encore utilisé, soit pas initialisé + if (s_moduleReferenceCounter > 1) + s_moduleReferenceCounter--; + + return; + } + + // Libération du module + s_moduleReferenceCounter = 0; + + NazaraNotice("Uninitialized: Physics2D module"); + + // Libération des dépendances + Core::Uninitialize(); + } + + unsigned int Physics2D::s_moduleReferenceCounter = 0; +} diff --git a/src/Nazara/Physics2D/RigidBody2D.cpp b/src/Nazara/Physics2D/RigidBody2D.cpp new file mode 100644 index 000000000..faa6223d1 --- /dev/null +++ b/src/Nazara/Physics2D/RigidBody2D.cpp @@ -0,0 +1,251 @@ +// Copyright (C) 2015 Jérôme Leclercq +// This file is part of the "Nazara Engine - Physics 2D module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Nz +{ + RigidBody2D::RigidBody2D(PhysWorld2D* world, float mass) : + RigidBody2D(world, mass, nullptr) + { + } + + RigidBody2D::RigidBody2D(PhysWorld2D* world, float mass, Collider2DRef geom) : + m_geom(), + m_world(world), + m_gravityFactor(1.f), + m_mass(0.f) + { + NazaraAssert(m_world, "Invalid world"); + + m_handle = cpBodyNew(0.f, 0.f); + cpBodySetUserData(m_handle, this); + cpSpaceAddBody(m_world->GetHandle(), m_handle); + + SetGeom(geom); + SetMass(mass); + } + + RigidBody2D::RigidBody2D(const RigidBody2D& object) : + m_geom(object.m_geom), + m_world(object.m_world), + m_gravityFactor(object.m_gravityFactor), + m_mass(0.f) + { + NazaraAssert(m_world, "Invalid world"); + NazaraAssert(m_geom, "Invalid geometry"); + + m_handle = cpBodyNew(0.f, 0.f); + cpBodySetUserData(m_handle, this); + cpSpaceAddBody(m_world->GetHandle(), m_handle); + + SetGeom(object.GetGeom()); + SetMass(object.GetMass()); + } + + RigidBody2D::RigidBody2D(RigidBody2D&& object) : + m_shapes(std::move(object.m_shapes)), + m_geom(std::move(object.m_geom)), + m_handle(object.m_handle), + m_world(object.m_world), + m_gravityFactor(object.m_gravityFactor), + m_mass(object.m_mass) + { + object.m_handle = nullptr; + } + + RigidBody2D::~RigidBody2D() + { + Destroy(); + } + + void RigidBody2D::AddForce(const Vector2f& force, CoordSys coordSys) + { + return AddForce(force, GetCenterOfGravity(coordSys), coordSys); + } + + void RigidBody2D::AddForce(const Vector2f& force, const Vector2f& point, CoordSys coordSys) + { + switch (coordSys) + { + case CoordSys_Global: + cpBodyApplyForceAtWorldPoint(m_handle, cpv(force.x, force.y), cpv(force.x, force.y)); + break; + + case CoordSys_Local: + cpBodyApplyForceAtLocalPoint(m_handle, cpv(force.x, force.y), cpv(point.x, point.y)); + break; + } + } + + void RigidBody2D::AddTorque(float torque) + { + cpBodySetTorque(m_handle, cpBodyGetTorque(m_handle) + torque); + } + + Rectf RigidBody2D::GetAABB() const + { + cpBB bb = cpBBNew(0.f, 0.f, 0.f, 0.f); + for (cpShape* shape : m_shapes) + bb = cpBBMerge(bb, cpShapeGetBB(shape)); + + return Rectf(Rect(bb.l, bb.t, bb.r - bb.l, bb.b - bb.t)); + } + + float RigidBody2D::GetAngularVelocity() const + { + return static_cast(cpBodyGetAngularVelocity(m_handle)); + } + + const Collider2DRef& RigidBody2D::GetGeom() const + { + return m_geom; + } + + cpBody* RigidBody2D::GetHandle() const + { + return m_handle; + } + + float RigidBody2D::GetMass() const + { + return m_mass; + } + + Vector2f RigidBody2D::GetCenterOfGravity(CoordSys coordSys) const + { + cpVect cog = cpBodyGetCenterOfGravity(m_handle); + + switch (coordSys) + { + case CoordSys_Global: + cog = cpBodyLocalToWorld(m_handle, cog); + break; + + case CoordSys_Local: + break; // Nothing to do + } + + return Vector2f(static_cast(cog.x), static_cast(cog.y)); + } + + Vector2f RigidBody2D::GetPosition() const + { + cpVect pos = cpBodyGetPosition(m_handle); + return Vector2f(static_cast(pos.x), static_cast(pos.y)); + } + + float RigidBody2D::GetRotation() const + { + return static_cast(cpBodyGetAngle(m_handle)); + } + + Vector2f RigidBody2D::GetVelocity() const + { + cpVect vel = cpBodyGetVelocity(m_handle); + return Vector2f(static_cast(vel.x), static_cast(vel.y)); + } + + bool RigidBody2D::IsMoveable() const + { + return m_mass > 0.f; + } + + bool RigidBody2D::IsSleeping() const + { + return cpBodyIsSleeping(m_handle) != 0; + } + + void RigidBody2D::SetAngularVelocity(float angularVelocity) + { + cpBodySetAngularVelocity(m_handle, angularVelocity); + } + + void RigidBody2D::SetMass(float mass) + { + if (m_mass > 0.f) + { + if (mass > 0.f) + cpBodySetMass(m_handle, mass); + else + cpBodySetType(m_handle, CP_BODY_TYPE_STATIC); + } + else if (mass > 0.f) + { + if (cpBodyGetType(m_handle) == CP_BODY_TYPE_STATIC) + cpBodySetType(m_handle, CP_BODY_TYPE_DYNAMIC); + } + + m_mass = mass; + } + + void RigidBody2D::SetMassCenter(const Vector2f& center) + { + if (m_mass > 0.f) + cpBodySetCenterOfGravity(m_handle, cpv(center.x, center.y)); + } + + void RigidBody2D::SetPosition(const Vector2f& position) + { + cpBodySetPosition(m_handle, cpv(position.x, position.y)); + } + + void RigidBody2D::SetRotation(float rotation) + { + cpBodySetAngle(m_handle, rotation); + } + + void RigidBody2D::SetVelocity(const Vector2f& velocity) + { + cpBodySetVelocity(m_handle, cpv(velocity.x, velocity.y)); + } + + RigidBody2D& RigidBody2D::operator=(const RigidBody2D& object) + { + RigidBody2D physObj(object); + return operator=(std::move(physObj)); + } + + RigidBody2D& RigidBody2D::operator=(RigidBody2D&& object) + { + Destroy(); + + m_handle = object.m_handle; + m_geom = std::move(object.m_geom); + m_gravityFactor = object.m_gravityFactor; + m_mass = object.m_mass; + m_shapes = std::move(object.m_shapes); + m_world = object.m_world; + + object.m_handle = nullptr; + + return *this; + } + + void RigidBody2D::Destroy() + { + for (cpShape* shape : m_shapes) + cpShapeFree(shape); + + if (m_handle) + cpBodyFree(m_handle); + } + + void RigidBody2D::SetGeom(Collider2DRef geom) + { + if (geom) + m_geom = geom; + else + m_geom = NullCollider2D::New(); + + m_shapes = m_geom->CreateShapes(this); + } +} diff --git a/src/Nazara/Physics3D/Collider3D.cpp b/src/Nazara/Physics3D/Collider3D.cpp new file mode 100644 index 000000000..7cddffdbe --- /dev/null +++ b/src/Nazara/Physics3D/Collider3D.cpp @@ -0,0 +1,445 @@ +// Copyright (C) 2015 Jérôme Leclercq +// This file is part of the "Nazara Engine - Physics 3D module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#include +#include +#include +#include +#include + +namespace Nz +{ + namespace + { + Collider3DRef CreateGeomFromPrimitive(const Primitive& primitive) + { + switch (primitive.type) + { + case PrimitiveType_Box: + return BoxCollider3D::New(primitive.box.lengths, primitive.matrix); + + case PrimitiveType_Cone: + return ConeCollider3D::New(primitive.cone.length, primitive.cone.radius, primitive.matrix); + + case PrimitiveType_Plane: + return BoxCollider3D::New(Vector3f(primitive.plane.size.x, 0.01f, primitive.plane.size.y), primitive.matrix); + ///TODO: PlaneGeom? + + case PrimitiveType_Sphere: + return SphereCollider3D::New(primitive.sphere.size, primitive.matrix.GetTranslation()); + } + + NazaraError("Primitive type not handled (0x" + String::Number(primitive.type, 16) + ')'); + return Collider3DRef(); + } + } + + Collider3D::~Collider3D() + { + for (auto& pair : m_handles) + NewtonDestroyCollision(pair.second); + } + + Boxf Collider3D::ComputeAABB(const Vector3f& translation, const Quaternionf& rotation, const Vector3f& scale) const + { + return ComputeAABB(Matrix4f::Transform(translation, rotation), scale); + } + + Boxf Collider3D::ComputeAABB(const Matrix4f& offsetMatrix, const Vector3f& scale) const + { + Vector3f min, max; + + // Si nous n'avons aucune instance, nous en créons une temporaire + if (m_handles.empty()) + { + PhysWorld3D world; + + NewtonCollision* collision = CreateHandle(&world); + { + NewtonCollisionCalculateAABB(collision, offsetMatrix, min, max); + } + NewtonDestroyCollision(collision); + } + else // Sinon on utilise une instance au hasard (elles sont toutes identiques de toute façon) + NewtonCollisionCalculateAABB(m_handles.begin()->second, offsetMatrix, min, max); + + return Boxf(scale * min, scale * max); + } + + void Collider3D::ComputeInertialMatrix(Vector3f* inertia, Vector3f* center) const + { + float inertiaMatrix[3]; + float origin[3]; + + // Si nous n'avons aucune instance, nous en créons une temporaire + if (m_handles.empty()) + { + PhysWorld3D world; + + NewtonCollision* collision = CreateHandle(&world); + { + NewtonConvexCollisionCalculateInertialMatrix(collision, inertiaMatrix, origin); + } + NewtonDestroyCollision(collision); + } + else // Sinon on utilise une instance au hasard (elles sont toutes identiques de toute façon) + NewtonConvexCollisionCalculateInertialMatrix(m_handles.begin()->second, inertiaMatrix, origin); + + if (inertia) + inertia->Set(inertiaMatrix); + + if (center) + center->Set(origin); + } + + float Collider3D::ComputeVolume() const + { + float volume; + + // Si nous n'avons aucune instance, nous en créons une temporaire + if (m_handles.empty()) + { + PhysWorld3D world; + + NewtonCollision* collision = CreateHandle(&world); + { + volume = NewtonConvexCollisionCalculateVolume(collision); + } + NewtonDestroyCollision(collision); + } + else // Sinon on utilise une instance au hasard (elles sont toutes identiques de toute façon) + volume = NewtonConvexCollisionCalculateVolume(m_handles.begin()->second); + + return volume; + } + + NewtonCollision* Collider3D::GetHandle(PhysWorld3D* world) const + { + auto it = m_handles.find(world); + if (it == m_handles.end()) + it = m_handles.insert(std::make_pair(world, CreateHandle(world))).first; + + return it->second; + } + + Collider3DRef Collider3D::Build(const PrimitiveList& list) + { + std::size_t primitiveCount = list.GetSize(); + if (primitiveCount > 1) + { + std::vector geoms(primitiveCount); + + for (unsigned int i = 0; i < primitiveCount; ++i) + geoms[i] = CreateGeomFromPrimitive(list.GetPrimitive(i)); + + return CompoundCollider3D::New(&geoms[0], primitiveCount); + } + else if (primitiveCount > 0) + return CreateGeomFromPrimitive(list.GetPrimitive(0)); + else + return NullCollider3D::New(); + } + + bool Collider3D::Initialize() + { + if (!Collider3DLibrary::Initialize()) + { + NazaraError("Failed to initialise library"); + return false; + } + + return true; + } + + void Collider3D::Uninitialize() + { + Collider3DLibrary::Uninitialize(); + } + + Collider3DLibrary::LibraryMap Collider3D::s_library; + + /********************************** BoxCollider3D **********************************/ + + BoxCollider3D::BoxCollider3D(const Vector3f& lengths, const Matrix4f& transformMatrix) : + m_matrix(transformMatrix), + m_lengths(lengths) + { + } + + BoxCollider3D::BoxCollider3D(const Vector3f& lengths, const Vector3f& translation, const Quaternionf& rotation) : + BoxCollider3D(lengths, Matrix4f::Transform(translation, rotation)) + { + } + + Boxf BoxCollider3D::ComputeAABB(const Matrix4f& offsetMatrix, const Vector3f& scale) const + { + Vector3f halfLengths(m_lengths * 0.5f); + + Boxf aabb(-halfLengths.x, -halfLengths.y, -halfLengths.z, m_lengths.x, m_lengths.y, m_lengths.z); + aabb.Transform(offsetMatrix, true); + aabb *= scale; + + return aabb; + } + + float BoxCollider3D::ComputeVolume() const + { + return m_lengths.x * m_lengths.y * m_lengths.z; + } + + Vector3f BoxCollider3D::GetLengths() const + { + return m_lengths; + } + + ColliderType3D BoxCollider3D::GetType() const + { + return ColliderType3D_Box; + } + + NewtonCollision* BoxCollider3D::CreateHandle(PhysWorld3D* world) const + { + return NewtonCreateBox(world->GetHandle(), m_lengths.x, m_lengths.y, m_lengths.z, 0, m_matrix); + } + + /******************************** CapsuleCollider3D ********************************/ + + CapsuleCollider3D::CapsuleCollider3D(float length, float radius, const Matrix4f& transformMatrix) : + m_matrix(transformMatrix), + m_length(length), + m_radius(radius) + { + } + + CapsuleCollider3D::CapsuleCollider3D(float length, float radius, const Vector3f& translation, const Quaternionf& rotation) : + CapsuleCollider3D(length, radius, Matrix4f::Transform(translation, rotation)) + { + } + + float CapsuleCollider3D::GetLength() const + { + return m_length; + } + + float CapsuleCollider3D::GetRadius() const + { + return m_radius; + } + + ColliderType3D CapsuleCollider3D::GetType() const + { + return ColliderType3D_Capsule; + } + + NewtonCollision* CapsuleCollider3D::CreateHandle(PhysWorld3D* world) const + { + return NewtonCreateCapsule(world->GetHandle(), m_radius, m_length, 0, m_matrix); + } + + /******************************* CompoundCollider3D ********************************/ + + CompoundCollider3D::CompoundCollider3D(Collider3D** geoms, std::size_t geomCount) + { + m_geoms.reserve(geomCount); + for (std::size_t i = 0; i < geomCount; ++i) + m_geoms.emplace_back(geoms[i]); + } + + const std::vector& CompoundCollider3D::GetGeoms() const + { + return m_geoms; + } + + ColliderType3D CompoundCollider3D::GetType() const + { + return ColliderType3D_Compound; + } + + NewtonCollision* CompoundCollider3D::CreateHandle(PhysWorld3D* world) const + { + NewtonCollision* compoundCollision = NewtonCreateCompoundCollision(world->GetHandle(), 0); + + NewtonCompoundCollisionBeginAddRemove(compoundCollision); + for (const Collider3DRef& geom : m_geoms) + { + if (geom->GetType() == ColliderType3D_Compound) + { + CompoundCollider3D* compoundGeom = static_cast(geom.Get()); + for (const Collider3DRef& piece : compoundGeom->GetGeoms()) + NewtonCompoundCollisionAddSubCollision(compoundCollision, piece->GetHandle(world)); + } + else + NewtonCompoundCollisionAddSubCollision(compoundCollision, geom->GetHandle(world)); + } + NewtonCompoundCollisionEndAddRemove(compoundCollision); + + return compoundCollision; + } + + /********************************* ConeCollider3D **********************************/ + + ConeCollider3D::ConeCollider3D(float length, float radius, const Matrix4f& transformMatrix) : + m_matrix(transformMatrix), + m_length(length), + m_radius(radius) + { + } + + ConeCollider3D::ConeCollider3D(float length, float radius, const Vector3f& translation, const Quaternionf& rotation) : + ConeCollider3D(length, radius, Matrix4f::Transform(translation, rotation)) + { + } + + float ConeCollider3D::GetLength() const + { + return m_length; + } + + float ConeCollider3D::GetRadius() const + { + return m_radius; + } + + ColliderType3D ConeCollider3D::GetType() const + { + return ColliderType3D_Cone; + } + + NewtonCollision* ConeCollider3D::CreateHandle(PhysWorld3D* world) const + { + return NewtonCreateCone(world->GetHandle(), m_radius, m_length, 0, m_matrix); + } + + /****************************** ConvexCollider3D *******************************/ + + ConvexCollider3D::ConvexCollider3D(SparsePtr vertices, unsigned int vertexCount, float tolerance, const Matrix4f& transformMatrix) : + m_matrix(transformMatrix), + m_tolerance(tolerance) + { + m_vertices.resize(vertexCount); + if (vertices.GetStride() != sizeof(Vector3f)) + { + for (unsigned int i = 0; i < vertexCount; ++i) + m_vertices[i] = *vertices++; + } + else // Fast path + std::memcpy(m_vertices.data(), vertices, vertexCount*sizeof(Vector3f)); + } + + ConvexCollider3D::ConvexCollider3D(SparsePtr vertices, unsigned int vertexCount, float tolerance, const Vector3f& translation, const Quaternionf& rotation) : + ConvexCollider3D(vertices, vertexCount, tolerance, Matrix4f::Transform(translation, rotation)) + { + } + + ColliderType3D ConvexCollider3D::GetType() const + { + return ColliderType3D_Compound; + } + + NewtonCollision* ConvexCollider3D::CreateHandle(PhysWorld3D* world) const + { + return NewtonCreateConvexHull(world->GetHandle(), static_cast(m_vertices.size()), reinterpret_cast(m_vertices.data()), sizeof(Vector3f), m_tolerance, 0, m_matrix); + } + + /******************************* CylinderCollider3D ********************************/ + + CylinderCollider3D::CylinderCollider3D(float length, float radius, const Matrix4f& transformMatrix) : + m_matrix(transformMatrix), + m_length(length), + m_radius(radius) + { + } + + CylinderCollider3D::CylinderCollider3D(float length, float radius, const Vector3f& translation, const Quaternionf& rotation) : + CylinderCollider3D(length, radius, Matrix4f::Transform(translation, rotation)) + { + } + + float CylinderCollider3D::GetLength() const + { + return m_length; + } + + float CylinderCollider3D::GetRadius() const + { + return m_radius; + } + + ColliderType3D CylinderCollider3D::GetType() const + { + return ColliderType3D_Cylinder; + } + + NewtonCollision* CylinderCollider3D::CreateHandle(PhysWorld3D* world) const + { + return NewtonCreateCylinder(world->GetHandle(), m_radius, m_length, 0, m_matrix); + } + + /********************************* NullCollider3D **********************************/ + + NullCollider3D::NullCollider3D() + { + } + + ColliderType3D NullCollider3D::GetType() const + { + return ColliderType3D_Null; + } + + void NullCollider3D::ComputeInertialMatrix(Vector3f* inertia, Vector3f* center) const + { + if (inertia) + inertia->MakeUnit(); + + if (center) + center->MakeZero(); + } + + NewtonCollision* NullCollider3D::CreateHandle(PhysWorld3D* world) const + { + return NewtonCreateNull(world->GetHandle()); + } + + /******************************** SphereCollider3D *********************************/ + + SphereCollider3D::SphereCollider3D(float radius, const Matrix4f& transformMatrix) : + SphereCollider3D(radius, transformMatrix.GetTranslation()) + { + } + + SphereCollider3D::SphereCollider3D(float radius, const Vector3f& translation, const Quaternionf& rotation) : + m_position(translation), + m_radius(radius) + { + NazaraUnused(rotation); + } + + Boxf SphereCollider3D::ComputeAABB(const Matrix4f& offsetMatrix, const Vector3f& scale) const + { + Vector3f size(m_radius * NazaraSuffixMacro(M_SQRT3, f) * scale); + Vector3f position(offsetMatrix.GetTranslation()); + + return Boxf(position - size, position + size); + } + + float SphereCollider3D::ComputeVolume() const + { + return float(M_PI) * m_radius * m_radius * m_radius / 3.f; + } + + float SphereCollider3D::GetRadius() const + { + return m_radius; + } + + ColliderType3D SphereCollider3D::GetType() const + { + return ColliderType3D_Sphere; + } + + NewtonCollision* SphereCollider3D::CreateHandle(PhysWorld3D* world) const + { + return NewtonCreateSphere(world->GetHandle(), m_radius, 0, Matrix4f::Translate(m_position)); + } +} diff --git a/src/Nazara/Physics3D/Debug/NewOverload.cpp b/src/Nazara/Physics3D/Debug/NewOverload.cpp new file mode 100644 index 000000000..18092514c --- /dev/null +++ b/src/Nazara/Physics3D/Debug/NewOverload.cpp @@ -0,0 +1,31 @@ +// Copyright (C) 2015 Jérôme Leclercq +// This file is part of the "Nazara Engine - Physics 3D module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#include +#if NAZARA_PHYSICS_MANAGE_MEMORY + +#include +#include // Nécessaire ? + +void* operator new(std::size_t size) +{ + return Nz::MemoryManager::Allocate(size, false); +} + +void* operator new[](std::size_t size) +{ + return Nz::MemoryManager::Allocate(size, true); +} + +void operator delete(void* pointer) noexcept +{ + Nz::MemoryManager::Free(pointer, false); +} + +void operator delete[](void* pointer) noexcept +{ + Nz::MemoryManager::Free(pointer, true); +} + +#endif // NAZARA_PHYSICS_MANAGE_MEMORY diff --git a/src/Nazara/Physics/PhysWorld.cpp b/src/Nazara/Physics3D/PhysWorld3D.cpp similarity index 57% rename from src/Nazara/Physics/PhysWorld.cpp rename to src/Nazara/Physics3D/PhysWorld3D.cpp index a3d76429b..c6990f635 100644 --- a/src/Nazara/Physics/PhysWorld.cpp +++ b/src/Nazara/Physics3D/PhysWorld3D.cpp @@ -1,14 +1,14 @@ // Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Physics module" +// This file is part of the "Nazara Engine - Physics 3D module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include +#include #include -#include +#include namespace Nz { - PhysWorld::PhysWorld() : + PhysWorld3D::PhysWorld3D() : m_gravity(Vector3f::Zero()), m_stepSize(0.005f), m_timestepAccumulator(0.f) @@ -17,42 +17,42 @@ namespace Nz NewtonWorldSetUserData(m_world, this); } - PhysWorld::~PhysWorld() + PhysWorld3D::~PhysWorld3D() { NewtonDestroy(m_world); } - Vector3f PhysWorld::GetGravity() const + Vector3f PhysWorld3D::GetGravity() const { return m_gravity; } - NewtonWorld* PhysWorld::GetHandle() const + NewtonWorld* PhysWorld3D::GetHandle() const { return m_world; } - float PhysWorld::GetStepSize() const + float PhysWorld3D::GetStepSize() const { return m_stepSize; } - void PhysWorld::SetGravity(const Vector3f& gravity) + void PhysWorld3D::SetGravity(const Vector3f& gravity) { m_gravity = gravity; } - void PhysWorld::SetSolverModel(unsigned int model) + void PhysWorld3D::SetSolverModel(unsigned int model) { NewtonSetSolverModel(m_world, model); } - void PhysWorld::SetStepSize(float stepSize) + void PhysWorld3D::SetStepSize(float stepSize) { m_stepSize = stepSize; } - void PhysWorld::Step(float timestep) + void PhysWorld3D::Step(float timestep) { m_timestepAccumulator += timestep; diff --git a/src/Nazara/Physics/Physics.cpp b/src/Nazara/Physics3D/Physics3D.cpp similarity index 64% rename from src/Nazara/Physics/Physics.cpp rename to src/Nazara/Physics3D/Physics3D.cpp index 584c334ab..8fb470f2a 100644 --- a/src/Nazara/Physics/Physics.cpp +++ b/src/Nazara/Physics3D/Physics3D.cpp @@ -1,24 +1,24 @@ // Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Physics module" +// This file is part of the "Nazara Engine - Physics 3D module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include +#include #include #include #include -#include -#include +#include +#include #include -#include +#include namespace Nz { - unsigned int Physics::GetMemoryUsed() + unsigned int Physics3D::GetMemoryUsed() { return NewtonGetMemoryUsed(); } - bool Physics::Initialize() + bool Physics3D::Initialize() { if (s_moduleReferenceCounter > 0) { @@ -36,22 +36,22 @@ namespace Nz s_moduleReferenceCounter++; // Initialisation du module - if (!PhysGeom::Initialize()) + if (!Collider3D::Initialize()) { NazaraError("Failed to initialize geoms"); return false; } - NazaraNotice("Initialized: Physics module"); + NazaraNotice("Initialized: Physics3D module"); return true; } - bool Physics::IsInitialized() + bool Physics3D::IsInitialized() { return s_moduleReferenceCounter != 0; } - void Physics::Uninitialize() + void Physics3D::Uninitialize() { if (s_moduleReferenceCounter != 1) { @@ -63,15 +63,15 @@ namespace Nz } // Libération du module - PhysGeom::Uninitialize(); + Collider3D::Uninitialize(); s_moduleReferenceCounter = 0; - NazaraNotice("Uninitialized: Physics module"); + NazaraNotice("Uninitialized: Physics3D module"); // Libération des dépendances Core::Uninitialize(); } - unsigned int Physics::s_moduleReferenceCounter = 0; + unsigned int Physics3D::s_moduleReferenceCounter = 0; } diff --git a/src/Nazara/Physics/PhysObject.cpp b/src/Nazara/Physics3D/RigidBody3D.cpp similarity index 67% rename from src/Nazara/Physics/PhysObject.cpp rename to src/Nazara/Physics3D/RigidBody3D.cpp index 1ee4a44d5..5051fa143 100644 --- a/src/Nazara/Physics/PhysObject.cpp +++ b/src/Nazara/Physics3D/RigidBody3D.cpp @@ -1,25 +1,25 @@ // Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Physics module" +// This file is part of the "Nazara Engine - Physics 3D module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include +#include #include -#include -#include +#include +#include #include #include -#include +#include namespace Nz { - PhysObject::PhysObject(PhysWorld* world, const Matrix4f& mat) : - PhysObject(world, NullGeom::New(), mat) + RigidBody3D::RigidBody3D(PhysWorld3D* world, const Matrix4f& mat) : + RigidBody3D(world, NullCollider3D::New(), mat) { } - PhysObject::PhysObject(PhysWorld* world, PhysGeomRef geom, const Matrix4f& mat) : - m_matrix(mat), + RigidBody3D::RigidBody3D(PhysWorld3D* world, Collider3DRef geom, const Matrix4f& mat) : m_geom(std::move(geom)), + m_matrix(mat), m_forceAccumulator(Vector3f::Zero()), m_torqueAccumulator(Vector3f::Zero()), m_world(world), @@ -29,15 +29,15 @@ namespace Nz NazaraAssert(m_world, "Invalid world"); if (!m_geom) - m_geom = NullGeom::New(); + m_geom = NullCollider3D::New(); m_body = NewtonCreateDynamicBody(m_world->GetHandle(), m_geom->GetHandle(m_world), m_matrix); NewtonBodySetUserData(m_body, this); } - PhysObject::PhysObject(const PhysObject& object) : - m_matrix(object.m_matrix), + RigidBody3D::RigidBody3D(const RigidBody3D& object) : m_geom(object.m_geom), + m_matrix(object.m_matrix), m_forceAccumulator(Vector3f::Zero()), m_torqueAccumulator(Vector3f::Zero()), m_world(object.m_world), @@ -52,9 +52,9 @@ namespace Nz SetMass(object.m_mass); } - PhysObject::PhysObject(PhysObject&& object) : - m_matrix(std::move(object.m_matrix)), + RigidBody3D::RigidBody3D(RigidBody3D&& object) : m_geom(std::move(object.m_geom)), + m_matrix(std::move(object.m_matrix)), m_forceAccumulator(std::move(object.m_forceAccumulator)), m_torqueAccumulator(std::move(object.m_torqueAccumulator)), m_body(object.m_body), @@ -65,13 +65,13 @@ namespace Nz object.m_body = nullptr; } - PhysObject::~PhysObject() + RigidBody3D::~RigidBody3D() { if (m_body) NewtonDestroyBody(m_body); } - void PhysObject::AddForce(const Vector3f& force, CoordSys coordSys) + void RigidBody3D::AddForce(const Vector3f& force, CoordSys coordSys) { switch (coordSys) { @@ -88,7 +88,7 @@ namespace Nz NewtonBodySetSleepState(m_body, 0); } - void PhysObject::AddForce(const Vector3f& force, const Vector3f& point, CoordSys coordSys) + void RigidBody3D::AddForce(const Vector3f& force, const Vector3f& point, CoordSys coordSys) { switch (coordSys) { @@ -105,7 +105,7 @@ namespace Nz NewtonBodySetSleepState(m_body, 0); } - void PhysObject::AddTorque(const Vector3f& torque, CoordSys coordSys) + void RigidBody3D::AddTorque(const Vector3f& torque, CoordSys coordSys) { switch (coordSys) { @@ -122,12 +122,12 @@ namespace Nz NewtonBodySetSleepState(m_body, 0); } - void PhysObject::EnableAutoSleep(bool autoSleep) + void RigidBody3D::EnableAutoSleep(bool autoSleep) { NewtonBodySetAutoSleep(m_body, autoSleep); } - Boxf PhysObject::GetAABB() const + Boxf RigidBody3D::GetAABB() const { Vector3f min, max; NewtonBodyGetAABB(m_body, min, max); @@ -135,7 +135,7 @@ namespace Nz return Boxf(min, max); } - Vector3f PhysObject::GetAngularVelocity() const + Vector3f RigidBody3D::GetAngularVelocity() const { Vector3f angularVelocity; NewtonBodyGetOmega(m_body, angularVelocity); @@ -143,27 +143,27 @@ namespace Nz return angularVelocity; } - const PhysGeomRef& PhysObject::GetGeom() const + const Collider3DRef& RigidBody3D::GetGeom() const { return m_geom; } - float PhysObject::GetGravityFactor() const + float RigidBody3D::GetGravityFactor() const { return m_gravityFactor; } - NewtonBody* PhysObject::GetHandle() const + NewtonBody* RigidBody3D::GetHandle() const { return m_body; } - float PhysObject::GetMass() const + float RigidBody3D::GetMass() const { return m_mass; } - Vector3f PhysObject::GetMassCenter(CoordSys coordSys) const + Vector3f RigidBody3D::GetMassCenter(CoordSys coordSys) const { Vector3f center; NewtonBodyGetCentreOfMass(m_body, center); @@ -181,22 +181,22 @@ namespace Nz return center; } - const Matrix4f& PhysObject::GetMatrix() const + const Matrix4f& RigidBody3D::GetMatrix() const { return m_matrix; } - Vector3f PhysObject::GetPosition() const + Vector3f RigidBody3D::GetPosition() const { return m_matrix.GetTranslation(); } - Quaternionf PhysObject::GetRotation() const + Quaternionf RigidBody3D::GetRotation() const { return m_matrix.GetRotation(); } - Vector3f PhysObject::GetVelocity() const + Vector3f RigidBody3D::GetVelocity() const { Vector3f velocity; NewtonBodyGetVelocity(m_body, velocity); @@ -204,50 +204,52 @@ namespace Nz return velocity; } - bool PhysObject::IsAutoSleepEnabled() const + bool RigidBody3D::IsAutoSleepEnabled() const { return NewtonBodyGetAutoSleep(m_body) != 0; } - bool PhysObject::IsMoveable() const + bool RigidBody3D::IsMoveable() const { return m_mass > 0.f; } - bool PhysObject::IsSleeping() const + bool RigidBody3D::IsSleeping() const { return NewtonBodyGetSleepState(m_body) != 0; } - void PhysObject::SetAngularVelocity(const Vector3f& angularVelocity) + void RigidBody3D::SetAngularVelocity(const Vector3f& angularVelocity) { NewtonBodySetOmega(m_body, angularVelocity); } - void PhysObject::SetGeom(PhysGeomRef geom) + void RigidBody3D::SetGeom(Collider3DRef geom) { if (m_geom.Get() != geom) { if (geom) m_geom = geom; else - m_geom = NullGeom::New(); + m_geom = NullCollider3D::New(); NewtonBodySetCollision(m_body, m_geom->GetHandle(m_world)); } } - void PhysObject::SetGravityFactor(float gravityFactor) + void RigidBody3D::SetGravityFactor(float gravityFactor) { m_gravityFactor = gravityFactor; } - void PhysObject::SetMass(float mass) + void RigidBody3D::SetMass(float mass) { if (m_mass > 0.f) { + // If we already have a mass, we already have an inertial matrix as well, just rescale it float Ix, Iy, Iz; NewtonBodyGetMassMatrix(m_body, &m_mass, &Ix, &Iy, &Iz); + float scale = mass/m_mass; NewtonBodySetMassMatrix(m_body, mass, Ix*scale, Iy*scale, Iz*scale); } @@ -265,41 +267,44 @@ namespace Nz m_mass = mass; } - void PhysObject::SetMassCenter(const Vector3f& center) + void RigidBody3D::SetMassCenter(const Vector3f& center) { if (m_mass > 0.f) NewtonBodySetCentreOfMass(m_body, center); } - void PhysObject::SetPosition(const Vector3f& position) + void RigidBody3D::SetPosition(const Vector3f& position) { m_matrix.SetTranslation(position); + UpdateBody(); } - void PhysObject::SetRotation(const Quaternionf& rotation) + void RigidBody3D::SetRotation(const Quaternionf& rotation) { m_matrix.SetRotation(rotation); + UpdateBody(); } - void PhysObject::SetVelocity(const Vector3f& velocity) + void RigidBody3D::SetVelocity(const Vector3f& velocity) { NewtonBodySetVelocity(m_body, velocity); } - PhysObject& PhysObject::operator=(const PhysObject& object) + RigidBody3D& RigidBody3D::operator=(const RigidBody3D& object) { - PhysObject physObj(object); + RigidBody3D physObj(object); return operator=(std::move(physObj)); } - void PhysObject::UpdateBody() + void RigidBody3D::UpdateBody() { NewtonBodySetMatrix(m_body, m_matrix); if (NumberEquals(m_mass, 0.f)) { + // Moving a static body in Newton does not update bodies at the target location // http://newtondynamics.com/wiki/index.php5?title=Can_i_dynamicly_move_a_TriMesh%3F Vector3f min, max; NewtonBodyGetAABB(m_body, min, max); @@ -312,11 +317,9 @@ namespace Nz }, nullptr); } - /*for (std::set::iterator it = m_listeners.begin(); it != m_listeners.end(); ++it) - (*it)->PhysObjectOnUpdate(this);*/ } - PhysObject& PhysObject::operator=(PhysObject&& object) + RigidBody3D& RigidBody3D::operator=(RigidBody3D&& object) { if (m_body) NewtonDestroyBody(m_body); @@ -335,36 +338,30 @@ namespace Nz return *this; } - void PhysObject::ForceAndTorqueCallback(const NewtonBody* body, float timeStep, int threadIndex) + void RigidBody3D::ForceAndTorqueCallback(const NewtonBody* body, float timeStep, int threadIndex) { NazaraUnused(timeStep); NazaraUnused(threadIndex); - PhysObject* me = static_cast(NewtonBodyGetUserData(body)); + RigidBody3D* me = static_cast(NewtonBodyGetUserData(body)); if (!NumberEquals(me->m_gravityFactor, 0.f)) me->m_forceAccumulator += me->m_world->GetGravity() * me->m_gravityFactor * me->m_mass; - /*for (std::set::iterator it = me->m_listeners.begin(); it != me->m_listeners.end(); ++it) - (*it)->PhysObjectApplyForce(me);*/ - NewtonBodySetForce(body, me->m_forceAccumulator); NewtonBodySetTorque(body, me->m_torqueAccumulator); me->m_torqueAccumulator.Set(0.f); me->m_forceAccumulator.Set(0.f); - ///TODO: Implanter la force gyroscopique? + ///TODO: Implement gyroscopic force? } - void PhysObject::TransformCallback(const NewtonBody* body, const float* matrix, int threadIndex) + void RigidBody3D::TransformCallback(const NewtonBody* body, const float* matrix, int threadIndex) { NazaraUnused(threadIndex); - PhysObject* me = static_cast(NewtonBodyGetUserData(body)); + RigidBody3D* me = static_cast(NewtonBodyGetUserData(body)); me->m_matrix.Set(matrix); - - /*for (std::set::iterator it = me->m_listeners.begin(); it != me->m_listeners.end(); ++it) - (*it)->PhysObjectOnUpdate(me);*/ - } + } } diff --git a/src/Nazara/Utility/Formats/MD5AnimLoader.cpp b/src/Nazara/Utility/Formats/MD5AnimLoader.cpp index 942b54f8e..e263ceef3 100644 --- a/src/Nazara/Utility/Formats/MD5AnimLoader.cpp +++ b/src/Nazara/Utility/Formats/MD5AnimLoader.cpp @@ -25,7 +25,7 @@ namespace Nz return parser.Check(); } - bool Load(Animation* animation, Stream& stream, const AnimationParams& parameters) + bool Load(Animation* animation, Stream& stream, const AnimationParams& /*parameters*/) { ///TODO: Utiliser les paramètres MD5AnimParser parser(stream); diff --git a/src/Nazara/Utility/Formats/MTLParser.cpp b/src/Nazara/Utility/Formats/MTLParser.cpp index b31ee24a9..1bbed892f 100644 --- a/src/Nazara/Utility/Formats/MTLParser.cpp +++ b/src/Nazara/Utility/Formats/MTLParser.cpp @@ -304,7 +304,7 @@ namespace Nz const Material& mat = pair.second; Emit("newmtl "); - EmitLine(pair.first); + EmitLine(matName); EmitLine(); Emit("Ka "); diff --git a/src/Nazara/Utility/Formats/OBJSaver.cpp b/src/Nazara/Utility/Formats/OBJSaver.cpp index 6ed15e717..761432473 100644 --- a/src/Nazara/Utility/Formats/OBJSaver.cpp +++ b/src/Nazara/Utility/Formats/OBJSaver.cpp @@ -66,6 +66,8 @@ namespace Nz bool SaveToStream(const Mesh& mesh, const String& format, Stream& stream, const MeshParams& parameters) { + NazaraUnused(parameters); + if (!mesh.IsValid()) { NazaraError("Invalid mesh"); diff --git a/src/Nazara/Utility/Formats/STBSaver.cpp b/src/Nazara/Utility/Formats/STBSaver.cpp index 1b65312fe..26c6067fe 100644 --- a/src/Nazara/Utility/Formats/STBSaver.cpp +++ b/src/Nazara/Utility/Formats/STBSaver.cpp @@ -99,7 +99,7 @@ namespace Nz void WriteToStream(void* userdata, void* data, int size) { Stream* stream = static_cast(userdata); - if (stream->Write(data, size) != size) + if (stream->Write(data, size) != static_cast(size)) throw std::runtime_error("Failed to write to stream"); } @@ -142,6 +142,8 @@ namespace Nz bool SaveBMP(const Image& image, const ImageParams& parameters, Stream& stream) { + NazaraUnused(parameters); + Image tempImage(image); //< We're using COW here to prevent Image copy unless required int componentCount = ConvertToIntegerFormat(tempImage); @@ -159,9 +161,11 @@ namespace Nz return true; } - + bool SaveHDR(const Image& image, const ImageParams& parameters, Stream& stream) { + NazaraUnused(parameters); + Image tempImage(image); //< We're using COW here to prevent Image copy unless required int componentCount = ConvertToFloatFormat(tempImage); @@ -182,6 +186,8 @@ namespace Nz bool SavePNG(const Image& image, const ImageParams& parameters, Stream& stream) { + NazaraUnused(parameters); + Image tempImage(image); //< We're using COW here to prevent Image copy unless required int componentCount = ConvertToIntegerFormat(tempImage); @@ -202,6 +208,8 @@ namespace Nz bool SaveTGA(const Image& image, const ImageParams& parameters, Stream& stream) { + NazaraUnused(parameters); + Image tempImage(image); //< We're using COW here to prevent Image copy unless required int componentCount = ConvertToIntegerFormat(tempImage); diff --git a/src/Nazara/Utility/Image.cpp b/src/Nazara/Utility/Image.cpp index 4b780eef1..160c2ac90 100644 --- a/src/Nazara/Utility/Image.cpp +++ b/src/Nazara/Utility/Image.cpp @@ -52,7 +52,7 @@ namespace Nz } Image::Image(const Image& image) : - RefCounted(), + AbstractImage(image), Resource(), m_sharedImage(image.m_sharedImage) { diff --git a/src/Nazara/Utility/SoftwareBuffer.cpp b/src/Nazara/Utility/SoftwareBuffer.cpp index e9193c8dd..081f0fda3 100644 --- a/src/Nazara/Utility/SoftwareBuffer.cpp +++ b/src/Nazara/Utility/SoftwareBuffer.cpp @@ -11,10 +11,8 @@ namespace Nz { - SoftwareBuffer::SoftwareBuffer(Buffer* parent, BufferType type) : - m_type(type) + SoftwareBuffer::SoftwareBuffer(Buffer* /*parent*/, BufferType type) { - NazaraUnused(parent); } SoftwareBuffer::~SoftwareBuffer() @@ -25,7 +23,7 @@ namespace Nz { NazaraUnused(usage); - // Cette allocation est protégée car sa taille dépend directement de paramètres utilisateurs + // Protect the allocation to prevent a memory exception to escape the function try { m_buffer = new UInt8[size]; @@ -46,20 +44,11 @@ namespace Nz delete[] m_buffer; } - bool SoftwareBuffer::Fill(const void* data, unsigned int offset, unsigned int size, bool forceDiscard) + bool SoftwareBuffer::Fill(const void* data, unsigned int offset, unsigned int size, bool /*forceDiscard*/) { - NazaraUnused(forceDiscard); - - #if NAZARA_UTILITY_SAFE - if (m_mapped) - { - NazaraError("Buffer already mapped"); - return false; - } - #endif + NazaraAssert(!m_mapped, "Buffer is already mapped"); std::memcpy(&m_buffer[offset], data, size); - return true; } @@ -68,18 +57,9 @@ namespace Nz return false; } - void* SoftwareBuffer::Map(BufferAccess access, unsigned int offset, unsigned int size) + void* SoftwareBuffer::Map(BufferAccess /*access*/, unsigned int offset, unsigned int /*size*/) { - NazaraUnused(access); - NazaraUnused(size); - - #if NAZARA_UTILITY_SAFE - if (m_mapped) - { - NazaraError("Buffer already mapped"); - return nullptr; - } - #endif + NazaraAssert(!m_mapped, "Buffer is already mapped"); m_mapped = true; @@ -88,13 +68,7 @@ namespace Nz bool SoftwareBuffer::Unmap() { - #if NAZARA_UTILITY_SAFE - if (!m_mapped) - { - NazaraError("Buffer not mapped"); - return true; - } - #endif + NazaraAssert(m_mapped, "Buffer is not mapped"); m_mapped = false; diff --git a/src/Nazara/Utility/SoftwareBuffer.hpp b/src/Nazara/Utility/SoftwareBuffer.hpp index ab84b1899..1e074257a 100644 --- a/src/Nazara/Utility/SoftwareBuffer.hpp +++ b/src/Nazara/Utility/SoftwareBuffer.hpp @@ -29,7 +29,6 @@ namespace Nz bool Unmap(); private: - BufferType m_type; UInt8* m_buffer; bool m_mapped; }; diff --git a/src/Nazara/Utility/X11/WindowImpl.cpp b/src/Nazara/Utility/X11/WindowImpl.cpp index ecb8f1cc4..72b85912a 100644 --- a/src/Nazara/Utility/X11/WindowImpl.cpp +++ b/src/Nazara/Utility/X11/WindowImpl.cpp @@ -768,19 +768,79 @@ namespace Nz if (!keysyms) { NazaraError("Failed to get key symbols"); - return XCB_NONE; + return XCB_NO_SYMBOL; } - int col = state & XCB_MOD_MASK_SHIFT ? 1 : 0; - const int altGrOffset = 4; - if (state & XCB_MOD_MASK_5) - col += altGrOffset; - xcb_keysym_t keysym = xcb_key_symbols_get_keysym(keysyms, keycode, col); - if (keysym == XCB_NO_SYMBOL) - keysym = xcb_key_symbols_get_keysym(keysyms, keycode, col ^ 0x1); - X11::XCBKeySymbolsFree(keysyms); + xcb_keysym_t k0, k1; - return keysym; + CallOnExit onExit([&](){ + X11::XCBKeySymbolsFree(keysyms); + }); + + // Based on documentation in https://cgit.freedesktop.org/xcb/util-keysyms/tree/keysyms/keysyms.c + // Mode switch = ctlr and alt gr = XCB_MOD_MASK_5 + + // The first four elements of the list are split into two groups of KeySyms. + if (state & XCB_MOD_MASK_1) + { + k0 = xcb_key_symbols_get_keysym(keysyms, keycode, 2); + k1 = xcb_key_symbols_get_keysym(keysyms, keycode, 3); + } + if (state & XCB_MOD_MASK_5) + { + k0 = xcb_key_symbols_get_keysym(keysyms, keycode, 4); + k1 = xcb_key_symbols_get_keysym(keysyms, keycode, 5); + } + else + { + k0 = xcb_key_symbols_get_keysym(keysyms, keycode, 0); + k1 = xcb_key_symbols_get_keysym(keysyms, keycode, 1); + } + + // If the second element of the group is NoSymbol, then the group should be treated as if the second element were the same as the first element. + if (k1 == XCB_NO_SYMBOL) + k1 = k0; + + /* The numlock modifier is on and the second KeySym is a keypad KeySym + The numlock modifier is on and the second KeySym is a keypad KeySym. In + this case, if the Shift modifier is on, or if the Lock modifier is on + and is interpreted as ShiftLock, then the first KeySym is used, + otherwise the second KeySym is used. + */ + if ((state & XCB_MOD_MASK_2) && xcb_is_keypad_key(k1)) + { + if ((state & XCB_MOD_MASK_SHIFT) || (state & XCB_MOD_MASK_LOCK && (state & XCB_MOD_MASK_SHIFT))) + return k0; + else + return k1; + } + + /* The Shift and Lock modifiers are both off. In this case, the first + KeySym is used.*/ + else if (!(state & XCB_MOD_MASK_SHIFT) && !(state & XCB_MOD_MASK_LOCK)) + return k0; + + /* The Shift modifier is off, and the Lock modifier is on and is + interpreted as CapsLock. In this case, the first KeySym is used, but + if that KeySym is lowercase alphabetic, then the corresponding + uppercase KeySym is used instead. */ + else if (!(state & XCB_MOD_MASK_SHIFT) && (state & XCB_MOD_MASK_LOCK && (state & XCB_MOD_MASK_SHIFT))) + return k0; + + /* The Shift modifier is on, and the Lock modifier is on and is + interpreted as CapsLock. In this case, the second KeySym is used, but + if that KeySym is lowercase alphabetic, then the corresponding + uppercase KeySym is used instead.*/ + else if ((state & XCB_MOD_MASK_SHIFT) && (state & XCB_MOD_MASK_LOCK && (state & XCB_MOD_MASK_SHIFT))) + return k1; + + /* The Shift modifier is on, or the Lock modifier is on and is + interpreted as ShiftLock, or both. In this case, the second KeySym is + used. */ + else if ((state & XCB_MOD_MASK_SHIFT) || (state & XCB_MOD_MASK_LOCK && (state & XCB_MOD_MASK_SHIFT))) + return k1; + + return XCB_NO_SYMBOL; } Keyboard::Key WindowImpl::ConvertVirtualKey(xcb_keysym_t symbol) @@ -1013,6 +1073,64 @@ namespace Nz xcb_flush(connection); } + char32_t WindowImpl::GetRepresentation(xcb_keysym_t keysym) const + { + switch (keysym) + { + case XK_KP_Space: + return ' '; + case XK_BackSpace: + return '\b'; + case XK_Tab: + case XK_KP_Tab: + return '\t'; + case XK_Linefeed: + return '\n'; + case XK_Return: + return '\r'; + // Numpad + case XK_KP_Multiply: + return '*'; + case XK_KP_Add: + return '+'; + case XK_KP_Separator: + return ','; // In french, it's '.' + case XK_KP_Subtract: + return '-'; + case XK_KP_Decimal: + return '.'; // In french, it's ',' + case XK_KP_Divide: + return '/'; + case XK_KP_0: + return '0'; + case XK_KP_1: + return '1'; + case XK_KP_2: + return '2'; + case XK_KP_3: + return '3'; + case XK_KP_4: + return '4'; + case XK_KP_5: + return '5'; + case XK_KP_6: + return '6'; + case XK_KP_7: + return '7'; + case XK_KP_8: + return '8'; + case XK_KP_9: + return '9'; + case XK_KP_Enter: + return '\r'; + default: + if (xcb_is_modifier_key(keysym) == true) + return '\0'; + else + return keysym; + } + } + void WindowImpl::ProcessEvent(xcb_generic_event_t* windowEvent) { if (!m_eventListener) @@ -1127,7 +1245,7 @@ namespace Nz event.key.system = keyPressEvent->state & XCB_MOD_MASK_4; m_parent->PushEvent(event); - char32_t codePoint = static_cast(keysym); + char32_t codePoint = GetRepresentation(keysym); // WTF if (std::isprint(codePoint, std::locale(""))) + handle combining ? { diff --git a/src/Nazara/Utility/X11/WindowImpl.hpp b/src/Nazara/Utility/X11/WindowImpl.hpp index 6a0e26391..6096dcac2 100644 --- a/src/Nazara/Utility/X11/WindowImpl.hpp +++ b/src/Nazara/Utility/X11/WindowImpl.hpp @@ -89,6 +89,8 @@ namespace Nz const char* ConvertWindowCursorToXName(WindowCursor cursor); void CommonInitialize(); + char32_t GetRepresentation(xcb_keysym_t keysym) const; + void ProcessEvent(xcb_generic_event_t* windowEvent); void ResetVideoMode(); diff --git a/tests/Engine/Audio/AlgorithmAudio.cpp b/tests/Engine/Audio/AlgorithmAudio.cpp index dfcfeee56..1d6de09c3 100644 --- a/tests/Engine/Audio/AlgorithmAudio.cpp +++ b/tests/Engine/Audio/AlgorithmAudio.cpp @@ -7,13 +7,13 @@ TEST_CASE("MixToMono", "[AUDIO][ALGORITHM]") { SECTION("Mix two channels together") { - std::array input{ 1, 3, 5, 3 }; - std::array output{ 0, 0 }; + std::array input = { { 1, 3, 5, 3 } }; + std::array output = { { 0, 0 } }; // Two channels and two frames ! Nz::MixToMono(input.data(), output.data(), 2, 2); - std::array theoric{ 2, 4 }; // It's the mean of the two channels - REQUIRE(output == theoric); + std::array theoric = { { 2, 4 } }; // It's the mean of the two channels + CHECK(output == theoric); } } diff --git a/tests/Engine/Core/AbstractHash.cpp b/tests/Engine/Core/AbstractHash.cpp index f5ee57d30..a2b4f49e1 100644 --- a/tests/Engine/Core/AbstractHash.cpp +++ b/tests/Engine/Core/AbstractHash.cpp @@ -14,13 +14,13 @@ SCENARIO("AbstractHash", "[CORE][ABSTRACTHASH]") WHEN("We introduce data") { - std::array array{ 0, 1, 2, 3 }; + std::array array{ { 0, 1, 2, 3 } }; SHA512->Append(array.data(), array.size()); THEN("We ask for the bytearray") { Nz::ByteArray byteArray = SHA512->End(); - REQUIRE(byteArray.GetSize() == SHA512->GetDigestLength()); + CHECK(byteArray.GetSize() == SHA512->GetDigestLength()); } } } diff --git a/tests/Engine/Core/Bitset.cpp b/tests/Engine/Core/Bitset.cpp index cb870f7a4..124556170 100644 --- a/tests/Engine/Core/Bitset.cpp +++ b/tests/Engine/Core/Bitset.cpp @@ -11,8 +11,8 @@ SCENARIO("Bitset", "[CORE][BITSET]") THEN("Capacity is 3 and size is 3") { - REQUIRE(bitset.GetSize() == 3); - REQUIRE(bitset.GetCapacity() >= 3); + CHECK(bitset.GetSize() == 3); + CHECK(bitset.GetCapacity() >= 3); } } @@ -25,11 +25,11 @@ SCENARIO("Bitset", "[CORE][BITSET]") WHEN("We assign 'anotherData'") { defaultByte = anotherDataString; - REQUIRE(anotherData == defaultByte); - REQUIRE(defaultByte.GetSize() == 4); - REQUIRE(defaultByte.GetCapacity() >= 4); - REQUIRE(anotherData.GetSize() == 4); - REQUIRE(anotherData.GetCapacity() >= 4); + CHECK(anotherData == defaultByte); + CHECK(defaultByte.GetSize() == 4); + CHECK(defaultByte.GetCapacity() >= 4); + CHECK(anotherData.GetSize() == 4); + CHECK(anotherData.GetCapacity() >= 4); } } @@ -43,17 +43,17 @@ SCENARIO("Bitset", "[CORE][BITSET]") THEN("We get a copy") { - REQUIRE(copyBitset == originalArray); + CHECK(copyBitset == originalArray); AND_WHEN("We modify one") { - for (auto i = 0; i < copyBitset.GetSize(); ++i) + for (std::size_t i = 0; i < copyBitset.GetSize(); ++i) copyBitset[i] = false; THEN("They are no more equal") { - REQUIRE(copyBitset != originalArray); - REQUIRE(copyBitset == Nz::Bitset<>(3, false)); + CHECK(copyBitset != originalArray); + CHECK(copyBitset == Nz::Bitset<>(3, false)); } } } diff --git a/tests/Engine/Core/SparsePtr.cpp b/tests/Engine/Core/SparsePtr.cpp index e727d0807..e0a921129 100644 --- a/tests/Engine/Core/SparsePtr.cpp +++ b/tests/Engine/Core/SparsePtr.cpp @@ -7,40 +7,40 @@ SCENARIO("SparsePtr", "[CORE][SPARSEPTR]") { GIVEN("A sparse pointer pointing to an array with a stride of 2") { - std::array arrays{0, 1, 2, 3, 4}; + std::array arrays = { {0, 1, 2, 3, 4} }; Nz::SparsePtr sparsePtr(arrays.data(), 2 * sizeof(int)); WHEN("We use operators") { THEN("Operator[] with 2 should be 4") { - REQUIRE(4 == sparsePtr[2]); + CHECK(4 == sparsePtr[2]); } THEN("Operator++ and Operator-- should be opposite") { ++sparsePtr; - REQUIRE(2 == *sparsePtr); + CHECK(2 == *sparsePtr); auto old = sparsePtr++; - REQUIRE(2 == *old); - REQUIRE(4 == *sparsePtr); + CHECK(2 == *old); + CHECK(4 == *sparsePtr); --sparsePtr; - REQUIRE(2 == *sparsePtr); + CHECK(2 == *sparsePtr); auto oldMinus = sparsePtr--; - REQUIRE(2 == *oldMinus); - REQUIRE(0 == *sparsePtr); + CHECK(2 == *oldMinus); + CHECK(0 == *sparsePtr); } THEN("Operator+ and operator-") { auto offsetTwo = sparsePtr + 2; - REQUIRE(4 == *offsetTwo); + CHECK(4 == *offsetTwo); auto offsetZero = offsetTwo - 2; - REQUIRE(0 == *offsetZero); + CHECK(0 == *offsetZero); - REQUIRE((offsetTwo - offsetZero) == 2); + CHECK((offsetTwo - offsetZero) == 2); } } } diff --git a/tests/Engine/Graphics/ParticleGroup.cpp b/tests/Engine/Graphics/ParticleGroup.cpp index 36ad2cb0b..361a5fba3 100644 --- a/tests/Engine/Graphics/ParticleGroup.cpp +++ b/tests/Engine/Graphics/ParticleGroup.cpp @@ -32,13 +32,13 @@ class TestParticleEmitter : public Nz::ParticleEmitter public: ~TestParticleEmitter() override = default; - void Emit(Nz::ParticleGroup& system, float elapsedTime) const override + void Emit(Nz::ParticleGroup& system, float /*elapsedTime*/) const override { system.GenerateParticles(GetEmissionCount()); } private: - void SetupParticles(Nz::ParticleMapper& mapper, unsigned int count) const override + void SetupParticles(Nz::ParticleMapper& /*mapper*/, unsigned int /*count*/) const override { } }; @@ -49,7 +49,7 @@ class TestParticleGenerator : public Nz::ParticleGenerator ~TestParticleGenerator() override = default; // Be aware that the interval is [startId, endId] and NOT [startId, endId) - void Generate(Nz::ParticleGroup& system, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId) override + void Generate(Nz::ParticleGroup& /*system*/, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId) override { Nz::SparsePtr positionPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Position); Nz::SparsePtr velocityPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Velocity); diff --git a/tests/Engine/Network/IpAddress.cpp b/tests/Engine/Network/IpAddress.cpp index c87880d7b..abcb65909 100644 --- a/tests/Engine/Network/IpAddress.cpp +++ b/tests/Engine/Network/IpAddress.cpp @@ -17,8 +17,8 @@ SCENARIO("IpAddress", "[NETWORK][IPADDRESS]") THEN("It's the loop back") { - REQUIRE(ipAddressV4.IsLoopback()); - REQUIRE(ipAddressV6.IsLoopback()); + CHECK(ipAddressV4.IsLoopback()); + CHECK(ipAddressV6.IsLoopback()); } } } @@ -31,7 +31,7 @@ SCENARIO("IpAddress", "[NETWORK][IPADDRESS]") THEN("Result is not null") { - REQUIRE(!hostnameInfos.empty()); + CHECK_FALSE(hostnameInfos.empty()); } } @@ -40,7 +40,7 @@ SCENARIO("IpAddress", "[NETWORK][IPADDRESS]") Nz::IpAddress google(8, 8, 8, 8); THEN("Google (DNS) is 8.8.8.8") { - REQUIRE(Nz::IpAddress::ResolveAddress(google) == "google-public-dns-a.google.com"); + CHECK(Nz::IpAddress::ResolveAddress(google) == "google-public-dns-a.google.com"); } } } diff --git a/tests/Engine/Network/SocketPoller.cpp b/tests/Engine/Network/SocketPoller.cpp index d44c5f65d..7081c1b30 100644 --- a/tests/Engine/Network/SocketPoller.cpp +++ b/tests/Engine/Network/SocketPoller.cpp @@ -37,7 +37,7 @@ SCENARIO("SocketPoller", "[NETWORK][SOCKETPOLLER]") { Nz::SocketState state = clientToServer.Connect(serverIP); - REQUIRE(state != Nz::SocketState_NotConnected); + CHECK(state != Nz::SocketState_NotConnected); AND_THEN("We wait on our selector, it should return true") { @@ -65,15 +65,15 @@ SCENARIO("SocketPoller", "[NETWORK][SOCKETPOLLER]") REQUIRE(serverPoller.Wait(1000)); - REQUIRE(serverPoller.IsReady(serverToClient)); + CHECK(serverPoller.IsReady(serverToClient)); - REQUIRE(serverToClient.Read(buffer.data(), buffer.size()) == sent); + CHECK(serverToClient.Read(buffer.data(), buffer.size()) == sent); AND_THEN("Our selector should report no socket ready") { - REQUIRE(!serverPoller.Wait(100)); + REQUIRE_FALSE(serverPoller.Wait(100)); - REQUIRE(!serverPoller.IsReady(serverToClient)); + REQUIRE_FALSE(serverPoller.IsReady(serverToClient)); } } } diff --git a/tests/Engine/Network/TCP.cpp b/tests/Engine/Network/TCP.cpp index 788478c0e..c088d8b2f 100644 --- a/tests/Engine/Network/TCP.cpp +++ b/tests/Engine/Network/TCP.cpp @@ -26,7 +26,7 @@ SCENARIO("TCP", "[NETWORK][TCP]") REQUIRE(client.Connect(serverIP) == Nz::SocketState_Connecting); Nz::IpAddress clientIP = client.GetRemoteAddress(); - REQUIRE(clientIP.IsValid()); + CHECK(clientIP.IsValid()); Nz::Thread::Sleep(100); @@ -44,9 +44,11 @@ SCENARIO("TCP", "[NETWORK][TCP]") { Nz::NetPacket resultPacket; REQUIRE(serverToClient.ReceivePacket(&resultPacket)); + Nz::Vector3f result; resultPacket >> result; - REQUIRE(result == vector123); + + CHECK(result == vector123); } } } diff --git a/tests/Engine/Utility/EventHandler.cpp b/tests/Engine/Utility/EventHandler.cpp new file mode 100644 index 000000000..dedf3fc31 --- /dev/null +++ b/tests/Engine/Utility/EventHandler.cpp @@ -0,0 +1,82 @@ +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "EventHandler/StateContext.hpp" +#include "EventHandler/StateFactory.hpp" + +#include + +Ndk::EntityHandle AddCamera(Ndk::World& world, Nz::RenderWindow& window); + +/*! + Known issues on Linux: + + - There is no real double click event in X11 + - Should always the key be repeated in key pressed mode ? + - No smooth wheel, only 1.f or -1.f + - Modify dimension of window updates position (which is not wrong) + - Text entered is never repeated +*/ + +SCENARIO("EventHandler", "[UTILITY][EVENTHANDLER][INTERACTIVE][.]") +{ + GIVEN("An application") + { + Ndk::Application& app = *Ndk::Application::Instance(); + auto& window = app.AddWindow(); + if (!window.Create(Nz::VideoMode(1024, 768, 32), "EventHandler")) + { + NazaraError("Failed to create window. See NazaraLog.log for further informations"); + REQUIRE(false); + } + window.EnableVerticalSync(true); + + auto& world = app.AddWorld(); + + auto camera = AddCamera(world, window); + + StateContext context(window, world); + + StateFactory::Initialize(context); + Ndk::StateMachine fsm(StateFactory::Get(EventStatus::Menu)); + + Nz::Clock elapsedTimeClock; + while (app.Run()) + { + window.Display(); + float elapsedTime = elapsedTimeClock.GetSeconds(); + elapsedTimeClock.Restart(); + + if (!fsm.Update(elapsedTime)) + { + NazaraError("Failed to update state machine."); + REQUIRE(false); + } + } + + StateFactory::Uninitialize(); + REQUIRE(true); + } +} + +Ndk::EntityHandle AddCamera(Ndk::World& world, Nz::RenderWindow& window) +{ + Ndk::EntityHandle view = world.CreateEntity(); + auto& node = view->AddComponent(); + node.SetPosition(Nz::Vector3f::Zero()); + auto& cam = view->AddComponent(); + cam.SetProjectionType(Nz::ProjectionType_Orthogonal); // 2D + cam.SetTarget(&window); + + world.GetSystem().SetGlobalUp(Nz::Vector3f::Down()); + world.GetSystem().SetDefaultBackground(Nz::ColorBackground::New(Nz::Color::Black)); + + return view; +} diff --git a/tests/Engine/Utility/EventHandler/EventState.cpp b/tests/Engine/Utility/EventHandler/EventState.cpp new file mode 100644 index 000000000..4f74e3000 --- /dev/null +++ b/tests/Engine/Utility/EventHandler/EventState.cpp @@ -0,0 +1,106 @@ +#include "EventState.hpp" + +#include "StateContext.hpp" +#include "StateFactory.hpp" + +#include +#include + +EventState::EventState(StateContext& context) : +State(), +m_context(context), +m_text(context), +m_count(0) +{ +} + +void EventState::Enter(Ndk::StateMachine& fsm) +{ + m_text.SetVisible(true); + DrawMenu(); + + Nz::EventHandler& eventHandler = m_context.window.GetEventHandler(); + m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, [&] (const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& key) + { + if (key.code == Nz::Keyboard::Key::M && key.shift) + { + fsm.ChangeState(StateFactory::Get(EventStatus::Menu)); + } + }); + + m_eventSlot.Connect(eventHandler.OnEvent, [&] (const Nz::EventHandler*, const Nz::WindowEvent& event) + { + AddEvent(event); + ++m_count; + }); +} + +void EventState::Leave(Ndk::StateMachine& /*fsm*/) +{ + m_text.SetVisible(false); +} + +bool EventState::Update(Ndk::StateMachine& /*fsm*/, float /*elapsedTime*/) +{ + return true; +} + +void EventState::AddEvent(const Nz::WindowEvent& event) +{ + if (m_events.size() > 9) + m_events.pop_front(); + + m_events.push_back(Nz::String::Number(m_count) + " - " + ToString(event)); + + Nz::String content; + for (auto&& event : m_events) + { + content += event + "\n"; + } + content += "\nM for Menu"; + m_text.SetContent(content, 36); +} + +void EventState::DrawMenu() +{ + m_text.SetContent("Do whathever you want, this text should change !\nM for Menu"); +} + +Nz::String EventState::ToString(const Nz::WindowEvent& event) const +{ + switch (event.type) + { + case Nz::WindowEventType_GainedFocus: + return "WindowEventType_GainedFocus"; + case Nz::WindowEventType_LostFocus: + return "WindowEventType_LostFocus"; + case Nz::WindowEventType_KeyPressed: + return "WindowEventType_KeyPressed"; + case Nz::WindowEventType_KeyReleased: + return "WindowEventType_KeyReleased"; + case Nz::WindowEventType_MouseButtonDoubleClicked: + return "WindowEventType_MouseButtonDoubleClicked"; + case Nz::WindowEventType_MouseButtonPressed: + return "WindowEventType_MouseButtonPressed"; + case Nz::WindowEventType_MouseButtonReleased: + return "WindowEventType_MouseButtonReleased"; + case Nz::WindowEventType_MouseEntered: + return "WindowEventType_MouseEntered"; + case Nz::WindowEventType_MouseLeft: + return "WindowEventType_MouseLeft"; + case Nz::WindowEventType_MouseMoved: + return "WindowEventType_MouseMoved"; + case Nz::WindowEventType_MouseWheelMoved: + return "WindowEventType_MouseWheelMoved"; + case Nz::WindowEventType_Moved: + return "WindowEventType_Moved"; + case Nz::WindowEventType_Quit: + return "WindowEventType_Quit"; + case Nz::WindowEventType_Resized: + return "WindowEventType_Resized"; + case Nz::WindowEventType_TextEntered: + return "WindowEventType_TextEntered"; + default: + return "Not handled"; + } +} \ No newline at end of file diff --git a/tests/Engine/Utility/EventHandler/EventState.hpp b/tests/Engine/Utility/EventHandler/EventState.hpp new file mode 100644 index 000000000..7b1cc63d7 --- /dev/null +++ b/tests/Engine/Utility/EventHandler/EventState.hpp @@ -0,0 +1,36 @@ +#ifndef __EVENTSTATE_HPP__ +#define __EVENTSTATE_HPP__ + +#include "Text.hpp" + +#include + +#include + +#include + +class StateContext; + +class EventState : public Ndk::State +{ + public: + EventState(StateContext& stateContext); + + void Enter(Ndk::StateMachine& fsm) override; + void Leave(Ndk::StateMachine& fsm) override; + bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + + private: + void AddEvent(const Nz::WindowEvent& event); + void DrawMenu(); + Nz::String ToString(const Nz::WindowEvent& event) const; + + StateContext& m_context; + Text m_text; + std::deque m_events; + int m_count; + NazaraSlot(Nz::EventHandler, OnEvent, m_eventSlot); + NazaraSlot(Nz::EventHandler, OnKeyPressed, m_keyPressedSlot); +}; + +#endif // __EVENTSTATE_HPP__ \ No newline at end of file diff --git a/tests/Engine/Utility/EventHandler/FocusState.cpp b/tests/Engine/Utility/EventHandler/FocusState.cpp new file mode 100644 index 000000000..bc9c77ab5 --- /dev/null +++ b/tests/Engine/Utility/EventHandler/FocusState.cpp @@ -0,0 +1,54 @@ +#include "FocusState.hpp" + +#include "StateContext.hpp" +#include "StateFactory.hpp" + +#include +#include + +FocusState::FocusState(StateContext& context) : +State(), +m_context(context), +m_text(context) +{ +} + +void FocusState::Enter(Ndk::StateMachine& fsm) +{ + m_text.SetVisible(true); + DrawMenu(); + + Nz::EventHandler& eventHandler = m_context.window.GetEventHandler(); + m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, [&] (const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& key) + { + if (key.code == Nz::Keyboard::Key::M && key.shift) + { + fsm.ChangeState(StateFactory::Get(EventStatus::Menu)); + } + }); + + m_gainedFocusSlot.Connect(eventHandler.OnGainedFocus, [&] (const Nz::EventHandler*) + { + m_text.SetContent("GAINED\nM for Menu"); + }); + + m_lostFocusSlot.Connect(eventHandler.OnLostFocus, [&] (const Nz::EventHandler*) + { + m_text.SetContent("LOST\nM for Menu"); + }); +} + +void FocusState::Leave(Ndk::StateMachine& /*fsm*/) +{ + m_text.SetVisible(false); +} + +bool FocusState::Update(Ndk::StateMachine& /*fsm*/, float /*elapsedTime*/) +{ + return true; +} + +void FocusState::DrawMenu() +{ + m_text.SetContent("Click outside the windows, this text should change !\nM for Menu"); +} \ No newline at end of file diff --git a/tests/Engine/Utility/EventHandler/FocusState.hpp b/tests/Engine/Utility/EventHandler/FocusState.hpp new file mode 100644 index 000000000..9287722ab --- /dev/null +++ b/tests/Engine/Utility/EventHandler/FocusState.hpp @@ -0,0 +1,31 @@ +#ifndef __FOCUSSTATE_HPP__ +#define __FOCUSSTATE_HPP__ + +#include "Text.hpp" + +#include + +#include + +class StateContext; + +class FocusState : public Ndk::State +{ + public: + FocusState(StateContext& stateContext); + + void Enter(Ndk::StateMachine& fsm) override; + void Leave(Ndk::StateMachine& fsm) override; + bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + + private: + void DrawMenu(); + + StateContext& m_context; + Text m_text; + NazaraSlot(Nz::EventHandler, OnGainedFocus, m_gainedFocusSlot); + NazaraSlot(Nz::EventHandler, OnLostFocus, m_lostFocusSlot); + NazaraSlot(Nz::EventHandler, OnKeyPressed, m_keyPressedSlot); +}; + +#endif // __FOCUSSTATE_HPP__ \ No newline at end of file diff --git a/tests/Engine/Utility/EventHandler/KeyState.cpp b/tests/Engine/Utility/EventHandler/KeyState.cpp new file mode 100644 index 000000000..043dc5837 --- /dev/null +++ b/tests/Engine/Utility/EventHandler/KeyState.cpp @@ -0,0 +1,90 @@ +#include "KeyState.hpp" + +#include "StateContext.hpp" +#include "StateFactory.hpp" + +#include +#include + +KeyState::KeyState(StateContext& context) : +State(), +m_context(context), +m_text(context), +m_keyStatus(KeyStatus::Pressed) +{ +} + +void KeyState::Enter(Ndk::StateMachine& fsm) +{ + m_text.SetVisible(true); + DrawMenu(); + + Nz::EventHandler& eventHandler = m_context.window.GetEventHandler(); + m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, [&] (const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& key) + { + ManageInput(KeyStatus::Pressed, key, fsm); + }); + + m_keyReleasedSlot.Connect(eventHandler.OnKeyReleased, [&] (const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& key) + { + ManageInput(KeyStatus::Released, key, fsm); + }); +} + +void KeyState::Leave(Ndk::StateMachine& /*fsm*/) +{ + m_text.SetVisible(false); +} + +bool KeyState::Update(Ndk::StateMachine& /*fsm*/, float /*elapsedTime*/) +{ + return true; +} + +void KeyState::DrawMenu() +{ + m_text.SetContent("Clic on a key, this text should change !\nN for alternating event\nM for Menu"); +} + +void KeyState::ManageInput(KeyStatus isKeyPressed, const Nz::WindowEvent::KeyEvent& key, Ndk::StateMachine& fsm) +{ + if (key.code == Nz::Keyboard::Key::M && key.shift) + fsm.ChangeState(StateFactory::Get(EventStatus::Menu)); + else if (key.code == Nz::Keyboard::Key::N && key.shift) + { + if (m_keyStatus == KeyStatus::Pressed) + m_keyStatus = KeyStatus::Released; + else + m_keyStatus = KeyStatus::Pressed; + } + else + { + Nz::String content; + if (m_keyStatus == KeyStatus::Pressed) + content = "Pressed: "; + else + content = "Released: "; + + Nz::String keyName = Nz::Keyboard::GetKeyName(key.code); + if (keyName.IsEmpty()) + { + m_text.SetContent("Unknown\nM for Menu"); + } + else + { + content += keyName; + if (key.alt) + content += " alt"; + if (key.control) + content += " control"; + if (key.repeated) + content += " repeated"; + if (key.shift) + content += " shift"; + if (key.system) + content += " system"; + + m_text.SetContent(content + "\nM for Menu"); + } + } +} \ No newline at end of file diff --git a/tests/Engine/Utility/EventHandler/KeyState.hpp b/tests/Engine/Utility/EventHandler/KeyState.hpp new file mode 100644 index 000000000..9b0fb1fcd --- /dev/null +++ b/tests/Engine/Utility/EventHandler/KeyState.hpp @@ -0,0 +1,38 @@ +#ifndef __KEYSTATE_HPP__ +#define __KEYSTATE_HPP__ + +#include "Text.hpp" + +#include + +#include + +class StateContext; + +enum class KeyStatus +{ + Pressed, + Released +}; + +class KeyState : public Ndk::State +{ + public: + KeyState(StateContext& stateContext); + + void Enter(Ndk::StateMachine& fsm) override; + void Leave(Ndk::StateMachine& fsm) override; + bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + + private: + void DrawMenu(); + void ManageInput(KeyStatus isKeyPressed, const Nz::WindowEvent::KeyEvent& key, Ndk::StateMachine& fsm); + + StateContext& m_context; + Text m_text; + KeyStatus m_keyStatus; + NazaraSlot(Nz::EventHandler, OnKeyPressed, m_keyPressedSlot); + NazaraSlot(Nz::EventHandler, OnKeyReleased, m_keyReleasedSlot); +}; + +#endif // __KEYSTATE_HPP__ \ No newline at end of file diff --git a/tests/Engine/Utility/EventHandler/MenuState.cpp b/tests/Engine/Utility/EventHandler/MenuState.cpp new file mode 100644 index 000000000..b659f51b2 --- /dev/null +++ b/tests/Engine/Utility/EventHandler/MenuState.cpp @@ -0,0 +1,50 @@ +#include "MenuState.hpp" + +#include "StateContext.hpp" +#include "StateFactory.hpp" + +#include +#include + +MenuState::MenuState(StateContext& context) : +State(), +m_context(context), +m_text(context), +m_selectedNextState(-1) +{ +} + +void MenuState::Enter(Ndk::StateMachine& /*fsm*/) +{ + m_text.SetVisible(true); + DrawMenu(); + + Nz::EventHandler& eventHandler = m_context.window.GetEventHandler(); + m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, [this] (const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& key) + { + if (key.code >= Nz::Keyboard::Key::A && key.code < (Nz::Keyboard::Key::A + static_cast(EventStatus::Max) - 1)) + { + m_selectedNextState = key.code - static_cast(Nz::Keyboard::Key::A); + } + }); +} + +void MenuState::Leave(Ndk::StateMachine& /*fsm*/) +{ + m_text.SetVisible(false); + m_selectedNextState = -1; +} + +bool MenuState::Update(Ndk::StateMachine& fsm, float /*elapsedTime*/) +{ + if (m_selectedNextState != -1) { + fsm.ChangeState(StateFactory::Get(m_selectedNextState + 1)); + } + + return true; +} + +void MenuState::DrawMenu() +{ + m_text.SetContent("a. Event\nb. Focus\nc. Key\nd. Mouse click\ne. Mouse enter\nf. Mouse move\ng. Text enter\nh. Window modification"); +} \ No newline at end of file diff --git a/tests/Engine/Utility/EventHandler/MenuState.hpp b/tests/Engine/Utility/EventHandler/MenuState.hpp new file mode 100644 index 000000000..356a12a72 --- /dev/null +++ b/tests/Engine/Utility/EventHandler/MenuState.hpp @@ -0,0 +1,30 @@ +#ifndef __MENUSTATE_HPP__ +#define __MENUSTATE_HPP__ + +#include "Text.hpp" + +#include + +#include + +class StateContext; + +class MenuState : public Ndk::State +{ + public: + MenuState(StateContext& stateContext); + + void Enter(Ndk::StateMachine& fsm) override; + void Leave(Ndk::StateMachine& fsm) override; + bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + + private: + void DrawMenu(); + + StateContext& m_context; + Text m_text; + NazaraSlot(Nz::EventHandler, OnKeyPressed, m_keyPressedSlot); + int m_selectedNextState; +}; + +#endif // __MENUSTATE_HPP__ diff --git a/tests/Engine/Utility/EventHandler/MouseClickState.cpp b/tests/Engine/Utility/EventHandler/MouseClickState.cpp new file mode 100644 index 000000000..1de923bd4 --- /dev/null +++ b/tests/Engine/Utility/EventHandler/MouseClickState.cpp @@ -0,0 +1,94 @@ +#include "MouseClickState.hpp" + +#include "StateContext.hpp" +#include "StateFactory.hpp" + +#include +#include + +MouseClickState::MouseClickState(StateContext& context) : +State(), +m_context(context), +m_text(context) +{ +} + +void MouseClickState::Enter(Ndk::StateMachine& fsm) +{ + m_text.SetVisible(true); + DrawMenu(); + + Nz::EventHandler& eventHandler = m_context.window.GetEventHandler(); + m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, [&] (const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& key) + { + if (key.code == Nz::Keyboard::Key::M && key.shift) + { + fsm.ChangeState(StateFactory::Get(EventStatus::Menu)); + } + }); + + m_mouseButtonDoubleClickedSlot.Connect(eventHandler.OnMouseButtonDoubleClicked, [&] (const Nz::EventHandler*, const Nz::WindowEvent::MouseButtonEvent& mouse) + { + ManageInput(MouseStatus::DoubleClick, mouse, fsm); + }); + + m_mouseButtonPressedSlot.Connect(eventHandler.OnMouseButtonPressed, [&] (const Nz::EventHandler*, const Nz::WindowEvent::MouseButtonEvent& mouse) + { + ManageInput(MouseStatus::Pressed, mouse, fsm); + }); + + m_mouseButtonReleasedSlot.Connect(eventHandler.OnMouseButtonReleased, [&] (const Nz::EventHandler*, const Nz::WindowEvent::MouseButtonEvent& mouse) + { + ManageInput(MouseStatus::Released, mouse, fsm); + }); +} + +void MouseClickState::Leave(Ndk::StateMachine& /*fsm*/) +{ + m_text.SetVisible(false); +} + +bool MouseClickState::Update(Ndk::StateMachine& /*fsm*/, float /*elapsedTime*/) +{ + return true; +} + +void MouseClickState::DrawMenu() +{ + m_text.SetContent("Click in the windows, this text should change !\nM for Menu"); +} + +void MouseClickState::ManageInput(MouseStatus mouseStatus, const Nz::WindowEvent::MouseButtonEvent& mouse, Ndk::StateMachine& fsm) +{ + Nz::String content; + if (mouseStatus == MouseStatus::Pressed) + content = "Pressed: "; + else if (mouseStatus == MouseStatus::Released) + content = "Released: "; + else + content = "Double clicked: "; + + switch (mouse.button) + { + case Nz::Mouse::Left: + content += "Left"; + break; + case Nz::Mouse::Middle: + content += "Middle"; + break; + case Nz::Mouse::Right: + content += "Right"; + break; + case Nz::Mouse::XButton1: + content += "XButton1"; + break; + case Nz::Mouse::XButton2: + content += "XButton2"; + break; + default: + content += "Unknown"; + break; + } + + m_text.SetContent(content + "\nM for Menu"); +} \ No newline at end of file diff --git a/tests/Engine/Utility/EventHandler/MouseClickState.hpp b/tests/Engine/Utility/EventHandler/MouseClickState.hpp new file mode 100644 index 000000000..28c4203a9 --- /dev/null +++ b/tests/Engine/Utility/EventHandler/MouseClickState.hpp @@ -0,0 +1,40 @@ +#ifndef __MOUSECLICKSTATE_HPP__ +#define __MOUSECLICKSTATE_HPP__ + +#include "Text.hpp" + +#include + +#include + +class StateContext; + +enum class MouseStatus +{ + DoubleClick, + Pressed, + Released +}; + +class MouseClickState : public Ndk::State +{ + public: + MouseClickState(StateContext& stateContext); + + void Enter(Ndk::StateMachine& fsm) override; + void Leave(Ndk::StateMachine& fsm) override; + bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + + private: + void DrawMenu(); + void ManageInput(MouseStatus mouseStatus, const Nz::WindowEvent::MouseButtonEvent& mouse, Ndk::StateMachine& fsm); + + StateContext& m_context; + Text m_text; + NazaraSlot(Nz::EventHandler, OnKeyPressed, m_keyPressedSlot); + NazaraSlot(Nz::EventHandler, OnMouseButtonDoubleClicked, m_mouseButtonDoubleClickedSlot); + NazaraSlot(Nz::EventHandler, OnMouseButtonPressed, m_mouseButtonPressedSlot); + NazaraSlot(Nz::EventHandler, OnMouseButtonReleased, m_mouseButtonReleasedSlot); +}; + +#endif // __MOUSECLICKSTATE_HPP__ \ No newline at end of file diff --git a/tests/Engine/Utility/EventHandler/MouseEnterState.cpp b/tests/Engine/Utility/EventHandler/MouseEnterState.cpp new file mode 100644 index 000000000..2a13f1c1e --- /dev/null +++ b/tests/Engine/Utility/EventHandler/MouseEnterState.cpp @@ -0,0 +1,54 @@ +#include "MouseEnterState.hpp" + +#include "StateContext.hpp" +#include "StateFactory.hpp" + +#include +#include + +MouseEnterState::MouseEnterState(StateContext& context) : +State(), +m_context(context), +m_text(context) +{ +} + +void MouseEnterState::Enter(Ndk::StateMachine& fsm) +{ + m_text.SetVisible(true); + DrawMenu(); + + Nz::EventHandler& eventHandler = m_context.window.GetEventHandler(); + m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, [&] (const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& key) + { + if (key.code == Nz::Keyboard::Key::M && key.shift) + { + fsm.ChangeState(StateFactory::Get(EventStatus::Menu)); + } + }); + + m_mouseEnteredSlot.Connect(eventHandler.OnMouseEntered, [&] (const Nz::EventHandler*) + { + m_text.SetContent("Entered\nM for Menu"); + }); + + m_mouseLeftSlot.Connect(eventHandler.OnMouseLeft, [&] (const Nz::EventHandler*) + { + m_text.SetContent("Left\nM for Menu"); + }); +} + +void MouseEnterState::Leave(Ndk::StateMachine& /*fsm*/) +{ + m_text.SetVisible(false); +} + +bool MouseEnterState::Update(Ndk::StateMachine& /*fsm*/, float /*elapsedTime*/) +{ + return true; +} + +void MouseEnterState::DrawMenu() +{ + m_text.SetContent("Move your mouse outside the windows, this text should change !\nM for Menu"); +} \ No newline at end of file diff --git a/tests/Engine/Utility/EventHandler/MouseEnterState.hpp b/tests/Engine/Utility/EventHandler/MouseEnterState.hpp new file mode 100644 index 000000000..b5c7a72be --- /dev/null +++ b/tests/Engine/Utility/EventHandler/MouseEnterState.hpp @@ -0,0 +1,31 @@ +#ifndef __MOUSEENTERSTATE_HPP__ +#define __MOUSEENTERSTATE_HPP__ + +#include "Text.hpp" + +#include + +#include + +class StateContext; + +class MouseEnterState : public Ndk::State +{ + public: + MouseEnterState(StateContext& stateContext); + + void Enter(Ndk::StateMachine& fsm) override; + void Leave(Ndk::StateMachine& fsm) override; + bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + + private: + void DrawMenu(); + + StateContext& m_context; + Text m_text; + NazaraSlot(Nz::EventHandler, OnKeyPressed, m_keyPressedSlot); + NazaraSlot(Nz::EventHandler, OnMouseEntered, m_mouseEnteredSlot); + NazaraSlot(Nz::EventHandler, OnMouseLeft, m_mouseLeftSlot); +}; + +#endif // __MOUSEENTERSTATE_HPP__ \ No newline at end of file diff --git a/tests/Engine/Utility/EventHandler/MouseMoveState.cpp b/tests/Engine/Utility/EventHandler/MouseMoveState.cpp new file mode 100644 index 000000000..6a2cbd947 --- /dev/null +++ b/tests/Engine/Utility/EventHandler/MouseMoveState.cpp @@ -0,0 +1,54 @@ +#include "MouseMoveState.hpp" + +#include "StateContext.hpp" +#include "StateFactory.hpp" + +#include +#include + +MouseMoveState::MouseMoveState(StateContext& context) : +State(), +m_context(context), +m_text(context) +{ +} + +void MouseMoveState::Enter(Ndk::StateMachine& fsm) +{ + m_text.SetVisible(true); + DrawMenu(); + + Nz::EventHandler& eventHandler = m_context.window.GetEventHandler(); + m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, [&] (const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& key) + { + if (key.code == Nz::Keyboard::Key::M && key.shift) + { + fsm.ChangeState(StateFactory::Get(EventStatus::Menu)); + } + }); + + m_mouseMovedSlot.Connect(eventHandler.OnMouseMoved, [&] (const Nz::EventHandler*, const Nz::WindowEvent::MouseMoveEvent& event) + { + m_text.SetContent("Position(" + Nz::String::Number(event.x) + ", " + Nz::String::Number(event.y) + ") delta: (" + Nz::String::Number(event.deltaX) + ", " + Nz::String::Number(event.deltaY) + ") \nM for Menu"); + }); + + m_mouseWheelMovedSlot.Connect(eventHandler.OnMouseWheelMoved, [&] (const Nz::EventHandler*, const Nz::WindowEvent::MouseWheelEvent& event) + { + m_text.SetContent("Wheel delta: " + Nz::String::Number(event.delta) + "\nM for Menu"); + }); +} + +void MouseMoveState::Leave(Ndk::StateMachine& /*fsm*/) +{ + m_text.SetVisible(false); +} + +bool MouseMoveState::Update(Ndk::StateMachine& /*fsm*/, float /*elapsedTime*/) +{ + return true; +} + +void MouseMoveState::DrawMenu() +{ + m_text.SetContent("Move your mouse or your wheel, this text should change !\nM for Menu"); +} \ No newline at end of file diff --git a/tests/Engine/Utility/EventHandler/MouseMoveState.hpp b/tests/Engine/Utility/EventHandler/MouseMoveState.hpp new file mode 100644 index 000000000..f94dc0998 --- /dev/null +++ b/tests/Engine/Utility/EventHandler/MouseMoveState.hpp @@ -0,0 +1,31 @@ +#ifndef __MOUSEMOVESTATE_HPP__ +#define __MOUSEMOVESTATE_HPP__ + +#include "Text.hpp" + +#include + +#include + +class StateContext; + +class MouseMoveState : public Ndk::State +{ + public: + MouseMoveState(StateContext& stateContext); + + void Enter(Ndk::StateMachine& fsm) override; + void Leave(Ndk::StateMachine& fsm) override; + bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + + private: + void DrawMenu(); + + StateContext& m_context; + Text m_text; + NazaraSlot(Nz::EventHandler, OnKeyPressed, m_keyPressedSlot); + NazaraSlot(Nz::EventHandler, OnMouseMoved, m_mouseMovedSlot); + NazaraSlot(Nz::EventHandler, OnMouseWheelMoved, m_mouseWheelMovedSlot); +}; + +#endif // __MOUSEMOVESTATE_HPP__ \ No newline at end of file diff --git a/tests/Engine/Utility/EventHandler/StateContext.cpp b/tests/Engine/Utility/EventHandler/StateContext.cpp new file mode 100644 index 000000000..69739a616 --- /dev/null +++ b/tests/Engine/Utility/EventHandler/StateContext.cpp @@ -0,0 +1,7 @@ +#include "StateContext.hpp" + +StateContext::StateContext(Nz::RenderWindow& windowContext, Ndk::World& worldContext) : +window(windowContext), +world(worldContext) +{ +} diff --git a/tests/Engine/Utility/EventHandler/StateContext.hpp b/tests/Engine/Utility/EventHandler/StateContext.hpp new file mode 100644 index 000000000..62614e073 --- /dev/null +++ b/tests/Engine/Utility/EventHandler/StateContext.hpp @@ -0,0 +1,23 @@ +#ifndef __STATECONTEXT_HPP__ +#define __STATECONTEXT_HPP__ + +namespace Ndk +{ + class World; +} + +namespace Nz +{ + class RenderWindow; +} + +class StateContext +{ + public: + StateContext(Nz::RenderWindow& window, Ndk::World& world); + + Nz::RenderWindow& window; + Ndk::World& world; +}; + +#endif // __STATECONTEXT_HPP__ diff --git a/tests/Engine/Utility/EventHandler/StateFactory.cpp b/tests/Engine/Utility/EventHandler/StateFactory.cpp new file mode 100644 index 000000000..8086dea6b --- /dev/null +++ b/tests/Engine/Utility/EventHandler/StateFactory.cpp @@ -0,0 +1,46 @@ +#include "StateFactory.hpp" + +#include "MenuState.hpp" +#include "EventState.hpp" +#include "FocusState.hpp" +#include "KeyState.hpp" +#include "MouseClickState.hpp" +#include "MouseEnterState.hpp" +#include "MouseMoveState.hpp" +#include "TextEnterState.hpp" +#include "WindowModificationState.hpp" + +std::shared_ptr StateFactory::Get(EventStatus state) +{ + return s_states[state]; +} + +std::shared_ptr StateFactory::Get(unsigned int state) +{ + NazaraAssert(state < s_states.size(), "State out of range"); + auto it = s_states.begin(); + std::advance(it, state); + return it->second; +} + +bool StateFactory::Initialize(StateContext& context) +{ + s_states.emplace(std::make_pair(EventStatus::Menu, std::make_shared(context))); + s_states.emplace(std::make_pair(EventStatus::Event, std::make_shared(context))); + s_states.emplace(std::make_pair(EventStatus::Focus, std::make_shared(context))); + s_states.emplace(std::make_pair(EventStatus::Key, std::make_shared(context))); + s_states.emplace(std::make_pair(EventStatus::MouseClick, std::make_shared(context))); + s_states.emplace(std::make_pair(EventStatus::MouseEnter, std::make_shared(context))); + s_states.emplace(std::make_pair(EventStatus::MouseMove, std::make_shared(context))); + s_states.emplace(std::make_pair(EventStatus::TextEnter, std::make_shared(context))); + s_states.emplace(std::make_pair(EventStatus::WindowModification, std::make_shared(context))); + + return true; +} + +void StateFactory::Uninitialize() +{ + s_states.clear(); +} + +std::map> StateFactory::s_states; \ No newline at end of file diff --git a/tests/Engine/Utility/EventHandler/StateFactory.hpp b/tests/Engine/Utility/EventHandler/StateFactory.hpp new file mode 100644 index 000000000..a17965d9d --- /dev/null +++ b/tests/Engine/Utility/EventHandler/StateFactory.hpp @@ -0,0 +1,42 @@ +#ifndef __STATEFACTORY_HPP__ +#define __STATEFACTORY_HPP__ + +#include + +#include +#include + +class StateContext; + +enum class EventStatus +{ + Min = 0, + Menu, + Event, + Focus, + Key, + MouseClick, + MouseEnter, + MouseMove, + TextEnter, + WindowModification, + Max = WindowModification +}; + +class StateFactory +{ + public: + + static std::shared_ptr Get(EventStatus state); + static std::shared_ptr Get(unsigned int state); + + static bool Initialize(StateContext& stateContext); + + static void Uninitialize(); + + private: + + static std::map> s_states; +}; + +#endif // __STATEFACTORY_HPP__ diff --git a/tests/Engine/Utility/EventHandler/Text.cpp b/tests/Engine/Utility/EventHandler/Text.cpp new file mode 100644 index 000000000..75cece5b9 --- /dev/null +++ b/tests/Engine/Utility/EventHandler/Text.cpp @@ -0,0 +1,35 @@ +#include "Text.hpp" + +#include +#include +#include +#include +#include +#include + +Text::Text(StateContext& stateContext) : +m_context(stateContext) +{ + m_text = m_context.world.CreateEntity(); + Ndk::NodeComponent& nodeComponent = m_text->AddComponent(); + Ndk::GraphicsComponent& graphicsComponent = m_text->AddComponent(); + + m_textSprite = Nz::TextSprite::New(); + graphicsComponent.Attach(m_textSprite); +} + +Text::~Text() +{ + m_textSprite->Clear(); + m_text->Kill(); +} + +void Text::SetContent(const Nz::String& string, unsigned int size) +{ + m_textSprite->Update(Nz::SimpleTextDrawer::Draw(string, size)); +} + +void Text::SetVisible(bool shouldBeVisible) +{ + m_text->Enable(shouldBeVisible); +} \ No newline at end of file diff --git a/tests/Engine/Utility/EventHandler/Text.hpp b/tests/Engine/Utility/EventHandler/Text.hpp new file mode 100644 index 000000000..a804b4baa --- /dev/null +++ b/tests/Engine/Utility/EventHandler/Text.hpp @@ -0,0 +1,23 @@ +#ifndef __TEXT_HPP__ +#define __TEXT_HPP__ + +#include +#include +#include "StateContext.hpp" + +class Text +{ + public: + Text(StateContext& context); + ~Text(); + + void SetContent(const Nz::String& string, unsigned int size = 36); + void SetVisible(bool shouldBeVisible = true); + + private: + StateContext& m_context; + Ndk::EntityHandle m_text; + Nz::TextSpriteRef m_textSprite; +}; + +#endif // __TEXT_HPP__ \ No newline at end of file diff --git a/tests/Engine/Utility/EventHandler/TextEnterState.cpp b/tests/Engine/Utility/EventHandler/TextEnterState.cpp new file mode 100644 index 000000000..1a0516f29 --- /dev/null +++ b/tests/Engine/Utility/EventHandler/TextEnterState.cpp @@ -0,0 +1,52 @@ +#include "TextEnterState.hpp" + +#include "StateContext.hpp" +#include "StateFactory.hpp" + +#include +#include + +TextEnterState::TextEnterState(StateContext& context) : +State(), +m_context(context), +m_text(context) +{ +} + +void TextEnterState::Enter(Ndk::StateMachine& fsm) +{ + m_text.SetVisible(true); + DrawMenu(); + + Nz::EventHandler& eventHandler = m_context.window.GetEventHandler(); + m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, [&] (const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& key) + { + if (key.code == Nz::Keyboard::Key::M && key.shift) + { + fsm.ChangeState(StateFactory::Get(EventStatus::Menu)); + } + }); + + m_textEnteredSlot.Connect(eventHandler.OnTextEntered, [&] (const Nz::EventHandler*, const Nz::WindowEvent::TextEvent& event) + { + Nz::String content = "Character: " + Nz::String::Unicode(event.character); + if (event.repeated) + content += " repeated"; + m_text.SetContent(content + "\nM for Menu"); + }); +} + +void TextEnterState::Leave(Ndk::StateMachine& /*fsm*/) +{ + m_text.SetVisible(false); +} + +bool TextEnterState::Update(Ndk::StateMachine& /*fsm*/, float /*elapsedTime*/) +{ + return true; +} + +void TextEnterState::DrawMenu() +{ + m_text.SetContent("Enter some text, this text should change !\nM for Menu"); +} \ No newline at end of file diff --git a/tests/Engine/Utility/EventHandler/TextEnterState.hpp b/tests/Engine/Utility/EventHandler/TextEnterState.hpp new file mode 100644 index 000000000..c9137c51d --- /dev/null +++ b/tests/Engine/Utility/EventHandler/TextEnterState.hpp @@ -0,0 +1,30 @@ +#ifndef __TEXTENTERSTATE_HPP__ +#define __TEXTENTERSTATE_HPP__ + +#include "Text.hpp" + +#include + +#include + +class StateContext; + +class TextEnterState : public Ndk::State +{ + public: + TextEnterState(StateContext& stateContext); + + void Enter(Ndk::StateMachine& fsm) override; + void Leave(Ndk::StateMachine& fsm) override; + bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + + private: + void DrawMenu(); + + StateContext& m_context; + Text m_text; + NazaraSlot(Nz::EventHandler, OnKeyPressed, m_keyPressedSlot); + NazaraSlot(Nz::EventHandler, OnTextEntered, m_textEnteredSlot); +}; + +#endif // __TEXTENTERSTATE_HPP__ \ No newline at end of file diff --git a/tests/Engine/Utility/EventHandler/WindowModificationState.cpp b/tests/Engine/Utility/EventHandler/WindowModificationState.cpp new file mode 100644 index 000000000..e50d94f51 --- /dev/null +++ b/tests/Engine/Utility/EventHandler/WindowModificationState.cpp @@ -0,0 +1,54 @@ +#include "WindowModificationState.hpp" + +#include "StateContext.hpp" +#include "StateFactory.hpp" + +#include +#include + +WindowModificationState::WindowModificationState(StateContext& context) : +State(), +m_context(context), +m_text(context) +{ +} + +void WindowModificationState::Enter(Ndk::StateMachine& fsm) +{ + m_text.SetVisible(true); + DrawMenu(); + + Nz::EventHandler& eventHandler = m_context.window.GetEventHandler(); + m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, [&] (const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& key) + { + if (key.code == Nz::Keyboard::Key::M && key.shift) + { + fsm.ChangeState(StateFactory::Get(EventStatus::Menu)); + } + }); + + m_movedSlot.Connect(eventHandler.OnMoved, [&] (const Nz::EventHandler*, const Nz::WindowEvent::PositionEvent& event) + { + m_text.SetContent("Position(" + Nz::String::Number(event.x) + ", " + Nz::String::Number(event.y) + ")\nM for Menu"); + }); + + m_resizedSlot.Connect(eventHandler.OnResized, [&] (const Nz::EventHandler*, const Nz::WindowEvent::SizeEvent& event) + { + m_text.SetContent("Size(" + Nz::String::Number(event.width) + ", " + Nz::String::Number(event.height) + ")\nM for Menu"); + }); +} + +void WindowModificationState::Leave(Ndk::StateMachine& /*fsm*/) +{ + m_text.SetVisible(false); +} + +bool WindowModificationState::Update(Ndk::StateMachine& /*fsm*/, float /*elapsedTime*/) +{ + return true; +} + +void WindowModificationState::DrawMenu() +{ + m_text.SetContent("Move the window or resize it, this text should change !\nM for Menu"); +} \ No newline at end of file diff --git a/tests/Engine/Utility/EventHandler/WindowModificationState.hpp b/tests/Engine/Utility/EventHandler/WindowModificationState.hpp new file mode 100644 index 000000000..4fb84188d --- /dev/null +++ b/tests/Engine/Utility/EventHandler/WindowModificationState.hpp @@ -0,0 +1,31 @@ +#ifndef __WINDOWMODIFICATIONSTATE_HPP__ +#define __WINDOWMODIFICATIONSTATE_HPP__ + +#include "Text.hpp" + +#include + +#include + +class StateContext; + +class WindowModificationState : public Ndk::State +{ + public: + WindowModificationState(StateContext& stateContext); + + void Enter(Ndk::StateMachine& fsm) override; + void Leave(Ndk::StateMachine& fsm) override; + bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + + private: + void DrawMenu(); + + StateContext& m_context; + Text m_text; + NazaraSlot(Nz::EventHandler, OnKeyPressed, m_keyPressedSlot); + NazaraSlot(Nz::EventHandler, OnMoved, m_movedSlot); + NazaraSlot(Nz::EventHandler, OnResized, m_resizedSlot); +}; + +#endif // __WINDOWMODIFICATIONSTATE_HPP__ \ No newline at end of file diff --git a/tests/SDK/NDK/BaseSystem.cpp b/tests/SDK/NDK/BaseSystem.cpp index e4ca2e1c9..a202c1f70 100644 --- a/tests/SDK/NDK/BaseSystem.cpp +++ b/tests/SDK/NDK/BaseSystem.cpp @@ -20,7 +20,7 @@ namespace static Ndk::SystemIndex systemIndex; private: - void OnUpdate(float elapsedTime) override + void OnUpdate(float /*elapsedTime*/) override { } }; diff --git a/tests/SDK/NDK/Entity.cpp b/tests/SDK/NDK/Entity.cpp index d784e28ad..cf02370ec 100644 --- a/tests/SDK/NDK/Entity.cpp +++ b/tests/SDK/NDK/Entity.cpp @@ -38,7 +38,7 @@ namespace static Ndk::SystemIndex systemIndex; private: - void OnUpdate(float elapsedTime) override + void OnUpdate(float /*elapsedTime*/) override { for (const Ndk::EntityHandle& entity : GetEntities()) { diff --git a/tests/SDK/NDK/StateMachine.cpp b/tests/SDK/NDK/StateMachine.cpp index 44b0e0dfd..1c14b1e76 100644 --- a/tests/SDK/NDK/StateMachine.cpp +++ b/tests/SDK/NDK/StateMachine.cpp @@ -4,7 +4,7 @@ class TestState : public Ndk::State { public: - void Enter(Ndk::StateMachine& fsm) override + void Enter(Ndk::StateMachine& /*fsm*/) override { m_isUpdated = false; } @@ -14,11 +14,11 @@ class TestState : public Ndk::State return m_isUpdated; } - void Leave(Ndk::StateMachine& fsm) override + void Leave(Ndk::StateMachine& /*fsm*/) override { } - bool Update(Ndk::StateMachine& fsm, float elapsedTime) override + bool Update(Ndk::StateMachine& /*fsm*/, float /*elapsedTime*/) override { m_isUpdated = true; return true; diff --git a/tests/SDK/NDK/System.cpp b/tests/SDK/NDK/System.cpp index 623b4a96f..d965e37f3 100644 --- a/tests/SDK/NDK/System.cpp +++ b/tests/SDK/NDK/System.cpp @@ -23,7 +23,7 @@ namespace private: int m_value; - void OnUpdate(float elapsedTime) override + void OnUpdate(float /*elapsedTime*/) override { } }; diff --git a/tests/SDK/NDK/Systems/PhysicsSystem.cpp b/tests/SDK/NDK/Systems/PhysicsSystem3D.cpp similarity index 73% rename from tests/SDK/NDK/Systems/PhysicsSystem.cpp rename to tests/SDK/NDK/Systems/PhysicsSystem3D.cpp index 2aa3c313e..3cb0d6bdb 100644 --- a/tests/SDK/NDK/Systems/PhysicsSystem.cpp +++ b/tests/SDK/NDK/Systems/PhysicsSystem3D.cpp @@ -1,8 +1,8 @@ -#include +#include #include -#include +#include #include -#include +#include #include SCENARIO("PhysicsSystem", "[NDK][PHYSICSSYSTEM]") @@ -11,12 +11,12 @@ SCENARIO("PhysicsSystem", "[NDK][PHYSICSSYSTEM]") { Ndk::World world; const Ndk::EntityHandle& staticEntity = world.CreateEntity(); - Ndk::CollisionComponent& collisionComponentStatic = staticEntity->AddComponent(); + Ndk::CollisionComponent3D& collisionComponentStatic = staticEntity->AddComponent(); Ndk::NodeComponent& nodeComponentStatic = staticEntity->AddComponent(); const Ndk::EntityHandle& dynamicEntity = world.CreateEntity(); Ndk::NodeComponent& nodeComponentDynamic = dynamicEntity->AddComponent(); - Ndk::PhysicsComponent& physicsComponentDynamic = dynamicEntity->AddComponent(); + Ndk::PhysicsComponent3D& physicsComponentDynamic = dynamicEntity->AddComponent(); WHEN("We make collide these two entities") { diff --git a/tests/SDK/NDK/World.cpp b/tests/SDK/NDK/World.cpp index 431490490..85ee241b4 100644 --- a/tests/SDK/NDK/World.cpp +++ b/tests/SDK/NDK/World.cpp @@ -38,7 +38,7 @@ namespace static Ndk::SystemIndex systemIndex; private: - void OnUpdate(float elapsedTime) override + void OnUpdate(float /*elapsedTime*/) override { for (const Ndk::EntityHandle& entity : GetEntities()) {