Merge branch 'master' into console-widget

This commit is contained in:
Lynix 2017-08-30 16:14:53 +02:00
commit 1e5e1d5f6d
352 changed files with 12780 additions and 4568 deletions

View File

@ -27,17 +27,17 @@
#ifndef NAZARA_CONFIG_MODULENAME_HPP #ifndef NAZARA_CONFIG_MODULENAME_HPP
#define NAZARA_CONFIG_MODULENAME_HPP #define NAZARA_CONFIG_MODULENAME_HPP
/// Chaque modification d'un paramètre du module nécessite une recompilation de celui-ci /// Each modification of a parameter needs a recompilation of the module
// Utilise le MemoryManager pour gérer les allocations dynamiques (détecte les leaks au prix d'allocations/libérations dynamiques plus lentes) // Use the MemoryManager to manage dynamic allocations (can detect memory leak but allocations/frees are slower)
#define NAZARA_MODULENAME_MANAGE_MEMORY 0 #define NAZARA_MODULENAME_MANAGE_MEMORY 0
// Active les tests de sécurité basés sur le code (Conseillé pour le développement) // Activate the security tests based on the code (Advised for development)
#define NAZARA_MODULENAME_SAFE 1 #define NAZARA_MODULENAME_SAFE 1
/// Chaque modification d'un paramètre ci-dessous implique une modification (souvent mineure) du code /// Each modification of a parameter following implies a modification (often minor) of the code
/// Vérification des valeurs et types de certaines constantes /// Checking the values and types of certain constants
#include <Nazara/ModuleName/ConfigCheck.hpp> #include <Nazara/ModuleName/ConfigCheck.hpp>
#if !defined(NAZARA_STATIC) #if !defined(NAZARA_STATIC)

View File

@ -7,13 +7,13 @@
#ifndef NAZARA_CONFIG_CHECK_MODULENAME_HPP #ifndef NAZARA_CONFIG_CHECK_MODULENAME_HPP
#define NAZARA_CONFIG_CHECK_MODULENAME_HPP #define NAZARA_CONFIG_CHECK_MODULENAME_HPP
/// Ce fichier sert à vérifier la valeur des constantes du fichier Config.hpp /// This file is used to check the constant values defined in Config.hpp
#include <type_traits> #include <type_traits>
#define CheckType(name, type, err) static_assert(std::is_ ##type <decltype(name)>::value, #type err) #define CheckType(name, type, err) static_assert(std::is_ ##type <decltype(name)>::value, #type err)
#define CheckTypeAndVal(name, type, op, val, err) static_assert(std::is_ ##type <decltype(name)>::value && name op val, #type err) #define CheckTypeAndVal(name, type, op, val, err) static_assert(std::is_ ##type <decltype(name)>::value && name op val, #type err)
// On force la valeur de MANAGE_MEMORY en mode debug // We force the value of MANAGE_MEMORY in debug
#if defined(NAZARA_DEBUG) && !NAZARA_MODULENAME_MANAGE_MEMORY #if defined(NAZARA_DEBUG) && !NAZARA_MODULENAME_MANAGE_MEMORY
#undef NAZARA_MODULENAME_MANAGE_MEMORY #undef NAZARA_MODULENAME_MANAGE_MEMORY
#define NAZARA_MODULENAME_MANAGE_MEMORY 0 #define NAZARA_MODULENAME_MANAGE_MEMORY 0

View File

@ -2,7 +2,7 @@
// This file is part of the "Nazara Engine - Module name" // This file is part of the "Nazara Engine - Module name"
// For conditions of distribution and use, see copyright notice in Config.hpp // 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 // We suppose that Debug.hpp is already included, same goes for Config.hpp
#if NAZARA_MODULENAME_MANAGE_MEMORY #if NAZARA_MODULENAME_MANAGE_MEMORY
#undef delete #undef delete
#undef new #undef new

View File

@ -23,7 +23,7 @@
#include <Nazara/Lua/LuaInstance.hpp> #include <Nazara/Lua/LuaInstance.hpp>
#include <Nazara/Graphics/TextSprite.hpp> #include <Nazara/Graphics/TextSprite.hpp>
#include <Nazara/Renderer/RenderTarget.hpp> #include <Nazara/Renderer/RenderTarget.hpp>
#include <Nazara/Utility/Window.hpp> #include <Nazara/Platform/Window.hpp>
#endif #endif
namespace Ndk namespace Ndk

View File

@ -23,20 +23,22 @@ namespace Ndk
using Factory = std::function<BaseComponent*()>; using Factory = std::function<BaseComponent*()>;
BaseComponent(ComponentIndex componentIndex); BaseComponent(ComponentIndex componentIndex);
BaseComponent(const BaseComponent&) = default;
BaseComponent(BaseComponent&&) = default; BaseComponent(BaseComponent&&) = default;
virtual ~BaseComponent(); virtual ~BaseComponent();
virtual std::unique_ptr<BaseComponent> Clone() const = 0; virtual std::unique_ptr<BaseComponent> Clone() const = 0;
inline const EntityHandle& GetEntity() const;
ComponentIndex GetIndex() const; ComponentIndex GetIndex() const;
inline static ComponentIndex GetMaxComponentIndex(); inline static ComponentIndex GetMaxComponentIndex();
BaseComponent& operator=(const BaseComponent&) = default; BaseComponent& operator=(const BaseComponent&) = delete;
BaseComponent& operator=(BaseComponent&&) = default; BaseComponent& operator=(BaseComponent&&) = default;
protected: protected:
BaseComponent(const BaseComponent&) = default;
ComponentIndex m_componentIndex; ComponentIndex m_componentIndex;
EntityHandle m_entity; EntityHandle m_entity;
@ -47,6 +49,7 @@ namespace Ndk
virtual void OnComponentAttached(BaseComponent& component); virtual void OnComponentAttached(BaseComponent& component);
virtual void OnComponentDetached(BaseComponent& component); virtual void OnComponentDetached(BaseComponent& component);
virtual void OnDetached(); virtual void OnDetached();
virtual void OnEntityDestruction();
void SetEntity(Entity* entity); void SetEntity(Entity* entity);

View File

@ -19,11 +19,19 @@ namespace Ndk
{ {
} }
/*!
* \brief Gets the entity owning this component
* \return A handle to the entity owning this component, may be invalid if no entity owns it.
*/
inline const EntityHandle& BaseComponent::GetEntity() const
{
return m_entity;
}
/*! /*!
* \brief Gets the index of the component * \brief Gets the index of the component
* \return Index of the component * \return Index of the component
*/ */
inline ComponentIndex BaseComponent::GetIndex() const inline ComponentIndex BaseComponent::GetIndex() const
{ {
return m_componentIndex; return m_componentIndex;

View File

@ -9,6 +9,7 @@
#include <Nazara/Core/Bitset.hpp> #include <Nazara/Core/Bitset.hpp>
#include <NDK/Entity.hpp> #include <NDK/Entity.hpp>
#include <NDK/EntityList.hpp>
#include <vector> #include <vector>
namespace Ndk namespace Ndk
@ -33,7 +34,7 @@ namespace Ndk
bool Filters(const Entity* entity) const; bool Filters(const Entity* entity) const;
inline const std::vector<EntityHandle>& GetEntities() const; inline const EntityList& GetEntities() const;
inline SystemIndex GetIndex() const; inline SystemIndex GetIndex() const;
inline int GetUpdateOrder() const; inline int GetUpdateOrder() const;
inline float GetUpdateRate() const; inline float GetUpdateRate() const;
@ -84,12 +85,11 @@ namespace Ndk
static inline bool Initialize(); static inline bool Initialize();
static inline void Uninitialize(); static inline void Uninitialize();
std::vector<EntityHandle> m_entities;
Nz::Bitset<Nz::UInt64> m_entityBits;
Nz::Bitset<> m_excludedComponents; Nz::Bitset<> m_excludedComponents;
mutable Nz::Bitset<> m_filterResult; mutable Nz::Bitset<> m_filterResult;
Nz::Bitset<> m_requiredAnyComponents; Nz::Bitset<> m_requiredAnyComponents;
Nz::Bitset<> m_requiredComponents; Nz::Bitset<> m_requiredComponents;
EntityList m_entities;
SystemIndex m_systemIndex; SystemIndex m_systemIndex;
World* m_world; World* m_world;
bool m_updateEnabled; bool m_updateEnabled;

View File

@ -56,7 +56,7 @@ namespace Ndk
* \return A constant reference to the list of entities * \return A constant reference to the list of entities
*/ */
inline const std::vector<EntityHandle>& BaseSystem::GetEntities() const inline const EntityList& BaseSystem::GetEntities() const
{ {
return m_entities; return m_entities;
} }
@ -121,10 +121,7 @@ namespace Ndk
inline bool BaseSystem::HasEntity(const Entity* entity) const inline bool BaseSystem::HasEntity(const Entity* entity) const
{ {
if (!entity) return m_entities.Has(entity);
return false;
return m_entityBits.UnboundedTest(entity->GetId());
} }
/*! /*!
@ -288,9 +285,7 @@ namespace Ndk
{ {
NazaraAssert(entity, "Invalid entity"); NazaraAssert(entity, "Invalid entity");
m_entities.emplace_back(entity); m_entities.Insert(entity);
m_entityBits.UnboundedSet(entity->GetId(), true);
entity->RegisterSystem(m_systemIndex); entity->RegisterSystem(m_systemIndex);
OnEntityAdded(entity); OnEntityAdded(entity);
@ -308,14 +303,7 @@ namespace Ndk
{ {
NazaraAssert(entity, "Invalid entity"); NazaraAssert(entity, "Invalid entity");
auto it = std::find(m_entities.begin(), m_entities.end(), *entity); m_entities.Remove(entity);
NazaraAssert(it != m_entities.end(), "Entity is not part of this system");
// To avoid moving a lot of handles, we swap and pop
std::swap(*it, m_entities.back());
m_entities.pop_back(); // We get it out of the vector
m_entityBits.Reset(entity->GetId());
entity->UnregisterSystem(m_systemIndex); entity->UnregisterSystem(m_systemIndex);
OnEntityRemoved(entity); // And we alert our callback OnEntityRemoved(entity); // And we alert our callback
@ -360,7 +348,7 @@ namespace Ndk
} }
/*! /*!
* \brief Uninitializes the BaseSystem * \brief Uninitialize the BaseSystem
*/ */
inline void BaseSystem::Uninitialize() inline void BaseSystem::Uninitialize()

View File

@ -12,9 +12,9 @@
#include <NDK/EntityOwner.hpp> #include <NDK/EntityOwner.hpp>
#include <NDK/World.hpp> #include <NDK/World.hpp>
#include <Nazara/Graphics/Sprite.hpp> #include <Nazara/Graphics/Sprite.hpp>
#include <Nazara/Utility/Cursor.hpp> #include <Nazara/Platform/Cursor.hpp>
#include <Nazara/Utility/Event.hpp> #include <Nazara/Platform/Event.hpp>
#include <Nazara/Utility/Mouse.hpp> #include <Nazara/Platform/Mouse.hpp>
#include <Nazara/Utility/Node.hpp> #include <Nazara/Utility/Node.hpp>
#include <limits> #include <limits>

View File

@ -9,8 +9,8 @@
#include <NDK/Prerequesites.hpp> #include <NDK/Prerequesites.hpp>
#include <NDK/BaseWidget.hpp> #include <NDK/BaseWidget.hpp>
#include <Nazara/Utility/CursorController.hpp> #include <Nazara/Platform/CursorController.hpp>
#include <Nazara/Utility/EventHandler.hpp> #include <Nazara/Platform/EventHandler.hpp>
namespace Ndk namespace Ndk
{ {
@ -44,13 +44,13 @@ namespace Ndk
void UnregisterWidget(std::size_t index); void UnregisterWidget(std::size_t index);
private: private:
void OnMouseButtonPressed(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseButtonEvent& event); void OnEventMouseButtonPressed(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseButtonEvent& event);
void OnMouseButtonRelease(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseButtonEvent& event); void OnEventMouseButtonRelease(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseButtonEvent& event);
void OnMouseMoved(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseMoveEvent& event); void OnEventMouseMoved(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseMoveEvent& event);
void OnMouseLeft(const Nz::EventHandler* eventHandler); void OnEventMouseLeft(const Nz::EventHandler* eventHandler);
void OnKeyPressed(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::KeyEvent& event); void OnEventKeyPressed(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::KeyEvent& event);
void OnKeyReleased(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::KeyEvent& event); void OnEventKeyReleased(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::KeyEvent& event);
void OnTextEntered(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::TextEvent& event); void OnEventTextEntered(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::TextEvent& event);
struct WidgetBox struct WidgetBox
{ {

View File

@ -3,7 +3,7 @@
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp // For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#include <NDK/Canvas.hpp> #include <NDK/Canvas.hpp>
#include <Nazara/Utility/Cursor.hpp> #include <Nazara/Platform/Cursor.hpp>
namespace Ndk namespace Ndk
{ {
@ -20,13 +20,13 @@ namespace Ndk
RegisterToCanvas(); RegisterToCanvas();
// Connect to every meaningful event // Connect to every meaningful event
m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, this, &Canvas::OnKeyPressed); m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, this, &Canvas::OnEventKeyPressed);
m_keyReleasedSlot.Connect(eventHandler.OnKeyReleased, this, &Canvas::OnKeyReleased); m_keyReleasedSlot.Connect(eventHandler.OnKeyReleased, this, &Canvas::OnEventKeyReleased);
m_mouseButtonPressedSlot.Connect(eventHandler.OnMouseButtonPressed, this, &Canvas::OnMouseButtonPressed); m_mouseButtonPressedSlot.Connect(eventHandler.OnMouseButtonPressed, this, &Canvas::OnEventMouseButtonPressed);
m_mouseButtonReleasedSlot.Connect(eventHandler.OnMouseButtonReleased, this, &Canvas::OnMouseButtonRelease); m_mouseButtonReleasedSlot.Connect(eventHandler.OnMouseButtonReleased, this, &Canvas::OnEventMouseButtonRelease);
m_mouseMovedSlot.Connect(eventHandler.OnMouseMoved, this, &Canvas::OnMouseMoved); m_mouseMovedSlot.Connect(eventHandler.OnMouseMoved, this, &Canvas::OnEventMouseMoved);
m_mouseLeftSlot.Connect(eventHandler.OnMouseLeft, this, &Canvas::OnMouseLeft); m_mouseLeftSlot.Connect(eventHandler.OnMouseLeft, this, &Canvas::OnEventMouseLeft);
m_textEnteredSlot.Connect(eventHandler.OnTextEntered, this, &Canvas::OnTextEntered); m_textEnteredSlot.Connect(eventHandler.OnTextEntered, this, &Canvas::OnEventTextEntered);
// Disable padding by default // Disable padding by default
SetPadding(0.f, 0.f, 0.f, 0.f); SetPadding(0.f, 0.f, 0.f, 0.f);

View File

@ -44,7 +44,7 @@ namespace Ndk
const Nz::Frustumf& GetFrustum() const override; const Nz::Frustumf& GetFrustum() const override;
inline unsigned int GetLayer() const; inline unsigned int GetLayer() const;
const Nz::Matrix4f& GetProjectionMatrix() const override; const Nz::Matrix4f& GetProjectionMatrix() const override;
inline Nz::ProjectionType GetProjectionType() const; Nz::ProjectionType GetProjectionType() const override;
inline const Nz::Vector2f& GetSize() const; inline const Nz::Vector2f& GetSize() const;
const Nz::RenderTarget* GetTarget() const override; const Nz::RenderTarget* GetTarget() const override;
inline const Nz::Rectf& GetTargetRegion() const; inline const Nz::Rectf& GetTargetRegion() const;

View File

@ -117,16 +117,6 @@ namespace Ndk
return m_layer; return m_layer;
} }
/*!
* \brief Gets the projection type of the camera
* \return Projection type of the camera
*/
inline Nz::ProjectionType CameraComponent::GetProjectionType() const
{
return m_projectionType;
}
/*! /*!
* \brief Gets the size of the camera * \brief Gets the size of the camera
* \return Size of the camera * \return Size of the camera

View File

@ -29,6 +29,7 @@ namespace Ndk
CollisionComponent2D(const CollisionComponent2D& collision); CollisionComponent2D(const CollisionComponent2D& collision);
~CollisionComponent2D() = default; ~CollisionComponent2D() = default;
Nz::Rectf GetAABB() const;
const Nz::Collider2DRef& GetGeom() const; const Nz::Collider2DRef& GetGeom() const;
void SetGeom(Nz::Collider2DRef geom); void SetGeom(Nz::Collider2DRef geom);

View File

@ -34,6 +34,16 @@ namespace Ndk
{ {
} }
/*!
* \brief Gets the collision box representing the entity
* \return The physics collision box
*/
inline Nz::Rectf CollisionComponent2D::GetAABB() const
{
return m_staticBody->GetAABB();
}
/*! /*!
* \brief Gets the geometry representing the entity * \brief Gets the geometry representing the entity
* \return A constant reference to the physics geometry * \return A constant reference to the physics geometry

View File

@ -51,6 +51,9 @@ namespace Ndk
inline void RemoveFromCullingList(GraphicsComponentCullingList* cullingList) const; inline void RemoveFromCullingList(GraphicsComponentCullingList* cullingList) const;
inline void UpdateLocalMatrix(const Nz::InstancedRenderable* instancedRenderable, const Nz::Matrix4f& localMatrix);
inline void UpdateRenderOrder(const Nz::InstancedRenderable* instancedRenderable, int renderOrder);
static ComponentIndex componentIndex; static ComponentIndex componentIndex;
private: private:

View File

@ -142,6 +142,32 @@ namespace Ndk
} }
} }
inline void GraphicsComponent::UpdateLocalMatrix(const Nz::InstancedRenderable* instancedRenderable, const Nz::Matrix4f& localMatrix)
{
for (auto& renderable : m_renderables)
{
if (renderable.renderable == instancedRenderable)
{
renderable.data.localMatrix = localMatrix;
InvalidateBoundingVolume();
break;
}
}
}
inline void GraphicsComponent::UpdateRenderOrder(const Nz::InstancedRenderable* instancedRenderable, int renderOrder)
{
for (auto& renderable : m_renderables)
{
if (renderable.renderable == instancedRenderable)
{
renderable.data.renderOrder = renderOrder;
break;
}
}
}
/*! /*!
* \brief Invalidates the bounding volume * \brief Invalidates the bounding volume
*/ */

View File

@ -24,7 +24,7 @@ namespace Ndk
ParticleEmitterComponent(ParticleEmitterComponent&& emitter) = default; ParticleEmitterComponent(ParticleEmitterComponent&& emitter) = default;
~ParticleEmitterComponent() = default; ~ParticleEmitterComponent() = default;
void Enable(bool active = true); inline void Enable(bool active = true);
inline bool IsActive() const; inline bool IsActive() const;

View File

@ -55,6 +55,7 @@ namespace Ndk
void OnComponentAttached(BaseComponent& component) override; void OnComponentAttached(BaseComponent& component) override;
void OnComponentDetached(BaseComponent& component) override; void OnComponentDetached(BaseComponent& component) override;
void OnDetached() override; void OnDetached() override;
void OnEntityDestruction() override;
std::unique_ptr<Nz::RigidBody2D> m_object; std::unique_ptr<Nz::RigidBody2D> m_object;
}; };

View File

@ -62,6 +62,7 @@ namespace Ndk
void OnComponentAttached(BaseComponent& component) override; void OnComponentAttached(BaseComponent& component) override;
void OnComponentDetached(BaseComponent& component) override; void OnComponentDetached(BaseComponent& component) override;
void OnDetached() override; void OnDetached() override;
void OnEntityDestruction() override;
std::unique_ptr<Nz::RigidBody3D> m_object; std::unique_ptr<Nz::RigidBody3D> m_object;
}; };

View File

@ -12,7 +12,7 @@
#include <Nazara/Core/ObjectHandle.hpp> #include <Nazara/Core/ObjectHandle.hpp>
#include <Nazara/Graphics/Sprite.hpp> #include <Nazara/Graphics/Sprite.hpp>
#include <Nazara/Graphics/TextSprite.hpp> #include <Nazara/Graphics/TextSprite.hpp>
#include <Nazara/Utility/Event.hpp> #include <Nazara/Platform/Event.hpp>
#include <Nazara/Utility/Node.hpp> #include <Nazara/Utility/Node.hpp>
#include <Nazara/Utility/SimpleTextDrawer.hpp> #include <Nazara/Utility/SimpleTextDrawer.hpp>
#include <NDK/BaseWidget.hpp> #include <NDK/BaseWidget.hpp>
@ -20,7 +20,7 @@
namespace Nz namespace Nz
{ {
class LuaInstance; class LuaState;
} }
namespace Ndk namespace Ndk
@ -34,7 +34,7 @@ namespace Ndk
class NDK_API Console : public BaseWidget, public Nz::HandledObject<Console> class NDK_API Console : public BaseWidget, public Nz::HandledObject<Console>
{ {
public: public:
Console(BaseWidget* parent, Nz::LuaInstance& instance); Console(BaseWidget* parent, Nz::LuaState& state);
Console(const Console& console) = delete; Console(const Console& console) = delete;
Console(Console&& console) = default; Console(Console&& console) = default;
~Console() = default; ~Console() = default;
@ -72,7 +72,7 @@ namespace Ndk
TextAreaWidget* m_history; TextAreaWidget* m_history;
TextAreaWidget* m_input; TextAreaWidget* m_input;
Nz::FontRef m_defaultFont; Nz::FontRef m_defaultFont;
Nz::LuaInstance& m_instance; Nz::LuaState& m_state;
unsigned int m_characterSize; unsigned int m_characterSize;
unsigned int m_maxHistoryLines; unsigned int m_maxHistoryLines;
}; };

View File

