diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..ee31794e8 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,16 @@ +# http://editorconfig.org/ + +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{hpp,inl,cpp,lua}] +indent_style = tab + +[*.html] +indent_size = 4 +indent_style = space diff --git a/.gitignore b/.gitignore index 7bdc61c6c..86ee68bd1 100644 --- a/.gitignore +++ b/.gitignore @@ -35,6 +35,7 @@ build/scripts/features/index.html doc # Codeblocks +*.save-failed build/**/*.cbp build/**/*.cbp build/**/*.cbTemp @@ -46,6 +47,9 @@ build/**/*.workspace # CodeLite build/**/*.project +# GMake +build/**/*.make + # Visual Studio build/**/*.pdb build/**/*.filters diff --git a/Doxyfile b/Doxyfile index 47af03df4..04a327a38 100644 --- a/Doxyfile +++ b/Doxyfile @@ -38,7 +38,7 @@ PROJECT_NAME = "Nazara Engine" # could be handy for archiving the generated documentation or if some version # control system is used. -PROJECT_NUMBER = 0.1 +PROJECT_NUMBER = 0.2 # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer a diff --git a/SDK/include/NDK/Application.inl b/SDK/include/NDK/Application.inl index d26a2daa8..0b4f2ce10 100644 --- a/SDK/include/NDK/Application.inl +++ b/SDK/include/NDK/Application.inl @@ -59,7 +59,7 @@ namespace Ndk * \param args Arguments used to create the window */ #ifndef NDK_SERVER - template + template T& Application::AddWindow(Args&&... args) { static_assert(std::is_base_of::value, "Type must inherit Window"); @@ -82,7 +82,7 @@ namespace Ndk * \param args Arguments used to create the world */ - template + template World& Application::AddWorld(Args&&... args) { m_worlds.emplace_back(std::forward(args)...); @@ -373,9 +373,9 @@ namespace Ndk { } - inline Application::WindowInfo::WindowInfo(std::unique_ptr&& window) : + inline Application::WindowInfo::WindowInfo(std::unique_ptr&& windowPtr) : renderTarget(nullptr), - window(std::move(window)) + window(std::move(windowPtr)) { } #endif diff --git a/SDK/include/NDK/BaseSystem.hpp b/SDK/include/NDK/BaseSystem.hpp index a4ff0bf41..7433f7d04 100644 --- a/SDK/include/NDK/BaseSystem.hpp +++ b/SDK/include/NDK/BaseSystem.hpp @@ -35,6 +35,7 @@ namespace Ndk inline const std::vector& GetEntities() const; inline SystemIndex GetIndex() const; + inline int GetUpdateOrder() const; inline float GetUpdateRate() const; inline World& GetWorld() const; @@ -42,6 +43,7 @@ namespace Ndk inline bool HasEntity(const Entity* entity) const; + void SetUpdateOrder(int updateOrder); inline void SetUpdateRate(float updatePerSecond); inline void Update(float elapsedTime); @@ -93,6 +95,7 @@ namespace Ndk bool m_updateEnabled; float m_updateCounter; float m_updateRate; + int m_updateOrder; static SystemIndex s_nextIndex; }; diff --git a/SDK/include/NDK/BaseSystem.inl b/SDK/include/NDK/BaseSystem.inl index 31a0c314e..79971e3d6 100644 --- a/SDK/include/NDK/BaseSystem.inl +++ b/SDK/include/NDK/BaseSystem.inl @@ -16,7 +16,9 @@ namespace Ndk inline BaseSystem::BaseSystem(SystemIndex systemId) : m_systemIndex(systemId), - m_updateEnabled(true) + m_world(nullptr), + m_updateEnabled(true), + m_updateOrder(0) { SetUpdateRate(30); } @@ -33,7 +35,8 @@ namespace Ndk m_systemIndex(system.m_systemIndex), m_updateEnabled(system.m_updateEnabled), m_updateCounter(0.f), - m_updateRate(system.m_updateRate) + m_updateRate(system.m_updateRate), + m_updateOrder(system.m_updateOrder) { } @@ -69,7 +72,18 @@ namespace Ndk } /*! - * \brief Gets the rate of update for the system + * \brief Gets the update order of the system + * \return Update order + * + * \see SetUpdateOrder + */ + inline int BaseSystem::GetUpdateOrder() const + { + return m_updateOrder; + } + + /*! + * \brief Gets the rate of update of the system * \return Update rate */ diff --git a/SDK/include/NDK/Components.hpp b/SDK/include/NDK/Components.hpp index 3338e5f52..3a2916009 100644 --- a/SDK/include/NDK/Components.hpp +++ b/SDK/include/NDK/Components.hpp @@ -6,6 +6,7 @@ #define NDK_COMPONENTS_GLOBAL_HPP #include +#include #include #include #include @@ -13,6 +14,7 @@ #include #include #include +#include #include #include diff --git a/SDK/include/NDK/Components/CameraComponent.hpp b/SDK/include/NDK/Components/CameraComponent.hpp index b26901a79..6bb3718c0 100644 --- a/SDK/include/NDK/Components/CameraComponent.hpp +++ b/SDK/include/NDK/Components/CameraComponent.hpp @@ -18,9 +18,12 @@ namespace Ndk { + class CameraComponent; class Entity; - class NDK_API CameraComponent : public Component, public Nz::AbstractViewer + using CameraComponentHandle = Nz::ObjectHandle; + + class NDK_API CameraComponent : public Component, public Nz::AbstractViewer, public Nz::HandledObject { public: inline CameraComponent(); @@ -51,7 +54,7 @@ namespace Ndk float GetZNear() const override; inline void SetFOV(float fov); - inline void SetLayer(unsigned int layer); + void SetLayer(unsigned int layer); inline void SetProjectionType(Nz::ProjectionType projection); inline void SetSize(const Nz::Vector2f& size); inline void SetSize(float width, float height); diff --git a/SDK/include/NDK/Components/CameraComponent.inl b/SDK/include/NDK/Components/CameraComponent.inl index 541096de5..550cbd7b4 100644 --- a/SDK/include/NDK/Components/CameraComponent.inl +++ b/SDK/include/NDK/Components/CameraComponent.inl @@ -99,7 +99,7 @@ namespace Ndk * \brief Gets the field of view of the camera * \return Field of view of the camera */ - float CameraComponent::GetFOV() const + inline float CameraComponent::GetFOV() const { return m_fov; } diff --git a/SDK/include/NDK/Components/CollisionComponent2D.hpp b/SDK/include/NDK/Components/CollisionComponent2D.hpp new file mode 100644 index 000000000..b282a850e --- /dev/null +++ b/SDK/include/NDK/Components/CollisionComponent2D.hpp @@ -0,0 +1,58 @@ +// 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_COMPONENTS_COLLISIONCOMPONENT2D_HPP +#define NDK_COMPONENTS_COLLISIONCOMPONENT2D_HPP + +#include +#include +#include + +namespace Nz +{ + class RigidBody2D; +} + +namespace Ndk +{ + class Entity; + + class NDK_API CollisionComponent2D : public Component + { + friend class PhysicsSystem2D; + + public: + CollisionComponent2D(Nz::Collider2DRef geom = Nz::Collider2DRef()); + CollisionComponent2D(const CollisionComponent2D& collision); + ~CollisionComponent2D() = default; + + const Nz::Collider2DRef& GetGeom() const; + + void SetGeom(Nz::Collider2DRef geom); + + CollisionComponent2D& operator=(Nz::Collider2DRef geom); + CollisionComponent2D& operator=(CollisionComponent2D&& collision) = default; + + static ComponentIndex componentIndex; + + private: + void InitializeStaticBody(); + Nz::RigidBody2D* GetStaticBody(); + + void OnAttached() override; + void OnComponentAttached(BaseComponent& component) override; + void OnComponentDetached(BaseComponent& component) override; + void OnDetached() override; + + std::unique_ptr m_staticBody; + Nz::Collider2DRef m_geom; + bool m_bodyUpdated; + }; +} + +#include + +#endif // NDK_COMPONENTS_COLLISIONCOMPONENT2D_HPP diff --git a/SDK/include/NDK/Components/CollisionComponent2D.inl b/SDK/include/NDK/Components/CollisionComponent2D.inl new file mode 100644 index 000000000..62bf422cb --- /dev/null +++ b/SDK/include/NDK/Components/CollisionComponent2D.inl @@ -0,0 +1,70 @@ +// 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 + +#include +#include +#include +#include +#include + +namespace Ndk +{ + /*! + * \brief Constructs a CollisionComponent2D object with a geometry + * + * \param geom Reference to a geometry symbolizing the entity + */ + + inline CollisionComponent2D::CollisionComponent2D(Nz::Collider2DRef geom) : + m_geom(std::move(geom)), + m_bodyUpdated(false) + { + } + + /*! + * \brief Constructs a CollisionComponent2D object by copy semantic + * + * \param collision CollisionComponent2D to copy + */ + + inline CollisionComponent2D::CollisionComponent2D(const CollisionComponent2D& collision) : + m_geom(collision.m_geom), + m_bodyUpdated(false) + { + } + + /*! + * \brief Gets the geometry representing the entity + * \return A constant reference to the physics geometry + */ + + inline const Nz::Collider2DRef& CollisionComponent2D::GetGeom() const + { + return m_geom; + } + + /*! + * \brief Assigns the geometry to this component + * \return A reference to this + * + * \param geom Reference to a geometry symbolizing the entity + */ + + inline CollisionComponent2D& CollisionComponent2D::operator=(Nz::Collider2DRef geom) + { + SetGeom(geom); + + return *this; + } + + /*! + * \brief Gets the static body used by the entity + * \return A pointer to the entity + */ + + inline Nz::RigidBody2D* CollisionComponent2D::GetStaticBody() + { + return m_staticBody.get(); + } +} diff --git a/SDK/include/NDK/Components/CollisionComponent3D.hpp b/SDK/include/NDK/Components/CollisionComponent3D.hpp index f6a07ede6..9a9671660 100644 --- a/SDK/include/NDK/Components/CollisionComponent3D.hpp +++ b/SDK/include/NDK/Components/CollisionComponent3D.hpp @@ -4,8 +4,8 @@ #pragma once -#ifndef NDK_COMPONENTS_COLLISIONCOMPONENT_HPP -#define NDK_COMPONENTS_COLLISIONCOMPONENT_HPP +#ifndef NDK_COMPONENTS_COLLISIONCOMPONENT3D_HPP +#define NDK_COMPONENTS_COLLISIONCOMPONENT3D_HPP #include #include @@ -23,7 +23,6 @@ namespace Ndk class NDK_API CollisionComponent3D : public Component { friend class PhysicsSystem3D; - friend class StaticCollisionSystem; public: CollisionComponent3D(Nz::Collider3DRef geom = Nz::Collider3DRef()); @@ -56,4 +55,4 @@ namespace Ndk #include -#endif // NDK_COMPONENTS_COLLISIONCOMPONENT_HPP +#endif // NDK_COMPONENTS_COLLISIONCOMPONENT3D_HPP diff --git a/SDK/include/NDK/Components/GraphicsComponent.hpp b/SDK/include/NDK/Components/GraphicsComponent.hpp index b536fc154..f8cd6d957 100644 --- a/SDK/include/NDK/Components/GraphicsComponent.hpp +++ b/SDK/include/NDK/Components/GraphicsComponent.hpp @@ -73,19 +73,19 @@ 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) + Renderable(Renderable&& rhs) noexcept : + renderableInvalidationSlot(std::move(rhs.renderableInvalidationSlot)), + renderableReleaseSlot(std::move(rhs.renderableReleaseSlot)), + data(std::move(rhs.data)), + renderable(std::move(rhs.renderable)), + dataUpdated(rhs.dataUpdated) { } ~Renderable() { // Disconnect release slot before releasing instanced renderable reference - renderableReleaseSlot.Disconnect(); + renderableReleaseSlot.Disconnect(); } Renderable& operator=(Renderable&& r) noexcept @@ -118,4 +118,4 @@ namespace Ndk #include #endif // NDK_COMPONENTS_GRAPHICSCOMPONENT_HPP -#endif // NDK_SERVER \ No newline at end of file +#endif // NDK_SERVER diff --git a/SDK/include/NDK/Components/PhysicsComponent2D.hpp b/SDK/include/NDK/Components/PhysicsComponent2D.hpp new file mode 100644 index 000000000..90dd7a5e6 --- /dev/null +++ b/SDK/include/NDK/Components/PhysicsComponent2D.hpp @@ -0,0 +1,65 @@ +// 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_COMPONENTS_PHYSICSCOMPONENT2D_HPP +#define NDK_COMPONENTS_PHYSICSCOMPONENT2D_HPP + +#include +#include +#include + +namespace Ndk +{ + class Entity; + + class NDK_API PhysicsComponent2D : public Component + { + friend class CollisionComponent2D; + friend class PhysicsSystem2D; + + public: + PhysicsComponent2D() = default; + PhysicsComponent2D(const PhysicsComponent2D& physics); + ~PhysicsComponent2D() = default; + + void AddForce(const Nz::Vector2f& force, Nz::CoordSys coordSys = Nz::CoordSys_Global); + void AddForce(const Nz::Vector2f& force, const Nz::Vector2f& point, Nz::CoordSys coordSys = Nz::CoordSys_Global); + void AddTorque(float torque); + + Nz::Rectf GetAABB() const; + float GetAngularVelocity() const; + Nz::Vector2f GetCenterOfGravity(Nz::CoordSys coordSys = Nz::CoordSys_Local) const; + float GetMass() const; + Nz::Vector2f GetPosition() const; + float GetRotation() const; + Nz::Vector2f GetVelocity() const; + + bool IsSleeping() const; + + void SetAngularVelocity(float angularVelocity); + void SetMass(float mass); + void SetMassCenter(const Nz::Vector2f& center); + void SetPosition(const Nz::Vector2f& position); + void SetRotation(float rotation); + void SetVelocity(const Nz::Vector2f& velocity); + + static ComponentIndex componentIndex; + + private: + Nz::RigidBody2D& GetRigidBody(); + + void OnAttached() override; + void OnComponentAttached(BaseComponent& component) override; + void OnComponentDetached(BaseComponent& component) override; + void OnDetached() override; + + std::unique_ptr m_object; + }; +} + +#include + +#endif // NDK_COMPONENTS_PHYSICSCOMPONENT2D_HPP diff --git a/SDK/include/NDK/Components/PhysicsComponent2D.inl b/SDK/include/NDK/Components/PhysicsComponent2D.inl new file mode 100644 index 000000000..312e23e3a --- /dev/null +++ b/SDK/include/NDK/Components/PhysicsComponent2D.inl @@ -0,0 +1,284 @@ +// 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 + +#include +#include "PhysicsComponent2D.hpp" + +namespace Ndk +{ + /*! + * \brief Constructs a PhysicsComponent2D object by copy semantic + * + * \param physics PhysicsComponent2D to copy + */ + + inline PhysicsComponent2D::PhysicsComponent2D(const PhysicsComponent2D& physics) + { + // No copy of physical object (because we only create it when attached to an entity) + NazaraUnused(physics); + } + + /*! + * \brief Applies a physics force to the entity + * + * \param force Force to apply on the entity + * \param coordSys System coordinates to consider + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline void PhysicsComponent2D::AddForce(const Nz::Vector2f& force, Nz::CoordSys coordSys) + { + NazaraAssert(m_object, "Invalid physics object"); + + m_object->AddForce(force, coordSys); + } + + /*! + * \brief Applies a physics force to the entity + * + * \param force Force to apply on the entity + * \param point Point where to apply the force + * \param coordSys System coordinates to consider + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline void PhysicsComponent2D::AddForce(const Nz::Vector2f& force, const Nz::Vector2f& point, Nz::CoordSys coordSys) + { + NazaraAssert(m_object, "Invalid physics object"); + + m_object->AddForce(force, point, coordSys); + } + + /*! + * \brief Applies a torque to the entity + * + * \param torque Torque to apply on the entity + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline void PhysicsComponent2D::AddTorque(float torque) + { + NazaraAssert(m_object, "Invalid physics object"); + + m_object->AddTorque(torque); + } + + /*! + * \brief Gets the AABB of the physics object + * \return AABB of the object + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + inline Nz::Rectf PhysicsComponent2D::GetAABB() const + { + NazaraAssert(m_object, "Invalid physics object"); + + return m_object->GetAABB(); + } + + /*! + * \brief Gets the angular velocity of the physics object + * \return Angular velocity of the object + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline float PhysicsComponent2D::GetAngularVelocity() const + { + NazaraAssert(m_object, "Invalid physics object"); + + return m_object->GetAngularVelocity(); + } + + /*! + * \brief Gets the gravity center of the physics object + * \return Gravity center of the object + * + * \param coordSys System coordinates to consider + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline Nz::Vector2f PhysicsComponent2D::GetCenterOfGravity(Nz::CoordSys coordSys) const + { + NazaraAssert(m_object, "Invalid physics object"); + + return m_object->GetCenterOfGravity(coordSys); + } + + /*! + * \brief Gets the mass of the physics object + * \return Mass of the object + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline float PhysicsComponent2D::GetMass() const + { + NazaraAssert(m_object, "Invalid physics object"); + + return m_object->GetMass(); + } + + /*! + * \brief Gets the position of the physics object + * \return Position of the object + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline Nz::Vector2f PhysicsComponent2D::GetPosition() const + { + NazaraAssert(m_object, "Invalid physics object"); + + return m_object->GetPosition(); + } + + /*! + * \brief Gets the rotation of the physics object + * \return Rotation of the object + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline float PhysicsComponent2D::GetRotation() const + { + NazaraAssert(m_object, "Invalid physics object"); + + return m_object->GetRotation(); + } + + /*! + * \brief Gets the velocity of the physics object + * \return Velocity of the object + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline Nz::Vector2f PhysicsComponent2D::GetVelocity() const + { + NazaraAssert(m_object, "Invalid physics object"); + + return m_object->GetVelocity(); + } + + /*! + * \brief Checks whether the entity is currently sleeping + * \return true If it is the case + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline bool PhysicsComponent2D::IsSleeping() const + { + NazaraAssert(m_object, "Invalid physics object"); + + return m_object->IsSleeping(); + } + + /*! + * \brief Sets the angular velocity of the physics object + * + * \param angularVelocity Angular velocity of the object + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline void PhysicsComponent2D::SetAngularVelocity(float angularVelocity) + { + NazaraAssert(m_object, "Invalid physics object"); + + m_object->SetAngularVelocity(angularVelocity); + } + + /*! + * \brief Sets the mass of the physics object + * + * \param mass Mass of the object + * + * \remark Produces a NazaraAssert if the physics object is invalid + * \remark Produces a NazaraAssert if the mass is negative + */ + + inline void PhysicsComponent2D::SetMass(float mass) + { + NazaraAssert(m_object, "Invalid physics object"); + NazaraAssert(mass > 0.f, "Mass should be positive"); + + m_object->SetMass(mass); + } + + /*! + * \brief Sets the gravity center of the physics object + * + * \param center Gravity center of the object + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline void PhysicsComponent2D::SetMassCenter(const Nz::Vector2f& center) + { + NazaraAssert(m_object, "Invalid physics object"); + + m_object->SetMassCenter(center); + } + + /*! + * \brief Sets the position of the physics object + * + * \param position Position of the object + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline void PhysicsComponent2D::SetPosition(const Nz::Vector2f& position) + { + NazaraAssert(m_object, "Invalid physics object"); + + m_object->SetPosition(position); + } + + /*! + * \brief Sets the rotation of the physics object + * + * \param rotation Rotation of the object + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline void PhysicsComponent2D::SetRotation(float rotation) + { + NazaraAssert(m_object, "Invalid physics object"); + + m_object->SetRotation(rotation); + } + + /*! + * \brief Sets the velocity of the physics object + * + * \param velocity Velocity of the object + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline void PhysicsComponent2D::SetVelocity(const Nz::Vector2f& velocity) + { + NazaraAssert(m_object, "Invalid physics object"); + + m_object->SetVelocity(velocity); + } + + /*! + * \brief Gets the underlying physics object + * \return A reference to the physics object + */ + + inline Nz::RigidBody2D& PhysicsComponent2D::GetRigidBody() + { + return *m_object.get(); + } +} diff --git a/SDK/include/NDK/Components/PhysicsComponent3D.hpp b/SDK/include/NDK/Components/PhysicsComponent3D.hpp index fc1367d84..9fb1bb45e 100644 --- a/SDK/include/NDK/Components/PhysicsComponent3D.hpp +++ b/SDK/include/NDK/Components/PhysicsComponent3D.hpp @@ -56,7 +56,7 @@ namespace Ndk static ComponentIndex componentIndex; private: - Nz::RigidBody3D& GetPhysObject(); + Nz::RigidBody3D& GetRigidBody(); void OnAttached() override; void OnComponentAttached(BaseComponent& component) override; diff --git a/SDK/include/NDK/Components/PhysicsComponent3D.inl b/SDK/include/NDK/Components/PhysicsComponent3D.inl index 84bc36db7..cad098af8 100644 --- a/SDK/include/NDK/Components/PhysicsComponent3D.inl +++ b/SDK/include/NDK/Components/PhysicsComponent3D.inl @@ -350,7 +350,7 @@ namespace Ndk * \return A reference to the physics object */ - inline Nz::RigidBody3D& PhysicsComponent3D::GetPhysObject() + inline Nz::RigidBody3D& PhysicsComponent3D::GetRigidBody() { return *m_object.get(); } diff --git a/SDK/include/NDK/LuaAPI.inl b/SDK/include/NDK/LuaAPI.inl index 1ae2ddd43..f2ddf251c 100644 --- a/SDK/include/NDK/LuaAPI.inl +++ b/SDK/include/NDK/LuaAPI.inl @@ -28,15 +28,6 @@ namespace Nz { - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param color Resulting color - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Color* color, TypeTag) { instance.CheckType(index, Nz::LuaType_Table); @@ -49,15 +40,6 @@ 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 angles Resulting euler angles - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, EulerAnglesd* angles, TypeTag) { switch (instance.GetType(index)) @@ -78,15 +60,6 @@ namespace Nz } } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param angles Resulting euler angles - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, EulerAnglesf* angles, TypeTag) { EulerAnglesd anglesDouble; @@ -96,15 +69,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 fontRef Resulting reference to a font - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, FontRef* fontRef, TypeTag) { *fontRef = *static_cast(instance.CheckUserdata(index, "Font")); @@ -112,15 +76,6 @@ 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 a font - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, FontParams* params, TypeTag) { NazaraUnused(params); @@ -132,14 +87,6 @@ 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); @@ -150,15 +97,6 @@ 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 address Resulting IP address - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, IpAddress* address, TypeTag) { switch (instance.GetType(index)) @@ -173,15 +111,6 @@ namespace Nz } } - /*! - * \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)) @@ -212,33 +141,15 @@ namespace Nz } } - /*! - * \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; + Matrix4d matDouble = Matrix4d::Identity(); unsigned int ret = LuaImplQueryArg(instance, index, &matDouble, TypeTag()); mat->Set(matDouble); 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 params Resulting parameters for a mesh - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MeshParams* params, TypeTag) { instance.CheckType(index, Nz::LuaType_Table); @@ -252,15 +163,6 @@ 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 quat Resulting quaternion - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Quaterniond* quat, TypeTag) { switch (instance.GetType(index)) @@ -281,15 +183,6 @@ namespace Nz } } - /*! - * \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; @@ -299,15 +192,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 rect Resulting rectangle - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Rectd* rect, TypeTag) { instance.CheckType(index, LuaType_Table); @@ -320,15 +204,6 @@ 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 rect Resulting rectangle - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Rectf* rect, TypeTag) { Rectd rectDouble; @@ -338,14 +213,14 @@ 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 rect Resulting rectangle - */ + inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Recti* rect, TypeTag) + { + Rectd rectDouble; + unsigned int ret = LuaImplQueryArg(instance, index, &rectDouble, TypeTag()); + + rect->Set(rectDouble); + return ret; + } inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Rectui* rect, TypeTag) { @@ -356,15 +231,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 vec Resulting vector2D - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector2d* vec, TypeTag) { switch (instance.GetType(index)) @@ -386,15 +252,6 @@ namespace Nz } } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param vec Resulting vector2D - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector2f* vec, TypeTag) { Vector2d vecDouble; @@ -404,15 +261,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 vec Resulting vector2D - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector2ui* vec, TypeTag) { Vector2d vecDouble; @@ -422,15 +270,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 vec Resulting vector3D - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector3d* vec, TypeTag) { switch (instance.GetType(index)) @@ -452,15 +291,6 @@ namespace Nz } } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param vec Resulting vector3D - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector3f* vec, TypeTag) { Vector3d vecDouble; @@ -470,15 +300,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 vec Resulting vector3D - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector3ui* vec, TypeTag) { Vector3d vecDouble; @@ -488,15 +309,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 handle Resulting entity - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Ndk::EntityHandle* handle, TypeTag) { *handle = *static_cast(instance.CheckUserdata(index, "Entity")); @@ -504,15 +316,6 @@ 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 handle Resulting world - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Ndk::WorldHandle* handle, TypeTag) { *handle = *static_cast(instance.CheckUserdata(index, "World")); @@ -521,16 +324,6 @@ namespace Nz } #ifndef NDK_SERVER - - /*! - * \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 instanced renderable - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, InstancedRenderableRef* renderable, TypeTag) { if (instance.IsOfType(index, "InstancedRenderable") || @@ -545,15 +338,6 @@ 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 material - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MaterialRef* materialRef, TypeTag) { *materialRef = *static_cast(instance.CheckUserdata(index, "Material")); @@ -561,15 +345,6 @@ 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 a material - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MaterialParams* params, TypeTag) { instance.CheckType(index, Nz::LuaType_Table); @@ -585,15 +360,6 @@ 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 a model - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, ModelParameters* params, TypeTag) { instance.CheckType(index, Nz::LuaType_Table); @@ -606,15 +372,6 @@ 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 a music - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MusicParams* params, TypeTag) { instance.CheckType(index, Nz::LuaType_Table); @@ -624,15 +381,6 @@ 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 a sound buffer - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, SoundBufferParams* params, TypeTag) { instance.CheckType(index, Nz::LuaType_Table); @@ -642,15 +390,6 @@ 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")); @@ -658,15 +397,6 @@ 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 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")); @@ -676,14 +406,6 @@ namespace Nz #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(); @@ -695,56 +417,24 @@ 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 euler angles - */ - inline int LuaImplReplyVal(const LuaInstance& instance, EulerAnglesd&& val, TypeTag) { instance.PushInstance("EulerAngles", 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 euler angles - */ - inline int LuaImplReplyVal(const LuaInstance& instance, EulerAnglesf&& val, TypeTag) { instance.PushInstance("EulerAngles", 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 reference to a font - */ - inline int LuaImplReplyVal(const LuaInstance& instance, FontRef&& val, TypeTag) { instance.PushInstance("Font", 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 size information for a font - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Font::SizeInfo&& val, TypeTag) { instance.PushTable(); @@ -756,14 +446,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 ImageParams - */ - inline int LuaImplReplyVal(const LuaInstance& instance, ImageParams&& val, TypeTag) { instance.PushTable(0, 2); @@ -773,111 +455,53 @@ 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 - * - * \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 - * - * \param instance Lua instance to interact with - * \param val Resulting quaternion - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Quaterniond&& val, TypeTag) { instance.PushInstance("Quaternion", 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 quaternion - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Quaternionf&& val, TypeTag) { instance.PushInstance("Quaternion", 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, Rectd&& val, TypeTag) { instance.PushInstance("Rect", 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, Rectf&& val, TypeTag) { instance.PushInstance("Rect", 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, Recti&& val, TypeTag) + { + instance.PushInstance("Rect", val); + return 1; + } inline int LuaImplReplyVal(const LuaInstance& instance, Rectui&& val, TypeTag) { @@ -885,182 +509,78 @@ 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 vector2D - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Vector2d&& val, TypeTag) { instance.PushInstance("Vector2", 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 vector2D - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Vector2f&& val, TypeTag) { instance.PushInstance("Vector2", 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 vector2D - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Vector2ui&& val, TypeTag) { instance.PushInstance("Vector2", 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 vector3D - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Vector3d&& val, TypeTag) { instance.PushInstance("Vector3", 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 vector3D - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Vector3f&& val, TypeTag) { instance.PushInstance("Vector3", 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 vector3D - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Vector3ui&& val, TypeTag) { instance.PushInstance("Vector3", val); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param ptr Resulting entity - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::Entity* ptr, TypeTag) { instance.PushInstance("Entity", ptr); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param ptr Resulting application - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::Application* ptr, TypeTag) { instance.PushInstance("Application", ptr); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param handle Resulting entity - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::EntityHandle&& handle, TypeTag) { instance.PushInstance("Entity", 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 node component - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::NodeComponentHandle&& handle, TypeTag) { instance.PushInstance("NodeComponent", 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 velocity component - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::VelocityComponentHandle&& handle, TypeTag) { instance.PushInstance("VelocityComponent", handle); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param ptr Resulting world - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::World* ptr, TypeTag) { instance.PushInstance("World", ptr); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param ptr Resulting world - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::WorldHandle&& handle, TypeTag) { instance.PushInstance("World", handle); @@ -1068,70 +588,35 @@ 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 - * - * \param instance Lua instance to interact with - * \param handle Resulting console - */ + inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::CameraComponentHandle&& handle, TypeTag) + { + instance.PushInstance("CameraComponent", handle); + return 1; + } inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::ConsoleHandle&& handle, TypeTag) { @@ -1139,14 +624,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 handle Resulting graphics component - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::GraphicsComponentHandle&& handle, TypeTag) { instance.PushInstance("GraphicsComponent", handle); diff --git a/SDK/include/NDK/LuaBinding.hpp b/SDK/include/NDK/LuaBinding.hpp index 0eb083162..559d6ac1f 100644 --- a/SDK/include/NDK/LuaBinding.hpp +++ b/SDK/include/NDK/LuaBinding.hpp @@ -58,6 +58,7 @@ namespace Ndk // Utility Nz::LuaClass abstractImage; Nz::LuaClass font; + Nz::LuaClass keyboard; Nz::LuaClass node; // SDK @@ -75,6 +76,7 @@ namespace Ndk Nz::LuaClass soundEmitter; // Graphics + Nz::LuaClass abstractViewer; Nz::LuaClass instancedRenderable; Nz::LuaClass material; Nz::LuaClass model; @@ -87,6 +89,7 @@ namespace Ndk Nz::LuaClass texture; // SDK + Nz::LuaClass cameraComponent; Nz::LuaClass console; Nz::LuaClass graphicsComponent; #endif diff --git a/SDK/include/NDK/Prerequesites.hpp b/SDK/include/NDK/Prerequesites.hpp index a2305c70f..f1ff2757a 100644 --- a/SDK/include/NDK/Prerequesites.hpp +++ b/SDK/include/NDK/Prerequesites.hpp @@ -25,11 +25,16 @@ #ifndef NDK_PREREQUESITES_HPP #define NDK_PREREQUESITES_HPP +/*! +* \defgroup NDK (NazaraSDK) Nazara Development Kit +* A library grouping every modules of Nazara into multiple higher-level features suchs as scene management (handled by an ECS), application, lua binding, etc. +*/ + #include // Importation/Exportation of the API #if defined(NAZARA_STATIC) - #define #define NDK_API + #define NDK_API #else #ifdef NDK_BUILD #define NDK_API NAZARA_EXPORT diff --git a/SDK/include/NDK/Systems.hpp b/SDK/include/NDK/Systems.hpp index 45a79bc6c..a0ee23e77 100644 --- a/SDK/include/NDK/Systems.hpp +++ b/SDK/include/NDK/Systems.hpp @@ -7,6 +7,7 @@ #include #include +#include #include #include #include diff --git a/SDK/include/NDK/Systems/PhysicsSystem2D.hpp b/SDK/include/NDK/Systems/PhysicsSystem2D.hpp new file mode 100644 index 000000000..31426450a --- /dev/null +++ b/SDK/include/NDK/Systems/PhysicsSystem2D.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_PHYSICSSYSTEM2D_HPP +#define NDK_SYSTEMS_PHYSICSSYSTEM2D_HPP + +#include +#include +#include +#include + +namespace Ndk +{ + class NDK_API PhysicsSystem2D : public System + { + public: + PhysicsSystem2D(); + PhysicsSystem2D(const PhysicsSystem2D& system); + ~PhysicsSystem2D() = default; + + Nz::PhysWorld2D& GetWorld(); + const Nz::PhysWorld2D& 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_PHYSICSSYSTEM2D_HPP diff --git a/SDK/include/NDK/Systems/PhysicsSystem2D.inl b/SDK/include/NDK/Systems/PhysicsSystem2D.inl new file mode 100644 index 000000000..21a34a6d4 --- /dev/null +++ b/SDK/include/NDK/Systems/PhysicsSystem2D.inl @@ -0,0 +1,32 @@ +// 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 + +namespace Ndk +{ + /*! + * \brief Gets the physical world + * \return A reference to the physical world + */ + + inline Nz::PhysWorld2D& PhysicsSystem2D::GetWorld() + { + if (!m_world) + CreatePhysWorld(); + + return *m_world; + } + + /*! + * \brief Gets the physical world + * \return A constant reference to the physical world + */ + + inline const Nz::PhysWorld2D& PhysicsSystem2D::GetWorld() const + { + if (!m_world) + CreatePhysWorld(); + + return *m_world; + } +} diff --git a/SDK/include/NDK/World.hpp b/SDK/include/NDK/World.hpp index 5d1dabb77..5e819e517 100644 --- a/SDK/include/NDK/World.hpp +++ b/SDK/include/NDK/World.hpp @@ -24,6 +24,7 @@ namespace Ndk class NDK_API World : public Nz::HandledObject { + friend BaseSystem; friend Entity; public: @@ -72,6 +73,8 @@ namespace Ndk private: inline void Invalidate(); inline void Invalidate(EntityId id); + inline void InvalidateSystemOrder(); + void ReorderSystems(); struct EntityBlock { @@ -83,15 +86,17 @@ namespace Ndk EntityBlock(EntityBlock&& block) = default; Entity entity; - unsigned int aliveIndex; + std::size_t aliveIndex; }; std::vector> m_systems; + std::vector m_orderedSystems; std::vector m_entities; std::vector m_freeIdList; EntityList m_aliveEntities; Nz::Bitset m_dirtyEntities; Nz::Bitset m_killedEntities; + bool m_orderedSystemsUpdated; }; } diff --git a/SDK/include/NDK/World.inl b/SDK/include/NDK/World.inl index 9960aef05..212038625 100644 --- a/SDK/include/NDK/World.inl +++ b/SDK/include/NDK/World.inl @@ -53,6 +53,7 @@ namespace Ndk m_systems[index]->SetWorld(this); Invalidate(); // We force an update for every entities + InvalidateSystemOrder(); // And regenerate the system update list return *m_systems[index].get(); } @@ -206,6 +207,8 @@ namespace Ndk inline void World::RemoveAllSystems() { m_systems.clear(); + + InvalidateSystemOrder(); } /*! @@ -219,7 +222,11 @@ namespace Ndk inline void World::RemoveSystem(SystemIndex index) { if (HasSystem(index)) + { m_systems[index].reset(); + + InvalidateSystemOrder(); + } } /*! @@ -246,32 +253,8 @@ namespace Ndk Update(); //< Update entities // And then update systems - for (auto& systemPtr : m_systems) - { - if (systemPtr) - systemPtr->Update(elapsedTime); - } - } - - /*! - * \brief Invalidates each entity in the world - */ - - inline void World::Invalidate() - { - m_dirtyEntities.Resize(m_entities.size(), false); - m_dirtyEntities.Set(true); // Activation of all bits - } - - /*! - * \brief Invalidates an entity in the world - * - * \param id Identifier of the entity - */ - - inline void World::Invalidate(EntityId id) - { - m_dirtyEntities.UnboundedSet(id, true); + for (auto& systemPtr : m_orderedSystems) + systemPtr->Update(elapsedTime); } /*! @@ -281,10 +264,12 @@ namespace Ndk inline World& World::operator=(World&& world) noexcept { - m_aliveEntities = std::move(world.m_aliveEntities); - m_dirtyEntities = std::move(world.m_dirtyEntities); - m_freeIdList = std::move(world.m_freeIdList); - m_killedEntities = std::move(world.m_killedEntities); + m_aliveEntities = std::move(world.m_aliveEntities); + m_dirtyEntities = std::move(world.m_dirtyEntities); + m_freeIdList = std::move(world.m_freeIdList); + m_killedEntities = std::move(world.m_killedEntities); + m_orderedSystems = std::move(world.m_orderedSystems); + m_orderedSystemsUpdated = world.m_orderedSystemsUpdated; m_entities = std::move(world.m_entities); for (EntityBlock& block : m_entities) @@ -296,4 +281,20 @@ namespace Ndk return *this; } + + inline void World::Invalidate() + { + m_dirtyEntities.Resize(m_entities.size(), false); + m_dirtyEntities.Set(true); // Activation of all bits + } + + inline void World::Invalidate(EntityId id) + { + m_dirtyEntities.UnboundedSet(id, true); + } + + inline void World::InvalidateSystemOrder() + { + m_orderedSystemsUpdated = false; + } } diff --git a/SDK/src/NDK/BaseSystem.cpp b/SDK/src/NDK/BaseSystem.cpp index 8a2a9dce5..b6ebe9892 100644 --- a/SDK/src/NDK/BaseSystem.cpp +++ b/SDK/src/NDK/BaseSystem.cpp @@ -3,6 +3,7 @@ // For conditions of distribution and use, see copyright notice in Prerequesites.hpp #include +#include namespace Ndk { @@ -56,6 +57,26 @@ namespace Ndk return true; } + /*! + * \brief Sets the update order of this system + * + * The system update order is used by the world it belongs to in order to know in which order they should be updated, as some application logic may rely a specific update order. + * A system with a greater update order (ex: 1) is guaranteed to be updated after a system with a lesser update order (ex: -1), otherwise the order is unspecified (and is not guaranteed to be stable). + * + * \param updateOrder The relative update order of the system + * + * \remark The update order is only used by World::Update(float) and does not have any effect regarding a call to BaseSystem::Update(float) + * + * \see GetUpdateOrder + */ + void BaseSystem::SetUpdateOrder(int updateOrder) + { + m_updateOrder = updateOrder; + + if (m_world) + m_world->InvalidateSystemOrder(); + } + /*! * \brief Operation to perform when entity is added to the system * diff --git a/SDK/src/NDK/Components/CollisionComponent2D.cpp b/SDK/src/NDK/Components/CollisionComponent2D.cpp new file mode 100644 index 000000000..912742b0e --- /dev/null +++ b/SDK/src/NDK/Components/CollisionComponent2D.cpp @@ -0,0 +1,118 @@ +// 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 + +#include +#include +#include +#include +#include +#include +#include + +namespace Ndk +{ + /*! + * \ingroup NDK + * \class Ndk::CollisionComponent2D + * \brief NDK class that represents a two-dimensional collision geometry + */ + + /*! + * \brief Sets geometry for the entity + * + * \param geom Geometry used for collisions + * + * \remark Produces a NazaraAssert if the entity has no physics component and has no static body + */ + + void CollisionComponent2D::SetGeom(Nz::Collider2DRef geom) + { + m_geom = std::move(geom); + + if (m_entity->HasComponent()) + { + // We update the geometry of the PhysiscsObject linked to the PhysicsComponent2D + PhysicsComponent2D& physComponent = m_entity->GetComponent(); + physComponent.GetRigidBody().SetGeom(m_geom); + } + else + { + NazaraAssert(m_staticBody, "An entity without physics component should have a static body"); + m_staticBody->SetGeom(m_geom); + } + } + + /*! + * \brief Initializes the static body + * + * \remark Produces a NazaraAssert if entity is invalid + * \remark Produces a NazaraAssert if entity is not linked to a world, or the world has no physics system + */ + + void CollisionComponent2D::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::PhysWorld2D& physWorld = entityWorld->GetSystem().GetWorld(); + + m_staticBody.reset(new Nz::RigidBody2D(&physWorld, 0.f, m_geom)); + + Nz::Matrix4f matrix; + if (m_entity->HasComponent()) + matrix = m_entity->GetComponent().GetTransformMatrix(); + else + matrix.MakeIdentity(); + + m_staticBody->SetPosition(Nz::Vector2f(matrix.GetTranslation())); + + } + + /*! + * \brief Operation to perform when component is attached to an entity + */ + + void CollisionComponent2D::OnAttached() + { + if (!m_entity->HasComponent()) + InitializeStaticBody(); + } + + /*! + * \brief Operation to perform when component is attached to this component + * + * \param component Component being attached + */ + + void CollisionComponent2D::OnComponentAttached(BaseComponent& component) + { + if (IsComponent(component)) + m_staticBody.reset(); + } + + /*! + * \brief Operation to perform when component is detached from this component + * + * \param component Component being detached + */ + + void CollisionComponent2D::OnComponentDetached(BaseComponent& component) + { + if (IsComponent(component)) + InitializeStaticBody(); + } + + /*! + * \brief Operation to perform when component is detached from an entity + */ + + void CollisionComponent2D::OnDetached() + { + m_staticBody.reset(); + } + + ComponentIndex CollisionComponent2D::componentIndex; +} diff --git a/SDK/src/NDK/Components/CollisionComponent3D.cpp b/SDK/src/NDK/Components/CollisionComponent3D.cpp index 423b06cb4..d54c460be 100644 --- a/SDK/src/NDK/Components/CollisionComponent3D.cpp +++ b/SDK/src/NDK/Components/CollisionComponent3D.cpp @@ -33,7 +33,7 @@ namespace Ndk { // We update the geometry of the PhysiscsObject linked to the PhysicsComponent3D PhysicsComponent3D& physComponent = m_entity->GetComponent(); - physComponent.GetPhysObject().SetGeom(m_geom); + physComponent.GetRigidBody().SetGeom(m_geom); } else { diff --git a/SDK/src/NDK/Components/PhysicsComponent2D.cpp b/SDK/src/NDK/Components/PhysicsComponent2D.cpp new file mode 100644 index 000000000..db66178b9 --- /dev/null +++ b/SDK/src/NDK/Components/PhysicsComponent2D.cpp @@ -0,0 +1,92 @@ +// 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 + +#include +#include +#include +#include +#include +#include +#include + +namespace Ndk +{ + /*! + * \ingroup NDK + * \class Ndk::PhysicsComponent2D + * \brief NDK class that represents a physics point, without any collision + */ + + /*! + * \brief Operation to perform when component is attached to an entity + * + * \remark Produces a NazaraAssert if the world does not have a physics system + */ + + void PhysicsComponent2D::OnAttached() + { + World* entityWorld = m_entity->GetWorld(); + NazaraAssert(entityWorld->HasSystem(), "World must have a 2D physics system"); + + Nz::PhysWorld2D& world = entityWorld->GetSystem().GetWorld(); + + Nz::Collider2DRef geom; + if (m_entity->HasComponent()) + geom = m_entity->GetComponent().GetGeom(); + + Nz::Matrix4f matrix; + if (m_entity->HasComponent()) + matrix = m_entity->GetComponent().GetTransformMatrix(); + else + matrix.MakeIdentity(); + + m_object.reset(new Nz::RigidBody2D(&world, 1.f, geom)); + m_object->SetPosition(Nz::Vector2f(matrix.GetTranslation())); + } + + /*! + * \brief Operation to perform when component is attached to this component + * + * \param component Component being attached + * + * \remark Produces a NazaraAssert if physical object is invalid + */ + + void PhysicsComponent2D::OnComponentAttached(BaseComponent& component) + { + if (IsComponent(component)) + { + NazaraAssert(m_object, "Invalid object"); + m_object->SetGeom(static_cast(component).GetGeom()); + } + } + + /*! + * \brief Operation to perform when component is detached from this component + * + * \param component Component being detached + * + * \remark Produces a NazaraAssert if physical object is invalid + */ + + void PhysicsComponent2D::OnComponentDetached(BaseComponent& component) + { + if (IsComponent(component)) + { + NazaraAssert(m_object, "Invalid object"); + m_object->SetGeom(Nz::NullCollider2D::New()); + } + } + + /*! + * \brief Operation to perform when component is detached from an entity + */ + + void PhysicsComponent2D::OnDetached() + { + m_object.reset(); + } + + ComponentIndex PhysicsComponent2D::componentIndex; +} diff --git a/SDK/src/NDK/Entity.cpp b/SDK/src/NDK/Entity.cpp index a49a8f6aa..4f60bb427 100644 --- a/SDK/src/NDK/Entity.cpp +++ b/SDK/src/NDK/Entity.cpp @@ -148,9 +148,11 @@ namespace Ndk // We alert each system for (std::size_t index = m_systemBits.FindFirst(); index != m_systemBits.npos; index = m_systemBits.FindNext(index)) { - if (m_world->HasSystem(index)) + auto sysIndex = static_cast(index); + + if (m_world->HasSystem(sysIndex)) { - BaseSystem& system = m_world->GetSystem(index); + BaseSystem& system = m_world->GetSystem(sysIndex); system.RemoveEntity(this); } } diff --git a/SDK/src/NDK/LuaBinding.cpp b/SDK/src/NDK/LuaBinding.cpp index 789427f26..9b990bdfd 100644 --- a/SDK/src/NDK/LuaBinding.cpp +++ b/SDK/src/NDK/LuaBinding.cpp @@ -36,6 +36,7 @@ namespace Ndk // Utility abstractImage("AbstractImage"), font("Font"), + keyboard("Keyboard"), node("Node"), // SDK @@ -55,6 +56,7 @@ namespace Ndk soundEmitter("SoundEmitter"), // Graphics + abstractViewer("AbstractViewer"), instancedRenderable("InstancedRenderable"), material("Material"), model("Model"), @@ -67,6 +69,7 @@ namespace Ndk texture("Texture"), // SDK + cameraComponent("CameraComponent"), console("Console"), graphicsComponent("GraphicsComponent") #endif diff --git a/SDK/src/NDK/LuaBinding_Audio.cpp b/SDK/src/NDK/LuaBinding_Audio.cpp index 46791b6c7..60f504939 100644 --- a/SDK/src/NDK/LuaBinding_Audio.cpp +++ b/SDK/src/NDK/LuaBinding_Audio.cpp @@ -41,12 +41,12 @@ namespace Ndk music.BindMethod("Stop", &Nz::Music::Stop); // Manual - music.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Music& music, std::size_t /*argumentCount*/) -> int + music.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Music& instance, std::size_t /*argumentCount*/) -> int { - Nz::StringStream stream("Music("); - stream << music.GetFilePath() << ')'; + Nz::StringStream ss("Music("); + ss << instance.GetFilePath() << ')'; - lua.PushString(stream); + lua.PushString(ss); return 1; }); @@ -65,15 +65,15 @@ namespace Ndk sound.BindMethod("SetPlayingOffset", &Nz::Sound::SetPlayingOffset); // Manual - sound.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Sound& sound, std::size_t /*argumentCount*/) -> int + sound.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Sound& instance, std::size_t /*argumentCount*/) -> int { - Nz::StringStream stream("Sound("); - if (const Nz::SoundBuffer* buffer = sound.GetBuffer()) - stream << buffer; + Nz::StringStream ss("Sound("); + if (const Nz::SoundBuffer* buffer = instance.GetBuffer()) + ss << buffer; - stream << ')'; + ss << ')'; - lua.PushString(stream); + lua.PushString(ss); return 1; }); @@ -124,18 +124,18 @@ namespace Ndk soundBuffer.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int { - Nz::StringStream stream("SoundBuffer("); + Nz::StringStream ss("SoundBuffer("); if (instance->IsValid()) { Nz::String filePath = instance->GetFilePath(); if (!filePath.IsEmpty()) - stream << "File: " << filePath << ", "; + ss << "File: " << filePath << ", "; - stream << "Duration: " << instance->GetDuration() / 1000.f << "s"; + ss << "Duration: " << instance->GetDuration() / 1000.f << "s"; } - stream << ')'; + ss << ')'; - lua.PushString(stream); + lua.PushString(ss); return 1; }); diff --git a/SDK/src/NDK/LuaBinding_Core.cpp b/SDK/src/NDK/LuaBinding_Core.cpp index dc149e3d0..3108e1a52 100644 --- a/SDK/src/NDK/LuaBinding_Core.cpp +++ b/SDK/src/NDK/LuaBinding_Core.cpp @@ -13,14 +13,37 @@ namespace Ndk void LuaBinding::BindCore() { /*********************************** Nz::Clock **********************************/ - clock.SetConstructor([](Nz::LuaInstance& lua, Nz::Clock* clock, std::size_t /*argumentCount*/) + clock.SetConstructor([](Nz::LuaInstance& lua, Nz::Clock* instance, std::size_t argumentCount) { - int argIndex = 2; - Nz::Int64 startingValue = lua.Check(&argIndex, 0); - bool paused = lua.Check(&argIndex, false); + std::size_t argCount = std::min(argumentCount, 2U); - Nz::PlacementNew(clock, startingValue, paused); - return true; + int argIndex = 2; + switch (argCount) + { + case 0: + Nz::PlacementNew(instance); + return true; + + case 1: + { + Nz::Int64 startingValue = lua.Check(&argIndex, 0); + + Nz::PlacementNew(instance, startingValue); + return true; + } + + case 2: + { + Nz::Int64 startingValue = lua.Check(&argIndex, 0); + bool paused = lua.Check(&argIndex, false); + + Nz::PlacementNew(instance, startingValue, paused); + return true; + } + } + + lua.Error("No matching overload for Clock constructor"); + return false; }); clock.BindMethod("GetMicroseconds", &Nz::Clock::GetMicroseconds); @@ -32,19 +55,19 @@ namespace Ndk clock.BindMethod("Unpause", &Nz::Clock::Unpause); // Manual - 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: "; - stream << clock.IsPaused(); - stream << ')'; + clock.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Clock& instance, std::size_t /*argumentCount*/) -> int { + Nz::StringStream ss("Clock(Elapsed: "); + ss << instance.GetSeconds(); + ss << "s, Paused: "; + ss << instance.IsPaused(); + ss << ')'; - lua.PushString(stream); + lua.PushString(ss); return 1; }); /********************************* Nz::Directory ********************************/ - directory.SetConstructor([](Nz::LuaInstance& lua, Nz::Directory* directory, std::size_t argumentCount) + directory.SetConstructor([](Nz::LuaInstance& lua, Nz::Directory* instance, std::size_t argumentCount) { std::size_t argCount = std::min(argumentCount, 1U); @@ -52,11 +75,11 @@ namespace Ndk switch (argCount) { case 0: - Nz::PlacementNew(directory); + Nz::PlacementNew(instance); return true; case 1: - Nz::PlacementNew(directory, lua.Check(&argIndex)); + Nz::PlacementNew(instance, lua.Check(&argIndex)); return true; } @@ -85,12 +108,12 @@ namespace Ndk directory.BindStaticMethod("SetCurrent", Nz::Directory::SetCurrent); // Manual - directory.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Directory& directory, std::size_t /*argumentCount*/) -> int { - Nz::StringStream stream("Directory("); - stream << directory.GetPath(); - stream << ')'; + directory.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Directory& instance, std::size_t /*argumentCount*/) -> int { + Nz::StringStream ss("Directory("); + ss << instance.GetPath(); + ss << ')'; - lua.PushString(stream); + lua.PushString(ss); return 1; }); @@ -110,35 +133,35 @@ namespace Ndk stream.BindMethod("IsWritable", &Nz::Stream::IsWritable); stream.BindMethod("SetCursorPos", &Nz::Stream::SetCursorPos); - stream.BindMethod("Read", [] (Nz::LuaInstance& lua, Nz::Stream& stream, std::size_t /*argumentCount*/) -> int { + stream.BindMethod("Read", [] (Nz::LuaInstance& lua, Nz::Stream& instance, std::size_t /*argumentCount*/) -> int { int argIndex = 2; std::size_t length = lua.Check(&argIndex); std::unique_ptr buffer(new char[length]); - std::size_t readLength = stream.Read(buffer.get(), length); + std::size_t readLength = instance.Read(buffer.get(), length); lua.PushString(Nz::String(buffer.get(), readLength)); return 1; }); - stream.BindMethod("Write", [] (Nz::LuaInstance& lua, Nz::Stream& stream, std::size_t /*argumentCount*/) -> int { + stream.BindMethod("Write", [] (Nz::LuaInstance& lua, Nz::Stream& instance, std::size_t /*argumentCount*/) -> int { int argIndex = 2; std::size_t bufferSize = 0; const char* buffer = lua.CheckString(argIndex, &bufferSize); - if (stream.IsTextModeEnabled()) - lua.Push(stream.Write(Nz::String(buffer, bufferSize))); + if (instance.IsTextModeEnabled()) + lua.Push(instance.Write(Nz::String(buffer, bufferSize))); else - lua.Push(stream.Write(buffer, bufferSize)); + lua.Push(instance.Write(buffer, bufferSize)); return 1; }); /*********************************** Nz::File ***********************************/ file.Inherit(stream); - file.SetConstructor([] (Nz::LuaInstance& lua, Nz::File* file, std::size_t argumentCount) + file.SetConstructor([] (Nz::LuaInstance& lua, Nz::File* instance, std::size_t argumentCount) { std::size_t argCount = std::min(argumentCount, 1U); @@ -146,14 +169,14 @@ namespace Ndk switch (argCount) { case 0: - Nz::PlacementNew(file); + Nz::PlacementNew(instance); return true; case 1: { Nz::String filePath = lua.Check(&argIndex); - Nz::PlacementNew(file, filePath); + Nz::PlacementNew(instance, filePath); return true; } @@ -162,7 +185,7 @@ namespace Ndk Nz::String filePath = lua.Check(&argIndex); Nz::UInt32 openMode = lua.Check(&argIndex); - Nz::PlacementNew(file, filePath, openMode); + Nz::PlacementNew(instance, filePath, openMode); return true; } } @@ -201,7 +224,7 @@ namespace Ndk file.BindStaticMethod("Rename", &Nz::File::Rename); // Manual - file.BindMethod("Open", [] (Nz::LuaInstance& lua, Nz::File& file, std::size_t argumentCount) -> int + file.BindMethod("Open", [] (Nz::LuaInstance& lua, Nz::File& instance, std::size_t argumentCount) -> int { std::size_t argCount = std::min(argumentCount, 2U); @@ -210,13 +233,13 @@ namespace Ndk { case 0: case 1: - return lua.Push(file.Open(lua.Check(&argIndex, Nz::OpenMode_NotOpen))); + return lua.Push(instance.Open(lua.Check(&argIndex, Nz::OpenMode_NotOpen))); case 2: { Nz::String filePath = lua.Check(&argIndex); Nz::UInt32 openMode = lua.Check(&argIndex, Nz::OpenMode_NotOpen); - return lua.Push(file.Open(filePath, openMode)); + return lua.Push(instance.Open(filePath, openMode)); } } @@ -224,7 +247,7 @@ namespace Ndk return 0; }); - file.BindMethod("SetCursorPos", [] (Nz::LuaInstance& lua, Nz::File& file, std::size_t argumentCount) -> int + file.BindMethod("SetCursorPos", [] (Nz::LuaInstance& lua, Nz::File& instance, std::size_t argumentCount) -> int { std::size_t argCount = std::min(argumentCount, 2U); @@ -232,13 +255,13 @@ namespace Ndk switch (argCount) { case 1: - return lua.Push(file.SetCursorPos(lua.Check(&argIndex))); + return lua.Push(instance.SetCursorPos(lua.Check(&argIndex))); case 2: { Nz::CursorPosition curPos = lua.Check(&argIndex); Nz::Int64 offset = lua.Check(&argIndex); - return lua.Push(file.SetCursorPos(curPos, offset)); + return lua.Push(instance.SetCursorPos(curPos, offset)); } } @@ -246,14 +269,14 @@ namespace Ndk return 0; }); - 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(); + file.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::File& instance, std::size_t /*argumentCount*/) -> int { + Nz::StringStream ss("File("); + if (instance.IsOpen()) + ss << "Path: " << instance.GetPath(); - stream << ')'; + ss << ')'; - lua.PushString(stream); + lua.PushString(ss); return 1; }); } diff --git a/SDK/src/NDK/LuaBinding_Graphics.cpp b/SDK/src/NDK/LuaBinding_Graphics.cpp index 4a2b53422..cdee66636 100644 --- a/SDK/src/NDK/LuaBinding_Graphics.cpp +++ b/SDK/src/NDK/LuaBinding_Graphics.cpp @@ -12,6 +12,18 @@ namespace Ndk void LuaBinding::BindGraphics() { + /*********************************** Nz::AbstractViewer ***********************************/ + abstractViewer.BindMethod("GetAspectRatio", &Nz::AbstractViewer::GetAspectRatio); + abstractViewer.BindMethod("GetEyePosition", &Nz::AbstractViewer::GetEyePosition); + abstractViewer.BindMethod("GetForward", &Nz::AbstractViewer::GetForward); + //abstractViewer.BindMethod("GetFrustum", &Nz::AbstractViewer::GetFrustum); + abstractViewer.BindMethod("GetProjectionMatrix", &Nz::AbstractViewer::GetProjectionMatrix); + //abstractViewer.BindMethod("GetTarget", &Nz::AbstractViewer::GetTarget); + abstractViewer.BindMethod("GetViewMatrix", &Nz::AbstractViewer::GetViewMatrix); + abstractViewer.BindMethod("GetViewport", &Nz::AbstractViewer::GetViewport); + abstractViewer.BindMethod("GetZFar", &Nz::AbstractViewer::GetZFar); + abstractViewer.BindMethod("GetZNear", &Nz::AbstractViewer::GetZNear); + /*********************************** Nz::InstancedRenderable ***********************************/ /*********************************** Nz::Material ***********************************/ @@ -122,7 +134,7 @@ namespace Ndk material.BindMethod("IsShadowCastingEnabled", &Nz::Material::IsShadowCastingEnabled); material.BindMethod("IsShadowReceiveEnabled", &Nz::Material::IsShadowReceiveEnabled); - material.BindMethod("LoadFromFile", &Nz::Material::LoadFromFile); + material.BindMethod("LoadFromFile", &Nz::Material::LoadFromFile, Nz::MaterialParams()); material.BindMethod("Reset", &Nz::Material::Reset); @@ -231,14 +243,14 @@ namespace Ndk }); /*********************************** Nz::Model ***********************************/ - model.Inherit(instancedRenderable, [] (Nz::ModelRef* model) -> Nz::InstancedRenderableRef* + model.Inherit(instancedRenderable, [] (Nz::ModelRef* modelRef) -> Nz::InstancedRenderableRef* { - return reinterpret_cast(model); //TODO: Make a ObjectRefCast + return reinterpret_cast(modelRef); //TODO: Make a ObjectRefCast }); - model.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::ModelRef* model, std::size_t /*argumentCount*/) + model.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::ModelRef* instance, std::size_t /*argumentCount*/) { - Nz::PlacementNew(model, Nz::Model::New()); + Nz::PlacementNew(instance, Nz::Model::New()); return true; }); @@ -260,14 +272,14 @@ namespace Ndk model.BindMethod("SetSkinCount", &Nz::Model::SetSkinCount); /*********************************** Nz::Sprite ***********************************/ - sprite.Inherit(instancedRenderable, [] (Nz::SpriteRef* sprite) -> Nz::InstancedRenderableRef* + sprite.Inherit(instancedRenderable, [] (Nz::SpriteRef* spriteRef) -> Nz::InstancedRenderableRef* { - return reinterpret_cast(sprite); //TODO: Make a ObjectRefCast + return reinterpret_cast(spriteRef); //TODO: Make a ObjectRefCast }); - sprite.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::SpriteRef* sprite, std::size_t /*argumentCount*/) + sprite.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::SpriteRef* instance, std::size_t /*argumentCount*/) { - Nz::PlacementNew(sprite, Nz::Sprite::New()); + Nz::PlacementNew(instance, Nz::Sprite::New()); return true; }); @@ -281,13 +293,37 @@ namespace Ndk 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); + sprite.BindMethod("SetMaterial", [] (Nz::LuaInstance& lua, Nz::SpriteRef& instance, std::size_t /*argumentCount*/) -> int + { + int argIndex = 2; + bool resizeSprite = lua.CheckBoolean(argIndex + 1, true); + + if (lua.IsOfType(argIndex, "Material")) + instance->SetMaterial(*static_cast(lua.ToUserdata(argIndex)), resizeSprite); + else + instance->SetMaterial(lua.Check(&argIndex), resizeSprite); + + return 0; + }); + + sprite.BindMethod("SetTexture", [] (Nz::LuaInstance& lua, Nz::SpriteRef& instance, std::size_t /*argumentCount*/) -> int + { + int argIndex = 2; + bool resizeSprite = lua.CheckBoolean(argIndex + 1, true); + + if (lua.IsOfType(argIndex, "Texture")) + instance->SetTexture(*static_cast(lua.ToUserdata(argIndex)), resizeSprite); + else + instance->SetTexture(lua.Check(&argIndex), resizeSprite); + + return 0; + }); + /*********************************** Nz::SpriteLibrary ***********************************/ spriteLibrary.BindStaticMethod("Get", &Nz::SpriteLibrary::Get); @@ -323,6 +359,7 @@ namespace Ndk void LuaBinding::RegisterGraphics(Nz::LuaInstance& instance) { + abstractViewer.Register(instance); instancedRenderable.Register(instance); material.Register(instance); model.Register(instance); diff --git a/SDK/src/NDK/LuaBinding_Math.cpp b/SDK/src/NDK/LuaBinding_Math.cpp index 51a510238..f777dce7f 100644 --- a/SDK/src/NDK/LuaBinding_Math.cpp +++ b/SDK/src/NDK/LuaBinding_Math.cpp @@ -14,22 +14,22 @@ namespace Ndk void LuaBinding::BindMath() { /*********************************** Nz::EulerAngles **********************************/ - eulerAngles.SetConstructor([] (Nz::LuaInstance& lua, Nz::EulerAnglesd* angles, std::size_t argumentCount) + eulerAngles.SetConstructor([] (Nz::LuaInstance& lua, Nz::EulerAnglesd* instance, std::size_t argumentCount) { std::size_t argCount = std::min(argumentCount, 1U); switch (argCount) { case 0: - Nz::PlacementNew(angles, Nz::EulerAnglesd::Zero()); + Nz::PlacementNew(instance, Nz::EulerAnglesd::Zero()); return true; case 1: - Nz::PlacementNew(angles, *static_cast(lua.CheckUserdata(1, "EulerAngles"))); + Nz::PlacementNew(instance, *static_cast(lua.CheckUserdata(1, "EulerAngles"))); return true; case 3: - Nz::PlacementNew(angles, lua.CheckNumber(1), lua.CheckNumber(2), lua.CheckNumber(3)); + Nz::PlacementNew(instance, lua.CheckNumber(1), lua.CheckNumber(2), lua.CheckNumber(3)); return true; } @@ -37,6 +37,9 @@ namespace Ndk return false; }); + eulerAngles.BindMethod("Normalize", &Nz::EulerAnglesd::Normalize); + eulerAngles.BindMethod("ToQuaternion", &Nz::EulerAnglesd::ToQuaternion); + eulerAngles.BindMethod("__tostring", &Nz::EulerAnglesd::ToString); eulerAngles.SetGetter([] (Nz::LuaInstance& lua, Nz::EulerAnglesd& instance) @@ -154,7 +157,7 @@ namespace Ndk return false; }); - + /*********************************** Nz::Matrix4 **********************************/ matrix4d.SetConstructor([] (Nz::LuaInstance& lua, Nz::Matrix4d* matrix, std::size_t argumentCount) { @@ -174,7 +177,7 @@ namespace Ndk case 16: { double values[16]; - for (std::size_t i = 0; i < 16; ++i) + for (int i = 0; i < 16; ++i) values[i] = lua.CheckNumber(i); Nz::PlacementNew(matrix, values); @@ -227,7 +230,7 @@ namespace Ndk { Nz::Matrix4d result; instance.GetTransposed(&result); - + return lua.Push(result); }); @@ -360,7 +363,7 @@ namespace Ndk }); /*********************************** Nz::Rect **********************************/ - rect.SetConstructor([] (Nz::LuaInstance& lua, Nz::Rectd* rect, std::size_t argumentCount) + rect.SetConstructor([] (Nz::LuaInstance& lua, Nz::Rectd* instance, std::size_t argumentCount) { std::size_t argCount = std::min(argumentCount, 4U); @@ -368,23 +371,23 @@ namespace Ndk { case 0: case 4: - PlacementNew(rect, lua.CheckNumber(1, 0.0), lua.CheckNumber(2, 0.0), lua.CheckNumber(3, 0.0), lua.CheckNumber(4, 0.0)); + PlacementNew(instance, lua.CheckNumber(1, 0.0), lua.CheckNumber(2, 0.0), lua.CheckNumber(3, 0.0), lua.CheckNumber(4, 0.0)); return true; case 1: { if (lua.IsOfType(1, "Rect")) - PlacementNew(rect, *static_cast(lua.ToUserdata(1))); + PlacementNew(instance, *static_cast(lua.ToUserdata(1))); else if (lua.IsOfType(1, Nz::LuaType_Table)) { - // TODO => Faire sans avoir à mettre de nom dans la table et prendre les éléments un à un pour créer le Rectd - PlacementNew(rect, lua.CheckField("x", 1), - lua.CheckField("y", 1), - lua.CheckField("width", 1), - lua.CheckField("height", 1)); + // TODO => Faire sans avoir à mettre de nom dans la table et prendre les éléments un à un pour créer le Rectd + PlacementNew(instance, lua.CheckField("x", 1), + lua.CheckField("y", 1), + lua.CheckField("width", 1), + lua.CheckField("height", 1)); } else if (lua.IsOfType(1, "Vector2")) - PlacementNew(rect, *static_cast(lua.ToUserdata(1))); + PlacementNew(instance, *static_cast(lua.ToUserdata(1))); else break; @@ -394,9 +397,9 @@ namespace Ndk case 2: { if (lua.IsOfType(1, Nz::LuaType_Number) && lua.IsOfType(2, Nz::LuaType_Number)) - PlacementNew(rect, lua.CheckNumber(1), lua.CheckNumber(2)); + PlacementNew(instance, lua.CheckNumber(1), lua.CheckNumber(2)); else if (lua.IsOfType(1, "Vector2") && lua.IsOfType(2, "Vector2")) - PlacementNew(rect, *static_cast(lua.ToUserdata(1)), *static_cast(lua.ToUserdata(2))); + PlacementNew(instance, *static_cast(lua.ToUserdata(1)), *static_cast(lua.ToUserdata(2))); else break; @@ -516,22 +519,22 @@ namespace Ndk }); /*********************************** Nz::Quaternion **********************************/ - quaternion.SetConstructor([] (Nz::LuaInstance& lua, Nz::Quaterniond* quaternion, std::size_t argumentCount) + quaternion.SetConstructor([] (Nz::LuaInstance& lua, Nz::Quaterniond* instance, std::size_t argumentCount) { std::size_t argCount = std::min(argumentCount, 4U); switch (argCount) { case 0: - Nz::PlacementNew(quaternion, Nz::Quaterniond::Zero()); + Nz::PlacementNew(instance, Nz::Quaterniond::Zero()); return true; case 1: { if (lua.IsOfType(1, "EulerAngles")) - Nz::PlacementNew(quaternion, *static_cast(lua.ToUserdata(1))); + Nz::PlacementNew(instance, *static_cast(lua.ToUserdata(1))); else if (lua.IsOfType(1, "Quaternion")) - Nz::PlacementNew(quaternion, *static_cast(lua.ToUserdata(1))); + Nz::PlacementNew(instance, *static_cast(lua.ToUserdata(1))); else break; @@ -539,11 +542,11 @@ namespace Ndk } case 2: - Nz::PlacementNew(quaternion, lua.CheckNumber(1), *static_cast(lua.CheckUserdata(2, "Vector3"))); + Nz::PlacementNew(instance, lua.CheckNumber(1), *static_cast(lua.CheckUserdata(2, "Vector3"))); return true; case 4: - Nz::PlacementNew(quaternion, lua.CheckNumber(1), lua.CheckNumber(2), lua.CheckNumber(3), lua.CheckNumber(4)); + Nz::PlacementNew(instance, lua.CheckNumber(1), lua.CheckNumber(2), lua.CheckNumber(3), lua.CheckNumber(4)); return true; default: @@ -554,8 +557,58 @@ namespace Ndk return false; }); + quaternion.BindMethod("ComputeW", &Nz::Quaterniond::ComputeW); + quaternion.BindMethod("Conjugate", &Nz::Quaterniond::Conjugate); + quaternion.BindMethod("DotProduct", &Nz::Quaterniond::DotProduct); + quaternion.BindMethod("GetConjugate", &Nz::Quaterniond::GetConjugate); + quaternion.BindMethod("GetInverse", &Nz::Quaterniond::GetInverse); + + quaternion.BindMethod("Inverse", &Nz::Quaterniond::Inverse); + quaternion.BindMethod("Magnitude", &Nz::Quaterniond::Magnitude); + + quaternion.BindMethod("SquaredMagnitude", &Nz::Quaterniond::SquaredMagnitude); + quaternion.BindMethod("ToEulerAngles", &Nz::Quaterniond::ToEulerAngles); + quaternion.BindMethod("__tostring", &Nz::Quaterniond::ToString); + quaternion.BindStaticMethod("Lerp", &Nz::Quaterniond::Lerp); + quaternion.BindStaticMethod("RotationBetween", &Nz::Quaterniond::RotationBetween); + quaternion.BindStaticMethod("Slerp", &Nz::Quaterniond::Slerp); + + quaternion.BindMethod("GetNormal", [] (Nz::LuaInstance& lua, Nz::Quaterniond& instance, std::size_t /*argumentCount*/) -> int + { + double length; + + lua.Push(instance.GetNormal(&length)); + lua.Push(length); + + return 2; + }); + + quaternion.BindMethod("Normalize", [] (Nz::LuaInstance& lua, Nz::Quaterniond& instance, std::size_t /*argumentCount*/) -> int + { + double length; + + instance.Normalize(&length); + lua.Push(1); //< instance + lua.Push(length); + + return 2; + }); + + quaternion.BindStaticMethod("Normalize", [] (Nz::LuaInstance& instance) -> int + { + int argIndex = 1; + Nz::Quaterniond quat = instance.Check(&argIndex); + + double length; + + instance.Push(Nz::Quaterniond::Normalize(quat, &length)); + instance.Push(length); + + return 2; + }); + quaternion.SetGetter([] (Nz::LuaInstance& lua, Nz::Quaterniond& instance) { std::size_t length; @@ -904,5 +957,12 @@ namespace Ndk rect.Register(instance); vector2d.Register(instance); vector3d.Register(instance); + + quaternion.PushGlobalTable(instance); + { + instance.PushField("Identity", Nz::Quaterniond::Identity()); + instance.PushField("Zero", Nz::Quaterniond::Zero()); + } + instance.Pop(); } } diff --git a/SDK/src/NDK/LuaBinding_Network.cpp b/SDK/src/NDK/LuaBinding_Network.cpp index bd1105962..b51906481 100644 --- a/SDK/src/NDK/LuaBinding_Network.cpp +++ b/SDK/src/NDK/LuaBinding_Network.cpp @@ -21,7 +21,7 @@ namespace Ndk abstractSocket.BindMethod("QueryAvailableBytes", &Nz::AbstractSocket::QueryAvailableBytes); /*********************************** Nz::IpAddress **********************************/ - ipAddress.SetConstructor([] (Nz::LuaInstance& lua, Nz::IpAddress* address, std::size_t argumentCount) + ipAddress.SetConstructor([] (Nz::LuaInstance& lua, Nz::IpAddress* instance, std::size_t argumentCount) { std::size_t argCount = std::min(argumentCount, 9U); @@ -29,11 +29,11 @@ namespace Ndk switch (argCount) { case 0: - Nz::PlacementNew(address); + Nz::PlacementNew(instance); return true; case 1: - Nz::PlacementNew(address, lua.CheckString(argIndex)); + Nz::PlacementNew(instance, lua.CheckString(argIndex)); return true; case 4: @@ -45,7 +45,7 @@ namespace Ndk Nz::UInt8 d = lua.Check(&argIndex); Nz::UInt16 port = lua.Check(&argIndex, 0); - Nz::PlacementNew(address, a, b, c, d, port); + Nz::PlacementNew(instance, a, b, c, d, port); return true; } @@ -62,7 +62,7 @@ namespace Ndk Nz::UInt16 h = lua.Check(&argIndex); Nz::UInt16 port = lua.Check(&argIndex, 0); - Nz::PlacementNew(address, a, b, c, d, e, f, g, h, port); + Nz::PlacementNew(instance, a, b, c, d, e, f, g, h, port); return true; } } @@ -199,7 +199,7 @@ namespace Ndk instance.PushField("Unknown", Nz::ResolveError_Unknown); } instance.SetGlobal("ResolveError"); - + // Nz::SocketError static_assert(Nz::SocketError_Max + 1 == 15, "Nz::ResolveError has been updated but change was not reflected to Lua binding"); instance.PushTable(0, 15); diff --git a/SDK/src/NDK/LuaBinding_Renderer.cpp b/SDK/src/NDK/LuaBinding_Renderer.cpp index 8ffe76c69..1f1f9479f 100644 --- a/SDK/src/NDK/LuaBinding_Renderer.cpp +++ b/SDK/src/NDK/LuaBinding_Renderer.cpp @@ -13,14 +13,14 @@ namespace Ndk void LuaBinding::BindRenderer() { /*********************************** Nz::Texture ***********************************/ - texture.Inherit(abstractImage, [] (Nz::TextureRef* texture) -> Nz::AbstractImageRef* + texture.Inherit(abstractImage, [] (Nz::TextureRef* textureRef) -> Nz::AbstractImageRef* { - return reinterpret_cast(texture); //TODO: Make a ObjectRefCast + return reinterpret_cast(textureRef); //TODO: Make a ObjectRefCast }); - texture.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::TextureRef* texture, std::size_t /*argumentCount*/) + texture.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::TextureRef* instance, std::size_t /*argumentCount*/) { - Nz::PlacementNew(texture, Nz::Texture::New()); + Nz::PlacementNew(instance, Nz::Texture::New()); return true; }); @@ -28,7 +28,7 @@ namespace Ndk 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); @@ -73,4 +73,4 @@ namespace Ndk { 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 3046f2483..37c2d71e9 100644 --- a/SDK/src/NDK/LuaBinding_SDK.cpp +++ b/SDK/src/NDK/LuaBinding_SDK.cpp @@ -1,4 +1,4 @@ -// Copyright (C) 2016 Jérôme Leclercq, Arnaud Cadot +// Copyright (C) 2016 Jérôme Leclercq, Arnaud Cadot // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp @@ -25,9 +25,9 @@ namespace Ndk application.BindMethod("IsFPSCounterEnabled", &Application::IsFPSCounterEnabled); #endif - application.BindMethod("AddWorld", [] (Nz::LuaInstance& instance, Application* application, std::size_t /*argumentCount*/) -> int + application.BindMethod("AddWorld", [] (Nz::LuaInstance& lua, Application* instance, std::size_t /*argumentCount*/) -> int { - instance.Push(application->AddWorld().CreateHandle()); + lua.Push(instance->AddWorld().CreateHandle()); return 1; }); @@ -59,7 +59,7 @@ namespace Ndk console.BindMethod("SetCharacterSize", &Console::SetCharacterSize); console.BindMethod("SetSize", &Console::SetSize); console.BindMethod("SetTextFont", &Console::SetTextFont); - + console.BindMethod("Show", &Console::Show, true); #endif @@ -138,8 +138,27 @@ namespace Ndk #ifndef NDK_SERVER + /*********************************** Ndk::CameraComponent **********************************/ + cameraComponent.Inherit(abstractViewer, [] (CameraComponentHandle* handle) -> Nz::AbstractViewer* + { + return handle->GetObject(); + }); + + cameraComponent.BindMethod("GetFOV", &Ndk::CameraComponent::GetFOV); + cameraComponent.BindMethod("GetLayer", &Ndk::CameraComponent::GetLayer); + + cameraComponent.BindMethod("SetFOV", &Ndk::CameraComponent::SetFOV); + cameraComponent.BindMethod("SetLayer", &Ndk::CameraComponent::SetLayer); + cameraComponent.BindMethod("SetProjectionType", &Ndk::CameraComponent::SetProjectionType); + cameraComponent.BindMethod("SetSize", (void(Ndk::CameraComponent::*)(const Nz::Vector2f&)) &Ndk::CameraComponent::SetSize); + //cameraComponent.BindMethod("SetTarget", &Ndk::CameraComponent::SetTarget); + cameraComponent.BindMethod("SetTargetRegion", &Ndk::CameraComponent::SetTargetRegion); + cameraComponent.BindMethod("SetViewport", &Ndk::CameraComponent::SetViewport); + cameraComponent.BindMethod("SetZFar", &Ndk::CameraComponent::SetZFar); + cameraComponent.BindMethod("SetZNear", &Ndk::CameraComponent::SetZNear); + /*********************************** Ndk::GraphicsComponent **********************************/ - graphicsComponent.BindMethod("Attach", [] (Nz::LuaInstance& lua, Ndk::GraphicsComponent *gfxComponent, std::size_t argumentCount) -> int + graphicsComponent.BindMethod("Attach", [] (Nz::LuaInstance& lua, Ndk::GraphicsComponent* instance, std::size_t argumentCount) -> int { /* void Attach(Nz::InstancedRenderableRef renderable, int renderOrder = 0); @@ -153,7 +172,7 @@ namespace Ndk case 1: { int argIndex = 2; - gfxComponent->Attach(lua.Check(&argIndex)); + instance->Attach(lua.Check(&argIndex)); return 0; } @@ -166,13 +185,13 @@ namespace Ndk { int renderOrder = lua.Check(&argIndex); - gfxComponent->Attach(renderable, renderOrder); + instance->Attach(renderable, renderOrder); } else if (lua.IsOfType(argIndex, "Matrix4")) { Nz::Matrix4f localMatrix = lua.Check(&argIndex); - gfxComponent->Attach(renderable, localMatrix); + instance->Attach(renderable, localMatrix); } else break; @@ -187,7 +206,7 @@ namespace Ndk Nz::Matrix4f localMatrix = lua.Check(&argIndex); int renderOrder = lua.Check(&argIndex); - gfxComponent->Attach(renderable, localMatrix, renderOrder); + instance->Attach(renderable, localMatrix, renderOrder); return 0; } } @@ -205,6 +224,7 @@ namespace Ndk BindComponent("Velocity"); #ifndef NDK_SERVER + BindComponent("Camera"); BindComponent("Graphics"); #endif } @@ -225,6 +245,7 @@ namespace Ndk world.Register(instance); #ifndef NDK_SERVER + cameraComponent.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 5ae37f669..686182410 100644 --- a/SDK/src/NDK/LuaBinding_Utility.cpp +++ b/SDK/src/NDK/LuaBinding_Utility.cpp @@ -25,20 +25,20 @@ namespace Ndk abstractImage.BindMethod("IsCompressed", &Nz::AbstractImage::IsCompressed); abstractImage.BindMethod("IsCubemap", &Nz::AbstractImage::IsCubemap); - abstractImage.BindMethod("GetMemoryUsage", [] (Nz::LuaInstance& lua, Nz::AbstractImage* abstractImage, std::size_t argumentCount) -> int + abstractImage.BindMethod("GetMemoryUsage", [] (Nz::LuaInstance& lua, Nz::AbstractImage* instance, std::size_t argumentCount) -> int { std::size_t argCount = std::min(argumentCount, 1U); switch (argCount) { case 0: - return lua.Push(abstractImage->GetMemoryUsage()); + return lua.Push(instance->GetMemoryUsage()); case 1: { int argIndex = 2; Nz::UInt8 level(lua.Check(&argIndex)); - return lua.Push(abstractImage->GetMemoryUsage(level)); + return lua.Push(instance->GetMemoryUsage(level)); } } @@ -46,7 +46,7 @@ namespace Ndk return 0; }); - abstractImage.BindMethod("Update", [] (Nz::LuaInstance& lua, Nz::AbstractImage* abstractImage, std::size_t argumentCount) -> int + abstractImage.BindMethod("Update", [] (Nz::LuaInstance& lua, Nz::AbstractImage* instance, std::size_t argumentCount) -> int { std::size_t argCount = std::min(argumentCount, 6U); int argIndex = 2; @@ -62,7 +62,7 @@ namespace Ndk Nz::UInt8 level = lua.Check(&argIndex, 0); ///TODO: Buffer checks (Nz::ByteBufferView ?) - return lua.Push(abstractImage->Update(pixels, srcWidth, srcHeight, level)); + return lua.Push(instance->Update(pixels, srcWidth, srcHeight, level)); } /* Disabled until Box and Rect have been ported else if (lua.IsOfType(2, "Box")) @@ -93,9 +93,9 @@ namespace Ndk }); /*********************************** Nz::Font **********************************/ - font.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::FontRef* font, std::size_t /*argumentCount*/) + font.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::FontRef* instance, std::size_t /*argumentCount*/) { - Nz::PlacementNew(font, Nz::Font::New()); + Nz::PlacementNew(instance, Nz::Font::New()); return true; }); @@ -153,6 +153,10 @@ namespace Ndk font.BindStaticMethod("SetDefaultGlyphBorder", &Nz::Font::SetDefaultGlyphBorder); font.BindStaticMethod("SetDefaultMinimumStepSize", &Nz::Font::SetDefaultMinimumStepSize); + /*********************************** Nz::Keyboard **********************************/ + keyboard.BindStaticMethod("GetKeyName", &Nz::Keyboard::GetKeyName); + keyboard.BindStaticMethod("IsKeyPressed", &Nz::Keyboard::IsKeyPressed); + /*********************************** Nz::Node **********************************/ node.BindMethod("GetBackward", &Nz::Node::GetBackward); //nodeClass.SetMethod("GetChilds", &Nz::Node::GetChilds); @@ -199,29 +203,29 @@ namespace Ndk 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); - node.BindMethod("Move", [] (Nz::LuaInstance& lua, Nz::Node& node, std::size_t /*argumentCount*/) -> int + node.BindMethod("Move", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t /*argumentCount*/) -> int { int argIndex = 2; Nz::Vector3f offset = lua.Check(&argIndex); Nz::CoordSys coordSys = lua.Check(&argIndex, Nz::CoordSys_Local); - node.Move(offset, coordSys); + instance.Move(offset, coordSys); return 0; }); - node.BindMethod("Rotate", [] (Nz::LuaInstance& lua, Nz::Node& node, std::size_t /*argumentCount*/) -> int + node.BindMethod("Rotate", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t /*argumentCount*/) -> int { int argIndex = 2; Nz::Quaternionf rotation = lua.Check(&argIndex); Nz::CoordSys coordSys = lua.Check(&argIndex, Nz::CoordSys_Local); - node.Rotate(rotation, coordSys); + instance.Rotate(rotation, coordSys); return 0; }); - node.BindMethod("Scale", [] (Nz::LuaInstance& lua, Nz::Node& node, std::size_t argumentCount) -> int + node.BindMethod("Scale", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t argumentCount) -> int { std::size_t argCount = std::min(argumentCount, 4U); @@ -231,15 +235,15 @@ namespace Ndk case 1: { if (lua.IsOfType(argIndex, Nz::LuaType_Number)) - node.Scale(lua.Check(&argIndex)); + instance.Scale(lua.Check(&argIndex)); else - node.Scale(lua.Check(&argIndex)); + instance.Scale(lua.Check(&argIndex)); return 0; } case 3: - node.Scale(lua.Check(&argIndex)); + instance.Scale(lua.Check(&argIndex)); return 0; } @@ -247,7 +251,7 @@ namespace Ndk return 0; }); - node.BindMethod("SetScale", [] (Nz::LuaInstance& lua, Nz::Node& node, std::size_t argumentCount) -> int + node.BindMethod("SetScale", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t argumentCount) -> int { std::size_t argCount = std::min(argumentCount, 4U); @@ -261,10 +265,10 @@ namespace Ndk { float scale = lua.Check(&argIndex); Nz::CoordSys coordSys = lua.Check(&argIndex, Nz::CoordSys_Local); - node.SetScale(scale, coordSys); + instance.SetScale(scale, coordSys); } else - node.SetScale(lua.Check(&argIndex)); + instance.SetScale(lua.Check(&argIndex)); return 0; } @@ -275,7 +279,7 @@ namespace Ndk Nz::Vector3f scale = lua.Check(&argIndex); Nz::CoordSys coordSys = lua.Check(&argIndex, Nz::CoordSys_Local); - node.SetScale(scale, coordSys); + instance.SetScale(scale, coordSys); return 0; } } @@ -284,7 +288,7 @@ namespace Ndk return 0; }); - node.BindMethod("SetInitialScale", [] (Nz::LuaInstance& lua, Nz::Node& node, std::size_t argumentCount) -> int + node.BindMethod("SetInitialScale", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t argumentCount) -> int { std::size_t argCount = std::min(argumentCount, 4U); @@ -294,16 +298,16 @@ namespace Ndk case 1: { if (lua.IsOfType(argIndex, Nz::LuaType_Number)) - node.SetInitialScale(lua.Check(&argIndex)); + instance.SetInitialScale(lua.Check(&argIndex)); else - node.SetInitialScale(lua.Check(&argIndex)); + instance.SetInitialScale(lua.Check(&argIndex)); return 0; } case 2: case 3: - node.SetInitialScale(lua.Check(&argIndex)); + instance.SetInitialScale(lua.Check(&argIndex)); return 0; } @@ -322,6 +326,92 @@ namespace Ndk { abstractImage.Register(instance); font.Register(instance); + keyboard.Register(instance); node.Register(instance); + + keyboard.PushGlobalTable(instance); + { + instance.PushField("Undefined", Nz::Keyboard::Undefined); + + // A-Z + for (std::size_t i = 0; i < 26; ++i) + instance.PushField(Nz::String('A' + char(i)), Nz::Keyboard::A + i); + + // Numerical + for (std::size_t i = 0; i < 10; ++i) + { + instance.PushField("Num" + Nz::String::Number(i), Nz::Keyboard::Num0 + i); + instance.PushField("Numpad" + Nz::String::Number(i), Nz::Keyboard::Numpad0 + i); + } + + // F1-F15 + for (std::size_t i = 0; i < 15; ++i) + instance.PushField('F' + Nz::String::Number(i+1), Nz::Keyboard::F1 + i); + + // And all the others... + instance.PushField("Down", Nz::Keyboard::Down); + instance.PushField("Left", Nz::Keyboard::Left); + instance.PushField("Right", Nz::Keyboard::Right); + instance.PushField("Up", Nz::Keyboard::Up); + + instance.PushField("Add", Nz::Keyboard::Add); + instance.PushField("Decimal", Nz::Keyboard::Decimal); + instance.PushField("Divide", Nz::Keyboard::Divide); + instance.PushField("Multiply", Nz::Keyboard::Multiply); + instance.PushField("Subtract", Nz::Keyboard::Subtract); + + instance.PushField("Backslash", Nz::Keyboard::Backslash); + instance.PushField("Backspace", Nz::Keyboard::Backspace); + instance.PushField("Clear", Nz::Keyboard::Clear); + instance.PushField("Comma", Nz::Keyboard::Comma); + instance.PushField("Dash", Nz::Keyboard::Dash); + instance.PushField("Delete", Nz::Keyboard::Delete); + instance.PushField("End", Nz::Keyboard::End); + instance.PushField("Equal", Nz::Keyboard::Equal); + instance.PushField("Escape", Nz::Keyboard::Escape); + instance.PushField("Home", Nz::Keyboard::Home); + instance.PushField("Insert", Nz::Keyboard::Insert); + instance.PushField("LAlt", Nz::Keyboard::LAlt); + instance.PushField("LBracket", Nz::Keyboard::LBracket); + instance.PushField("LControl", Nz::Keyboard::LControl); + instance.PushField("LShift", Nz::Keyboard::LShift); + instance.PushField("LSystem", Nz::Keyboard::LSystem); + instance.PushField("PageDown", Nz::Keyboard::PageDown); + instance.PushField("PageUp", Nz::Keyboard::PageUp); + instance.PushField("Pause", Nz::Keyboard::Pause); + instance.PushField("Period", Nz::Keyboard::Period); + instance.PushField("Print", Nz::Keyboard::Print); + instance.PushField("PrintScreen", Nz::Keyboard::PrintScreen); + instance.PushField("Quote", Nz::Keyboard::Quote); + instance.PushField("RAlt", Nz::Keyboard::RAlt); + instance.PushField("RBracket", Nz::Keyboard::RBracket); + instance.PushField("RControl", Nz::Keyboard::RControl); + instance.PushField("Return", Nz::Keyboard::Return); + instance.PushField("RShift", Nz::Keyboard::RShift); + instance.PushField("RSystem", Nz::Keyboard::RSystem); + instance.PushField("Semicolon", Nz::Keyboard::Semicolon); + instance.PushField("Slash", Nz::Keyboard::Slash); + instance.PushField("Space", Nz::Keyboard::Space); + instance.PushField("Tab", Nz::Keyboard::Tab); + instance.PushField("Tilde", Nz::Keyboard::Tilde); + instance.PushField("Browser_Back", Nz::Keyboard::Browser_Back); + instance.PushField("Browser_Favorites", Nz::Keyboard::Browser_Favorites); + instance.PushField("Browser_Forward", Nz::Keyboard::Browser_Forward); + instance.PushField("Browser_Home", Nz::Keyboard::Browser_Home); + instance.PushField("Browser_Refresh", Nz::Keyboard::Browser_Refresh); + instance.PushField("Browser_Search", Nz::Keyboard::Browser_Search); + instance.PushField("Browser_Stop", Nz::Keyboard::Browser_Stop); + instance.PushField("Media_Next", Nz::Keyboard::Media_Next); + instance.PushField("Media_Play", Nz::Keyboard::Media_Play); + instance.PushField("Media_Previous", Nz::Keyboard::Media_Previous); + instance.PushField("Media_Stop", Nz::Keyboard::Media_Stop); + instance.PushField("Volume_Down", Nz::Keyboard::Volume_Down); + instance.PushField("Volume_Mute", Nz::Keyboard::Volume_Mute); + instance.PushField("Volume_Up", Nz::Keyboard::Volume_Up); + instance.PushField("CapsLock", Nz::Keyboard::CapsLock); + instance.PushField("NumLock", Nz::Keyboard::NumLock); + instance.PushField("ScrollLock", Nz::Keyboard::ScrollLock); + } + instance.Pop(); } -} \ No newline at end of file +} diff --git a/SDK/src/NDK/Sdk.cpp b/SDK/src/NDK/Sdk.cpp index 36283ada3..81080af06 100644 --- a/SDK/src/NDK/Sdk.cpp +++ b/SDK/src/NDK/Sdk.cpp @@ -9,14 +9,18 @@ #include #include #include +#include #include #include #include #include +#include #include #include +#include #include #include +#include #include #include @@ -68,6 +72,7 @@ namespace Ndk Nz::Lua::Initialize(); Nz::Noise::Initialize(); + Nz::Physics2D::Initialize(); Nz::Physics3D::Initialize(); Nz::Utility::Initialize(); @@ -83,9 +88,11 @@ namespace Ndk BaseComponent::Initialize(); // Shared components - InitializeComponent("NdkColli"); + InitializeComponent("NdkColl2"); + InitializeComponent("NdkColl3"); InitializeComponent("NdkNode"); - InitializeComponent("NdkPhys"); + InitializeComponent("NdkPhys2"); + InitializeComponent("NdkPhys3"); InitializeComponent("NdkVeloc"); #ifndef NDK_SERVER @@ -103,6 +110,7 @@ namespace Ndk BaseSystem::Initialize(); // Shared systems + InitializeSystem(); InitializeSystem(); InitializeSystem(); @@ -161,6 +169,7 @@ namespace Ndk // Shared modules Nz::Lua::Uninitialize(); Nz::Noise::Uninitialize(); + Nz::Physics2D::Uninitialize(); Nz::Physics3D::Uninitialize(); Nz::Utility::Uninitialize(); diff --git a/SDK/src/NDK/Systems/ListenerSystem.cpp b/SDK/src/NDK/Systems/ListenerSystem.cpp index 9c7333d34..3de647a08 100644 --- a/SDK/src/NDK/Systems/ListenerSystem.cpp +++ b/SDK/src/NDK/Systems/ListenerSystem.cpp @@ -25,6 +25,7 @@ namespace Ndk ListenerSystem::ListenerSystem() { Requires(); + SetUpdateOrder(100); //< Update last, after every movement is done } /*! @@ -33,11 +34,9 @@ namespace Ndk * \param elapsedTime Delta time used for the update */ - void ListenerSystem::OnUpdate(float elapsedTime) + void ListenerSystem::OnUpdate(float /*elapsedTime*/) { - NazaraUnused(elapsedTime); - - unsigned int activeListenerCount = 0; + std::size_t activeListenerCount = 0; for (const Ndk::EntityHandle& entity : GetEntities()) { diff --git a/SDK/src/NDK/Systems/PhysicsSystem2D.cpp b/SDK/src/NDK/Systems/PhysicsSystem2D.cpp new file mode 100644 index 000000000..adedfc170 --- /dev/null +++ b/SDK/src/NDK/Systems/PhysicsSystem2D.cpp @@ -0,0 +1,140 @@ +// 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 + +#include +#include +#include +#include +#include +#include + +namespace Ndk +{ + /*! + * \ingroup NDK + * \class Ndk::PhysicsSystem2D + * \brief NDK class that represents a two-dimensional physics system + * + * \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 + */ + + /*! + * \brief Constructs an PhysicsSystem object by default + */ + + PhysicsSystem2D::PhysicsSystem2D() + { + Requires(); + RequiresAny(); + Excludes(); + } + + /*! + * \brief Constructs a PhysicsSystem object by copy semantic + * + * \param system PhysicsSystem to copy + */ + + PhysicsSystem2D::PhysicsSystem2D(const PhysicsSystem2D& system) : + System(system), + m_world() + { + } + + void PhysicsSystem2D::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 + * + * \param entity Pointer to the entity + * \param justAdded Is the entity newly added + */ + + void PhysicsSystem2D::OnEntityValidation(Entity* entity, bool justAdded) + { + // It's possible our entity got revalidated because of the addition/removal of a PhysicsComponent3D + if (!justAdded) + { + // 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; + entities.Insert(entity); + + if (!m_world) + CreatePhysWorld(); + } + + /*! + * \brief Operation to perform when system is updated + * + * \param elapsedTime Delta time used for the update + */ + + void PhysicsSystem2D::OnUpdate(float elapsedTime) + { + if (!m_world) + return; + + m_world->Step(elapsedTime); + + for (const Ndk::EntityHandle& entity : m_dynamicObjects) + { + NodeComponent& node = entity->GetComponent(); + PhysicsComponent2D& phys = entity->GetComponent(); + + Nz::RigidBody2D& body = phys.GetRigidBody(); + node.SetRotation(Nz::EulerAnglesf(0.f, 0.f, body.GetRotation()), Nz::CoordSys_Global); + node.SetPosition(Nz::Vector3f(body.GetPosition(), node.GetPosition(Nz::CoordSys_Global).z), Nz::CoordSys_Global); + } + + float invElapsedTime = 1.f / elapsedTime; + for (const Ndk::EntityHandle& entity : m_staticObjects) + { + CollisionComponent2D& collision = entity->GetComponent(); + NodeComponent& node = entity->GetComponent(); + + Nz::RigidBody2D* body = collision.GetStaticBody(); + + Nz::Vector2f oldPosition = body->GetPosition(); + Nz::Vector2f newPosition = Nz::Vector2f(node.GetPosition(Nz::CoordSys_Global)); + + // To move static objects and ensure their collisions, we have to specify them a velocity + // (/!\: the physical motor does not apply the speed on static objects) + if (newPosition != oldPosition) + { + body->SetPosition(newPosition); + body->SetVelocity((newPosition - oldPosition) * invElapsedTime); + } + else + body->SetVelocity(Nz::Vector2f::Zero()); + +/* + if (newRotation != oldRotation) + { + Nz::Quaternionf transition = newRotation * oldRotation.GetConjugate(); + Nz::EulerAnglesf angles = transition.ToEulerAngles(); + Nz::Vector3f angularVelocity(Nz::ToRadians(angles.pitch * invElapsedTime), + Nz::ToRadians(angles.yaw * invElapsedTime), + Nz::ToRadians(angles.roll * invElapsedTime)); + + physObj->SetRotation(oldRotation); + physObj->SetAngularVelocity(angularVelocity); + } + else + physObj->SetAngularVelocity(Nz::Vector3f::Zero()); +*/ + } + } + + SystemIndex PhysicsSystem2D::systemIndex; +} diff --git a/SDK/src/NDK/Systems/PhysicsSystem3D.cpp b/SDK/src/NDK/Systems/PhysicsSystem3D.cpp index fd5e05d66..c26c932e0 100644 --- a/SDK/src/NDK/Systems/PhysicsSystem3D.cpp +++ b/SDK/src/NDK/Systems/PhysicsSystem3D.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include namespace Ndk @@ -27,6 +28,7 @@ namespace Ndk { Requires(); RequiresAny(); + Excludes(); } /*! @@ -90,7 +92,7 @@ namespace Ndk NodeComponent& node = entity->GetComponent(); PhysicsComponent3D& phys = entity->GetComponent(); - Nz::RigidBody3D& physObj = phys.GetPhysObject(); + Nz::RigidBody3D& physObj = phys.GetRigidBody(); node.SetRotation(physObj.GetRotation(), Nz::CoordSys_Global); node.SetPosition(physObj.GetPosition(), Nz::CoordSys_Global); } diff --git a/SDK/src/NDK/Systems/RenderSystem.cpp b/SDK/src/NDK/Systems/RenderSystem.cpp index fbc2d3e08..fb6709227 100644 --- a/SDK/src/NDK/Systems/RenderSystem.cpp +++ b/SDK/src/NDK/Systems/RenderSystem.cpp @@ -35,7 +35,8 @@ namespace Ndk { ChangeRenderTechnique(); SetDefaultBackground(Nz::ColorBackground::New()); - SetUpdateRate(0.f); + SetUpdateOrder(100); //< Render last, after every movement is done + SetUpdateRate(0.f); //< We don't want any rate limit } /*! @@ -116,10 +117,8 @@ namespace Ndk * \param elapsedTime Delta time used for the update */ - void RenderSystem::OnUpdate(float elapsedTime) + void RenderSystem::OnUpdate(float /*elapsedTime*/) { - NazaraUnused(elapsedTime); - // Invalidate every renderable if the coordinate system changed if (m_coordinateSystemInvalidated) { diff --git a/SDK/src/NDK/Systems/VelocitySystem.cpp b/SDK/src/NDK/Systems/VelocitySystem.cpp index c1298bde3..4bc3b3a68 100644 --- a/SDK/src/NDK/Systems/VelocitySystem.cpp +++ b/SDK/src/NDK/Systems/VelocitySystem.cpp @@ -24,8 +24,9 @@ namespace Ndk VelocitySystem::VelocitySystem() { - Requires(); Excludes(); + Requires(); + SetUpdateOrder(10); //< Since some systems may want to stop us } /*! diff --git a/SDK/src/NDK/World.cpp b/SDK/src/NDK/World.cpp index 6ba110aee..78b250aaf 100644 --- a/SDK/src/NDK/World.cpp +++ b/SDK/src/NDK/World.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -40,6 +41,7 @@ namespace Ndk void World::AddDefaultSystems() { + AddSystem(); AddSystem(); AddSystem(); @@ -67,7 +69,7 @@ namespace Ndk else { // We allocate a new entity - id = m_entities.size(); + id = static_cast(m_entities.size()); // We can't use emplace_back due to the scope m_entities.push_back(Entity(this, id)); @@ -172,6 +174,9 @@ namespace Ndk void World::Update() { + if (!m_orderedSystemsUpdated) + ReorderSystems(); + // Handle killed entities before last call for (std::size_t i = m_killedEntities.FindFirst(); i != m_killedEntities.npos; i = m_killedEntities.FindNext(i)) { @@ -218,15 +223,11 @@ namespace Ndk Nz::Bitset<>& removedComponents = entity->GetRemovedComponentBits(); for (std::size_t j = removedComponents.FindFirst(); j != m_dirtyEntities.npos; j = removedComponents.FindNext(j)) - entity->DestroyComponent(j); + entity->DestroyComponent(static_cast(j)); removedComponents.Reset(); - for (auto& system : m_systems) + for (auto& system : m_orderedSystems) { - // Ignore non-existent systems - if (!system) - continue; - // Is our entity already part of this system? bool partOfSystem = system->HasEntity(entity); @@ -249,4 +250,22 @@ namespace Ndk } m_dirtyEntities.Reset(); } + + void World::ReorderSystems() + { + m_orderedSystems.clear(); + + for (auto& systemPtr : m_systems) + { + if (systemPtr) + m_orderedSystems.push_back(systemPtr.get()); + } + + std::sort(m_orderedSystems.begin(), m_orderedSystems.end(), [] (BaseSystem* first, BaseSystem* second) + { + return first->GetUpdateOrder() < second->GetUpdateOrder(); + }); + + m_orderedSystemsUpdated = true; + } } diff --git a/build/Build_CodeBlocks.bat b/build/Build_CodeBlocks.bat index 439c5efac..5e6c23c44 100644 --- a/build/Build_CodeBlocks.bat +++ b/build/Build_CodeBlocks.bat @@ -1 +1 @@ -premake4 codeblocks \ No newline at end of file +premake5 codeblocks \ No newline at end of file diff --git a/build/scripts/actions/codeblocks.lua b/build/scripts/actions/codeblocks.lua new file mode 100644 index 000000000..f96a6d591 --- /dev/null +++ b/build/scripts/actions/codeblocks.lua @@ -0,0 +1,4 @@ +dofile("codeblocks/_codeblocks.lua") +dofile("codeblocks/codeblocks.lua") + +ACTION.Manual = true diff --git a/build/scripts/actions/codeblocks/_codeblocks.lua b/build/scripts/actions/codeblocks/_codeblocks.lua new file mode 100644 index 000000000..6a52bc404 --- /dev/null +++ b/build/scripts/actions/codeblocks/_codeblocks.lua @@ -0,0 +1,44 @@ +-- +-- _codeblocks.lua +-- Define the Code::Blocks action(s). +-- Copyright (c) 2002-2011 Jason Perkins and the Premake project +-- + local p = premake + + p.modules.codeblocks = {} + p.modules.codeblocks._VERSION = p._VERSION + + local codeblocks = p.modules.codeblocks + + newaction { + trigger = "codeblocks", + shortname = "Code::Blocks", + description = "Generate Code::Blocks project files", + + valid_kinds = { "ConsoleApp", "WindowedApp", "StaticLib", "SharedLib" }, + + valid_languages = { "C", "C++" }, + + valid_tools = { + cc = { "clang", "gcc", "ow" }, + }, + + onWorkspace = function(wks) + p.modules.codeblocks.generateWorkspace(wks) + end, + + onProject = function(prj) + p.modules.codeblocks.generateProject(prj) + end, + + onCleanWorkspace = function(wks) + p.clean.file(wks, wks.name .. ".workspace") + p.clean.file(wks, wks.name .. ".workspace.layout") + end, + + onCleanProject = function(prj) + p.clean.file(prj, prj.name .. ".workspace") + p.clean.file(prj, prj.name .. ".depend") + p.clean.file(prj, prj.name .. ".layout") + end + } diff --git a/build/scripts/actions/codeblocks/codeblocks.lua b/build/scripts/actions/codeblocks/codeblocks.lua new file mode 100644 index 000000000..ebd8d11fa --- /dev/null +++ b/build/scripts/actions/codeblocks/codeblocks.lua @@ -0,0 +1,67 @@ +-- +-- codeblocks_workspace.lua +-- Generate a Code::Blocks workspace. +-- Copyright (c) 2009 Jason Perkins and the Premake project +-- + + local p = premake + + p.modules.codeblocks = {} + p.modules.codeblocks._VERSION = p._VERSION + + local codeblocks = p.modules.codeblocks + local project = p.project + + + function codeblocks.cfgname(cfg) + local cfgname = cfg.buildcfg + if codeblocks.workspace.multiplePlatforms then + cfgname = string.format("%s|%s", cfg.platform, cfg.buildcfg) + end + return cfgname + end + + function codeblocks.esc(value) + local result = value:gsub('"', '"') + result = result:gsub('<', '<') + result = result:gsub('>', '>') + return result + end + + function codeblocks.generateWorkspace(wks) + p.eol("\r\n") + p.indent("\t") + p.escaper(codeblocks.esc) + + p.generate(wks, ".workspace", codeblocks.workspace.generate) + end + + function codeblocks.generateProject(prj) + p.eol("\r\n") + p.indent("\t") + p.escaper(codeblocks.esc) + + if project.iscpp(prj) then + p.generate(prj, ".cbp", codeblocks.project.generate) + end + end + + function codeblocks.cleanWorkspace(wks) + p.clean.file(wks, wks.name .. ".workspace") + p.clean.file(wks, wks.name .. ".workspace.layout") + end + + function codeblocks.cleanProject(prj) + p.clean.file(prj, prj.name .. ".workspace") + p.clean.file(prj, prj.name .. ".depend") + p.clean.file(prj, prj.name .. ".layout") + end + + function codeblocks.cleanTarget(prj) + -- TODO.. + end + + include("codeblocks_workspace.lua") + include("codeblocks_project.lua") + + diff --git a/build/scripts/actions/codeblocks/codeblocks_project.lua b/build/scripts/actions/codeblocks/codeblocks_project.lua new file mode 100644 index 000000000..acfede4c2 --- /dev/null +++ b/build/scripts/actions/codeblocks/codeblocks_project.lua @@ -0,0 +1,243 @@ +-- +-- codeblocks_cbp.lua +-- Generate a Code::Blocks C/C++ project. +-- Copyright (c) 2009, 2011 Jason Perkins and the Premake project +-- + + local p = premake + local project = p.project + local config = p.config + local tree = p.tree + local codeblocks = p.modules.codeblocks + + codeblocks.project = {} + local m = codeblocks.project + m.elements = {} + + m.ctools = { + gcc = "gcc", + msc = "Visual C++", + } + + function m.getcompilername(cfg) + local tool = _OPTIONS.cc or cfg.toolset or p.GCC + + local toolset = p.tools[tool] + if not toolset then + error("Invalid toolset '" + (_OPTIONS.cc or cfg.toolset) + "'") + end + + return m.ctools[tool] + end + + function m.getcompiler(cfg) + local toolset = p.tools[_OPTIONS.cc or cfg.toolset or p.GCC] + if not toolset then + error("Invalid toolset '" + (_OPTIONS.cc or cfg.toolset) + "'") + end + return toolset + end + + function m.header(prj) + _p('') + _p('') + _p(1,'') + + -- write project block header + _p(1,'') + _p(2,'') + _p('') + end + + m.elements.project = function(prj) + return { + m.header, + m.configurations, + m.files, + m.extensions, + m.footer + } + end + +-- +-- Project: Generate the CodeBlocks project file. +-- + function m.generate(prj) + p.utf8() + + p.callArray(m.elements.project, prj) + end + + function m.configurations(prj) + -- write configuration blocks + _p(2,'') + local platforms = {} + for cfg in project.eachconfig(prj) do + local found = false + for k,v in pairs(platforms) do + if (v.platform == cfg.platform) then + table.insert(v.configs, cfg) + found = true + break + end + end + + if (not found) then + table.insert(platforms, {platform = cfg.platform, configs = {cfg}}) + end + end + + for k,platform in pairs(platforms) do + for k,cfg in pairs(platform.configs) do + local compiler = m.getcompiler(cfg) + + _p(3,'', cfg.longname) + + _p(4,'') + end + end + _p(2,'') + end + +-- +-- Write out a list of the source code files in the project. +-- + + function m.files(prj) + local pchheader + if (prj.pchheader) then + pchheader = path.getrelative(prj.location, prj.pchheader) + end + + local tr = project.getsourcetree(prj) + tree.traverse(tr, { + -- source files are handled at the leaves + onleaf = function(node, depth) + if node.relpath == node.vpath then + _p(2,'', node.relpath) + else + _p(2,'', node.name) + _p(3,'') + + end, + }, false, 1) + end + + function m.extensions(prj) + for cfg in project.eachconfig(prj) do + if cfg.debugenvs and #cfg.debugenvs > 0 then + --Assumption: if gcc is being used then so is gdb although this section will be ignored by + --other debuggers. If using gcc and not gdb it will silently not pass the + --environment arguments to the debugger + if m.getcompilername(cfg) == "gcc" then + _p(3,'') + _p(4,'', p.esc(cfg.longname)) + local args = '' + local sz = #cfg.debugenvs + for idx, v in ipairs(cfg.debugenvs) do + args = args .. 'set env ' .. v + if sz ~= idx then args = args .. ' ' end + end + _p(5,'',args) + _p(4,'') + _p(3,'') + else + error('Sorry at this moment there is no support for debug environment variables with this debugger and codeblocks') + end + end + end + end diff --git a/build/scripts/actions/codeblocks/codeblocks_workspace.lua b/build/scripts/actions/codeblocks/codeblocks_workspace.lua new file mode 100644 index 000000000..3de935877 --- /dev/null +++ b/build/scripts/actions/codeblocks/codeblocks_workspace.lua @@ -0,0 +1,44 @@ +-- +-- Name: codelite/codelite_workspace.lua +-- Purpose: Generate a CodeLite workspace. +-- Author: Ryan Pusztai +-- Modified by: Andrea Zanellato +-- Manu Evans +-- Created: 2013/05/06 +-- Copyright: (c) 2008-2015 Jason Perkins and the Premake project +-- + + local p = premake + local project = p.project + local workspace = p.workspace + local tree = p.tree + local codeblocks = p.modules.codeblocks + + codeblocks.workspace = {} + local m = codeblocks.workspace + +-- +-- Generate a CodeBlocks workspace +-- + function m.generate(wks) + p.utf8() + + _p('') + _p('') + _p(1,'', wks.name) + + for prj in workspace.eachproject(wks) do + local fname = path.join(path.getrelative(wks.location, prj.location), prj.name) + local active = iif(prj.project == wks.projects[1], ' active="1"', '') + + _p(2,'', fname, active) + for _,dep in ipairs(project.getdependencies(prj)) do + _p(3,'', path.join(path.getrelative(wks.location, dep.location), dep.name)) + end + + _p(2,'') + end + + _p(1,'') + _p('') + end \ No newline at end of file diff --git a/build/scripts/common.lua b/build/scripts/common.lua index 423ebad0d..01b51562d 100644 --- a/build/scripts/common.lua +++ b/build/scripts/common.lua @@ -1,4 +1,7 @@ -NazaraBuild = {} -- L'équivalent d'un namespace en Lua est une table +NazaraBuild = {} + +-- I wish Premake had a way to know the compiler in advance +local clangGccActions = "action:" .. table.concat({"codeblocks", "codelite", "gmake", "xcode3", "xcode4"}, " or ") function NazaraBuild:AddExecutablePath(path) self.ExecutableDir[path] = true @@ -9,21 +12,47 @@ function NazaraBuild:AddInstallPath(path) self.InstallDir[path] = true end +function NazaraBuild:FilterLibDirectory(prefix, func) + filter({"action:codeblocks or codelite or gmake", "architecture:x86", "system:Windows"}) + func(prefix .. "mingw/x86") + + filter({"action:codeblocks or codelite or gmake", "architecture:x86_64", "system:Windows"}) + func(prefix .. "mingw/x64") + + filter({"action:codeblocks or codelite or gmake", "architecture:x86", "system:not Windows"}) + func(prefix .. "gmake/x86") + + filter({"action:codeblocks or codelite or gmake", "architecture:x86_64", "system:not Windows"}) + func(prefix .. "gmake/x64") + + filter({"action:vs*", "architecture:x86"}) + func(prefix .. "msvc/x86") + + filter({"action:vs*", "architecture:x86_64"}) + func(prefix .. "msvc/x64") + + filter({"action:xcode3 or xcode4", "architecture:x86"}) + func(prefix .. "xcode/x86") + + filter({"action:xcode3 or xcode4", "architecture:x86_64"}) + func(prefix .. "xcode/x64") + + filter({}) +end + function NazaraBuild:Execute() - if (_ACTION == nil) then -- Si aucune action n'est spécifiée + if (_ACTION == nil) then -- If no action is specified, the user probably only wants to know how all of this works return -- Alors l'utilisateur voulait probablement savoir comment utiliser le programme, on ne fait rien end local platformData if (os.is64bit()) then - platformData = {"x64", "x32"} + platformData = {"x64", "x86"} else - platformData = {"x32", "x64"} + platformData = {"x86", "x64"} end if (self.Actions[_ACTION] == nil) then - local makeLibDir = os.is("windows") and "mingw" or "gmake" - if (self.Config["BuildDependencies"]) then workspace("NazaraExtlibs") platforms(platformData) @@ -34,63 +63,19 @@ function NazaraBuild:Execute() "ReleaseStatic" }) + self:PrepareGeneric() + self:FilterLibDirectory("../extlibs/lib/", targetdir) + + filter(clangGccActions) + buildoptions("-U__STRICT_ANSI__") + + filter({}) + includedirs("../extlibs/include") libdirs("../extlibs/lib/common") location(_ACTION) kind("StaticLib") - configuration({"codeblocks or codelite or gmake", "x32"}) - libdirs("../extlibs/lib/" .. makeLibDir .. "/x86") - targetdir("../extlibs/lib/" .. makeLibDir .. "/x86") - - configuration({"codeblocks or codelite or gmake", "x64"}) - libdirs("../extlibs/lib/" .. makeLibDir .. "/x64") - targetdir("../extlibs/lib/" .. makeLibDir .. "/x64") - - configuration("vs*") - buildoptions({"/MP", "/bigobj"}) -- Multiprocessus build and big .obj - - configuration({"vs*", "x32"}) - libdirs("../extlibs/lib/msvc/x86") - targetdir("../extlibs/lib/msvc/x86") - - configuration({"vs*", "x64"}) - libdirs("../extlibs/lib/msvc/x64") - targetdir("../extlibs/lib/msvc/x64") - - configuration({"xcode3 or xcode4", "x32"}) - libdirs("../extlibs/lib/xcode/x86") - targetdir("../extlibs/lib/xcode/x86") - - configuration({"xcode3 or xcode4", "x64"}) - libdirs("../extlibs/lib/xcode/x64") - targetdir("../extlibs/lib/xcode/x64") - - configuration("Debug*") - flags("Symbols") - - configuration("Release*") - flags("NoFramePointer") - optimize("Speed") - rtti("Off") - vectorextensions("SSE2") - - configuration({"Release*", "codeblocks or codelite or gmake or xcode3 or xcode4"}) - buildoptions("-mfpmath=sse") -- Utilisation du SSE pour les calculs flottants - buildoptions("-ftree-vectorize") -- Activation de la vectorisation du code - - configuration("DebugStatic") - targetsuffix("-s-d") - - configuration("ReleaseStatic") - targetsuffix("-s") - - configuration({"not windows", "codeblocks or codelite or gmake or xcode3 or xcode4"}) - buildoptions("-fPIC") - - configuration("codeblocks or codelite or gmake or xcode3 or xcode4") - buildoptions({"-std=c++14", "-U__STRICT_ANSI__"}) - for k, libTable in ipairs(self.OrderedExtLibs) do project(libTable.Name) @@ -105,25 +90,30 @@ function NazaraBuild:Execute() includedirs(libTable.Includes) links(libTable.Libraries) - configuration("x32") + filter("architecture:x86") libdirs(libTable.LibraryPaths.x86) - configuration("x64") + filter("architecture:x86_64") libdirs(libTable.LibraryPaths.x64) for k,v in pairs(libTable.ConfigurationLibraries) do - configuration(k) - links(v) + filter(k) + links(v) end - configuration({}) + filter({}) end end - + + -- Start defining projects workspace("NazaraEngine") platforms(platformData) - -- Configuration générale + self:PrepareMainWorkspace() + + -- Add lib/conf/arch to library search path + self:FilterLibDirectory("../lib/", libdirs) + configurations({ -- "DebugStatic", -- "ReleaseStatic", @@ -134,36 +124,7 @@ function NazaraBuild:Execute() language("C++") location(_ACTION) - configuration("Debug*") - defines("NAZARA_DEBUG") - flags("Symbols") - - configuration("Release*") - flags("NoFramePointer") - optimize("Speed") - vectorextensions("SSE2") - - configuration({"Release*", "codeblocks or codelite or gmake or xcode3 or xcode4"}) - buildoptions("-mfpmath=sse") -- Utilisation du SSE pour les calculs flottants - buildoptions("-ftree-vectorize") -- Activation de la vectorisation du code - - configuration("*Static") - defines("NAZARA_STATIC") - - configuration("codeblocks or codelite or gmake or xcode3 or xcode4") - buildoptions("-std=c++14") - - configuration({"linux or bsd or macosx", "gmake"}) - buildoptions("-fvisibility=hidden") - - configuration("vs*") - buildoptions({"/MP", "/bigobj"}) -- Multiprocessus build and big .obj - flags("NoMinimalRebuild") - defines("_CRT_SECURE_NO_WARNINGS") - defines("_SCL_SECURE_NO_WARNINGS") - - - -- Spécification des modules + -- Modules if (_OPTIONS["united"]) then project("NazaraEngine") end @@ -175,78 +136,12 @@ function NazaraBuild:Execute() location(_ACTION .. "/modules") - defines("NAZARA_BUILD") - includedirs({ "../include", "../src/", "../extlibs/include" }) - libdirs("../lib") - libdirs("../extlibs/lib/common") - - configuration("x32") - libdirs(moduleTable.LibraryPaths.x86) - - configuration("x64") - defines("NAZARA_PLATFORM_x64") - libdirs(moduleTable.LibraryPaths.x64) - - configuration({"codeblocks or codelite or gmake", "x32"}) - libdirs("../extlibs/lib/" .. makeLibDir .. "/x86") - libdirs("../lib/" .. makeLibDir .. "/x86") - targetdir("../lib/" .. makeLibDir .. "/x86") - - configuration({"codeblocks or codelite or gmake", "x64"}) - libdirs("../extlibs/lib/" .. makeLibDir .. "/x64") - libdirs("../lib/" .. makeLibDir .. "/x64") - targetdir("../lib/" .. makeLibDir .. "/x64") - - -- Copy the module binaries to the example folder - self:MakeInstallCommands(moduleTable) - - configuration({"vs*", "x32"}) - libdirs("../extlibs/lib/msvc/x86") - libdirs("../lib/msvc/x86") - targetdir("../lib/msvc/x86") - - configuration({"vs*", "x64"}) - libdirs("../extlibs/lib/msvc/x64") - libdirs("../lib/msvc/x64") - targetdir("../lib/msvc/x64") - - configuration({"xcode3 or xcode4", "x32"}) - libdirs("../extlibs/lib/xcode/x86") - libdirs("../lib/xcode/x86") - targetdir("../lib/xcode/x86") - - configuration({"xcode3 or xcode4", "x64"}) - libdirs("../extlibs/lib/xcode/x64") - libdirs("../lib/xcode/x64") - targetdir("../lib/xcode/x64") - - configuration("*Static") - defines("NAZARA_STATIC") - kind("StaticLib") - - configuration("*Dynamic") - kind("SharedLib") - - configuration("DebugStatic") - targetsuffix("-s-d") - - configuration("ReleaseStatic") - targetsuffix("-s") - - configuration("DebugDynamic") - targetsuffix("-d") - - configuration("Release*") - rtti(moduleTable.EnableRTTI and "On" or "Off") - - configuration({}) - files(moduleTable.Files) excludes(moduleTable.FilesExcluded) @@ -255,12 +150,29 @@ function NazaraBuild:Execute() includedirs(moduleTable.Includes) links(moduleTable.Libraries) + libdirs({ + "../extlibs/lib/common", + "../lib" + }) + + -- Output to lib/conf/arch + self:FilterLibDirectory("../lib/", targetdir) + + -- Copy the module binaries to the example folder + self:MakeInstallCommands(moduleTable) + + filter("architecture:x86") + libdirs(moduleTable.LibraryPaths.x86) + + filter("architecture:x86_64") + libdirs(moduleTable.LibraryPaths.x64) + for k,v in pairs(moduleTable.ConfigurationLibraries) do - configuration(k) + filter(k) links(v) end - configuration({}) + filter({}) end -- Tools @@ -288,7 +200,7 @@ function NazaraBuild:Execute() kind("WindowedApp") end else - assert(false, "Invalid tool Kind") + assert(false, "Invalid tool kind") end includedirs({ @@ -296,94 +208,10 @@ function NazaraBuild:Execute() "../extlibs/include" }) - libdirs("../lib") - libdirs("../extlibs/lib/common") - - configuration("x32") - libdirs(toolTable.LibraryPaths.x86) - - configuration("x64") - defines("NAZARA_PLATFORM_x64") - libdirs(toolTable.LibraryPaths.x64) - - configuration({"codeblocks or codelite or gmake", "x32"}) - libdirs("../extlibs/lib/" .. makeLibDir .. "/x86") - libdirs("../lib/" .. makeLibDir .. "/x86") - if (toolTable.Kind == "library") then - targetdir(toolTable.TargetDirectory .. "/" .. makeLibDir .. "/x86") - elseif (toolTable.Kind == "plugin") then - targetdir("../plugins/lib/" .. makeLibDir .. "/x86") - end - - configuration({"codeblocks or codelite or gmake", "x64"}) - libdirs("../extlibs/lib/" .. makeLibDir .. "/x64") - libdirs("../lib/" .. makeLibDir .. "/x64") - if (toolTable.Kind == "library") then - targetdir(toolTable.TargetDirectory .. "/" .. makeLibDir .. "/x64") - elseif (toolTable.Kind == "plugin") then - targetdir("../plugins/lib/" .. makeLibDir .. "/x64") - end - - configuration({"vs*", "x32"}) - libdirs("../extlibs/lib/msvc/x86") - libdirs("../lib/msvc/x86") - if (toolTable.Kind == "library") then - targetdir(toolTable.TargetDirectory .. "/msvc/x86") - elseif (toolTable.Kind == "plugin") then - targetdir("../plugins/lib/msvc/x86") - end - - configuration({"vs*", "x64"}) - libdirs("../extlibs/lib/msvc/x64") - libdirs("../lib/msvc/x64") - if (toolTable.Kind == "library") then - targetdir(toolTable.TargetDirectory .. "/msvc/x64") - elseif (toolTable.Kind == "plugin") then - targetdir("../plugins/lib/msvc/x64") - end - - configuration({"xcode3 or xcode4", "x32"}) - libdirs("../extlibs/lib/xcode/x86") - libdirs("../lib/xcode/x86") - if (toolTable.Kind == "library") then - targetdir(toolTable.TargetDirectory .. "/xcode/x86") - elseif (toolTable.Kind == "plugin") then - targetdir("../plugins/lib/xcode/x86") - end - - configuration({"xcode3 or xcode4", "x64"}) - libdirs("../extlibs/lib/xcode/x64") - libdirs("../lib/xcode/x64") - if (toolTable.Kind == "library") then - targetdir(toolTable.TargetDirectory .. "/xcode/x64") - elseif (toolTable.Kind == "plugin") then - targetdir("../plugins/lib/xcode/x64") - end - - configuration("*Static") - defines("NAZARA_STATIC") - - configuration("Release*") - rtti(toolTable.EnableRTTI and "On" or "Off") - - if (toolTable.Kind == "library" or toolTable.Kind == "plugin") then - configuration("*Static") - kind("StaticLib") - - configuration("*Dynamic") - kind("SharedLib") - - configuration("DebugStatic") - targetsuffix("-s-d") - - configuration("ReleaseStatic") - targetsuffix("-s") - - configuration("DebugDynamic") - targetsuffix("-d") - end - - configuration({}) + libdirs({ + "../extlibs/lib/common", + "../lib" + }) files(toolTable.Files) excludes(toolTable.FilesExcluded) @@ -393,12 +221,25 @@ function NazaraBuild:Execute() includedirs(toolTable.Includes) links(toolTable.Libraries) + -- Output to lib/conf/arch + if (toolTable.Kind == "library") then + self:FilterLibDirectory(toolTable.TargetDirectory .. "/", targetdir) + elseif (toolTable.Kind == "plugin") then + self:FilterLibDirectory("../plugins/lib/", targetdir) + end + + filter("architecture:x86") + libdirs(toolTable.LibraryPaths.x86) + + filter("architecture:x86_64") + libdirs(toolTable.LibraryPaths.x64) + for k,v in pairs(toolTable.ConfigurationLibraries) do - configuration(k) + filter(k) links(v) end - configuration({}) + filter({}) end for k, exampleTable in ipairs(self.OrderedExamples) do @@ -429,7 +270,6 @@ function NazaraBuild:Execute() "../extlibs/include" }) libdirs("../lib") - targetdir(destPath) files(exampleTable.Files) excludes(exampleTable.FilesExcluded) @@ -438,41 +278,14 @@ function NazaraBuild:Execute() flags(exampleTable.Flags) includedirs(exampleTable.Includes) links(exampleTable.Libraries) - - configuration("Release*") - rtti(exampleTable.EnableRTTI and "On" or "Off") - - configuration("x32") - libdirs(exampleTable.LibraryPaths.x86) - - configuration("x64") - defines("NAZARA_PLATFORM_x64") - libdirs(exampleTable.LibraryPaths.x64) - - configuration({"codeblocks or codelite or gmake", "x32"}) - libdirs("../lib/" .. makeLibDir .. "/x86") - - configuration({"codeblocks or codelite or gmake", "x64"}) - libdirs("../lib/" .. makeLibDir .. "/x64") - - configuration({"vs*", "x32"}) - libdirs("../lib/msvc/x86") - - configuration({"vs*", "x64"}) - libdirs("../lib/msvc/x64") - - configuration({"xcode3 or xcode4", "x32"}) - libdirs("../lib/xcode/x86") - - configuration({"xcode3 or xcode4", "x64"}) - libdirs("../lib/xcode/x64") + targetdir(destPath) for k,v in pairs(exampleTable.ConfigurationLibraries) do - configuration(k) + filter(k) links(v) end - configuration({}) + filter({}) end end end @@ -712,39 +525,37 @@ function NazaraBuild:LoadConfig() end function NazaraBuild:MakeInstallCommands(infoTable) - if (PremakeVersion < 50) then - return - end - if (os.is("windows")) then - configuration("*Dynamic") - + filter("kind:SharedLib") + + postbuildmessage("Copying " .. infoTable.Name .. " library and its dependencies to install/executable directories...") + for k,v in pairs(self.InstallDir) do local destPath = path.translate(path.isabsolute(k) and k or "../../" .. k) - postbuildcommands({[[xcopy "%{path.translate(cfg.linktarget.relpath):sub(1, -5) .. ".dll"}" "]] .. destPath .. [[\" /E /Y]]}) + postbuildcommands({[[xcopy "%{path.translate(cfg.buildtarget.relpath)}" "]] .. destPath .. [[\" /E /Y]]}) end for k,fileName in pairs(table.join(infoTable.Libraries, infoTable.DynLib)) do local paths = {} for k,v in pairs(infoTable.BinaryPaths.x86) do - table.insert(paths, {"x32", v .. "/" .. fileName .. ".dll"}) - table.insert(paths, {"x32", v .. "/lib" .. fileName .. ".dll"}) + table.insert(paths, {"x86", v .. "/" .. fileName .. ".dll"}) + table.insert(paths, {"x86", v .. "/lib" .. fileName .. ".dll"}) end for k,v in pairs(infoTable.BinaryPaths.x64) do - table.insert(paths, {"x64", v .. "/" .. fileName .. ".dll"}) - table.insert(paths, {"x64", v .. "/lib" .. fileName .. ".dll"}) + table.insert(paths, {"x86_64", v .. "/" .. fileName .. ".dll"}) + table.insert(paths, {"x86_64", v .. "/lib" .. fileName .. ".dll"}) end for k,v in pairs(paths) do - local config = v[1] + local arch = v[1] local srcPath = v[2] if (os.isfile(srcPath)) then if (infoTable.Kind == "plugin") then srcPath = "../../" .. srcPath end - configuration(config) + filter("architecture:" .. arch) for k,v in pairs(self.ExecutableDir) do local srcPath = path.isabsolute(srcPath) and path.translate(srcPath) or [[%{path.translate(cfg.linktarget.relpath:sub(1, -#cfg.linktarget.name - 1) .. "../../]] .. srcPath .. [[")}]] @@ -754,6 +565,8 @@ function NazaraBuild:MakeInstallCommands(infoTable) end end end + + filter({}) end end @@ -876,41 +689,125 @@ function NazaraBuild:Process(infoTable) return true end +function NazaraBuild:PrepareGeneric() + flags({ + "C++14", + "MultiProcessorCompile", + "NoMinimalRebuild", + "RelativeLinks", + "ShadowedVariables", + "UndefinedIdentifiers" + }) + + self:FilterLibDirectory("../extlibs/lib/", libdirs) + + -- Fixes Premake stuff + filter({"kind:SharedLib", clangGccActions}) + implibprefix("lib") + filter({"kind:*Lib", clangGccActions, "system:Windows"}) + implibextension(".a") + filter({"kind:StaticLib", clangGccActions}) + targetextension(".a") + targetprefix("lib") + + -- General configuration + filter("kind:*Lib") + pic("On") + + filter({"kind:*Lib", "configurations:DebugStatic"}) + targetsuffix("-s-d") + + filter({"kind:*Lib", "configurations:ReleaseStatic"}) + targetsuffix("-s") + + filter({"kind:*Lib", "configurations:DebugDynamic"}) + targetsuffix("-d") + + filter("configurations:Debug*") + symbols("On") + + -- Setup some optimizations for release + filter("configurations:Release*") + flags("NoFramePointer") + optimize("Speed") + vectorextensions("SSE2") + + filter("configurations:*Static") + kind("StaticLib") + + filter("configurations:*Dynamic") + kind("SharedLib") + + -- Enable SSE math and vectorization optimizations + filter({"configurations:Release*", clangGccActions}) + buildoptions("-mfpmath=sse") + buildoptions("-ftree-vectorize") + + filter({}) +end + +function NazaraBuild:PrepareMainWorkspace() + self:PrepareGeneric() + + filter("action:vs*") + buildoptions({"/MP", "/bigobj"}) -- Multiprocessus build and big .obj + defines("_CRT_SECURE_NO_WARNINGS") + defines("_SCL_SECURE_NO_WARNINGS") + + filter("architecture:x86_64") + defines("NAZARA_PLATFORM_x64") + + filter("configurations:Debug*") + defines("NAZARA_DEBUG") + + filter("configurations:*Static") + defines("NAZARA_STATIC") + + filter("kind:*Lib") + defines("NAZARA_BUILD") + + filter({"system:Windows", clangGccActions}) + buildoptions("-Wa,-mbig-obj") -- big object + + filter({"system:not Windows", clangGccActions}) + buildoptions("-fvisibility=hidden") + + filter({}) +end + function NazaraBuild:RegisterAction(actionTable) - if (actionTable.Name == nil or type(actionTable.Name) ~= "string" or string.len(actionTable.Name) == 0) then - return false, "Invalid action name" + if (not actionTable.Manual) then + if (actionTable.Name == nil or type(actionTable.Name) ~= "string" or string.len(actionTable.Name) == 0) then + return false, "Invalid action name" + end + + local lowerCaseName = string.lower(actionTable.Name) + if (self.Actions[lowerCaseName] ~= nil) then + return false, "This action name is already in use" + end + + if (actionTable.Description == nil or type(actionTable.Description) ~= "string") then + return false, "Action description is invalid" + end + + if (string.len(actionTable.Description) == 0) then + return false, "Action description is empty" + end + + if (actionTable.Function == nil or type(actionTable.Function) ~= "function") then + return false, "Action function is invalid" + end + + self.Actions[lowerCaseName] = actionTable + + newaction + { + trigger = lowerCaseName, + description = actionTable.Description, + execute = function () actionTable:Function() end + } end - local lowerCaseName = string.lower(actionTable.Name) - if (self.Actions[lowerCaseName] ~= nil) then - return false, "This action name is already in use" - end - - if (actionTable.Description == nil or type(actionTable.Description) ~= "string") then - return false, "Action description is invalid" - end - - if (string.len(actionTable.Description) == 0) then - return false, "Action description is empty" - end - - if (self.Actions[actionTable.name] ~= nil) then - return false, "Action name \"" .. actionTable.name .. " is already registred" - end - - if (actionTable.Function == nil or type(actionTable.Function) ~= "function") then - return false, "Action function is invalid" - end - - self.Actions[lowerCaseName] = actionTable - - newaction - { - trigger = lowerCaseName, - description = actionTable.Description, - execute = function () actionTable:Function() end - } - return true end diff --git a/include/Nazara/Core/AbstractLogger.docx b/include/Nazara/Core/AbstractLogger.docx deleted file mode 100644 index 6ac06b95c..000000000 --- a/include/Nazara/Core/AbstractLogger.docx +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -/*! -* \ingroup core -* \class Nz::AbstractLogger -* \brief Logger interface -*/ - diff --git a/include/Nazara/Core/Algorithm.hpp b/include/Nazara/Core/Algorithm.hpp index 5bb461f26..a6d5e77a7 100644 --- a/include/Nazara/Core/Algorithm.hpp +++ b/include/Nazara/Core/Algorithm.hpp @@ -22,6 +22,7 @@ namespace Nz template decltype(auto) Apply(F&& fn, Tuple&& t); template decltype(auto) Apply(O& object, F&& fn, Tuple&& t); + template constexpr std::size_t BitCount(); 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 b02924446..fea1fd964 100644 --- a/include/Nazara/Core/Algorithm.inl +++ b/include/Nazara/Core/Algorithm.inl @@ -11,6 +11,7 @@ #include #include #include +#include #include namespace Nz @@ -70,6 +71,17 @@ namespace Nz return Detail::ApplyImplMethod(object, std::forward(fn), std::forward(t), std::make_index_sequence()); } + /*! + * \ingroup core + * \brief Returns the number of bits occupied by the type T + * \return Number of bits occupied by the type + */ + template + constexpr std::size_t BitCount() + { + return CHAR_BIT * sizeof(T); + } + /*! * \ingroup core * \brief Computes the hash of a hashable object diff --git a/include/Nazara/Core/Bitset.hpp b/include/Nazara/Core/Bitset.hpp index 5c2746d16..622238854 100644 --- a/include/Nazara/Core/Bitset.hpp +++ b/include/Nazara/Core/Bitset.hpp @@ -8,6 +8,7 @@ #define NAZARA_BITSET_HPP #include +#include #include #include #include @@ -24,6 +25,7 @@ namespace Nz public: class Bit; + using PointerSequence = std::pair; //< Start pointer, bit offset Bitset(); explicit Bitset(std::size_t bitCount, bool val); @@ -35,6 +37,8 @@ namespace Nz Bitset(Bitset&& bitset) noexcept = default; ~Bitset() noexcept = default; + template void AppendBits(T bits, std::size_t bitCount); + void Clear() noexcept; std::size_t Count() const; void Flip(); @@ -47,6 +51,9 @@ namespace Nz std::size_t GetCapacity() const; std::size_t GetSize() const; + PointerSequence Read(const void* ptr, std::size_t bitCount); + PointerSequence Read(const PointerSequence& sequence, std::size_t bitCount); + void PerformsAND(const Bitset& a, const Bitset& b); void PerformsNOT(const Bitset& a); void PerformsOR(const Bitset& a, const Bitset& b); @@ -60,6 +67,8 @@ namespace Nz void Reset(); void Reset(std::size_t bit); + void Reverse(); + void Set(bool val = true); void Set(std::size_t bit, bool val = true); void SetBlock(std::size_t i, Block block); @@ -102,9 +111,11 @@ namespace Nz Bitset& operator^=(const Bitset& bitset); static constexpr Block fullBitMask = std::numeric_limits::max(); - static constexpr std::size_t bitsPerBlock = std::numeric_limits::digits; + static constexpr std::size_t bitsPerBlock = BitCount(); static constexpr std::size_t npos = std::numeric_limits::max(); + static Bitset FromPointer(const void* ptr, std::size_t bitCount, PointerSequence* sequence = nullptr); + private: std::size_t FindFirstFrom(std::size_t blockIndex) const; Block GetLastBlockMask() const; @@ -154,6 +165,9 @@ namespace Nz Block m_mask; }; + template + std::ostream& operator<<(std::ostream& out, const Bitset& bitset); + template bool operator==(const Bitset& lhs, const Nz::Bitset& rhs); diff --git a/include/Nazara/Core/Bitset.inl b/include/Nazara/Core/Bitset.inl index 6ddb252e7..afec6983a 100644 --- a/include/Nazara/Core/Bitset.inl +++ b/include/Nazara/Core/Bitset.inl @@ -6,7 +6,6 @@ #include #include #include -#include #include #include @@ -122,13 +121,13 @@ namespace Nz { if (sizeof(T) <= sizeof(Block)) { - m_bitCount = std::numeric_limits::digits; + m_bitCount = BitCount(); m_blocks.push_back(static_cast(value)); } else { // Note: I was kinda tired when I wrote this, there's probably a much easier method than checking bits to write bits - for (std::size_t bitPos = 0; bitPos < std::numeric_limits::digits; bitPos++) + for (std::size_t bitPos = 0; bitPos < BitCount(); bitPos++) { if (value & (T(1U) << bitPos)) UnboundedSet(bitPos, true); @@ -137,11 +136,63 @@ namespace Nz } /*! - * \brief Clears the content of the bitset, GetSize() is now equals to 0 + * \brief Appends bits to the bitset * - * \remark The memory allocated is not released + * This function extends the bitset with bits extracted from an integer value + * + * \param bits An integer value from where bits will be extracted + * \param bitCount Number of bits to extract from the value + * + * \remark This function does not require bitCount to be lower or equal to the number of bits of T, thus + * reading 32 bits from a UInt8 will work (by extracting the first 8 bits values and appending 24 zeros afterneath). + * + * \see AppendBits + * \see Read */ + template + template + void Bitset::AppendBits(T bits, std::size_t bitCount) + { + std::size_t bitShift = m_bitCount % bitsPerBlock; + m_bitCount += bitCount; + if (bitShift != 0) + { + std::size_t remainingBits = bitsPerBlock - bitShift; + m_blocks.back() |= Block(bits) << bitShift; + bits >>= bitsPerBlock - bitShift; + + bitCount -= std::min(remainingBits, bitCount); + } + + if (bitCount > 0) + { + std::size_t blockCount = ComputeBlockCount(bitCount); + for (std::size_t block = 0; block < blockCount - 1; ++block) + { + m_blocks.push_back(static_cast(bits)); + bits = (BitCount() < BitCount()) ? bits >> BitCount() : 0U; + bitCount -= BitCount(); + } + + // For the last iteration, mask out the bits we don't want + std::size_t remainingBits = bitCount; + + bits &= ((Block(1U) << remainingBits) - 1U); + m_blocks.push_back(static_cast(bits)); + } + } + + /*! + * \brief Clears the content of the bitset + * + * This function clears the bitset content, resetting its bit and block count at zero. + * + * \remark This does not changes the bits values to zero but empties the bitset, to reset the bits use the Reset() function + * \remark This call does not changes the bitset capacity + * + * \see Reset() + */ template void Bitset::Clear() noexcept { @@ -151,9 +202,9 @@ namespace Nz /*! * \brief Counts the number of bits set to 1 + * * \return Number of bits set to 1 */ - template std::size_t Bitset::Count() const { @@ -169,8 +220,9 @@ namespace Nz /*! * \brief Flips each bit of the bitset + * + * This function flips every bit of the bitset, which means every '1' turns into a '0' and conversely. */ - template void Bitset::Flip() { @@ -182,9 +234,9 @@ namespace Nz /*! * \brief Finds the first bit set to one in the bitset - * \return Index of the first bit + * + * \return The 0-based index of the first bit enabled */ - template std::size_t Bitset::FindFirst() const { @@ -192,14 +244,14 @@ namespace Nz } /*! - * \brief Finds the next bit set to one in the bitset - * \return Index of the next bit if exists or npos + * \brief Finds the next enabled in the bitset * - * \param bit Index of the bit, the search begin with bit + 1 + * \param bit Index of the last bit found, which will not be treated by this function * - * \remark Produce a NazaraAssert if bit is greather than number of bits in bitset + * \return Index of the next enabled bit or npos if all the following bits are disabled + * + * \remark This function is typically used in for-loops to iterate on bits */ - template std::size_t Bitset::FindNext(std::size_t bit) const { @@ -275,6 +327,76 @@ namespace Nz return m_bitCount; } + /*! + * \brief Read a byte sequence into a bitset + * + * This function extends the bitset with bits read from a byte sequence + * + * \param ptr A pointer to the start of the byte sequence + * \param bitCount Number of bits to read from the byte sequence + * + * \returns A pointer to the next byte to read along with the next bit index (useful when reading multiple times) + * + * \remark For technical reasons, ceil(bitCount / 8) bytes from the sequence will always be read (even with non-multiple-of-8 bitCount) + * + * \see AppendBits + * \see Read + */ + template + typename Bitset::PointerSequence Bitset::Read(const void* ptr, std::size_t bitCount) + { + return Read(PointerSequence(ptr, 0U), bitCount); + } + + /*! + * \brief Read a byte sequence into a bitset + * + * This function extends the bitset with bits read from a pointer sequence (made of a pointer and a bit index) + * + * \param sequence A pointer sequence to the start of the byte sequence + * \param bitCount Number of bits to read from the byte sequence + * + * \returns A pointer to the next byte to read along with the next bit index (useful when reading multiple times) + * + * \remark For technical reasons, ceil(bitCount / 8) bytes from the sequence will always be read (even with non-multiple-of-8 bitCount) + * + * \see AppendBits + * \see Read + */ + template + typename Bitset::PointerSequence Bitset::Read(const PointerSequence& sequence, std::size_t bitCount) + { + NazaraAssert(sequence.first, "Invalid pointer sequence"); + NazaraAssert(sequence.second < 8, "Invalid next bit index (must be < 8)"); + + std::size_t totalBitCount = sequence.second + bitCount; + + const UInt8* u8Ptr = static_cast(sequence.first); + const UInt8* endPtr = u8Ptr + ((totalBitCount != 0) ? (totalBitCount - 1) / 8 : 0); + const UInt8* nextPtr = endPtr + ((totalBitCount % 8 != 0) ? 0 : 1); + + // Read the first block apart to apply a mask on the first byte if necessary + if (sequence.second != 0) + { + UInt8 mask = ~((1U << sequence.second) - 1U); + + std::size_t readCount = std::min(bitCount, 8 - sequence.second); + AppendBits(Block(*u8Ptr++ & mask) >> sequence.second, readCount); + bitCount -= readCount; + } + + // And then read the remaining bytes + while (u8Ptr <= endPtr) + { + std::size_t bitToRead = std::min(bitCount, 8); + AppendBits(*u8Ptr++, bitToRead); + bitCount -= bitToRead; + } + + // Returns informations to continue reading + return PointerSequence(nextPtr, totalBitCount % 8); + } + /*! * \brief Performs the "AND" operator between two bitsets * @@ -289,15 +411,17 @@ namespace Nz { std::pair minmax = std::minmax(a.GetBlockCount(), b.GetBlockCount()); - // We reinitialise our blocks with zero - m_blocks.clear(); - m_blocks.resize(minmax.second, 0U); + m_blocks.resize(minmax.second); m_bitCount = std::max(a.GetSize(), b.GetSize()); // In case of the "AND", we can stop with the smallest size (because x & 0 = 0) for (std::size_t i = 0; i < minmax.first; ++i) m_blocks[i] = a.GetBlock(i) & b.GetBlock(i); + // And then reset every other block to zero + for (std::size_t i = minmax.first; i < minmax.second; ++i) + m_blocks[i] = 0U; + ResetExtraBits(); } @@ -458,6 +582,30 @@ namespace Nz Set(bit, false); } + /*! + * \brief Reverse the order of bits in a bitset + * + * Reverse the order of bits in the bitset (first bit swap with the last one, etc.) + */ + template + void Bitset::Reverse() + { + if (m_bitCount == 0) + return; + + std::size_t i = 0; + std::size_t j = m_bitCount - 1; + + while (i < j) + { + bool bit1 = Test(i); + bool bit2 = Test(j); + + Set(i++, bit2); + Set(j--, bit1); + } + } + /*! * \brief Sets the bitset to val * @@ -535,27 +683,28 @@ namespace Nz return; } - auto div = std::lldiv(pos, bitsPerBlock); - if (div.rem != 0) + std::size_t blockShift = pos / bitsPerBlock; + std::size_t remainder = pos % bitsPerBlock; + if (remainder != 0) { std::size_t lastIndex = m_blocks.size() - 1; - std::size_t remaining = bitsPerBlock - div.rem; + std::size_t remaining = bitsPerBlock - remainder; - for (std::size_t i = lastIndex - div.quot; i > 0; --i) - m_blocks[i + div.quot] = (m_blocks[i] << div.rem) | (m_blocks[i - 1] >> remaining); + for (std::size_t i = lastIndex - blockShift; i > 0; --i) + m_blocks[i + blockShift] = (m_blocks[i] << remainder) | (m_blocks[i - 1] >> remaining); - m_blocks[div.quot] = m_blocks[0] << div.rem; + m_blocks[blockShift] = m_blocks[0] << remainder; - std::fill_n(m_blocks.begin(), div.quot, Block(0)); + std::fill_n(m_blocks.begin(), blockShift, Block(0)); } else { for (auto it = m_blocks.rbegin(); it != m_blocks.rend(); ++it) { - if (static_cast(std::distance(m_blocks.rbegin(), it) + div.quot) < m_blocks.size()) + if (static_cast(std::distance(m_blocks.rbegin(), it) + blockShift) < m_blocks.size()) { auto shiftedIt = it; - std::advance(shiftedIt, div.quot); + std::advance(shiftedIt, blockShift); *it = *shiftedIt; } @@ -588,27 +737,28 @@ namespace Nz return; } - auto div = std::lldiv(pos, bitsPerBlock); - if (div.rem != 0) + std::size_t blockShift = pos / bitsPerBlock; + std::size_t remainder = pos % bitsPerBlock; + if (remainder != 0) { std::size_t lastIndex = m_blocks.size() - 1; - std::size_t remaining = bitsPerBlock - div.rem; + std::size_t remaining = bitsPerBlock - remainder; - for (std::size_t i = div.quot; i < lastIndex; ++i) - m_blocks[i - div.quot] = (m_blocks[i] >> div.rem) | (m_blocks[i + 1] << remaining); + for (std::size_t i = blockShift; i < lastIndex; ++i) + m_blocks[i - blockShift] = (m_blocks[i] >> remainder) | (m_blocks[i + 1] << remaining); - m_blocks[lastIndex - div.quot] = m_blocks[lastIndex] >> div.rem; + m_blocks[lastIndex - blockShift] = m_blocks[lastIndex] >> remainder; - std::fill_n(m_blocks.begin() + (m_blocks.size() - div.quot), div.quot, Block(0)); + std::fill_n(m_blocks.begin() + (m_blocks.size() - blockShift), blockShift, Block(0)); } else { for (auto it = m_blocks.begin(); it != m_blocks.end(); ++it) { - if (static_cast(std::distance(m_blocks.begin(), it) + div.quot) < m_blocks.size()) + if (static_cast(std::distance(m_blocks.begin(), it) + blockShift) < m_blocks.size()) { auto shiftedIt = it; - std::advance(shiftedIt, div.quot); + std::advance(shiftedIt, blockShift); *it = *shiftedIt; } @@ -716,7 +866,7 @@ namespace Nz { static_assert(std::is_integral() && std::is_unsigned(), "T must be a unsigned integral type"); - NazaraAssert(m_bitCount <= std::numeric_limits::digits, "Bit count cannot be greater than T bit count"); + NazaraAssert(m_bitCount <= BitCount(), "Bit count cannot be greater than T bit count"); T value = 0; for (std::size_t i = 0; i < m_blocks.size(); ++i) @@ -989,13 +1139,41 @@ namespace Nz return *this; } + /*! + * \brief Builds a bitset from a byte sequence + * + * This function builds a bitset using a byte sequence by reading bitCount bits from it + * + * \param ptr A pointer to the start of the byte sequence + * \param bitCount Number of bits to read from the byte sequence + * \param sequence Optional data to pass to a next call to Read + * + * \return The constructed bitset + * + * \remark For technical reasons, ceil(bitCount / 8) bytes from the sequence will always be read (even with non-multiple-of-8 bitCount) + * + * \see AppendBits + * \see Read + */ + template + Bitset Bitset::FromPointer(const void* ptr, std::size_t bitCount, PointerSequence* sequence) + { + Bitset bitset; + + if (sequence) + *sequence = bitset.Read(ptr, bitCount); + else + bitset.Read(ptr, bitCount); + + return bitset; + } + /*! * \brief Finds the position of the first bit set to true after the blockIndex * \return The position of the bit * * \param blockIndex Index of the block */ - template std::size_t Bitset::FindFirstFrom(std::size_t blockIndex) const { @@ -1124,7 +1302,7 @@ namespace Nz template bool Bitset::Bit::Test() const { - return m_block & m_mask; + return (m_block & m_mask) != 0; } /*! @@ -1269,6 +1447,14 @@ namespace Nz return *this; } + + template + std::ostream& operator<<(std::ostream& out, const Bitset& bitset) + { + return out << bitset.ToString(); + } + + /*! * \brief Compares two bitsets * \return true if the two bitsets are the same diff --git a/include/Nazara/Core/ByteArray.hpp b/include/Nazara/Core/ByteArray.hpp index 90f9c5d03..4bdc34150 100644 --- a/include/Nazara/Core/ByteArray.hpp +++ b/include/Nazara/Core/ByteArray.hpp @@ -88,7 +88,7 @@ namespace Nz inline void ShrinkToFit(); inline void Swap(ByteArray& other); - inline String ToHex() const; + String ToHex() const; inline String ToString() const; // STL interface diff --git a/include/Nazara/Core/ByteArray.inl b/include/Nazara/Core/ByteArray.inl index 068bee4b6..b5d8b1510 100644 --- a/include/Nazara/Core/ByteArray.inl +++ b/include/Nazara/Core/ByteArray.inl @@ -465,22 +465,6 @@ namespace Nz m_array.swap(other.m_array); } - /*! - * \brief Gives a string representation in base 16 - * \return String in base 16 - */ - - inline String ByteArray::ToHex() const - { - std::size_t length = m_array.size() * 2; - - String hexOutput(length, '\0'); - for (std::size_t i = 0; i < m_array.size(); ++i) - std::sprintf(&hexOutput[i * 2], "%02x", m_array[i]); - - return hexOutput; - } - /*! * \brief Gives a string representation * \return String where each byte is converted to char diff --git a/include/Nazara/Core/ConditionVariable.hpp b/include/Nazara/Core/ConditionVariable.hpp index f6aeafe9b..19ab9e863 100644 --- a/include/Nazara/Core/ConditionVariable.hpp +++ b/include/Nazara/Core/ConditionVariable.hpp @@ -29,7 +29,7 @@ namespace Nz bool Wait(Mutex* mutex, UInt32 timeout); ConditionVariable& operator=(const ConditionVariable&) = delete; - inline ConditionVariable& operator=(ConditionVariable&& condition) noexcept; + ConditionVariable& operator=(ConditionVariable&& condition) noexcept; private: ConditionVariableImpl* m_impl; diff --git a/include/Nazara/Core/ParameterList.hpp b/include/Nazara/Core/ParameterList.hpp index 751746aea..b34f0eca0 100644 --- a/include/Nazara/Core/ParameterList.hpp +++ b/include/Nazara/Core/ParameterList.hpp @@ -60,10 +60,10 @@ namespace Nz { struct UserdataValue { - UserdataValue(Destructor Destructor, void* value) : + UserdataValue(Destructor func, void* ud) : counter(1), - destructor(Destructor), - ptr(value) + destructor(func), + ptr(ud) { } diff --git a/include/Nazara/Graphics/ForwardRenderQueue.hpp b/include/Nazara/Graphics/ForwardRenderQueue.hpp index 99be2743e..56474a642 100644 --- a/include/Nazara/Graphics/ForwardRenderQueue.hpp +++ b/include/Nazara/Graphics/ForwardRenderQueue.hpp @@ -87,7 +87,7 @@ namespace Nz struct SpriteChain_XYZ_Color_UV { const VertexStruct_XYZ_Color_UV* vertices; - unsigned int spriteCount; + std::size_t spriteCount; }; struct BatchedSpriteEntry @@ -160,7 +160,7 @@ namespace Nz const Material* material; }; - typedef std::vector TransparentModelContainer; + typedef std::vector TransparentModelContainer; struct Layer { diff --git a/include/Nazara/Graphics/ParticleDeclaration.hpp b/include/Nazara/Graphics/ParticleDeclaration.hpp index 278d25961..770cbe31d 100644 --- a/include/Nazara/Graphics/ParticleDeclaration.hpp +++ b/include/Nazara/Graphics/ParticleDeclaration.hpp @@ -36,10 +36,10 @@ namespace Nz ~ParticleDeclaration(); void DisableComponent(ParticleComponent component); - void EnableComponent(ParticleComponent component, ComponentType type, unsigned int offset); + void EnableComponent(ParticleComponent component, ComponentType type, std::size_t offset); - void GetComponent(ParticleComponent component, bool* enabled, ComponentType* type, unsigned int* offset) const; - unsigned int GetStride() const; + void GetComponent(ParticleComponent component, bool* enabled, ComponentType* type, std::size_t* offset) const; + std::size_t GetStride() const; void SetStride(unsigned int stride); @@ -60,7 +60,7 @@ namespace Nz { ComponentType type; bool enabled = false; - unsigned int offset; + std::size_t offset; /* ** -Lynix: @@ -71,7 +71,7 @@ namespace Nz }; std::array m_components; - unsigned int m_stride; + std::size_t m_stride; static std::array s_declarations; static ParticleDeclarationLibrary::LibraryMap s_library; diff --git a/include/Nazara/Graphics/ParticleEmitter.hpp b/include/Nazara/Graphics/ParticleEmitter.hpp index 8bd26a4bd..cfbb9e98a 100644 --- a/include/Nazara/Graphics/ParticleEmitter.hpp +++ b/include/Nazara/Graphics/ParticleEmitter.hpp @@ -28,12 +28,12 @@ namespace Nz void EnableLagCompensation(bool enable); - unsigned int GetEmissionCount() const; + std::size_t GetEmissionCount() const; float GetEmissionRate() const; bool IsLagCompensationEnabled() const; - void SetEmissionCount(unsigned int count); + void SetEmissionCount(std::size_t count); void SetEmissionRate(float rate); ParticleEmitter& operator=(const ParticleEmitter& emitter) = default; @@ -49,7 +49,7 @@ namespace Nz bool m_lagCompensationEnabled; mutable float m_emissionAccumulator; float m_emissionRate; - unsigned int m_emissionCount; + std::size_t m_emissionCount; }; } diff --git a/include/Nazara/Graphics/ParticleGroup.hpp b/include/Nazara/Graphics/ParticleGroup.hpp index 409090284..35feaa674 100644 --- a/include/Nazara/Graphics/ParticleGroup.hpp +++ b/include/Nazara/Graphics/ParticleGroup.hpp @@ -45,11 +45,11 @@ namespace Nz void* GenerateParticles(unsigned int count); const ParticleDeclarationConstRef& GetDeclaration() const; - unsigned int GetMaxParticleCount() const; - unsigned int GetParticleCount() const; - unsigned int GetParticleSize() const; + std::size_t GetMaxParticleCount() const; + std::size_t GetParticleCount() const; + std::size_t GetParticleSize() const; - void KillParticle(unsigned int index); + void KillParticle(std::size_t index); void KillParticles(); void RemoveController(ParticleController* controller); @@ -81,6 +81,9 @@ namespace Nz }; std::set> m_dyingParticles; + std::size_t m_maxParticleCount; + std::size_t m_particleCount; + std::size_t m_particleSize; mutable std::vector m_buffer; std::vector m_controllers; std::vector m_emitters; @@ -88,9 +91,6 @@ namespace Nz ParticleDeclarationConstRef m_declaration; ParticleRendererRef m_renderer; bool m_processing; - unsigned int m_maxParticleCount; - unsigned int m_particleCount; - unsigned int m_particleSize; }; } diff --git a/include/Nazara/Graphics/ParticleMapper.inl b/include/Nazara/Graphics/ParticleMapper.inl index 63c9c49ba..7d33bb655 100644 --- a/include/Nazara/Graphics/ParticleMapper.inl +++ b/include/Nazara/Graphics/ParticleMapper.inl @@ -23,7 +23,7 @@ namespace Nz // Then the component that are interesting bool enabled; ComponentType type; - unsigned int offset; + std::size_t offset; m_declaration->GetComponent(component, &enabled, &type, &offset); if (enabled) @@ -54,7 +54,7 @@ namespace Nz // Then the component that are interesting bool enabled; ComponentType type; - unsigned int offset; + std::size_t offset; m_declaration->GetComponent(component, &enabled, &type, &offset); if (enabled) diff --git a/include/Nazara/Graphics/RenderTechniques.hpp b/include/Nazara/Graphics/RenderTechniques.hpp index 1e006858a..a4642ffc8 100644 --- a/include/Nazara/Graphics/RenderTechniques.hpp +++ b/include/Nazara/Graphics/RenderTechniques.hpp @@ -29,7 +29,7 @@ namespace Nz static AbstractRenderTechnique* GetByName(const String& name, int* techniqueRanking = nullptr); static AbstractRenderTechnique* GetByRanking(int maxRanking, int* techniqueRanking = nullptr); - static unsigned int GetCount(); + static std::size_t GetCount(); static void Register(const String& name, int ranking, RenderTechniqueFactory factory); diff --git a/include/Nazara/Graphics/Sprite.hpp b/include/Nazara/Graphics/Sprite.hpp index 13bcc289b..2c42f4ce1 100644 --- a/include/Nazara/Graphics/Sprite.hpp +++ b/include/Nazara/Graphics/Sprite.hpp @@ -47,9 +47,11 @@ namespace Nz inline void SetCornerColor(RectCorner corner, const Color& color); inline void SetDefaultMaterial(); inline void SetMaterial(MaterialRef material, bool resizeSprite = true); + bool SetMaterial(String materialName, bool resizeSprite = true); inline void SetOrigin(const Vector3f& origin); inline void SetSize(const Vector2f& size); inline void SetSize(float sizeX, float sizeY); + bool SetTexture(String textureName, bool resizeSprite = true); inline void SetTexture(TextureRef texture, bool resizeSprite = true); inline void SetTextureCoords(const Rectf& coords); inline void SetTextureRect(const Rectui& rect); diff --git a/include/Nazara/Graphics/Sprite.inl b/include/Nazara/Graphics/Sprite.inl index 35885a94a..deec75959 100644 --- a/include/Nazara/Graphics/Sprite.inl +++ b/include/Nazara/Graphics/Sprite.inl @@ -184,12 +184,11 @@ namespace Nz } /*! - * \brief Sets the material of the sprite + * \brief Changes the material of the sprite * * \param material Material for the sprite - * \param resizeSprite Should sprite be resized to the material size (diffuse map) + * \param resizeSprite Should the sprite be resized to the texture size? */ - inline void Sprite::SetMaterial(MaterialRef material, bool resizeSprite) { m_material = std::move(material); @@ -249,16 +248,19 @@ namespace Nz /*! * \brief Sets the texture of the sprite * + * Assign a texture to the sprite material + * * \param texture Texture for the sprite - * \param resizeSprite Should sprite be resized to the texture size + * \param resizeSprite Should the sprite be resized to the texture size? + * + * \remark The sprite material gets copied to prevent accidentally changing other drawable materials */ - inline void Sprite::SetTexture(TextureRef texture, bool resizeSprite) { if (!m_material) SetDefaultMaterial(); else if (m_material->GetReferenceCount() > 1) - m_material = Material::New(*m_material); // Copie + m_material = Material::New(*m_material); // Copy the material if (resizeSprite && texture && texture->IsValid()) SetSize(Vector2f(Vector2ui(texture->GetSize()))); diff --git a/include/Nazara/Graphics/TileMap.inl b/include/Nazara/Graphics/TileMap.inl index 4473a8600..f8faa7b54 100644 --- a/include/Nazara/Graphics/TileMap.inl +++ b/include/Nazara/Graphics/TileMap.inl @@ -29,7 +29,7 @@ namespace Nz m_isometricModeEnabled(false) { NazaraAssert(m_tiles.size() != 0U, "Invalid map size"); - NazaraAssert(m_tileSize.x != 0U && m_tileSize.y != 0U, "Invalid tile size"); + NazaraAssert(m_tileSize.x > 0 && m_tileSize.y > 0, "Invalid tile size"); NazaraAssert(m_layers.size() != 0U, "Invalid material count"); for (Layer& layer : m_layers) @@ -175,7 +175,7 @@ namespace Nz * \param color The multiplicative color applied to the tile * \param materialIndex The material which will be used for rendering this tile * - * \remark The material at [materialIndex] must have a valid diffuse map before using this function, + * \remark The material at [materialIndex] must have a valid diffuse map before using this function, * as the size of the material diffuse map is used to compute normalized texture coordinates before returning. * * \see EnableTiles @@ -253,7 +253,7 @@ namespace Nz Rectf unnormalizedCoords(invWidth * rect.x, invHeight * rect.y, invWidth * rect.width, invHeight * rect.height); EnableTiles(unnormalizedCoords, color, materialIndex); } - + /*! * \brief Enable and sets tileCount tiles at positions contained at tilesPos location, enabling rendering at those locations * @@ -434,14 +434,14 @@ namespace Nz * * \param TileMap The other TileMap */ - inline TileMap& TileMap::operator=(const TileMap& TileMap) + inline TileMap& TileMap::operator=(const TileMap& tileMap) { - InstancedRenderable::operator=(TileMap); + InstancedRenderable::operator=(tileMap); - m_layers = TileMap.m_layers; - m_mapSize = TileMap.m_mapSize; - m_tiles = TileMap.m_tiles; - m_tileSize = TileMap.m_tileSize; + m_layers = tileMap.m_layers; + m_mapSize = tileMap.m_mapSize; + m_tiles = tileMap.m_tiles; + m_tileSize = tileMap.m_tileSize; // We do not copy final vertices because it's highly probable that our parameters are modified and they must be regenerated InvalidateBoundingVolume(); diff --git a/include/Nazara/Lua/LuaClass.inl b/include/Nazara/Lua/LuaClass.inl index daf7a632a..3168ba43d 100644 --- a/include/Nazara/Lua/LuaClass.inl +++ b/include/Nazara/Lua/LuaClass.inl @@ -129,7 +129,7 @@ namespace Nz BindMethod(name, [func, handler] (LuaInstance& lua, T& object, std::size_t /*argumentCount*/) -> int { - handler.ProcessArgs(lua); + handler.ProcessArguments(lua); return handler.Invoke(lua, object, func); }); @@ -143,7 +143,7 @@ namespace Nz BindMethod(name, [func, handler] (LuaInstance& lua, T& object, std::size_t /*argumentCount*/) -> int { - handler.ProcessArgs(lua); + handler.ProcessArguments(lua); return handler.Invoke(lua, object, func); }); @@ -157,7 +157,7 @@ namespace Nz BindMethod(name, [func, handler] (LuaInstance& lua, T& object, std::size_t /*argumentCount*/) -> int { - handler.ProcessArgs(lua); + handler.ProcessArguments(lua); return handler.Invoke(lua, object, func); }); @@ -171,7 +171,7 @@ namespace Nz BindMethod(name, [func, handler] (LuaInstance& lua, T& object, std::size_t /*argumentCount*/) -> int { - handler.ProcessArgs(lua); + handler.ProcessArguments(lua); return handler.Invoke(lua, object, func); }); @@ -203,7 +203,7 @@ namespace Nz BindStaticMethod(name, [func, handler] (LuaInstance& lua) -> int { - handler.ProcessArgs(lua); + handler.ProcessArguments(lua); return handler.Invoke(lua, func); }); @@ -335,7 +335,7 @@ namespace Nz NazaraWarning("Class \"" + m_info->name + "\" already registred in this instance"); { SetupFinalizer(lua); - + if (m_info->getter || !m_info->parentGetters.empty()) SetupGetter(lua, GetterProxy); else diff --git a/include/Nazara/Lua/LuaInstance.inl b/include/Nazara/Lua/LuaInstance.inl index 25f193675..9bc20c73a 100644 --- a/include/Nazara/Lua/LuaInstance.inl +++ b/include/Nazara/Lua/LuaInstance.inl @@ -59,7 +59,7 @@ namespace Nz m_memoryUsage = instance.m_memoryUsage; m_state = instance.m_state; m_timeLimit = instance.m_timeLimit; - + instance.m_state = nullptr; return *this; @@ -320,7 +320,7 @@ namespace Nz { } - void ProcessArgs(const LuaInstance& instance) const + void ProcessArguments(const LuaInstance& instance) const { m_index = 1; ProcessArgs<0, Args...>(instance); @@ -391,7 +391,7 @@ namespace Nz { } - void ProcessArgs(const LuaInstance& instance) const + void ProcessArguments(const LuaInstance& instance) const { m_index = 2; //< 1 being the instance ProcessArgs<0, Args...>(instance); @@ -714,7 +714,7 @@ namespace Nz PushFunction([func, handler] (LuaInstance& lua) -> int { - handler.ProcessArgs(lua); + handler.ProcessArguments(lua); return handler.Invoke(lua, func); }); diff --git a/include/Nazara/Math/Algorithm.hpp b/include/Nazara/Math/Algorithm.hpp index 45281bb50..f138a8fc9 100644 --- a/include/Nazara/Math/Algorithm.hpp +++ b/include/Nazara/Math/Algorithm.hpp @@ -37,7 +37,7 @@ namespace Nz { template /*constexpr*/ T Approach(T value, T objective, T increment); template constexpr T Clamp(T value, T min, T max); - template /*constexpr*/ T CountBits(T value); + template /*constexpr*/ std::size_t CountBits(T value); template constexpr T FromDegrees(T degrees); template constexpr T FromRadians(T radians); template constexpr T DegreeToRadian(T degrees); diff --git a/include/Nazara/Math/Algorithm.inl b/include/Nazara/Math/Algorithm.inl index b61d82916..02ede739a 100644 --- a/include/Nazara/Math/Algorithm.inl +++ b/include/Nazara/Math/Algorithm.inl @@ -147,10 +147,10 @@ namespace Nz template //TODO: Mark as constexpr when supported by all major compilers - /*constexpr*/ inline T CountBits(T value) + /*constexpr*/ inline std::size_t CountBits(T value) { // https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan - unsigned int count = 0; + std::size_t count = 0; while (value) { value &= value - 1; diff --git a/include/Nazara/Math/EulerAngles.inl b/include/Nazara/Math/EulerAngles.inl index 24bfd4630..3b12e7abe 100644 --- a/include/Nazara/Math/EulerAngles.inl +++ b/include/Nazara/Math/EulerAngles.inl @@ -17,11 +17,11 @@ namespace Nz { /*! - * \ingroup math + * \ingroup math * \class Nz::EulerAngles * \brief Math class that represents an Euler angle. Those describe a rotation transformation by rotating an object on its various axes in specified amounts per axis, and a specified axis order * - * \remark Rotation are "left-handed", it means that you take your left hand, put your thumb finger in the direction you want and you other fingers represent the way of rotating + * \remark Rotation are "right-handed", it means that you take your right hand, put your thumb finger in the direction you want and you other fingers represent the way of rotating */ /*! @@ -197,6 +197,7 @@ namespace Nz template Quaternion EulerAngles::ToQuaternion() const { + // XYZ T c1 = std::cos(ToRadians(yaw) / F(2.0)); T c2 = std::cos(ToRadians(roll) / F(2.0)); T c3 = std::cos(ToRadians(pitch) / F(2.0)); diff --git a/include/Nazara/Math/Matrix4.inl b/include/Nazara/Math/Matrix4.inl index 021cb6378..f045ac28a 100644 --- a/include/Nazara/Math/Matrix4.inl +++ b/include/Nazara/Math/Matrix4.inl @@ -792,7 +792,7 @@ namespace Nz template bool Matrix4::IsAffine() const { - return m14 == F(0.0) && m24 == F(0.0) && m34 == F(0.0) && m44 == F(1.0); + return NumberEquals(m14, F(0.0)) && NumberEquals(m24, F(0.0)) && NumberEquals(m34, F(0.0)) && NumberEquals(m44, F(1.0)); } /*! diff --git a/include/Nazara/Math/Quaternion.inl b/include/Nazara/Math/Quaternion.inl index 5c7df28cd..f7f7c693c 100644 --- a/include/Nazara/Math/Quaternion.inl +++ b/include/Nazara/Math/Quaternion.inl @@ -714,10 +714,10 @@ namespace Nz #endif Quaternion interpolated; - interpolated.w = Lerp(from.w, to.w, interpolation); - interpolated.x = Lerp(from.x, to.x, interpolation); - interpolated.y = Lerp(from.y, to.y, interpolation); - interpolated.z = Lerp(from.z, to.z, interpolation); + interpolated.w = Nz::Lerp(from.w, to.w, interpolation); + interpolated.x = Nz::Lerp(from.x, to.x, interpolation); + interpolated.y = Nz::Lerp(from.y, to.y, interpolation); + interpolated.z = Nz::Lerp(from.z, to.z, interpolation); return interpolated; } diff --git a/include/Nazara/Math/Vector3.inl b/include/Nazara/Math/Vector3.inl index 555286024..604cbfb86 100644 --- a/include/Nazara/Math/Vector3.inl +++ b/include/Nazara/Math/Vector3.inl @@ -911,9 +911,9 @@ namespace Nz template bool Vector3::operator<(const Vector3& vec) const { - if (x == vec.x) + if (NumberEquals(x, vec.x)) { - if (y == vec.y) + if (NumberEquals(y, vec.y)) return z < vec.z; else return y < vec.y; @@ -931,10 +931,10 @@ namespace Nz template bool Vector3::operator<=(const Vector3& vec) const { - if (x == vec.x) + if (NumberEquals(x, vec.x)) { - if (y == vec.y) - return z <= vec.z; + if (NumberEquals(y, vec.y)) + return NumberEquals(z, vec.z) || z < vec.z; else return y < vec.y; } @@ -1371,7 +1371,7 @@ namespace std } }; } - + #undef F #include diff --git a/include/Nazara/Math/Vector4.inl b/include/Nazara/Math/Vector4.inl index 190d31b99..f3cad0a31 100644 --- a/include/Nazara/Math/Vector4.inl +++ b/include/Nazara/Math/Vector4.inl @@ -843,11 +843,11 @@ namespace Nz template bool Vector4::operator<(const Vector4& vec) const { - if (x == vec.x) + if (NumberEquals(x, vec.x)) { - if (y == vec.y) + if (NumberEquals(y, vec.y)) { - if (z == vec.z) + if (NumberEquals(z, vec.z)) return w < vec.w; else return z < vec.z; @@ -869,12 +869,12 @@ namespace Nz template bool Vector4::operator<=(const Vector4& vec) const { - if (x == vec.x) + if (NumberEquals(x, vec.x)) { - if (y == vec.y) + if (NumberEquals(y, vec.y)) { - if (z == vec.z) - return w <= vec.w; + if (NumberEquals(z, vec.z)) + return NumberEquals(w, vec.w) || w < vec.w; else return z < vec.z; } @@ -1144,7 +1144,7 @@ namespace std } }; } - + #undef F #include diff --git a/include/Nazara/Network/IpAddress.inl b/include/Nazara/Network/IpAddress.inl index 1eaef4341..ed06b1af7 100644 --- a/include/Nazara/Network/IpAddress.inl +++ b/include/Nazara/Network/IpAddress.inl @@ -380,7 +380,7 @@ namespace std // This is SDBM adapted for IP addresses, tested to generate the least collisions possible // (It doesn't mean it cannot be improved though) - std::size_t hash = 0; + std::size_t h = 0; switch (ip.GetProtocol()) { case Nz::NetProtocol_Any: @@ -389,20 +389,20 @@ namespace std case Nz::NetProtocol_IPv4: { - hash = ip.ToUInt32() + (hash << 6) + (hash << 16) - hash; + h = ip.ToUInt32() + (h << 6) + (h << 16) - h; break; } case Nz::NetProtocol_IPv6: { Nz::IpAddress::IPv6 v6 = ip.ToIPv6(); for (std::size_t i = 0; i < v6.size(); i++) - hash = v6[i] + (hash << 6) + (hash << 16) - hash; + h = v6[i] + (h << 6) + (h << 16) - h; break; } } - return ip.GetPort() + (hash << 6) + (hash << 16) - hash; + return ip.GetPort() + (h << 6) + (h << 16) - h; } }; } diff --git a/include/Nazara/Physics2D/Collider2D.hpp b/include/Nazara/Physics2D/Collider2D.hpp index f8cd7d6af..7bc1c7618 100644 --- a/include/Nazara/Physics2D/Collider2D.hpp +++ b/include/Nazara/Physics2D/Collider2D.hpp @@ -125,6 +125,33 @@ namespace Nz private: std::vector CreateShapes(RigidBody2D* body) const override; }; + + class SegmentCollider2D; + + using SegmentCollider2DConstRef = ObjectRef; + using SegmentCollider2DRef = ObjectRef; + + class NAZARA_PHYSICS2D_API SegmentCollider2D : public Collider2D + { + public: + inline SegmentCollider2D(const Vector2f& first, const Vector2f& second, float thickness = 1.f); + + float ComputeInertialMatrix(float mass) const override; + + inline const Vector2f& GetFirstPoint() const; + inline float GetLength() const; + inline const Vector2f& GetSecondPoint() const; + ColliderType2D GetType() const override; + + template static SegmentCollider2DRef New(Args&&... args); + + private: + std::vector CreateShapes(RigidBody2D* body) const override; + + Vector2f m_first; + Vector2f m_second; + float m_thickness; + }; } #include diff --git a/include/Nazara/Physics2D/Collider2D.inl b/include/Nazara/Physics2D/Collider2D.inl index 2cd44d326..5c3909cde 100644 --- a/include/Nazara/Physics2D/Collider2D.inl +++ b/include/Nazara/Physics2D/Collider2D.inl @@ -49,6 +49,36 @@ namespace Nz return object.release(); } + SegmentCollider2D::SegmentCollider2D(const Vector2f& first, const Vector2f& second, float thickness) : + m_first(first), + m_second(second), + m_thickness(thickness) + { + } + + inline const Vector2f& SegmentCollider2D::GetFirstPoint() const + { + return m_first; + } + + inline float SegmentCollider2D::GetLength() const + { + return m_first.Distance(m_second); + } + + inline const Vector2f& SegmentCollider2D::GetSecondPoint() const + { + return m_second; + } + + template + SegmentCollider2DRef SegmentCollider2D::New(Args&&... args) + { + std::unique_ptr object(new SegmentCollider2D(std::forward(args)...)); + object->SetPersistent(false); + + return object.release(); + } } #include diff --git a/include/Nazara/Physics2D/ConfigCheck.hpp b/include/Nazara/Physics2D/ConfigCheck.hpp index 4689d6e68..3b3b90afc 100644 --- a/include/Nazara/Physics2D/ConfigCheck.hpp +++ b/include/Nazara/Physics2D/ConfigCheck.hpp @@ -10,9 +10,9 @@ /// 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 +#if defined(NAZARA_DEBUG) && !NAZARA_PHYSICS2D_MANAGE_MEMORY + #undef NAZARA_PHYSICS2D_MANAGE_MEMORY + #define NAZARA_PHYSICS2D_MANAGE_MEMORY 0 #endif #endif // NAZARA_CONFIG_CHECK_PHYSICS_HPP diff --git a/include/Nazara/Physics2D/Debug.hpp b/include/Nazara/Physics2D/Debug.hpp index f9cebc624..729491e7c 100644 --- a/include/Nazara/Physics2D/Debug.hpp +++ b/include/Nazara/Physics2D/Debug.hpp @@ -2,7 +2,7 @@ // This file is part of the "Nazara Engine - Physics 2D module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include -#if NAZARA_PHYSICS_MANAGE_MEMORY +#include +#if NAZARA_PHYSICS2D_MANAGE_MEMORY #include #endif diff --git a/include/Nazara/Physics2D/DebugOff.hpp b/include/Nazara/Physics2D/DebugOff.hpp index dd95ffe34..ffbd0a25a 100644 --- a/include/Nazara/Physics2D/DebugOff.hpp +++ b/include/Nazara/Physics2D/DebugOff.hpp @@ -3,7 +3,7 @@ // 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 +#if NAZARA_PHYSICS2D_MANAGE_MEMORY #undef delete #undef new #endif diff --git a/include/Nazara/Physics2D/RigidBody2D.hpp b/include/Nazara/Physics2D/RigidBody2D.hpp index 7d521fbe6..79b7d64bc 100644 --- a/include/Nazara/Physics2D/RigidBody2D.hpp +++ b/include/Nazara/Physics2D/RigidBody2D.hpp @@ -49,6 +49,7 @@ namespace Nz bool IsSleeping() const; void SetAngularVelocity(float angularVelocity); + void SetGeom(Collider2DRef geom); void SetMass(float mass); void SetMassCenter(const Vector2f& center); void SetPosition(const Vector2f& position); @@ -59,8 +60,8 @@ namespace Nz RigidBody2D& operator=(RigidBody2D&& object); private: + void Create(float mass = 1.f, float moment = 1.f); void Destroy(); - void SetGeom(Collider2DRef geom); std::vector m_shapes; Collider2DRef m_geom; diff --git a/include/Nazara/Physics3D/ConfigCheck.hpp b/include/Nazara/Physics3D/ConfigCheck.hpp index 6b1c82073..012cc426c 100644 --- a/include/Nazara/Physics3D/ConfigCheck.hpp +++ b/include/Nazara/Physics3D/ConfigCheck.hpp @@ -10,8 +10,8 @@ /// 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 +#if defined(NAZARA_DEBUG) && !NAZARA_PHYSICS3D_MANAGE_MEMORY + #undef NAZARA_PHYSICS3D_MANAGE_MEMORY #define NAZARA_PHYSICS3D_MANAGE_MEMORY 0 #endif diff --git a/include/Nazara/Physics3D/Debug.hpp b/include/Nazara/Physics3D/Debug.hpp index f70a8b570..ef111fb96 100644 --- a/include/Nazara/Physics3D/Debug.hpp +++ b/include/Nazara/Physics3D/Debug.hpp @@ -3,6 +3,6 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#if NAZARA_PHYSICS_MANAGE_MEMORY +#if NAZARA_PHYSICS3D_MANAGE_MEMORY #include #endif diff --git a/include/Nazara/Physics3D/DebugOff.hpp b/include/Nazara/Physics3D/DebugOff.hpp index 595f0ad94..b8b84c240 100644 --- a/include/Nazara/Physics3D/DebugOff.hpp +++ b/include/Nazara/Physics3D/DebugOff.hpp @@ -3,7 +3,7 @@ // 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 +#if NAZARA_PHYSICS3D_MANAGE_MEMORY #undef delete #undef new #endif diff --git a/include/Nazara/Physics3D/Enums.hpp b/include/Nazara/Physics3D/Enums.hpp index 1b8920cbc..b01c9bb83 100644 --- a/include/Nazara/Physics3D/Enums.hpp +++ b/include/Nazara/Physics3D/Enums.hpp @@ -25,6 +25,6 @@ namespace Nz ColliderType3D_Max = ColliderType3D_Tree }; -}; +} #endif // NAZARA_ENUMS_PHYSICS3D_HPP diff --git a/include/Nazara/Prerequesites.hpp b/include/Nazara/Prerequesites.hpp index bf9d1d75f..dbe478661 100644 --- a/include/Nazara/Prerequesites.hpp +++ b/include/Nazara/Prerequesites.hpp @@ -25,8 +25,7 @@ #ifndef NAZARA_PREREQUESITES_HPP #define NAZARA_PREREQUESITES_HPP -// Identification du compilateur -///TODO: Rajouter des tests d'identification de compilateurs +// Try to identify the compiler #if defined(__BORLANDC__) #define NAZARA_COMPILER_BORDLAND #define NAZARA_COMPILER_SUPPORTS_CPP11 (defined(__cplusplus) && __cplusplus >= 201103L) @@ -63,10 +62,10 @@ #pragma warning(disable: 4251) #else #define NAZARA_COMPILER_UNKNOWN + #define NAZARA_COMPILER_SUPPORTS_CPP11 (defined(__cplusplus) && __cplusplus >= 201103L) #define NAZARA_DEPRECATED(txt) - #define NAZARA_FUNCTION __func__ // __func__ est standard depuis le C++11 + #define NAZARA_FUNCTION __func__ // __func__ has been standardized in C++ 2011 - /// Cette ligne n'est là que pour prévenir, n'hésitez pas à la commenter si elle vous empêche de compiler #pragma message This compiler is not fully supported #endif @@ -76,20 +75,20 @@ // Nazara version macro #define NAZARA_VERSION_MAJOR 0 -#define NAZARA_VERSION_MINOR 1 +#define NAZARA_VERSION_MINOR 2 #define NAZARA_VERSION_PATCH 1 #include -// Identification de la plateforme +// Try to identify target platform via defines #if defined(_WIN32) #define NAZARA_PLATFORM_WINDOWS #define NAZARA_EXPORT __declspec(dllexport) #define NAZARA_IMPORT __declspec(dllimport) - // Des defines pour le header Windows - #if defined(NAZARA_BUILD) // Pour ne pas entrer en conflit avec les defines de l'application ou d'une autre bibliothèque + // Somes defines for windows.h include.. + #if defined(NAZARA_BUILD) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif @@ -99,13 +98,12 @@ #endif #if NAZARA_CORE_WINDOWS_NT6 - // Version de Windows minimale : Vista #define NAZARA_WINNT 0x0600 #else #define NAZARA_WINNT 0x0501 #endif - // Pour ne pas casser le define déjà en place s'il est applicable + // Keep the actual define if existing and greater than our requirement #if defined(_WIN32_WINNT) #if _WIN32_WINNT < NAZARA_WINNT #undef _WIN32_WINNT @@ -128,7 +126,6 @@ #define NAZARA_PLATFORM_MACOSX #define NAZARA_PLATFORM_POSIX*/ #else - // À commenter pour tenter quand même une compilation #error This operating system is not fully supported by the Nazara Engine #define NAZARA_PLATFORM_UNKNOWN @@ -141,12 +138,7 @@ #define NAZARA_PLATFORM_x64 #endif -// Définit NDEBUG si NAZARA_DEBUG n'est pas présent -#if !defined(NAZARA_DEBUG) && !defined(NDEBUG) - #define NDEBUG -#endif - -// Macros supplémentaires +// A bunch of useful macros #define NazaraPrefix(a, prefix) prefix ## a #define NazaraPrefixMacro(a, prefix) NazaraPrefix(a, prefix) #define NazaraSuffix(a, suffix) a ## suffix @@ -155,8 +147,11 @@ #define NazaraStringifyMacro(s) NazaraStringify(s) // http://gcc.gnu.org/onlinedocs/cpp/Stringification.html#Stringification #define NazaraUnused(a) (void) a +#include #include +static_assert(CHAR_BIT == 8, "CHAR_BIT is expected to be 8"); + static_assert(sizeof(int8_t) == 1, "int8_t is not of the correct size" ); static_assert(sizeof(int16_t) == 2, "int16_t is not of the correct size"); static_assert(sizeof(int32_t) == 4, "int32_t is not of the correct size"); @@ -169,17 +164,17 @@ static_assert(sizeof(uint64_t) == 8, "uint64_t is not of the correct size"); namespace Nz { - typedef int8_t Int8; - typedef uint8_t UInt8; + typedef int8_t Int8; + typedef uint8_t UInt8; - typedef int16_t Int16; - typedef uint16_t UInt16; + typedef int16_t Int16; + typedef uint16_t UInt16; - typedef int32_t Int32; - typedef uint32_t UInt32; + typedef int32_t Int32; + typedef uint32_t UInt32; - typedef int64_t Int64; - typedef uint64_t UInt64; + typedef int64_t Int64; + typedef uint64_t UInt64; } #endif // NAZARA_PREREQUESITES_HPP diff --git a/include/Nazara/Utility/Config.hpp b/include/Nazara/Utility/Config.hpp index ee77405be..39aa014af 100644 --- a/include/Nazara/Utility/Config.hpp +++ b/include/Nazara/Utility/Config.hpp @@ -38,9 +38,6 @@ // Lors du parsage d'une ressource, déclenche un avertissement si une erreur non-critique est repérée dans une ressource (Plus lent) #define NAZARA_UTILITY_STRICT_RESOURCE_PARSING 1 -// Fait tourner chaque fenêtre dans un thread séparé si le système le supporte -#define NAZARA_UTILITY_THREADED_WINDOW 0 - // Protège les classes des accès concurrentiels //#define NAZARA_UTILITY_THREADSAFE 1 diff --git a/include/Nazara/Utility/Enums.hpp b/include/Nazara/Utility/Enums.hpp index 3f32945c2..9390b7991 100644 --- a/include/Nazara/Utility/Enums.hpp +++ b/include/Nazara/Utility/Enums.hpp @@ -432,15 +432,17 @@ namespace Nz enum WindowStyleFlags { - WindowStyle_None = 0x0, - WindowStyle_Fullscreen = 0x1, + WindowStyle_None = 0x0, ///< Window has no border nor titlebar. + WindowStyle_Fullscreen = 0x1, ///< At the window creation, the OS tries to set it in fullscreen. - WindowStyle_Closable = 0x2, - WindowStyle_Resizable = 0x4, - WindowStyle_Titlebar = 0x8, + WindowStyle_Closable = 0x2, ///< Allows the window to be closed by a button in the titlebar, generating a Quit event. + WindowStyle_Resizable = 0x4, ///< Allows the window to be resized by dragging its corners or by a button of the titlebar. + WindowStyle_Titlebar = 0x8, ///< Adds a titlebar to the window, this option is automatically enabled if buttons of the titlebar are enabled. + + WindowStyle_Threaded = 0x10, ///< Runs the window into a thread, allowing the application to keep updating while resizing/dragging the window. WindowStyle_Default = WindowStyle_Closable | WindowStyle_Resizable | WindowStyle_Titlebar, - WindowStyle_Max = WindowStyle_Titlebar*2-1 + WindowStyle_Max = WindowStyle_Threaded*2-1 }; } diff --git a/include/Nazara/Utility/EventHandler.hpp b/include/Nazara/Utility/EventHandler.hpp index 2464d5e72..5bc47bdea 100644 --- a/include/Nazara/Utility/EventHandler.hpp +++ b/include/Nazara/Utility/EventHandler.hpp @@ -24,6 +24,9 @@ namespace Nz inline void Dispatch(const WindowEvent& event); + EventHandler& operator=(const EventHandler&) = delete; + EventHandler& operator=(EventHandler&&) = default; + NazaraSignal(OnEvent, const EventHandler* /*eventHandler*/, const WindowEvent& /*event*/); NazaraSignal(OnGainedFocus, const EventHandler* /*eventHandler*/); NazaraSignal(OnLostFocus, const EventHandler* /*eventHandler*/); diff --git a/include/Nazara/Utility/Image.hpp b/include/Nazara/Utility/Image.hpp index 029157885..e1712aed1 100644 --- a/include/Nazara/Utility/Image.hpp +++ b/include/Nazara/Utility/Image.hpp @@ -91,6 +91,8 @@ namespace Nz ImageType GetType() const; unsigned int GetWidth(UInt8 level = 0) const; + bool HasAlpha() const; + bool IsValid() const; // Load diff --git a/include/Nazara/Utility/PixelFormat.inl b/include/Nazara/Utility/PixelFormat.inl index 4d8676916..59ad2ab04 100644 --- a/include/Nazara/Utility/PixelFormat.inl +++ b/include/Nazara/Utility/PixelFormat.inl @@ -39,18 +39,8 @@ namespace Nz } inline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, Bitset<> rMask, Bitset<> gMask, Bitset<> bMask, Bitset<> aMask, PixelFormatSubType subType) : - redMask(rMask), - greenMask(gMask), - blueMask(bMask), - alphaMask(aMask), - content(formatContent), - redType(subType), - greenType(subType), - blueType(subType), - alphaType(subType), - name(formatName) + PixelFormatInfo(formatName, formatContent, subType, rMask, subType, gMask, subType, bMask, subType, aMask) { - RecomputeBitsPerPixel(); } inline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, PixelFormatSubType rType, Bitset<> rMask, PixelFormatSubType gType, Bitset<> gMask, PixelFormatSubType bType, Bitset<> bMask, PixelFormatSubType aType, Bitset<> aMask, UInt8 bpp) : @@ -65,6 +55,11 @@ namespace Nz alphaType(aType), name(formatName) { + redMask.Reverse(); + greenMask.Reverse(); + blueMask.Reverse(); + alphaMask.Reverse(); + if (bpp == 0) RecomputeBitsPerPixel(); } @@ -123,6 +118,9 @@ namespace Nz if (usedBits > bitsPerPixel) return false; + if (usedBits > 64) //< Currently, formats with over 64 bits per component are not supported + return false; + switch (types[i]) { case PixelFormatSubType_Half: diff --git a/include/Nazara/Utility/VideoMode.hpp b/include/Nazara/Utility/VideoMode.hpp index dae9a5410..3c2243817 100644 --- a/include/Nazara/Utility/VideoMode.hpp +++ b/include/Nazara/Utility/VideoMode.hpp @@ -19,6 +19,7 @@ namespace Nz { public: VideoMode(); + VideoMode(unsigned int w, unsigned int h); VideoMode(unsigned int w, unsigned int h, UInt8 bpp); bool IsFullscreenValid() const; diff --git a/include/Nazara/Utility/Window.hpp b/include/Nazara/Utility/Window.hpp index e544093c5..0f7688a81 100644 --- a/include/Nazara/Utility/Window.hpp +++ b/include/Nazara/Utility/Window.hpp @@ -10,6 +10,8 @@ #define NAZARA_WINDOW_HPP #include +#include +#include #include #include #include @@ -19,11 +21,6 @@ #include #include -#if NAZARA_UTILITY_THREADED_WINDOW -#include -#include -#endif - namespace Nz { class Cursor; @@ -114,23 +111,24 @@ namespace Nz private: void IgnoreNextMouseEvent(int mouseX, int mouseY) const; + inline void HandleEvent(const WindowEvent& event); inline void PushEvent(const WindowEvent& event); static bool Initialize(); static void Uninitialize(); std::queue m_events; - #if NAZARA_UTILITY_THREADED_WINDOW + std::vector m_pendingEvents; ConditionVariable m_eventCondition; + EventHandler m_eventHandler; Mutex m_eventMutex; Mutex m_eventConditionMutex; - bool m_waitForEvent; - #endif - EventHandler m_eventHandler; + bool m_asyncWindow; bool m_closed; bool m_closeOnQuit; bool m_eventPolling; bool m_ownsWindow; + bool m_waitForEvent; }; } diff --git a/include/Nazara/Utility/Window.inl b/include/Nazara/Utility/Window.inl index 08b23fc04..cceefebef 100644 --- a/include/Nazara/Utility/Window.inl +++ b/include/Nazara/Utility/Window.inl @@ -4,6 +4,7 @@ #include #include +#include #include namespace Nz @@ -13,11 +14,10 @@ namespace Nz */ inline Window::Window() : m_impl(nullptr), - #if NAZARA_UTILITY_THREADED_WINDOW - m_waitForEvent(false), - #endif + m_asyncWindow(false), m_closeOnQuit(true), - m_eventPolling(false) + m_eventPolling(false), + m_waitForEvent(false) { } @@ -41,16 +41,16 @@ namespace Nz inline Window::Window(Window&& window) noexcept : m_impl(window.m_impl), m_events(std::move(window.m_events)), - #if NAZARA_UTILITY_THREADED_WINDOW + m_pendingEvents(std::move(window.m_pendingEvents)), m_eventCondition(std::move(window.m_eventCondition)), + m_eventHandler(std::move(window.m_eventHandler)), m_eventMutex(std::move(window.m_eventMutex)), m_eventConditionMutex(std::move(window.m_eventConditionMutex)), - m_waitForEvent(window.m_waitForEvent), - #endif m_closed(window.m_closed), m_closeOnQuit(window.m_closeOnQuit), m_eventPolling(window.m_eventPolling), - m_ownsWindow(window.m_ownsWindow) + m_ownsWindow(window.m_ownsWindow), + m_waitForEvent(window.m_waitForEvent) { window.m_impl = nullptr; } @@ -104,12 +104,8 @@ namespace Nz return m_impl != nullptr; } - inline void Window::PushEvent(const WindowEvent& event) + inline void Window::HandleEvent(const WindowEvent& event) { - #if NAZARA_UTILITY_THREADED_WINDOW - m_eventMutex.Lock(); - #endif - if (m_eventPolling) m_events.push(event); @@ -120,17 +116,27 @@ namespace Nz if (event.type == WindowEventType_Quit && m_closeOnQuit) Close(); + } - #if NAZARA_UTILITY_THREADED_WINDOW - m_eventMutex.Unlock(); - - if (m_waitForEvent) + inline void Window::PushEvent(const WindowEvent& event) + { + if (!m_asyncWindow) + HandleEvent(event); + else { - m_eventConditionMutex.Lock(); - m_eventCondition.Signal(); - m_eventConditionMutex.Unlock(); + { + LockGuard eventLock(m_eventMutex); + + m_pendingEvents.push_back(event); + } + + if (m_waitForEvent) + { + m_eventConditionMutex.Lock(); + m_eventCondition.Signal(); + m_eventConditionMutex.Unlock(); + } } - #endif } /*! @@ -141,22 +147,21 @@ namespace Nz { Destroy(); - m_closed = window.m_closed; - m_closeOnQuit = window.m_closeOnQuit; - m_eventPolling = window.m_eventPolling; - m_impl = window.m_impl; - m_events = std::move(window.m_events); - m_ownsWindow = window.m_ownsWindow; + m_closed = window.m_closed; + m_closeOnQuit = window.m_closeOnQuit; + m_eventCondition = std::move(window.m_eventCondition); + m_eventConditionMutex = std::move(window.m_eventConditionMutex); + m_eventHandler = std::move(window.m_eventHandler); + m_eventMutex = std::move(window.m_eventMutex); + m_eventPolling = window.m_eventPolling; + m_impl = window.m_impl; + m_events = std::move(window.m_events); + m_pendingEvents = std::move(window.m_pendingEvents); + m_ownsWindow = window.m_ownsWindow; + m_waitForEvent = window.m_waitForEvent; window.m_impl = nullptr; - #if NAZARA_UTILITY_THREADED_WINDOW - m_eventCondition = std::move(window.m_eventCondition); - m_eventMutex = std::move(window.m_eventMutex); - m_eventConditionMutex = std::move(window.m_eventConditionMutex); - m_waitForEvent = window.m_waitForEvent; - #endif - return *this; } } diff --git a/readme.md b/readme.md index edb58080e..ea054e608 100644 --- a/readme.md +++ b/readme.md @@ -1,7 +1,7 @@ Platform | Build Status ------------ | ------------- Windows | [![AppVeyor Build status](https://ci.appveyor.com/api/projects/status/dj5qx7axym4uakmy/branch/master?svg=true)](https://ci.appveyor.com/project/DPSLynix/nazaraengine/branch/master) -Linux | [![Travis CI Build Status](https://travis-ci.org/DigitalPulseSoftware/NazaraEngine.svg)](https://travis-ci.org/DigitalPulseSoftware/NazaraEngine) +Linux | [![Travis CI Build Status](https://travis-ci.org/DigitalPulseSoftware/NazaraEngine.svg?branch=master)](https://travis-ci.org/DigitalPulseSoftware/NazaraEngine) # Nazara Engine diff --git a/readme_fr.md b/readme_fr.md index d7aff37b9..422be6a0e 100644 --- a/readme_fr.md +++ b/readme_fr.md @@ -1,7 +1,7 @@ Platforme | Build Status ------------ | ------------- Windows | [![AppVeyor Build status](https://ci.appveyor.com/api/projects/status/dj5qx7axym4uakmy/branch/master?svg=true)](https://ci.appveyor.com/project/DPSLynix/nazaraengine/branch/master) -Linux | [![Travis CI Build Status](https://travis-ci.org/DigitalPulseSoftware/NazaraEngine.svg)](https://travis-ci.org/DigitalPulseSoftware/NazaraEngine) +Linux | [![Travis CI Build Status](https://travis-ci.org/DigitalPulseSoftware/NazaraEngine.svg?branch=master)](https://travis-ci.org/DigitalPulseSoftware/NazaraEngine) # Nazara Engine diff --git a/src/Nazara/Core/ByteArray.cpp b/src/Nazara/Core/ByteArray.cpp index e505f13f2..592170e40 100644 --- a/src/Nazara/Core/ByteArray.cpp +++ b/src/Nazara/Core/ByteArray.cpp @@ -15,6 +15,22 @@ namespace Nz * \brief Core class that represents an array of bytes */ + /*! + * \brief Gives a string representation in base 16 + * \return String in base 16 + */ + + String ByteArray::ToHex() const + { + std::size_t length = m_array.size() * 2; + + String hexOutput(length, '\0'); + for (std::size_t i = 0; i < m_array.size(); ++i) + std::sprintf(&hexOutput[i * 2], "%02x", m_array[i]); + + return hexOutput; + } + /*! * \brief Output operator * \return The stream diff --git a/src/Nazara/Core/File.cpp b/src/Nazara/Core/File.cpp index 131ceb7f3..1fd77546f 100644 --- a/src/Nazara/Core/File.cpp +++ b/src/Nazara/Core/File.cpp @@ -906,5 +906,5 @@ namespace Nz } return true; - }; + } } diff --git a/src/Nazara/Graphics/DeferredGeometryPass.cpp b/src/Nazara/Graphics/DeferredGeometryPass.cpp index 79e651926..e95bf250b 100644 --- a/src/Nazara/Graphics/DeferredGeometryPass.cpp +++ b/src/Nazara/Graphics/DeferredGeometryPass.cpp @@ -159,13 +159,13 @@ namespace Nz instanceBuffer->SetVertexDeclaration(VertexDeclaration::Get(VertexLayout_Matrix4)); const Matrix4f* instanceMatrices = &instances[0]; - unsigned int instanceCount = instances.size(); - unsigned int maxInstanceCount = instanceBuffer->GetVertexCount(); // The number of matrices that can be hold in the buffer + std::size_t instanceCount = instances.size(); + std::size_t maxInstanceCount = instanceBuffer->GetVertexCount(); // The number of matrices that can be hold in the buffer while (instanceCount > 0) { // We compute the number of instances that we will be able to show this time (Depending on the instance buffer size) - unsigned int renderedInstanceCount = std::min(instanceCount, maxInstanceCount); + std::size_t renderedInstanceCount = std::min(instanceCount, maxInstanceCount); instanceCount -= renderedInstanceCount; // We fill the instancing buffer with our world matrices diff --git a/src/Nazara/Graphics/DepthRenderTechnique.cpp b/src/Nazara/Graphics/DepthRenderTechnique.cpp index bcae2eb57..60d344fb7 100644 --- a/src/Nazara/Graphics/DepthRenderTechnique.cpp +++ b/src/Nazara/Graphics/DepthRenderTechnique.cpp @@ -267,13 +267,13 @@ namespace Nz const Texture* overlay = overlayIt.first; auto& spriteChainVector = overlayIt.second.spriteChains; - unsigned int spriteChainCount = spriteChainVector.size(); + std::size_t spriteChainCount = spriteChainVector.size(); if (spriteChainCount > 0) { Renderer::SetTexture(overlayUnit, (overlay) ? overlay : &m_whiteTexture); - unsigned int spriteChain = 0; // Which chain of sprites are we treating - unsigned int spriteChainOffset = 0; // Where was the last offset where we stopped in the last chain + std::size_t spriteChain = 0; // Which chain of sprites are we treating + std::size_t spriteChainOffset = 0; // Where was the last offset where we stopped in the last chain do { @@ -281,13 +281,13 @@ namespace Nz BufferMapper vertexMapper(m_spriteBuffer, BufferAccess_DiscardAndWrite); VertexStruct_XYZ_Color_UV* vertices = static_cast(vertexMapper.GetPointer()); - unsigned int spriteCount = 0; - unsigned int maxSpriteCount = std::min(s_maxQuads, m_spriteBuffer.GetVertexCount() / 4); + std::size_t spriteCount = 0; + std::size_t maxSpriteCount = std::min(s_maxQuads, m_spriteBuffer.GetVertexCount() / 4); do { ForwardRenderQueue::SpriteChain_XYZ_Color_UV& currentChain = spriteChainVector[spriteChain]; - unsigned int count = std::min(maxSpriteCount - spriteCount, currentChain.spriteCount - spriteChainOffset); + std::size_t count = std::min(maxSpriteCount - spriteCount, currentChain.spriteCount - spriteChainOffset); std::memcpy(vertices, currentChain.vertices + spriteChainOffset * 4, 4 * count * sizeof(VertexStruct_XYZ_Color_UV)); vertices += count * 4; @@ -373,17 +373,17 @@ namespace Nz auto& entry = matIt.second; auto& billboardVector = entry.billboards; - unsigned int billboardCount = billboardVector.size(); + std::size_t billboardCount = billboardVector.size(); if (billboardCount > 0) { // We begin to apply the material (and get the shader activated doing so) material->Apply(pipelineInstance); const ForwardRenderQueue::BillboardData* data = &billboardVector[0]; - unsigned int maxBillboardPerDraw = instanceBuffer->GetVertexCount(); + std::size_t maxBillboardPerDraw = instanceBuffer->GetVertexCount(); do { - unsigned int renderedBillboardCount = std::min(billboardCount, maxBillboardPerDraw); + std::size_t renderedBillboardCount = std::min(billboardCount, maxBillboardPerDraw); billboardCount -= renderedBillboardCount; instanceBuffer->Fill(data, 0, renderedBillboardCount, true); @@ -435,12 +435,12 @@ namespace Nz auto& billboardVector = entry.billboards; const ForwardRenderQueue::BillboardData* data = &billboardVector[0]; - unsigned int maxBillboardPerDraw = std::min(s_maxQuads, m_billboardPointBuffer.GetVertexCount() / 4); + std::size_t maxBillboardPerDraw = std::min(s_maxQuads, m_billboardPointBuffer.GetVertexCount() / 4); - unsigned int billboardCount = billboardVector.size(); + std::size_t billboardCount = billboardVector.size(); do { - unsigned int renderedBillboardCount = std::min(billboardCount, maxBillboardPerDraw); + std::size_t renderedBillboardCount = std::min(billboardCount, maxBillboardPerDraw); billboardCount -= renderedBillboardCount; BufferMapper vertexMapper(m_billboardPointBuffer, BufferAccess_DiscardAndWrite, 0, renderedBillboardCount * 4); @@ -584,13 +584,13 @@ namespace Nz instanceBuffer->SetVertexDeclaration(VertexDeclaration::Get(VertexLayout_Matrix4)); const Matrix4f* instanceMatrices = &instances[0]; - unsigned int instanceCount = instances.size(); - unsigned int maxInstanceCount = instanceBuffer->GetVertexCount(); // Maximum number of instance in one batch + std::size_t instanceCount = instances.size(); + std::size_t maxInstanceCount = instanceBuffer->GetVertexCount(); // Maximum number of instance in one batch while (instanceCount > 0) { // We compute the number of instances that we will be able to draw this time (depending on the instancing buffer size) - unsigned int renderedInstanceCount = std::min(instanceCount, maxInstanceCount); + std::size_t renderedInstanceCount = std::min(instanceCount, maxInstanceCount); instanceCount -= renderedInstanceCount; // We fill the instancing buffer with our world matrices diff --git a/src/Nazara/Graphics/ForwardRenderQueue.cpp b/src/Nazara/Graphics/ForwardRenderQueue.cpp index b74ffa732..97c3a53d5 100644 --- a/src/Nazara/Graphics/ForwardRenderQueue.cpp +++ b/src/Nazara/Graphics/ForwardRenderQueue.cpp @@ -383,7 +383,7 @@ namespace Nz auto& transparentModelData = currentLayer.transparentModelData; // The material is transparent, we must draw this mesh using another way (after the rendering of opages objects while sorting them) - unsigned int index = transparentModelData.size(); + std::size_t index = transparentModelData.size(); transparentModelData.resize(index+1); TransparentModelData& data = transparentModelData.back(); @@ -603,7 +603,7 @@ namespace Nz { Layer& layer = pair.second; - std::sort(layer.transparentModels.begin(), layer.transparentModels.end(), [&layer, &nearPlane, &viewerNormal] (unsigned int index1, unsigned int index2) + std::sort(layer.transparentModels.begin(), layer.transparentModels.end(), [&layer, &nearPlane, &viewerNormal] (std::size_t index1, std::size_t index2) { const Spheref& sphere1 = layer.transparentModelData[index1].squaredBoundingSphere; const Spheref& sphere2 = layer.transparentModelData[index2].squaredBoundingSphere; @@ -672,7 +672,7 @@ namespace Nz BatchedBillboardEntry& entry = it->second; auto& billboardVector = entry.billboards; - unsigned int prevSize = billboardVector.size(); + std::size_t prevSize = billboardVector.size(); billboardVector.resize(prevSize + count); return &billboardVector[prevSize]; diff --git a/src/Nazara/Graphics/ForwardRenderTechnique.cpp b/src/Nazara/Graphics/ForwardRenderTechnique.cpp index 699ae416a..7792a93b2 100644 --- a/src/Nazara/Graphics/ForwardRenderTechnique.cpp +++ b/src/Nazara/Graphics/ForwardRenderTechnique.cpp @@ -33,8 +33,8 @@ namespace Nz Vector2f uv; }; - unsigned int s_maxQuads = std::numeric_limits::max() / 6; - unsigned int s_vertexBufferSize = 4 * 1024 * 1024; // 4 MiB + std::size_t s_maxQuads = std::numeric_limits::max() / 6; + std::size_t s_vertexBufferSize = 4 * 1024 * 1024; // 4 MiB } /*! @@ -347,13 +347,13 @@ namespace Nz const Texture* overlay = overlayIt.first; auto& spriteChainVector = overlayIt.second.spriteChains; - unsigned int spriteChainCount = spriteChainVector.size(); + std::size_t spriteChainCount = spriteChainVector.size(); if (spriteChainCount > 0) { Renderer::SetTexture(overlayUnit, (overlay) ? overlay : &m_whiteTexture); - unsigned int spriteChain = 0; // Which chain of sprites are we treating - unsigned int spriteChainOffset = 0; // Where was the last offset where we stopped in the last chain + std::size_t spriteChain = 0; // Which chain of sprites are we treating + std::size_t spriteChainOffset = 0; // Where was the last offset where we stopped in the last chain do { @@ -361,13 +361,13 @@ namespace Nz BufferMapper vertexMapper(m_spriteBuffer, BufferAccess_DiscardAndWrite); VertexStruct_XYZ_Color_UV* vertices = static_cast(vertexMapper.GetPointer()); - unsigned int spriteCount = 0; - unsigned int maxSpriteCount = std::min(s_maxQuads, m_spriteBuffer.GetVertexCount() / 4); + std::size_t spriteCount = 0; + std::size_t maxSpriteCount = std::min(s_maxQuads, m_spriteBuffer.GetVertexCount() / 4); do { ForwardRenderQueue::SpriteChain_XYZ_Color_UV& currentChain = spriteChainVector[spriteChain]; - unsigned int count = std::min(maxSpriteCount - spriteCount, currentChain.spriteCount - spriteChainOffset); + std::size_t count = std::min(maxSpriteCount - spriteCount, currentChain.spriteCount - spriteChainOffset); std::memcpy(vertices, currentChain.vertices + spriteChainOffset * 4, 4 * count * sizeof(VertexStruct_XYZ_Color_UV)); vertices += count * 4; @@ -450,17 +450,17 @@ namespace Nz auto& entry = matIt.second; auto& billboardVector = entry.billboards; - unsigned int billboardCount = billboardVector.size(); + std::size_t billboardCount = billboardVector.size(); if (billboardCount > 0) { // We begin to apply the material (and get the shader activated doing so) material->Apply(pipelineInstance); const ForwardRenderQueue::BillboardData* data = &billboardVector[0]; - unsigned int maxBillboardPerDraw = instanceBuffer->GetVertexCount(); + std::size_t maxBillboardPerDraw = instanceBuffer->GetVertexCount(); do { - unsigned int renderedBillboardCount = std::min(billboardCount, maxBillboardPerDraw); + std::size_t renderedBillboardCount = std::min(billboardCount, maxBillboardPerDraw); billboardCount -= renderedBillboardCount; instanceBuffer->Fill(data, 0, renderedBillboardCount, true); @@ -512,12 +512,12 @@ namespace Nz auto& billboardVector = entry.billboards; const ForwardRenderQueue::BillboardData* data = &billboardVector[0]; - unsigned int maxBillboardPerDraw = std::min(s_maxQuads, m_billboardPointBuffer.GetVertexCount() / 4); + std::size_t maxBillboardPerDraw = std::min(s_maxQuads, m_billboardPointBuffer.GetVertexCount() / 4); - unsigned int billboardCount = billboardVector.size(); + std::size_t billboardCount = billboardVector.size(); do { - unsigned int renderedBillboardCount = std::min(billboardCount, maxBillboardPerDraw); + std::size_t renderedBillboardCount = std::min(billboardCount, maxBillboardPerDraw); billboardCount -= renderedBillboardCount; BufferMapper vertexMapper(m_billboardPointBuffer, BufferAccess_DiscardAndWrite, 0, renderedBillboardCount * 4); @@ -666,16 +666,16 @@ namespace Nz // With instancing, impossible to select the lights for each object // So, it's only activated for directional lights - unsigned int lightCount = m_renderQueue.directionalLights.size(); - unsigned int lightIndex = 0; + std::size_t lightCount = m_renderQueue.directionalLights.size(); + std::size_t lightIndex = 0; RendererComparison oldDepthFunc = Renderer::GetDepthFunc(); - unsigned int passCount = (lightCount == 0) ? 1 : (lightCount - 1) / NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS + 1; - for (unsigned int pass = 0; pass < passCount; ++pass) + std::size_t passCount = (lightCount == 0) ? 1 : (lightCount - 1) / NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS + 1; + for (std::size_t pass = 0; pass < passCount; ++pass) { if (shaderUniforms->hasLightUniforms) { - unsigned int renderedLightCount = std::min(lightCount, NazaraSuffixMacro(NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS, U)); + std::size_t renderedLightCount = std::min(lightCount, NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS); lightCount -= renderedLightCount; if (pass == 1) @@ -690,18 +690,18 @@ namespace Nz } // Sends the uniforms - for (unsigned int i = 0; i < NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS; ++i) + for (std::size_t i = 0; i < NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS; ++i) SendLightUniforms(shader, shaderUniforms->lightUniforms, lightIndex++, shaderUniforms->lightOffset * i, freeTextureUnit + i); } const Matrix4f* instanceMatrices = &instances[0]; - unsigned int instanceCount = instances.size(); - unsigned int maxInstanceCount = instanceBuffer->GetVertexCount(); // Maximum number of instance in one batch + std::size_t instanceCount = instances.size(); + std::size_t maxInstanceCount = instanceBuffer->GetVertexCount(); // Maximum number of instance in one batch while (instanceCount > 0) { // We compute the number of instances that we will be able to draw this time (depending on the instancing buffer size) - unsigned int renderedInstanceCount = std::min(instanceCount, maxInstanceCount); + std::size_t renderedInstanceCount = std::min(instanceCount, maxInstanceCount); instanceCount -= renderedInstanceCount; // We fill the instancing buffer with our world matrices @@ -726,16 +726,16 @@ namespace Nz // Choose the lights depending on an object position and apparent radius ChooseLights(Spheref(matrix.GetTranslation() + squaredBoundingSphere.GetPosition(), squaredBoundingSphere.radius)); - unsigned int lightCount = m_lights.size(); + std::size_t lightCount = m_lights.size(); Renderer::SetMatrix(MatrixType_World, matrix); - unsigned int lightIndex = 0; + std::size_t lightIndex = 0; RendererComparison oldDepthFunc = Renderer::GetDepthFunc(); // In the case where we have to change it - unsigned int passCount = (lightCount == 0) ? 1 : (lightCount - 1) / NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS + 1; - for (unsigned int pass = 0; pass < passCount; ++pass) + std::size_t passCount = (lightCount == 0) ? 1 : (lightCount - 1) / NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS + 1; + for (std::size_t pass = 0; pass < passCount; ++pass) { - lightCount -= std::min(lightCount, NazaraSuffixMacro(NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS, U)); + lightCount -= std::min(lightCount, NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS); if (pass == 1) { @@ -749,7 +749,7 @@ namespace Nz } // Sends the light uniforms to the shader - for (unsigned int i = 0; i < NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS; ++i) + for (std::size_t i = 0; i < NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS; ++i) SendLightUniforms(shader, shaderUniforms->lightUniforms, lightIndex++, shaderUniforms->lightOffset*i, freeTextureUnit + i); // And we draw @@ -835,7 +835,7 @@ namespace Nz { lightCount = std::min(m_renderQueue.directionalLights.size(), static_cast(NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS)); - for (unsigned int i = 0; i < lightCount; ++i) + for (std::size_t i = 0; i < lightCount; ++i) SendLightUniforms(shader, shaderUniforms->lightUniforms, i, shaderUniforms->lightOffset * i, freeTextureUnit++); } @@ -874,7 +874,7 @@ namespace Nz float radius = modelData.squaredBoundingSphere.radius; ChooseLights(Spheref(position, radius), false); - for (unsigned int i = lightCount; i < NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS; ++i) + for (std::size_t i = lightCount; i < NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS; ++i) SendLightUniforms(shader, shaderUniforms->lightUniforms, i, shaderUniforms->lightOffset*i, freeTextureUnit++); } diff --git a/src/Nazara/Graphics/InstancedRenderable.cpp b/src/Nazara/Graphics/InstancedRenderable.cpp index ef5f62b96..e927e2d22 100644 --- a/src/Nazara/Graphics/InstancedRenderable.cpp +++ b/src/Nazara/Graphics/InstancedRenderable.cpp @@ -94,6 +94,7 @@ namespace Nz void InstancedRenderable::UpdateData(InstanceData* instanceData) const { NazaraAssert(instanceData, "Invalid instance data"); + NazaraUnused(instanceData); } InstancedRenderableLibrary::LibraryMap InstancedRenderable::s_library; diff --git a/src/Nazara/Graphics/ParticleDeclaration.cpp b/src/Nazara/Graphics/ParticleDeclaration.cpp index ebd84e95d..60786c1f1 100644 --- a/src/Nazara/Graphics/ParticleDeclaration.cpp +++ b/src/Nazara/Graphics/ParticleDeclaration.cpp @@ -100,7 +100,7 @@ namespace Nz * \remark Produces a NazaraError with NAZARA_GRAPHICS_SAFE defined if type is not supported */ - void ParticleDeclaration::EnableComponent(ParticleComponent component, ComponentType type, unsigned int offset) + void ParticleDeclaration::EnableComponent(ParticleComponent component, ComponentType type, std::size_t offset) { #ifdef NAZARA_DEBUG if (component > ParticleComponent_Max) @@ -145,7 +145,7 @@ namespace Nz * \remark Produces a NazaraError with NAZARA_GRAPHICS_SAFE defined if enumeration is equal to ParticleComponent_Unused */ - void ParticleDeclaration::GetComponent(ParticleComponent component, bool* enabled, ComponentType* type, unsigned int* offset) const + void ParticleDeclaration::GetComponent(ParticleComponent component, bool* enabled, ComponentType* type, std::size_t* offset) const { #ifdef NAZARA_DEBUG if (component > ParticleComponent_Max) @@ -180,7 +180,7 @@ namespace Nz * \return Stride of the declaration */ - unsigned int ParticleDeclaration::GetStride() const + std::size_t ParticleDeclaration::GetStride() const { return m_stride; } diff --git a/src/Nazara/Graphics/ParticleEmitter.cpp b/src/Nazara/Graphics/ParticleEmitter.cpp index fe27575e7..038e69ce9 100644 --- a/src/Nazara/Graphics/ParticleEmitter.cpp +++ b/src/Nazara/Graphics/ParticleEmitter.cpp @@ -74,11 +74,11 @@ namespace Nz if (emissionCount >= 1.f) { // We compute the maximum number of particles which can be emitted - unsigned int emissionCountInt = static_cast(emissionCount); - unsigned int maxParticleCount = emissionCountInt * m_emissionCount; + std::size_t emissionCountInt = static_cast(emissionCount); + std::size_t maxParticleCount = emissionCountInt * m_emissionCount; // We get the number of particles that we are able to create (depending on the free space) - unsigned int particleCount = std::min(maxParticleCount, system.GetMaxParticleCount() - system.GetParticleCount()); + std::size_t particleCount = std::min(maxParticleCount, system.GetMaxParticleCount() - system.GetParticleCount()); if (particleCount == 0) return; @@ -115,7 +115,7 @@ namespace Nz * \return Current emission count */ - unsigned int ParticleEmitter::GetEmissionCount() const + std::size_t ParticleEmitter::GetEmissionCount() const { return m_emissionCount; } @@ -146,7 +146,7 @@ namespace Nz * \param count Emission count */ - void ParticleEmitter::SetEmissionCount(unsigned int count) + void ParticleEmitter::SetEmissionCount(std::size_t count) { m_emissionCount = count; } diff --git a/src/Nazara/Graphics/ParticleGroup.cpp b/src/Nazara/Graphics/ParticleGroup.cpp index 5aca6c2b4..f2c46d91c 100644 --- a/src/Nazara/Graphics/ParticleGroup.cpp +++ b/src/Nazara/Graphics/ParticleGroup.cpp @@ -142,11 +142,10 @@ namespace Nz * \remark Produces a NazaraAssert if renderQueue is invalid */ - void ParticleGroup::AddToRenderQueue(AbstractRenderQueue* renderQueue, const Matrix4f& transformMatrix) const + void ParticleGroup::AddToRenderQueue(AbstractRenderQueue* renderQueue, const Matrix4f& /*transformMatrix*/) const { NazaraAssert(m_renderer, "Invalid particle renderer"); NazaraAssert(renderQueue, "Invalid renderqueue"); - NazaraUnused(transformMatrix); if (m_particleCount > 0) { @@ -215,7 +214,7 @@ namespace Nz if (m_particleCount + count > m_maxParticleCount) return nullptr; - unsigned int particlesIndex = m_particleCount; + std::size_t particlesIndex = m_particleCount; m_particleCount += count; return &m_buffer[particlesIndex * m_particleSize]; @@ -264,7 +263,7 @@ namespace Nz * \return Current maximum number */ - unsigned int ParticleGroup::GetMaxParticleCount() const + std::size_t ParticleGroup::GetMaxParticleCount() const { return m_maxParticleCount; } @@ -274,7 +273,7 @@ namespace Nz * \return Current number */ - unsigned int ParticleGroup::GetParticleCount() const + std::size_t ParticleGroup::GetParticleCount() const { return m_particleCount; } @@ -284,7 +283,7 @@ namespace Nz * \return Current size */ - unsigned int ParticleGroup::GetParticleSize() const + std::size_t ParticleGroup::GetParticleSize() const { return m_particleSize; } @@ -295,7 +294,7 @@ namespace Nz * \param index Index of the particle */ - void ParticleGroup::KillParticle(unsigned int index) + void ParticleGroup::KillParticle(std::size_t index) { ///FIXME: Verify the index @@ -402,10 +401,8 @@ namespace Nz * \param transformMatrix Matrix transformation for our bounding volume */ - void ParticleGroup::UpdateBoundingVolume(const Matrix4f& transformMatrix) + void ParticleGroup::UpdateBoundingVolume(const Matrix4f& /*transformMatrix*/) { - NazaraUnused(transformMatrix); - // Nothing to do here (our bounding volume is global) } diff --git a/src/Nazara/Graphics/RenderTechniques.cpp b/src/Nazara/Graphics/RenderTechniques.cpp index 46d84d9c4..8298245b7 100644 --- a/src/Nazara/Graphics/RenderTechniques.cpp +++ b/src/Nazara/Graphics/RenderTechniques.cpp @@ -170,7 +170,7 @@ namespace Nz * \return Number of techniques */ - unsigned int RenderTechniques::GetCount() + std::size_t RenderTechniques::GetCount() { return s_renderTechniques.size(); } diff --git a/src/Nazara/Graphics/Sprite.cpp b/src/Nazara/Graphics/Sprite.cpp index 1b14ab6de..d23fe4122 100644 --- a/src/Nazara/Graphics/Sprite.cpp +++ b/src/Nazara/Graphics/Sprite.cpp @@ -44,6 +44,64 @@ namespace Nz m_boundingVolume.Set(-origin, m_size.x*Vector3f::Right() + m_size.y*Vector3f::Down() - origin); } + /*! + * \brief Sets the material of the sprite from a name + * + * Tries to get a material from the MaterialLibrary and then the MaterialManager (which will treat the name as a path) + * Fails if the texture name is not a part of the MaterialLibrary nor the MaterialManager (which fails if it couldn't load the texture from its filepath) + * + * \param materialName Named texture for the material + * \param resizeSprite Should the sprite be resized to the material diffuse map size? + * + * \return True if the material was found or loaded from its name/path, false if it couldn't + */ + bool Sprite::SetMaterial(String materialName, bool resizeSprite) + { + MaterialRef material = MaterialLibrary::Query(materialName); + if (!material) + { + material = MaterialManager::Get(materialName); + if (!material) + { + NazaraError("Failed to get material \"" + materialName + "\""); + return false; + } + } + + SetMaterial(std::move(material), resizeSprite); + return true; + } + + /*! + * \brief Sets the texture of the sprite from a name + * + * Tries to get a texture from the TextureLibrary and then the TextureManager (which will treat the name as a path) + * Fails if the texture name is not a part of the TextureLibrary nor the TextureManager (which fails if it couldn't load the texture from its filepath) + * + * \param textureName Named texture for the sprite + * \param resizeSprite Should the sprite be resized to the texture size? + * + * \return True if the texture was found or loaded from its name/path, false if it couldn't + * + * \remark The sprite material gets copied to prevent accidentally changing other drawable materials + */ + bool Sprite::SetTexture(String textureName, bool resizeSprite) + { + TextureRef texture = TextureLibrary::Query(textureName); + if (!texture) + { + texture = TextureManager::Get(textureName); + if (!texture) + { + NazaraError("Failed to get texture \"" + textureName + "\""); + return false; + } + } + + SetTexture(std::move(texture), resizeSprite); + return true; + } + /*! * \brief Updates the data of the sprite * diff --git a/src/Nazara/Network/NetPacket.cpp b/src/Nazara/Network/NetPacket.cpp index 0823f5258..dcac9e178 100644 --- a/src/Nazara/Network/NetPacket.cpp +++ b/src/Nazara/Network/NetPacket.cpp @@ -146,7 +146,7 @@ namespace Nz if (!m_buffer) m_buffer = std::make_unique(); - m_buffer->Resize(static_cast(cursorPos)); + m_buffer->Resize(minCapacity); m_memoryStream.SetBuffer(m_buffer.get(), openMode); m_memoryStream.SetCursorPos(cursorPos); diff --git a/src/Nazara/Network/TcpClient.cpp b/src/Nazara/Network/TcpClient.cpp index 1c84dc498..2be3d44cf 100644 --- a/src/Nazara/Network/TcpClient.cpp +++ b/src/Nazara/Network/TcpClient.cpp @@ -385,7 +385,7 @@ namespace Nz * \remark Produces a NazaraError because it is a special stream */ - bool TcpClient::SetCursorPos(UInt64 offset) + bool TcpClient::SetCursorPos(UInt64 /*offset*/) { NazaraError("SetCursorPos() cannot be used on sequential streams"); return false; diff --git a/src/Nazara/Network/Win32/SocketImpl.cpp b/src/Nazara/Network/Win32/SocketImpl.cpp index 628d29807..5a02b4bae 100644 --- a/src/Nazara/Network/Win32/SocketImpl.cpp +++ b/src/Nazara/Network/Win32/SocketImpl.cpp @@ -437,6 +437,10 @@ namespace Nz return result; #else + NazaraUnused(fdarray); + NazaraUnused(nfds); + NazaraUnused(timeout); + if (error) *error = SocketError_NotSupported; diff --git a/src/Nazara/Physics2D/Collider2D.cpp b/src/Nazara/Physics2D/Collider2D.cpp index a840393e8..986a03ccf 100644 --- a/src/Nazara/Physics2D/Collider2D.cpp +++ b/src/Nazara/Physics2D/Collider2D.cpp @@ -10,7 +10,7 @@ namespace Nz { Collider2D::~Collider2D() = default; - + /******************************** BoxCollider2D *********************************/ BoxCollider2D::BoxCollider2D(const Vector2f& size, float radius) : @@ -84,4 +84,25 @@ namespace Nz { return std::vector(); } + + /******************************** SegmentCollider2D *********************************/ + + float SegmentCollider2D::ComputeInertialMatrix(float mass) const + { + return static_cast(cpMomentForSegment(mass, cpv(m_first.x, m_first.y), cpv(m_second.x, m_second.y), m_thickness)); + } + + ColliderType2D SegmentCollider2D::GetType() const + { + return ColliderType2D_Segment; + } + + std::vector SegmentCollider2D::CreateShapes(RigidBody2D* body) const + { + std::vector shapes; + shapes.push_back(cpSegmentShapeNew(body->GetHandle(), cpv(m_first.x, m_first.y), cpv(m_second.x, m_second.y), m_thickness)); + + return shapes; + } + } diff --git a/src/Nazara/Physics2D/Debug/NewOverload.cpp b/src/Nazara/Physics2D/Debug/NewOverload.cpp index bd3153d1d..0c82acc94 100644 --- a/src/Nazara/Physics2D/Debug/NewOverload.cpp +++ b/src/Nazara/Physics2D/Debug/NewOverload.cpp @@ -2,8 +2,8 @@ // This file is part of the "Nazara Engine - Physics 2D module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include -#if NAZARA_PHYSICS_MANAGE_MEMORY +#include +#if NAZARA_PHYSICS2D_MANAGE_MEMORY #include #include // Nécessaire ? diff --git a/src/Nazara/Physics2D/PhysWorld2D.cpp b/src/Nazara/Physics2D/PhysWorld2D.cpp index 5290abfcd..878a84400 100644 --- a/src/Nazara/Physics2D/PhysWorld2D.cpp +++ b/src/Nazara/Physics2D/PhysWorld2D.cpp @@ -24,7 +24,7 @@ namespace Nz Vector2f PhysWorld2D::GetGravity() const { cpVect gravity = cpSpaceGetGravity(m_handle); - return Vector2f(gravity.x, gravity.y); + return Vector2f(Vector2(gravity.x, gravity.y)); } cpSpace* PhysWorld2D::GetHandle() const diff --git a/src/Nazara/Physics2D/RigidBody2D.cpp b/src/Nazara/Physics2D/RigidBody2D.cpp index faa6223d1..9fdb34d50 100644 --- a/src/Nazara/Physics2D/RigidBody2D.cpp +++ b/src/Nazara/Physics2D/RigidBody2D.cpp @@ -22,13 +22,11 @@ namespace Nz m_geom(), m_world(world), m_gravityFactor(1.f), - m_mass(0.f) + m_mass(1.f) { NazaraAssert(m_world, "Invalid world"); - m_handle = cpBodyNew(0.f, 0.f); - cpBodySetUserData(m_handle, this); - cpSpaceAddBody(m_world->GetHandle(), m_handle); + Create(); SetGeom(geom); SetMass(mass); @@ -43,9 +41,7 @@ namespace Nz 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); + Create(); SetGeom(object.GetGeom()); SetMass(object.GetMass()); @@ -77,7 +73,7 @@ namespace Nz switch (coordSys) { case CoordSys_Global: - cpBodyApplyForceAtWorldPoint(m_handle, cpv(force.x, force.y), cpv(force.x, force.y)); + cpBodyApplyForceAtWorldPoint(m_handle, cpv(force.x, force.y), cpv(point.x, point.y)); break; case CoordSys_Local: @@ -169,19 +165,60 @@ namespace Nz cpBodySetAngularVelocity(m_handle, angularVelocity); } + void RigidBody2D::SetGeom(Collider2DRef geom) + { + // We have no public way of getting rid of an existing geom without removing the whole body + // So let's save some attributes of the body, destroy it and rebuild it + if (m_geom) + { + cpVect pos = cpBodyGetPosition(m_handle); + cpFloat mass = cpBodyGetMass(m_handle); + cpFloat moment = cpBodyGetMoment(m_handle); + cpFloat rot = cpBodyGetAngle(m_handle); + cpVect vel = cpBodyGetVelocity(m_handle); + + Destroy(); + Create(mass, moment); + + cpBodySetAngle(m_handle, rot); + cpBodySetPosition(m_handle, pos); + cpBodySetVelocity(m_handle, vel); + } + + if (geom) + m_geom = geom; + else + m_geom = NullCollider2D::New(); + + m_shapes = m_geom->CreateShapes(this); + + cpSpace* space = m_world->GetHandle(); + for (cpShape* shape : m_shapes) + cpSpaceAddShape(space, shape); + + cpBodySetMoment(m_handle, m_geom->ComputeInertialMatrix(m_mass)); + } + void RigidBody2D::SetMass(float mass) { if (m_mass > 0.f) { if (mass > 0.f) + { cpBodySetMass(m_handle, mass); + cpBodySetMoment(m_handle, m_geom->ComputeInertialMatrix(m_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); + cpBodySetMass(m_handle, mass); + cpBodySetMoment(m_handle, m_geom->ComputeInertialMatrix(m_mass)); + } } m_mass = mass; @@ -196,6 +233,8 @@ namespace Nz void RigidBody2D::SetPosition(const Vector2f& position) { cpBodySetPosition(m_handle, cpv(position.x, position.y)); + if (cpBodyGetType(m_handle) == CP_BODY_TYPE_STATIC) + cpSpaceReindexShapesForBody(m_world->GetHandle(), m_handle); } void RigidBody2D::SetRotation(float rotation) @@ -230,22 +269,26 @@ namespace Nz return *this; } + void RigidBody2D::Create(float mass, float moment) + { + m_handle = cpBodyNew(mass, moment); + cpBodySetUserData(m_handle, this); + cpSpaceAddBody(m_world->GetHandle(), m_handle); + } + void RigidBody2D::Destroy() { + cpSpace* space = m_world->GetHandle(); for (cpShape* shape : m_shapes) + { + cpSpaceRemoveShape(space, shape); cpShapeFree(shape); + } if (m_handle) + { + cpSpaceRemoveBody(space, 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/Debug/NewOverload.cpp b/src/Nazara/Physics3D/Debug/NewOverload.cpp index 18092514c..b87984066 100644 --- a/src/Nazara/Physics3D/Debug/NewOverload.cpp +++ b/src/Nazara/Physics3D/Debug/NewOverload.cpp @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#if NAZARA_PHYSICS_MANAGE_MEMORY +#if NAZARA_PHYSICS3D_MANAGE_MEMORY #include #include // Nécessaire ? diff --git a/src/Nazara/Renderer/RenderTexture.cpp b/src/Nazara/Renderer/RenderTexture.cpp new file mode 100644 index 000000000..d90ba5f1a --- /dev/null +++ b/src/Nazara/Renderer/RenderTexture.cpp @@ -0,0 +1,855 @@ +// Copyright (C) 2015 Jérôme Leclercq +// This file is part of the "Nazara Engine - Renderer 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 +#include +#include + +namespace Nz +{ + namespace + { + struct Attachment + { + NazaraSlot(RenderBuffer, OnRenderBufferDestroy, renderBufferDestroySlot); + NazaraSlot(Texture, OnTextureDestroy, textureDestroySlot); + + RenderBufferRef buffer; + TextureRef texture; + + AttachmentPoint attachmentPoint; + bool isBuffer; + bool isUsed = false; + unsigned int height; + unsigned int width; + }; + + unsigned int attachmentIndex[AttachmentPoint_Max+1] = + { + 3, // AttachmentPoint_Color + 0, // AttachmentPoint_Depth + 1, // AttachmentPoint_DepthStencil + 2 // AttachmentPoint_Stencil + }; + + AttachmentPoint FormatTypeToAttachment(PixelFormatType format) + { + const PixelFormatInfo& info = PixelFormat::GetInfo(format); + switch (info.content) + { + case PixelFormatContent_ColorRGBA: + return AttachmentPoint_Color; + + case PixelFormatContent_DepthStencil: + return (!info.greenMask.TestAny()) ? AttachmentPoint_Depth : AttachmentPoint_DepthStencil; + + case PixelFormatContent_Stencil: + return AttachmentPoint_Stencil; + + case PixelFormatContent_Undefined: + break; + } + + NazaraInternalError("Unexpected pixel format content: 0x" + String::Number(info.content, 16)); + return AttachmentPoint_Max; + } + + GLuint lockedPrevious = 0; + UInt8 lockedLevel = 0; + } + + struct RenderTextureImpl + { + NazaraSlot(Context, OnContextDestroy, contextDestroySlot); + + GLuint fbo; + std::vector attachments; + std::vector colorTargets; + mutable std::vector drawBuffers; + const Context* context; + bool complete = false; + bool userDefinedTargets = false; + unsigned int height; + unsigned int width; + }; + + bool RenderTexture::AttachBuffer(AttachmentPoint attachmentPoint, UInt8 index, RenderBuffer* buffer) + { + #if NAZARA_RENDERER_SAFE + if (!m_impl) + { + NazaraError("Render texture not created"); + return false; + } + + if (attachmentPoint != AttachmentPoint_Color) + { + if (index > 0) + { + NazaraError("Index must be 0 for non-color attachments"); + return false; + } + } + else + { + if (index >= Renderer::GetMaxColorAttachments()) + { + NazaraError("Color index is over max color attachments (" + String::Number(index) + " >= " + String::Number(Renderer::GetMaxColorAttachments()) + ")"); + return false; + } + } + + if (!buffer || !buffer->IsValid()) + { + NazaraError("Invalid render buffer"); + return false; + } + + unsigned int depthStencilIndex = attachmentIndex[AttachmentPoint_DepthStencil]; + if (m_impl->attachments.size() > depthStencilIndex && m_impl->attachments[depthStencilIndex].isUsed) + { + if (attachmentPoint == AttachmentPoint_Depth) + { + NazaraError("Depth target already attached by DepthStencil attachment"); + return false; + } + else if (attachmentPoint == AttachmentPoint_Stencil) + { + NazaraError("Stencil target already attached by DepthStencil attachment"); + return false; + } + } + + AttachmentPoint targetAttachmentPoint = FormatTypeToAttachment(buffer->GetFormat()); + if (targetAttachmentPoint != attachmentPoint && targetAttachmentPoint != AttachmentPoint_DepthStencil && + attachmentPoint != AttachmentPoint_Depth && attachmentPoint != AttachmentPoint_Stencil) + { + NazaraError("Pixel format type does not match attachment point type"); + return false; + } + #endif + + if (!Lock()) + { + NazaraError("Failed to lock render texture"); + return false; + } + + // Détachement de l'attache précédente (Si il y a) + Detach(attachmentPoint, index); + + glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, OpenGL::Attachment[attachmentPoint]+index, GL_RENDERBUFFER, buffer->GetOpenGLID()); + + Unlock(); + + unsigned int attachIndex = attachmentIndex[attachmentPoint] + index; + if (attachIndex >= m_impl->attachments.size()) + m_impl->attachments.resize(attachIndex+1); + + Attachment& attachment = m_impl->attachments[attachIndex]; + attachment.attachmentPoint = attachmentPoint; + attachment.buffer = buffer; + attachment.renderBufferDestroySlot.Connect(buffer->OnRenderBufferDestroy, std::bind(&RenderTexture::OnRenderBufferDestroy, this, std::placeholders::_1, attachIndex)); + attachment.isBuffer = true; + attachment.isUsed = true; + attachment.height = buffer->GetHeight(); + attachment.width = buffer->GetWidth(); + + InvalidateSize(); + InvalidateTargets(); + + return true; + } + + bool RenderTexture::AttachBuffer(AttachmentPoint attachmentPoint, UInt8 index, PixelFormatType format, unsigned int width, unsigned int height) + { + RenderBufferRef renderBuffer = RenderBuffer::New(); + if (!renderBuffer->Create(format, width, height)) + { + NazaraError("Failed to create RenderBuffer"); + return false; + } + + if (!AttachBuffer(attachmentPoint, index, renderBuffer)) + { + NazaraError("Failed to attach buffer"); + return false; + } + + return true; + } + + bool RenderTexture::AttachTexture(AttachmentPoint attachmentPoint, UInt8 index, Texture* texture, unsigned int z) + { + #if NAZARA_RENDERER_SAFE + if (!m_impl) + { + NazaraError("Render texture not created"); + return false; + } + + if (attachmentPoint != AttachmentPoint_Color) + { + if (index > 0) + { + NazaraError("Index must be 0 for non-color attachments"); + return false; + } + } + else + { + if (index >= Renderer::GetMaxColorAttachments()) + { + NazaraError("Color index is over max color attachments (" + String::Number(index) + " >= " + String::Number(Renderer::GetMaxColorAttachments()) + ")"); + return false; + } + } + + if (attachmentPoint == AttachmentPoint_Stencil) + { + NazaraError("Targeting stencil-only textures is not supported"); + return false; + } + + unsigned int depthStencilIndex = attachmentIndex[AttachmentPoint_DepthStencil]; + if (attachmentPoint == AttachmentPoint_Depth && m_impl->attachments.size() > depthStencilIndex && + m_impl->attachments[depthStencilIndex].isUsed) + { + NazaraError("Depth target already attached by DepthStencil attachment"); + return false; + } + + if (!texture || !texture->IsValid()) + { + NazaraError("Invalid texture"); + return false; + } + + unsigned int depth = (texture->GetType() == ImageType_Cubemap) ? 6 : texture->GetDepth(); + if (z >= depth) + { + NazaraError("Z value exceeds depth (" + String::Number(z) + " >= (" + String::Number(depth) + ')'); + return false; + } + + AttachmentPoint targetAttachmentPoint = FormatTypeToAttachment(texture->GetFormat()); + if (targetAttachmentPoint != attachmentPoint && targetAttachmentPoint != AttachmentPoint_DepthStencil && + attachmentPoint != AttachmentPoint_Depth && attachmentPoint != AttachmentPoint_Stencil) + { + NazaraError("Pixel format type does not match attachment point type"); + return false; + } + #endif + + if (!Lock()) + { + NazaraError("Failed to lock render texture"); + return false; + } + + // Détachement de l'attache précédente (Si il y a) + Detach(attachmentPoint, index); + + switch (texture->GetType()) + { + case ImageType_1D: + glFramebufferTexture1D(GL_DRAW_FRAMEBUFFER, OpenGL::Attachment[attachmentPoint]+index, GL_TEXTURE_1D, texture->GetOpenGLID(), 0); + break; + + case ImageType_1D_Array: + case ImageType_2D_Array: + glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, OpenGL::Attachment[attachmentPoint]+index, texture->GetOpenGLID(), 0, z); + break; + + case ImageType_2D: + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, OpenGL::Attachment[attachmentPoint]+index, GL_TEXTURE_2D, texture->GetOpenGLID(), 0); + break; + + case ImageType_3D: + glFramebufferTexture3D(GL_DRAW_FRAMEBUFFER, OpenGL::Attachment[attachmentPoint]+index, GL_TEXTURE_3D, texture->GetOpenGLID(), 0, z); + break; + + case ImageType_Cubemap: + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, OpenGL::Attachment[attachmentPoint]+index, OpenGL::CubemapFace[z], texture->GetOpenGLID(), 0); + break; + } + + Unlock(); + + unsigned int attachIndex = attachmentIndex[attachmentPoint] + index; + if (attachIndex >= m_impl->attachments.size()) + m_impl->attachments.resize(attachIndex+1); + + Attachment& attachment = m_impl->attachments[attachIndex]; + attachment.attachmentPoint = attachmentPoint; + attachment.isBuffer = false; + attachment.isUsed = true; + attachment.height = texture->GetHeight(); + attachment.texture = texture; + attachment.textureDestroySlot.Connect(texture->OnTextureDestroy, std::bind(&RenderTexture::OnTextureDestroy, this, std::placeholders::_1, attachIndex)); + attachment.width = texture->GetWidth(); + + InvalidateSize(); + InvalidateTargets(); + + return true; + } + + bool RenderTexture::Create(bool lock) + { + Destroy(); + + #if NAZARA_RENDERER_SAFE + if (Context::GetCurrent() == nullptr) + { + NazaraError("No active context"); + return false; + } + #endif + + std::unique_ptr impl(new RenderTextureImpl); + + impl->fbo = 0; + glGenFramebuffers(1, &impl->fbo); + + if (!impl->fbo) + { + NazaraError("Failed to create framebuffer"); + return false; + } + + m_impl = impl.release(); + m_impl->context = Context::GetCurrent(); + m_impl->contextDestroySlot.Connect(m_impl->context->OnContextDestroy, this, &RenderTexture::OnContextDestroy); + + m_checked = false; + m_drawBuffersUpdated = true; + m_sizeUpdated = false; + m_targetsUpdated = true; + + if (lock) + { + // En cas d'exception, la ressource sera quand même libérée + CallOnExit onExit([this] () + { + Destroy(); + }); + + if (!Lock()) + { + NazaraError("Failed to lock render texture"); + return false; + } + + onExit.Reset(); + } + + OnRenderTargetParametersChange(this); + OnRenderTargetSizeChange(this); + + return true; + } + + void RenderTexture::Destroy() + { + if (m_impl) + { + if (IsActive()) + Renderer::SetTarget(nullptr); + + // Le FBO devant être supprimé dans son contexte d'origine, nous déléguons sa suppression à la classe OpenGL + // Celle-ci va libérer le FBO dès que possible (la prochaine fois que son contexte d'origine sera actif) + OpenGL::DeleteFrameBuffer(m_impl->context, m_impl->fbo); + + delete m_impl; // Enlève également une références sur les Texture/RenderBuffer + m_impl = nullptr; + } + } + + void RenderTexture::Detach(AttachmentPoint attachmentPoint, UInt8 index) + { + #if NAZARA_RENDERER_SAFE + if (!m_impl) + { + NazaraError("Render texture not created"); + return; + } + + if (attachmentPoint != AttachmentPoint_Color && index > 0) + { + NazaraError("Index must be 0 for non-color attachments"); + return; + } + #endif + + unsigned int attachIndex = attachmentIndex[attachmentPoint] + index; + if (attachIndex >= m_impl->attachments.size()) + return; + + Attachment& attachement = m_impl->attachments[attachIndex]; + if (!attachement.isUsed) + return; + + if (!Lock()) + { + NazaraError("Failed to lock render texture"); + return; + } + + attachement.isUsed = false; + + if (attachement.isBuffer) + { + glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, OpenGL::Attachment[attachmentPoint]+index, GL_RENDERBUFFER, 0); + + attachement.buffer = nullptr; + attachement.renderBufferDestroySlot.Disconnect(); + } + else + { + if (glFramebufferTexture) + glFramebufferTexture(GL_DRAW_FRAMEBUFFER, OpenGL::Attachment[attachmentPoint]+index, 0, 0); + else + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, OpenGL::Attachment[attachmentPoint]+index, 0, 0, 0); + + attachement.texture = nullptr; + attachement.textureDestroySlot.Disconnect(); + } + + InvalidateSize(); + + if (attachement.attachmentPoint == AttachmentPoint_Color) + InvalidateTargets(); + + Unlock(); + + m_checked = false; + } + + unsigned int RenderTexture::GetHeight() const + { + NazaraAssert(m_impl, "Invalid render texture"); + + if (!m_sizeUpdated) + UpdateSize(); + + return m_impl->height; + } + + RenderTargetParameters RenderTexture::GetParameters() const + { + NazaraAssert(m_impl, "Invalid render texture"); + + ///TODO + return RenderTargetParameters(); + } + + Vector2ui RenderTexture::GetSize() const + { + NazaraAssert(m_impl, "Invalid render texture"); + + if (!m_sizeUpdated) + UpdateSize(); + + return Vector2ui(m_impl->width, m_impl->height); + } + + unsigned int RenderTexture::GetWidth() const + { + NazaraAssert(m_impl, "Invalid render texture"); + + if (!m_sizeUpdated) + UpdateSize(); + + return m_impl->width; + } + + bool RenderTexture::IsComplete() const + { + NazaraAssert(m_impl, "Invalid render texture"); + + if (!m_checked) + { + if (!Lock()) + { + NazaraError("Failed to lock render texture"); + return false; + } + + GLenum status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); + Unlock(); + + m_impl->complete = false; + + switch (status) + { + case GL_FRAMEBUFFER_COMPLETE: + m_impl->complete = true; + break; + + case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: + NazaraError("Incomplete attachment"); + break; + + case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: + NazaraInternalError("Incomplete draw buffer"); + break; + + case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: + NazaraInternalError("Incomplete read buffer"); + break; + + case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: + NazaraError("Incomplete missing attachment"); + break; + + case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: + NazaraError("Incomplete multisample"); + break; + + case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: + NazaraError("Incomplete layer targets"); + break; + + case GL_FRAMEBUFFER_UNSUPPORTED: + NazaraError("Render texture has unsupported attachments"); + break; + + default: + NazaraInternalError("Unknown error"); + } + + m_checked = true; + } + + return m_impl->complete; + } + + bool RenderTexture::IsRenderable() const + { + return IsComplete() && !m_impl->attachments.empty(); + } + + bool RenderTexture::Lock() const + { + NazaraAssert(m_impl, "Invalid render texture"); + + #if NAZARA_RENDERER_SAFE + if (Context::GetCurrent() != m_impl->context) + { + NazaraError("RenderTexture cannot be used with this context"); + return false; + } + #endif + + if (lockedLevel++ == 0) + { + GLint previous; + glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &previous); + + lockedPrevious = previous; + + if (lockedPrevious != m_impl->fbo) + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_impl->fbo); + } + + return true; + } + + void RenderTexture::SetColorTargets(const UInt8* targets, unsigned int targetCount) const + { + NazaraAssert(m_impl, "Invalid render texture"); + + #if NAZARA_RENDERER_SAFE + for (unsigned int i = 0; i < targetCount; ++i) + { + unsigned int index = attachmentIndex[AttachmentPoint_Color] + targets[i]; + if (index >= m_impl->attachments.size() || !m_impl->attachments[index].isUsed) + { + NazaraError("Target " + String::Number(targets[i]) + " not attached"); + return; + } + } + #endif + + m_impl->colorTargets.resize(targetCount); + std::memcpy(&m_impl->colorTargets[0], targets, targetCount*sizeof(UInt8)); + + m_impl->userDefinedTargets = true; + InvalidateTargets(); + } + + void RenderTexture::SetColorTargets(const std::initializer_list& targets) const + { + NazaraAssert(m_impl, "Invalid render texture"); + + #if NAZARA_RENDERER_SAFE + for (UInt8 target : targets) + { + unsigned int index = attachmentIndex[AttachmentPoint_Color] + target; + if (index >= m_impl->attachments.size() || !m_impl->attachments[index].isUsed) + { + NazaraError("Target " + String::Number(target) + " not attached"); + return; + } + } + #endif + + m_impl->colorTargets.resize(targets.size()); + + UInt8* ptr = &m_impl->colorTargets[0]; + for (UInt8 index : targets) + *ptr++ = index; + + m_impl->userDefinedTargets = true; + InvalidateTargets(); + } + + void RenderTexture::Unlock() const + { + NazaraAssert(m_impl, "Invalid render texture"); + + #if NAZARA_RENDERER_SAFE + if (Context::GetCurrent() != m_impl->context) + { + NazaraError("RenderTexture cannot be used with this context"); + return; + } + + if (lockedLevel == 0) + { + NazaraWarning("Unlock called on non-locked texture"); + return; + } + #endif + + if (--lockedLevel == 0 && lockedPrevious != m_impl->fbo) // Ici, il est important qu'un FBO soit débindé si l'ancien était 0 + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, lockedPrevious); + } + + unsigned int RenderTexture::GetOpenGLID() const + { + NazaraAssert(m_impl, "Invalid render texture"); + + #if NAZARA_RENDERER_SAFE + if (Context::GetCurrent() != m_impl->context) + { + NazaraError("RenderTexture cannot be used with this context"); + return 0; + } + #endif + + return m_impl->fbo; + } + + bool RenderTexture::HasContext() const + { + return false; + } + + void RenderTexture::Blit(RenderTexture* src, Rectui srcRect, RenderTexture* dst, Rectui dstRect, UInt32 buffers, bool bilinearFilter) + { + NazaraAssert(src && src->IsValid(), "Invalid source render texture"); + NazaraAssert(dst && dst->IsValid(), "Invalid destination render texture"); + + #if NAZARA_RENDERER_SAFE + if (srcRect.x+srcRect.width > src->GetWidth() || srcRect.y+srcRect.height > src->GetHeight()) + { + NazaraError("Source rectangle dimensions are out of bounds"); + return; + } + + if (dstRect.x+dstRect.width > dst->GetWidth() || dstRect.y+dstRect.height > dst->GetHeight()) + { + NazaraError("Destination rectangle dimensions are out of bounds"); + return; + } + + if (bilinearFilter && (buffers & RendererBuffer_Depth || buffers & RendererBuffer_Stencil)) + { + NazaraError("Filter cannot be bilinear when blitting depth/stencil buffers"); + return; + } + #endif + + GLbitfield mask = 0; + if (buffers & RendererBuffer_Color) + mask |= GL_COLOR_BUFFER_BIT; + + if (buffers & RendererBuffer_Depth) + mask |= GL_DEPTH_BUFFER_BIT; + + if (buffers & RendererBuffer_Stencil) + mask |= GL_STENCIL_BUFFER_BIT; + + GLint previousDrawBuffer, previousReadBuffer; + glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &previousDrawBuffer); + glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &previousReadBuffer); + + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, dst->GetOpenGLID()); + glBindFramebuffer(GL_READ_FRAMEBUFFER, src->GetOpenGLID()); + + glBlitFramebuffer(srcRect.x, srcRect.y, srcRect.x + srcRect.width, srcRect.y + srcRect.height, + dstRect.x, dstRect.y, dstRect.x + dstRect.width, dstRect.y + dstRect.height, + mask, (bilinearFilter) ? GL_LINEAR : GL_NEAREST); + + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, previousDrawBuffer); + glBindFramebuffer(GL_READ_FRAMEBUFFER, previousReadBuffer); + } + + bool RenderTexture::Activate() const + { + NazaraAssert(m_impl, "Invalid render texture"); + + #if NAZARA_RENDERER_SAFE + if (Context::GetCurrent() != m_impl->context) + { + NazaraError("RenderTexture cannot be used with this context"); + return false; + } + #endif + + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_impl->fbo); + + m_drawBuffersUpdated = false; + + return true; + } + + void RenderTexture::Desactivate() const + { + NazaraAssert(m_impl, "Invalid render texture"); + + #if NAZARA_RENDERER_SAFE + if (Context::GetCurrent() != m_impl->context) + { + NazaraError("RenderTexture cannot be used with this context"); + return; + } + #endif + + glFlush(); + + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + } + + void RenderTexture::EnsureTargetUpdated() const + { + if (!m_drawBuffersUpdated) + UpdateDrawBuffers(); + + for (UInt8 index : m_impl->colorTargets) + { + Attachment& attachment = m_impl->attachments[attachmentIndex[AttachmentPoint_Color] + index]; + if (!attachment.isBuffer) + attachment.texture->InvalidateMipmaps(); + } + } + + void RenderTexture::OnContextDestroy(const Context* context) + { + NazaraAssert(m_impl, "Invalid internal state"); + NazaraUnused(context); + + #ifdef NAZARA_DEBUG + if (m_impl->context != context) + { + NazaraInternalError("Not listening to " + String::Pointer(context)); + return; + } + #endif + + Destroy(); + } + + void RenderTexture::OnRenderBufferDestroy(const RenderBuffer* renderBuffer, unsigned int attachmentIndex) + { + NazaraAssert(m_impl, "Invalid internal state"); + NazaraAssert(attachmentIndex < m_impl->attachments.size(), "Invalid attachment index"); + NazaraAssert(m_impl->attachments[attachmentIndex].isBuffer, "Invalid attachment state"); + NazaraUnused(renderBuffer); + + Attachment& attachment = m_impl->attachments[attachmentIndex]; + attachment.buffer = nullptr; + attachment.isUsed = false; + attachment.renderBufferDestroySlot.Disconnect(); + + InvalidateTargets(); + } + + void RenderTexture::OnTextureDestroy(const Texture* texture, unsigned int attachmentIndex) + { + NazaraAssert(m_impl, "Invalid internal state"); + NazaraAssert(attachmentIndex < m_impl->attachments.size(), "Invalid attachment index"); + NazaraAssert(!m_impl->attachments[attachmentIndex].isBuffer, "Invalid attachment state"); + NazaraUnused(texture); + NazaraUnused(attachmentIndex); + + InvalidateTargets(); + } + + void RenderTexture::UpdateDrawBuffers() const + { + if (!m_targetsUpdated) + UpdateTargets(); + + glDrawBuffers(m_impl->drawBuffers.size(), &m_impl->drawBuffers[0]); + + m_drawBuffersUpdated = true; + } + + void RenderTexture::UpdateSize() const + { + m_impl->width = 0; + m_impl->height = 0; + for (Attachment& attachment : m_impl->attachments) + { + if (attachment.isUsed) + { + m_impl->height = std::max(m_impl->height, attachment.height); + m_impl->width = std::max(m_impl->width, attachment.width); + } + } + + m_sizeUpdated = true; + } + + void RenderTexture::UpdateTargets() const + { + if (!m_impl->userDefinedTargets) + { + m_impl->colorTargets.clear(); + + unsigned int colorIndex = 0; + for (unsigned int index = attachmentIndex[AttachmentPoint_Color]; index < m_impl->attachments.size(); ++index) + m_impl->colorTargets.push_back(colorIndex++); + } + + if (m_impl->colorTargets.empty()) + { + m_impl->drawBuffers.resize(1); + m_impl->drawBuffers[0] = GL_NONE; + } + else + { + m_impl->drawBuffers.resize(m_impl->colorTargets.size()); + GLenum* ptr = &m_impl->drawBuffers[0]; + for (UInt8 index : m_impl->colorTargets) + *ptr++ = GL_COLOR_ATTACHMENT0 + index; + } + + m_targetsUpdated = true; + } +} diff --git a/src/Nazara/Utility/AlgorithmUtility.cpp b/src/Nazara/Utility/AlgorithmUtility.cpp index d82af98af..90a3d53e3 100644 --- a/src/Nazara/Utility/AlgorithmUtility.cpp +++ b/src/Nazara/Utility/AlgorithmUtility.cpp @@ -742,7 +742,7 @@ namespace Nz Vector3f halfLengths = lengths/2.f; // Face +X - transform.MakeTransform(Vector3f::UnitX() * halfLengths.x, EulerAnglesf(-90.f, 0.f, -90.f)); + transform.MakeTransform(Vector3f::UnitX() * halfLengths.x, EulerAnglesf(-90.f, -90.f, 180.f)); GeneratePlane(Vector2ui(subdivision.z, subdivision.y), Vector2f(lengths.z, lengths.y), Matrix4f::ConcatenateAffine(matrix, transform), textureCoords, vertexPointers, indices, nullptr, indexOffset); indexOffset += xVertexCount; indices += xIndexCount; @@ -776,7 +776,7 @@ namespace Nz vertexPointers.uvPtr += yVertexCount; // Face +Z - transform.MakeTransform(Vector3f::UnitZ() * halfLengths.z, EulerAnglesf(-90.f, 90.f, 90.f)); + transform.MakeTransform(Vector3f::UnitZ() * halfLengths.z, EulerAnglesf(90.f, 0.f, 0.f)); GeneratePlane(Vector2ui(subdivision.x, subdivision.y), Vector2f(lengths.x, lengths.y), Matrix4f::ConcatenateAffine(matrix, transform), textureCoords, vertexPointers, indices, nullptr, indexOffset); indexOffset += zVertexCount; indices += zIndexCount; @@ -793,7 +793,7 @@ namespace Nz vertexPointers.uvPtr += zVertexCount; // Face -X - transform.MakeTransform(-Vector3f::UnitX() * halfLengths.x, EulerAnglesf(-90.f, 0.f, 90.f)); + transform.MakeTransform(-Vector3f::UnitX() * halfLengths.x, EulerAnglesf(-90.f, 90.f, 180.f)); GeneratePlane(Vector2ui(subdivision.z, subdivision.y), Vector2f(lengths.z, lengths.y), Matrix4f::ConcatenateAffine(matrix, transform), textureCoords, vertexPointers, indices, nullptr, indexOffset); indexOffset += xVertexCount; indices += xIndexCount; @@ -810,7 +810,7 @@ namespace Nz vertexPointers.uvPtr += xVertexCount; // Face -Y - transform.MakeTransform(-Vector3f::UnitY() * halfLengths.y, EulerAnglesf(0.f, 0.f, 180.f)); + transform.MakeTransform(-Vector3f::UnitY() * halfLengths.y, EulerAnglesf(0.f, 180.f, 180.f)); GeneratePlane(Vector2ui(subdivision.x, subdivision.z), Vector2f(lengths.x, lengths.z), Matrix4f::ConcatenateAffine(matrix, transform), textureCoords, vertexPointers, indices, nullptr, indexOffset); indexOffset += yVertexCount; indices += yIndexCount; @@ -827,7 +827,7 @@ namespace Nz vertexPointers.uvPtr += yVertexCount; // Face -Z - transform.MakeTransform(-Vector3f::UnitZ() * halfLengths.z, EulerAnglesf(-90.f, -90.f, 90.f)); + transform.MakeTransform(-Vector3f::UnitZ() * halfLengths.z, EulerAnglesf(90.f, 180.f, 0.f)); GeneratePlane(Vector2ui(subdivision.x, subdivision.y), Vector2f(lengths.x, lengths.y), Matrix4f::ConcatenateAffine(matrix, transform), textureCoords, vertexPointers, indices, nullptr, indexOffset); indexOffset += zVertexCount; indices += zIndexCount; diff --git a/src/Nazara/Utility/Formats/DDSLoader.cpp b/src/Nazara/Utility/Formats/DDSLoader.cpp index d9783115b..1e707e610 100644 --- a/src/Nazara/Utility/Formats/DDSLoader.cpp +++ b/src/Nazara/Utility/Formats/DDSLoader.cpp @@ -174,15 +174,15 @@ namespace Nz if (header.format.flags & DDPF_RGB) { // Reverse bits for our masks - info.redMask = ReverseBits(header.format.redMask); - info.greenMask = ReverseBits(header.format.greenMask); - info.blueMask = ReverseBits(header.format.blueMask); + info.redMask = header.format.redMask; + info.greenMask = header.format.greenMask; + info.blueMask = header.format.blueMask; } else if (header.format.flags & DDPF_LUMINANCE) - info.redMask = ReverseBits(header.format.redMask); + info.redMask = header.format.redMask; if (header.format.flags & (DDPF_ALPHA | DDPF_ALPHAPIXELS)) - info.alphaMask = ReverseBits(header.format.alphaMask); + info.alphaMask = header.format.alphaMask; *format = PixelFormat::IdentifyFormat(info); if (!PixelFormat::IsValid(*format)) diff --git a/src/Nazara/Utility/Formats/MTLParser.cpp b/src/Nazara/Utility/Formats/MTLParser.cpp index 1bbed892f..c3b60a6e5 100644 --- a/src/Nazara/Utility/Formats/MTLParser.cpp +++ b/src/Nazara/Utility/Formats/MTLParser.cpp @@ -331,19 +331,19 @@ namespace Nz Emit(mat.specular.b / 255.f); EmitLine(); - if (mat.alpha != 1.f) + if (!NumberEquals(mat.alpha, 1.f)) { Emit("d "); EmitLine(mat.alpha); } - if (mat.refractionIndex != 1.f) + if (!NumberEquals(mat.refractionIndex, 1.f)) { Emit("ni "); EmitLine(mat.refractionIndex); } - if (mat.shininess != 1.f) + if (!NumberEquals(mat.shininess, 1.f)) { Emit("ns "); EmitLine(mat.shininess); diff --git a/src/Nazara/Utility/Formats/OBJParser.cpp b/src/Nazara/Utility/Formats/OBJParser.cpp index 3b03b7f78..eed0ee2b1 100644 --- a/src/Nazara/Utility/Formats/OBJParser.cpp +++ b/src/Nazara/Utility/Formats/OBJParser.cpp @@ -128,17 +128,17 @@ namespace Nz UInt32 faceReserve = 0; UInt32 vertexReserve = 0; unsigned int matCount = 0; - auto GetMaterial = [&] (const String& meshName, const String& matName) -> Mesh* + auto GetMaterial = [&] (const String& mesh, const String& mat) -> Mesh* { - auto& map = meshesByName[meshName]; - auto it = map.find(matName); + auto& map = meshesByName[mesh]; + auto it = map.find(mat); if (it == map.end()) - it = map.insert(std::make_pair(matName, MatPair(Mesh(), matCount++))).first; + it = map.insert(std::make_pair(mat, MatPair(Mesh(), matCount++))).first; - Mesh& mesh = it->second.first; + Mesh& meshData = it->second.first; - mesh.faces.reserve(faceReserve); - mesh.vertices.reserve(vertexReserve); + meshData.faces.reserve(faceReserve); + meshData.vertices.reserve(vertexReserve); faceReserve = 0; vertexReserve = 0; @@ -550,19 +550,19 @@ namespace Nz EmitLine(pair.second.size()); EmitLine(); - for (std::size_t meshIndex : pair.second) + for (std::size_t index : pair.second) { - const Mesh& mesh = m_meshes[meshIndex]; + const Mesh& mesh = m_meshes[index]; Emit("g "); EmitLine(mesh.name); EmitLine(); - + Emit("# face count: "); EmitLine(mesh.faces.size()); Emit("# vertex count: "); EmitLine(mesh.vertices.size()); - + for (const Face& face : mesh.faces) { Emit('f'); diff --git a/src/Nazara/Utility/Image.cpp b/src/Nazara/Utility/Image.cpp index 160c2ac90..39d99cdd1 100644 --- a/src/Nazara/Utility/Image.cpp +++ b/src/Nazara/Utility/Image.cpp @@ -825,6 +825,44 @@ namespace Nz return GetLevelSize(m_sharedImage->width, level); } + bool Image::HasAlpha() const + { + NazaraAssert(m_sharedImage != &emptyImage, "Image must be valid"); + + if (!PixelFormat::HasAlpha(m_sharedImage->format)) + return false; + + if (!PixelFormat::IsCompressed(m_sharedImage->format)) + { + const PixelFormatInfo& info = PixelFormat::GetInfo(m_sharedImage->format); + const UInt8* pixel = GetConstPixels(); + + Bitset<> workingBitset; + std::size_t pixelCount = m_sharedImage->width * m_sharedImage->height * ((m_sharedImage->type == ImageType_Cubemap) ? 6 : m_sharedImage->depth); + if (pixelCount == 0) + return false; + + auto seq = workingBitset.Read(GetConstPixels(), info.bitsPerPixel); + do + { + workingBitset &= info.alphaMask; + if (workingBitset.Count() != info.alphaMask.Count()) //< Means that at least one bit of the alpha mask of this pixel is disabled + return true; + + workingBitset.Clear(); + workingBitset.Read(seq, info.bitsPerPixel); + } + while (--pixelCount > 0); + + return false; + } + else + { + // FIXME: Currently, we assume the pixel format is already the right one + return true; + } + } + bool Image::IsValid() const { return m_sharedImage != &emptyImage; @@ -1441,7 +1479,7 @@ namespace Nz SharedImage::PixelContainer levels(m_sharedImage->levels.size()); for (unsigned int i = 0; i < levels.size(); ++i) { - unsigned int size = GetMemoryUsage(i); + std::size_t size = GetMemoryUsage(i); levels[i].reset(new UInt8[size]); std::memcpy(levels[i].get(), m_sharedImage->levels[i].get(), size); } diff --git a/src/Nazara/Utility/SimpleTextDrawer.cpp b/src/Nazara/Utility/SimpleTextDrawer.cpp index 03a95f35a..0d06fa0ba 100644 --- a/src/Nazara/Utility/SimpleTextDrawer.cpp +++ b/src/Nazara/Utility/SimpleTextDrawer.cpp @@ -75,6 +75,7 @@ namespace Nz Font* SimpleTextDrawer::GetFont(std::size_t index) const { NazaraAssert(index == 0, "Font index out of range"); + NazaraUnused(index); return m_font; } diff --git a/src/Nazara/Utility/SoftwareBuffer.cpp b/src/Nazara/Utility/SoftwareBuffer.cpp index 081f0fda3..040017c1e 100644 --- a/src/Nazara/Utility/SoftwareBuffer.cpp +++ b/src/Nazara/Utility/SoftwareBuffer.cpp @@ -11,7 +11,7 @@ namespace Nz { - SoftwareBuffer::SoftwareBuffer(Buffer* /*parent*/, BufferType type) + SoftwareBuffer::SoftwareBuffer(Buffer* /*parent*/, BufferType /*type*/) { } diff --git a/src/Nazara/Utility/VertexBuffer.cpp b/src/Nazara/Utility/VertexBuffer.cpp index 0bc890340..b196d723a 100644 --- a/src/Nazara/Utility/VertexBuffer.cpp +++ b/src/Nazara/Utility/VertexBuffer.cpp @@ -45,7 +45,7 @@ namespace Nz bool VertexBuffer::Fill(const void* data, unsigned int startVertex, unsigned int length, bool forceDiscard) { - unsigned int stride = m_vertexDeclaration->GetStride(); + std::size_t stride = m_vertexDeclaration->GetStride(); return FillRaw(data, startVertex*stride, length*stride, forceDiscard); } diff --git a/src/Nazara/Utility/VideoMode.cpp b/src/Nazara/Utility/VideoMode.cpp index 6313ff460..2c6a2f321 100644 --- a/src/Nazara/Utility/VideoMode.cpp +++ b/src/Nazara/Utility/VideoMode.cpp @@ -24,6 +24,11 @@ namespace Nz width(0) { } + + VideoMode::VideoMode(unsigned int w, unsigned int h) : + VideoMode(w, h, GetDesktopMode().bitsPerPixel) + { + } VideoMode::VideoMode(unsigned int w, unsigned int h, UInt8 bpp) : bitsPerPixel(bpp), diff --git a/src/Nazara/Utility/Win32/WindowImpl.cpp b/src/Nazara/Utility/Win32/WindowImpl.cpp index b494a7789..558a44ddb 100644 --- a/src/Nazara/Utility/Win32/WindowImpl.cpp +++ b/src/Nazara/Utility/Win32/WindowImpl.cpp @@ -83,6 +83,7 @@ namespace Nz bool WindowImpl::Create(const VideoMode& mode, const String& title, UInt32 style) { + bool async = (style & WindowStyle_Threaded) != 0; bool fullscreen = (style & WindowStyle_Fullscreen) != 0; DWORD win32Style, win32StyleEx; unsigned int x, y; @@ -147,19 +148,25 @@ namespace Nz m_callback = 0; - #if NAZARA_UTILITY_THREADED_WINDOW - Mutex mutex; - ConditionVariable condition; - m_threadActive = true; + m_eventListener = true; + m_ownsWindow = true; + m_sizemove = false; + m_style = style; - // On attend que la fenêtre soit créée - mutex.Lock(); - m_thread = Thread(WindowThread, &m_handle, win32StyleEx, title.GetWideString().data(), win32Style, x, y, width, height, this, &mutex, &condition); - condition.Wait(&mutex); - mutex.Unlock(); - #else - m_handle = CreateWindowExW(win32StyleEx, className, title.GetWideString().data(), win32Style, x, y, width, height, nullptr, nullptr, GetModuleHandle(nullptr), this); - #endif + if (async) + { + Mutex mutex; + ConditionVariable condition; + m_threadActive = true; + + // On attend que la fenêtre soit créée + mutex.Lock(); + m_thread = Thread(WindowThread, &m_handle, win32StyleEx, title, win32Style, fullscreen, Rectui(x, y, width, height), this, &mutex, &condition); + condition.Wait(&mutex); + mutex.Unlock(); + } + else + m_handle = CreateWindowExW(win32StyleEx, className, title.GetWideString().data(), win32Style, x, y, width, height, nullptr, nullptr, GetModuleHandle(nullptr), this); if (!m_handle) { @@ -167,26 +174,8 @@ namespace Nz return false; } - if (fullscreen) - { - SetForegroundWindow(m_handle); - ShowWindow(m_handle, SW_SHOW); - } - - m_eventListener = true; - m_ownsWindow = true; - #if !NAZARA_UTILITY_THREADED_WINDOW - m_sizemove = false; - #endif - m_style = style; - - // Récupération de la position/taille de la fenêtre (Après sa création) - RECT clientRect, windowRect; - GetClientRect(m_handle, &clientRect); - GetWindowRect(m_handle, &windowRect); - - m_position.Set(windowRect.left, windowRect.top); - m_size.Set(clientRect.right - clientRect.left, clientRect.bottom - clientRect.top); + if (!async) + PrepareWindow(fullscreen); return true; } @@ -203,9 +192,7 @@ namespace Nz m_eventListener = false; m_ownsWindow = false; - #if !NAZARA_UTILITY_THREADED_WINDOW m_sizemove = false; - #endif m_style = RetrieveStyle(m_handle); RECT clientRect, windowRect; @@ -222,18 +209,21 @@ namespace Nz { if (m_ownsWindow) { - #if NAZARA_UTILITY_THREADED_WINDOW - if (m_thread.IsJoinable()) + if (m_style & WindowStyle_Threaded) { - m_threadActive = false; - PostMessageW(m_handle, WM_NULL, 0, 0); // Pour réveiller le thread + if (m_thread.IsJoinable()) + { + m_threadActive = false; + PostMessageW(m_handle, WM_NULL, 0, 0); // Wake up our thread - m_thread.Join(); + m_thread.Join(); + } + } + else + { + if (m_handle) + DestroyWindow(m_handle); } - #else - if (m_handle) - DestroyWindow(m_handle); - #endif } else SetEventListener(false); @@ -280,7 +270,7 @@ namespace Nz if (titleSize == 0) return String(); - titleSize++; // Caractère nul + titleSize++; // \0 std::unique_ptr wTitle(new wchar_t[titleSize]); GetWindowTextW(m_handle, wTitle.get(), titleSize); @@ -525,7 +515,6 @@ namespace Nz return true; // Afin que Windows ne ferme pas la fenêtre automatiquement } - #if !NAZARA_UTILITY_THREADED_WINDOW case WM_ENTERSIZEMOVE: { m_sizemove = true; @@ -536,6 +525,10 @@ namespace Nz { m_sizemove = false; + // In case of threaded window, size and move events are not blocked + if (m_style & WindowStyle_Threaded) + break; + // On vérifie ce qui a changé RECT clientRect, windowRect; GetClientRect(m_handle, &clientRect); @@ -565,7 +558,6 @@ namespace Nz m_parent->PushEvent(event); } } - #endif case WM_KEYDOWN: case WM_SYSKEYDOWN: @@ -789,15 +781,23 @@ namespace Nz case WM_MOVE: { + if (m_sizemove && (m_style & WindowStyle_Threaded) == 0) + break; + RECT windowRect; GetWindowRect(m_handle, &windowRect); - WindowEvent event; - event.type = WindowEventType_Moved; - event.position.x = windowRect.left; - event.position.y = windowRect.top; - m_parent->PushEvent(event); + Vector2i position(windowRect.left, windowRect.top); + if (m_position != position) + { + m_position = position; + WindowEvent event; + event.type = WindowEventType_Moved; + event.position.x = position.x; + event.position.y = position.y; + m_parent->PushEvent(event); + } break; } @@ -852,27 +852,26 @@ namespace Nz case WM_SIZE: { - #if NAZARA_UTILITY_THREADED_WINDOW - if (wParam != SIZE_MINIMIZED) - #else - if (!m_sizemove && wParam != SIZE_MINIMIZED) - #endif - { - RECT rect; - GetClientRect(m_handle, &rect); + if (m_sizemove && (m_style & WindowStyle_Threaded) == 0) + break; - Vector2ui size(rect.right-rect.left, rect.bottom-rect.top); // On récupère uniquement la taille de la zone client - if (m_size == size) - break; + if (wParam == SIZE_MINIMIZED) + break; - m_size = size; + RECT rect; + GetClientRect(m_handle, &rect); - WindowEvent event; - event.type = WindowEventType_Resized; - event.size.width = size.x; - event.size.height = size.y; - m_parent->PushEvent(event); - } + Vector2ui size(rect.right-rect.left, rect.bottom-rect.top); // On récupère uniquement la taille de la zone client + if (m_size == size) + break; + + m_size = size; + + WindowEvent event; + event.type = WindowEventType_Resized; + event.size.width = size.x; + event.size.height = size.y; + m_parent->PushEvent(event); break; } @@ -963,6 +962,23 @@ namespace Nz return false; } + void WindowImpl::PrepareWindow(bool fullscreen) + { + if (fullscreen) + { + SetForegroundWindow(m_handle); + ShowWindow(m_handle, SW_SHOW); + } + + // Cache window position/size after creation + RECT clientRect, windowRect; + GetClientRect(m_handle, &clientRect); + GetWindowRect(m_handle, &windowRect); + + m_position.Set(windowRect.left, windowRect.top); + m_size.Set(clientRect.right - clientRect.left, clientRect.bottom - clientRect.top); + } + bool WindowImpl::Initialize() { // Nous devons faire un type Unicode pour que la fenêtre le soit également @@ -1177,15 +1193,17 @@ namespace Nz return style; } - #if NAZARA_UTILITY_THREADED_WINDOW - void WindowImpl::WindowThread(HWND* handle, DWORD styleEx, const wchar_t* title, DWORD style, unsigned int x, unsigned int y, unsigned int width, unsigned int height, WindowImpl* window, Mutex* mutex, ConditionVariable* condition) + void WindowImpl::WindowThread(HWND* handle, DWORD styleEx, const String& title, DWORD style, bool fullscreen, const Rectui& dimensions, WindowImpl* window, Mutex* mutex, ConditionVariable* condition) { HWND& winHandle = *handle; - winHandle = CreateWindowExW(styleEx, className, title, style, x, y, width, height, nullptr, nullptr, GetModuleHandle(nullptr), window); + winHandle = CreateWindowExW(styleEx, className, title.GetWideString().data(), style, dimensions.x, dimensions.y, dimensions.width, dimensions.height, nullptr, nullptr, GetModuleHandle(nullptr), window); + + if (winHandle) + window->PrepareWindow(fullscreen); mutex->Lock(); condition->Signal(); - mutex->Unlock(); // mutex et condition sont considérés invalides à partir d'ici + mutex->Unlock(); // mutex and condition may be destroyed after this line if (!winHandle) return; @@ -1195,5 +1213,4 @@ namespace Nz DestroyWindow(winHandle); } -#endif } diff --git a/src/Nazara/Utility/Win32/WindowImpl.hpp b/src/Nazara/Utility/Win32/WindowImpl.hpp index b0fcf8ae0..bb718738a 100644 --- a/src/Nazara/Utility/Win32/WindowImpl.hpp +++ b/src/Nazara/Utility/Win32/WindowImpl.hpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -22,10 +23,8 @@ namespace Nz { - #if NAZARA_UTILITY_THREADED_WINDOW class ConditionVariable; class Mutex; - #endif class Window; #undef IsMinimized // Conflit avec la méthode du même nom @@ -84,13 +83,12 @@ namespace Nz private: bool HandleMessage(HWND window, UINT message, WPARAM wParam, LPARAM lParam); + void PrepareWindow(bool fullscreen); static Keyboard::Key ConvertVirtualKey(WPARAM key, LPARAM flags); static LRESULT CALLBACK MessageHandler(HWND window, UINT message, WPARAM wParam, LPARAM lParam); static UInt32 RetrieveStyle(HWND window); - #if NAZARA_UTILITY_THREADED_WINDOW - static void WindowThread(HWND* handle, DWORD styleEx, const wchar_t* title, DWORD style, unsigned int x, unsigned int y, unsigned int width, unsigned int height, WindowImpl* window, Mutex* mutex, ConditionVariable* condition); - #endif + static void WindowThread(HWND* handle, DWORD styleEx, const String& title, DWORD style, bool fullscreen, const Rectui& dimensions, WindowImpl* window, Mutex* mutex, ConditionVariable* condition); HCURSOR m_cursor; HWND m_handle; @@ -101,21 +99,15 @@ namespace Nz Vector2i m_mousePos; Vector2i m_position; Vector2ui m_size; - #if NAZARA_UTILITY_THREADED_WINDOW Thread m_thread; - #endif Window* m_parent; bool m_eventListener; bool m_keyRepeat; bool m_mouseInside; bool m_ownsWindow; - #if !NAZARA_UTILITY_THREADED_WINDOW bool m_sizemove; - #endif bool m_smoothScrolling; - #if NAZARA_UTILITY_THREADED_WINDOW bool m_threadActive; - #endif short m_scrolling; }; } diff --git a/src/Nazara/Utility/Window.cpp b/src/Nazara/Utility/Window.cpp index 078ff2bc5..803badb85 100644 --- a/src/Nazara/Utility/Window.cpp +++ b/src/Nazara/Utility/Window.cpp @@ -66,6 +66,8 @@ namespace Nz else if (style & WindowStyle_Closable || style & WindowStyle_Resizable) style |= WindowStyle_Titlebar; + m_asyncWindow = (style & WindowStyle_Threaded) != 0; + std::unique_ptr impl = std::make_unique(this); if (!impl->Create(mode, title, style)) { @@ -107,6 +109,7 @@ namespace Nz { Destroy(); + m_asyncWindow = false; m_impl = new WindowImpl(this); if (!m_impl->Create(handle)) { @@ -313,11 +316,8 @@ namespace Nz } #endif - #if NAZARA_UTILITY_THREADED_WINDOW - LockGuard lock(m_eventMutex); - #else - m_impl->ProcessEvents(false); - #endif + if (!m_asyncWindow) + m_impl->ProcessEvents(false); if (!m_events.empty()) { @@ -335,10 +335,19 @@ namespace Nz void Window::ProcessEvents(bool block) { NazaraAssert(m_impl, "Window not created"); + NazaraUnused(block); - #if !NAZARA_UTILITY_THREADED_WINDOW - m_impl->ProcessEvents(block); - #endif + if (!m_asyncWindow) + m_impl->ProcessEvents(block); + else + { + LockGuard eventLock(m_eventMutex); + + for (const WindowEvent& event : m_pendingEvents) + HandleEvent(event); + + m_pendingEvents.clear(); + } } void Window::SetCursor(WindowCursor cursor) @@ -383,25 +392,13 @@ namespace Nz } #endif - #if NAZARA_UTILITY_THREADED_WINDOW m_impl->SetEventListener(listener); if (!listener) { - // On vide la pile des évènements - LockGuard lock(m_eventMutex); + // Empty the event queue while (!m_events.empty()) m_events.pop(); } - #else - if (m_ownsWindow) - { - // Inutile de transmettre l'ordre dans ce cas-là - if (!listener) - NazaraError("A non-threaded window needs to listen to events"); - } - else - m_impl->SetEventListener(listener); - #endif } void Window::SetFocus() @@ -589,22 +586,11 @@ namespace Nz } #endif - #if NAZARA_UTILITY_THREADED_WINDOW - LockGuard lock(m_eventMutex); - - if (m_events.empty()) + if (!m_asyncWindow) { - m_waitForEvent = true; - m_eventConditionMutex.Lock(); - m_eventMutex.Unlock(); - m_eventCondition.Wait(&m_eventConditionMutex); - m_eventMutex.Lock(); - m_eventConditionMutex.Unlock(); - m_waitForEvent = false; - } + while (m_events.empty()) + m_impl->ProcessEvents(true); - if (!m_events.empty()) - { if (event) *event = m_events.front(); @@ -612,19 +598,33 @@ namespace Nz return true; } + else + { + LockGuard lock(m_eventMutex); - return false; - #else - while (m_events.empty()) - m_impl->ProcessEvents(true); + if (m_events.empty()) + { + m_waitForEvent = true; + m_eventConditionMutex.Lock(); + m_eventMutex.Unlock(); + m_eventCondition.Wait(&m_eventConditionMutex); + m_eventMutex.Lock(); + m_eventConditionMutex.Unlock(); + m_waitForEvent = false; + } - if (event) - *event = m_events.front(); + if (!m_events.empty()) + { + if (event) + *event = m_events.front(); - m_events.pop(); + m_events.pop(); - return true; - #endif + return true; + } + + return false; + } } bool Window::OnWindowCreated() diff --git a/src/Nazara/Utility/X11/InputImpl.cpp b/src/Nazara/Utility/X11/InputImpl.cpp index e21fdae96..7083100db 100644 --- a/src/Nazara/Utility/X11/InputImpl.cpp +++ b/src/Nazara/Utility/X11/InputImpl.cpp @@ -23,32 +23,32 @@ namespace Nz switch (key) { // Lettres - case Keyboard::A: keysym = XK_A; break; - case Keyboard::B: keysym = XK_B; break; - case Keyboard::C: keysym = XK_C; break; - case Keyboard::D: keysym = XK_D; break; - case Keyboard::E: keysym = XK_E; break; - case Keyboard::F: keysym = XK_F; break; - case Keyboard::G: keysym = XK_G; break; - case Keyboard::H: keysym = XK_H; break; - case Keyboard::I: keysym = XK_I; break; - case Keyboard::J: keysym = XK_J; break; - case Keyboard::K: keysym = XK_K; break; - case Keyboard::L: keysym = XK_L; break; - case Keyboard::M: keysym = XK_M; break; - case Keyboard::N: keysym = XK_N; break; - case Keyboard::O: keysym = XK_O; break; - case Keyboard::P: keysym = XK_P; break; - case Keyboard::Q: keysym = XK_Q; break; - case Keyboard::R: keysym = XK_R; break; - case Keyboard::S: keysym = XK_S; break; - case Keyboard::T: keysym = XK_T; break; - case Keyboard::U: keysym = XK_U; break; - case Keyboard::V: keysym = XK_V; break; - case Keyboard::W: keysym = XK_W; break; - case Keyboard::X: keysym = XK_X; break; - case Keyboard::Y: keysym = XK_Y; break; - case Keyboard::Z: keysym = XK_Z; break; + case Keyboard::A: keysym = XK_a; break; + case Keyboard::B: keysym = XK_b; break; + case Keyboard::C: keysym = XK_c; break; + case Keyboard::D: keysym = XK_d; break; + case Keyboard::E: keysym = XK_e; break; + case Keyboard::F: keysym = XK_f; break; + case Keyboard::G: keysym = XK_g; break; + case Keyboard::H: keysym = XK_h; break; + case Keyboard::I: keysym = XK_i; break; + case Keyboard::J: keysym = XK_j; break; + case Keyboard::K: keysym = XK_k; break; + case Keyboard::L: keysym = XK_l; break; + case Keyboard::M: keysym = XK_m; break; + case Keyboard::N: keysym = XK_n; break; + case Keyboard::O: keysym = XK_o; break; + case Keyboard::P: keysym = XK_p; break; + case Keyboard::Q: keysym = XK_q; break; + case Keyboard::R: keysym = XK_r; break; + case Keyboard::S: keysym = XK_s; break; + case Keyboard::T: keysym = XK_t; break; + case Keyboard::U: keysym = XK_u; break; + case Keyboard::V: keysym = XK_v; break; + case Keyboard::W: keysym = XK_w; break; + case Keyboard::X: keysym = XK_x; break; + case Keyboard::Y: keysym = XK_y; break; + case Keyboard::Z: keysym = XK_z; break; // Touches de fonction case Keyboard::F1: keysym = XK_F1; break; @@ -248,6 +248,8 @@ namespace Nz xcb_keysym_t keySym = GetKeySym(key); + xcb_keycode_t realKeyCode = XCB_NO_SYMBOL; + xcb_key_symbols_t* keySymbols = X11::XCBKeySymbolsAlloc(connection); if (!keySymbols) { @@ -261,6 +263,20 @@ namespace Nz NazaraError("Failed to get key code"); return false; } + + // One keysym is associated with multiple key codes, we have to find the matching one ... + int i = 0; + while (keyCode.get()[i] != XCB_NO_SYMBOL) + { + xcb_keycode_t toTry = keyCode.get()[i]; + if (keySym == xcb_key_symbols_get_keysym(keySymbols, toTry, 0)) + { + realKeyCode = toTry; + break; + } + ++i; + } + X11::XCBKeySymbolsFree(keySymbols); ScopedXCB error(nullptr); @@ -281,7 +297,7 @@ namespace Nz } // Check our keycode - return (keymap->keys[*keyCode.get() / 8] & (1 << (*keyCode.get() % 8))) != 0; + return (keymap->keys[realKeyCode / 8] & (1 << (realKeyCode % 8))) != 0; } bool EventImpl::IsMouseButtonPressed(Mouse::Button button) diff --git a/src/Nazara/Utility/X11/WindowImpl.cpp b/src/Nazara/Utility/X11/WindowImpl.cpp index 72b85912a..297583a0f 100644 --- a/src/Nazara/Utility/X11/WindowImpl.cpp +++ b/src/Nazara/Utility/X11/WindowImpl.cpp @@ -203,17 +203,18 @@ namespace Nz // Set the window's name SetTitle(title); - #if NAZARA_UTILITY_THREADED_WINDOW - Mutex mutex; - ConditionVariable condition; - m_threadActive = true; + if (m_style & WindowStyle_Threaded) + { + Mutex mutex; + ConditionVariable condition; + m_threadActive = true; - // We wait that thread is well launched - mutex.Lock(); - m_thread = Thread(WindowThread, this, &mutex, &condition); - condition.Wait(&mutex); - mutex.Unlock(); - #endif + // Wait until the thread is ready + mutex.Lock(); + m_thread = Thread(WindowThread, this, &mutex, &condition); + condition.Wait(&mutex); + mutex.Unlock(); + } // Set fullscreen video mode and switch to fullscreen if necessary if (fullscreen) @@ -275,13 +276,15 @@ namespace Nz { if (m_ownsWindow) { - #if NAZARA_UTILITY_THREADED_WINDOW - if (m_thread.IsJoinable()) + if (m_style & WindowStyle_Threaded) { - m_threadActive = false; - m_thread.Join(); + if (m_thread.IsJoinable()) + { + m_threadActive = false; + m_thread.Join(); + } } - #else + // Destroy the window if (m_window && m_ownsWindow) { @@ -293,13 +296,11 @@ namespace Nz xcb_destroy_window( connection, m_window - )) - ) + ))) NazaraError("Failed to destroy window"); xcb_flush(connection); } - #endif } else SetEventListener(false); @@ -1247,7 +1248,7 @@ namespace Nz char32_t codePoint = GetRepresentation(keysym); - // WTF if (std::isprint(codePoint, std::locale(""))) + handle combining ? + // if (std::isprint(codePoint)) Is not working ? + handle combining ? { WindowEvent event; event.type = Nz::WindowEventType_TextEntered; @@ -1405,7 +1406,7 @@ namespace Nz // Catch reparent events to properly apply fullscreen on // some "strange" window managers (like Awesome) which // seem to make use of temporary parents during mapping - if (m_style & Nz::WindowStyle_Fullscreen) + if (m_style & WindowStyle_Fullscreen) SwitchToFullscreen(); break; @@ -1685,12 +1686,11 @@ namespace Nz )); } - #if NAZARA_UTILITY_THREADED_WINDOW void WindowImpl::WindowThread(WindowImpl* window, Mutex* mutex, ConditionVariable* condition) { mutex->Lock(); condition->Signal(); - mutex->Unlock(); // mutex et condition sont considérés invalides à partir d'ici + mutex->Unlock(); // mutex and condition may be destroyed after this line if (!window->m_window) return; @@ -1700,5 +1700,4 @@ namespace Nz window->Destroy(); } - #endif } diff --git a/src/Nazara/Utility/X11/WindowImpl.hpp b/src/Nazara/Utility/X11/WindowImpl.hpp index 6096dcac2..70a699421 100644 --- a/src/Nazara/Utility/X11/WindowImpl.hpp +++ b/src/Nazara/Utility/X11/WindowImpl.hpp @@ -20,10 +20,8 @@ namespace Nz { - #if NAZARA_UTILITY_THREADED_WINDOW class ConditionVariable; class Mutex; - #endif class Cursor; class Icon; class VideoMode; @@ -103,25 +101,19 @@ namespace Nz bool UpdateNormalHints(); void UpdateEventQueue(xcb_generic_event_t* event); - #if NAZARA_UTILITY_THREADED_WINDOW static void WindowThread(WindowImpl* window, Mutex* mutex, ConditionVariable* condition); - #endif xcb_window_t m_window; xcb_screen_t* m_screen; xcb_randr_get_screen_info_reply_t m_oldVideoMode; xcb_size_hints_t m_size_hints; - UInt32 m_style; - #if NAZARA_UTILITY_THREADED_WINDOW Thread m_thread; - #endif + UInt32 m_style; Window* m_parent; bool m_eventListener; bool m_ownsWindow; bool m_smoothScrolling; - #if NAZARA_UTILITY_THREADED_WINDOW bool m_threadActive; - #endif short m_scrolling; Vector2i m_mousePos; bool m_keyRepeat; diff --git a/tests/Engine/Core/Bitset.cpp b/tests/Engine/Core/Bitset.cpp index 124556170..b06a38aa8 100644 --- a/tests/Engine/Core/Bitset.cpp +++ b/tests/Engine/Core/Bitset.cpp @@ -1,116 +1,308 @@ +#include #include #include - +#include #include +#include + +template void Check(const char* title); +template void CheckAppend(const char* title); +template void CheckBitOps(const char* title); +template void CheckConstructor(const char* title); +template void CheckCopyMoveSwap(const char* title); +template void CheckRead(const char* title); +template void CheckReverse(const char* title); SCENARIO("Bitset", "[CORE][BITSET]") { - GIVEN("Allocate and constructor") + Check("Bitset made of 8bits blocks"); + Check("Bitset made of 16bits blocks"); + Check("Bitset made of 32bits blocks"); + Check("Bitset made of 64bits blocks"); +} + +template +void Check(const char* title) +{ + CheckConstructor(title); + CheckCopyMoveSwap(title); + + CheckBitOps(title); + + CheckAppend(title); + CheckRead(title); + CheckReverse(title); +} + +template +void CheckAppend(const char* title) +{ + SECTION(title) { - Nz::Bitset<> bitset(3, false); - - THEN("Capacity is 3 and size is 3") + GIVEN("An empty bitset filled by bytes") { - CHECK(bitset.GetSize() == 3); - CHECK(bitset.GetCapacity() >= 3); - } - } + #define BitVal1 00110111 + #define BitVal2 11011110 + #define BitVal3 01000010 + std::array data = {{NazaraPrefixMacro(BitVal1, 0b), NazaraPrefixMacro(BitVal2, 0b), NazaraPrefixMacro(BitVal3, 0b)}}; + const char result[] = NazaraStringifyMacro(BitVal3) NazaraStringifyMacro(BitVal2) NazaraStringifyMacro(BitVal1); + std::size_t resultLength = Nz::CountOf(result) - 1; + std::size_t bitCount = data.size() * 8; + #undef BitVal1 + #undef BitVal2 + #undef BitVal3 - GIVEN("Iterator and default constructor") - { - Nz::String anotherDataString("0101"); - Nz::Bitset<> defaultByte; - Nz::Bitset<> anotherData(anotherDataString.GetConstBuffer()); - - WHEN("We assign 'anotherData'") - { - defaultByte = anotherDataString; - CHECK(anotherData == defaultByte); - CHECK(defaultByte.GetSize() == 4); - CHECK(defaultByte.GetCapacity() >= 4); - CHECK(anotherData.GetSize() == 4); - CHECK(anotherData.GetCapacity() >= 4); - } - } - - GIVEN("Copy and Move constructor") - { - Nz::Bitset<> originalArray(3, true); - - WHEN("We copy") - { - Nz::Bitset<> copyBitset(originalArray); - - THEN("We get a copy") - { - CHECK(copyBitset == originalArray); - - AND_WHEN("We modify one") + std::array, 7> tests = { { - for (std::size_t i = 0; i < copyBitset.GetSize(); ++i) - copyBitset[i] = false; - - THEN("They are no more equal") - { - CHECK(copyBitset != originalArray); - CHECK(copyBitset == Nz::Bitset<>(3, false)); - } + {"We append bits one by one", 1}, + {"We append bits two by two", 2}, + {"We append bits three by three", 3}, + {"We append bits four by four", 4}, + {"We append bits six by six", 6}, + {"We append bits byte by byte", 8}, + {"We append bits twelve by twelve", 12} } - } - } + }; - WHEN("We move") - { - Nz::Bitset<> moveBitset(std::move(originalArray)); - - THEN("These results are expected") + for (auto& pair : tests) { - REQUIRE(moveBitset == Nz::Bitset<>(3, true)); - REQUIRE(originalArray.GetCapacity() == 0); - } - } - } + WHEN(pair.first) + { + Nz::Bitset bitset; - GIVEN("Three bitsets") - { - Nz::Bitset<> first("01001"); - Nz::Bitset<> second("10110"); - Nz::Bitset<> third; + for (std::size_t i = 0; i < bitCount; i += pair.second) + { + Nz::UInt16 value = data[i / 8] >> (i % 8); + if ((i % 8) + pair.second > 8 && i/8 != data.size()-1) + value |= static_cast(data[i / 8 + 1]) << (8 - (i % 8)); - WHEN("We swap first and third, then second and third and finally third and first") - { - Nz::Bitset<> oldFirst(first); - Nz::Bitset<> oldSecond(second); + bitset.AppendBits(value, pair.second); + } - first.Swap(third); - std::swap(second, third); - third.Swap(first); + REQUIRE(bitset.GetSize() == bitCount); - THEN("First and second have been swapped and third is still empty.") - { - REQUIRE(oldFirst == second); - REQUIRE(oldSecond == first); - REQUIRE(third.GetSize() == 0); - } - } - } + Nz::Bitset expectedBitset(result); - GIVEN("Two bitsets") - { - Nz::Bitset<> first("01001"); - Nz::Bitset<> second("10111"); - - WHEN("We perform operators") - { - Nz::Bitset<> andBitset = first & second; - Nz::Bitset<> orBitset = first | second; - Nz::Bitset<> xorBitset = first ^ second; - - THEN("They should operate as logical operators") - { - REQUIRE(andBitset == Nz::Bitset<>("00001")); - REQUIRE(orBitset == Nz::Bitset<>("11111")); - REQUIRE(xorBitset == Nz::Bitset<>("11110")); + CHECK(bitset == expectedBitset); + CHECK(bitset.GetBlockCount() == (bitCount / bitset.bitsPerBlock + std::min(1, bitCount % bitset.bitsPerBlock))); + } + } + } + } +} + +template +void CheckBitOps(const char* title) +{ + SECTION(title) + { + GIVEN("Two bitsets") + { + Nz::Bitset first("01001"); + Nz::Bitset second("10111"); + + WHEN("We perform operators") + { + Nz::Bitset andBitset = first & second; + Nz::Bitset orBitset = first | second; + Nz::Bitset xorBitset = first ^ second; + + THEN("They should operate as logical operators") + { + CHECK(andBitset == Nz::Bitset("00001")); + CHECK(orBitset == Nz::Bitset("11111")); + CHECK(xorBitset == Nz::Bitset("11110")); + } + } + } + } +} + +template +void CheckConstructor(const char* title) +{ + SECTION(title) + { + GIVEN("Allocate and constructor") + { + Nz::Bitset bitset(3, false); + + THEN("Capacity is 3 and size is 3") + { + CHECK(bitset.GetSize() == 3); + CHECK(bitset.GetCapacity() >= 3); + } + } + + GIVEN("Iterator and default constructor") + { + Nz::String anotherDataString("0101"); + Nz::Bitset defaultByte; + Nz::Bitset anotherData(anotherDataString.GetConstBuffer()); + + WHEN("We assign 'anotherData'") + { + defaultByte = anotherDataString; + CHECK(anotherData == defaultByte); + CHECK(defaultByte.GetSize() == 4); + CHECK(defaultByte.GetCapacity() >= 4); + CHECK(anotherData.GetSize() == 4); + CHECK(anotherData.GetCapacity() >= 4); + } + } + } +} + +template +void CheckCopyMoveSwap(const char* title) +{ + SECTION(title) + { + GIVEN("Copy and Move constructor") + { + Nz::Bitset originalArray(3, true); + + WHEN("We copy") + { + Nz::Bitset copyBitset(originalArray); + + THEN("We get a copy") + { + CHECK(copyBitset == originalArray); + + AND_WHEN("We modify one") + { + for (std::size_t i = 0; i < copyBitset.GetSize(); ++i) + copyBitset[i] = false; + + THEN("They are no more equal") + { + CHECK(copyBitset != originalArray); + CHECK(copyBitset == Nz::Bitset(3, false)); + } + } + } + } + + WHEN("We move") + { + Nz::Bitset moveBitset(std::move(originalArray)); + + THEN("These results are expected") + { + CHECK(moveBitset == Nz::Bitset(3, true)); + CHECK(originalArray.GetCapacity() == 0); + } + } + } + + GIVEN("Three bitsets") + { + Nz::Bitset first("01001"); + Nz::Bitset second("10110"); + Nz::Bitset third; + + WHEN("We swap first and third, then second and third and finally third and first") + { + Nz::Bitset oldFirst(first); + Nz::Bitset oldSecond(second); + + first.Swap(third); + std::swap(second, third); + third.Swap(first); + + THEN("First and second have been swapped and third is still empty.") + { + CHECK(oldFirst == second); + CHECK(oldSecond == first); + CHECK(third.GetSize() == 0); + } + } + } + } +} + +template +void CheckRead(const char* title) +{ + SECTION(title) + { + GIVEN("An empty bitset filled by reading") + { + #define BitVal1 10010101 + #define BitVal2 11010010 + #define BitVal3 01101010 + std::array data = {{NazaraPrefixMacro(BitVal1, 0b), NazaraPrefixMacro(BitVal2, 0b), NazaraPrefixMacro(BitVal3, 0b)}}; + const char result[] = NazaraStringifyMacro(BitVal3) NazaraStringifyMacro(BitVal2) NazaraStringifyMacro(BitVal1); + std::size_t resultLength = Nz::CountOf(result) - 1; + std::size_t bitCount = data.size() * 8; + #undef BitVal1 + #undef BitVal2 + #undef BitVal3 + + std::array, 8> tests = { + { + {"We read bits one by one", 1}, + {"We read bits two by two", 2}, + {"We read bits three by three", 3}, + {"We read bits four by four", 4}, + {"We read bits six by six", 6}, + {"We read bits byte by byte", 8}, + {"We read bits twelve by twelve", 12}, + {"We read bits all at once", 24} + } + }; + + for (auto& pair : tests) + { + WHEN(pair.first) + { + Nz::Bitset bitset; + + auto seq = bitset.Read(data.data(), pair.second); + for (std::size_t i = pair.second; i < bitCount; i += pair.second) + seq = bitset.Read(seq, pair.second); + + REQUIRE(bitset.GetSize() == bitCount); + + Nz::Bitset expectedBitset(result); + + CHECK(bitset == expectedBitset); + CHECK(bitset.GetBlockCount() == (bitCount / bitset.bitsPerBlock + std::min(1, bitCount % bitset.bitsPerBlock))); + } + } + } + } +} + +template +void CheckReverse(const char* title) +{ + SECTION(title) + { + GIVEN("A bitset") + { + Nz::String bits = "010011100010001101001111"; + Nz::Bitset expected(bits); + + WHEN("We reverse the order of bits") + { + Nz::Bitset bitset(bits); + bitset.Reverse(); + + THEN("The order of bits should be reversed") + { + CHECK(bitset == Nz::Bitset(bits.Reversed())); + } + AND_WHEN("We reverse the bit order again") + { + bitset.Reverse(); + + THEN("It should be back to normal") + { + CHECK(bitset == expected); + } + } } } } diff --git a/tests/Engine/Graphics/ParticleDeclaration.cpp b/tests/Engine/Graphics/ParticleDeclaration.cpp index 1bc1739d3..4cde9c5d2 100644 --- a/tests/Engine/Graphics/ParticleDeclaration.cpp +++ b/tests/Engine/Graphics/ParticleDeclaration.cpp @@ -11,10 +11,10 @@ SCENARIO("ParticleDeclaration", "[GRAPHICS][PARTICLEDECLARATION]") { bool enabled; Nz::ComponentType type; - unsigned int offset; + std::size_t offset; particleDeclaration->GetComponent(Nz::ParticleComponent_Position, &enabled, &type, &offset); REQUIRE(enabled); - unsigned int oldStride = particleDeclaration->GetStride(); + std::size_t oldStride = particleDeclaration->GetStride(); particleDeclaration->DisableComponent(Nz::ParticleComponent_Position); REQUIRE(oldStride != particleDeclaration->GetStride());