@ -9,6 +9,7 @@
#include <Nazara/Core/Bitset.hpp> #include <Nazara/Core/Bitset.hpp>
#include <Nazara/Core/HandledObject.hpp> #include <Nazara/Core/HandledObject.hpp>
#include <Nazara/Core/Signal.hpp>
#include <NDK/Algorithm.hpp> #include <NDK/Algorithm.hpp>
#include <memory> #include <memory>
#include <vector> #include <vector>
@ -16,14 +17,17 @@
namespace Ndk namespace Ndk
{ {
class BaseComponent; class BaseComponent;
class BaseSystem;
class Entity; class Entity;
class EntityList;
class World; class World;
using EntityHandle = Nz::ObjectHandle<Entity>; using EntityHandle = Nz::ObjectHandle<Entity>;
class NDK_API Entity : public Nz::HandledObject<Entity> class NDK_API Entity : public Nz::HandledObject<Entity>
{ {
friend class BaseSystem; friend BaseSystem;
friend EntityList;
friend World; friend World;
public: public:
@ -65,6 +69,8 @@ namespace Ndk
Entity& operator=(const Entity&) = delete; Entity& operator=(const Entity&) = delete;
Entity& operator=(Entity&&) = delete; Entity& operator=(Entity&&) = delete;
NazaraSignal(OnEntityDestruction, Entity* /*entity*/);
private: private:
Entity(World* world, EntityId id); Entity(World* world, EntityId id);
@ -75,13 +81,16 @@ namespace Ndk
inline Nz::Bitset<>& GetRemovedComponentBits(); inline Nz::Bitset<>& GetRemovedComponentBits();
inline void RegisterEntityList(EntityList* list);
inline void RegisterSystem(SystemIndex index); inline void RegisterSystem(SystemIndex index);
inline void SetWorld(World* world) noexcept; inline void SetWorld(World* world) noexcept;
inline void UnregisterEntityList(EntityList* list);
inline void UnregisterSystem(SystemIndex index); inline void UnregisterSystem(SystemIndex index);
std::vector<std::unique_ptr<BaseComponent>> m_components; std::vector<std::unique_ptr<BaseComponent>> m_components;
std::vector<EntityList*> m_containedInLists;
Nz::Bitset<> m_componentBits; Nz::Bitset<> m_componentBits;
Nz::Bitset<> m_removedComponentBits; Nz::Bitset<> m_removedComponentBits;
Nz::Bitset<> m_systemBits; Nz::Bitset<> m_systemBits;

View File

@ -6,6 +6,7 @@
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <Nazara/Core/StringStream.hpp> #include <Nazara/Core/StringStream.hpp>
#include <algorithm> #include <algorithm>
#include <cassert>
#include <type_traits> #include <type_traits>
#include <utility> #include <utility>
@ -257,11 +258,10 @@ namespace Ndk
return m_removedComponentBits; return m_removedComponentBits;
} }
/*! inline void Entity::RegisterEntityList(EntityList* list)
* \brief Registers a system for the entity {
* m_containedInLists.push_back(list);
* \param index Index of the system }
*/
inline void Entity::RegisterSystem(SystemIndex index) inline void Entity::RegisterSystem(SystemIndex index)
{ {
@ -289,6 +289,16 @@ namespace Ndk
* \param index Index of the system * \param index Index of the system
*/ */
inline void Entity::UnregisterEntityList(EntityList* list)
{
auto it = std::find(m_containedInLists.begin(), m_containedInLists.end(), list);
assert(it != m_containedInLists.end());
// Swap and pop idiom
*it = m_containedInLists.back();
m_containedInLists.pop_back();
}
inline void Entity::UnregisterSystem(SystemIndex index) inline void Entity::UnregisterSystem(SystemIndex index)
{ {
m_systemBits.UnboundedReset(index); m_systemBits.UnboundedReset(index);

View File

@ -15,46 +15,68 @@ namespace Ndk
{ {
class NDK_API EntityList class NDK_API EntityList
{ {
public: friend Entity;
using Container = std::vector<EntityHandle>;
EntityList() = default; public:
~EntityList() = default; class iterator;
friend iterator;
using size_type = std::size_t;
inline EntityList();
inline EntityList(const EntityList& entityList);
inline EntityList(EntityList&& entityList) noexcept;
inline ~EntityList();
inline void Clear(); inline void Clear();
inline bool Has(const Entity* entity); inline bool Has(const Entity* entity) const;
inline bool Has(EntityId entity); inline bool Has(EntityId entity) const;
inline void Insert(Entity* entity); inline void Insert(Entity* entity);
inline void Remove(Entity* entity); inline void Remove(Entity* entity);
// STL API // STL API
inline Container::iterator begin(); inline iterator begin() const;
inline Container::const_iterator begin() const;
inline Container::const_iterator cbegin() const;
inline Container::const_iterator cend() const;
inline Container::const_reverse_iterator crbegin() const;
inline Container::const_reverse_iterator crend() const;
inline bool empty() const; inline bool empty() const;
inline iterator end() const;
inline size_type size() const;
inline Container::iterator end(); inline EntityList& operator=(const EntityList& entityList);
inline Container::const_iterator end() const; inline EntityList& operator=(EntityList&& entityList) noexcept;
inline Container::reverse_iterator rbegin();
inline Container::const_reverse_iterator rbegin() const;
inline Container::reverse_iterator rend();
inline Container::const_reverse_iterator rend() const;
inline Container::size_type size() const;
private: private:
std::vector<EntityHandle> m_entities; inline std::size_t FindNext(std::size_t currentId) const;
inline World* GetWorld() const;
inline void NotifyEntityDestruction(const Entity* entity);
Nz::Bitset<Nz::UInt64> m_entityBits; Nz::Bitset<Nz::UInt64> m_entityBits;
World* m_world;
};
class NDK_API EntityList::iterator : public std::iterator<std::forward_iterator_tag, const EntityHandle>
{
friend EntityList;
public:
inline iterator(const iterator& it);
const EntityHandle& operator*() const;
inline iterator& operator=(const iterator& it);
inline iterator& operator++();
inline iterator operator++(int);
friend inline bool operator==(const iterator& lhs, const iterator& rhs);
friend inline bool operator!=(const iterator& lhs, const iterator& rhs);
friend inline void swap(iterator& lhs, iterator& rhs);
private:
inline iterator(const EntityList* world, std::size_t nextId);
std::size_t m_nextEntityId;
const EntityList* m_list;
}; };
} }

View File

@ -2,6 +2,7 @@
// This file is part of the "Nazara Development Kit" // This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp // For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#include <NDK/EntityList.hpp>
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <algorithm> #include <algorithm>
@ -14,24 +15,71 @@ namespace Ndk
*/ */
/*! /*!
* \brief Clears the set from every entities * \brief Construct a new entity list
*/ */
inline EntityList::EntityList() :
inline void EntityList::Clear() m_world(nullptr)
{ {
m_entities.clear();
m_entityBits.Clear();
} }
/*! /*!
* \brief Checks whether or not the set contains the entity * \brief Construct a new entity list by copying another one
*/
inline EntityList::EntityList(const EntityList& entityList) :
m_entityBits(entityList.m_entityBits),
m_world(entityList.m_world)
{
for (const Ndk::EntityHandle& entity : *this)
entity->RegisterEntityList(this);
}
/*!
* \brief Construct a new entity list by moving a list into this one
*/
inline EntityList::EntityList(EntityList&& entityList) noexcept :
m_entityBits(std::move(entityList.m_entityBits)),
m_world(entityList.m_world)
{
for (const Ndk::EntityHandle& entity : *this)
{
entity->UnregisterEntityList(&entityList);
entity->RegisterEntityList(this);
}
}
inline EntityList::~EntityList()
{
for (const Ndk::EntityHandle& entity : *this)
entity->UnregisterEntityList(this);
}
/*!
* \brief Clears the set from every entities
*
* \remark This resets the implicit world member, allowing you to insert entities from a different world than previously
*/
inline void EntityList::Clear()
{
for (const Ndk::EntityHandle& entity : *this)
entity->UnregisterEntityList(this);
m_entityBits.Clear();
m_world = nullptr;
}
/*!
* \brief Checks whether or not the EntityList contains the entity
* \return true If it is the case * \return true If it is the case
* *
* \param entity Pointer to the entity * \param entity Pointer to the entity
*
* \remark If the Insert function was called since the EntityList construction (or last call to Clear), the entity passed by parameter must belong to the same world as the previously inserted entities.
*/ */
inline bool EntityList::Has(const Entity* entity) const
inline bool EntityList::Has(const Entity* entity)
{ {
NazaraAssert(!m_world || !entity || entity->GetWorld() == m_world, "Incompatible world");
return entity && entity->IsValid() && Has(entity->GetId()); return entity && entity->IsValid() && Has(entity->GetId());
} }
@ -41,8 +89,7 @@ namespace Ndk
* *
* \param id Identifier of the entity * \param id Identifier of the entity
*/ */
inline bool EntityList::Has(EntityId entity) const
inline bool EntityList::Has(EntityId entity)
{ {
return m_entityBits.UnboundedTest(entity); return m_entityBits.UnboundedTest(entity);
} }
@ -50,17 +97,23 @@ namespace Ndk
/*! /*!
* \brief Inserts the entity into the set * \brief Inserts the entity into the set
* *
* \param entity Pointer to the entity * Marks an entity as present in this entity list, it must belongs to the same world as others entities contained in this list.
*
* \param entity Valid pointer to an entity
* *
* \remark If entity is already contained, no action is performed * \remark If entity is already contained, no action is performed
* \remark If any entity has been inserted since construction (or last Clear call), the entity must belong to the same world as the previously inserted entities
*/ */
inline void EntityList::Insert(Entity* entity) inline void EntityList::Insert(Entity* entity)
{ {
NazaraAssert(entity, "Invalid entity");
if (!Has(entity)) if (!Has(entity))
{ {
m_entities.emplace_back(entity); entity->RegisterEntityList(this);
m_entityBits.UnboundedSet(entity->GetId(), true); m_entityBits.UnboundedSet(entity->GetId(), true);
m_world = entity->GetWorld();
} }
} }
@ -70,89 +123,138 @@ namespace Ndk
* \param entity Pointer to the entity * \param entity Pointer to the entity
* *
* \remark If entity is not contained, no action is performed * \remark If entity is not contained, no action is performed
* \remark This function never resets the implicit world member, even if it empties the list. Use the Clear method if you want to reset it.
*
* \see Clear
*/ */
inline void EntityList::Remove(Entity* entity) inline void EntityList::Remove(Entity* entity)
{ {
if (Has(entity)) if (Has(entity))
{ {
auto it = std::find(m_entities.begin(), m_entities.end(), *entity); m_entityBits.Reset(entity->GetId());
NazaraAssert(it != m_entities.end(), "Entity should be part of the vector");
std::swap(*it, m_entities.back()); entity->UnregisterEntityList(this);
m_entities.pop_back(); // We get it out of the vector
m_entityBits.UnboundedSet(entity->GetId(), false);
} }
} }
// Nz::Interface STD // STL Interface
inline EntityList::Container::iterator EntityList::begin() inline EntityList::iterator EntityList::begin() const
{ {
return m_entities.begin(); return EntityList::iterator(this, m_entityBits.FindFirst());
}
inline EntityList::Container::const_iterator EntityList::begin() const
{
return m_entities.begin();
}
inline EntityList::Container::const_iterator EntityList::cbegin() const
{
return m_entities.cbegin();
}
inline EntityList::Container::const_iterator EntityList::cend() const
{
return m_entities.cend();
}
inline EntityList::Container::const_reverse_iterator EntityList::crbegin() const
{
return m_entities.crbegin();
}
inline EntityList::Container::const_reverse_iterator EntityList::crend() const
{
return m_entities.crend();
} }
inline bool EntityList::empty() const inline bool EntityList::empty() const
{ {
return m_entities.empty(); return !m_entityBits.TestAny();
} }
inline EntityList::Container::iterator EntityList::end() inline EntityList::iterator EntityList::end() const
{ {
return m_entities.end(); return EntityList::iterator(this, m_entityBits.npos);
} }
inline EntityList::Container::const_iterator EntityList::end() const inline EntityList::size_type EntityList::size() const
{ {
return m_entities.end(); return m_entityBits.Count();
} }
inline EntityList::Container::reverse_iterator EntityList::rbegin() inline EntityList& EntityList::operator=(const EntityList& entityList)
{ {
return m_entities.rbegin(); m_entityBits = entityList.m_entityBits;
m_world = entityList.m_world;
for (const Ndk::EntityHandle& entity : *this)
entity->RegisterEntityList(this);
return *this;
} }
inline EntityList::Container::const_reverse_iterator EntityList::rbegin() const inline EntityList& EntityList::operator=(EntityList&& entityList) noexcept
{ {
return m_entities.rbegin(); m_entityBits = std::move(entityList.m_entityBits);
m_world = entityList.m_world;
for (const Ndk::EntityHandle& entity : *this)
{
entity->UnregisterEntityList(&entityList);
entity->RegisterEntityList(this);
}
return *this;
} }
inline EntityList::Container::reverse_iterator EntityList::rend() inline std::size_t EntityList::FindNext(std::size_t currentId) const
{ {
return m_entities.rend(); return m_entityBits.FindNext(currentId);
} }
inline EntityList::Container::const_reverse_iterator EntityList::rend() const inline World* EntityList::GetWorld() const
{ {
return m_entities.rend(); return m_world;
} }
inline EntityList::Container::size_type EntityList::size() const inline void EntityList::NotifyEntityDestruction(const Entity* entity)
{ {
return m_entities.size(); assert(Has(entity));
m_entityBits.Reset(entity->GetId());
}
inline EntityList::iterator::iterator(const EntityList* list, std::size_t nextId) :
m_nextEntityId(nextId),
m_list(list)
{
}
inline EntityList::iterator::iterator(const iterator& it) :
m_nextEntityId(it.m_nextEntityId),
m_list(it.m_list)
{
}
inline EntityList::iterator& EntityList::iterator::operator=(const iterator& it)
{
m_nextEntityId = it.m_nextEntityId;
m_list = it.m_list;
return *this;
}
inline EntityList::iterator& EntityList::iterator::operator++()
{
m_nextEntityId = m_list->FindNext(m_nextEntityId);
return *this;
}
inline EntityList::iterator EntityList::iterator::operator++(int)
{
std::size_t previousId = m_nextEntityId;
m_nextEntityId = m_list->FindNext(m_nextEntityId);
return iterator(m_list, previousId);
}
inline bool operator==(const EntityList::iterator& lhs, const EntityList::iterator& rhs)
{
NazaraAssert(lhs.m_list == rhs.m_list, "Cannot compare iterator coming from different lists");
return lhs.m_nextEntityId == rhs.m_nextEntityId;
}
inline bool operator!=(const EntityList::iterator& lhs, const EntityList::iterator& rhs)
{
return !operator==(lhs, rhs);
}
inline void swap(EntityList::iterator& lhs, EntityList::iterator& rhs)
{
NazaraAssert(lhs.m_list == rhs.m_list, "Cannot compare iterator coming from different lists");
using std::swap;
swap(lhs.m_nextEntityId, rhs.m_nextEntityId);
} }
} }

View File

@ -24,7 +24,7 @@ namespace Ndk
template<typename T> void BindComponent(const Nz::String& name); template<typename T> void BindComponent(const Nz::String& name);
void RegisterClasses(Nz::LuaInstance& instance); void RegisterClasses(Nz::LuaState& state);
std::unique_ptr<LuaBinding_Base> core; std::unique_ptr<LuaBinding_Base> core;
std::unique_ptr<LuaBinding_Base> math; std::unique_ptr<LuaBinding_Base> math;
@ -36,17 +36,18 @@ namespace Ndk
std::unique_ptr<LuaBinding_Base> audio; std::unique_ptr<LuaBinding_Base> audio;
std::unique_ptr<LuaBinding_Base> graphics; std::unique_ptr<LuaBinding_Base> graphics;
std::unique_ptr<LuaBinding_Base> renderer; std::unique_ptr<LuaBinding_Base> renderer;
std::unique_ptr<LuaBinding_Base> platform;
#endif #endif
private: private:
template<typename T> template<typename T>
static int AddComponentOfType(Nz::LuaInstance& lua, EntityHandle& handle); static int AddComponentOfType(Nz::LuaState& lua, EntityHandle& handle);
template<typename T> template<typename T>
static int PushComponentOfType(Nz::LuaInstance& lua, BaseComponent& component); static int PushComponentOfType(Nz::LuaState& lua, BaseComponent& component);
using AddComponentFunc = int(*)(Nz::LuaInstance&, EntityHandle&); using AddComponentFunc = int(*)(Nz::LuaState&, EntityHandle&);
using GetComponentFunc = int(*)(Nz::LuaInstance&, BaseComponent&); using GetComponentFunc = int(*)(Nz::LuaState&, BaseComponent&);
struct ComponentBinding struct ComponentBinding
{ {
@ -56,7 +57,7 @@ namespace Ndk
Nz::String name; Nz::String name;
}; };
ComponentBinding* QueryComponentIndex(Nz::LuaInstance& lua, int argIndex = 2); ComponentBinding* QueryComponentIndex(Nz::LuaState& lua, int argIndex = 2);
std::vector<ComponentBinding> m_componentBinding; std::vector<ComponentBinding> m_componentBinding;
std::unordered_map<Nz::String, ComponentIndex> m_componentBindingByName; std::unordered_map<Nz::String, ComponentIndex> m_componentBindingByName;

View File

@ -6,6 +6,35 @@
namespace Ndk namespace Ndk
{ {
namespace Detail
{
template<bool HasDefaultConstructor>
struct AddComponentIf;
template<>
struct AddComponentIf<true>
{
template<typename T>
static int AddComponent(Nz::LuaState& lua, EntityHandle& handle)
{
T& component = handle->AddComponent<T>();
lua.Push(component.CreateHandle());
return 1;
}
};
template<>
struct AddComponentIf<false>
{
template<typename T>
static int AddComponent(Nz::LuaState& lua, EntityHandle& /*handle*/)
{
lua.Error("Component has no default constructor and cannot be created from Lua yet");
return 0;
}
};
}
/*! /*!
* \brief Binds a component to a name * \brief Binds a component to a name
* *
@ -13,14 +42,15 @@ namespace Ndk
* *
* \remark Produces a NazaraAssert if name is empty * \remark Produces a NazaraAssert if name is empty
*/ */
template<typename T> template<typename T>
void LuaBinding::BindComponent(const Nz::String& name) void LuaBinding::BindComponent(const Nz::String& name)
{ {
NazaraAssert(!name.IsEmpty(), "Component name cannot be empty"); NazaraAssert(!name.IsEmpty(), "Component name cannot be empty");
static_assert(std::is_base_of<BaseComponent, T>::value, "ComponentType must inherit BaseComponent");
ComponentBinding binding; ComponentBinding binding;
binding.adder = &AddComponentOfType<T>; binding.adder = &Detail::AddComponentIf<std::is_default_constructible<T>::value>::template AddComponent<T>;
binding.getter = &PushComponentOfType<T>; binding.getter = &PushComponentOfType<T>;
binding.index = T::componentIndex; binding.index = T::componentIndex;
binding.name = name; binding.name = name;
@ -33,20 +63,8 @@ namespace Ndk
} }
template<typename T> template<typename T>
int LuaBinding::AddComponentOfType(Nz::LuaInstance& lua, EntityHandle& handle) int LuaBinding::PushComponentOfType(Nz::LuaState& lua, BaseComponent& component)
{ {
static_assert(std::is_base_of<BaseComponent, T>::value, "ComponentType must inherit BaseComponent");
T& component = handle->AddComponent<T>();
lua.Push(component.CreateHandle());
return 1;
}
template<typename T>
int LuaBinding::PushComponentOfType(Nz::LuaInstance& lua, BaseComponent& component)
{
static_assert(std::is_base_of<BaseComponent, T>::value, "ComponentType must inherit BaseComponent");
T& rightComponent = static_cast<T&>(component); T& rightComponent = static_cast<T&>(component);
lua.Push(rightComponent.CreateHandle()); lua.Push(rightComponent.CreateHandle());
return 1; return 1;

View File

@ -21,7 +21,7 @@ namespace Ndk
LuaBinding_Audio(LuaBinding& binding); LuaBinding_Audio(LuaBinding& binding);
~LuaBinding_Audio() = default; ~LuaBinding_Audio() = default;
void Register(Nz::LuaInstance& instance) override; void Register(Nz::LuaState& state) override;
Nz::LuaClass<Nz::Music> music; Nz::LuaClass<Nz::Music> music;
Nz::LuaClass<Nz::Sound> sound; Nz::LuaClass<Nz::Sound> sound;

View File

@ -23,6 +23,7 @@ namespace Ndk
class LuaBinding_Renderer; class LuaBinding_Renderer;
class LuaBinding_SDK; class LuaBinding_SDK;
class LuaBinding_Utility; class LuaBinding_Utility;
class LuaBinding_Platform;
class NDK_API LuaBinding_Base class NDK_API LuaBinding_Base
{ {
@ -30,7 +31,7 @@ namespace Ndk
LuaBinding_Base(LuaBinding& binding); LuaBinding_Base(LuaBinding& binding);
virtual ~LuaBinding_Base(); virtual ~LuaBinding_Base();
virtual void Register(Nz::LuaInstance& instance) = 0; virtual void Register(Nz::LuaState& state) = 0;
// Implementation lies in the respective .cpp files (still searching for a cleaner way..) // Implementation lies in the respective .cpp files (still searching for a cleaner way..)
static std::unique_ptr<LuaBinding_Base> BindCore(LuaBinding& binding); static std::unique_ptr<LuaBinding_Base> BindCore(LuaBinding& binding);
@ -43,6 +44,7 @@ namespace Ndk
static std::unique_ptr<LuaBinding_Base> BindAudio(LuaBinding& binding); static std::unique_ptr<LuaBinding_Base> BindAudio(LuaBinding& binding);
static std::unique_ptr<LuaBinding_Base> BindGraphics(LuaBinding& binding); static std::unique_ptr<LuaBinding_Base> BindGraphics(LuaBinding& binding);
static std::unique_ptr<LuaBinding_Base> BindRenderer(LuaBinding& binding); static std::unique_ptr<LuaBinding_Base> BindRenderer(LuaBinding& binding);
static std::unique_ptr<LuaBinding_Base> BindPlatform(LuaBinding& binding);
#endif #endif
protected: protected:

View File

@ -21,7 +21,7 @@ namespace Ndk
LuaBinding_Core(LuaBinding& binding); LuaBinding_Core(LuaBinding& binding);
~LuaBinding_Core() = default; ~LuaBinding_Core() = default;
void Register(Nz::LuaInstance& instance) override; void Register(Nz::LuaState& state) override;
Nz::LuaClass<Nz::Clock> clock; Nz::LuaClass<Nz::Clock> clock;
Nz::LuaClass<Nz::Directory> directory; Nz::LuaClass<Nz::Directory> directory;

View File

@ -22,7 +22,7 @@ namespace Ndk
LuaBinding_Graphics(LuaBinding& binding); LuaBinding_Graphics(LuaBinding& binding);
~LuaBinding_Graphics() = default; ~LuaBinding_Graphics() = default;
void Register(Nz::LuaInstance& instance) override; void Register(Nz::LuaState& state) override;
Nz::LuaClass<Nz::AbstractViewer> abstractViewer; Nz::LuaClass<Nz::AbstractViewer> abstractViewer;
Nz::LuaClass<Nz::InstancedRenderableRef> instancedRenderable; Nz::LuaClass<Nz::InstancedRenderableRef> instancedRenderable;

View File

@ -23,7 +23,7 @@ namespace Ndk
LuaBinding_Math(LuaBinding& binding); LuaBinding_Math(LuaBinding& binding);
~LuaBinding_Math() = default; ~LuaBinding_Math() = default;
void Register(Nz::LuaInstance& instance) override; void Register(Nz::LuaState& state) override;
Nz::LuaClass<Nz::EulerAnglesd> eulerAngles; Nz::LuaClass<Nz::EulerAnglesd> eulerAngles;
Nz::LuaClass<Nz::Matrix4d> matrix4d; Nz::LuaClass<Nz::Matrix4d> matrix4d;

View File

@ -9,6 +9,7 @@
#include <Nazara/Network/AbstractSocket.hpp> #include <Nazara/Network/AbstractSocket.hpp>
#include <Nazara/Network/IpAddress.hpp> #include <Nazara/Network/IpAddress.hpp>
#include <Nazara/Network/UdpSocket.hpp>
#include <NDK/Lua/LuaBinding_Base.hpp> #include <NDK/Lua/LuaBinding_Base.hpp>
namespace Ndk namespace Ndk
@ -19,10 +20,11 @@ namespace Ndk
LuaBinding_Network(LuaBinding& binding); LuaBinding_Network(LuaBinding& binding);
~LuaBinding_Network() = default; ~LuaBinding_Network() = default;
void Register(Nz::LuaInstance& instance) override; void Register(Nz::LuaState& state) override;
Nz::LuaClass<Nz::AbstractSocket> abstractSocket; Nz::LuaClass<Nz::AbstractSocket> abstractSocket;
Nz::LuaClass<Nz::IpAddress> ipAddress; Nz::LuaClass<Nz::IpAddress> ipAddress;
Nz::LuaClass<Nz::UdpSocket> udpSocket;
}; };
} }

View File

@ -0,0 +1,28 @@
// Copyright (C) 2017 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_LUABINDING_SYSTEM_HPP
#define NDK_LUABINDING_SYSTEM_HPP
#include <Nazara/Platform/Keyboard.hpp>
#include <NDK/Lua/LuaBinding_Base.hpp>
namespace Ndk
{
class NDK_API LuaBinding_Platform : public LuaBinding_Base
{
public:
LuaBinding_Platform(LuaBinding& binding);
~LuaBinding_Platform() = default;
void Register(Nz::LuaState& state) override;
// Platform
Nz::LuaClass<Nz::Keyboard> keyboard;
};
}
#endif // NDK_LUABINDING_SYSTEM_HPP

View File

@ -18,7 +18,7 @@ namespace Ndk
LuaBinding_Renderer(LuaBinding& binding); LuaBinding_Renderer(LuaBinding& binding);
~LuaBinding_Renderer() = default; ~LuaBinding_Renderer() = default;
void Register(Nz::LuaInstance& instance) override; void Register(Nz::LuaState& state) override;
Nz::LuaClass<Nz::TextureRef> texture; Nz::LuaClass<Nz::TextureRef> texture;
Nz::LuaClass<Nz::TextureLibrary> textureLibrary; Nz::LuaClass<Nz::TextureLibrary> textureLibrary;

View File

@ -22,7 +22,7 @@ namespace Ndk
LuaBinding_SDK(LuaBinding& binding); LuaBinding_SDK(LuaBinding& binding);
~LuaBinding_SDK() = default; ~LuaBinding_SDK() = default;
void Register(Nz::LuaInstance& instance) override; void Register(Nz::LuaState& state) override;
Nz::LuaClass<Application*> application; Nz::LuaClass<Application*> application;
Nz::LuaClass<EntityHandle> entity; Nz::LuaClass<EntityHandle> entity;

View File

@ -9,7 +9,6 @@
#include <Nazara/Utility/AbstractImage.hpp> #include <Nazara/Utility/AbstractImage.hpp>
#include <Nazara/Utility/Font.hpp> #include <Nazara/Utility/Font.hpp>
#include <Nazara/Utility/Keyboard.hpp>
#include <Nazara/Utility/Node.hpp> #include <Nazara/Utility/Node.hpp>
#include <NDK/Lua/LuaBinding_Base.hpp> #include <NDK/Lua/LuaBinding_Base.hpp>
@ -21,12 +20,11 @@ namespace Ndk
LuaBinding_Utility(LuaBinding& binding); LuaBinding_Utility(LuaBinding& binding);
~LuaBinding_Utility() = default; ~LuaBinding_Utility() = default;
void Register(Nz::LuaInstance& instance) override; void Register(Nz::LuaState& state) override;
// Utility // Utility
Nz::LuaClass<Nz::AbstractImageRef> abstractImage; Nz::LuaClass<Nz::AbstractImageRef> abstractImage;
Nz::LuaClass<Nz::FontRef> font; Nz::LuaClass<Nz::FontRef> font;
Nz::LuaClass<Nz::Keyboard> keyboard;
Nz::LuaClass<Nz::Node> node; Nz::LuaClass<Nz::Node> node;
}; };
} }

View File

@ -11,7 +11,7 @@
namespace Nz namespace Nz
{ {
class LuaInstance; class LuaState;
} }
namespace Ndk namespace Ndk
@ -28,7 +28,7 @@ namespace Ndk
static bool Initialize(); static bool Initialize();
static void RegisterClasses(Nz::LuaInstance& instance); static void RegisterClasses(Nz::LuaState& state);
static void Uninitialize(); static void Uninitialize();

View File

@ -4,7 +4,7 @@
#include <NDK/LuaAPI.hpp> #include <NDK/LuaAPI.hpp>
#include <Nazara/Core/Color.hpp> #include <Nazara/Core/Color.hpp>
#include <Nazara/Lua/LuaInstance.hpp> #include <Nazara/Lua/LuaState.hpp>
#include <Nazara/Math/EulerAngles.hpp> #include <Nazara/Math/EulerAngles.hpp>
#include <Nazara/Math/Quaternion.hpp> #include <Nazara/Math/Quaternion.hpp>
#include <Nazara/Math/Vector3.hpp> #include <Nazara/Math/Vector3.hpp>
@ -28,103 +28,103 @@
namespace Nz namespace Nz
{ {
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Color* color, TypeTag<Color>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Color* color, TypeTag<Color>)
{ {
instance.CheckType(index, Nz::LuaType_Table); state.CheckType(index, Nz::LuaType_Table);
color->r = instance.CheckField<UInt8>("r", index); color->r = state.CheckField<UInt8>("r", index);
color->g = instance.CheckField<UInt8>("g", index); color->g = state.CheckField<UInt8>("g", index);
color->b = instance.CheckField<UInt8>("b", index); color->b = state.CheckField<UInt8>("b", index);
color->a = instance.CheckField<UInt8>("a", 255, index); color->a = state.CheckField<UInt8>("a", 255, index);
return 1; return 1;
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, EulerAnglesd* angles, TypeTag<EulerAnglesd>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, EulerAnglesd* angles, TypeTag<EulerAnglesd>)
{ {
switch (instance.GetType(index)) switch (state.GetType(index))
{ {
case Nz::LuaType_Table: case Nz::LuaType_Table:
angles->Set(instance.CheckField<double>("pitch", index), instance.CheckField<double>("yaw", index), instance.CheckField<double>("roll", index)); angles->Set(state.CheckField<double>("pitch", index), state.CheckField<double>("yaw", index), state.CheckField<double>("roll", index));
return 1; return 1;
default: default:
{ {
if (instance.IsOfType(index, "EulerAngles")) if (state.IsOfType(index, "EulerAngles"))
angles->Set(*static_cast<EulerAnglesd*>(instance.ToUserdata(index))); angles->Set(*static_cast<EulerAnglesd*>(state.ToUserdata(index)));
else else
angles->Set(*static_cast<Quaterniond*>(instance.CheckUserdata(index, "Quaternion"))); angles->Set(*static_cast<Quaterniond*>(state.CheckUserdata(index, "Quaternion")));
return 1; return 1;
} }
} }
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, EulerAnglesf* angles, TypeTag<EulerAnglesf>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, EulerAnglesf* angles, TypeTag<EulerAnglesf>)
{ {
EulerAnglesd anglesDouble; EulerAnglesd anglesDouble;
unsigned int ret = LuaImplQueryArg(instance, index, &anglesDouble, TypeTag<EulerAnglesd>()); unsigned int ret = LuaImplQueryArg(state, index, &anglesDouble, TypeTag<EulerAnglesd>());
angles->Set(anglesDouble); angles->Set(anglesDouble);
return ret; return ret;
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, FontRef* fontRef, TypeTag<FontRef>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, FontRef* fontRef, TypeTag<FontRef>)
{ {
*fontRef = *static_cast<FontRef*>(instance.CheckUserdata(index, "Font")); *fontRef = *static_cast<FontRef*>(state.CheckUserdata(index, "Font"));
return 1; return 1;
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, FontParams* params, TypeTag<FontParams>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, FontParams* params, TypeTag<FontParams>)
{ {
NazaraUnused(params); NazaraUnused(params);
instance.CheckType(index, Nz::LuaType_Table); state.CheckType(index, Nz::LuaType_Table);
// Structure is empty for now // Structure is empty for now
return 1; return 1;
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, ImageParams* params, TypeTag<ImageParams>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, ImageParams* params, TypeTag<ImageParams>)
{ {
instance.CheckType(index, Nz::LuaType_Table); state.CheckType(index, Nz::LuaType_Table);
params->levelCount = instance.CheckField<Nz::UInt8>("LevelCount"); params->levelCount = state.CheckField<Nz::UInt8>("LevelCount");
params->loadFormat = instance.CheckField<Nz::PixelFormatType>("LoadFormat"); params->loadFormat = state.CheckField<Nz::PixelFormatType>("LoadFormat");
return 1; return 1;
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, IpAddress* address, TypeTag<IpAddress>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, IpAddress* address, TypeTag<IpAddress>)
{ {
switch (instance.GetType(index)) switch (state.GetType(index))
{ {
case Nz::LuaType_String: case Nz::LuaType_String:
address->BuildFromAddress(instance.CheckString(index)); address->BuildFromAddress(state.CheckString(index));
return 1; return 1;
default: default:
*address = *static_cast<IpAddress*>(instance.CheckUserdata(index, "IpAddress")); *address = *static_cast<IpAddress*>(state.CheckUserdata(index, "IpAddress"));
return 1; return 1;
} }
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Matrix4d* mat, TypeTag<Matrix4d>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Matrix4d* mat, TypeTag<Matrix4d>)
{ {
switch (instance.GetType(index)) switch (state.GetType(index))
{ {
case Nz::LuaType_Table: case Nz::LuaType_Table:
{ {
double values[16]; double values[16];
for (std::size_t i = 0; i < 16; ++i) for (std::size_t i = 0; i < 16; ++i)
{ {
instance.PushInteger(i + 1); state.PushInteger(i + 1);
instance.GetTable(); state.GetTable();
values[i] = instance.CheckNumber(-1); values[i] = state.CheckNumber(-1);
instance.Pop(); state.Pop();
} }
mat->Set(values); mat->Set(values);
@ -133,500 +133,500 @@ namespace Nz
default: default:
{ {
if (instance.IsOfType(index, "Matrix4")) if (state.IsOfType(index, "Matrix4"))
mat->Set(*static_cast<Matrix4d*>(instance.ToUserdata(index))); mat->Set(*static_cast<Matrix4d*>(state.ToUserdata(index)));
return 1; return 1;
} }
} }
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Matrix4f* mat, TypeTag<Matrix4f>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Matrix4f* mat, TypeTag<Matrix4f>)
{ {
Matrix4d matDouble = Matrix4d::Identity(); Matrix4d matDouble = Matrix4d::Identity();
unsigned int ret = LuaImplQueryArg(instance, index, &matDouble, TypeTag<Matrix4d>()); unsigned int ret = LuaImplQueryArg(state, index, &matDouble, TypeTag<Matrix4d>());
mat->Set(matDouble); mat->Set(matDouble);
return ret; return ret;
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MeshParams* params, TypeTag<MeshParams>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, MeshParams* params, TypeTag<MeshParams>)
{ {
instance.CheckType(index, Nz::LuaType_Table); state.CheckType(index, Nz::LuaType_Table);
params->animated = instance.CheckField<bool>("Animated", params->animated); params->animated = state.CheckField<bool>("Animated", params->animated);
params->center = instance.CheckField<bool>("Center", params->center); params->center = state.CheckField<bool>("Center", params->center);
params->matrix = instance.CheckField<Matrix4f>("Matrix", params->matrix); params->matrix = state.CheckField<Matrix4f>("Matrix", params->matrix);
params->optimizeIndexBuffers = instance.CheckField<bool>("OptimizeIndexBuffers", params->optimizeIndexBuffers); params->optimizeIndexBuffers = state.CheckField<bool>("OptimizeIndexBuffers", params->optimizeIndexBuffers);
params->texCoordOffset = instance.CheckField<Vector2f>("TexCoordOffset", params->texCoordOffset); params->texCoordOffset = state.CheckField<Vector2f>("TexCoordOffset", params->texCoordOffset);
params->texCoordScale = instance.CheckField<Vector2f>("TexCoordScale", params->texCoordScale); params->texCoordScale = state.CheckField<Vector2f>("TexCoordScale", params->texCoordScale);
return 1; return 1;
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Quaterniond* quat, TypeTag<Quaterniond>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Quaterniond* quat, TypeTag<Quaterniond>)
{ {
switch (instance.GetType(index)) switch (state.GetType(index))
{ {
case Nz::LuaType_Table: case Nz::LuaType_Table:
quat->Set(instance.CheckField<double>("w", index), instance.CheckField<double>("x", index), instance.CheckField<double>("y", index), instance.CheckField<double>("z", index)); quat->Set(state.CheckField<double>("w", index), state.CheckField<double>("x", index), state.CheckField<double>("y", index), state.CheckField<double>("z", index));
return 1; return 1;
default: default:
{ {
if (instance.IsOfType(index, "EulerAngles")) if (state.IsOfType(index, "EulerAngles"))
quat->Set(*static_cast<EulerAnglesd*>(instance.ToUserdata(index))); quat->Set(*static_cast<EulerAnglesd*>(state.ToUserdata(index)));
else else
quat->Set(*static_cast<Quaterniond*>(instance.CheckUserdata(index, "Quaternion"))); quat->Set(*static_cast<Quaterniond*>(state.CheckUserdata(index, "Quaternion")));
return 1; return 1;
} }
} }
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Quaternionf* quat, TypeTag<Quaternionf>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Quaternionf* quat, TypeTag<Quaternionf>)
{ {
Quaterniond quatDouble; Quaterniond quatDouble;
unsigned int ret = LuaImplQueryArg(instance, index, &quatDouble, TypeTag<Quaterniond>()); unsigned int ret = LuaImplQueryArg(state, index, &quatDouble, TypeTag<Quaterniond>());
quat->Set(quatDouble); quat->Set(quatDouble);
return ret; return ret;
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Rectd* rect, TypeTag<Rectd>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Rectd* rect, TypeTag<Rectd>)
{ {
instance.CheckType(index, LuaType_Table); state.CheckType(index, LuaType_Table);
rect->x = instance.CheckField<double>("x", index); rect->x = state.CheckField<double>("x", index);
rect->y = instance.CheckField<double>("y", index); rect->y = state.CheckField<double>("y", index);
rect->width = instance.CheckField<double>("width", index); rect->width = state.CheckField<double>("width", index);
rect->height = instance.CheckField<double>("height", index); rect->height = state.CheckField<double>("height", index);
return 1; return 1;
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Rectf* rect, TypeTag<Rectf>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Rectf* rect, TypeTag<Rectf>)
{ {
Rectd rectDouble; Rectd rectDouble;
unsigned int ret = LuaImplQueryArg(instance, index, &rectDouble, TypeTag<Rectd>()); unsigned int ret = LuaImplQueryArg(state, index, &rectDouble, TypeTag<Rectd>());
rect->Set(rectDouble); rect->Set(rectDouble);
return ret; return ret;
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Recti* rect, TypeTag<Recti>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Recti* rect, TypeTag<Recti>)
{ {
Rectd rectDouble; Rectd rectDouble;
unsigned int ret = LuaImplQueryArg(instance, index, &rectDouble, TypeTag<Rectd>()); unsigned int ret = LuaImplQueryArg(state, index, &rectDouble, TypeTag<Rectd>());
rect->Set(rectDouble); rect->Set(rectDouble);
return ret; return ret;
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Rectui* rect, TypeTag<Rectui>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Rectui* rect, TypeTag<Rectui>)
{ {
Rectd rectDouble; Rectd rectDouble;
unsigned int ret = LuaImplQueryArg(instance, index, &rectDouble, TypeTag<Rectd>()); unsigned int ret = LuaImplQueryArg(state, index, &rectDouble, TypeTag<Rectd>());
rect->Set(rectDouble); rect->Set(rectDouble);
return ret; return ret;
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector2d* vec, TypeTag<Vector2d>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Vector2d* vec, TypeTag<Vector2d>)
{ {
switch (instance.GetType(index)) switch (state.GetType(index))
{ {
case Nz::LuaType_Number: case Nz::LuaType_Number:
if (index < 0 && index > -2) if (index < 0 && index > -2)
instance.Error("Vector2 expected, two numbers are required to convert it"); state.Error("Vector2 expected, two numbers are required to convert it");
vec->Set(instance.CheckNumber(index), instance.CheckNumber(index + 1)); vec->Set(state.CheckNumber(index), state.CheckNumber(index + 1));
return 2; return 2;
case Nz::LuaType_Table: case Nz::LuaType_Table:
vec->Set(instance.CheckField<double>("x", index), instance.CheckField<double>("y", index)); vec->Set(state.CheckField<double>("x", index), state.CheckField<double>("y", index));
return 1; return 1;
default: default:
vec->Set(*static_cast<Vector2d*>(instance.CheckUserdata(index, "Vector2"))); vec->Set(*static_cast<Vector2d*>(state.CheckUserdata(index, "Vector2")));
return 1; return 1;
} }
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector2f* vec, TypeTag<Vector2f>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Vector2f* vec, TypeTag<Vector2f>)
{ {
Vector2d vecDouble; Vector2d vecDouble;
unsigned int ret = LuaImplQueryArg(instance, index, &vecDouble, TypeTag<Vector2d>()); unsigned int ret = LuaImplQueryArg(state, index, &vecDouble, TypeTag<Vector2d>());
vec->Set(vecDouble); vec->Set(vecDouble);
return ret; return ret;
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector2ui* vec, TypeTag<Vector2ui>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Vector2ui* vec, TypeTag<Vector2ui>)
{ {
Vector2d vecDouble; Vector2d vecDouble;
unsigned int ret = LuaImplQueryArg(instance, index, &vecDouble, TypeTag<Vector2d>()); unsigned int ret = LuaImplQueryArg(state, index, &vecDouble, TypeTag<Vector2d>());
vec->Set(vecDouble); vec->Set(vecDouble);
return ret; return ret;
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector3d* vec, TypeTag<Vector3d>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Vector3d* vec, TypeTag<Vector3d>)
{ {
switch (instance.GetType(index)) switch (state.GetType(index))
{ {
case Nz::LuaType_Number: case Nz::LuaType_Number:
if (index < 0 && index > -3) if (index < 0 && index > -3)
instance.Error("Vector3 expected, three numbers are required to convert it"); state.Error("Vector3 expected, three numbers are required to convert it");
vec->Set(instance.CheckNumber(index), instance.CheckNumber(index + 1), instance.CheckNumber(index + 2, 0.0)); vec->Set(state.CheckNumber(index), state.CheckNumber(index + 1), state.CheckNumber(index + 2, 0.0));
return 3; return 3;
case Nz::LuaType_Table: case Nz::LuaType_Table:
vec->Set(instance.CheckField<double>("x", index), instance.CheckField<double>("y", index), instance.CheckField<double>("z", 0.0, index)); vec->Set(state.CheckField<double>("x", index), state.CheckField<double>("y", index), state.CheckField<double>("z", 0.0, index));
return 1; return 1;
default: default:
vec->Set(*static_cast<Vector3d*>(instance.CheckUserdata(index, "Vector3"))); vec->Set(*static_cast<Vector3d*>(state.CheckUserdata(index, "Vector3")));
return 1; return 1;
} }
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector3f* vec, TypeTag<Vector3f>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Vector3f* vec, TypeTag<Vector3f>)
{ {
Vector3d vecDouble; Vector3d vecDouble;
unsigned int ret = LuaImplQueryArg(instance, index, &vecDouble, TypeTag<Vector3d>()); unsigned int ret = LuaImplQueryArg(state, index, &vecDouble, TypeTag<Vector3d>());
vec->Set(vecDouble); vec->Set(vecDouble);
return ret; return ret;
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector3ui* vec, TypeTag<Vector3ui>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Vector3ui* vec, TypeTag<Vector3ui>)
{ {
Vector3d vecDouble; Vector3d vecDouble;
unsigned int ret = LuaImplQueryArg(instance, index, &vecDouble, TypeTag<Vector3d>()); unsigned int ret = LuaImplQueryArg(state, index, &vecDouble, TypeTag<Vector3d>());
vec->Set(vecDouble); vec->Set(vecDouble);
return ret; return ret;
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Ndk::EntityHandle* handle, TypeTag<Ndk::EntityHandle>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Ndk::EntityHandle* handle, TypeTag<Ndk::EntityHandle>)
{ {
*handle = *static_cast<Ndk::EntityHandle*>(instance.CheckUserdata(index, "Entity")); *handle = *static_cast<Ndk::EntityHandle*>(state.CheckUserdata(index, "Entity"));
return 1; return 1;
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Ndk::WorldHandle* handle, TypeTag<Ndk::WorldHandle>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Ndk::WorldHandle* handle, TypeTag<Ndk::WorldHandle>)
{ {
*handle = *static_cast<Ndk::WorldHandle*>(instance.CheckUserdata(index, "World")); *handle = *static_cast<Ndk::WorldHandle*>(state.CheckUserdata(index, "World"));
return 1; return 1;
} }
#ifndef NDK_SERVER #ifndef NDK_SERVER
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, InstancedRenderableRef* renderable, TypeTag<InstancedRenderableRef>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, InstancedRenderableRef* renderable, TypeTag<InstancedRenderableRef>)
{ {
if (instance.IsOfType(index, "InstancedRenderable") || if (state.IsOfType(index, "InstancedRenderable") ||
instance.IsOfType(index, "Model") || state.IsOfType(index, "Model") ||
instance.IsOfType(index, "Sprite")) state.IsOfType(index, "Sprite"))
{ {
*renderable = *static_cast<InstancedRenderableRef*>(instance.ToUserdata(index)); *renderable = *static_cast<InstancedRenderableRef*>(state.ToUserdata(index));
} }
else else
instance.ArgError(index, "is not a InstancedRenderable instance"); state.ArgError(index, "is not a InstancedRenderable instance");
return 1; return 1;
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MaterialRef* materialRef, TypeTag<MaterialRef>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, MaterialRef* materialRef, TypeTag<MaterialRef>)
{ {
*materialRef = *static_cast<MaterialRef*>(instance.CheckUserdata(index, "Material")); *materialRef = *static_cast<MaterialRef*>(state.CheckUserdata(index, "Material"));
return 1; return 1;
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MaterialParams* params, TypeTag<MaterialParams>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, MaterialParams* params, TypeTag<MaterialParams>)
{ {
instance.CheckType(index, Nz::LuaType_Table); state.CheckType(index, Nz::LuaType_Table);
params->loadAlphaMap = instance.CheckField<bool>("LoadAlphaMap", params->loadAlphaMap); params->loadAlphaMap = state.CheckField<bool>("LoadAlphaMap", params->loadAlphaMap);
params->loadDiffuseMap = instance.CheckField<bool>("LoadDiffuseMap", params->loadDiffuseMap); params->loadDiffuseMap = state.CheckField<bool>("LoadDiffuseMap", params->loadDiffuseMap);
params->loadEmissiveMap = instance.CheckField<bool>("LoadEmissiveMap", params->loadEmissiveMap); params->loadEmissiveMap = state.CheckField<bool>("LoadEmissiveMap", params->loadEmissiveMap);
params->loadHeightMap = instance.CheckField<bool>("LoadHeightMap", params->loadHeightMap); params->loadHeightMap = state.CheckField<bool>("LoadHeightMap", params->loadHeightMap);
params->loadNormalMap = instance.CheckField<bool>("LoadNormalMap", params->loadNormalMap); params->loadNormalMap = state.CheckField<bool>("LoadNormalMap", params->loadNormalMap);
params->loadSpecularMap = instance.CheckField<bool>("LoadSpecularMap", params->loadSpecularMap); params->loadSpecularMap = state.CheckField<bool>("LoadSpecularMap", params->loadSpecularMap);
params->shaderName = instance.CheckField<String>("ShaderName", params->shaderName); params->shaderName = state.CheckField<String>("ShaderName", params->shaderName);
return 1; return 1;
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, ModelParameters* params, TypeTag<ModelParameters>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, ModelParameters* params, TypeTag<ModelParameters>)
{ {
instance.CheckType(index, Nz::LuaType_Table); state.CheckType(index, Nz::LuaType_Table);
params->loadMaterials = instance.CheckField<bool>("LoadMaterials", params->loadMaterials); params->loadMaterials = state.CheckField<bool>("LoadMaterials", params->loadMaterials);
LuaImplQueryArg(instance, -1, &params->material, TypeTag<MaterialParams>()); LuaImplQueryArg(state, -1, &params->material, TypeTag<MaterialParams>());
LuaImplQueryArg(instance, -1, &params->mesh, TypeTag<MeshParams>()); LuaImplQueryArg(state, -1, &params->mesh, TypeTag<MeshParams>());
return 1; return 1;
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MusicParams* params, TypeTag<MusicParams>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, MusicParams* params, TypeTag<MusicParams>)
{ {
instance.CheckType(index, Nz::LuaType_Table); state.CheckType(index, Nz::LuaType_Table);
params->forceMono = instance.CheckField<bool>("ForceMono", params->forceMono); params->forceMono = state.CheckField<bool>("ForceMono", params->forceMono);
return 1; return 1;
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, SoundBufferParams* params, TypeTag<SoundBufferParams>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, SoundBufferParams* params, TypeTag<SoundBufferParams>)
{ {
instance.CheckType(index, Nz::LuaType_Table); state.CheckType(index, Nz::LuaType_Table);
params->forceMono = instance.CheckField<bool>("ForceMono", params->forceMono); params->forceMono = state.CheckField<bool>("ForceMono", params->forceMono);
return 1; return 1;
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, SpriteRef* spriteRef, TypeTag<SpriteRef>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, SpriteRef* spriteRef, TypeTag<SpriteRef>)
{ {
*spriteRef = *static_cast<SpriteRef*>(instance.CheckUserdata(index, "Sprite")); *spriteRef = *static_cast<SpriteRef*>(state.CheckUserdata(index, "Sprite"));
return 1; return 1;
} }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, TextureRef* textureRef, TypeTag<TextureRef>) inline unsigned int LuaImplQueryArg(const LuaState& state, int index, TextureRef* textureRef, TypeTag<TextureRef>)
{ {
*textureRef = *static_cast<TextureRef*>(instance.CheckUserdata(index, "Texture")); *textureRef = *static_cast<TextureRef*>(state.CheckUserdata(index, "Texture"));
return 1; return 1;
} }
#endif #endif
inline int LuaImplReplyVal(const LuaInstance& instance, Color&& val, TypeTag<Color>) inline int LuaImplReplyVal(const LuaState& state, Color&& val, TypeTag<Color>)
{ {
instance.PushTable(); state.PushTable();
instance.PushField("r", val.r); state.PushField("r", val.r);
instance.PushField("g", val.g); state.PushField("g", val.g);
instance.PushField("b", val.b); state.PushField("b", val.b);
instance.PushField("a", val.a); state.PushField("a", val.a);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, EulerAnglesd&& val, TypeTag<EulerAnglesd>) inline int LuaImplReplyVal(const LuaState& state, EulerAnglesd&& val, TypeTag<EulerAnglesd>)
{ {
instance.PushInstance<EulerAnglesd>("EulerAngles", val); state.PushInstance<EulerAnglesd>("EulerAngles", val);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, EulerAnglesf&& val, TypeTag<EulerAnglesf>) inline int LuaImplReplyVal(const LuaState& state, EulerAnglesf&& val, TypeTag<EulerAnglesf>)
{ {
instance.PushInstance<EulerAnglesd>("EulerAngles", val); state.PushInstance<EulerAnglesd>("EulerAngles", val);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, FontRef&& val, TypeTag<FontRef>) inline int LuaImplReplyVal(const LuaState& state, FontRef&& val, TypeTag<FontRef>)
{ {
instance.PushInstance<FontRef>("Font", val); state.PushInstance<FontRef>("Font", val);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Font::SizeInfo&& val, TypeTag<Font::SizeInfo>) inline int LuaImplReplyVal(const LuaState& state, Font::SizeInfo&& val, TypeTag<Font::SizeInfo>)
{ {
instance.PushTable(); state.PushTable();
instance.PushField("LineHeight", val.lineHeight); state.PushField("LineHeight", val.lineHeight);
instance.PushField("SpaceAdvance", val.spaceAdvance); state.PushField("SpaceAdvance", val.spaceAdvance);
instance.PushField("UnderlinePosition", val.underlinePosition); state.PushField("UnderlinePosition", val.underlinePosition);
instance.PushField("UnderlineThickness", val.underlineThickness); state.PushField("UnderlineThickness", val.underlineThickness);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, ImageParams&& val, TypeTag<ImageParams>) inline int LuaImplReplyVal(const LuaState& state, ImageParams&& val, TypeTag<ImageParams>)
{ {
instance.PushTable(0, 2); state.PushTable(0, 2);
instance.PushField("LevelCount", val.levelCount); state.PushField("LevelCount", val.levelCount);
instance.PushField("LoadFormat", val.loadFormat); state.PushField("LoadFormat", val.loadFormat);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, IpAddress&& val, TypeTag<IpAddress>) inline int LuaImplReplyVal(const LuaState& state, IpAddress&& val, TypeTag<IpAddress>)
{ {
instance.PushInstance<IpAddress>("IpAddress", val); state.PushInstance<IpAddress>("IpAddress", val);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Matrix4d&& val, TypeTag<Matrix4d>) inline int LuaImplReplyVal(const LuaState& state, Matrix4d&& val, TypeTag<Matrix4d>)
{ {
instance.PushInstance<Matrix4d>("Matrix4", val); state.PushInstance<Matrix4d>("Matrix4", val);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Matrix4f&& val, TypeTag<Matrix4f>) inline int LuaImplReplyVal(const LuaState& state, Matrix4f&& val, TypeTag<Matrix4f>)
{ {
instance.PushInstance<Matrix4d>("Matrix4", val); state.PushInstance<Matrix4d>("Matrix4", val);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Quaterniond&& val, TypeTag<Quaterniond>) inline int LuaImplReplyVal(const LuaState& state, Quaterniond&& val, TypeTag<Quaterniond>)
{ {
instance.PushInstance<Quaterniond>("Quaternion", val); state.PushInstance<Quaterniond>("Quaternion", val);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Quaternionf&& val, TypeTag<Quaternionf>) inline int LuaImplReplyVal(const LuaState& state, Quaternionf&& val, TypeTag<Quaternionf>)
{ {
instance.PushInstance<Quaterniond>("Quaternion", val); state.PushInstance<Quaterniond>("Quaternion", val);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Rectd&& val, TypeTag<Rectd>) inline int LuaImplReplyVal(const LuaState& state, Rectd&& val, TypeTag<Rectd>)
{ {
instance.PushInstance<Rectd>("Rect", val); state.PushInstance<Rectd>("Rect", val);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Rectf&& val, TypeTag<Rectf>) inline int LuaImplReplyVal(const LuaState& state, Rectf&& val, TypeTag<Rectf>)
{ {
instance.PushInstance<Rectd>("Rect", val); state.PushInstance<Rectd>("Rect", val);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Recti&& val, TypeTag<Recti>) inline int LuaImplReplyVal(const LuaState& state, Recti&& val, TypeTag<Recti>)
{ {
instance.PushInstance<Rectd>("Rect", val); state.PushInstance<Rectd>("Rect", val);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Rectui&& val, TypeTag<Rectui>) inline int LuaImplReplyVal(const LuaState& state, Rectui&& val, TypeTag<Rectui>)
{ {
instance.PushInstance<Rectd>("Rect", val); state.PushInstance<Rectd>("Rect", val);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Vector2d&& val, TypeTag<Vector2d>) inline int LuaImplReplyVal(const LuaState& state, Vector2d&& val, TypeTag<Vector2d>)
{ {
instance.PushInstance<Vector2d>("Vector2", val); state.PushInstance<Vector2d>("Vector2", val);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Vector2f&& val, TypeTag<Vector2f>) inline int LuaImplReplyVal(const LuaState& state, Vector2f&& val, TypeTag<Vector2f>)
{ {
instance.PushInstance<Vector2d>("Vector2", val); state.PushInstance<Vector2d>("Vector2", val);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Vector2ui&& val, TypeTag<Vector2ui>) inline int LuaImplReplyVal(const LuaState& state, Vector2ui&& val, TypeTag<Vector2ui>)
{ {
instance.PushInstance<Vector2d>("Vector2", val); state.PushInstance<Vector2d>("Vector2", val);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Vector3d&& val, TypeTag<Vector3d>) inline int LuaImplReplyVal(const LuaState& state, Vector3d&& val, TypeTag<Vector3d>)
{ {
instance.PushInstance<Vector3d>("Vector3", val); state.PushInstance<Vector3d>("Vector3", val);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Vector3f&& val, TypeTag<Vector3f>) inline int LuaImplReplyVal(const LuaState& state, Vector3f&& val, TypeTag<Vector3f>)
{ {
instance.PushInstance<Vector3d>("Vector3", val); state.PushInstance<Vector3d>("Vector3", val);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Vector3ui&& val, TypeTag<Vector3ui>) inline int LuaImplReplyVal(const LuaState& state, Vector3ui&& val, TypeTag<Vector3ui>)
{ {
instance.PushInstance<Vector3d>("Vector3", val); state.PushInstance<Vector3d>("Vector3", val);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::Entity* ptr, TypeTag<Ndk::Entity*>) inline int LuaImplReplyVal(const LuaState& state, Ndk::Entity* ptr, TypeTag<Ndk::Entity*>)
{ {
instance.PushInstance<Ndk::EntityHandle>("Entity", ptr); state.PushInstance<Ndk::EntityHandle>("Entity", ptr);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::Application* ptr, TypeTag<Ndk::Application*>) inline int LuaImplReplyVal(const LuaState& state, Ndk::Application* ptr, TypeTag<Ndk::Application*>)
{ {
instance.PushInstance<Ndk::Application*>("Application", ptr); state.PushInstance<Ndk::Application*>("Application", ptr);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::EntityHandle&& handle, TypeTag<Ndk::EntityHandle>) inline int LuaImplReplyVal(const LuaState& state, Ndk::EntityHandle&& handle, TypeTag<Ndk::EntityHandle>)
{ {
instance.PushInstance<Ndk::EntityHandle>("Entity", handle); state.PushInstance<Ndk::EntityHandle>("Entity", handle);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::NodeComponentHandle&& handle, TypeTag<Ndk::NodeComponentHandle>) inline int LuaImplReplyVal(const LuaState& state, Ndk::NodeComponentHandle&& handle, TypeTag<Ndk::NodeComponentHandle>)
{ {
instance.PushInstance<Ndk::NodeComponentHandle>("NodeComponent", handle); state.PushInstance<Ndk::NodeComponentHandle>("NodeComponent", handle);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::VelocityComponentHandle&& handle, TypeTag<Ndk::VelocityComponentHandle>) inline int LuaImplReplyVal(const LuaState& state, Ndk::VelocityComponentHandle&& handle, TypeTag<Ndk::VelocityComponentHandle>)
{ {
instance.PushInstance<Ndk::VelocityComponentHandle>("VelocityComponent", handle); state.PushInstance<Ndk::VelocityComponentHandle>("VelocityComponent", handle);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::World* ptr, TypeTag<Ndk::World*>) inline int LuaImplReplyVal(const LuaState& state, Ndk::World* ptr, TypeTag<Ndk::World*>)
{ {
instance.PushInstance<Ndk::WorldHandle>("World", ptr); state.PushInstance<Ndk::WorldHandle>("World", ptr);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::WorldHandle&& handle, TypeTag<Ndk::WorldHandle>) inline int LuaImplReplyVal(const LuaState& state, Ndk::WorldHandle&& handle, TypeTag<Ndk::WorldHandle>)
{ {
instance.PushInstance<Ndk::WorldHandle>("World", handle); state.PushInstance<Ndk::WorldHandle>("World", handle);
return 1; return 1;
} }
#ifndef NDK_SERVER #ifndef NDK_SERVER
inline int LuaImplReplyVal(const LuaInstance& instance, MaterialRef&& handle, TypeTag<MaterialRef>) inline int LuaImplReplyVal(const LuaState& state, MaterialRef&& handle, TypeTag<MaterialRef>)
{ {
instance.PushInstance<MaterialRef>("Material", handle); state.PushInstance<MaterialRef>("Material", handle);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, const SoundBuffer* val, TypeTag<const SoundBuffer*>) inline int LuaImplReplyVal(const LuaState& state, const SoundBuffer* val, TypeTag<const SoundBuffer*>)
{ {
instance.PushInstance<SoundBufferConstRef>("SoundBuffer", val); state.PushInstance<SoundBufferConstRef>("SoundBuffer", val);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, SpriteRef&& handle, TypeTag<SpriteRef>) inline int LuaImplReplyVal(const LuaState& state, SpriteRef&& handle, TypeTag<SpriteRef>)
{ {
instance.PushInstance<SpriteRef>("Sprite", handle); state.PushInstance<SpriteRef>("Sprite", handle);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, TextureRef&& handle, TypeTag<TextureRef>) inline int LuaImplReplyVal(const LuaState& state, TextureRef&& handle, TypeTag<TextureRef>)
{ {
instance.PushInstance<TextureRef>("Texture", handle); state.PushInstance<TextureRef>("Texture", handle);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::CameraComponentHandle&& handle, TypeTag<Ndk::CameraComponentHandle>) inline int LuaImplReplyVal(const LuaState& state, Ndk::CameraComponentHandle&& handle, TypeTag<Ndk::CameraComponentHandle>)
{ {
instance.PushInstance<Ndk::CameraComponentHandle>("CameraComponent", handle); state.PushInstance<Ndk::CameraComponentHandle>("CameraComponent", handle);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::ConsoleHandle&& handle, TypeTag<Ndk::ConsoleHandle>) inline int LuaImplReplyVal(const LuaState& state, Ndk::ConsoleHandle&& handle, TypeTag<Ndk::ConsoleHandle>)
{ {
instance.PushInstance<Ndk::ConsoleHandle>("Console", handle); state.PushInstance<Ndk::ConsoleHandle>("Console", handle);
return 1; return 1;
} }
inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::GraphicsComponentHandle&& handle, TypeTag<Ndk::GraphicsComponentHandle>) inline int LuaImplReplyVal(const LuaState& state, Ndk::GraphicsComponentHandle&& handle, TypeTag<Ndk::GraphicsComponentHandle>)
{ {
instance.PushInstance<Ndk::GraphicsComponentHandle>("GraphicsComponent", handle); state.PushInstance<Ndk::GraphicsComponentHandle>("GraphicsComponent", handle);
return 1; return 1;
} }
#endif #endif

View File

@ -1,4 +1,4 @@
// Copyright (C) 2017 Jérôme Leclercq // Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit" // This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp // For conditions of distribution and use, see copyright notice in Prerequesites.hpp
@ -10,6 +10,7 @@
#include <NDK/Prerequesites.hpp> #include <NDK/Prerequesites.hpp>
#include <NDK/State.hpp> #include <NDK/State.hpp>
#include <memory> #include <memory>
#include <vector>
namespace Ndk namespace Ndk
{ {
@ -25,14 +26,21 @@ namespace Ndk
inline const std::shared_ptr<State>& GetCurrentState() const; inline const std::shared_ptr<State>& GetCurrentState() const;
inline bool IsTopState(const State* state) const;
inline std::shared_ptr<State> PopState();
inline bool PopStatesUntil(std::shared_ptr<State> state);
inline void PushState(std::shared_ptr<State> state);
inline void SetState(std::shared_ptr<State> state);
inline bool Update(float elapsedTime); inline bool Update(float elapsedTime);
inline StateMachine& operator=(StateMachine&& fsm) = default; inline StateMachine& operator=(StateMachine&& fsm) = default;
StateMachine& operator=(const StateMachine&) = delete; StateMachine& operator=(const StateMachine&) = delete;
private: private:
std::shared_ptr<State> m_currentState; std::vector<std::shared_ptr<State>> m_states;
std::shared_ptr<State> m_nextState;
}; };
} }

View File

@ -3,7 +3,6 @@
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp // For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <NDK/StateMachine.hpp>
#include <utility> #include <utility>
namespace Ndk namespace Ndk
@ -11,7 +10,7 @@ namespace Ndk
/*! /*!
* \ingroup NDK * \ingroup NDK
* \class Ndk::StateMachine * \class Ndk::StateMachine
* \brief NDK class that represents a state machine, to represent the multiple states of your program * \brief NDK class that represents a state machine, to represent the multiple states of your program as a stack
*/ */
/*! /*!
@ -23,61 +22,153 @@ namespace Ndk
* \remark Produces a NazaraAssert if nullptr is given * \remark Produces a NazaraAssert if nullptr is given
*/ */
inline StateMachine::StateMachine(std::shared_ptr<State> originalState) : inline StateMachine::StateMachine(std::shared_ptr<State> originalState)
m_currentState(std::move(originalState))
{ {
NazaraAssert(m_currentState, "StateMachine must have a state to begin with"); NazaraAssert(originalState, "StateMachine must have a state to begin with");
m_currentState->Enter(*this); PushState(std::move(originalState));
} }
/*! /*!
* \brief Destructs the object * \brief Destructs the object
* *
* \remark Calls "Leave" on the state * \remark Calls "Leave" on all the states
*/ */
inline StateMachine::~StateMachine() inline StateMachine::~StateMachine()
{ {
m_currentState->Leave(*this); for (std::shared_ptr<State>& state : m_states)
state->Leave(*this);
} }
/*! /*!
* \brief Changes the current state of the machine * \brief Replaces the current state on the top of the machine
* *
* \param state Next state to represent * \param state State to replace the top one if it is nullptr, no action is performed
*/ */
inline void StateMachine::ChangeState(std::shared_ptr<State> state) inline void StateMachine::ChangeState(std::shared_ptr<State> state)
{ {
m_nextState = std::move(state); if (state)
{
PopState();
PushState(std::move(state));
}
} }
/*! /*!
* \brief Gets the current state of the machine * \brief Gets the current state on the top of the machine
* \return A constant reference to the state * \return A constant reference to the state
*
* \remark The stack is supposed to be non empty, otherwise it is undefined behaviour
*
* \see PopStatesUntil
*/ */
inline const std::shared_ptr<State>& StateMachine::GetCurrentState() const inline const std::shared_ptr<State>& StateMachine::GetCurrentState() const
{ {
return m_currentState; return m_states.back();
} }
/*! /*!
* \brief Updates the state * \brief Checks whether the state is on the top of the machine
* \return True if update is successful * \return true If it is the case
*
* \param state State to compare the top with
*/
inline bool StateMachine::IsTopState(const State* state) const
{
if (m_states.empty())
return false;
return m_states.back().get() == state;
}
/*!
* \brief Pops the state on the top of the machine
* \return Old state on the top, nullptr if stack was empty
*
* \remark This method can completely empty the stack
*/
inline std::shared_ptr<State> StateMachine::PopState()
{
if (m_states.empty())
return nullptr;
m_states.back()->Leave(*this);
std::shared_ptr<State> oldTopState = std::move(m_states.back());
m_states.pop_back();
return oldTopState;
}
/*!
* \brief Pops all the states of the machine until a specific one is reached
* \return true If that specific state is on top, false if stack is empty
*
* \param state State to find on the stack if it is nullptr, no action is performed
*
* \remark This method can completely empty the stack
*/
inline bool StateMachine::PopStatesUntil(std::shared_ptr<State> state)
{
if (!state)
return false;
while (!m_states.empty() && !IsTopState(state.get()))
PopState();
return !m_states.empty();
}
/*!
* \brief Pushes a new state on the top of the machine
*
* \param state Next state to represent if it is nullptr, it performs no action
*
* \remark Produces a NazaraAssert if the same state is pushed two times on the stack
*/
inline void StateMachine::PushState(std::shared_ptr<State> state)
{
if (state)
{
NazaraAssert(std::find(m_states.begin(), m_states.end(), state) == m_states.end(), "The same state was pushed two times");
m_states.push_back(std::move(state));
m_states.back()->Enter(*this);
}
}
/*!
* \brief Pops every states of the machine to put a new one
*
* \param state State to reset the stack with if it is nullptr, no action is performed
*/
inline void StateMachine::SetState(std::shared_ptr<State> state)
{
if (state)
{
while (!m_states.empty())
PopState();
PushState(std::move(state));
}
}
/*!
* \brief Updates all the states
* \return true If update is successful for everyone of them
* *
* \param elapsedTime Delta time used for the update * \param elapsedTime Delta time used for the update
*/ */
inline bool StateMachine::Update(float elapsedTime) inline bool StateMachine::Update(float elapsedTime)
{ {
if (m_nextState) return std::all_of(m_states.begin(), m_states.end(), [=](std::shared_ptr<State>& state) {
{ return state->Update(*this, elapsedTime);
m_currentState->Leave(*this); });
m_currentState = std::move(m_nextState);
m_currentState->Enter(*this);
}
return m_currentState->Update(*this, elapsedTime);
} }
} }

View File

@ -57,7 +57,7 @@ namespace Ndk
std::unique_ptr<Nz::AbstractRenderTechnique> m_renderTechnique; std::unique_ptr<Nz::AbstractRenderTechnique> m_renderTechnique;
std::vector<GraphicsComponentCullingList::VolumeEntry> m_volumeEntries; std::vector<GraphicsComponentCullingList::VolumeEntry> m_volumeEntries;
EntityList m_cameras; std::vector<EntityHandle> m_cameras;
EntityList m_drawables; EntityList m_drawables;
EntityList m_directionalLights; EntityList m_directionalLights;
EntityList m_lights; EntityList m_lights;

View File

@ -6,7 +6,9 @@
#define NDK_WIDGETS_GLOBAL_HPP #define NDK_WIDGETS_GLOBAL_HPP
#include <NDK/Widgets/ButtonWidget.hpp> #include <NDK/Widgets/ButtonWidget.hpp>
#include <NDK/Widgets/CheckboxWidget.hpp>
#include <NDK/Widgets/LabelWidget.hpp> #include <NDK/Widgets/LabelWidget.hpp>
#include <NDK/Widgets/ProgressBarWidget.hpp>
#include <NDK/Widgets/TextAreaWidget.hpp> #include <NDK/Widgets/TextAreaWidget.hpp>
#endif // NDK_WIDGETS_GLOBAL_HPP #endif // NDK_WIDGETS_GLOBAL_HPP

View File

@ -9,5 +9,7 @@ namespace Ndk
inline void ButtonWidget::UpdateText(const Nz::AbstractTextDrawer& drawer) inline void ButtonWidget::UpdateText(const Nz::AbstractTextDrawer& drawer)
{ {
m_textSprite->Update(drawer); m_textSprite->Update(drawer);
Layout();
} }
} }

View File

@ -0,0 +1,104 @@
// Copyright (C) 2017 Samy Bensaid
// 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_WIDGETS_CHECKBOXWIDGET_HPP
#define NDK_WIDGETS_CHECKBOXWIDGET_HPP
#include <NDK/Prerequesites.hpp>
#include <NDK/BaseWidget.hpp>
#include <NDK/Widgets/Enums.hpp>
#include <NDK/Components/NodeComponent.hpp>
#include <Nazara/Renderer/Texture.hpp>
#include <Nazara/Utility/AbstractTextDrawer.hpp>
#include <Nazara/Graphics/Sprite.hpp>
#include <Nazara/Graphics/TextSprite.hpp>
#include <Nazara/Math/Vector2.hpp>
#include <Nazara/Math/Rect.hpp>
namespace Ndk
{
class World;
class NDK_API CheckboxWidget : public BaseWidget
{
friend class Sdk;
public:
CheckboxWidget(BaseWidget* parent = nullptr);
CheckboxWidget(const CheckboxWidget&) = delete;
CheckboxWidget(CheckboxWidget&&) = default;
~CheckboxWidget() = default;
//virtual CheckboxWidget* Clone() const = 0;
inline void EnableAdaptativeMargin(bool enable = true);
inline void EnableCheckbox(bool enable = true);
inline void EnableTristate(bool enable = true);
inline bool IsCheckboxEnabled() const;
inline bool IsMarginAdaptative() const;
inline bool IsTristateEnabled() const;
inline const Nz::Vector2f& GetCheckboxSize() const;
inline Nz::Vector2f GetCheckboxBorderSize() const;
inline CheckboxState GetState() const;
inline float GetTextMargin() const;
inline void SetCheckboxSize(const Nz::Vector2f& size);
CheckboxState SwitchToNextState();
void SetState(CheckboxState state);
inline void SetTextMargin(float margin);
void ResizeToContent() override;
inline void UpdateText(const Nz::AbstractTextDrawer& drawer);
CheckboxWidget& operator=(const CheckboxWidget&) = delete;
CheckboxWidget& operator=(CheckboxWidget&&) = default;
NazaraSignal(OnStateChanged, const CheckboxWidget* /*checkbox*/);
private:
static bool Initialize();
static void Uninitialize();
void Layout() override;
void UpdateCheckbox();
void OnMouseButtonRelease(int x, int y, Nz::Mouse::Button button) override;
inline bool ContainsCheckbox(int x, int y) const;
EntityHandle m_checkboxBorderEntity;
EntityHandle m_checkboxBackgroundEntity;
EntityHandle m_checkboxContentEntity;
EntityHandle m_textEntity;
Nz::TextureRef m_checkMark;
Nz::SpriteRef m_checkboxContentSprite;
Nz::SpriteRef m_checkboxBorderSprite;
Nz::SpriteRef m_checkboxBackgroundSprite;
Nz::TextSpriteRef m_textSprite;
static Nz::Color s_backgroundColor;
static Nz::Color s_disabledBackgroundColor;
static Nz::Color s_disabledBorderColor;
static Nz::Color s_borderColor;
bool m_adaptativeMargin;
bool m_checkboxEnabled;
bool m_tristateEnabled;
static float s_borderScale;
float m_textMargin;
CheckboxState m_state;
};
}
#include <NDK/Widgets/CheckboxWidget.inl>
#endif // NDK_WIDGETS_CHECKBOXWIDGET_HPP

View File

@ -0,0 +1,91 @@
// Copyright (C) 2017 Samy Bensaid
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
namespace Ndk
{
inline void CheckboxWidget::EnableAdaptativeMargin(bool enable)
{
m_adaptativeMargin = enable;
Layout();
}
inline void CheckboxWidget::EnableCheckbox(bool enable)
{
m_checkboxEnabled = enable;
UpdateCheckbox();
}
inline void CheckboxWidget::EnableTristate(bool enable)
{
m_tristateEnabled = enable;
if (m_tristateEnabled && GetState() == CheckboxState_Tristate)
SetState(CheckboxState_Unchecked);
}
inline bool CheckboxWidget::IsCheckboxEnabled() const
{
return m_checkboxEnabled;
}
inline bool CheckboxWidget::IsMarginAdaptative() const
{
return m_adaptativeMargin;
}
inline bool CheckboxWidget::IsTristateEnabled() const
{
return m_tristateEnabled;
}
inline const Nz::Vector2f& CheckboxWidget::GetCheckboxSize() const
{
return m_checkboxBorderSprite->GetSize();
}
inline Nz::Vector2f CheckboxWidget::GetCheckboxBorderSize() const
{
return GetCheckboxSize() / s_borderScale;
}
inline CheckboxState CheckboxWidget::GetState() const
{
return m_state;
}
inline float CheckboxWidget::GetTextMargin() const
{
return m_textMargin;
}
inline void CheckboxWidget::SetCheckboxSize(const Nz::Vector2f& size)
{
m_checkboxBorderSprite->SetSize(size);
m_checkboxBackgroundSprite->SetSize(size - GetCheckboxBorderSize() * 2.f);
m_checkboxContentSprite->SetSize(GetCheckboxSize() - GetCheckboxBorderSize() * 2.f - Nz::Vector2f { 4.f, 4.f });
Layout();
}
inline void CheckboxWidget::SetTextMargin(float margin)
{
m_textMargin = margin;
Layout();
}
inline void CheckboxWidget::UpdateText(const Nz::AbstractTextDrawer& drawer)
{
m_textSprite->Update(drawer);
Layout();
}
inline bool CheckboxWidget::ContainsCheckbox(int x, int y) const
{
Nz::Vector2f checkboxSize = GetCheckboxSize();
Nz::Vector3f pos = m_checkboxBorderEntity->GetComponent<NodeComponent>().GetPosition(Nz::CoordSys_Local);
return x > pos.x && x < pos.x + checkboxSize.x &&
y > pos.y && y < pos.y + checkboxSize.y;
}
}

View File

@ -0,0 +1,22 @@
// Copyright (C) 2017 Samy Bensaid
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#pragma once
#ifndef NAZARA_ENUMS_SDK_HPP
#define NAZARA_ENUMS_SDK_HPP
namespace Ndk
{
enum CheckboxState
{
CheckboxState_Checked,
CheckboxState_Tristate,
CheckboxState_Unchecked,
CheckboxState_Max = CheckboxState_Unchecked
};
}
#endif // NAZARA_ENUMS_SDK_HPP

View File

@ -0,0 +1,106 @@
// Copyright (C) 2017 Samy Bensaid
// 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_WIDGETS_PROGRESSBARWIDGET_HPP
#define NDK_WIDGETS_PROGRESSBARWIDGET_HPP
#include <NDK/Prerequesites.hpp>
#include <NDK/BaseWidget.hpp>
#include <Nazara/Renderer/Texture.hpp>
#include <Nazara/Utility/SimpleTextDrawer.hpp>
#include <Nazara/Graphics/Sprite.hpp>
#include <Nazara/Graphics/TextSprite.hpp>
#include <Nazara/Core/Color.hpp>
#include <Nazara/Math/Vector2.hpp>
#include <Nazara/Math/Vector3.hpp>
namespace Ndk
{
class World;
class NDK_API ProgressBarWidget : public BaseWidget
{
friend class Sdk;
public:
ProgressBarWidget(BaseWidget* parent = nullptr);
ProgressBarWidget(const ProgressBarWidget&) = delete;
ProgressBarWidget(ProgressBarWidget&&) = default;
~ProgressBarWidget() = default;
//virtual ProgressBarWidget* Clone() const = 0;
inline void EnableText(bool enable = true);
inline void EnableBorder(bool enable = true);
inline bool IsTextEnabled() const;
inline bool IsBorderEnabled() const;
inline unsigned GetPercentageValue() const;
inline Nz::Vector2f GetProgressBarSize() const;
inline Nz::Vector2f GetProgressBarBorderSize() const;
inline float GetTextMargin() const;
inline const Nz::Color& GetBarBackgroundColor() const;
inline const Nz::Color& GetBarBackgroundCornerColor() const;
inline const Nz::Color& GetBarColor() const;
inline const Nz::Color& GetBarCornerColor() const;
inline const Nz::TextureRef& GetBarBackgroundTexture() const;
inline const Nz::TextureRef& GetBarTexture() const;
static const Nz::Color& GetDefaultBarColor();
static const Nz::Color& GetDefaultBarCornerColor();
static const Nz::Color& GetDefaultBarBackgroundColor();
static const Nz::Color& GetDefaultBarBackgroundCornerColor();
inline void SetBarBackgroundColor(const Nz::Color& globalColor, const Nz::Color& cornerColor);
inline void SetBarBackgroundTexture(Nz::TextureRef texture, bool resetColors = true);
inline void SetBarColor(const Nz::Color& globalColor, const Nz::Color& cornerColor);
inline void SetBarTexture(Nz::TextureRef texture, bool resetColors = true);
inline void SetPercentageValue(unsigned percentage);
inline void SetTextMargin(float margin);
inline void SetTextColor(const Nz::Color& color);
inline void ResizeToContent() override {}
NazaraSignal(OnValueChanged, const ProgressBarWidget* /*progressBar*/);
private:
void Layout() override;
inline void UpdateText();
EntityHandle m_borderEntity;
EntityHandle m_barEntity;
EntityHandle m_textEntity;
static Nz::Color s_borderColor;
static Nz::Color s_barBackgroundColor;
static Nz::Color s_barBackgroundCornerColor;
static Nz::Color s_barColor;
static Nz::Color s_barCornerColor;
Nz::Color m_textColor;
Nz::SpriteRef m_borderSprite;
Nz::SpriteRef m_barBackgroundSprite;
Nz::SpriteRef m_barSprite;
Nz::TextSpriteRef m_textSprite;
static float s_borderScale;
float m_textMargin;
unsigned m_value;
};
}
#include <NDK/Widgets/ProgressBarWidget.inl>
#endif // NDK_WIDGETS_PROGRESSBARWIDGET_HPP

View File

@ -0,0 +1,156 @@
// Copyright (C) 2017 Samy Bensaid
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
namespace Ndk
{
inline void ProgressBarWidget::EnableText(bool enable)
{
m_textEntity->Enable(enable);
Layout();
}
inline void ProgressBarWidget::EnableBorder(bool enable)
{
m_borderEntity->Enable(enable);
}
inline bool ProgressBarWidget::IsTextEnabled() const
{
return m_textEntity->IsEnabled();
}
inline bool ProgressBarWidget::IsBorderEnabled() const
{
return m_borderEntity->IsEnabled();
}
inline unsigned ProgressBarWidget::GetPercentageValue() const
{
return m_value;
}
inline Nz::Vector2f ProgressBarWidget::GetProgressBarSize() const
{
Nz::Vector3f progressBarSize = m_borderSprite->GetBoundingVolume().obb.localBox.GetLengths();
if (IsTextEnabled())
{
Nz::Vector3f textSize = m_textSprite->GetBoundingVolume().obb.localBox.GetLengths();
progressBarSize -= { textSize.x + m_textMargin, 0.f, 0.f };
}
return { progressBarSize.x, progressBarSize.y };
}
inline Nz::Vector2f ProgressBarWidget::GetProgressBarBorderSize() const
{
Nz::Vector2f barSize = GetProgressBarSize();
return { barSize.y / s_borderScale, barSize.y / s_borderScale };
}
inline float ProgressBarWidget::GetTextMargin() const
{
return m_textMargin;
}
inline const Nz::Color& ProgressBarWidget::GetBarBackgroundColor() const
{
return m_barBackgroundSprite->GetColor();
}
inline const Nz::Color& ProgressBarWidget::GetBarBackgroundCornerColor() const
{
return m_barBackgroundSprite->GetCornerColor(Nz::RectCorner_LeftTop);
}
inline const Nz::Color& ProgressBarWidget::GetBarColor() const
{
return m_barSprite->GetColor();
}
inline const Nz::Color& ProgressBarWidget::GetBarCornerColor() const
{
return m_barSprite->GetCornerColor(Nz::RectCorner_LeftTop);
}
inline const Nz::TextureRef& ProgressBarWidget::GetBarBackgroundTexture() const
{
return m_barBackgroundSprite->GetMaterial()->GetDiffuseMap();
}
inline const Nz::TextureRef& ProgressBarWidget::GetBarTexture() const
{
return m_barSprite->GetMaterial()->GetDiffuseMap();
}
inline void ProgressBarWidget::SetBarBackgroundColor(const Nz::Color& globalColor, const Nz::Color& cornerColor)
{
m_barBackgroundSprite->SetColor(globalColor);
m_barBackgroundSprite->SetCornerColor(Nz::RectCorner_LeftTop, cornerColor);
m_barBackgroundSprite->SetCornerColor(Nz::RectCorner_RightTop, cornerColor);
m_barBackgroundSprite->SetCornerColor(Nz::RectCorner_LeftBottom, globalColor);
m_barBackgroundSprite->SetCornerColor(Nz::RectCorner_RightBottom, globalColor);
}
inline void ProgressBarWidget::SetBarBackgroundTexture(Nz::TextureRef texture, bool resetColors)
{
m_barBackgroundSprite->SetTexture(texture, false);
if (resetColors)
SetBarBackgroundColor(Nz::Color::White, Nz::Color::White);
}
inline void ProgressBarWidget::SetBarColor(const Nz::Color& globalColor, const Nz::Color& cornerColor)
{
m_barSprite->SetColor(globalColor);
m_barSprite->SetCornerColor(Nz::RectCorner_LeftTop, cornerColor);
m_barSprite->SetCornerColor(Nz::RectCorner_RightTop, cornerColor);
m_barSprite->SetCornerColor(Nz::RectCorner_LeftBottom, globalColor);
m_barSprite->SetCornerColor(Nz::RectCorner_RightBottom, globalColor);
}
inline void ProgressBarWidget::SetBarTexture(Nz::TextureRef texture, bool resetColors)
{
m_barSprite->SetTexture(texture, false);
if (resetColors)
SetBarColor(Nz::Color::White, Nz::Color::White);
}
inline void ProgressBarWidget::SetPercentageValue(unsigned percentage)
{
m_value = percentage;
OnValueChanged(this);
Layout();
}
inline void ProgressBarWidget::SetTextMargin(float margin)
{
m_textMargin = margin;
if (IsTextEnabled())
Layout();
}
inline void ProgressBarWidget::SetTextColor(const Nz::Color& color)
{
m_textColor = color;
UpdateText();
}
inline void ProgressBarWidget::UpdateText()
{
if (IsTextEnabled())
{
Nz::Vector2f size = GetContentSize();
m_textSprite->Update(Nz::SimpleTextDrawer::Draw(Nz::String::Number(m_value).Append('%'),
static_cast<unsigned>(std::min(size.x, size.y) / 2.f), 0u, m_textColor));
}
}
}

View File

@ -32,7 +32,8 @@ namespace Ndk
inline void EnableMultiline(bool enable = true); inline void EnableMultiline(bool enable = true);
inline std::size_t GetCursorPosition() const; inline const Nz::Vector2ui& GetCursorPosition() const;
inline std::size_t GetGlyphUnderCursor() const;
inline std::size_t GetLineCount() const; inline std::size_t GetLineCount() const;
inline const Nz::String& GetText() const; inline const Nz::String& GetText() const;
inline const Nz::Color& GetTextColor() const; inline const Nz::Color& GetTextColor() const;
@ -43,10 +44,12 @@ namespace Ndk
inline bool IsReadOnly() const; inline bool IsReadOnly() const;
inline void MoveCursor(int offset); inline void MoveCursor(int offset);
inline void MoveCursor(const Nz::Vector2i& offset);
void ResizeToContent() override; void ResizeToContent() override;
inline void SetCursorPosition(std::size_t cursorPosition); inline void SetCursorPosition(std::size_t glyphIndex);
inline void SetCursorPosition(Nz::Vector2ui cursorPosition);
inline void SetReadOnly(bool readOnly = true); inline void SetReadOnly(bool readOnly = true);
inline void SetText(const Nz::String& text); inline void SetText(const Nz::String& text);
inline void SetTextColor(const Nz::Color& text); inline void SetTextColor(const Nz::Color& text);
@ -82,7 +85,8 @@ namespace Ndk
Nz::SimpleTextDrawer m_drawer; Nz::SimpleTextDrawer m_drawer;
Nz::SpriteRef m_cursorSprite; Nz::SpriteRef m_cursorSprite;
Nz::TextSpriteRef m_textSprite; Nz::TextSpriteRef m_textSprite;
std::size_t m_cursorPosition; Nz::Vector2ui m_cursorPosition;
std::size_t m_cursorGlyph;
bool m_multiLineEnabled; bool m_multiLineEnabled;
bool m_readOnly; bool m_readOnly;
}; };

View File

@ -20,11 +20,16 @@ namespace Ndk
m_multiLineEnabled = enable; m_multiLineEnabled = enable;
} }
inline std::size_t TextAreaWidget::GetCursorPosition() const inline const Nz::Vector2ui& TextAreaWidget::GetCursorPosition() const
{ {
return m_cursorPosition; return m_cursorPosition;
} }
inline std::size_t Ndk::TextAreaWidget::GetGlyphUnderCursor() const
{
return m_cursorGlyph;
}
inline std::size_t TextAreaWidget::GetLineCount() const inline std::size_t TextAreaWidget::GetLineCount() const
{ {
return m_drawer.GetLineCount(); return m_drawer.GetLineCount();
@ -53,22 +58,84 @@ namespace Ndk
inline void TextAreaWidget::MoveCursor(int offset) inline void TextAreaWidget::MoveCursor(int offset)
{ {
if (offset >= 0) if (offset >= 0)
SetCursorPosition(m_cursorPosition += static_cast<std::size_t>(offset)); SetCursorPosition(m_cursorGlyph + static_cast<std::size_t>(offset));
else else
{ {
std::size_t nOffset = static_cast<std::size_t>(-offset); std::size_t nOffset = static_cast<std::size_t>(-offset);
if (nOffset >= m_cursorPosition) if (nOffset >= m_cursorGlyph)
SetCursorPosition(0); SetCursorPosition(0);
else else
SetCursorPosition(m_cursorPosition - nOffset); SetCursorPosition(m_cursorGlyph - nOffset);
} }
} }
inline void TextAreaWidget::SetCursorPosition(std::size_t cursorPosition) inline void TextAreaWidget::MoveCursor(const Nz::Vector2i& offset)
{ {
OnTextAreaCursorMove(this, &cursorPosition); auto BoundOffset = [] (unsigned int cursorPosition, int offset) -> unsigned int
{
if (offset >= 0)
return cursorPosition + offset;
else
{
unsigned int nOffset = static_cast<unsigned int>(-offset);
if (nOffset >= cursorPosition)
return 0;
else
return cursorPosition - nOffset;
}
};
m_cursorPosition = std::min(cursorPosition, m_drawer.GetGlyphCount()); Nz::Vector2ui cursorPosition = m_cursorPosition;
cursorPosition.x = BoundOffset(static_cast<unsigned int>(cursorPosition.x), offset.x);
cursorPosition.y = BoundOffset(static_cast<unsigned int>(cursorPosition.y), offset.y);
SetCursorPosition(cursorPosition);
}
inline void TextAreaWidget::SetCursorPosition(std::size_t glyphIndex)
{
OnTextAreaCursorMove(this, &glyphIndex);
m_cursorGlyph = std::min(glyphIndex, m_drawer.GetGlyphCount());
std::size_t lineCount = m_drawer.GetLineCount();
std::size_t line = 0U;
for (std::size_t i = line + 1; i < lineCount; ++i)
{
if (m_drawer.GetLine(i).glyphIndex > m_cursorGlyph)
break;
line = i;
}
const auto& lineInfo = m_drawer.GetLine(line);
m_cursorPosition.y = line;
m_cursorPosition.x = m_cursorGlyph - lineInfo.glyphIndex;
RefreshCursor();
}
inline void TextAreaWidget::SetCursorPosition(Nz::Vector2ui cursorPosition)
{
std::size_t lineCount = m_drawer.GetLineCount();
if (cursorPosition.y >= lineCount)
cursorPosition.y = static_cast<unsigned int>(lineCount - 1);
m_cursorPosition = cursorPosition;
const auto& lineInfo = m_drawer.GetLine(cursorPosition.y);
if (cursorPosition.y + 1 < lineCount)
{
const auto& nextLineInfo = m_drawer.GetLine(cursorPosition.y + 1);
cursorPosition.x = std::min(cursorPosition.x, static_cast<unsigned int>(nextLineInfo.glyphIndex - lineInfo.glyphIndex - 1));
}
std::size_t glyphIndex = lineInfo.glyphIndex + cursorPosition.x;
OnTextAreaCursorMove(this, &glyphIndex);
m_cursorGlyph = std::min(glyphIndex, m_drawer.GetGlyphCount());
RefreshCursor(); RefreshCursor();
} }

View File

@ -10,6 +10,7 @@
#include <Nazara/Core/Bitset.hpp> #include <Nazara/Core/Bitset.hpp>
#include <Nazara/Core/HandledObject.hpp> #include <Nazara/Core/HandledObject.hpp>
#include <NDK/Entity.hpp> #include <NDK/Entity.hpp>
#include <NDK/EntityList.hpp>
#include <NDK/System.hpp> #include <NDK/System.hpp>
#include <algorithm> #include <algorithm>
#include <memory> #include <memory>
@ -28,7 +29,7 @@ namespace Ndk
friend Entity; friend Entity;
public: public:
using EntityList = std::vector<EntityHandle>; using EntityVector = std::vector<EntityHandle>;
inline World(bool addDefaultSystems = true); inline World(bool addDefaultSystems = true);
World(const World&) = delete; World(const World&) = delete;
@ -41,21 +42,21 @@ namespace Ndk
template<typename SystemType, typename... Args> SystemType& AddSystem(Args&&... args); template<typename SystemType, typename... Args> SystemType& AddSystem(Args&&... args);
const EntityHandle& CreateEntity(); const EntityHandle& CreateEntity();
inline EntityList CreateEntities(unsigned int count); inline EntityVector CreateEntities(unsigned int count);
void Clear() noexcept; void Clear() noexcept;
const EntityHandle& CloneEntity(EntityId id); const EntityHandle& CloneEntity(EntityId id);
const EntityHandle& GetEntity(EntityId id); inline const EntityHandle& GetEntity(EntityId id);
inline const EntityList& GetEntities(); inline const EntityList& GetEntities() const;
inline BaseSystem& GetSystem(SystemIndex index); inline BaseSystem& GetSystem(SystemIndex index);
template<typename SystemType> SystemType& GetSystem(); template<typename SystemType> SystemType& GetSystem();
inline bool HasSystem(SystemIndex index) const; inline bool HasSystem(SystemIndex index) const;
template<typename SystemType> bool HasSystem() const; template<typename SystemType> bool HasSystem() const;
void KillEntity(Entity* entity); inline void KillEntity(Entity* entity);
inline void KillEntities(const EntityList& list); inline void KillEntities(const EntityVector& list);
inline bool IsEntityValid(const Entity* entity) const; inline bool IsEntityValid(const Entity* entity) const;
inline bool IsEntityIdValid(EntityId id) const; inline bool IsEntityIdValid(EntityId id) const;
@ -79,19 +80,22 @@ namespace Ndk
struct EntityBlock struct EntityBlock
{ {
EntityBlock(Entity&& e) : EntityBlock(Entity&& e) :
entity(std::move(e)) entity(std::move(e)),
handle(&entity)
{ {
} }
EntityBlock(EntityBlock&& block) = default; EntityBlock(EntityBlock&& block) = default;
Entity entity; Entity entity;
std::size_t aliveIndex; EntityHandle handle;
}; };
std::vector<std::unique_ptr<BaseSystem>> m_systems; std::vector<std::unique_ptr<BaseSystem>> m_systems;
std::vector<BaseSystem*> m_orderedSystems; std::vector<BaseSystem*> m_orderedSystems;
std::vector<EntityBlock> m_entities; std::vector<EntityBlock> m_entities;
std::vector<EntityBlock*> m_entityBlocks;
std::vector<std::unique_ptr<EntityBlock>> m_waitingEntities;
std::vector<EntityId> m_freeIdList; std::vector<EntityId> m_freeIdList;
EntityList m_aliveEntities; EntityList m_aliveEntities;
Nz::Bitset<Nz::UInt64> m_dirtyEntities; Nz::Bitset<Nz::UInt64> m_dirtyEntities;

View File

@ -82,9 +82,9 @@ namespace Ndk
* \param count Number of entities to create * \param count Number of entities to create
*/ */
inline World::EntityList World::CreateEntities(unsigned int count) inline World::EntityVector World::CreateEntities(unsigned int count)
{ {
EntityList list; EntityVector list;
list.reserve(count); list.reserve(count);
for (unsigned int i = 0; i < count; ++i) for (unsigned int i = 0; i < count; ++i)
@ -98,7 +98,7 @@ namespace Ndk
* \return A constant reference to the entities * \return A constant reference to the entities
*/ */
inline const World::EntityList& World::GetEntities() inline const EntityList& World::GetEntities() const
{ {
return m_aliveEntities; return m_aliveEntities;
} }
@ -164,18 +164,53 @@ namespace Ndk
return HasSystem(index); return HasSystem(index);
} }
/*!
* \brief Marks an entity for deletion
*
* \param Pointer to the entity
*
* \remark If the entity pointer is invalid, nothing is done
* \remark For safety, entities are not killed until the next world update
*/
inline void World::KillEntity(Entity* entity)
{
if (IsEntityValid(entity))
m_killedEntities.UnboundedSet(entity->GetId(), true);
}
/*! /*!
* \brief Kills a set of entities * \brief Kills a set of entities
* *
* This function has the same effect as calling KillEntity for every entity contained in the vector
*
* \param list Set of entities to kill * \param list Set of entities to kill
*/ */
inline void World::KillEntities(const EntityVector& list)
inline void World::KillEntities(const EntityList& list)
{ {
for (const EntityHandle& entity : list) for (const EntityHandle& entity : list)
KillEntity(entity); KillEntity(entity);
} }
/*!
* \brief Gets an entity
* \return A constant reference to a handle of the entity
*
* \param id Identifier of the entity
*
* \remark Handle referenced by this function can move in memory when updating the world, do not keep a reference to a handle from a world update to another
* \remark If an invalid identifier is provided, an error got triggered and an invalid handle is returned
*/
inline const EntityHandle& World::GetEntity(EntityId id)
{
if (IsEntityIdValid(id))
return m_entityBlocks[id]->handle;
else
{
NazaraError("Invalid ID");
return EntityHandle::InvalidHandle;
}
}
/*! /*!
* \brief Checks whether or not an entity is valid * \brief Checks whether or not an entity is valid
* \return true If it is the case * \return true If it is the case
@ -197,7 +232,7 @@ namespace Ndk
inline bool World::IsEntityIdValid(EntityId id) const inline bool World::IsEntityIdValid(EntityId id) const
{ {
return id < m_entities.size() && m_entities[id].entity.IsValid(); return id < m_entityBlocks.size() && m_entityBlocks[id]->entity.IsValid();
} }
/*! /*!
@ -266,10 +301,12 @@ namespace Ndk
{ {
m_aliveEntities = std::move(world.m_aliveEntities); m_aliveEntities = std::move(world.m_aliveEntities);
m_dirtyEntities = std::move(world.m_dirtyEntities); m_dirtyEntities = std::move(world.m_dirtyEntities);
m_entityBlocks = std::move(world.m_entityBlocks);
m_freeIdList = std::move(world.m_freeIdList); m_freeIdList = std::move(world.m_freeIdList);
m_killedEntities = std::move(world.m_killedEntities); m_killedEntities = std::move(world.m_killedEntities);
m_orderedSystems = std::move(world.m_orderedSystems); m_orderedSystems = std::move(world.m_orderedSystems);
m_orderedSystemsUpdated = world.m_orderedSystemsUpdated; m_orderedSystemsUpdated = world.m_orderedSystemsUpdated;
m_waitingEntities = std::move(world.m_waitingEntities);
m_entities = std::move(world.m_entities); m_entities = std::move(world.m_entities);
for (EntityBlock& block : m_entities) for (EntityBlock& block : m_entities)
@ -284,7 +321,7 @@ namespace Ndk
inline void World::Invalidate() inline void World::Invalidate()
{ {
m_dirtyEntities.Resize(m_entities.size(), false); m_dirtyEntities.Resize(m_entityBlocks.size(), false);
m_dirtyEntities.Set(true); // Activation of all bits m_dirtyEntities.Set(true); // Activation of all bits
} }

View File

@ -166,25 +166,25 @@ namespace Ndk
LuaAPI::RegisterClasses(overlay->lua); LuaAPI::RegisterClasses(overlay->lua);
// Override "print" function to add a line in the console // Override "print" function to add a line in the console
overlay->lua.PushFunction([&consoleRef] (Nz::LuaInstance& instance) overlay->lua.PushFunction([&consoleRef] (Nz::LuaState& state)
{ {
Nz::StringStream stream; Nz::StringStream stream;
unsigned int argCount = instance.GetStackTop(); unsigned int argCount = state.GetStackTop();
instance.GetGlobal("tostring"); state.GetGlobal("tostring");
for (unsigned int i = 1; i <= argCount; ++i) for (unsigned int i = 1; i <= argCount; ++i)
{ {
instance.PushValue(-1); // tostring function state.PushValue(-1); // tostring function
instance.PushValue(i); // argument state.PushValue(i); // argument
instance.Call(1, 1); state.Call(1, 1);
std::size_t length; std::size_t length;
const char* str = instance.CheckString(-1, &length); const char* str = state.CheckString(-1, &length);
if (i > 1) if (i > 1)
stream << '\t'; stream << '\t';
stream << Nz::String(str, length); stream << Nz::String(str, length);
instance.Pop(1); state.Pop(1);
} }
consoleRef.AddLine(stream); consoleRef.AddLine(stream);

View File

@ -54,6 +54,15 @@ namespace Ndk
{ {
} }
/*!
* \brief Operation to perform when the entity is destroyed and we're still attached to it
*
* \remark This is always called before the entity proper destruction, and thus its components.
*/
void BaseComponent::OnEntityDestruction()
{
}
std::vector<BaseComponent::ComponentEntry> BaseComponent::s_entries; std::vector<BaseComponent::ComponentEntry> BaseComponent::s_entries;
std::unordered_map<ComponentId, ComponentIndex> BaseComponent::s_idToIndex; std::unordered_map<ComponentId, ComponentIndex> BaseComponent::s_idToIndex;
} }

View File

@ -11,6 +11,20 @@
namespace Ndk namespace Ndk
{ {
/*!
* \ingroup NDK
* \class Ndk::BaseWidget
* \brief Abstract class serving as a base class for all widgets
*/
/*!
* \brief Constructs a BaseWidget object using another widget as its parent
*
* \param parent Parent widget, must be valid and attached to a canvas
*
* Constructs a BaseWidget object using another widget as a base.
* This will also register the widget to the canvas owning the top-most widget.
*/
BaseWidget::BaseWidget(BaseWidget* parent) : BaseWidget::BaseWidget(BaseWidget* parent) :
BaseWidget() BaseWidget()
{ {
@ -24,11 +38,19 @@ namespace Ndk
RegisterToCanvas(); RegisterToCanvas();
} }
/*!
* \brief Frees the widget, unregistering it from its canvas
*/
BaseWidget::~BaseWidget() BaseWidget::~BaseWidget()
{ {
UnregisterFromCanvas(); UnregisterFromCanvas();
} }
/*!
* \brief Destroy the widget, deleting it in the process.
*
* Calling this function immediately destroys the widget, freeing its memory.
*/
void BaseWidget::Destroy() void BaseWidget::Destroy()
{ {
NazaraAssert(this != m_canvas, "Canvas cannot be destroyed by calling Destroy()"); NazaraAssert(this != m_canvas, "Canvas cannot be destroyed by calling Destroy()");
@ -36,6 +58,9 @@ namespace Ndk
m_widgetParent->DestroyChild(this); //< This does delete us m_widgetParent->DestroyChild(this); //< This does delete us
} }
/*!
* \brief Enable or disables the widget background.
*/
void BaseWidget::EnableBackground(bool enable) void BaseWidget::EnableBackground(bool enable)
{ {
if (m_backgroundEntity.IsValid() == enable) if (m_backgroundEntity.IsValid() == enable)
@ -142,11 +167,11 @@ namespace Ndk
m_canvas->NotifyWidgetBoxUpdate(m_canvasIndex); m_canvas->NotifyWidgetBoxUpdate(m_canvasIndex);
} }
void BaseWidget::OnKeyPressed(const Nz::WindowEvent::KeyEvent& key) void BaseWidget::OnKeyPressed(const Nz::WindowEvent::KeyEvent& /*key*/)
{ {
} }
void BaseWidget::OnKeyReleased(const Nz::WindowEvent::KeyEvent& key) void BaseWidget::OnKeyReleased(const Nz::WindowEvent::KeyEvent& /*key*/)
{ {
} }
@ -154,15 +179,15 @@ namespace Ndk
{ {
} }
void BaseWidget::OnMouseMoved(int x, int y, int deltaX, int deltaY) void BaseWidget::OnMouseMoved(int /*x*/, int /*y*/, int /*deltaX*/, int /*deltaY*/)
{ {
} }
void BaseWidget::OnMouseButtonPress(int x, int y, Nz::Mouse::Button button) void BaseWidget::OnMouseButtonPress(int /*x*/, int /*y*/, Nz::Mouse::Button /*button*/)
{ {
} }
void BaseWidget::OnMouseButtonRelease(int x, int y, Nz::Mouse::Button button) void BaseWidget::OnMouseButtonRelease(int /*x*/, int /*y*/, Nz::Mouse::Button /*button*/)
{ {
} }
@ -170,11 +195,11 @@ namespace Ndk
{ {
} }
void BaseWidget::OnParentResized(const Nz::Vector2f& newSize) void BaseWidget::OnParentResized(const Nz::Vector2f& /*newSize*/)
{ {
} }
void BaseWidget::OnTextEntered(char32_t character, bool repeated) void BaseWidget::OnTextEntered(char32_t /*character*/, bool /*repeated*/)
{ {
} }

View File

@ -48,7 +48,7 @@ namespace Ndk
m_widgetBoxes.pop_back(); m_widgetBoxes.pop_back();
} }
void Canvas::OnMouseButtonPressed(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::MouseButtonEvent& event) void Canvas::OnEventMouseButtonPressed(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::MouseButtonEvent& event)
{ {
if (m_hoveredWidget) if (m_hoveredWidget)
{ {
@ -59,7 +59,7 @@ namespace Ndk
} }
} }
void Canvas::OnMouseButtonRelease(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::MouseButtonEvent & event) void Canvas::OnEventMouseButtonRelease(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::MouseButtonEvent & event)
{ {
if (m_hoveredWidget) if (m_hoveredWidget)
{ {
@ -70,7 +70,7 @@ namespace Ndk
} }
} }
void Canvas::OnMouseMoved(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::MouseMoveEvent& event) void Canvas::OnEventMouseMoved(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::MouseMoveEvent& event)
{ {
const WidgetBox* bestEntry = nullptr; const WidgetBox* bestEntry = nullptr;
float bestEntryArea = std::numeric_limits<float>::infinity(); float bestEntryArea = std::numeric_limits<float>::infinity();
@ -120,7 +120,7 @@ namespace Ndk
} }
} }
void Canvas::OnMouseLeft(const Nz::EventHandler* /*eventHandler*/) void Canvas::OnEventMouseLeft(const Nz::EventHandler* /*eventHandler*/)
{ {
if (m_hoveredWidget) if (m_hoveredWidget)
{ {
@ -129,19 +129,19 @@ namespace Ndk
} }
} }
void Canvas::OnKeyPressed(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::KeyEvent& event) void Canvas::OnEventKeyPressed(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::KeyEvent& event)
{ {
if (m_keyboardOwner) if (m_keyboardOwner)
m_keyboardOwner->OnKeyPressed(event); m_keyboardOwner->OnKeyPressed(event);
} }
void Canvas::OnKeyReleased(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::KeyEvent& event) void Canvas::OnEventKeyReleased(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::KeyEvent& event)
{ {
if (m_keyboardOwner) if (m_keyboardOwner)
m_keyboardOwner->OnKeyReleased(event); m_keyboardOwner->OnKeyReleased(event);
} }
void Canvas::OnTextEntered(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::TextEvent& event) void Canvas::OnEventTextEntered(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::TextEvent& event)
{ {
if (m_keyboardOwner) if (m_keyboardOwner)
m_keyboardOwner->OnTextEntered(event.character, event.repeated); m_keyboardOwner->OnTextEntered(event.character, event.repeated);

View File

@ -93,6 +93,17 @@ namespace Ndk
return m_projectionMatrix; return m_projectionMatrix;
} }
/*!
* \brief Gets the projection type of the camera
* \return Projection type of the camera
*/
Nz::ProjectionType CameraComponent::GetProjectionType() const
{
return m_projectionType;
}
/*! /*!
* \brief Gets the target of the camera * \brief Gets the target of the camera
* \return A constant reference to the render target of the camera * \return A constant reference to the render target of the camera

View File

@ -88,5 +88,11 @@ namespace Ndk
m_object.reset(); m_object.reset();
} }
void PhysicsComponent2D::OnEntityDestruction()
{
// Kill rigidbody before entity destruction to force contact callbacks to be called while the entity is still valid
m_object.reset();
}
ComponentIndex PhysicsComponent2D::componentIndex; ComponentIndex PhysicsComponent2D::componentIndex;
} }

View File

@ -88,5 +88,11 @@ namespace Ndk
m_object.reset(); m_object.reset();
} }
void PhysicsComponent3D::OnEntityDestruction()
{
// Kill rigid body before entity destruction to force contact callbacks to be called while the entity is still valid
m_object.reset();
}
ComponentIndex PhysicsComponent3D::componentIndex; ComponentIndex PhysicsComponent3D::componentIndex;
} }

View File

@ -34,11 +34,11 @@ namespace Ndk
* \param instance Lua instance that will interact with the world * \param instance Lua instance that will interact with the world
*/ */
Console::Console(BaseWidget* parent, Nz::LuaInstance& instance) : Console::Console(BaseWidget* parent, Nz::LuaState& state) :
BaseWidget(parent), BaseWidget(parent),
m_historyPosition(0), m_historyPosition(0),
m_defaultFont(Nz::Font::GetDefault()), m_defaultFont(Nz::Font::GetDefault()),
m_instance(instance), m_state(state),
m_characterSize(24) m_characterSize(24)
{ {
// History // History
@ -65,7 +65,7 @@ namespace Ndk
m_input->OnTextAreaKeyBackspace.Connect([](const TextAreaWidget* textArea, bool* ignoreDefaultAction) m_input->OnTextAreaKeyBackspace.Connect([](const TextAreaWidget* textArea, bool* ignoreDefaultAction)
{ {
if (textArea->GetCursorPosition() <= s_inputPrefixSize) if (textArea->GetGlyphUnderCursor() <= s_inputPrefixSize)
*ignoreDefaultAction = true; *ignoreDefaultAction = true;
}); });
@ -157,8 +157,8 @@ namespace Ndk
AddLine(input); //< With the input prefix AddLine(input); //< With the input prefix
if (!m_instance.Execute(inputCmd)) if (!m_state.Execute(inputCmd))
AddLine(m_instance.GetLastError(), Nz::Color::Red); AddLine(m_state.GetLastError(), Nz::Color::Red);
} }
/*! /*!

View File

@ -23,13 +23,16 @@ namespace Ndk
Entity::Entity(Entity&& entity) : Entity::Entity(Entity&& entity) :
HandledObject(std::move(entity)), HandledObject(std::move(entity)),
m_components(std::move(entity.m_components)), m_components(std::move(entity.m_components)),
m_containedInLists(std::move(entity.m_containedInLists)),
m_componentBits(std::move(entity.m_componentBits)), m_componentBits(std::move(entity.m_componentBits)),
m_removedComponentBits(std::move(entity.m_removedComponentBits)),
m_systemBits(std::move(entity.m_systemBits)), m_systemBits(std::move(entity.m_systemBits)),
m_id(entity.m_id), m_id(entity.m_id),
m_world(entity.m_world), m_world(entity.m_world),
m_enabled(entity.m_enabled), m_enabled(entity.m_enabled),
m_valid(entity.m_valid) m_valid(entity.m_valid)
{ {
entity.m_world = nullptr;
} }
/*! /*!
@ -53,7 +56,8 @@ namespace Ndk
Entity::~Entity() Entity::~Entity()
{ {
Destroy(); if (m_world)
Destroy();
} }
/*! /*!
@ -145,6 +149,17 @@ namespace Ndk
void Entity::Destroy() void Entity::Destroy()
{ {
OnEntityDestruction(this);
OnEntityDestruction.Clear();
// We prepare components for entity destruction (some components needs this to handle some final callbacks while the entity is still valid)
for (std::size_t i = m_componentBits.FindFirst(); i != m_componentBits.npos; i = m_componentBits.FindNext(i))
m_components[i]->OnEntityDestruction();
// Detach components while they're still attached to systems
for (std::size_t i = m_componentBits.FindFirst(); i != m_componentBits.npos; i = m_componentBits.FindNext(i))
m_components[i]->SetEntity(nullptr);
// We alert each system // We alert each system
for (std::size_t index = m_systemBits.FindFirst(); index != m_systemBits.npos; index = m_systemBits.FindNext(index)) for (std::size_t index = m_systemBits.FindFirst(); index != m_systemBits.npos; index = m_systemBits.FindNext(index))
{ {
@ -158,16 +173,19 @@ namespace Ndk
} }
m_systemBits.Clear(); m_systemBits.Clear();
// We properly destroy each component // Destroy components
for (std::size_t i = m_componentBits.FindFirst(); i != m_componentBits.npos; i = m_componentBits.FindNext(i))
m_components[i]->SetEntity(nullptr);
m_components.clear(); m_components.clear();
m_componentBits.Reset(); m_componentBits.Reset();
// And then free every handle // Free every handle
UnregisterAllHandles(); UnregisterAllHandles();
// Remove from every list
for (EntityList* list : m_containedInLists)
list->NotifyEntityDestruction(this);
m_containedInLists.clear();
m_valid = false; m_valid = false;
} }

View File

@ -0,0 +1,14 @@
// Copyright (C) 2017 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 <NDK/EntityList.hpp>
#include <NDK/World.hpp>
namespace Ndk
{
const EntityHandle& EntityList::iterator::operator*() const
{
return m_list->GetWorld()->GetEntity(static_cast<EntityId>(m_nextEntityId));
}
}

View File

@ -22,9 +22,10 @@ namespace Ndk
utility = LuaBinding_Base::BindUtility(*this); utility = LuaBinding_Base::BindUtility(*this);
#ifndef NDK_SERVER #ifndef NDK_SERVER
audio = LuaBinding_Base::BindAudio(*this); audio = LuaBinding_Base::BindAudio(*this);
renderer = LuaBinding_Base::BindRenderer(*this); renderer = LuaBinding_Base::BindRenderer(*this);
graphics = LuaBinding_Base::BindGraphics(*this); graphics = LuaBinding_Base::BindGraphics(*this);
platform = LuaBinding_Base::BindPlatform(*this);
#endif #endif
sdk = LuaBinding_Base::BindSDK(*this); sdk = LuaBinding_Base::BindSDK(*this);
@ -36,31 +37,32 @@ namespace Ndk
* \param instance Lua instance that will interact with the engine & SDK * \param instance Lua instance that will interact with the engine & SDK
*/ */
void LuaBinding::RegisterClasses(Nz::LuaInstance& instance) void LuaBinding::RegisterClasses(Nz::LuaState& state)
{ {
core->Register(instance); core->Register(state);
math->Register(instance); math->Register(state);
network->Register(instance); network->Register(state);
sdk->Register(instance); sdk->Register(state);
utility->Register(instance); utility->Register(state);
#ifndef NDK_SERVER #ifndef NDK_SERVER
audio->Register(instance); audio->Register(state);
graphics->Register(instance); graphics->Register(state);
renderer->Register(instance); renderer->Register(state);
platform->Register(state);
#endif #endif
// ComponentType (fake enumeration to expose component indexes) // ComponentType (fake enumeration to expose component indexes)
instance.PushTable(0, m_componentBinding.size()); state.PushTable(0, m_componentBinding.size());
{ {
for (const ComponentBinding& entry : m_componentBinding) for (const ComponentBinding& entry : m_componentBinding)
{ {
if (entry.name.IsEmpty()) if (entry.name.IsEmpty())
continue; continue;
instance.PushField(entry.name, entry.index); state.PushField(entry.name, entry.index);
} }
} }
instance.SetGlobal("ComponentType"); state.SetGlobal("ComponentType");
} }
} }

View File

@ -77,7 +77,7 @@ namespace Ndk
music.BindMethod("Stop", &Nz::Music::Stop); music.BindMethod("Stop", &Nz::Music::Stop);
// Manual // Manual
music.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Music& instance, std::size_t /*argumentCount*/) -> int music.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::Music& instance, std::size_t /*argumentCount*/) -> int
{ {
Nz::StringStream ss("Music("); Nz::StringStream ss("Music(");
ss << instance.GetFilePath() << ')'; ss << instance.GetFilePath() << ')';
@ -104,7 +104,7 @@ namespace Ndk
sound.BindMethod("SetPlayingOffset", &Nz::Sound::SetPlayingOffset); sound.BindMethod("SetPlayingOffset", &Nz::Sound::SetPlayingOffset);
// Manual // Manual
sound.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Sound& instance, std::size_t /*argumentCount*/) -> int sound.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::Sound& instance, std::size_t /*argumentCount*/) -> int
{ {
Nz::StringStream ss("Sound("); Nz::StringStream ss("Sound(");
if (const Nz::SoundBuffer* buffer = instance.GetBuffer()) if (const Nz::SoundBuffer* buffer = instance.GetBuffer())
@ -120,7 +120,7 @@ namespace Ndk
/*********************************** Nz::SoundBuffer **********************************/ /*********************************** Nz::SoundBuffer **********************************/
soundBuffer.Reset("SoundBuffer"); soundBuffer.Reset("SoundBuffer");
{ {
soundBuffer.SetConstructor([] (Nz::LuaInstance& lua, Nz::SoundBufferRef* instance, std::size_t argumentCount) soundBuffer.SetConstructor([] (Nz::LuaState& lua, Nz::SoundBufferRef* instance, std::size_t argumentCount)
{ {
NazaraUnused(lua); NazaraUnused(lua);
NazaraUnused(argumentCount); NazaraUnused(argumentCount);
@ -143,7 +143,7 @@ namespace Ndk
soundBuffer.BindStaticMethod("IsFormatSupported", &Nz::SoundBuffer::IsFormatSupported); soundBuffer.BindStaticMethod("IsFormatSupported", &Nz::SoundBuffer::IsFormatSupported);
// Manual // Manual
soundBuffer.BindMethod("Create", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int soundBuffer.BindMethod("Create", [] (Nz::LuaState& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int
{ {
int index = 2; int index = 2;
Nz::AudioFormat format = lua.Check<Nz::AudioFormat>(&index); Nz::AudioFormat format = lua.Check<Nz::AudioFormat>(&index);
@ -158,13 +158,13 @@ namespace Ndk
return 1; return 1;
}); });
soundBuffer.BindMethod("GetSamples", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int soundBuffer.BindMethod("GetSamples", [] (Nz::LuaState& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int
{ {
lua.PushString(reinterpret_cast<const char*>(instance->GetSamples()), instance->GetSampleCount() * sizeof(Nz::Int16)); lua.PushString(reinterpret_cast<const char*>(instance->GetSamples()), instance->GetSampleCount() * sizeof(Nz::Int16));
return 1; return 1;
}); });
soundBuffer.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int soundBuffer.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int
{ {
Nz::StringStream ss("SoundBuffer("); Nz::StringStream ss("SoundBuffer(");
if (instance->IsValid()) if (instance->IsValid())
@ -188,11 +188,11 @@ namespace Ndk
* *
* \param instance Lua instance that will interact with the Audio classes * \param instance Lua instance that will interact with the Audio classes
*/ */
void LuaBinding_Audio::Register(Nz::LuaInstance& instance) void LuaBinding_Audio::Register(Nz::LuaState& state)
{ {
music.Register(instance); music.Register(state);
sound.Register(instance); sound.Register(state);
soundBuffer.Register(instance); soundBuffer.Register(state);
soundEmitter.Register(instance); soundEmitter.Register(state);
} }
} }

View File

@ -32,28 +32,28 @@ namespace Ndk
stream.BindMethod("IsWritable", &Nz::Stream::IsWritable); stream.BindMethod("IsWritable", &Nz::Stream::IsWritable);
stream.BindMethod("SetCursorPos", &Nz::Stream::SetCursorPos); stream.BindMethod("SetCursorPos", &Nz::Stream::SetCursorPos);
stream.BindMethod("Read", [] (Nz::LuaInstance& lua, Nz::Stream& instance, std::size_t /*argumentCount*/) -> int { stream.BindMethod("Read", [] (Nz::LuaState& lua, Nz::Stream& stream, std::size_t /*argumentCount*/) -> int {
int argIndex = 2; int argIndex = 2;
std::size_t length = lua.Check<std::size_t>(&argIndex); std::size_t length = lua.Check<std::size_t>(&argIndex);
std::unique_ptr<char[]> buffer(new char[length]); std::unique_ptr<char[]> buffer(new char[length]);
std::size_t readLength = instance.Read(buffer.get(), length); std::size_t readLength = stream.Read(buffer.get(), length);
lua.PushString(Nz::String(buffer.get(), readLength)); lua.PushString(Nz::String(buffer.get(), readLength));
return 1; return 1;
}); });
stream.BindMethod("Write", [] (Nz::LuaInstance& lua, Nz::Stream& instance, std::size_t /*argumentCount*/) -> int { stream.BindMethod("Write", [] (Nz::LuaState& lua, Nz::Stream& stream, std::size_t /*argumentCount*/) -> int {
int argIndex = 2; int argIndex = 2;
std::size_t bufferSize = 0; std::size_t bufferSize = 0;
const char* buffer = lua.CheckString(argIndex, &bufferSize); const char* buffer = lua.CheckString(argIndex, &bufferSize);
if (instance.IsTextModeEnabled()) if (stream.IsTextModeEnabled())
lua.Push(instance.Write(Nz::String(buffer, bufferSize))); lua.Push(stream.Write(Nz::String(buffer, bufferSize)));
else else
lua.Push(instance.Write(buffer, bufferSize)); lua.Push(stream.Write(buffer, bufferSize));
return 1; return 1;
}); });
} }
@ -61,7 +61,7 @@ namespace Ndk
/*********************************** Nz::Clock **********************************/ /*********************************** Nz::Clock **********************************/
clock.Reset("Clock"); clock.Reset("Clock");
{ {
clock.SetConstructor([] (Nz::LuaInstance& lua, Nz::Clock* instance, std::size_t argumentCount) clock.SetConstructor([] (Nz::LuaState& lua, Nz::Clock* instance, std::size_t argumentCount)
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 2U); std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
@ -103,11 +103,11 @@ namespace Ndk
clock.BindMethod("Unpause", &Nz::Clock::Unpause); clock.BindMethod("Unpause", &Nz::Clock::Unpause);
// Manual // Manual
clock.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Clock& instance, std::size_t /*argumentCount*/) -> int { clock.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::Clock& clock, std::size_t /*argumentCount*/) -> int {
Nz::StringStream ss("Clock(Elapsed: "); Nz::StringStream ss("Clock(Elapsed: ");
ss << instance.GetSeconds(); ss << clock.GetSeconds();
ss << "s, Paused: "; ss << "s, Paused: ";
ss << instance.IsPaused(); ss << clock.IsPaused();
ss << ')'; ss << ')';
lua.PushString(ss); lua.PushString(ss);
@ -118,7 +118,7 @@ namespace Ndk
/********************************* Nz::Directory ********************************/ /********************************* Nz::Directory ********************************/
directory.Reset("Directory"); directory.Reset("Directory");
{ {
directory.SetConstructor([] (Nz::LuaInstance& lua, Nz::Directory* instance, std::size_t argumentCount) directory.SetConstructor([] (Nz::LuaState& lua, Nz::Directory* instance, std::size_t argumentCount)
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 1U); std::size_t argCount = std::min<std::size_t>(argumentCount, 1U);
@ -159,9 +159,9 @@ namespace Ndk
directory.BindStaticMethod("SetCurrent", Nz::Directory::SetCurrent); directory.BindStaticMethod("SetCurrent", Nz::Directory::SetCurrent);
// Manual // Manual
directory.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Directory& instance, std::size_t /*argumentCount*/) -> int { directory.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::Directory& dir, std::size_t /*argumentCount*/) -> int {
Nz::StringStream ss("Directory("); Nz::StringStream ss("Directory(");
ss << instance.GetPath(); ss << dir.GetPath();
ss << ')'; ss << ')';
lua.PushString(ss); lua.PushString(ss);
@ -174,7 +174,7 @@ namespace Ndk
{ {
file.Inherit(stream); file.Inherit(stream);
file.SetConstructor([] (Nz::LuaInstance& lua, Nz::File* instance, std::size_t argumentCount) file.SetConstructor([] (Nz::LuaState& lua, Nz::File* instance, std::size_t argumentCount)
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 1U); std::size_t argCount = std::min<std::size_t>(argumentCount, 1U);
@ -237,7 +237,7 @@ namespace Ndk
file.BindStaticMethod("Rename", &Nz::File::Rename); file.BindStaticMethod("Rename", &Nz::File::Rename);
// Manual // Manual
file.BindMethod("Open", [] (Nz::LuaInstance& lua, Nz::File& instance, std::size_t argumentCount) -> int file.BindMethod("Open", [] (Nz::LuaState& lua, Nz::File& file, std::size_t argumentCount) -> int
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 2U); std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
@ -246,13 +246,13 @@ namespace Ndk
{ {
case 0: case 0:
case 1: case 1:
return lua.Push(instance.Open(lua.Check<Nz::UInt32>(&argIndex, Nz::OpenMode_NotOpen))); return lua.Push(file.Open(lua.Check<Nz::UInt32>(&argIndex, Nz::OpenMode_NotOpen)));
case 2: case 2:
{ {
Nz::String filePath = lua.Check<Nz::String>(&argIndex); Nz::String filePath = lua.Check<Nz::String>(&argIndex);
Nz::UInt32 openMode = lua.Check<Nz::UInt32>(&argIndex, Nz::OpenMode_NotOpen); Nz::UInt32 openMode = lua.Check<Nz::UInt32>(&argIndex, Nz::OpenMode_NotOpen);
return lua.Push(instance.Open(filePath, openMode)); return lua.Push(file.Open(filePath, openMode));
} }
} }
@ -260,7 +260,7 @@ namespace Ndk
return 0; return 0;
}); });
file.BindMethod("SetCursorPos", [] (Nz::LuaInstance& lua, Nz::File& instance, std::size_t argumentCount) -> int file.BindMethod("SetCursorPos", [] (Nz::LuaState& lua, Nz::File& file, std::size_t argumentCount) -> int
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 2U); std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
@ -268,13 +268,13 @@ namespace Ndk
switch (argCount) switch (argCount)
{ {
case 1: case 1:
return lua.Push(instance.SetCursorPos(lua.Check<Nz::UInt64>(&argIndex))); return lua.Push(file.SetCursorPos(lua.Check<Nz::UInt64>(&argIndex)));
case 2: case 2:
{ {
Nz::CursorPosition curPos = lua.Check<Nz::CursorPosition>(&argIndex); Nz::CursorPosition curPos = lua.Check<Nz::CursorPosition>(&argIndex);
Nz::Int64 offset = lua.Check<Nz::Int64>(&argIndex); Nz::Int64 offset = lua.Check<Nz::Int64>(&argIndex);
return lua.Push(instance.SetCursorPos(curPos, offset)); return lua.Push(file.SetCursorPos(curPos, offset));
} }
} }
@ -282,10 +282,10 @@ namespace Ndk
return 0; return 0;
}); });
file.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::File& instance, std::size_t /*argumentCount*/) -> int { file.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::File& file, std::size_t /*argumentCount*/) -> int {
Nz::StringStream ss("File("); Nz::StringStream ss("File(");
if (instance.IsOpen()) if (file.IsOpen())
ss << "Path: " << instance.GetPath(); ss << "Path: " << file.GetPath();
ss << ')'; ss << ')';
@ -300,55 +300,56 @@ namespace Ndk
* *
* \param instance Lua instance that will interact with the Core classes * \param instance Lua instance that will interact with the Core classes
*/ */
void LuaBinding_Core::Register(Nz::LuaInstance& instance) void LuaBinding_Core::Register(Nz::LuaState& state)
{ {
// Classes // Classes
clock.Register(instance); clock.Register(state);
directory.Register(instance); directory.Register(state);
file.Register(instance); file.Register(state);
stream.Register(instance); stream.Register(state);
// Enums // Enums
// Nz::CursorPosition // Nz::CursorPosition
static_assert(Nz::CursorPosition_Max + 1 == 3, "Nz::CursorPosition has been updated but change was not reflected to Lua binding"); static_assert(Nz::CursorPosition_Max + 1 == 3, "Nz::CursorPosition has been updated but change was not reflected to Lua binding");
instance.PushTable(0, 3); state.PushTable(0, 3);
{ {
instance.PushField("AtBegin", Nz::CursorPosition_AtBegin); state.PushField("AtBegin", Nz::CursorPosition_AtBegin);
instance.PushField("AtCurrent", Nz::CursorPosition_AtCurrent); state.PushField("AtCurrent", Nz::CursorPosition_AtCurrent);
instance.PushField("AtEnd", Nz::CursorPosition_AtEnd); state.PushField("AtEnd", Nz::CursorPosition_AtEnd);
} }
instance.SetGlobal("CursorPosition"); state.SetGlobal("CursorPosition");
// Nz::HashType // Nz::HashType
static_assert(Nz::HashType_Max + 1 == 9, "Nz::HashType has been updated but change was not reflected to Lua binding"); static_assert(Nz::HashType_Max + 1 == 10, "Nz::HashType has been updated but change was not reflected to Lua binding");
instance.PushTable(0, 9); state.PushTable(0, 10);
{ {
instance.PushField("CRC32", Nz::HashType_CRC32); state.PushField("CRC32", Nz::HashType_CRC32);
instance.PushField("Fletcher16", Nz::HashType_Fletcher16); state.PushField("CRC64", Nz::HashType_CRC64);
instance.PushField("MD5", Nz::HashType_MD5); state.PushField("Fletcher16", Nz::HashType_Fletcher16);
instance.PushField("SHA1", Nz::HashType_SHA1); state.PushField("MD5", Nz::HashType_MD5);
instance.PushField("SHA224", Nz::HashType_SHA224); state.PushField("SHA1", Nz::HashType_SHA1);
instance.PushField("SHA256", Nz::HashType_SHA256); state.PushField("SHA224", Nz::HashType_SHA224);
instance.PushField("SHA384", Nz::HashType_SHA384); state.PushField("SHA256", Nz::HashType_SHA256);
instance.PushField("SHA512", Nz::HashType_SHA512); state.PushField("SHA384", Nz::HashType_SHA384);
instance.PushField("Whirlpool", Nz::HashType_Whirlpool); state.PushField("SHA512", Nz::HashType_SHA512);
state.PushField("Whirlpool", Nz::HashType_Whirlpool);
} }
instance.SetGlobal("HashType"); state.SetGlobal("HashType");
// Nz::OpenMode // Nz::OpenMode
static_assert(Nz::OpenMode_Max + 1 == 8, "Nz::OpenModeFlags has been updated but change was not reflected to Lua binding"); static_assert(Nz::OpenMode_Max + 1 == 8, "Nz::OpenModeFlags has been updated but change was not reflected to Lua binding");
instance.PushTable(0, Nz::OpenMode_Max + 1); state.PushTable(0, Nz::OpenMode_Max + 1);
{ {
instance.PushField("Append", Nz::OpenMode_Append); state.PushField("Append", Nz::OpenMode_Append);
instance.PushField("NotOpen", Nz::OpenMode_NotOpen); state.PushField("NotOpen", Nz::OpenMode_NotOpen);
instance.PushField("Lock", Nz::OpenMode_Lock); state.PushField("Lock", Nz::OpenMode_Lock);
instance.PushField("ReadOnly", Nz::OpenMode_ReadOnly); state.PushField("ReadOnly", Nz::OpenMode_ReadOnly);
instance.PushField("ReadWrite", Nz::OpenMode_ReadWrite); state.PushField("ReadWrite", Nz::OpenMode_ReadWrite);
instance.PushField("Text", Nz::OpenMode_Text); state.PushField("Text", Nz::OpenMode_Text);
instance.PushField("Truncate", Nz::OpenMode_Truncate); state.PushField("Truncate", Nz::OpenMode_Truncate);
instance.PushField("WriteOnly", Nz::OpenMode_WriteOnly); state.PushField("WriteOnly", Nz::OpenMode_WriteOnly);
} }
instance.SetGlobal("OpenMode"); state.SetGlobal("OpenMode");
} }
} }

View File

@ -37,7 +37,7 @@ namespace Ndk
/*********************************** Nz::Material ***********************************/ /*********************************** Nz::Material ***********************************/
material.Reset("Material"); material.Reset("Material");
{ {
material.SetConstructor([] (Nz::LuaInstance& lua, Nz::MaterialRef* instance, std::size_t argumentCount) material.SetConstructor([] (Nz::LuaState& lua, Nz::MaterialRef* instance, std::size_t argumentCount)
{ {
switch (argumentCount) switch (argumentCount)
{ {
@ -70,7 +70,7 @@ namespace Ndk
return false; return false;
}); });
material.BindMethod("Configure", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int material.BindMethod("Configure", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{ {
int argIndex = 2; int argIndex = 2;
if (lua.IsOfType(argIndex, "MaterialPipeline")) if (lua.IsOfType(argIndex, "MaterialPipeline"))
@ -168,7 +168,7 @@ namespace Ndk
material.BindStaticMethod("GetDefault", &Nz::Material::GetDefault); material.BindStaticMethod("GetDefault", &Nz::Material::GetDefault);
material.BindMethod("SetAlphaMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int material.BindMethod("SetAlphaMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{ {
int argIndex = 2; int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture")) if (lua.IsOfType(argIndex, "Texture"))
@ -180,7 +180,7 @@ namespace Ndk
return lua.Push(instance->SetAlphaMap(lua.Check<Nz::String>(&argIndex))); return lua.Push(instance->SetAlphaMap(lua.Check<Nz::String>(&argIndex)));
}); });
material.BindMethod("SetDiffuseMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int material.BindMethod("SetDiffuseMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{ {
int argIndex = 2; int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture")) if (lua.IsOfType(argIndex, "Texture"))
@ -192,7 +192,7 @@ namespace Ndk
return lua.Push(instance->SetDiffuseMap(lua.Check<Nz::String>(&argIndex))); return lua.Push(instance->SetDiffuseMap(lua.Check<Nz::String>(&argIndex)));
}); });
material.BindMethod("SetEmissiveMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int material.BindMethod("SetEmissiveMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{ {
int argIndex = 2; int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture")) if (lua.IsOfType(argIndex, "Texture"))
@ -204,7 +204,7 @@ namespace Ndk
return lua.Push(instance->SetEmissiveMap(lua.Check<Nz::String>(&argIndex))); return lua.Push(instance->SetEmissiveMap(lua.Check<Nz::String>(&argIndex)));
}); });
material.BindMethod("SetHeightMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int material.BindMethod("SetHeightMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{ {
int argIndex = 2; int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture")) if (lua.IsOfType(argIndex, "Texture"))
@ -216,7 +216,7 @@ namespace Ndk
return lua.Push(instance->SetHeightMap(lua.Check<Nz::String>(&argIndex))); return lua.Push(instance->SetHeightMap(lua.Check<Nz::String>(&argIndex)));
}); });
material.BindMethod("SetNormalMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int material.BindMethod("SetNormalMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{ {
int argIndex = 2; int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture")) if (lua.IsOfType(argIndex, "Texture"))
@ -228,7 +228,7 @@ namespace Ndk
return lua.Push(instance->SetNormalMap(lua.Check<Nz::String>(&argIndex))); return lua.Push(instance->SetNormalMap(lua.Check<Nz::String>(&argIndex)));
}); });
material.BindMethod("SetShader", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int material.BindMethod("SetShader", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{ {
int argIndex = 2; int argIndex = 2;
if (lua.IsOfType(argIndex, "UberShader")) if (lua.IsOfType(argIndex, "UberShader"))
@ -240,7 +240,7 @@ namespace Ndk
return lua.Push(instance->SetShader(lua.Check<Nz::String>(&argIndex))); return lua.Push(instance->SetShader(lua.Check<Nz::String>(&argIndex)));
}); });
material.BindMethod("SetSpecularMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int material.BindMethod("SetSpecularMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{ {
int argIndex = 2; int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture")) if (lua.IsOfType(argIndex, "Texture"))
@ -261,7 +261,7 @@ namespace Ndk
return reinterpret_cast<Nz::InstancedRenderableRef*>(modelRef); //TODO: Make a ObjectRefCast return reinterpret_cast<Nz::InstancedRenderableRef*>(modelRef); //TODO: Make a ObjectRefCast
}); });
model.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::ModelRef* instance, std::size_t /*argumentCount*/) model.SetConstructor([] (Nz::LuaState& /*lua*/, Nz::ModelRef* instance, std::size_t /*argumentCount*/)
{ {
Nz::PlacementNew(instance, Nz::Model::New()); Nz::PlacementNew(instance, Nz::Model::New());
return true; return true;
@ -293,7 +293,7 @@ namespace Ndk
return reinterpret_cast<Nz::InstancedRenderableRef*>(spriteRef); //TODO: Make a ObjectRefCast return reinterpret_cast<Nz::InstancedRenderableRef*>(spriteRef); //TODO: Make a ObjectRefCast
}); });
sprite.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::SpriteRef* instance, std::size_t /*argumentCount*/) sprite.SetConstructor([] (Nz::LuaState& /*lua*/, Nz::SpriteRef* instance, std::size_t /*argumentCount*/)
{ {
Nz::PlacementNew(instance, Nz::Sprite::New()); Nz::PlacementNew(instance, Nz::Sprite::New());
return true; return true;
@ -314,7 +314,7 @@ namespace Ndk
sprite.BindMethod("SetTextureCoords", &Nz::Sprite::SetTextureCoords); sprite.BindMethod("SetTextureCoords", &Nz::Sprite::SetTextureCoords);
sprite.BindMethod("SetTextureRect", &Nz::Sprite::SetTextureRect); sprite.BindMethod("SetTextureRect", &Nz::Sprite::SetTextureRect);
sprite.BindMethod("SetMaterial", [] (Nz::LuaInstance& lua, Nz::SpriteRef& instance, std::size_t /*argumentCount*/) -> int sprite.BindMethod("SetMaterial", [] (Nz::LuaState& lua, Nz::SpriteRef& instance, std::size_t /*argumentCount*/) -> int
{ {
int argIndex = 2; int argIndex = 2;
bool resizeSprite = lua.CheckBoolean(argIndex + 1, true); bool resizeSprite = lua.CheckBoolean(argIndex + 1, true);
@ -327,7 +327,7 @@ namespace Ndk
return 0; return 0;
}); });
sprite.BindMethod("SetTexture", [] (Nz::LuaInstance& lua, Nz::SpriteRef& instance, std::size_t /*argumentCount*/) -> int sprite.BindMethod("SetTexture", [] (Nz::LuaState& lua, Nz::SpriteRef& instance, std::size_t /*argumentCount*/) -> int
{ {
int argIndex = 2; int argIndex = 2;
bool resizeSprite = lua.CheckBoolean(argIndex + 1, true); bool resizeSprite = lua.CheckBoolean(argIndex + 1, true);
@ -358,13 +358,13 @@ namespace Ndk
* \param instance Lua instance that will interact with the Graphics classes * \param instance Lua instance that will interact with the Graphics classes
*/ */
void LuaBinding_Graphics::Register(Nz::LuaInstance& instance) void LuaBinding_Graphics::Register(Nz::LuaState& state)
{ {
abstractViewer.Register(instance); abstractViewer.Register(state);
instancedRenderable.Register(instance); instancedRenderable.Register(state);
material.Register(instance); material.Register(state);
model.Register(instance); model.Register(state);
sprite.Register(instance); sprite.Register(state);
spriteLibrary.Register(instance); spriteLibrary.Register(state);
} }
} }

View File

@ -18,7 +18,7 @@ namespace Ndk
/*********************************** Nz::EulerAngles **********************************/ /*********************************** Nz::EulerAngles **********************************/
eulerAngles.Reset("EulerAngles"); eulerAngles.Reset("EulerAngles");
{ {
eulerAngles.SetConstructor([] (Nz::LuaInstance& lua, Nz::EulerAnglesd* instance, std::size_t argumentCount) eulerAngles.SetConstructor([] (Nz::LuaState& lua, Nz::EulerAnglesd* instance, std::size_t argumentCount)
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 3U); std::size_t argCount = std::min<std::size_t>(argumentCount, 3U);
@ -46,7 +46,7 @@ namespace Ndk
eulerAngles.BindMethod("__tostring", &Nz::EulerAnglesd::ToString); eulerAngles.BindMethod("__tostring", &Nz::EulerAnglesd::ToString);
eulerAngles.SetGetter([] (Nz::LuaInstance& lua, Nz::EulerAnglesd& instance) eulerAngles.SetGetter([] (Nz::LuaState& lua, Nz::EulerAnglesd& instance)
{ {
std::size_t length; std::size_t length;
const char* ypr = lua.CheckString(2, &length); const char* ypr = lua.CheckString(2, &length);
@ -103,7 +103,7 @@ namespace Ndk
return false; return false;
}); });
eulerAngles.SetSetter([] (Nz::LuaInstance& lua, Nz::EulerAnglesd& instance) eulerAngles.SetSetter([] (Nz::LuaState& lua, Nz::EulerAnglesd& instance)
{ {
std::size_t length; std::size_t length;
const char* ypr = lua.CheckString(2, &length); const char* ypr = lua.CheckString(2, &length);
@ -165,7 +165,7 @@ namespace Ndk
/*********************************** Nz::Matrix4 **********************************/ /*********************************** Nz::Matrix4 **********************************/
matrix4d.Reset("Matrix4"); matrix4d.Reset("Matrix4");
{ {
matrix4d.SetConstructor([] (Nz::LuaInstance& lua, Nz::Matrix4d* matrix, std::size_t argumentCount) matrix4d.SetConstructor([] (Nz::LuaState& lua, Nz::Matrix4d* matrix, std::size_t argumentCount)
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 3U); std::size_t argCount = std::min<std::size_t>(argumentCount, 3U);
@ -207,7 +207,7 @@ namespace Ndk
matrix4d.BindMethod("GetDeterminant", &Nz::Matrix4d::GetDeterminant); matrix4d.BindMethod("GetDeterminant", &Nz::Matrix4d::GetDeterminant);
matrix4d.BindMethod("GetDeterminantAffine", &Nz::Matrix4d::GetDeterminantAffine); matrix4d.BindMethod("GetDeterminantAffine", &Nz::Matrix4d::GetDeterminantAffine);
matrix4d.BindMethod("GetInverse", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int matrix4d.BindMethod("GetInverse", [] (Nz::LuaState& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{ {
Nz::Matrix4d result; Nz::Matrix4d result;
if (instance.GetInverse(&result)) if (instance.GetInverse(&result))
@ -216,7 +216,7 @@ namespace Ndk
return lua.Push(false); return lua.Push(false);
}); });
matrix4d.BindMethod("GetInverseAffine", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int matrix4d.BindMethod("GetInverseAffine", [] (Nz::LuaState& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{ {
Nz::Matrix4d result; Nz::Matrix4d result;
if (instance.GetInverseAffine(&result)) if (instance.GetInverseAffine(&result))
@ -232,7 +232,7 @@ namespace Ndk
matrix4d.BindMethod("GetSquaredScale", &Nz::Matrix4d::GetSquaredScale); matrix4d.BindMethod("GetSquaredScale", &Nz::Matrix4d::GetSquaredScale);
matrix4d.BindMethod("GetTranslation", &Nz::Matrix4d::GetTranslation); matrix4d.BindMethod("GetTranslation", &Nz::Matrix4d::GetTranslation);
matrix4d.BindMethod("GetTransposed", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int matrix4d.BindMethod("GetTransposed", [] (Nz::LuaState& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{ {
Nz::Matrix4d result; Nz::Matrix4d result;
instance.GetTransposed(&result); instance.GetTransposed(&result);
@ -243,7 +243,7 @@ namespace Ndk
matrix4d.BindMethod("HasNegativeScale", &Nz::Matrix4d::HasNegativeScale); matrix4d.BindMethod("HasNegativeScale", &Nz::Matrix4d::HasNegativeScale);
matrix4d.BindMethod("HasScale", &Nz::Matrix4d::HasScale); matrix4d.BindMethod("HasScale", &Nz::Matrix4d::HasScale);
matrix4d.BindMethod("Inverse", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int matrix4d.BindMethod("Inverse", [] (Nz::LuaState& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{ {
bool succeeded; bool succeeded;
instance.Inverse(&succeeded); instance.Inverse(&succeeded);
@ -251,7 +251,7 @@ namespace Ndk
return lua.Push(succeeded); return lua.Push(succeeded);
}); });
matrix4d.BindMethod("InverseAffine", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int matrix4d.BindMethod("InverseAffine", [] (Nz::LuaState& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{ {
bool succeeded; bool succeeded;
instance.InverseAffine(&succeeded); instance.InverseAffine(&succeeded);
@ -273,7 +273,7 @@ namespace Ndk
matrix4d.BindMethod("MakeViewMatrix", &Nz::Matrix4d::MakeViewMatrix); matrix4d.BindMethod("MakeViewMatrix", &Nz::Matrix4d::MakeViewMatrix);
matrix4d.BindMethod("MakeZero", &Nz::Matrix4d::MakeZero); matrix4d.BindMethod("MakeZero", &Nz::Matrix4d::MakeZero);
matrix4d.BindMethod("Set", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t argumentCount) -> int matrix4d.BindMethod("Set", [] (Nz::LuaState& lua, Nz::Matrix4d& instance, std::size_t argumentCount) -> int
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 3U); std::size_t argCount = std::min<std::size_t>(argumentCount, 3U);
@ -305,7 +305,7 @@ namespace Ndk
matrix4d.BindMethod("SetScale", &Nz::Matrix4d::SetScale); matrix4d.BindMethod("SetScale", &Nz::Matrix4d::SetScale);
matrix4d.BindMethod("SetTranslation", &Nz::Matrix4d::SetTranslation); matrix4d.BindMethod("SetTranslation", &Nz::Matrix4d::SetTranslation);
matrix4d.BindMethod("Transform", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int matrix4d.BindMethod("Transform", [] (Nz::LuaState& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{ {
int argIndex = 2; int argIndex = 2;
if (lua.IsOfType(argIndex, "Vector2")) if (lua.IsOfType(argIndex, "Vector2"))
@ -345,7 +345,7 @@ namespace Ndk
matrix4d.BindStaticMethod("ViewMatrix", &Nz::Matrix4d::ViewMatrix); matrix4d.BindStaticMethod("ViewMatrix", &Nz::Matrix4d::ViewMatrix);
matrix4d.BindStaticMethod("Zero", &Nz::Matrix4d::Zero); matrix4d.BindStaticMethod("Zero", &Nz::Matrix4d::Zero);
matrix4d.SetGetter([] (Nz::LuaInstance& lua, Nz::Matrix4d& instance) matrix4d.SetGetter([] (Nz::LuaState& lua, Nz::Matrix4d& instance)
{ {
bool succeeded = false; bool succeeded = false;
std::size_t index = static_cast<std::size_t>(lua.ToInteger(2, &succeeded)); std::size_t index = static_cast<std::size_t>(lua.ToInteger(2, &succeeded));
@ -356,7 +356,7 @@ namespace Ndk
return true; return true;
}); });
matrix4d.SetSetter([] (Nz::LuaInstance& lua, Nz::Matrix4d& instance) matrix4d.SetSetter([] (Nz::LuaState& lua, Nz::Matrix4d& instance)
{ {
bool succeeded = false; bool succeeded = false;
std::size_t index = static_cast<std::size_t>(lua.ToInteger(2, &succeeded)); std::size_t index = static_cast<std::size_t>(lua.ToInteger(2, &succeeded));
@ -372,7 +372,7 @@ namespace Ndk
/*********************************** Nz::Rect **********************************/ /*********************************** Nz::Rect **********************************/
rect.Reset("Rect"); rect.Reset("Rect");
{ {
rect.SetConstructor([] (Nz::LuaInstance& lua, Nz::Rectd* instance, std::size_t argumentCount) rect.SetConstructor([] (Nz::LuaState& lua, Nz::Rectd* instance, std::size_t argumentCount)
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U); std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
@ -422,7 +422,7 @@ namespace Ndk
rect.BindMethod("__tostring", &Nz::Rectd::ToString); rect.BindMethod("__tostring", &Nz::Rectd::ToString);
rect.SetGetter([] (Nz::LuaInstance& lua, Nz::Rectd& instance) rect.SetGetter([] (Nz::LuaState& lua, Nz::Rectd& instance)
{ {
switch (lua.GetType(2)) switch (lua.GetType(2))
{ {
@ -475,7 +475,7 @@ namespace Ndk
return false; return false;
}); });
rect.SetSetter([] (Nz::LuaInstance& lua, Nz::Rectd& instance) rect.SetSetter([] (Nz::LuaState& lua, Nz::Rectd& instance)
{ {
switch (lua.GetType(2)) switch (lua.GetType(2))
{ {
@ -531,7 +531,7 @@ namespace Ndk
/*********************************** Nz::Quaternion **********************************/ /*********************************** Nz::Quaternion **********************************/
quaternion.Reset("Quaternion"); quaternion.Reset("Quaternion");
{ {
quaternion.SetConstructor([] (Nz::LuaInstance& lua, Nz::Quaterniond* instance, std::size_t argumentCount) quaternion.SetConstructor([] (Nz::LuaState& lua, Nz::Quaterniond* instance, std::size_t argumentCount)
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U); std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
@ -587,7 +587,7 @@ namespace Ndk
quaternion.BindStaticMethod("RotationBetween", &Nz::Quaterniond::RotationBetween); quaternion.BindStaticMethod("RotationBetween", &Nz::Quaterniond::RotationBetween);
quaternion.BindStaticMethod("Slerp", &Nz::Quaterniond::Slerp); quaternion.BindStaticMethod("Slerp", &Nz::Quaterniond::Slerp);
quaternion.BindMethod("GetNormal", [] (Nz::LuaInstance& lua, Nz::Quaterniond& instance, std::size_t /*argumentCount*/) -> int quaternion.BindMethod("GetNormal", [] (Nz::LuaState& lua, Nz::Quaterniond& instance, std::size_t /*argumentCount*/) -> int
{ {
double length; double length;
@ -597,7 +597,7 @@ namespace Ndk
return 2; return 2;
}); });
quaternion.BindMethod("Normalize", [] (Nz::LuaInstance& lua, Nz::Quaterniond& instance, std::size_t /*argumentCount*/) -> int quaternion.BindMethod("Normalize", [] (Nz::LuaState& lua, Nz::Quaterniond& instance, std::size_t /*argumentCount*/) -> int
{ {
double length; double length;
@ -608,20 +608,20 @@ namespace Ndk
return 2; return 2;
}); });
quaternion.BindStaticMethod("Normalize", [] (Nz::LuaInstance& instance) -> int quaternion.BindStaticMethod("Normalize", [] (Nz::LuaState& state) -> int
{ {
int argIndex = 1; int argIndex = 1;
Nz::Quaterniond quat = instance.Check<Nz::Quaterniond>(&argIndex); Nz::Quaterniond quat = state.Check<Nz::Quaterniond>(&argIndex);
double length; double length;
instance.Push(Nz::Quaterniond::Normalize(quat, &length)); state.Push(Nz::Quaterniond::Normalize(quat, &length));
instance.Push(length); state.Push(length);
return 2; return 2;
}); });
quaternion.SetGetter([] (Nz::LuaInstance& lua, Nz::Quaterniond& instance) quaternion.SetGetter([] (Nz::LuaState& lua, Nz::Quaterniond& instance)
{ {
std::size_t length; std::size_t length;
const char* wxyz = lua.CheckString(2, &length); const char* wxyz = lua.CheckString(2, &length);
@ -651,7 +651,7 @@ namespace Ndk
return false; return false;
}); });
quaternion.SetSetter([] (Nz::LuaInstance& lua, Nz::Quaterniond& instance) quaternion.SetSetter([] (Nz::LuaState& lua, Nz::Quaterniond& instance)
{ {
std::size_t length; std::size_t length;
const char* wxyz = lua.CheckString(2, &length); const char* wxyz = lua.CheckString(2, &length);
@ -690,7 +690,7 @@ namespace Ndk
/*********************************** Nz::Vector2 **********************************/ /*********************************** Nz::Vector2 **********************************/
vector2d.Reset("Vector2"); vector2d.Reset("Vector2");
{ {
vector2d.SetConstructor([] (Nz::LuaInstance& lua, Nz::Vector2d* vector, std::size_t argumentCount) vector2d.SetConstructor([] (Nz::LuaState& lua, Nz::Vector2d* vector, std::size_t argumentCount)
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 2U); std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
@ -720,7 +720,7 @@ namespace Ndk
vector2d.BindMethod("__tostring", &Nz::Vector2d::ToString); vector2d.BindMethod("__tostring", &Nz::Vector2d::ToString);
vector2d.SetGetter([] (Nz::LuaInstance& lua, Nz::Vector2d& instance) vector2d.SetGetter([] (Nz::LuaState& lua, Nz::Vector2d& instance)
{ {
switch (lua.GetType(2)) switch (lua.GetType(2))
{ {
@ -765,7 +765,7 @@ namespace Ndk
return false; return false;
}); });
vector2d.SetSetter([] (Nz::LuaInstance& lua, Nz::Vector2d& instance) vector2d.SetSetter([] (Nz::LuaState& lua, Nz::Vector2d& instance)
{ {
switch (lua.GetType(2)) switch (lua.GetType(2))
{ {
@ -816,7 +816,7 @@ namespace Ndk
/*********************************** Nz::Vector3 **********************************/ /*********************************** Nz::Vector3 **********************************/
vector3d.Reset("Vector3"); vector3d.Reset("Vector3");
{ {
vector3d.SetConstructor([] (Nz::LuaInstance& lua, Nz::Vector3d* vector, std::size_t argumentCount) vector3d.SetConstructor([] (Nz::LuaState& lua, Nz::Vector3d* vector, std::size_t argumentCount)
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 3U); std::size_t argCount = std::min<std::size_t>(argumentCount, 3U);
@ -860,7 +860,7 @@ namespace Ndk
vector3d.BindMethod("__tostring", &Nz::Vector3d::ToString); vector3d.BindMethod("__tostring", &Nz::Vector3d::ToString);
vector3d.SetGetter([] (Nz::LuaInstance& lua, Nz::Vector3d& instance) vector3d.SetGetter([] (Nz::LuaState& lua, Nz::Vector3d& instance)
{ {
switch (lua.GetType(2)) switch (lua.GetType(2))
{ {
@ -909,7 +909,7 @@ namespace Ndk
return false; return false;
}); });
vector3d.SetSetter([] (Nz::LuaInstance& lua, Nz::Vector3d& instance) vector3d.SetSetter([] (Nz::LuaState& lua, Nz::Vector3d& instance)
{ {
switch (lua.GetType(2)) switch (lua.GetType(2))
{ {
@ -967,20 +967,20 @@ namespace Ndk
* *
* \param instance Lua instance that will interact with the Math classes * \param instance Lua instance that will interact with the Math classes
*/ */
void LuaBinding_Math::Register(Nz::LuaInstance& instance) void LuaBinding_Math::Register(Nz::LuaState& state)
{ {
eulerAngles.Register(instance); eulerAngles.Register(state);
matrix4d.Register(instance); matrix4d.Register(state);
quaternion.Register(instance); quaternion.Register(state);
rect.Register(instance); rect.Register(state);
vector2d.Register(instance); vector2d.Register(state);
vector3d.Register(instance); vector3d.Register(state);
quaternion.PushGlobalTable(instance); quaternion.PushGlobalTable(state);
{ {
instance.PushField("Identity", Nz::Quaterniond::Identity()); state.PushField("Identity", Nz::Quaterniond::Identity());
instance.PushField("Zero", Nz::Quaterniond::Zero()); state.PushField("Zero", Nz::Quaterniond::Zero());
} }
instance.Pop(); state.Pop();
} }
} }

View File

@ -28,11 +28,11 @@ namespace Ndk
/*********************************** Nz::IpAddress **********************************/ /*********************************** Nz::IpAddress **********************************/
ipAddress.Reset("IpAddress"); ipAddress.Reset("IpAddress");
{ {
ipAddress.SetConstructor([] (Nz::LuaInstance& lua, Nz::IpAddress* instance, std::size_t argumentCount) ipAddress.SetConstructor([] (Nz::LuaState& lua, Nz::IpAddress* instance, std::size_t argumentCount)
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 9U); std::size_t argCount = std::min<std::size_t>(argumentCount, 9U);
int argIndex = 2; int argIndex = 1;
switch (argCount) switch (argCount)
{ {
case 0: case 0:
@ -85,63 +85,120 @@ namespace Ndk
ipAddress.BindMethod("ToUInt32", &Nz::IpAddress::ToUInt32); ipAddress.BindMethod("ToUInt32", &Nz::IpAddress::ToUInt32);
ipAddress.BindMethod("__tostring", &Nz::IpAddress::ToString); ipAddress.BindMethod("__tostring", &Nz::IpAddress::ToString);
ipAddress.BindStaticMethod("ResolveAddress", [] (Nz::LuaInstance& instance) -> int ipAddress.BindStaticMethod("ResolveAddress", [] (Nz::LuaState& state) -> int
{ {
Nz::String service; Nz::String service;
Nz::ResolveError error = Nz::ResolveError_Unknown; Nz::ResolveError error = Nz::ResolveError_Unknown;
int argIndex = 2; int argIndex = 2;
Nz::String hostName = Nz::IpAddress::ResolveAddress(instance.Check<Nz::IpAddress>(&argIndex), &service, &error); Nz::String hostName = Nz::IpAddress::ResolveAddress(state.Check<Nz::IpAddress>(&argIndex), &service, &error);
if (error == Nz::ResolveError_NoError) if (error == Nz::ResolveError_NoError)
{ {
instance.Push(hostName); state.Push(hostName);
instance.Push(service); state.Push(service);
return 2; return 2;
} }
else else
{ {
instance.PushBoolean(false); state.PushBoolean(false);
instance.Push(error); state.Push(error);
return 2; return 2;
} }
}); });
ipAddress.BindStaticMethod("ResolveHostname", [] (Nz::LuaInstance& instance) -> int ipAddress.BindStaticMethod("ResolveHostname", [] (Nz::LuaState& state) -> int
{ {
Nz::ResolveError error = Nz::ResolveError_Unknown; Nz::ResolveError error = Nz::ResolveError_Unknown;
int argIndex = 2; int argIndex = 2;
Nz::NetProtocol protocol = instance.Check<Nz::NetProtocol>(&argIndex); Nz::NetProtocol protocol = state.Check<Nz::NetProtocol>(&argIndex);
Nz::String hostname = instance.Check<Nz::String>(&argIndex); Nz::String hostname = state.Check<Nz::String>(&argIndex);
Nz::String service = instance.Check<Nz::String>(&argIndex, "http"); Nz::String service = state.Check<Nz::String>(&argIndex, "http");
std::vector<Nz::HostnameInfo> addresses = Nz::IpAddress::ResolveHostname(protocol, hostname, service, &error); std::vector<Nz::HostnameInfo> addresses = Nz::IpAddress::ResolveHostname(protocol, hostname, service, &error);
if (error == Nz::ResolveError_NoError) if (error == Nz::ResolveError_NoError)
{ {
int index = 1; int index = 1;
instance.PushTable(addresses.size()); state.PushTable(addresses.size());
for (Nz::HostnameInfo& info : addresses) for (Nz::HostnameInfo& info : addresses)
{ {
instance.PushInteger(index++); state.PushInteger(index++);
instance.PushTable(0, 4); state.PushTable(0, 4);
instance.PushField("Address", std::move(info.address)); state.PushField("Address", std::move(info.address));
instance.PushField("CanonicalName", std::move(info.canonicalName)); state.PushField("CanonicalName", std::move(info.canonicalName));
instance.PushField("Protocol", std::move(info.protocol)); state.PushField("Protocol", std::move(info.protocol));
instance.PushField("SocketType", std::move(info.socketType)); state.PushField("SocketType", std::move(info.socketType));
instance.SetTable(); state.SetTable();
} }
return 1; return 1;
} }
else else
{ {
instance.PushBoolean(false); state.PushBoolean(false);
instance.Push(error); state.Push(error);
return 2; return 2;
} }
}); });
} }
udpSocket.Reset("UdpSocket");
{
udpSocket.Inherit<Nz::AbstractSocket>(abstractSocket);
udpSocket.BindDefaultConstructor();
udpSocket.BindMethod("Create", &Nz::UdpSocket::Create);
udpSocket.BindMethod("EnableBroadcasting", &Nz::UdpSocket::EnableBroadcasting);
udpSocket.BindMethod("GetBoundAddress", &Nz::UdpSocket::GetBoundAddress);
udpSocket.BindMethod("GetBoundPort", &Nz::UdpSocket::GetBoundPort);
udpSocket.BindMethod("IsBroadcastingEnabled", &Nz::UdpSocket::IsBroadcastingEnabled);
udpSocket.BindMethod("QueryMaxDatagramSize", &Nz::UdpSocket::QueryMaxDatagramSize);
udpSocket.BindMethod("Bind", [](Nz::LuaState& lua, Nz::UdpSocket& socket, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "IpAddress"))
return lua.Push(socket.Bind(*static_cast<Nz::IpAddress*>(lua.ToUserdata(argIndex))));
else
return lua.Push(socket.Bind(lua.Check<Nz::UInt16>(&argIndex)));
});
udpSocket.BindMethod("Receive", [](Nz::LuaState& lua, Nz::UdpSocket& socket, std::size_t /*argumentCount*/) -> int
{
Nz::IpAddress from;
std::array<char, 0xFFFF> buffer;
std::size_t received;
if (socket.Receive(buffer.data(), buffer.size(), &from, &received))
{
lua.PushBoolean(true);
lua.PushString(from.ToString());
lua.PushString(buffer.data(), received);
return 3;
}
lua.PushBoolean(false);
return 1;
});
udpSocket.BindMethod("Send", [](Nz::LuaState& lua, Nz::UdpSocket& socket, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
Nz::String to = lua.Check<Nz::String>(&argIndex);
std::size_t bufferLength;
const char* buffer = lua.CheckString(argIndex, &bufferLength);
std::size_t sent;
bool ret;
if ((ret = socket.Send(Nz::IpAddress(to), buffer, bufferLength, &sent)) != true)
sent = 0;
return lua.Push(std::make_pair(ret, sent));
});
}
} }
/*! /*!
@ -149,107 +206,108 @@ namespace Ndk
* *
* \param instance Lua instance that will interact with the Network classes * \param instance Lua instance that will interact with the Network classes
*/ */
void LuaBinding_Network::Register(Nz::LuaInstance& instance) void LuaBinding_Network::Register(Nz::LuaState& state)
{ {
// Classes // Classes
abstractSocket.Register(instance); abstractSocket.Register(state);
ipAddress.Register(instance); ipAddress.Register(state);
udpSocket.Register(state);
// Enums // Enums
// Nz::NetProtocol // Nz::NetProtocol
static_assert(Nz::NetProtocol_Max + 1 == 4, "Nz::NetProtocol has been updated but change was not reflected to Lua binding"); static_assert(Nz::NetProtocol_Max + 1 == 4, "Nz::NetProtocol has been updated but change was not reflected to Lua binding");
instance.PushTable(0, 4); state.PushTable(0, 4);
{ {
instance.PushField("Any", Nz::NetProtocol_Any); state.PushField("Any", Nz::NetProtocol_Any);
instance.PushField("IPv4", Nz::NetProtocol_IPv4); state.PushField("IPv4", Nz::NetProtocol_IPv4);
instance.PushField("IPv6", Nz::NetProtocol_IPv6); state.PushField("IPv6", Nz::NetProtocol_IPv6);
instance.PushField("Unknown", Nz::NetProtocol_Unknown); state.PushField("Unknown", Nz::NetProtocol_Unknown);
} }
instance.SetGlobal("NetProtocol"); state.SetGlobal("NetProtocol");
// Nz::PacketPriority // Nz::PacketPriority
static_assert(Nz::PacketPriority_Max + 1 == 4, "Nz::PacketPriority has been updated but change was not reflected to Lua binding"); static_assert(Nz::PacketPriority_Max + 1 == 4, "Nz::PacketPriority has been updated but change was not reflected to Lua binding");
instance.PushTable(0, 6); state.PushTable(0, 6);
{ {
instance.PushField("High", Nz::PacketPriority_High); state.PushField("High", Nz::PacketPriority_High);
instance.PushField("Highest", Nz::PacketPriority_Highest); state.PushField("Highest", Nz::PacketPriority_Highest);
instance.PushField("Immediate", Nz::PacketPriority_Immediate); state.PushField("Immediate", Nz::PacketPriority_Immediate);
instance.PushField("Medium", Nz::PacketPriority_Medium); state.PushField("Medium", Nz::PacketPriority_Medium);
instance.PushField("Low", Nz::PacketPriority_Low); state.PushField("Low", Nz::PacketPriority_Low);
instance.PushField("Lowest", Nz::PacketPriority_Lowest); state.PushField("Lowest", Nz::PacketPriority_Lowest);
} }
instance.SetGlobal("PacketPriority"); state.SetGlobal("PacketPriority");
// Nz::PacketReliability // Nz::PacketReliability
static_assert(Nz::PacketReliability_Max + 1 == 3, "Nz::PacketReliability has been updated but change was not reflected to Lua binding"); static_assert(Nz::PacketReliability_Max + 1 == 3, "Nz::PacketReliability has been updated but change was not reflected to Lua binding");
instance.PushTable(0, 3); state.PushTable(0, 3);
{ {
instance.PushField("Reliable", Nz::PacketReliability_Reliable); state.PushField("Reliable", Nz::PacketReliability_Reliable);
instance.PushField("ReliableOrdered", Nz::PacketReliability_ReliableOrdered); state.PushField("ReliableOrdered", Nz::PacketReliability_ReliableOrdered);
instance.PushField("Unreliable", Nz::PacketReliability_Unreliable); state.PushField("Unreliable", Nz::PacketReliability_Unreliable);
} }
instance.SetGlobal("PacketReliability"); state.SetGlobal("PacketReliability");
// Nz::ResolveError // Nz::ResolveError
static_assert(Nz::ResolveError_Max + 1 == 9, "Nz::ResolveError has been updated but change was not reflected to Lua binding"); static_assert(Nz::ResolveError_Max + 1 == 9, "Nz::ResolveError has been updated but change was not reflected to Lua binding");
instance.PushTable(0, 9); state.PushTable(0, 9);
{ {
instance.PushField("Internal", Nz::ResolveError_Internal); state.PushField("Internal", Nz::ResolveError_Internal);
instance.PushField("ResourceError", Nz::ResolveError_ResourceError); state.PushField("ResourceError", Nz::ResolveError_ResourceError);
instance.PushField("NoError", Nz::ResolveError_NoError); state.PushField("NoError", Nz::ResolveError_NoError);
instance.PushField("NonRecoverable", Nz::ResolveError_NonRecoverable); state.PushField("NonRecoverable", Nz::ResolveError_NonRecoverable);
instance.PushField("NotFound", Nz::ResolveError_NotFound); state.PushField("NotFound", Nz::ResolveError_NotFound);
instance.PushField("NotInitialized", Nz::ResolveError_NotInitialized); state.PushField("NotInitialized", Nz::ResolveError_NotInitialized);
instance.PushField("ProtocolNotSupported", Nz::ResolveError_ProtocolNotSupported); state.PushField("ProtocolNotSupported", Nz::ResolveError_ProtocolNotSupported);
instance.PushField("TemporaryFailure", Nz::ResolveError_TemporaryFailure); state.PushField("TemporaryFailure", Nz::ResolveError_TemporaryFailure);
instance.PushField("Unknown", Nz::ResolveError_Unknown); state.PushField("Unknown", Nz::ResolveError_Unknown);
} }
instance.SetGlobal("ResolveError"); state.SetGlobal("ResolveError");
// Nz::SocketError // Nz::SocketError
static_assert(Nz::SocketError_Max + 1 == 15, "Nz::ResolveError has been updated but change was not reflected to Lua binding"); static_assert(Nz::SocketError_Max + 1 == 15, "Nz::ResolveError has been updated but change was not reflected to Lua binding");
instance.PushTable(0, 15); state.PushTable(0, 15);
{ {
instance.PushField("AddressNotAvailable", Nz::SocketError_AddressNotAvailable); state.PushField("AddressNotAvailable", Nz::SocketError_AddressNotAvailable);
instance.PushField("ConnectionClosed", Nz::SocketError_ConnectionClosed); state.PushField("ConnectionClosed", Nz::SocketError_ConnectionClosed);
instance.PushField("ConnectionRefused", Nz::SocketError_ConnectionRefused); state.PushField("ConnectionRefused", Nz::SocketError_ConnectionRefused);
instance.PushField("DatagramSize", Nz::SocketError_DatagramSize); state.PushField("DatagramSize", Nz::SocketError_DatagramSize);
instance.PushField("Internal", Nz::SocketError_Internal); state.PushField("Internal", Nz::SocketError_Internal);
instance.PushField("Packet", Nz::SocketError_Packet); state.PushField("Packet", Nz::SocketError_Packet);
instance.PushField("NetworkError", Nz::SocketError_NetworkError); state.PushField("NetworkError", Nz::SocketError_NetworkError);
instance.PushField("NoError", Nz::SocketError_NoError); state.PushField("NoError", Nz::SocketError_NoError);
instance.PushField("NotInitialized", Nz::SocketError_NotInitialized); state.PushField("NotInitialized", Nz::SocketError_NotInitialized);
instance.PushField("NotSupported", Nz::SocketError_NotSupported); state.PushField("NotSupported", Nz::SocketError_NotSupported);
instance.PushField("ResolveError", Nz::SocketError_ResolveError); state.PushField("ResolveError", Nz::SocketError_ResolveError);
instance.PushField("ResourceError", Nz::SocketError_ResourceError); state.PushField("ResourceError", Nz::SocketError_ResourceError);
instance.PushField("TimedOut", Nz::SocketError_TimedOut); state.PushField("TimedOut", Nz::SocketError_TimedOut);
instance.PushField("Unknown", Nz::SocketError_Unknown); state.PushField("Unknown", Nz::SocketError_Unknown);
instance.PushField("UnreachableHost", Nz::SocketError_UnreachableHost); state.PushField("UnreachableHost", Nz::SocketError_UnreachableHost);
} }
instance.SetGlobal("SocketError"); state.SetGlobal("SocketError");
// Nz::SocketState // Nz::SocketState
static_assert(Nz::SocketState_Max + 1 == 5, "Nz::SocketState has been updated but change was not reflected to Lua binding"); static_assert(Nz::SocketState_Max + 1 == 5, "Nz::SocketState has been updated but change was not reflected to Lua binding");
instance.PushTable(0, 5); state.PushTable(0, 5);
{ {
instance.PushField("Bound", Nz::SocketState_Bound); state.PushField("Bound", Nz::SocketState_Bound);
instance.PushField("Connecting", Nz::SocketState_Connecting); state.PushField("Connecting", Nz::SocketState_Connecting);
instance.PushField("Connected", Nz::SocketState_Connected); state.PushField("Connected", Nz::SocketState_Connected);
instance.PushField("NotConnected", Nz::SocketState_NotConnected); state.PushField("NotConnected", Nz::SocketState_NotConnected);
instance.PushField("Resolving", Nz::SocketState_Resolving); state.PushField("Resolving", Nz::SocketState_Resolving);
} }
instance.SetGlobal("SocketState"); state.SetGlobal("SocketState");
// Nz::SocketType // Nz::SocketType
static_assert(Nz::SocketType_Max + 1 == 4, "Nz::SocketState has been updated but change was not reflected to Lua binding"); static_assert(Nz::SocketType_Max + 1 == 4, "Nz::SocketState has been updated but change was not reflected to Lua binding");
instance.PushTable(0, 4); state.PushTable(0, 4);
{ {
instance.PushField("Raw", Nz::SocketType_Raw); state.PushField("Raw", Nz::SocketType_Raw);
instance.PushField("TCP", Nz::SocketType_TCP); state.PushField("TCP", Nz::SocketType_TCP);
instance.PushField("UDP", Nz::SocketType_UDP); state.PushField("UDP", Nz::SocketType_UDP);
instance.PushField("Unknown", Nz::SocketType_Unknown); state.PushField("Unknown", Nz::SocketType_Unknown);
} }
instance.SetGlobal("SocketType"); state.SetGlobal("SocketType");
} }
} }

View File

@ -0,0 +1,133 @@
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#include <NDK/Lua/LuaBinding_Platform.hpp>
#include <NDK/LuaAPI.hpp>
namespace Ndk
{
std::unique_ptr<LuaBinding_Base> LuaBinding_Base::BindPlatform(LuaBinding& binding)
{
return std::make_unique<LuaBinding_Platform>(binding);
}
LuaBinding_Platform::LuaBinding_Platform(LuaBinding& binding) :
LuaBinding_Base(binding)
{
/*********************************** Nz::Keyboard **********************************/
keyboard.Reset("Keyboard");
{
keyboard.BindStaticMethod("GetKeyName", &Nz::Keyboard::GetKeyName);
keyboard.BindStaticMethod("IsKeyPressed", &Nz::Keyboard::IsKeyPressed);
}
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the Utility classes
*/
void LuaBinding_Platform::Register(Nz::LuaState& state)
{
keyboard.Register(state);
keyboard.PushGlobalTable(state);
{
static_assert(Nz::Keyboard::Count == 121, "Nz::Keyboard::Key has been updated but change was not reflected to Lua binding");
state.PushField("Undefined", Nz::Keyboard::Undefined);
// A-Z
for (std::size_t i = 0; i < 26; ++i)
state.PushField(Nz::String('A' + char(i)), Nz::Keyboard::A + i);
// Numerical
for (std::size_t i = 0; i < 10; ++i)
{
state.PushField("Num" + Nz::String::Number(i), Nz::Keyboard::Num0 + i);
state.PushField("Numpad" + Nz::String::Number(i), Nz::Keyboard::Numpad0 + i);
}
// F1-F15
for (std::size_t i = 0; i < 15; ++i)
state.PushField('F' + Nz::String::Number(i+1), Nz::Keyboard::F1 + i);
// And all the others...
state.PushField("Down", Nz::Keyboard::Down);
state.PushField("Left", Nz::Keyboard::Left);
state.PushField("Right", Nz::Keyboard::Right);
state.PushField("Up", Nz::Keyboard::Up);
state.PushField("Add", Nz::Keyboard::Add);
state.PushField("Decimal", Nz::Keyboard::Decimal);
state.PushField("Divide", Nz::Keyboard::Divide);
state.PushField("Multiply", Nz::Keyboard::Multiply);
state.PushField("Subtract", Nz::Keyboard::Subtract);
state.PushField("Backslash", Nz::Keyboard::Backslash);
state.PushField("Backspace", Nz::Keyboard::Backspace);
state.PushField("Clear", Nz::Keyboard::Clear);
state.PushField("Comma", Nz::Keyboard::Comma);
state.PushField("Dash", Nz::Keyboard::Dash);
state.PushField("Delete", Nz::Keyboard::Delete);
state.PushField("End", Nz::Keyboard::End);
state.PushField("Equal", Nz::Keyboard::Equal);
state.PushField("Escape", Nz::Keyboard::Escape);
state.PushField("Home", Nz::Keyboard::Home);
state.PushField("Insert", Nz::Keyboard::Insert);
state.PushField("LAlt", Nz::Keyboard::LAlt);
state.PushField("LBracket", Nz::Keyboard::LBracket);
state.PushField("LControl", Nz::Keyboard::LControl);
state.PushField("LShift", Nz::Keyboard::LShift);
state.PushField("LSystem", Nz::Keyboard::LSystem);
state.PushField("PageDown", Nz::Keyboard::PageDown);
state.PushField("PageUp", Nz::Keyboard::PageUp);
state.PushField("Pause", Nz::Keyboard::Pause);
state.PushField("Period", Nz::Keyboard::Period);
state.PushField("Print", Nz::Keyboard::Print);
state.PushField("PrintScreen", Nz::Keyboard::PrintScreen);
state.PushField("Quote", Nz::Keyboard::Quote);
state.PushField("RAlt", Nz::Keyboard::RAlt);
state.PushField("RBracket", Nz::Keyboard::RBracket);
state.PushField("RControl", Nz::Keyboard::RControl);
state.PushField("Return", Nz::Keyboard::Return);
state.PushField("RShift", Nz::Keyboard::RShift);
state.PushField("RSystem", Nz::Keyboard::RSystem);
state.PushField("Semicolon", Nz::Keyboard::Semicolon);
state.PushField("Slash", Nz::Keyboard::Slash);
state.PushField("Space", Nz::Keyboard::Space);
state.PushField("Tab", Nz::Keyboard::Tab);
state.PushField("Tilde", Nz::Keyboard::Tilde);
state.PushField("Browser_Back", Nz::Keyboard::Browser_Back);
state.PushField("Browser_Favorites", Nz::Keyboard::Browser_Favorites);
state.PushField("Browser_Forward", Nz::Keyboard::Browser_Forward);
state.PushField("Browser_Home", Nz::Keyboard::Browser_Home);
state.PushField("Browser_Refresh", Nz::Keyboard::Browser_Refresh);
state.PushField("Browser_Search", Nz::Keyboard::Browser_Search);
state.PushField("Browser_Stop", Nz::Keyboard::Browser_Stop);
state.PushField("Media_Next", Nz::Keyboard::Media_Next);
state.PushField("Media_Play", Nz::Keyboard::Media_Play);
state.PushField("Media_Previous", Nz::Keyboard::Media_Previous);
state.PushField("Media_Stop", Nz::Keyboard::Media_Stop);
state.PushField("Volume_Down", Nz::Keyboard::Volume_Down);
state.PushField("Volume_Mute", Nz::Keyboard::Volume_Mute);
state.PushField("Volume_Up", Nz::Keyboard::Volume_Up);
state.PushField("CapsLock", Nz::Keyboard::CapsLock);
state.PushField("NumLock", Nz::Keyboard::NumLock);
state.PushField("ScrollLock", Nz::Keyboard::ScrollLock);
}
state.Pop();
static_assert(Nz::WindowStyle_Max + 1 == 6, "Nz::WindowStyle has been updated but change was not reflected to Lua binding");
state.PushTable(0, Nz::WindowStyle_Max + 1);
{
state.PushField("None", Nz::WindowStyle_None);
state.PushField("Fullscreen", Nz::WindowStyle_Fullscreen);
state.PushField("Closable", Nz::WindowStyle_Closable);
state.PushField("Resizable", Nz::WindowStyle_Resizable);
state.PushField("Titlebar", Nz::WindowStyle_Titlebar);
state.PushField("Threaded", Nz::WindowStyle_Threaded);
}
state.SetGlobal("WindowStyle");
}
}

View File

@ -27,7 +27,7 @@ namespace Ndk
return reinterpret_cast<Nz::AbstractImageRef*>(textureRef); //TODO: Make a ObjectRefCast return reinterpret_cast<Nz::AbstractImageRef*>(textureRef); //TODO: Make a ObjectRefCast
}); });
texture.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::TextureRef* instance, std::size_t /*argumentCount*/) texture.SetConstructor([] (Nz::LuaState& /*lua*/, Nz::TextureRef* instance, std::size_t /*argumentCount*/)
{ {
Nz::PlacementNew(instance, Nz::Texture::New()); Nz::PlacementNew(instance, Nz::Texture::New());
return true; return true;
@ -84,7 +84,7 @@ namespace Ndk
} }
/*********************************** Nz::TextureManager ***********************************/ /*********************************** Nz::TextureManager ***********************************/
textureManager.Reset("textureManager"); textureManager.Reset("TextureManager");
{ {
textureManager.BindStaticMethod("Clear", &Nz::TextureManager::Clear); textureManager.BindStaticMethod("Clear", &Nz::TextureManager::Clear);
textureManager.BindStaticMethod("Get", &Nz::TextureManager::Get); textureManager.BindStaticMethod("Get", &Nz::TextureManager::Get);
@ -101,10 +101,10 @@ namespace Ndk
* *
* \param instance Lua instance that will interact with the Renderer classes * \param instance Lua instance that will interact with the Renderer classes
*/ */
void LuaBinding_Renderer::Register(Nz::LuaInstance& instance) void LuaBinding_Renderer::Register(Nz::LuaState& state)
{ {
texture.Register(instance); texture.Register(state);
textureLibrary.Register(instance); textureLibrary.Register(state);
textureManager.Register(instance); textureManager.Register(state);
} }
} }

View File

@ -40,7 +40,7 @@ namespace Ndk
application.BindMethod("IsFPSCounterEnabled", &Application::IsFPSCounterEnabled); application.BindMethod("IsFPSCounterEnabled", &Application::IsFPSCounterEnabled);
#endif #endif
application.BindMethod("AddWorld", [] (Nz::LuaInstance& lua, Application* instance, std::size_t /*argumentCount*/) -> int application.BindMethod("AddWorld", [] (Nz::LuaState& lua, Application* instance, std::size_t /*argumentCount*/) -> int
{ {
lua.Push(instance->AddWorld().CreateHandle()); lua.Push(instance->AddWorld().CreateHandle());
return 1; return 1;
@ -66,6 +66,8 @@ namespace Ndk
//console.BindMethod("GetInput", &Console::GetInput); //console.BindMethod("GetInput", &Console::GetInput);
console.BindMethod("GetTextFont", &Console::GetTextFont); console.BindMethod("GetTextFont", &Console::GetTextFont);
console.BindMethod("IsValidHandle", &ConsoleHandle::IsValid);
console.BindMethod("SetCharacterSize", &Console::SetCharacterSize); console.BindMethod("SetCharacterSize", &Console::SetCharacterSize);
console.BindMethod("SetTextFont", &Console::SetTextFont); console.BindMethod("SetTextFont", &Console::SetTextFont);
} }
@ -80,26 +82,35 @@ namespace Ndk
entity.BindMethod("Kill", &Entity::Kill); entity.BindMethod("Kill", &Entity::Kill);
entity.BindMethod("IsEnabled", &Entity::IsEnabled); entity.BindMethod("IsEnabled", &Entity::IsEnabled);
entity.BindMethod("IsValid", &Entity::IsValid); entity.BindMethod("IsValid", &Entity::IsValid);
entity.BindMethod("IsValidHandle", &EntityHandle::IsValid);
entity.BindMethod("RemoveAllComponents", &Entity::RemoveAllComponents); entity.BindMethod("RemoveAllComponents", &Entity::RemoveAllComponents);
entity.BindMethod("__tostring", &EntityHandle::ToString); entity.BindMethod("__tostring", &EntityHandle::ToString);
entity.BindMethod("AddComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle, std::size_t /*argumentCount*/) -> int entity.BindMethod("AddComponent", [this] (Nz::LuaState& state, EntityHandle& handle, std::size_t /*argumentCount*/) -> int
{ {
LuaBinding::ComponentBinding* bindingComponent = m_binding.QueryComponentIndex(instance); LuaBinding::ComponentBinding* bindingComponent = m_binding.QueryComponentIndex(state);
return bindingComponent->adder(instance, handle); return bindingComponent->adder(state, handle);
}); });
entity.BindMethod("GetComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle, std::size_t /*argumentCount*/) -> int entity.BindMethod("HasComponent", [this](Nz::LuaState& state, EntityHandle& handle, std::size_t /*argumentCount*/) -> int
{ {
LuaBinding::ComponentBinding* bindingComponent = m_binding.QueryComponentIndex(instance); LuaBinding::ComponentBinding* bindingComponent = m_binding.QueryComponentIndex(state);
return bindingComponent->getter(instance, handle->GetComponent(bindingComponent->index)); state.PushBoolean(handle->HasComponent(bindingComponent->index));
return 1;
}); });
entity.BindMethod("RemoveComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle, std::size_t /*argumentCount*/) -> int entity.BindMethod("GetComponent", [this] (Nz::LuaState& state, EntityHandle& handle, std::size_t /*argumentCount*/) -> int
{ {
LuaBinding::ComponentBinding* bindingComponent = m_binding.QueryComponentIndex(instance); LuaBinding::ComponentBinding* bindingComponent = m_binding.QueryComponentIndex(state);
return bindingComponent->getter(state, handle->GetComponent(bindingComponent->index));
});
entity.BindMethod("RemoveComponent", [this] (Nz::LuaState& state, EntityHandle& handle, std::size_t /*argumentCount*/) -> int
{
LuaBinding::ComponentBinding* bindingComponent = m_binding.QueryComponentIndex(state);
handle->RemoveComponent(bindingComponent->index); handle->RemoveComponent(bindingComponent->index);
return 0; return 0;
@ -109,6 +120,8 @@ namespace Ndk
/*********************************** Ndk::NodeComponent **********************************/ /*********************************** Ndk::NodeComponent **********************************/
nodeComponent.Reset("NodeComponent"); nodeComponent.Reset("NodeComponent");
{ {
nodeComponent.BindMethod("IsValidHandle", &NodeComponentHandle::IsValid);
nodeComponent.Inherit<Nz::Node>(utility.node, [] (NodeComponentHandle* handle) -> Nz::Node* nodeComponent.Inherit<Nz::Node>(utility.node, [] (NodeComponentHandle* handle) -> Nz::Node*
{ {
return handle->GetObject(); return handle->GetObject();
@ -118,7 +131,9 @@ namespace Ndk
/*********************************** Ndk::VelocityComponent **********************************/ /*********************************** Ndk::VelocityComponent **********************************/
velocityComponent.Reset("VelocityComponent"); velocityComponent.Reset("VelocityComponent");
{ {
velocityComponent.SetGetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance) velocityComponent.BindMethod("IsValidHandle", &VelocityComponentHandle::IsValid);
velocityComponent.SetGetter([] (Nz::LuaState& lua, VelocityComponentHandle& instance)
{ {
std::size_t length; std::size_t length;
const char* member = lua.CheckString(2, &length); const char* member = lua.CheckString(2, &length);
@ -132,7 +147,7 @@ namespace Ndk
return false; return false;
}); });
velocityComponent.SetSetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance) velocityComponent.SetSetter([] (Nz::LuaState& lua, VelocityComponentHandle& instance)
{ {
std::size_t length; std::size_t length;
const char* member = lua.CheckString(2, &length); const char* member = lua.CheckString(2, &length);
@ -154,6 +169,8 @@ namespace Ndk
world.BindMethod("CreateEntity", &World::CreateEntity); world.BindMethod("CreateEntity", &World::CreateEntity);
world.BindMethod("CreateEntities", &World::CreateEntities); world.BindMethod("CreateEntities", &World::CreateEntities);
world.BindMethod("Clear", &World::Clear); world.BindMethod("Clear", &World::Clear);
world.BindMethod("IsValidHandle", &WorldHandle::IsValid);
} }
#ifndef NDK_SERVER #ifndef NDK_SERVER
@ -165,24 +182,26 @@ namespace Ndk
return handle->GetObject(); return handle->GetObject();
}); });
cameraComponent.BindMethod("GetFOV", &Ndk::CameraComponent::GetFOV); cameraComponent.BindMethod("GetFOV", &CameraComponent::GetFOV);
cameraComponent.BindMethod("GetLayer", &Ndk::CameraComponent::GetLayer); cameraComponent.BindMethod("GetLayer", &CameraComponent::GetLayer);
cameraComponent.BindMethod("SetFOV", &Ndk::CameraComponent::SetFOV); cameraComponent.BindMethod("IsValidHandle", &CameraComponentHandle::IsValid);
cameraComponent.BindMethod("SetLayer", &Ndk::CameraComponent::SetLayer);
cameraComponent.BindMethod("SetProjectionType", &Ndk::CameraComponent::SetProjectionType); cameraComponent.BindMethod("SetFOV", &CameraComponent::SetFOV);
cameraComponent.BindMethod("SetSize", (void(Ndk::CameraComponent::*)(const Nz::Vector2f&)) &Ndk::CameraComponent::SetSize); cameraComponent.BindMethod("SetLayer", &CameraComponent::SetLayer);
//cameraComponent.BindMethod("SetTarget", &Ndk::CameraComponent::SetTarget); cameraComponent.BindMethod("SetProjectionType", &CameraComponent::SetProjectionType);
cameraComponent.BindMethod("SetTargetRegion", &Ndk::CameraComponent::SetTargetRegion); cameraComponent.BindMethod("SetSize", (void(CameraComponent::*)(const Nz::Vector2f&)) &CameraComponent::SetSize);
cameraComponent.BindMethod("SetViewport", &Ndk::CameraComponent::SetViewport); //cameraComponent.BindMethod("SetTarget", &CameraComponent::SetTarget);
cameraComponent.BindMethod("SetZFar", &Ndk::CameraComponent::SetZFar); cameraComponent.BindMethod("SetTargetRegion", &CameraComponent::SetTargetRegion);
cameraComponent.BindMethod("SetZNear", &Ndk::CameraComponent::SetZNear); cameraComponent.BindMethod("SetViewport", &CameraComponent::SetViewport);
cameraComponent.BindMethod("SetZFar", &CameraComponent::SetZFar);
cameraComponent.BindMethod("SetZNear", &CameraComponent::SetZNear);
} }
/*********************************** Ndk::GraphicsComponent **********************************/ /*********************************** Ndk::GraphicsComponent **********************************/
graphicsComponent.Reset("GraphicsComponent"); graphicsComponent.Reset("GraphicsComponent");
{ {
graphicsComponent.BindMethod("Attach", [] (Nz::LuaInstance& lua, Ndk::GraphicsComponent* instance, std::size_t argumentCount) -> int graphicsComponent.BindMethod("Attach", [] (Nz::LuaState& lua, Ndk::GraphicsComponent* instance, std::size_t argumentCount) -> int
{ {
/* /*
void Attach(Nz::InstancedRenderableRef renderable, int renderOrder = 0); void Attach(Nz::InstancedRenderableRef renderable, int renderOrder = 0);
@ -238,6 +257,8 @@ namespace Ndk
lua.Error("No matching overload for method GetMemoryUsage"); lua.Error("No matching overload for method GetMemoryUsage");
return 0; return 0;
}); });
graphicsComponent.BindMethod("IsValidHandle", &GraphicsComponentHandle::IsValid);
} }
#endif #endif
@ -256,19 +277,19 @@ namespace Ndk
* *
* \param instance Lua instance that will interact with the SDK classes * \param instance Lua instance that will interact with the SDK classes
*/ */
void LuaBinding_SDK::Register(Nz::LuaInstance& instance) void LuaBinding_SDK::Register(Nz::LuaState& state)
{ {
// Classes // Classes
application.Register(instance); application.Register(state);
entity.Register(instance); entity.Register(state);
nodeComponent.Register(instance); nodeComponent.Register(state);
velocityComponent.Register(instance); velocityComponent.Register(state);
world.Register(instance); world.Register(state);
#ifndef NDK_SERVER #ifndef NDK_SERVER
cameraComponent.Register(instance); cameraComponent.Register(state);
console.Register(instance); console.Register(state);
graphicsComponent.Register(instance); graphicsComponent.Register(state);
#endif #endif
// Enums // Enums
@ -281,23 +302,23 @@ namespace Ndk
* \param instance Lua instance that will interact with the component * \param instance Lua instance that will interact with the component
* \param argIndex Index of the component * \param argIndex Index of the component
*/ */
LuaBinding::ComponentBinding* LuaBinding::QueryComponentIndex(Nz::LuaInstance& instance, int argIndex) LuaBinding::ComponentBinding* LuaBinding::QueryComponentIndex(Nz::LuaState& state, int argIndex)
{ {
switch (instance.GetType(argIndex)) switch (state.GetType(argIndex))
{ {
case Nz::LuaType_Number: case Nz::LuaType_Number:
{ {
ComponentIndex componentIndex = instance.Check<ComponentIndex>(&argIndex); ComponentIndex componentIndex = state.Check<ComponentIndex>(&argIndex);
if (componentIndex > m_componentBinding.size()) if (componentIndex > m_componentBinding.size())
{ {
instance.Error("Invalid component index"); state.Error("Invalid component index");
return nullptr; return nullptr;
} }
ComponentBinding& binding = m_componentBinding[componentIndex]; ComponentBinding& binding = m_componentBinding[componentIndex];
if (binding.name.IsEmpty()) if (binding.name.IsEmpty())
{ {
instance.Error("Invalid component index"); state.Error("Invalid component index");
return nullptr; return nullptr;
} }
@ -306,11 +327,11 @@ namespace Ndk
case Nz::LuaType_String: case Nz::LuaType_String:
{ {
const char* key = instance.CheckString(argIndex); const char* key = state.CheckString(argIndex);
auto it = m_componentBindingByName.find(key); auto it = m_componentBindingByName.find(key);
if (it == m_componentBindingByName.end()) if (it == m_componentBindingByName.end())
{ {
instance.Error("Invalid component name"); state.Error("Invalid component name");
return nullptr; return nullptr;
} }
@ -321,7 +342,7 @@ namespace Ndk
break; break;
} }
instance.Error("Invalid component index at #" + Nz::String::Number(argIndex)); state.Error("Invalid component index at #" + Nz::String::Number(argIndex));
return nullptr; return nullptr;
} }
} }

View File

@ -29,7 +29,7 @@ namespace Ndk
abstractImage.BindMethod("IsCompressed", &Nz::AbstractImage::IsCompressed); abstractImage.BindMethod("IsCompressed", &Nz::AbstractImage::IsCompressed);
abstractImage.BindMethod("IsCubemap", &Nz::AbstractImage::IsCubemap); abstractImage.BindMethod("IsCubemap", &Nz::AbstractImage::IsCubemap);
abstractImage.BindMethod("GetMemoryUsage", [] (Nz::LuaInstance& lua, Nz::AbstractImage* instance, std::size_t argumentCount) -> int abstractImage.BindMethod("GetMemoryUsage", [] (Nz::LuaState& lua, Nz::AbstractImage* instance, std::size_t argumentCount) -> int
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 1U); std::size_t argCount = std::min<std::size_t>(argumentCount, 1U);
switch (argCount) switch (argCount)
@ -50,7 +50,7 @@ namespace Ndk
return 0; return 0;
}); });
abstractImage.BindMethod("Update", [] (Nz::LuaInstance& lua, Nz::AbstractImage* instance, std::size_t argumentCount) -> int abstractImage.BindMethod("Update", [] (Nz::LuaState& lua, Nz::AbstractImage* instance, std::size_t argumentCount) -> int
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 6U); std::size_t argCount = std::min<std::size_t>(argumentCount, 6U);
int argIndex = 2; int argIndex = 2;
@ -100,7 +100,7 @@ namespace Ndk
/*********************************** Nz::Font **********************************/ /*********************************** Nz::Font **********************************/
font.Reset("Font"); font.Reset("Font");
{ {
font.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::FontRef* instance, std::size_t /*argumentCount*/) font.SetConstructor([] (Nz::LuaState& /*lua*/, Nz::FontRef* instance, std::size_t /*argumentCount*/)
{ {
Nz::PlacementNew(instance, Nz::Font::New()); Nz::PlacementNew(instance, Nz::Font::New());
return true; return true;
@ -112,7 +112,7 @@ namespace Ndk
font.BindMethod("Destroy", &Nz::Font::Destroy); font.BindMethod("Destroy", &Nz::Font::Destroy);
font.BindMethod("GetCachedGlyphCount", [] (Nz::LuaInstance& lua, Nz::FontRef& instance, std::size_t argumentCount) -> int font.BindMethod("GetCachedGlyphCount", [] (Nz::LuaState& lua, Nz::FontRef& instance, std::size_t argumentCount) -> int
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 2U); std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
@ -161,13 +161,6 @@ namespace Ndk
font.BindStaticMethod("SetDefaultMinimumStepSize", &Nz::Font::SetDefaultMinimumStepSize); font.BindStaticMethod("SetDefaultMinimumStepSize", &Nz::Font::SetDefaultMinimumStepSize);
} }
/*********************************** Nz::Keyboard **********************************/
keyboard.Reset("Keyboard");
{
keyboard.BindStaticMethod("GetKeyName", &Nz::Keyboard::GetKeyName);
keyboard.BindStaticMethod("IsKeyPressed", &Nz::Keyboard::IsKeyPressed);
}
/*********************************** Nz::Node **********************************/ /*********************************** Nz::Node **********************************/
node.Reset("Node"); node.Reset("Node");
{ {
@ -216,29 +209,29 @@ namespace Ndk
node.BindMethod("SetPosition", (void(Nz::Node::*)(const Nz::Vector3f&, Nz::CoordSys)) &Nz::Node::SetPosition, Nz::CoordSys_Local); node.BindMethod("SetPosition", (void(Nz::Node::*)(const Nz::Vector3f&, Nz::CoordSys)) &Nz::Node::SetPosition, Nz::CoordSys_Local);
node.BindMethod("SetRotation", (void(Nz::Node::*)(const Nz::Quaternionf&, Nz::CoordSys)) &Nz::Node::SetRotation, Nz::CoordSys_Local); 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& instance, std::size_t /*argumentCount*/) -> int node.BindMethod("Move", [] (Nz::LuaState& lua, Nz::Node& node, std::size_t /*argumentCount*/) -> int
{ {
int argIndex = 2; int argIndex = 2;
Nz::Vector3f offset = lua.Check<Nz::Vector3f>(&argIndex); Nz::Vector3f offset = lua.Check<Nz::Vector3f>(&argIndex);
Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local); Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local);
instance.Move(offset, coordSys); node.Move(offset, coordSys);
return 0; return 0;
}); });
node.BindMethod("Rotate", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t /*argumentCount*/) -> int node.BindMethod("Rotate", [] (Nz::LuaState& lua, Nz::Node& node, std::size_t /*argumentCount*/) -> int
{ {
int argIndex = 2; int argIndex = 2;
Nz::Quaternionf rotation = lua.Check<Nz::Quaternionf>(&argIndex); Nz::Quaternionf rotation = lua.Check<Nz::Quaternionf>(&argIndex);
Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local); Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local);
instance.Rotate(rotation, coordSys); node.Rotate(rotation, coordSys);
return 0; return 0;
}); });
node.BindMethod("Scale", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t argumentCount) -> int node.BindMethod("Scale", [] (Nz::LuaState& lua, Nz::Node& node, std::size_t argumentCount) -> int
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U); std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
@ -248,15 +241,15 @@ namespace Ndk
case 1: case 1:
{ {
if (lua.IsOfType(argIndex, Nz::LuaType_Number)) if (lua.IsOfType(argIndex, Nz::LuaType_Number))
instance.Scale(lua.Check<float>(&argIndex)); node.Scale(lua.Check<float>(&argIndex));
else else
instance.Scale(lua.Check<Nz::Vector3f>(&argIndex)); node.Scale(lua.Check<Nz::Vector3f>(&argIndex));
return 0; return 0;
} }
case 3: case 3:
instance.Scale(lua.Check<Nz::Vector3f>(&argIndex)); node.Scale(lua.Check<Nz::Vector3f>(&argIndex));
return 0; return 0;
} }
@ -264,7 +257,7 @@ namespace Ndk
return 0; return 0;
}); });
node.BindMethod("SetScale", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t argumentCount) -> int node.BindMethod("SetScale", [] (Nz::LuaState& lua, Nz::Node& node, std::size_t argumentCount) -> int
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U); std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
@ -278,10 +271,10 @@ namespace Ndk
{ {
float scale = lua.Check<float>(&argIndex); float scale = lua.Check<float>(&argIndex);
Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local); Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local);
instance.SetScale(scale, coordSys); node.SetScale(scale, coordSys);
} }
else else
instance.SetScale(lua.Check<Nz::Vector3f>(&argIndex)); node.SetScale(lua.Check<Nz::Vector3f>(&argIndex));
return 0; return 0;
} }
@ -292,7 +285,7 @@ namespace Ndk
Nz::Vector3f scale = lua.Check<Nz::Vector3f>(&argIndex); Nz::Vector3f scale = lua.Check<Nz::Vector3f>(&argIndex);
Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local); Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local);
instance.SetScale(scale, coordSys); node.SetScale(scale, coordSys);
return 0; return 0;
} }
} }
@ -301,7 +294,7 @@ namespace Ndk
return 0; return 0;
}); });
node.BindMethod("SetInitialScale", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t argumentCount) -> int node.BindMethod("SetInitialScale", [] (Nz::LuaState& lua, Nz::Node& node, std::size_t argumentCount) -> int
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U); std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
@ -311,16 +304,16 @@ namespace Ndk
case 1: case 1:
{ {
if (lua.IsOfType(argIndex, Nz::LuaType_Number)) if (lua.IsOfType(argIndex, Nz::LuaType_Number))
instance.SetInitialScale(lua.Check<float>(&argIndex)); node.SetInitialScale(lua.Check<float>(&argIndex));
else else
instance.SetInitialScale(lua.Check<Nz::Vector2f>(&argIndex)); node.SetInitialScale(lua.Check<Nz::Vector2f>(&argIndex));
return 0; return 0;
} }
case 2: case 2:
case 3: case 3:
instance.SetInitialScale(lua.Check<Nz::Vector3f>(&argIndex)); node.SetInitialScale(lua.Check<Nz::Vector3f>(&argIndex));
return 0; return 0;
} }
@ -335,112 +328,10 @@ namespace Ndk
* *
* \param instance Lua instance that will interact with the Utility classes * \param instance Lua instance that will interact with the Utility classes
*/ */
void LuaBinding_Utility::Register(Nz::LuaInstance& instance) void LuaBinding_Utility::Register(Nz::LuaState& state)
{ {
abstractImage.Register(instance); abstractImage.Register(state);
font.Register(instance); font.Register(state);
keyboard.Register(instance); node.Register(state);
node.Register(instance);
keyboard.PushGlobalTable(instance);
{
static_assert(Nz::Keyboard::Count == 121, "Nz::Keyboard::Key has been updated but change was not reflected to Lua binding");
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();
static_assert(Nz::WindowStyle_Max + 1 == 6, "Nz::WindowStyle has been updated but change was not reflected to Lua binding");
instance.PushTable(0, Nz::WindowStyle_Max + 1);
{
instance.PushField("None", Nz::WindowStyle_None);
instance.PushField("Fullscreen", Nz::WindowStyle_Fullscreen);
instance.PushField("Closable", Nz::WindowStyle_Closable);
instance.PushField("Resizable", Nz::WindowStyle_Resizable);
instance.PushField("Titlebar", Nz::WindowStyle_Titlebar);
instance.PushField("Threaded", Nz::WindowStyle_Threaded);
}
instance.SetGlobal("WindowStyle");
} }
} }

View File

@ -44,10 +44,10 @@ namespace Ndk
* \param instance Lua instance that will interact with the engine & SDK * \param instance Lua instance that will interact with the engine & SDK
*/ */
void LuaAPI::RegisterClasses(Nz::LuaInstance& instance) void LuaAPI::RegisterClasses(Nz::LuaState& state)
{ {
Nz::ErrorFlags errFlags(Nz::ErrorFlag_ThrowException, true); Nz::ErrorFlags errFlags(Nz::ErrorFlag_ThrowException, true);
GetBinding()->RegisterClasses(instance); GetBinding()->RegisterClasses(state);
} }
/*! /*!

File diff suppressed because one or more lines are too long

View File

@ -6,11 +6,13 @@
#include <Nazara/Audio/Audio.hpp> #include <Nazara/Audio/Audio.hpp>
#include <Nazara/Core/ErrorFlags.hpp> #include <Nazara/Core/ErrorFlags.hpp>
#include <Nazara/Core/Log.hpp> #include <Nazara/Core/Log.hpp>
#include <Nazara/Core/ParameterList.hpp>
#include <Nazara/Graphics/Graphics.hpp> #include <Nazara/Graphics/Graphics.hpp>
#include <Nazara/Lua/Lua.hpp> #include <Nazara/Lua/Lua.hpp>
#include <Nazara/Noise/Noise.hpp> #include <Nazara/Noise/Noise.hpp>
#include <Nazara/Physics2D/Physics2D.hpp> #include <Nazara/Physics2D/Physics2D.hpp>
#include <Nazara/Physics3D/Physics3D.hpp> #include <Nazara/Physics3D/Physics3D.hpp>
#include <Nazara/Platform/Platform.hpp>
#include <Nazara/Utility/Utility.hpp> #include <Nazara/Utility/Utility.hpp>
#include <NDK/Algorithm.hpp> #include <NDK/Algorithm.hpp>
#include <NDK/BaseSystem.hpp> #include <NDK/BaseSystem.hpp>
@ -34,6 +36,7 @@
#include <NDK/Systems/ParticleSystem.hpp> #include <NDK/Systems/ParticleSystem.hpp>
#include <NDK/Systems/ListenerSystem.hpp> #include <NDK/Systems/ListenerSystem.hpp>
#include <NDK/Systems/RenderSystem.hpp> #include <NDK/Systems/RenderSystem.hpp>
#include <NDK/Widgets/CheckboxWidget.hpp>
#endif #endif
namespace Ndk namespace Ndk
@ -63,13 +66,6 @@ namespace Ndk
// Initialize the engine first // Initialize the engine first
// Shared modules // Shared modules
#ifdef NDK_SERVER
Nz::ParameterList parameters;
parameters.SetParameter("NoWindowSystem", true);
Nz::Utility::SetParameters(parameters);
#endif
Nz::Lua::Initialize(); Nz::Lua::Initialize();
Nz::Noise::Initialize(); Nz::Noise::Initialize();
Nz::Physics2D::Initialize(); Nz::Physics2D::Initialize();
@ -119,6 +115,13 @@ namespace Ndk
InitializeSystem<ListenerSystem>(); InitializeSystem<ListenerSystem>();
InitializeSystem<ParticleSystem>(); InitializeSystem<ParticleSystem>();
InitializeSystem<RenderSystem>(); InitializeSystem<RenderSystem>();
// Widgets
if (!CheckboxWidget::Initialize())
{
NazaraError("Failed to initialize Checkbox Widget");
return false;
}
#endif #endif
NazaraNotice("Initialized: SDK"); NazaraNotice("Initialized: SDK");
@ -127,7 +130,6 @@ namespace Ndk
catch (const std::exception& e) catch (const std::exception& e)
{ {
NazaraError("Failed to initialize NDK: " + Nz::String(e.what())); NazaraError("Failed to initialize NDK: " + Nz::String(e.what()));
return false; return false;
} }
} }
@ -173,6 +175,11 @@ namespace Ndk
Nz::Physics3D::Uninitialize(); Nz::Physics3D::Uninitialize();
Nz::Utility::Uninitialize(); Nz::Utility::Uninitialize();
#ifndef NDK_SERVER
// Widgets
CheckboxWidget::Uninitialize();
#endif
NazaraNotice("Uninitialized: SDK"); NazaraNotice("Uninitialized: SDK");
} }

View File

@ -48,12 +48,14 @@ namespace Ndk
{ {
m_forceRenderQueueInvalidation = true; //< Hackfix until lights and particles are handled by culling list m_forceRenderQueueInvalidation = true; //< Hackfix until lights and particles are handled by culling list
m_cameras.Remove(entity); for (auto it = m_cameras.begin(); it != m_cameras.end(); ++it)
m_directionalLights.Remove(entity); {
m_drawables.Remove(entity); if (it->GetObject() == entity)
m_lights.Remove(entity); {
m_particleGroups.Remove(entity); m_cameras.erase(it);
m_pointSpotLights.Remove(entity); break;
}
}
if (entity->HasComponent<GraphicsComponent>()) if (entity->HasComponent<GraphicsComponent>())
{ {
@ -74,14 +76,23 @@ namespace Ndk
if (entity->HasComponent<CameraComponent>() && entity->HasComponent<NodeComponent>()) if (entity->HasComponent<CameraComponent>() && entity->HasComponent<NodeComponent>())
{ {
m_cameras.Insert(entity); m_cameras.emplace_back(entity);
std::sort(m_cameras.begin(), m_cameras.end(), [](const EntityHandle& handle1, const EntityHandle& handle2) std::sort(m_cameras.begin(), m_cameras.end(), [](const EntityHandle& handle1, const EntityHandle& handle2)
{ {
return handle1->GetComponent<CameraComponent>().GetLayer() < handle2->GetComponent<CameraComponent>().GetLayer(); return handle1->GetComponent<CameraComponent>().GetLayer() < handle2->GetComponent<CameraComponent>().GetLayer();
}); });
} }
else else
m_cameras.Remove(entity); {
for (auto it = m_cameras.begin(); it != m_cameras.end(); ++it)
{
if (it->GetObject() == entity)
{
m_cameras.erase(it);
break;
}
}
}
if (entity->HasComponent<GraphicsComponent>() && entity->HasComponent<NodeComponent>()) if (entity->HasComponent<GraphicsComponent>() && entity->HasComponent<NodeComponent>())
{ {
@ -181,7 +192,7 @@ namespace Ndk
GraphicsComponent& graphicsComponent = drawable->GetComponent<GraphicsComponent>(); GraphicsComponent& graphicsComponent = drawable->GetComponent<GraphicsComponent>();
graphicsComponent.EnsureBoundingVolumeUpdate(); graphicsComponent.EnsureBoundingVolumeUpdate();
} }
bool forceInvalidation = false; bool forceInvalidation = false;
std::size_t visibilityHash = m_drawableCulling.Cull(camComponent.GetFrustum(), &forceInvalidation); std::size_t visibilityHash = m_drawableCulling.Cull(camComponent.GetFrustum(), &forceInvalidation);

View File

@ -61,7 +61,6 @@ namespace Ndk
m_gradientSprite->SetColor(Nz::Color(128, 128, 128)); m_gradientSprite->SetColor(Nz::Color(128, 128, 128));
} }
void ButtonWidget::OnMouseExit() void ButtonWidget::OnMouseExit()
{ {
m_gradientSprite->SetColor(Nz::Color(74, 74, 74)); m_gradientSprite->SetColor(Nz::Color(74, 74, 74));

View File

@ -0,0 +1,185 @@
// Copyright (C) 2017 Samy Bensaid
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#include <NDK/World.hpp>
#include <NDK/Widgets/CheckboxWidget.hpp>
#include <NDK/Components/GraphicsComponent.hpp>
#include <Nazara/Utility/SimpleTextDrawer.hpp>
#include <Nazara/Graphics/Material.hpp>
#include <Nazara/Utility/Font.hpp>
#include <Nazara/Utility/FontGlyph.hpp>
#include <algorithm>
namespace Ndk
{
Nz::Color CheckboxWidget::s_backgroundColor { Nz::Color::White };
Nz::Color CheckboxWidget::s_disabledBackgroundColor { 201, 201, 201 };
Nz::Color CheckboxWidget::s_disabledBorderColor { 62, 62, 62 };
Nz::Color CheckboxWidget::s_borderColor { Nz::Color::Black };
float CheckboxWidget::s_borderScale { 16.f };
CheckboxWidget::CheckboxWidget(BaseWidget* parent) :
BaseWidget(parent),
m_adaptativeMargin { true },
m_checkboxEnabled { true },
m_tristateEnabled { false },
m_textMargin { 16.f },
m_state { CheckboxState_Unchecked }
{
m_checkboxBorderSprite = Nz::Sprite::New(Nz::Material::New("Basic2D"));
m_checkboxBackgroundSprite = Nz::Sprite::New(Nz::Material::New("Basic2D"));
m_checkboxContentSprite = Nz::Sprite::New(Nz::Material::New("Translucent2D"));
m_textSprite = Nz::TextSprite::New();
m_checkboxBorderEntity = CreateEntity();
m_checkboxBorderEntity->AddComponent<NodeComponent>().SetParent(this);
m_checkboxBorderEntity->AddComponent<GraphicsComponent>().Attach(m_checkboxBorderSprite);
m_checkboxBackgroundEntity = CreateEntity();
m_checkboxBackgroundEntity->AddComponent<NodeComponent>().SetParent(this);
m_checkboxBackgroundEntity->AddComponent<GraphicsComponent>().Attach(m_checkboxBackgroundSprite, 1);
m_checkboxContentEntity = CreateEntity();
m_checkboxContentEntity->AddComponent<NodeComponent>().SetParent(this);
m_checkboxContentEntity->AddComponent<GraphicsComponent>().Attach(m_checkboxContentSprite, 2);
m_textEntity = CreateEntity();
m_textEntity->AddComponent<NodeComponent>().SetParent(this);
m_textEntity->AddComponent<GraphicsComponent>().Attach(m_textSprite);
m_checkMark = Nz::TextureLibrary::Get("Ndk::CheckboxWidget::checkmark");
SetCheckboxSize({ 32.f, 32.f });
UpdateCheckbox();
}
bool CheckboxWidget::Initialize()
{
const Nz::UInt8 r_checkmark[] =
{
#include <NDK/Resources/checkmark.png.h>
};
Nz::TextureRef checkmarkTexture = Nz::Texture::New();
if (!checkmarkTexture->LoadFromMemory(r_checkmark, sizeof(r_checkmark) / sizeof(r_checkmark[0])))
{
NazaraError("Failed to load embedded checkmark");
return false;
}
Nz::TextureLibrary::Register("Ndk::CheckboxWidget::checkmark", checkmarkTexture);
return true;
}
void CheckboxWidget::Uninitialize()
{
Nz::TextureLibrary::Unregister("Ndk::CheckboxWidget::checkmark");
}
void CheckboxWidget::SetState(CheckboxState state)
{
if (!m_checkboxEnabled)
return;
if (state == CheckboxState_Tristate)
m_tristateEnabled = true;
m_state = state;
UpdateCheckbox();
}
CheckboxState CheckboxWidget::SwitchToNextState()
{
if (!m_checkboxEnabled)
return m_state;
switch (m_state)
{
case CheckboxState_Unchecked:
SetState(CheckboxState_Checked);
break;
case CheckboxState_Checked:
SetState(m_tristateEnabled ? CheckboxState_Tristate : CheckboxState_Unchecked);
break;
case CheckboxState_Tristate:
SetState(CheckboxState_Unchecked);
break;
}
return m_state;
}
void CheckboxWidget::ResizeToContent()
{
Nz::Vector3f textSize = m_textSprite->GetBoundingVolume().obb.localBox.GetLengths();
Nz::Vector2f checkboxSize = GetCheckboxSize();
Nz::Vector2f finalSize { checkboxSize.x + (m_adaptativeMargin ? checkboxSize.x / 2.f : m_textMargin) + textSize.x, std::max(textSize.y, checkboxSize.y) };
SetContentSize(finalSize);
}
void CheckboxWidget::Layout()
{
BaseWidget::Layout();
Nz::Vector2f origin = GetContentOrigin();
Nz::Vector2f checkboxSize = GetCheckboxSize();
Nz::Vector2f borderSize = GetCheckboxBorderSize();
m_checkboxBorderEntity->GetComponent<NodeComponent>().SetPosition(origin);
m_checkboxBackgroundEntity->GetComponent<NodeComponent>().SetPosition(origin + borderSize);
Nz::Vector3f checkboxBox = m_checkboxContentSprite->GetBoundingVolume().obb.localBox.GetLengths();
m_checkboxContentEntity->GetComponent<NodeComponent>().SetPosition(origin.x + checkboxSize.x / 2.f - checkboxBox.x / 2.f,
origin.y + checkboxSize.y / 2.f - checkboxBox.y / 2.f);
Nz::Vector3f textBox = m_textSprite->GetBoundingVolume().obb.localBox.GetLengths();
m_textEntity->GetComponent<NodeComponent>().SetPosition(origin.x + checkboxSize.x + (m_adaptativeMargin ? checkboxSize.x / 2.f : m_textMargin),
origin.y + checkboxSize.y / 2.f - textBox.y / 2.f);
}
void CheckboxWidget::OnMouseButtonRelease(int x, int y, Nz::Mouse::Button button)
{
if (button == Nz::Mouse::Left && ContainsCheckbox(x, y) && IsCheckboxEnabled())
{
SwitchToNextState();
OnStateChanged(this);
}
}
void CheckboxWidget::UpdateCheckbox()
{
if (m_checkboxEnabled)
{
m_checkboxBorderSprite->SetColor(s_borderColor);
m_checkboxBackgroundSprite->SetColor(s_backgroundColor);
}
else
{
m_checkboxBorderSprite->SetColor(s_disabledBorderColor);
m_checkboxBackgroundSprite->SetColor(s_disabledBackgroundColor);
}
if (m_state == CheckboxState_Unchecked)
{
m_checkboxContentEntity->Enable(false);
return;
}
else if (m_state == CheckboxState_Checked)
{
m_checkboxContentEntity->Enable();
m_checkboxContentSprite->SetColor(Nz::Color::White);
m_checkboxContentSprite->SetTexture(m_checkMark, false);
}
else // Tristate
{
m_checkboxContentEntity->Enable();
m_checkboxContentSprite->SetColor(Nz::Color::Black);
m_checkboxContentSprite->SetTexture(Nz::TextureRef {});
}
}
}

View File

@ -0,0 +1,104 @@
// Copyright (C) 2017 Samy Bensaid
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#include <NDK/World.hpp>
#include <NDK/Widgets/ProgressBarWidget.hpp>
#include <Nazara/Utility/Image.hpp>
#include <NDK/Components/NodeComponent.hpp>
#include <NDK/Components/GraphicsComponent.hpp>
namespace Ndk
{
float ProgressBarWidget::s_borderScale { 16.f };
Nz::Color ProgressBarWidget::s_borderColor { Nz::Color::Black };
Nz::Color ProgressBarWidget::s_barBackgroundColor { Nz::Color { 225, 225, 225 } };
Nz::Color ProgressBarWidget::s_barBackgroundCornerColor { Nz::Color { 255, 255, 255 } };
Nz::Color ProgressBarWidget::s_barColor { Nz::Color { 0, 225, 0 } };
Nz::Color ProgressBarWidget::s_barCornerColor { Nz::Color { 220, 255, 220 } };
ProgressBarWidget::ProgressBarWidget(BaseWidget* parent) :
BaseWidget(parent),
m_textColor { Nz::Color::Black },
m_textMargin { 16.f },
m_value { 0u }
{
m_borderSprite = Nz::Sprite::New(Nz::Material::New("Basic2D"));
m_barBackgroundSprite = Nz::Sprite::New(Nz::Material::New("Basic2D"));
m_barSprite = Nz::Sprite::New(Nz::Material::New("Basic2D"));
m_borderSprite->SetColor(s_borderColor);
SetBarBackgroundColor(s_barBackgroundColor, s_barBackgroundCornerColor);
SetBarColor(s_barColor, s_barCornerColor);
m_borderEntity = CreateEntity();
m_borderEntity->AddComponent<NodeComponent>().SetParent(this);
m_borderEntity->AddComponent<GraphicsComponent>().Attach(m_borderSprite);
m_barEntity = CreateEntity();
m_barEntity->AddComponent<NodeComponent>().SetParent(this);
GraphicsComponent& graphics = m_barEntity->AddComponent<GraphicsComponent>();
graphics.Attach(m_barBackgroundSprite, 1);
graphics.Attach(m_barSprite, 2);
m_textSprite = Nz::TextSprite::New();
m_textEntity = CreateEntity();
m_textEntity->AddComponent<NodeComponent>().SetParent(this);
m_textEntity->AddComponent<GraphicsComponent>().Attach(m_textSprite);
UpdateText();
Layout();
}
const Nz::Color& ProgressBarWidget::GetDefaultBarColor()
{
return s_barColor;
}
const Nz::Color& ProgressBarWidget::GetDefaultBarCornerColor()
{
return s_barCornerColor;
}
const Nz::Color& ProgressBarWidget::GetDefaultBarBackgroundColor()
{
return s_barBackgroundColor;
}
const Nz::Color& ProgressBarWidget::GetDefaultBarBackgroundCornerColor()
{
return s_barBackgroundCornerColor;
}
void ProgressBarWidget::Layout()
{
Nz::Vector2f origin = GetContentOrigin();
Nz::Vector2f size = GetContentSize();
Nz::Vector2f progressBarSize = size;
if (IsTextEnabled())
{
UpdateText();
Nz::Vector3f textSize = m_textSprite->GetBoundingVolume().obb.localBox.GetLengths();
m_textEntity->GetComponent<NodeComponent>().SetPosition(origin.x + size.x - textSize.x, origin.y + size.y / 2.f - textSize.y);
progressBarSize -= { textSize.x + m_textMargin, 0.f };
}
m_borderSprite->SetSize(progressBarSize);
Nz::Vector2f borderSize = GetProgressBarBorderSize();
m_barBackgroundSprite->SetSize(progressBarSize - (borderSize * 2.f));
m_barSprite->SetSize((progressBarSize.x - (borderSize.x * 2.f)) / 100.f * static_cast<float>(m_value), progressBarSize.y - (borderSize.y * 2.f));
m_borderEntity->GetComponent<NodeComponent>().SetPosition(origin.x, origin.y);
m_barEntity->GetComponent<NodeComponent>().SetPosition(origin.x + borderSize.x, origin.y + borderSize.y);
}
}

View File

@ -13,7 +13,8 @@ namespace Ndk
{ {
TextAreaWidget::TextAreaWidget(BaseWidget* parent) : TextAreaWidget::TextAreaWidget(BaseWidget* parent) :
BaseWidget(parent), BaseWidget(parent),
m_cursorPosition(0U), m_cursorPosition(0U, 0U),
m_cursorGlyph(0),
m_multiLineEnabled(false), m_multiLineEnabled(false),
m_readOnly(false) m_readOnly(false)
{ {
@ -81,7 +82,7 @@ namespace Ndk
void TextAreaWidget::Write(const Nz::String& text) void TextAreaWidget::Write(const Nz::String& text)
{ {
if (m_cursorPosition >= m_drawer.GetGlyphCount()) if (m_cursorGlyph >= m_drawer.GetGlyphCount())
{ {
AppendText(text); AppendText(text);
SetCursorPosition(m_drawer.GetGlyphCount()); SetCursorPosition(m_drawer.GetGlyphCount());
@ -89,10 +90,10 @@ namespace Ndk
else else
{ {
Nz::String currentText = m_drawer.GetText(); Nz::String currentText = m_drawer.GetText();
currentText.Insert(currentText.GetCharacterPosition(m_cursorPosition), text); currentText.Insert(currentText.GetCharacterPosition(m_cursorGlyph), text);
SetText(currentText); SetText(currentText);
SetCursorPosition(m_cursorPosition + text.GetLength()); SetCursorPosition(m_cursorGlyph + text.GetLength());
} }
} }
@ -114,11 +115,11 @@ namespace Ndk
const Nz::String& text = m_drawer.GetText(); const Nz::String& text = m_drawer.GetText();
Nz::String newText; Nz::String newText;
if (m_cursorPosition > 0) if (m_cursorGlyph > 0)
newText.Append(text.SubString(0, text.GetCharacterPosition(m_cursorPosition) - 1)); newText.Append(text.SubString(0, text.GetCharacterPosition(m_cursorGlyph) - 1));
if (m_cursorPosition < m_drawer.GetGlyphCount()) if (m_cursorGlyph < m_drawer.GetGlyphCount())
newText.Append(text.SubString(text.GetCharacterPosition(m_cursorPosition + 1))); newText.Append(text.SubString(text.GetCharacterPosition(m_cursorGlyph + 1)));
m_drawer.SetText(newText); m_drawer.SetText(newText);
m_textSprite->Update(m_drawer); m_textSprite->Update(m_drawer);
@ -133,7 +134,7 @@ namespace Ndk
if (ignoreDefaultAction) if (ignoreDefaultAction)
break; break;
//TODO MoveCursor({0, 1});
break; break;
} }
@ -145,7 +146,7 @@ namespace Ndk
if (ignoreDefaultAction) if (ignoreDefaultAction)
break; break;
MoveCursor(-1); MoveCursor({-1, 0});
break; break;
} }
@ -157,7 +158,7 @@ namespace Ndk
if (ignoreDefaultAction) if (ignoreDefaultAction)
break; break;
MoveCursor(1); MoveCursor({1, 0});
break; break;
} }
@ -169,7 +170,7 @@ namespace Ndk
if (ignoreDefaultAction) if (ignoreDefaultAction)
break; break;
//TODO MoveCursor({0, -1});
break; break;
} }
} }
@ -221,13 +222,13 @@ namespace Ndk
const Nz::String& text = m_drawer.GetText(); const Nz::String& text = m_drawer.GetText();
Nz::String newText; Nz::String newText;
if (m_cursorPosition > 1) if (m_cursorGlyph > 1)
newText.Append(text.SubString(0, text.GetCharacterPosition(m_cursorPosition - 1) - 1)); newText.Append(text.SubString(0, text.GetCharacterPosition(m_cursorGlyph - 1) - 1));
if (m_cursorPosition < m_drawer.GetGlyphCount()) if (m_cursorGlyph < m_drawer.GetGlyphCount())
newText.Append(text.SubString(text.GetCharacterPosition(m_cursorPosition))); newText.Append(text.SubString(text.GetCharacterPosition(m_cursorGlyph)));
MoveCursor(-1); MoveCursor({-1, 0});
SetText(newText); SetText(newText);
break; break;
} }
@ -258,25 +259,15 @@ namespace Ndk
void TextAreaWidget::RefreshCursor() void TextAreaWidget::RefreshCursor()
{ {
std::size_t lineCount = m_drawer.GetLineCount(); const auto& lineInfo = m_drawer.GetLine(m_cursorPosition.y);
std::size_t line = 0U;
for (std::size_t i = line + 1; i < lineCount; ++i)
{
if (m_drawer.GetLine(i).glyphIndex > m_cursorPosition)
break;
line = i;
}
const auto& lineInfo = m_drawer.GetLine(line);
std::size_t glyphCount = m_drawer.GetGlyphCount(); std::size_t glyphCount = m_drawer.GetGlyphCount();
float position; float position;
if (glyphCount > 0 && lineInfo.glyphIndex < m_cursorPosition) if (glyphCount > 0 && lineInfo.glyphIndex < m_cursorGlyph)
{ {
const auto& glyph = m_drawer.GetGlyph(std::min(m_cursorPosition, glyphCount - 1)); const auto& glyph = m_drawer.GetGlyph(std::min(m_cursorGlyph, glyphCount - 1));
position = glyph.bounds.x; position = glyph.bounds.x;
if (m_cursorPosition >= glyphCount) if (m_cursorGlyph >= glyphCount)
position += glyph.bounds.width; position += glyph.bounds.width;
} }
else else

View File

@ -60,29 +60,51 @@ namespace Ndk
const EntityHandle& World::CreateEntity() const EntityHandle& World::CreateEntity()
{ {
EntityId id; EntityId id;
EntityBlock* entBlock;
if (!m_freeIdList.empty()) if (!m_freeIdList.empty())
{ {
// We get an identifier // We get an identifier
id = m_freeIdList.back(); id = m_freeIdList.back();
m_freeIdList.pop_back(); m_freeIdList.pop_back();
entBlock = &m_entities[id];
entBlock->handle.Reset(&entBlock->entity); //< Reset handle (as it was reset when entity got destroyed)
m_entityBlocks[id] = entBlock;
} }
else else
{ {
// We allocate a new entity // We allocate a new entity
id = static_cast<Ndk::EntityId>(m_entities.size()); id = static_cast<Ndk::EntityId>(m_entityBlocks.size());
// We can't use emplace_back due to the scope if (m_entities.capacity() > m_entities.size())
m_entities.push_back(Entity(this, id)); {
NazaraAssert(m_waitingEntities.empty(), "There should be no waiting entities if space is available in main container");
m_entities.push_back(Entity(this, id)); //< We can't use emplace_back due to the scope
entBlock = &m_entities.back();
}
else
{
// Pushing to entities would reallocate vector and thus, invalidate EntityHandles (which we don't want until world update)
// To prevent this, allocate them into a separate vector and move them at update
// For now, we are counting on m_entities grow strategy to keep allocation frequency low
m_waitingEntities.emplace_back(std::make_unique<EntityBlock>(Entity(this, id)));
entBlock = m_waitingEntities.back().get();
}
if (id >= m_entityBlocks.size())
m_entityBlocks.resize(id + 1);
m_entityBlocks[id] = entBlock;
} }
// We initialise the entity and we add it to the list of alive entities // We initialize the entity and we add it to the list of alive entities
Entity& entity = m_entities[id].entity; entBlock->entity.Create();
entity.Create();
m_aliveEntities.emplace_back(&entity); m_aliveEntities.Insert(&entBlock->entity);
m_entities[id].aliveIndex = m_aliveEntities.size() - 1;
return m_aliveEntities.back(); return entBlock->handle;
} }
/*! /*!
@ -96,8 +118,11 @@ namespace Ndk
// First, destruction of entities, then handles // First, destruction of entities, then handles
// This is made to avoid that handle warn uselessly entities before their destruction // This is made to avoid that handle warn uselessly entities before their destruction
m_entities.clear(); m_entities.clear();
m_entityBlocks.clear();
m_freeIdList.clear();
m_waitingEntities.clear();
m_aliveEntities.clear(); m_aliveEntities.Clear();
m_dirtyEntities.Clear(); m_dirtyEntities.Clear();
m_killedEntities.Clear(); m_killedEntities.Clear();
} }
@ -120,7 +145,7 @@ namespace Ndk
return EntityHandle::InvalidHandle; return EntityHandle::InvalidHandle;
} }
EntityHandle clone = CreateEntity(); const EntityHandle& clone = CreateEntity();
const Nz::Bitset<>& componentBits = original->GetComponentBits(); const Nz::Bitset<>& componentBits = original->GetComponentBits();
for (std::size_t i = componentBits.FindFirst(); i != componentBits.npos; i = componentBits.FindNext(i)) for (std::size_t i = componentBits.FindFirst(); i != componentBits.npos; i = componentBits.FindNext(i))
@ -129,41 +154,7 @@ namespace Ndk
clone->AddComponent(std::move(component)); clone->AddComponent(std::move(component));
} }
return GetEntity(clone->GetId()); return clone;
}
/*!
* \brief Kills an entity
*
* \param Pointer to the entity
*
* \remark No change is done if entity is invalid
*/
void World::KillEntity(Entity* entity)
{
if (IsEntityValid(entity))
m_killedEntities.UnboundedSet(entity->GetId(), true);
}
/*!
* \brief Gets an entity
* \return A constant reference to the modified entity
*
* \param id Identifier of the entity
*
* \remark Produces a NazaraError if entity identifier is not valid
*/
const EntityHandle& World::GetEntity(EntityId id)
{
if (IsEntityIdValid(id))
return m_aliveEntities[m_entities[id].aliveIndex];
else
{
NazaraError("Invalid ID");
return EntityHandle::InvalidHandle;
}
} }
/*! /*!
@ -177,45 +168,43 @@ namespace Ndk
if (!m_orderedSystemsUpdated) if (!m_orderedSystemsUpdated)
ReorderSystems(); ReorderSystems();
// Move waiting entities to entity list
if (!m_waitingEntities.empty())
{
constexpr std::size_t MinEntityCapacity = 10; //< We want to be able to grow maximum entity count by at least ten without going to the waiting list
m_entities.reserve(m_entities.size() + m_waitingEntities.size() + MinEntityCapacity);
for (auto& blockPtr : m_waitingEntities)
m_entities.push_back(std::move(*blockPtr));
m_waitingEntities.clear();
// Update entity blocks pointers
for (std::size_t i = 0; i < m_entities.size(); ++i)
m_entityBlocks[i] = &m_entities[i];
}
// Handle killed entities before last call // Handle killed entities before last call
for (std::size_t i = m_killedEntities.FindFirst(); i != m_killedEntities.npos; i = m_killedEntities.FindNext(i)) for (std::size_t i = m_killedEntities.FindFirst(); i != m_killedEntities.npos; i = m_killedEntities.FindNext(i))
{ {
EntityBlock& block = m_entities[i]; NazaraAssert(i < m_entityBlocks.size(), "Entity index out of range");
Entity& entity = block.entity;
NazaraAssert(entity.IsValid(), "Entity must be valid"); Entity* entity = &m_entityBlocks[i]->entity;
// Send back the identifier of the entity to the free queue
m_freeIdList.push_back(entity.GetId());
// Destruction of the entity (invalidation of handle by the same way) // Destruction of the entity (invalidation of handle by the same way)
entity.Destroy(); entity->Destroy();
// We take out the handle from the list of alive entities // Send back the identifier of the entity to the free queue
// With the idiom swap and pop m_freeIdList.push_back(entity->GetId());
NazaraAssert(block.aliveIndex < m_aliveEntities.size(), "Alive index out of range");
if (block.aliveIndex < m_aliveEntities.size() - 1) // If it's not the last handle
{
EntityHandle& lastHandle = m_aliveEntities.back();
EntityHandle& myHandle = m_aliveEntities[block.aliveIndex];
myHandle = std::move(lastHandle);
// We don't forget to update the index associated to the entity
m_entities[myHandle->GetId()].aliveIndex = block.aliveIndex;
}
m_aliveEntities.pop_back();
} }
m_killedEntities.Reset(); m_killedEntities.Reset();
// Handle of entities which need an update from the systems // Handle of entities which need an update from the systems
for (std::size_t i = m_dirtyEntities.FindFirst(); i != m_dirtyEntities.npos; i = m_dirtyEntities.FindNext(i)) for (std::size_t i = m_dirtyEntities.FindFirst(); i != m_dirtyEntities.npos; i = m_dirtyEntities.FindNext(i))
{ {
NazaraAssert(i < m_entities.size(), "Entity index out of range"); NazaraAssert(i < m_entityBlocks.size(), "Entity index out of range");
Entity* entity = &m_entities[i].entity; Entity* entity = &m_entityBlocks[i]->entity;
// Check entity validity (as it could have been reported as dirty and killed during the same iteration) // Check entity validity (as it could have been reported as dirty and killed during the same iteration)
if (!entity->IsValid()) if (!entity->IsValid())
@ -242,7 +231,7 @@ namespace Ndk
} }
else else
{ {
// No, it shouldn't, remove it if it's part of the system // No it shouldn't, remove it if it's part of the system
if (partOfSystem) if (partOfSystem)
system->RemoveEntity(entity); system->RemoveEntity(entity);
} }

View File

@ -1,6 +1,9 @@
-- This file contains special configurations values, such as directories to extern libraries (Qt) -- This file contains special configurations values, such as directories to extern libraries (Qt)
-- Editing this file is not required to use/compile the engine, as default values should be enough -- Editing this file is not required to use/compile the engine, as default values should be enough
-- Additionnal compilation options
--AdditionalCompilationOptions = "-fsanitize=address" -- Enable ASan
-- Builds Nazara extern libraries (such as lua/STB) -- Builds Nazara extern libraries (such as lua/STB)
BuildDependencies = true BuildDependencies = true
@ -13,6 +16,9 @@ Configurations = "Debug,Release" -- "Debug,Release,ReleaseWithDebug"
-- Setup additionnals install directories, separated by a semi-colon ; (library binaries will be copied there) -- Setup additionnals install directories, separated by a semi-colon ; (library binaries will be copied there)
--InstallDir = "/usr/local/lib64" --InstallDir = "/usr/local/lib64"
-- Adds a project which will recall premake with its original arguments when built (only works on Windows for now)
PremakeProject = true
-- Excludes client-only modules/tools/examples -- Excludes client-only modules/tools/examples
ServerMode = false ServerMode = false

View File

@ -5,8 +5,14 @@ ACTION.Function = function ()
print("Encoding resources ...") print("Encoding resources ...")
local startClock = os.clock() local startClock = os.clock()
local modules = os.matchdirs("../src/Nazara/*") local modules = os.matchdirs("../src/Nazara/*")
table.insert(modules, "../SDK/src/NDK")
for k, modulePath in pairs(modules) do for k, modulePath in pairs(modules) do
local moduleName = modulePath:sub(15, -1) local moduleName
if (modulePath:sub(4, 6) == "src") then
moduleName = modulePath:sub(15, -1)
else
moduleName = "SDK"
end
local files = os.matchfiles(modulePath .. "/Resources/**") local files = os.matchfiles(modulePath .. "/Resources/**")
for k, filePath in pairs(files) do for k, filePath in pairs(files) do
if (filePath:sub(-2) ~= ".h") then if (filePath:sub(-2) ~= ".h") then

View File

@ -85,7 +85,7 @@ ACTION.Function = function ()
local exeFileExt local exeFileExt
local exeFilterFunc local exeFilterFunc
if (os.is("windows")) then if (os.is("windows")) then
binFileMasks = {"**.dll"} binFileMasks = {"**.dll", "**.pdb"}
libFileMasks = {"**.lib", "**.a"} libFileMasks = {"**.lib", "**.a"}
exeFileExt = ".exe" exeFileExt = ".exe"
exeFilterFunc = function (filePath) return true end exeFilterFunc = function (filePath) return true end

View File

@ -42,7 +42,7 @@ end
function NazaraBuild:Execute() function NazaraBuild:Execute()
if (_ACTION == nil) then -- If no action is specified, the user probably only wants to know how all of this works 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 return
end end
local platformData local platformData
@ -74,7 +74,6 @@ function NazaraBuild:Execute()
includedirs("../extlibs/include") includedirs("../extlibs/include")
libdirs("../extlibs/lib/common") libdirs("../extlibs/lib/common")
location(_ACTION) location(_ACTION)
kind("StaticLib")
for k, libTable in ipairs(self.OrderedExtLibs) do for k, libTable in ipairs(self.OrderedExtLibs) do
project(libTable.Name) project(libTable.Name)
@ -129,6 +128,13 @@ function NazaraBuild:Execute()
language("C++") language("C++")
location(_ACTION) location(_ACTION)
if (self.Config["PremakeProject"] and os.is("windows")) then
local commandLine = "premake5.exe " .. table.concat(_ARGV, ' ')
project("_PremakeProject")
kind("Utility")
prebuildcommands("cd .. && " .. commandLine)
end
-- Modules -- Modules
if (_OPTIONS["united"]) then if (_OPTIONS["united"]) then
project("NazaraEngine") project("NazaraEngine")
@ -505,11 +511,47 @@ function NazaraBuild:LoadConfig()
end end
end end
local AddStringOption = function (option, name, description)
newoption({
trigger = name,
description = description
})
local str = _OPTIONS[name]
if (str) then
configTable[option] = str
end
end
AddBoolOption("BuildDependencies", "with-extlibs", "Builds the extern libraries") AddBoolOption("BuildDependencies", "with-extlibs", "Builds the extern libraries")
AddBoolOption("BuildExamples", "with-examples", "Builds the examples") AddBoolOption("BuildExamples", "with-examples", "Builds the examples")
AddBoolOption("PremakeProject", "premakeproject", "Add a PremakeProject as a shortcut to call Premake")
AddBoolOption("ServerMode", "server", "Excludes client-only modules/tools/examples") AddBoolOption("ServerMode", "server", "Excludes client-only modules/tools/examples")
AddBoolOption("UniteModules", "united", "Builds all the modules as one united library") AddBoolOption("UniteModules", "united", "Builds all the modules as one united library")
-- AdditionalCompilationOptions
do
newoption({
trigger = "compile-options",
description = "Specify additionnal compilation options to be added to every generated project."
})
configTable["AdditionalCompilationOptions"] = configTable["AdditionalCompilationOptions"] or ""
if (_OPTIONS["compile-options"] ~= nil) then
configTable["AdditionalCompilationOptions"] = configTable["AdditionalCompilationOptions"] .. ";" .. _OPTIONS["compile-options"]
end
local configs = {}
local paths = string.explode(configTable["AdditionalCompilationOptions"], ";")
for k,v in pairs(paths) do
if (#v > 0) then
table.insert(configs, v)
end
end
configTable["AdditionalCompilationOptions"] = configs
end
-- Configurations -- Configurations
do do
newoption({ newoption({
@ -792,6 +834,8 @@ function NazaraBuild:PrepareGeneric()
buildoptions("-ftree-vectorize") buildoptions("-ftree-vectorize")
filter({}) filter({})
buildoptions(self.Config["AdditionalCompilationOptions"])
end end
function NazaraBuild:PrepareMainWorkspace() function NazaraBuild:PrepareMainWorkspace()

View File

@ -3,5 +3,6 @@ MODULE.Name = "Graphics"
MODULE.Libraries = { MODULE.Libraries = {
"NazaraCore", "NazaraCore",
"NazaraUtility", "NazaraUtility",
"NazaraPlatform",
"NazaraRenderer" "NazaraRenderer"
} }

View File

@ -0,0 +1,31 @@
MODULE.Name = "Platform"
MODULE.Libraries = {
"NazaraCore",
"NazaraUtility"
}
MODULE.OsFiles.Windows = {
"../src/Nazara/Platform/Win32/**.hpp",
"../src/Nazara/Platform/Win32/**.cpp"
}
MODULE.OsFiles.Posix = {
"../src/Nazara/Platform/X11/**.hpp",
"../src/Nazara/Platform/X11/**.cpp"
}
MODULE.OsLibraries.Windows = {
"gdi32"
}
MODULE.OsLibraries.Posix = {
"X11",
"xcb",
"xcb-cursor",
"xcb-ewmh",
"xcb-icccm",
"xcb-keysyms",
"xcb-randr"
}

View File

@ -8,7 +8,8 @@ MODULE.Defines = {
MODULE.Libraries = { MODULE.Libraries = {
"NazaraCore", "NazaraCore",
"NazaraUtility" "NazaraUtility",
"NazaraPlatform"
} }
MODULE.OsFiles.Windows = { MODULE.OsFiles.Windows = {

View File

@ -5,29 +5,11 @@ MODULE.Libraries = {
"stb_image" "stb_image"
} }
MODULE.OsFiles.Windows = {
"../src/Nazara/Utility/Win32/**.hpp",
"../src/Nazara/Utility/Win32/**.cpp"
}
MODULE.OsFiles.Posix = {
"../src/Nazara/Utility/X11/**.hpp",
"../src/Nazara/Utility/X11/**.cpp"
}
MODULE.OsLibraries.Windows = { MODULE.OsLibraries.Windows = {
"freetype-s", "freetype-s"
"gdi32"
} }
MODULE.OsLibraries.Posix = { MODULE.OsLibraries.Posix = {
"freetype", "freetype"
"X11",
"xcb",
"xcb-cursor",
"xcb-ewmh",
"xcb-icccm",
"xcb-keysyms",
"xcb-randr"
} }

View File

@ -37,7 +37,8 @@ TOOL.FilesExcluded = {
"../SDK/**/*Widget*.*", "../SDK/**/*Widget*.*",
"../SDK/**/LuaBinding_Audio.*", "../SDK/**/LuaBinding_Audio.*",
"../SDK/**/LuaBinding_Graphics.*", "../SDK/**/LuaBinding_Graphics.*",
"../SDK/**/LuaBinding_Renderer.*" "../SDK/**/LuaBinding_Renderer.*",
"../SDK/**/LuaBinding_Platform.*"
} }

View File

@ -25,7 +25,7 @@ TOOL.Files = {
TOOL.FilesExcluded = { TOOL.FilesExcluded = {
"../tests/Engine/Audio/**", "../tests/Engine/Audio/**",
"../tests/Engine/Graphics/**", "../tests/Engine/Graphics/**",
"../tests/Engine/Utility/**", "../tests/Engine/Platform/**",
"../tests/SDK/NDK/Application.cpp", "../tests/SDK/NDK/Application.cpp",
"../tests/SDK/NDK/Systems/ListenerSystem.cpp", "../tests/SDK/NDK/Systems/ListenerSystem.cpp",
"../tests/SDK/NDK/Systems/RenderSystem.cpp" "../tests/SDK/NDK/Systems/RenderSystem.cpp"

View File

@ -9,5 +9,6 @@ EXAMPLE.Files = {
EXAMPLE.Libraries = { EXAMPLE.Libraries = {
"NazaraAudio", "NazaraAudio",
"NazaraCore", "NazaraCore",
"NazaraPlatform",
"NazaraUtility" "NazaraUtility"
} }

View File

@ -12,14 +12,14 @@
#include <Nazara/Core/Clock.hpp> #include <Nazara/Core/Clock.hpp>
#include <Nazara/Core/Thread.hpp> // Thread::Sleep #include <Nazara/Core/Thread.hpp> // Thread::Sleep
#include <Nazara/Math/Vector3.hpp> #include <Nazara/Math/Vector3.hpp>
#include <Nazara/Utility/Keyboard.hpp> #include <Nazara/Platform/Keyboard.hpp>
#include <Nazara/Utility/Utility.hpp> #include <Nazara/Platform/Platform.hpp>
#include <iostream> #include <iostream>
int main() int main()
{ {
// NzKeyboard nécessite l'initialisation du module Utilitaire // NzKeyboard nécessite l'initialisation du module Utilitaire
Nz::Initializer<Nz::Audio, Nz::Utility> audio; Nz::Initializer<Nz::Audio, Nz::Platform> audio;
if (!audio) if (!audio)
{ {
std::cout << "Failed to initialize audio module" << std::endl; std::cout << "Failed to initialize audio module" << std::endl;

View File

@ -16,6 +16,7 @@
#include <Nazara/Lua.hpp> // Module de scripting #include <Nazara/Lua.hpp> // Module de scripting
#include <Nazara/Graphics.hpp> // Module graphique #include <Nazara/Graphics.hpp> // Module graphique
#include <Nazara/Renderer.hpp> // Module de rendu #include <Nazara/Renderer.hpp> // Module de rendu
#include <Nazara/Network.hpp> // Module utilitaire
#include <Nazara/Utility.hpp> // Module utilitaire #include <Nazara/Utility.hpp> // Module utilitaire
#include <NDK/Application.hpp> #include <NDK/Application.hpp>
#include <NDK/Components.hpp> #include <NDK/Components.hpp>
@ -33,6 +34,7 @@ int main()
{ {
// Ndk::Application est une classe s'occupant de l'initialisation du moteur ainsi que de la gestion de beaucoup de choses // Ndk::Application est une classe s'occupant de l'initialisation du moteur ainsi que de la gestion de beaucoup de choses
Ndk::Application application; Ndk::Application application;
Nz::Initializer<Nz::Network> network;
// Nazara étant initialisé, nous pouvons créer le monde pour contenir notre scène. // Nazara étant initialisé, nous pouvons créer le monde pour contenir notre scène.
// Dans un ECS, le monde représente bien ce que son nom indique, c'est l'ensemble de ce qui existe au niveau de l'application. // Dans un ECS, le monde représente bien ce que son nom indique, c'est l'ensemble de ce qui existe au niveau de l'application.

View File

@ -12,6 +12,7 @@ EXAMPLE.Files = {
EXAMPLE.Libraries = { EXAMPLE.Libraries = {
"NazaraCore", "NazaraCore",
"NazaraPlatform",
"NazaraRenderer", "NazaraRenderer",
"NazaraUtility" "NazaraUtility"
} }

View File

@ -8,6 +8,7 @@ EXAMPLE.Files = {
EXAMPLE.Libraries = { EXAMPLE.Libraries = {
"NazaraCore", "NazaraCore",
"NazaraPlatform",
"NazaraUtility" "NazaraUtility"
} }

View File

@ -1,4 +1,5 @@
#include "LogoDemo.hpp" #include "LogoDemo.hpp"
#include <Nazara/Core/OffsetOf.hpp>
#include <Nazara/Graphics.hpp> #include <Nazara/Graphics.hpp>
#include <Nazara/Utility.hpp> #include <Nazara/Utility.hpp>
#include <NDK/Components.hpp> #include <NDK/Components.hpp>
@ -8,12 +9,22 @@
namespace namespace
{ {
const float duration = 10.f; const float duration = 10.f;
const float maxVel = 50.f; const float maxSpeed = 100.f;
const float maxMouseForce = 1000.f;
const float mouseForce = 500.f;
const float pauseTime = 3.f; const float pauseTime = 3.f;
const float startTime = 2.f; const float startTime = 2.f;
const float speed = 3.f; const float speed = 3.f;
} }
struct ParticleData
{
Nz::Color color;
Nz::Vector2f destination;
Nz::Vector2f position;
Nz::Vector2f velocity;
};
struct SpriteController : public Nz::ParticleController struct SpriteController : public Nz::ParticleController
{ {
void Apply(Nz::ParticleGroup& system, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, float elapsedTime) override void Apply(Nz::ParticleGroup& system, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, float elapsedTime) override
@ -21,15 +32,70 @@ struct SpriteController : public Nz::ParticleController
if (!enabled) if (!enabled)
return; return;
auto posPtr = mapper.GetComponentPtr<Nz::Vector3f>(Nz::ParticleComponent_Position); auto destPtr = mapper.GetComponentPtr<Nz::Vector2f>(Nz::ParticleComponent_Userdata0);
auto velPtr = mapper.GetComponentPtr<Nz::Vector3f>(Nz::ParticleComponent_Velocity); auto posPtr = mapper.GetComponentPtr<Nz::Vector2f>(Nz::ParticleComponent_Position);
auto velPtr = mapper.GetComponentPtr<Nz::Vector2f>(Nz::ParticleComponent_Velocity);
std::uniform_real_distribution<float> dis(-1.f, 1.f);
for (unsigned int i = startId; i <= endId; ++i) for (unsigned int i = startId; i <= endId; ++i)
posPtr[i] += velPtr[i] * elapsedTime * factor; {
Nz::Vector2f newVel = destPtr[i] - posPtr[i];
float length;
newVel.Normalize(&length);
float distance = SquaredDistancePointSegment(oldMousePos, actualMousePos, posPtr[i]);
if (distance < 250.f)
{
Nz::Vector2f mouseLine = actualMousePos - oldMousePos;
float mouseLength;
mouseLine.Normalize(&mouseLength);
if (mouseLength > 5.f)
{
velPtr[i] += mouseLine * std::min(mouseLength * mouseForce, maxMouseForce) * elapsedTime;
velPtr[i] += Nz::Vector2f(dis(randomGen), dis(randomGen)) * std::min(mouseLength, maxMouseForce * 0.1f);
}
}
if (length > 1.f || velPtr[i].GetSquaredLength() > Nz::IntegralPow(30.f, 2))
{
newVel *= maxSpeed;
velPtr[i] = Nz::Lerp(velPtr[i], newVel, 0.4f * elapsedTime);
posPtr[i] += velPtr[i] * elapsedTime;
}
else
{
velPtr[i] = Nz::Vector2f::Zero();
posPtr[i] = destPtr[i];
}
}
} }
static float SquaredDistancePointSegment(const Nz::Vector2f& s0, const Nz::Vector2f& s1, const Nz::Vector2f& point)
{
// http://geomalgorithms.com/a02-_lines.html
Nz::Vector2f v = s1 - s0;
Nz::Vector2f w = point - s0;
float c1 = Nz::Vector2f::DotProduct(w, v);
if (c1 <= 0.f)
return point.SquaredDistance(s0);
float c2 = Nz::Vector2f::DotProduct(v, v);
if (c2 <= c1)
return point.SquaredDistance(s1);
float b = c1 / c2;
Nz::Vector2f projPoint = s0 + b * v;
return projPoint.SquaredDistance(point);
}
std::mt19937 randomGen;
bool enabled = false; bool enabled = false;
float factor = 1.f; float factor = 1000.f;
Nz::Vector2f actualMousePos;
Nz::Vector2f oldMousePos;
}; };
@ -67,9 +133,9 @@ ParticleDemo("Logo", sharedData)
unsigned int height = m_logo.GetHeight(); unsigned int height = m_logo.GetHeight();
m_pixels.reserve(width * height); m_pixels.reserve(width * height);
for (unsigned int y = 0; y < height; ++y) for (unsigned int x = 0; x < width; ++x)
{ {
for (unsigned int x = 0; x < width; ++x) for (unsigned int y = 0; y < height; ++y)
{ {
Nz::Color color = m_logo.GetPixelColor(x, y); Nz::Color color = m_logo.GetPixelColor(x, y);
if (color.a == 0) if (color.a == 0)
@ -93,6 +159,12 @@ ParticleDemo("Logo", sharedData)
m_controller = new SpriteController; m_controller = new SpriteController;
m_renderer = new SpriteRenderer(std::move(material)); m_renderer = new SpriteRenderer(std::move(material));
m_declaration = Nz::ParticleDeclaration::New();
m_declaration->EnableComponent(Nz::ParticleComponent_Color, Nz::ComponentType_Color, NazaraOffsetOf(ParticleData, color));
m_declaration->EnableComponent(Nz::ParticleComponent_Position, Nz::ComponentType_Float2, NazaraOffsetOf(ParticleData, position));
m_declaration->EnableComponent(Nz::ParticleComponent_Userdata0, Nz::ComponentType_Float2, NazaraOffsetOf(ParticleData, destination));
m_declaration->EnableComponent(Nz::ParticleComponent_Velocity, Nz::ComponentType_Float2, NazaraOffsetOf(ParticleData, velocity));
} }
void LogoExample::Enter(Ndk::StateMachine& fsm) void LogoExample::Enter(Ndk::StateMachine& fsm)
@ -106,17 +178,20 @@ void LogoExample::Enter(Ndk::StateMachine& fsm)
m_shared.world2D->GetSystem<Ndk::RenderSystem>().SetDefaultBackground(Nz::TextureBackground::New(std::move(backgroundTexture))); m_shared.world2D->GetSystem<Ndk::RenderSystem>().SetDefaultBackground(Nz::TextureBackground::New(std::move(backgroundTexture)));
Ndk::EntityHandle particleGroupEntity = m_shared.world2D->CreateEntity(); Ndk::EntityHandle particleGroupEntity = m_shared.world2D->CreateEntity();
Ndk::ParticleGroupComponent& particleGroup = particleGroupEntity->AddComponent<Ndk::ParticleGroupComponent>(m_pixels.size(), Nz::ParticleLayout_Sprite); Ndk::ParticleGroupComponent& particleGroup = particleGroupEntity->AddComponent<Ndk::ParticleGroupComponent>(m_pixels.size(), m_declaration);
RegisterParticleGroup(particleGroupEntity); RegisterParticleGroup(particleGroupEntity);
particleGroup.AddController(m_controller); particleGroup.AddController(m_controller);
particleGroup.SetRenderer(m_renderer); particleGroup.SetRenderer(m_renderer);
m_particles = static_cast<Nz::ParticleStruct_Sprite*>(particleGroup.CreateParticles(m_pixels.size())); m_particles = particleGroup.CreateParticles(m_pixels.size());
ResetParticles(-duration * (speed / 2.f)); ResetParticles(-duration * (speed / 2.f));
m_accumulator = pauseTime + duration; m_accumulator = pauseTime + duration;
m_totalAccumulator = 0.f; m_totalAccumulator = 0.f;
SpriteController* controller = static_cast<SpriteController*>(m_controller.Get());
controller->actualMousePos = controller->oldMousePos = Nz::Vector2f(Nz::Mouse::GetPosition(*m_shared.target));
} }
void LogoExample::Leave(Ndk::StateMachine & fsm) void LogoExample::Leave(Ndk::StateMachine & fsm)
@ -136,35 +211,62 @@ bool LogoExample::Update(Ndk::StateMachine& fsm, float elapsedTime)
m_accumulator += elapsedTime; m_accumulator += elapsedTime;
SpriteController* controller = static_cast<SpriteController*>(m_controller.Get()); SpriteController* controller = static_cast<SpriteController*>(m_controller.Get());
if (m_accumulator > pauseTime + 2.f * duration) controller->enabled = (m_accumulator > pauseTime);
if (m_mouseClock.GetMilliseconds() > 1000/30)
{ {
ResetParticles(0.f); m_mouseClock.Restart();
m_accumulator = 0.f;
controller->oldMousePos = controller->actualMousePos;
controller->actualMousePos = Nz::Vector2f(Nz::Mouse::GetPosition(*m_shared.target));
} }
controller->enabled = (m_accumulator > pauseTime); if (Nz::Mouse::IsButtonPressed(Nz::Mouse::Left))
controller->factor = -speed + speed * (m_accumulator - pauseTime) / (duration); {
if (!m_hasClicked)
{
m_hasClicked = true;
std::uniform_real_distribution<float> dis(50.f, 60.f);
ParticleData* sprite = static_cast<ParticleData*>(m_particles);
for (std::size_t i = 0; i < m_pixels.size(); ++i)
{
Nz::Vector2f particleToMouse = sprite[i].position - controller->actualMousePos;
float sqDist = particleToMouse.GetSquaredLength();
if (sqDist < 10000.f)
{
float dist = std::sqrt(sqDist);
particleToMouse /= std::max(dist, 1.f);
sprite[i].velocity += particleToMouse * dis(m_shared.randomGen);
}
}
}
}
else
m_hasClicked = false;
return true; return true;
} }
void LogoExample::ResetParticles(float elapsed) void LogoExample::ResetParticles(float elapsed)
{ {
Nz::Vector2f center = {m_shared.target->GetWidth() / 2.f, m_shared.target->GetHeight() / 2.f}; unsigned int width = m_shared.target->GetWidth();
unsigned int height = m_shared.target->GetHeight();
Nz::Vector2f center = {width / 2.f, height / 2.f};
Nz::Vector2f offset = center - Nz::Vector2f(Nz::Vector2ui(m_logo.GetSize()) / 2); Nz::Vector2f offset = center - Nz::Vector2f(Nz::Vector2ui(m_logo.GetSize()) / 2);
float ratio = float(m_shared.target->GetWidth()) / m_shared.target->GetHeight(); std::uniform_real_distribution<float> disX(0.f, float(width));
std::uniform_real_distribution<float> disX(-maxVel * ratio, maxVel * ratio); std::uniform_real_distribution<float> disY(-float(height) * 0.5f, float(height) * 1.5f);
std::uniform_real_distribution<float> disY(-maxVel, maxVel);
Nz::ParticleStruct_Sprite* sprite = m_particles; ParticleData* sprite = static_cast<ParticleData*>(m_particles);
for (PixelData& data : m_pixels) for (PixelData& data : m_pixels)
{ {
sprite->color = data.color; sprite->color = data.color;
sprite->position = offset + Nz::Vector2f(data.pos); sprite->destination = offset + Nz::Vector2f(data.pos);
sprite->rotation = 0.f; sprite->position.Set(disX(m_shared.randomGen) - float(width), disY(m_shared.randomGen));
sprite->velocity.Set(disX(m_shared.randomGen), disY(m_shared.randomGen), 0.f); sprite->velocity = Nz::Vector2f::Zero();
sprite->position += sprite->velocity * elapsed;
sprite++; sprite++;
} }
} }

View File

@ -30,10 +30,13 @@ class LogoExample : public ParticleDemo
std::vector<PixelData> m_pixels; std::vector<PixelData> m_pixels;
Nz::BackgroundRef m_oldBackground; Nz::BackgroundRef m_oldBackground;
Nz::ParticleStruct_Sprite* m_particles; void* m_particles;
Nz::Clock m_mouseClock;
Nz::Image m_logo; Nz::Image m_logo;
Nz::ParticleControllerRef m_controller; Nz::ParticleControllerRef m_controller;
Nz::ParticleDeclarationRef m_declaration;
Nz::ParticleRendererRef m_renderer; Nz::ParticleRendererRef m_renderer;
bool m_hasClicked;
float m_accumulator; float m_accumulator;
float m_totalAccumulator; float m_totalAccumulator;
}; };

View File

@ -2,6 +2,7 @@
#include <Nazara/Audio/Sound.hpp> #include <Nazara/Audio/Sound.hpp>
#include <Nazara/Core/OffsetOf.hpp> #include <Nazara/Core/OffsetOf.hpp>
#include <Nazara/Graphics.hpp> #include <Nazara/Graphics.hpp>
#include <Nazara/Platform.hpp>
#include <Nazara/Utility.hpp> #include <Nazara/Utility.hpp>
#include <NDK/Components.hpp> #include <NDK/Components.hpp>
#include <NDK/Systems.hpp> #include <NDK/Systems.hpp>

Some files were not shown because too many files have changed in this diff Show More