Merge remote-tracking branch 'refs/remotes/origin/master' into gui

This commit is contained in:
Lynix 2016-11-30 13:08:08 +01:00
commit e6e4a437bd
227 changed files with 9347 additions and 4815 deletions

16
.editorconfig Normal file
View File

@ -0,0 +1,16 @@
# http://editorconfig.org/
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[*.{hpp,inl,cpp,lua}]
indent_style = tab
[*.html]
indent_size = 4
indent_style = space

5
.gitignore vendored
View File

@ -11,7 +11,6 @@ plugins/lib/*
package/* package/*
# Example files # Example files
>>>>>>> master
examples/bin/*.exe examples/bin/*.exe
examples/bin/*.pdb examples/bin/*.pdb
examples/bin/*.dll examples/bin/*.dll
@ -36,6 +35,7 @@ build/scripts/features/index.html
doc doc
# Codeblocks # Codeblocks
*.save-failed
build/**/*.cbp build/**/*.cbp
build/**/*.cbp build/**/*.cbp
build/**/*.cbTemp build/**/*.cbTemp
@ -47,6 +47,9 @@ build/**/*.workspace
# CodeLite # CodeLite
build/**/*.project build/**/*.project
# GMake
build/**/*.make
# Visual Studio # Visual Studio
build/**/*.pdb build/**/*.pdb
build/**/*.filters build/**/*.filters

View File

@ -38,7 +38,7 @@ PROJECT_NAME = "Nazara Engine"
# could be handy for archiving the generated documentation or if some version # could be handy for archiving the generated documentation or if some version
# control system is used. # control system is used.
PROJECT_NUMBER = 0.1 PROJECT_NUMBER = 0.2
# Using the PROJECT_BRIEF tag one can provide an optional one line description # Using the PROJECT_BRIEF tag one can provide an optional one line description
# for a project that appears at the top of each page and should give viewer a # for a project that appears at the top of each page and should give viewer a

View File

@ -59,7 +59,7 @@ namespace Ndk
* \param args Arguments used to create the window * \param args Arguments used to create the window
*/ */
#ifndef NDK_SERVER #ifndef NDK_SERVER
template<typename T, typename... Args> template<typename T, typename... Args>
T& Application::AddWindow(Args&&... args) T& Application::AddWindow(Args&&... args)
{ {
static_assert(std::is_base_of<Nz::Window, T>::value, "Type must inherit Window"); static_assert(std::is_base_of<Nz::Window, T>::value, "Type must inherit Window");
@ -82,7 +82,7 @@ namespace Ndk
* \param args Arguments used to create the world * \param args Arguments used to create the world
*/ */
template<typename... Args> template<typename... Args>
World& Application::AddWorld(Args&&... args) World& Application::AddWorld(Args&&... args)
{ {
m_worlds.emplace_back(std::forward<Args>(args)...); m_worlds.emplace_back(std::forward<Args>(args)...);
@ -373,9 +373,9 @@ namespace Ndk
{ {
} }
inline Application::WindowInfo::WindowInfo(std::unique_ptr<Nz::Window>&& window) : inline Application::WindowInfo::WindowInfo(std::unique_ptr<Nz::Window>&& windowPtr) :
renderTarget(nullptr), renderTarget(nullptr),
window(std::move(window)) window(std::move(windowPtr))
{ {
} }
#endif #endif

View File

@ -35,6 +35,7 @@ namespace Ndk
inline const std::vector<EntityHandle>& GetEntities() const; inline const std::vector<EntityHandle>& GetEntities() const;
inline SystemIndex GetIndex() const; inline SystemIndex GetIndex() const;
inline int GetUpdateOrder() const;
inline float GetUpdateRate() const; inline float GetUpdateRate() const;
inline World& GetWorld() const; inline World& GetWorld() const;
@ -42,6 +43,7 @@ namespace Ndk
inline bool HasEntity(const Entity* entity) const; inline bool HasEntity(const Entity* entity) const;
void SetUpdateOrder(int updateOrder);
inline void SetUpdateRate(float updatePerSecond); inline void SetUpdateRate(float updatePerSecond);
inline void Update(float elapsedTime); inline void Update(float elapsedTime);
@ -93,6 +95,7 @@ namespace Ndk
bool m_updateEnabled; bool m_updateEnabled;
float m_updateCounter; float m_updateCounter;
float m_updateRate; float m_updateRate;
int m_updateOrder;
static SystemIndex s_nextIndex; static SystemIndex s_nextIndex;
}; };

View File

@ -16,7 +16,9 @@ namespace Ndk
inline BaseSystem::BaseSystem(SystemIndex systemId) : inline BaseSystem::BaseSystem(SystemIndex systemId) :
m_systemIndex(systemId), m_systemIndex(systemId),
m_updateEnabled(true) m_world(nullptr),
m_updateEnabled(true),
m_updateOrder(0)
{ {
SetUpdateRate(30); SetUpdateRate(30);
} }
@ -33,7 +35,8 @@ namespace Ndk
m_systemIndex(system.m_systemIndex), m_systemIndex(system.m_systemIndex),
m_updateEnabled(system.m_updateEnabled), m_updateEnabled(system.m_updateEnabled),
m_updateCounter(0.f), m_updateCounter(0.f),
m_updateRate(system.m_updateRate) m_updateRate(system.m_updateRate),
m_updateOrder(system.m_updateOrder)
{ {
} }
@ -69,7 +72,18 @@ namespace Ndk
} }
/*! /*!
* \brief Gets the rate of update for the system * \brief Gets the update order of the system
* \return Update order
*
* \see SetUpdateOrder
*/
inline int BaseSystem::GetUpdateOrder() const
{
return m_updateOrder;
}
/*!
* \brief Gets the rate of update of the system
* \return Update rate * \return Update rate
*/ */

View File

@ -1,4 +1,4 @@
// This file was automatically generated on 30 Jul 2016 at 15:29:16 // This file was automatically generated
#pragma once #pragma once
@ -6,6 +6,7 @@
#define NDK_COMPONENTS_GLOBAL_HPP #define NDK_COMPONENTS_GLOBAL_HPP
#include <NDK/Components/CameraComponent.hpp> #include <NDK/Components/CameraComponent.hpp>
#include <NDK/Components/CollisionComponent2D.hpp>
#include <NDK/Components/CollisionComponent3D.hpp> #include <NDK/Components/CollisionComponent3D.hpp>
#include <NDK/Components/GraphicsComponent.hpp> #include <NDK/Components/GraphicsComponent.hpp>
#include <NDK/Components/LightComponent.hpp> #include <NDK/Components/LightComponent.hpp>
@ -13,6 +14,7 @@
#include <NDK/Components/NodeComponent.hpp> #include <NDK/Components/NodeComponent.hpp>
#include <NDK/Components/ParticleEmitterComponent.hpp> #include <NDK/Components/ParticleEmitterComponent.hpp>
#include <NDK/Components/ParticleGroupComponent.hpp> #include <NDK/Components/ParticleGroupComponent.hpp>
#include <NDK/Components/PhysicsComponent2D.hpp>
#include <NDK/Components/PhysicsComponent3D.hpp> #include <NDK/Components/PhysicsComponent3D.hpp>
#include <NDK/Components/VelocityComponent.hpp> #include <NDK/Components/VelocityComponent.hpp>

View File

@ -18,9 +18,12 @@
namespace Ndk namespace Ndk
{ {
class CameraComponent;
class Entity; class Entity;
class NDK_API CameraComponent : public Component<CameraComponent>, public Nz::AbstractViewer using CameraComponentHandle = Nz::ObjectHandle<CameraComponent>;
class NDK_API CameraComponent : public Component<CameraComponent>, public Nz::AbstractViewer, public Nz::HandledObject<CameraComponent>
{ {
public: public:
inline CameraComponent(); inline CameraComponent();
@ -51,7 +54,7 @@ namespace Ndk
float GetZNear() const override; float GetZNear() const override;
inline void SetFOV(float fov); inline void SetFOV(float fov);
inline void SetLayer(unsigned int layer); void SetLayer(unsigned int layer);
inline void SetProjectionType(Nz::ProjectionType projection); inline void SetProjectionType(Nz::ProjectionType projection);
inline void SetSize(const Nz::Vector2f& size); inline void SetSize(const Nz::Vector2f& size);
inline void SetSize(float width, float height); inline void SetSize(float width, float height);
@ -61,6 +64,8 @@ namespace Ndk
inline void SetZFar(float zFar); inline void SetZFar(float zFar);
inline void SetZNear(float zNear); inline void SetZNear(float zNear);
inline bool UpdateVisibility(std::size_t visibilityHash);
static ComponentIndex componentIndex; static ComponentIndex componentIndex;
private: private:
@ -86,6 +91,7 @@ namespace Ndk
NazaraSlot(Nz::RenderTarget, OnRenderTargetRelease, m_targetReleaseSlot); NazaraSlot(Nz::RenderTarget, OnRenderTargetRelease, m_targetReleaseSlot);
NazaraSlot(Nz::RenderTarget, OnRenderTargetSizeChange, m_targetResizeSlot); NazaraSlot(Nz::RenderTarget, OnRenderTargetSizeChange, m_targetResizeSlot);
std::size_t m_visibilityHash;
Nz::ProjectionType m_projectionType; Nz::ProjectionType m_projectionType;
mutable Nz::Frustumf m_frustum; mutable Nz::Frustumf m_frustum;
mutable Nz::Matrix4f m_projectionMatrix; mutable Nz::Matrix4f m_projectionMatrix;

View File

@ -13,6 +13,7 @@ namespace Ndk
*/ */
inline CameraComponent::CameraComponent() : inline CameraComponent::CameraComponent() :
m_visibilityHash(0U),
m_projectionType(Nz::ProjectionType_Perspective), m_projectionType(Nz::ProjectionType_Perspective),
m_targetRegion(0.f, 0.f, 1.f, 1.f), m_targetRegion(0.f, 0.f, 1.f, 1.f),
m_target(nullptr), m_target(nullptr),
@ -38,6 +39,7 @@ namespace Ndk
inline CameraComponent::CameraComponent(const CameraComponent& camera) : inline CameraComponent::CameraComponent(const CameraComponent& camera) :
Component(camera), Component(camera),
AbstractViewer(camera), AbstractViewer(camera),
m_visibilityHash(camera.m_visibilityHash),
m_projectionType(camera.m_projectionType), m_projectionType(camera.m_projectionType),
m_targetRegion(camera.m_targetRegion), m_targetRegion(camera.m_targetRegion),
m_target(nullptr), m_target(nullptr),
@ -99,7 +101,7 @@ namespace Ndk
* \brief Gets the field of view of the camera * \brief Gets the field of view of the camera
* \return Field of view of the camera * \return Field of view of the camera
*/ */
float CameraComponent::GetFOV() const inline float CameraComponent::GetFOV() const
{ {
return m_fov; return m_fov;
} }
@ -280,6 +282,26 @@ namespace Ndk
InvalidateProjectionMatrix(); InvalidateProjectionMatrix();
} }
/*!
* \brief Update the camera component visibility hash
*
* This is used with CullingList (which produce a visibility hash)
*
* \param visibilityHash New visibility hash
*
* \return True if the visibility hash is not the same as before
*/
inline bool CameraComponent::UpdateVisibility(std::size_t visibilityHash)
{
if (m_visibilityHash != visibilityHash)
{
m_visibilityHash = visibilityHash;
return true;
}
return false;
}
/*! /*!
* \brief Invalidates the frustum * \brief Invalidates the frustum
*/ */

View File

@ -0,0 +1,58 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#pragma once
#ifndef NDK_COMPONENTS_COLLISIONCOMPONENT2D_HPP
#define NDK_COMPONENTS_COLLISIONCOMPONENT2D_HPP
#include <Nazara/Physics2D/Collider2D.hpp>
#include <NDK/Component.hpp>
#include <memory>
namespace Nz
{
class RigidBody2D;
}
namespace Ndk
{
class Entity;
class NDK_API CollisionComponent2D : public Component<CollisionComponent2D>
{
friend class PhysicsSystem2D;
public:
CollisionComponent2D(Nz::Collider2DRef geom = Nz::Collider2DRef());
CollisionComponent2D(const CollisionComponent2D& collision);
~CollisionComponent2D() = default;
const Nz::Collider2DRef& GetGeom() const;
void SetGeom(Nz::Collider2DRef geom);
CollisionComponent2D& operator=(Nz::Collider2DRef geom);
CollisionComponent2D& operator=(CollisionComponent2D&& collision) = default;
static ComponentIndex componentIndex;
private:
void InitializeStaticBody();
Nz::RigidBody2D* GetStaticBody();
void OnAttached() override;
void OnComponentAttached(BaseComponent& component) override;
void OnComponentDetached(BaseComponent& component) override;
void OnDetached() override;
std::unique_ptr<Nz::RigidBody2D> m_staticBody;
Nz::Collider2DRef m_geom;
bool m_bodyUpdated;
};
}
#include <NDK/Components/CollisionComponent2D.inl>
#endif // NDK_COMPONENTS_COLLISIONCOMPONENT2D_HPP

View File

@ -0,0 +1,70 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#include <NDK/Components/CollisionComponent2D.hpp>
#include <NDK/Entity.hpp>
#include <NDK/World.hpp>
#include <NDK/Components/PhysicsComponent2D.hpp>
#include <NDK/Systems/PhysicsSystem2D.hpp>
namespace Ndk
{
/*!
* \brief Constructs a CollisionComponent2D object with a geometry
*
* \param geom Reference to a geometry symbolizing the entity
*/
inline CollisionComponent2D::CollisionComponent2D(Nz::Collider2DRef geom) :
m_geom(std::move(geom)),
m_bodyUpdated(false)
{
}
/*!
* \brief Constructs a CollisionComponent2D object by copy semantic
*
* \param collision CollisionComponent2D to copy
*/
inline CollisionComponent2D::CollisionComponent2D(const CollisionComponent2D& collision) :
m_geom(collision.m_geom),
m_bodyUpdated(false)
{
}
/*!
* \brief Gets the geometry representing the entity
* \return A constant reference to the physics geometry
*/
inline const Nz::Collider2DRef& CollisionComponent2D::GetGeom() const
{
return m_geom;
}
/*!
* \brief Assigns the geometry to this component
* \return A reference to this
*
* \param geom Reference to a geometry symbolizing the entity
*/
inline CollisionComponent2D& CollisionComponent2D::operator=(Nz::Collider2DRef geom)
{
SetGeom(geom);
return *this;
}
/*!
* \brief Gets the static body used by the entity
* \return A pointer to the entity
*/
inline Nz::RigidBody2D* CollisionComponent2D::GetStaticBody()
{
return m_staticBody.get();
}
}

View File

@ -4,8 +4,8 @@
#pragma once #pragma once
#ifndef NDK_COMPONENTS_COLLISIONCOMPONENT_HPP #ifndef NDK_COMPONENTS_COLLISIONCOMPONENT3D_HPP
#define NDK_COMPONENTS_COLLISIONCOMPONENT_HPP #define NDK_COMPONENTS_COLLISIONCOMPONENT3D_HPP
#include <Nazara/Physics3D/Collider3D.hpp> #include <Nazara/Physics3D/Collider3D.hpp>
#include <NDK/Component.hpp> #include <NDK/Component.hpp>
@ -23,7 +23,6 @@ namespace Ndk
class NDK_API CollisionComponent3D : public Component<CollisionComponent3D> class NDK_API CollisionComponent3D : public Component<CollisionComponent3D>
{ {
friend class PhysicsSystem3D; friend class PhysicsSystem3D;
friend class StaticCollisionSystem;
public: public:
CollisionComponent3D(Nz::Collider3DRef geom = Nz::Collider3DRef()); CollisionComponent3D(Nz::Collider3DRef geom = Nz::Collider3DRef());
@ -56,4 +55,4 @@ namespace Ndk
#include <NDK/Components/CollisionComponent3D.inl> #include <NDK/Components/CollisionComponent3D.inl>
#endif // NDK_COMPONENTS_COLLISIONCOMPONENT_HPP #endif // NDK_COMPONENTS_COLLISIONCOMPONENT3D_HPP

View File

@ -8,6 +8,7 @@
#ifndef NDK_COMPONENTS_GRAPHICSCOMPONENT_HPP #ifndef NDK_COMPONENTS_GRAPHICSCOMPONENT_HPP
#define NDK_COMPONENTS_GRAPHICSCOMPONENT_HPP #define NDK_COMPONENTS_GRAPHICSCOMPONENT_HPP
#include <Nazara/Graphics/CullingList.hpp>
#include <Nazara/Graphics/InstancedRenderable.hpp> #include <Nazara/Graphics/InstancedRenderable.hpp>
#include <Nazara/Utility/Node.hpp> #include <Nazara/Utility/Node.hpp>
#include <NDK/Component.hpp> #include <NDK/Component.hpp>
@ -16,6 +17,7 @@ namespace Ndk
{ {
class GraphicsComponent; class GraphicsComponent;
using GraphicsComponentCullingList = Nz::CullingList<GraphicsComponent>;
using GraphicsComponentHandle = Nz::ObjectHandle<GraphicsComponent>; using GraphicsComponentHandle = Nz::ObjectHandle<GraphicsComponent>;
class NDK_API GraphicsComponent : public Component<GraphicsComponent>, public Nz::HandledObject<GraphicsComponent> class NDK_API GraphicsComponent : public Component<GraphicsComponent>, public Nz::HandledObject<GraphicsComponent>
@ -29,10 +31,11 @@ namespace Ndk
inline GraphicsComponent(const GraphicsComponent& graphicsComponent); inline GraphicsComponent(const GraphicsComponent& graphicsComponent);
~GraphicsComponent() = default; ~GraphicsComponent() = default;
inline void AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue) const; inline void AddToCullingList(GraphicsComponentCullingList* cullingList) const;
void AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue) const;
inline void Attach(Nz::InstancedRenderableRef renderable, int renderOrder = 0); void Attach(Nz::InstancedRenderableRef renderable, int renderOrder = 0);
inline void Attach(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& localMatrix, int renderOrder = 0); void Attach(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& localMatrix, int renderOrder = 0);
inline void Clear(); inline void Clear();
@ -46,10 +49,12 @@ namespace Ndk
inline const Nz::BoundingVolumef& GetBoundingVolume() const; inline const Nz::BoundingVolumef& GetBoundingVolume() const;
inline void RemoveFromCullingList(GraphicsComponentCullingList* cullingList) const;
static ComponentIndex componentIndex; static ComponentIndex componentIndex;
private: private:
inline void InvalidateBoundingVolume(); inline void InvalidateBoundingVolume() const;
void InvalidateRenderableData(const Nz::InstancedRenderable* renderable, Nz::UInt32 flags, std::size_t index); void InvalidateRenderableData(const Nz::InstancedRenderable* renderable, Nz::UInt32 flags, std::size_t index);
inline void InvalidateRenderables(); inline void InvalidateRenderables();
inline void InvalidateTransformMatrix(); inline void InvalidateTransformMatrix();
@ -73,19 +78,20 @@ namespace Ndk
{ {
} }
Renderable(Renderable&& renderable) noexcept : Renderable(Renderable&& rhs) noexcept :
renderableInvalidationSlot(std::move(renderable.renderableInvalidationSlot)), renderableBoundingVolumeInvalidationSlot(std::move(rhs.renderableBoundingVolumeInvalidationSlot)),
renderableReleaseSlot(std::move(renderable.renderableReleaseSlot)), renderableDataInvalidationSlot(std::move(rhs.renderableDataInvalidationSlot)),
data(std::move(renderable.data)), renderableReleaseSlot(std::move(rhs.renderableReleaseSlot)),
renderable(std::move(renderable.renderable)), data(std::move(rhs.data)),
dataUpdated(renderable.dataUpdated) renderable(std::move(rhs.renderable)),
dataUpdated(rhs.dataUpdated)
{ {
} }
~Renderable() ~Renderable()
{ {
// Disconnect release slot before releasing instanced renderable reference // Disconnect release slot before releasing instanced renderable reference
renderableReleaseSlot.Disconnect(); renderableReleaseSlot.Disconnect();
} }
Renderable& operator=(Renderable&& r) noexcept Renderable& operator=(Renderable&& r) noexcept
@ -93,13 +99,15 @@ namespace Ndk
data = std::move(r.data); data = std::move(r.data);
dataUpdated = r.dataUpdated; dataUpdated = r.dataUpdated;
renderable = std::move(r.renderable); renderable = std::move(r.renderable);
renderableInvalidationSlot = std::move(r.renderableInvalidationSlot); renderableBoundingVolumeInvalidationSlot = std::move(r.renderableBoundingVolumeInvalidationSlot);
renderableDataInvalidationSlot = std::move(r.renderableDataInvalidationSlot);
renderableReleaseSlot = std::move(r.renderableReleaseSlot); renderableReleaseSlot = std::move(r.renderableReleaseSlot);
return *this; return *this;
} }
NazaraSlot(Nz::InstancedRenderable, OnInstancedRenderableInvalidateData, renderableInvalidationSlot); NazaraSlot(Nz::InstancedRenderable, OnInstancedRenderableInvalidateBoundingVolume, renderableBoundingVolumeInvalidationSlot);
NazaraSlot(Nz::InstancedRenderable, OnInstancedRenderableInvalidateData, renderableDataInvalidationSlot);
NazaraSlot(Nz::InstancedRenderable, OnInstancedRenderableRelease, renderableReleaseSlot); NazaraSlot(Nz::InstancedRenderable, OnInstancedRenderableRelease, renderableReleaseSlot);
mutable Nz::InstancedRenderable::InstanceData data; mutable Nz::InstancedRenderable::InstanceData data;
@ -107,6 +115,16 @@ namespace Ndk
mutable bool dataUpdated; mutable bool dataUpdated;
}; };
using VolumeCullingListEntry = GraphicsComponentCullingList::VolumeEntry;
struct VolumeCullingEntry
{
VolumeCullingListEntry listEntry;
NazaraSlot(GraphicsComponentCullingList, OnCullingListRelease, cullingListReleaseSlot);
};
mutable std::vector<VolumeCullingEntry> m_volumeCullingEntries;
std::vector<Renderable> m_renderables; std::vector<Renderable> m_renderables;
mutable Nz::BoundingVolumef m_boundingVolume; mutable Nz::BoundingVolumef m_boundingVolume;
mutable Nz::Matrix4f m_transformMatrix; mutable Nz::Matrix4f m_transformMatrix;
@ -118,4 +136,4 @@ namespace Ndk
#include <NDK/Components/GraphicsComponent.inl> #include <NDK/Components/GraphicsComponent.inl>
#endif // NDK_COMPONENTS_GRAPHICSCOMPONENT_HPP #endif // NDK_COMPONENTS_GRAPHICSCOMPONENT_HPP
#endif // NDK_SERVER #endif // NDK_SERVER

View File

@ -28,52 +28,12 @@ namespace Ndk
Attach(r.renderable, r.data.renderOrder); Attach(r.renderable, r.data.renderOrder);
} }
/*! inline void GraphicsComponent::AddToCullingList(GraphicsComponentCullingList* cullingList) const
* \brief Adds the renderable elements to the render queue
*
* \param renderQueue Queue to be added
*/
inline void GraphicsComponent::AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue) const
{ {
EnsureTransformMatrixUpdate(); m_volumeCullingEntries.emplace_back(VolumeCullingEntry{});
VolumeCullingEntry& entry = m_volumeCullingEntries.back();
Ndk::RenderSystem& renderSystem = m_entity->GetWorld()->GetSystem<Ndk::RenderSystem>(); entry.cullingListReleaseSlot.Connect(cullingList->OnCullingListRelease, this, &GraphicsComponent::RemoveFromCullingList);
entry.listEntry = cullingList->RegisterVolumeTest(this);
for (const Renderable& object : m_renderables)
{
if (!object.dataUpdated)
{
object.data.transformMatrix = Nz::Matrix4f::ConcatenateAffine(renderSystem.GetCoordinateSystemMatrix(), Nz::Matrix4f::ConcatenateAffine(object.data.localMatrix, m_transformMatrix));
object.renderable->UpdateData(&object.data);
object.dataUpdated = true;
}
object.renderable->AddToRenderQueue(renderQueue, object.data);
}
}
/*!
* \brief Attaches a renderable to the entity
*
* \param renderable Reference to a renderable element
* \param renderOrder Render order of the element
*/
inline void GraphicsComponent::Attach(Nz::InstancedRenderableRef renderable, int renderOrder)
{
return Attach(renderable, Nz::Matrix4f::Identity(), renderOrder);
}
inline void GraphicsComponent::Attach(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& localMatrix, int renderOrder)
{
m_renderables.emplace_back(m_transformMatrix);
Renderable& r = m_renderables.back();
r.data.localMatrix = localMatrix;
r.data.renderOrder = renderOrder;
r.renderable = std::move(renderable);
r.renderableInvalidationSlot.Connect(r.renderable->OnInstancedRenderableInvalidateData, std::bind(&GraphicsComponent::InvalidateRenderableData, this, std::placeholders::_1, std::placeholders::_2, m_renderables.size() - 1));
r.renderableReleaseSlot.Connect(r.renderable->OnInstancedRenderableRelease, this, &GraphicsComponent::Detach);
InvalidateBoundingVolume(); InvalidateBoundingVolume();
} }
@ -167,11 +127,26 @@ namespace Ndk
return m_boundingVolume; return m_boundingVolume;
} }
inline void GraphicsComponent::RemoveFromCullingList(GraphicsComponentCullingList* cullingList) const
{
for (auto it = m_volumeCullingEntries.begin(); it != m_volumeCullingEntries.end(); ++it)
{
if (it->listEntry.GetParent() == cullingList)
{
if (m_volumeCullingEntries.size() > 1)
*it = std::move(m_volumeCullingEntries.back());
m_volumeCullingEntries.pop_back();
break;
}
}
}
/*! /*!
* \brief Invalidates the bounding volume * \brief Invalidates the bounding volume
*/ */
inline void GraphicsComponent::InvalidateBoundingVolume() inline void GraphicsComponent::InvalidateBoundingVolume() const
{ {
m_boundingVolumeUpdated = false; m_boundingVolumeUpdated = false;
} }
@ -192,9 +167,9 @@ namespace Ndk
inline void GraphicsComponent::InvalidateTransformMatrix() inline void GraphicsComponent::InvalidateTransformMatrix()
{ {
m_boundingVolumeUpdated = false;
m_transformMatrixUpdated = false; m_transformMatrixUpdated = false;
InvalidateBoundingVolume();
InvalidateRenderables(); InvalidateRenderables();
} }
} }

View File

@ -0,0 +1,65 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#pragma once
#ifndef NDK_COMPONENTS_PHYSICSCOMPONENT2D_HPP
#define NDK_COMPONENTS_PHYSICSCOMPONENT2D_HPP
#include <Nazara/Physics2D/RigidBody2D.hpp>
#include <NDK/Component.hpp>
#include <memory>
namespace Ndk
{
class Entity;
class NDK_API PhysicsComponent2D : public Component<PhysicsComponent2D>
{
friend class CollisionComponent2D;
friend class PhysicsSystem2D;
public:
PhysicsComponent2D() = default;
PhysicsComponent2D(const PhysicsComponent2D& physics);
~PhysicsComponent2D() = default;
void AddForce(const Nz::Vector2f& force, Nz::CoordSys coordSys = Nz::CoordSys_Global);
void AddForce(const Nz::Vector2f& force, const Nz::Vector2f& point, Nz::CoordSys coordSys = Nz::CoordSys_Global);
void AddTorque(float torque);
Nz::Rectf GetAABB() const;
float GetAngularVelocity() const;
Nz::Vector2f GetCenterOfGravity(Nz::CoordSys coordSys = Nz::CoordSys_Local) const;
float GetMass() const;
Nz::Vector2f GetPosition() const;
float GetRotation() const;
Nz::Vector2f GetVelocity() const;
bool IsSleeping() const;
void SetAngularVelocity(float angularVelocity);
void SetMass(float mass);
void SetMassCenter(const Nz::Vector2f& center);
void SetPosition(const Nz::Vector2f& position);
void SetRotation(float rotation);
void SetVelocity(const Nz::Vector2f& velocity);
static ComponentIndex componentIndex;
private:
Nz::RigidBody2D& GetRigidBody();
void OnAttached() override;
void OnComponentAttached(BaseComponent& component) override;
void OnComponentDetached(BaseComponent& component) override;
void OnDetached() override;
std::unique_ptr<Nz::RigidBody2D> m_object;
};
}
#include <NDK/Components/PhysicsComponent2D.inl>
#endif // NDK_COMPONENTS_PHYSICSCOMPONENT2D_HPP

View File

@ -0,0 +1,284 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#include <Nazara/Core/Error.hpp>
#include "PhysicsComponent2D.hpp"
namespace Ndk
{
/*!
* \brief Constructs a PhysicsComponent2D object by copy semantic
*
* \param physics PhysicsComponent2D to copy
*/
inline PhysicsComponent2D::PhysicsComponent2D(const PhysicsComponent2D& physics)
{
// No copy of physical object (because we only create it when attached to an entity)
NazaraUnused(physics);
}
/*!
* \brief Applies a physics force to the entity
*
* \param force Force to apply on the entity
* \param coordSys System coordinates to consider
*
* \remark Produces a NazaraAssert if the physics object is invalid
*/
inline void PhysicsComponent2D::AddForce(const Nz::Vector2f& force, Nz::CoordSys coordSys)
{
NazaraAssert(m_object, "Invalid physics object");
m_object->AddForce(force, coordSys);
}
/*!
* \brief Applies a physics force to the entity
*
* \param force Force to apply on the entity
* \param point Point where to apply the force
* \param coordSys System coordinates to consider
*
* \remark Produces a NazaraAssert if the physics object is invalid
*/
inline void PhysicsComponent2D::AddForce(const Nz::Vector2f& force, const Nz::Vector2f& point, Nz::CoordSys coordSys)
{
NazaraAssert(m_object, "Invalid physics object");
m_object->AddForce(force, point, coordSys);
}
/*!
* \brief Applies a torque to the entity
*
* \param torque Torque to apply on the entity
*
* \remark Produces a NazaraAssert if the physics object is invalid
*/
inline void PhysicsComponent2D::AddTorque(float torque)
{
NazaraAssert(m_object, "Invalid physics object");
m_object->AddTorque(torque);
}
/*!
* \brief Gets the AABB of the physics object
* \return AABB of the object
*
* \remark Produces a NazaraAssert if the physics object is invalid
*/
inline Nz::Rectf PhysicsComponent2D::GetAABB() const
{
NazaraAssert(m_object, "Invalid physics object");
return m_object->GetAABB();
}
/*!
* \brief Gets the angular velocity of the physics object
* \return Angular velocity of the object
*
* \remark Produces a NazaraAssert if the physics object is invalid
*/
inline float PhysicsComponent2D::GetAngularVelocity() const
{
NazaraAssert(m_object, "Invalid physics object");
return m_object->GetAngularVelocity();
}
/*!
* \brief Gets the gravity center of the physics object
* \return Gravity center of the object
*
* \param coordSys System coordinates to consider
*
* \remark Produces a NazaraAssert if the physics object is invalid
*/
inline Nz::Vector2f PhysicsComponent2D::GetCenterOfGravity(Nz::CoordSys coordSys) const
{
NazaraAssert(m_object, "Invalid physics object");
return m_object->GetCenterOfGravity(coordSys);
}
/*!
* \brief Gets the mass of the physics object
* \return Mass of the object
*
* \remark Produces a NazaraAssert if the physics object is invalid
*/
inline float PhysicsComponent2D::GetMass() const
{
NazaraAssert(m_object, "Invalid physics object");
return m_object->GetMass();
}
/*!
* \brief Gets the position of the physics object
* \return Position of the object
*
* \remark Produces a NazaraAssert if the physics object is invalid
*/
inline Nz::Vector2f PhysicsComponent2D::GetPosition() const
{
NazaraAssert(m_object, "Invalid physics object");
return m_object->GetPosition();
}
/*!
* \brief Gets the rotation of the physics object
* \return Rotation of the object
*
* \remark Produces a NazaraAssert if the physics object is invalid
*/
inline float PhysicsComponent2D::GetRotation() const
{
NazaraAssert(m_object, "Invalid physics object");
return m_object->GetRotation();
}
/*!
* \brief Gets the velocity of the physics object
* \return Velocity of the object
*
* \remark Produces a NazaraAssert if the physics object is invalid
*/
inline Nz::Vector2f PhysicsComponent2D::GetVelocity() const
{
NazaraAssert(m_object, "Invalid physics object");
return m_object->GetVelocity();
}
/*!
* \brief Checks whether the entity is currently sleeping
* \return true If it is the case
*
* \remark Produces a NazaraAssert if the physics object is invalid
*/
inline bool PhysicsComponent2D::IsSleeping() const
{
NazaraAssert(m_object, "Invalid physics object");
return m_object->IsSleeping();
}
/*!
* \brief Sets the angular velocity of the physics object
*
* \param angularVelocity Angular velocity of the object
*
* \remark Produces a NazaraAssert if the physics object is invalid
*/
inline void PhysicsComponent2D::SetAngularVelocity(float angularVelocity)
{
NazaraAssert(m_object, "Invalid physics object");
m_object->SetAngularVelocity(angularVelocity);
}
/*!
* \brief Sets the mass of the physics object
*
* \param mass Mass of the object
*
* \remark Produces a NazaraAssert if the physics object is invalid
* \remark Produces a NazaraAssert if the mass is negative
*/
inline void PhysicsComponent2D::SetMass(float mass)
{
NazaraAssert(m_object, "Invalid physics object");
NazaraAssert(mass > 0.f, "Mass should be positive");
m_object->SetMass(mass);
}
/*!
* \brief Sets the gravity center of the physics object
*
* \param center Gravity center of the object
*
* \remark Produces a NazaraAssert if the physics object is invalid
*/
inline void PhysicsComponent2D::SetMassCenter(const Nz::Vector2f& center)
{
NazaraAssert(m_object, "Invalid physics object");
m_object->SetMassCenter(center);
}
/*!
* \brief Sets the position of the physics object
*
* \param position Position of the object
*
* \remark Produces a NazaraAssert if the physics object is invalid
*/
inline void PhysicsComponent2D::SetPosition(const Nz::Vector2f& position)
{
NazaraAssert(m_object, "Invalid physics object");
m_object->SetPosition(position);
}
/*!
* \brief Sets the rotation of the physics object
*
* \param rotation Rotation of the object
*
* \remark Produces a NazaraAssert if the physics object is invalid
*/
inline void PhysicsComponent2D::SetRotation(float rotation)
{
NazaraAssert(m_object, "Invalid physics object");
m_object->SetRotation(rotation);
}
/*!
* \brief Sets the velocity of the physics object
*
* \param velocity Velocity of the object
*
* \remark Produces a NazaraAssert if the physics object is invalid
*/
inline void PhysicsComponent2D::SetVelocity(const Nz::Vector2f& velocity)
{
NazaraAssert(m_object, "Invalid physics object");
m_object->SetVelocity(velocity);
}
/*!
* \brief Gets the underlying physics object
* \return A reference to the physics object
*/
inline Nz::RigidBody2D& PhysicsComponent2D::GetRigidBody()
{
return *m_object.get();
}
}

View File

@ -56,7 +56,7 @@ namespace Ndk
static ComponentIndex componentIndex; static ComponentIndex componentIndex;
private: private:
Nz::RigidBody3D& GetPhysObject(); Nz::RigidBody3D& GetRigidBody();
void OnAttached() override; void OnAttached() override;
void OnComponentAttached(BaseComponent& component) override; void OnComponentAttached(BaseComponent& component) override;

View File

@ -350,7 +350,7 @@ namespace Ndk
* \return A reference to the physics object * \return A reference to the physics object
*/ */
inline Nz::RigidBody3D& PhysicsComponent3D::GetPhysObject() inline Nz::RigidBody3D& PhysicsComponent3D::GetRigidBody()
{ {
return *m_object.get(); return *m_object.get();
} }

View File

@ -4,6 +4,7 @@
#pragma once #pragma once
#ifndef NDK_SERVER
#ifndef NDK_CONSOLE_HPP #ifndef NDK_CONSOLE_HPP
#define NDK_CONSOLE_HPP #define NDK_CONSOLE_HPP
@ -99,3 +100,4 @@ namespace Ndk
#include <NDK/Console.inl> #include <NDK/Console.inl>
#endif // NDK_CONSOLE_HPP #endif // NDK_CONSOLE_HPP
#endif // NDK_SERVER

View File

@ -0,0 +1,68 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#pragma once
#ifndef NDK_LUABINDING_HPP
#define NDK_LUABINDING_HPP
#include <NDK/BaseComponent.hpp>
#include <NDK/Entity.hpp>
#include <NDK/Lua/LuaBinding_Base.hpp>
#include <memory>
namespace Ndk
{
class NDK_API LuaBinding
{
friend class LuaBinding_SDK;
public:
LuaBinding();
~LuaBinding() = default;
template<typename T> void BindComponent(const Nz::String& name);
void RegisterClasses(Nz::LuaInstance& instance);
std::unique_ptr<LuaBinding_Base> core;
std::unique_ptr<LuaBinding_Base> math;
std::unique_ptr<LuaBinding_Base> network;
std::unique_ptr<LuaBinding_Base> sdk;
std::unique_ptr<LuaBinding_Base> utility;
#ifndef NDK_SERVER
std::unique_ptr<LuaBinding_Base> audio;
std::unique_ptr<LuaBinding_Base> graphics;
std::unique_ptr<LuaBinding_Base> renderer;
#endif
private:
template<typename T>
static int AddComponentOfType(Nz::LuaInstance& lua, EntityHandle& handle);
template<typename T>
static int PushComponentOfType(Nz::LuaInstance& lua, BaseComponent& component);
using AddComponentFunc = int(*)(Nz::LuaInstance&, EntityHandle&);
using GetComponentFunc = int(*)(Nz::LuaInstance&, BaseComponent&);
struct ComponentBinding
{
AddComponentFunc adder;
ComponentIndex index;
GetComponentFunc getter;
Nz::String name;
};
ComponentBinding* QueryComponentIndex(Nz::LuaInstance& lua, int argIndex = 2);
std::vector<ComponentBinding> m_componentBinding;
std::unordered_map<Nz::String, ComponentIndex> m_componentBindingByName;
};
}
#include <NDK/Lua/LuaBinding.inl>
#endif // NDK_LUABINDING_HPP

View File

@ -2,7 +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/LuaBinding.hpp> #include <NDK/Lua/LuaBinding.hpp>
namespace Ndk namespace Ndk
{ {
@ -32,18 +32,8 @@ namespace Ndk
m_componentBindingByName[name] = T::componentIndex; m_componentBindingByName[name] = T::componentIndex;
} }
/*!
* \brief Adds a component to an entity
* \return 1 in case of success
*
* \param instance Lua instance that will interact with the component
* \param handle Entity which component will be added to
*
* \remark T must be a subtype of BaseComponent
*/
template<typename T> template<typename T>
int AddComponentOfType(Nz::LuaInstance& lua, EntityHandle& handle) int LuaBinding::AddComponentOfType(Nz::LuaInstance& lua, EntityHandle& handle)
{ {
static_assert(std::is_base_of<BaseComponent, T>::value, "ComponentType must inherit BaseComponent"); static_assert(std::is_base_of<BaseComponent, T>::value, "ComponentType must inherit BaseComponent");
@ -52,18 +42,8 @@ namespace Ndk
return 1; return 1;
} }
/*!
* \brief Pushes a component
* \return 1 in case of success
*
* \param instance Lua instance that will interact with the component
* \param component Component that will be pushed
*
* \remark T must be a subtype of BaseComponent
*/
template<typename T> template<typename T>
int PushComponentOfType(Nz::LuaInstance& lua, BaseComponent& component) int LuaBinding::PushComponentOfType(Nz::LuaInstance& lua, BaseComponent& component)
{ {
static_assert(std::is_base_of<BaseComponent, T>::value, "ComponentType must inherit BaseComponent"); static_assert(std::is_base_of<BaseComponent, T>::value, "ComponentType must inherit BaseComponent");

View File

@ -0,0 +1,33 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#pragma once
#ifndef NDK_LUABINDING_AUDIO_HPP
#define NDK_LUABINDING_AUDIO_HPP
#include <Nazara/Audio/Music.hpp>
#include <Nazara/Audio/Sound.hpp>
#include <Nazara/Audio/SoundBuffer.hpp>
#include <Nazara/Audio/SoundEmitter.hpp>
#include <NDK/Lua/LuaBinding_Base.hpp>
namespace Ndk
{
class NDK_API LuaBinding_Audio : public LuaBinding_Base
{
public:
LuaBinding_Audio(LuaBinding& binding);
~LuaBinding_Audio() = default;
void Register(Nz::LuaInstance& instance) override;
Nz::LuaClass<Nz::Music> music;
Nz::LuaClass<Nz::Sound> sound;
Nz::LuaClass<Nz::SoundBufferRef> soundBuffer;
Nz::LuaClass<Nz::SoundEmitter> soundEmitter;
};
}
#endif // NDK_LUABINDING_CORE_HPP

View File

@ -0,0 +1,53 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#pragma once
#ifndef NDK_LUABINDING_BASE_HPP
#define NDK_LUABINDING_BASE_HPP
#include <Nazara/Lua/LuaClass.hpp>
#include <Nazara/Lua/LuaInstance.hpp>
#include <NDK/Prerequesites.hpp>
namespace Ndk
{
class LuaBinding;
class LuaBinding_Audio;
class LuaBinding_Core;
class LuaBinding_Graphics;
class LuaBinding_Math;
class LuaBinding_Network;
class LuaBinding_Renderer;
class LuaBinding_SDK;
class LuaBinding_Utility;
class NDK_API LuaBinding_Base
{
public:
LuaBinding_Base(LuaBinding& binding);
virtual ~LuaBinding_Base();
virtual void Register(Nz::LuaInstance& instance) = 0;
// 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> BindMath(LuaBinding& binding);
static std::unique_ptr<LuaBinding_Base> BindNetwork(LuaBinding& binding);
static std::unique_ptr<LuaBinding_Base> BindSDK(LuaBinding& binding);
static std::unique_ptr<LuaBinding_Base> BindUtility(LuaBinding& binding);
#ifndef NDK_SERVER
static std::unique_ptr<LuaBinding_Base> BindAudio(LuaBinding& binding);
static std::unique_ptr<LuaBinding_Base> BindGraphics(LuaBinding& binding);
static std::unique_ptr<LuaBinding_Base> BindRenderer(LuaBinding& binding);
#endif
protected:
LuaBinding& m_binding;
};
}
#endif // NDK_LUABINDING_BASE_HPP

View File

@ -0,0 +1,33 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#pragma once
#ifndef NDK_LUABINDING_CORE_HPP
#define NDK_LUABINDING_CORE_HPP
#include <Nazara/Core/Clock.hpp>
#include <Nazara/Core/Directory.hpp>
#include <Nazara/Core/File.hpp>
#include <Nazara/Core/Stream.hpp>
#include <NDK/Lua/LuaBinding_Base.hpp>
namespace Ndk
{
class NDK_API LuaBinding_Core : public LuaBinding_Base
{
public:
LuaBinding_Core(LuaBinding& binding);
~LuaBinding_Core() = default;
void Register(Nz::LuaInstance& instance) override;
Nz::LuaClass<Nz::Clock> clock;
Nz::LuaClass<Nz::Directory> directory;
Nz::LuaClass<Nz::File> file;
Nz::LuaClass<Nz::Stream> stream;
};
}
#endif // NDK_LUABINDING_CORE_HPP

View File

@ -0,0 +1,36 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#pragma once
#ifndef NDK_LUABINDING_GRAPHICS_HPP
#define NDK_LUABINDING_GRAPHICS_HPP
#include <Nazara/Graphics/AbstractViewer.hpp>
#include <Nazara/Graphics/InstancedRenderable.hpp>
#include <Nazara/Graphics/Material.hpp>
#include <Nazara/Graphics/Model.hpp>
#include <Nazara/Graphics/Sprite.hpp>
#include <NDK/Lua/LuaBinding_Base.hpp>
namespace Ndk
{
class NDK_API LuaBinding_Graphics : public LuaBinding_Base
{
public:
LuaBinding_Graphics(LuaBinding& binding);
~LuaBinding_Graphics() = default;
void Register(Nz::LuaInstance& instance) override;
Nz::LuaClass<Nz::AbstractViewer> abstractViewer;
Nz::LuaClass<Nz::InstancedRenderableRef> instancedRenderable;
Nz::LuaClass<Nz::MaterialRef> material;
Nz::LuaClass<Nz::ModelRef> model;
Nz::LuaClass<Nz::SpriteRef> sprite;
Nz::LuaClass<Nz::SpriteLibrary> spriteLibrary;
};
}
#endif // NDK_LUABINDING_GRAPHICS_HPP

View File

@ -0,0 +1,37 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#pragma once
#ifndef NDK_LUABINDING_MATH_HPP
#define NDK_LUABINDING_MATH_HPP
#include <Nazara/Math/EulerAngles.hpp>
#include <Nazara/Math/Matrix4.hpp>
#include <Nazara/Math/Quaternion.hpp>
#include <Nazara/Math/Rect.hpp>
#include <Nazara/Math/Vector2.hpp>
#include <Nazara/Math/Vector3.hpp>
#include <NDK/Lua/LuaBinding_Base.hpp>
namespace Ndk
{
class NDK_API LuaBinding_Math : public LuaBinding_Base
{
public:
LuaBinding_Math(LuaBinding& binding);
~LuaBinding_Math() = default;
void Register(Nz::LuaInstance& instance) override;
Nz::LuaClass<Nz::EulerAnglesd> eulerAngles;
Nz::LuaClass<Nz::Matrix4d> matrix4d;
Nz::LuaClass<Nz::Quaterniond> quaternion;
Nz::LuaClass<Nz::Rectd> rect;
Nz::LuaClass<Nz::Vector2d> vector2d;
Nz::LuaClass<Nz::Vector3d> vector3d;
};
}
#endif // NDK_LUABINDING_MATH_HPP

View File

@ -0,0 +1,29 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#pragma once
#ifndef NDK_LUABINDING_NETWORK_HPP
#define NDK_LUABINDING_NETWORK_HPP
#include <Nazara/Network/AbstractSocket.hpp>
#include <Nazara/Network/IpAddress.hpp>
#include <NDK/Lua/LuaBinding_Base.hpp>
namespace Ndk
{
class NDK_API LuaBinding_Network : public LuaBinding_Base
{
public:
LuaBinding_Network(LuaBinding& binding);
~LuaBinding_Network() = default;
void Register(Nz::LuaInstance& instance) override;
Nz::LuaClass<Nz::AbstractSocket> abstractSocket;
Nz::LuaClass<Nz::IpAddress> ipAddress;
};
}
#endif // NDK_LUABINDING_NETWORK_HPP

View File

@ -0,0 +1,29 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#pragma once
#ifndef NDK_LUABINDING_RENDERER_HPP
#define NDK_LUABINDING_RENDERER_HPP
#include <Nazara/Renderer/Texture.hpp>
#include <NDK/Lua/LuaBinding_Base.hpp>
namespace Ndk
{
class NDK_API LuaBinding_Renderer : public LuaBinding_Base
{
public:
LuaBinding_Renderer(LuaBinding& binding);
~LuaBinding_Renderer() = default;
void Register(Nz::LuaInstance& instance) override;
Nz::LuaClass<Nz::TextureRef> texture;
Nz::LuaClass<Nz::TextureLibrary> textureLibrary;
Nz::LuaClass<Nz::TextureManager> textureManager;
};
}
#endif // NDK_LUABINDING_RENDERER_HPP

View File

@ -0,0 +1,42 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#pragma once
#ifndef NDK_LUABINDING_SDK_HPP
#define NDK_LUABINDING_SDK_HPP
#include <NDK/Lua/LuaBinding_Base.hpp>
#include <NDK/Components.hpp>
#include <NDK/Console.hpp>
#include <NDK/Entity.hpp>
namespace Ndk
{
class Application;
class NDK_API LuaBinding_SDK : public LuaBinding_Base
{
public:
LuaBinding_SDK(LuaBinding& binding);
~LuaBinding_SDK() = default;
void Register(Nz::LuaInstance& instance) override;
Nz::LuaClass<Application*> application;
Nz::LuaClass<EntityHandle> entity;
Nz::LuaClass<NodeComponentHandle> nodeComponent;
Nz::LuaClass<VelocityComponentHandle> velocityComponent;
Nz::LuaClass<WorldHandle> world;
#ifndef NDK_SERVER
Nz::LuaClass<CameraComponentHandle> cameraComponent;
Nz::LuaClass<ConsoleHandle> console;
Nz::LuaClass<GraphicsComponentHandle> graphicsComponent;
#endif
};
}
#endif // NDK_LUABINDING_SDK_HPP

View File

@ -0,0 +1,34 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#pragma once
#ifndef NDK_LUABINDING_UTILITY_HPP
#define NDK_LUABINDING_UTILITY_HPP
#include <Nazara/Utility/AbstractImage.hpp>
#include <Nazara/Utility/Font.hpp>
#include <Nazara/Utility/Keyboard.hpp>
#include <Nazara/Utility/Node.hpp>
#include <NDK/Lua/LuaBinding_Base.hpp>
namespace Ndk
{
class NDK_API LuaBinding_Utility : public LuaBinding_Base
{
public:
LuaBinding_Utility(LuaBinding& binding);
~LuaBinding_Utility() = default;
void Register(Nz::LuaInstance& instance) override;
// Utility
Nz::LuaClass<Nz::AbstractImageRef> abstractImage;
Nz::LuaClass<Nz::FontRef> font;
Nz::LuaClass<Nz::Keyboard> keyboard;
Nz::LuaClass<Nz::Node> node;
};
}
#endif // NDK_LUABINDING_UTILITY_HPP

View File

@ -28,15 +28,6 @@
namespace Nz namespace Nz
{ {
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param color Resulting color
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Color* color, TypeTag<Color>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Color* color, TypeTag<Color>)
{ {
instance.CheckType(index, Nz::LuaType_Table); instance.CheckType(index, Nz::LuaType_Table);
@ -49,15 +40,6 @@ namespace Nz
return 1; return 1;
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param angles Resulting euler angles
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, EulerAnglesd* angles, TypeTag<EulerAnglesd>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, EulerAnglesd* angles, TypeTag<EulerAnglesd>)
{ {
switch (instance.GetType(index)) switch (instance.GetType(index))
@ -78,15 +60,6 @@ namespace Nz
} }
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param angles Resulting euler angles
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, EulerAnglesf* angles, TypeTag<EulerAnglesf>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, EulerAnglesf* angles, TypeTag<EulerAnglesf>)
{ {
EulerAnglesd anglesDouble; EulerAnglesd anglesDouble;
@ -96,15 +69,6 @@ namespace Nz
return ret; return ret;
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param fontRef Resulting reference to a font
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, FontRef* fontRef, TypeTag<FontRef>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, FontRef* fontRef, TypeTag<FontRef>)
{ {
*fontRef = *static_cast<FontRef*>(instance.CheckUserdata(index, "Font")); *fontRef = *static_cast<FontRef*>(instance.CheckUserdata(index, "Font"));
@ -112,15 +76,6 @@ namespace Nz
return 1; return 1;
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param params Resulting parameters for a font
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, FontParams* params, TypeTag<FontParams>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, FontParams* params, TypeTag<FontParams>)
{ {
NazaraUnused(params); NazaraUnused(params);
@ -132,14 +87,6 @@ namespace Nz
return 1; return 1;
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param params Resulting parameters for an image
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, ImageParams* params, TypeTag<ImageParams>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, ImageParams* params, TypeTag<ImageParams>)
{ {
instance.CheckType(index, Nz::LuaType_Table); instance.CheckType(index, Nz::LuaType_Table);
@ -150,15 +97,6 @@ namespace Nz
return 1; return 1;
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param address Resulting IP address
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, IpAddress* address, TypeTag<IpAddress>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, IpAddress* address, TypeTag<IpAddress>)
{ {
switch (instance.GetType(index)) switch (instance.GetType(index))
@ -173,15 +111,6 @@ namespace Nz
} }
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param quat Resulting quaternion
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Matrix4d* mat, TypeTag<Matrix4d>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Matrix4d* mat, TypeTag<Matrix4d>)
{ {
switch (instance.GetType(index)) switch (instance.GetType(index))
@ -212,55 +141,29 @@ namespace Nz
} }
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param quat Resulting quaternion
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Matrix4f* mat, TypeTag<Matrix4f>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Matrix4f* mat, TypeTag<Matrix4f>)
{ {
Matrix4d matDouble; Matrix4d matDouble = Matrix4d::Identity();
unsigned int ret = LuaImplQueryArg(instance, index, &matDouble, TypeTag<Matrix4d>()); unsigned int ret = LuaImplQueryArg(instance, index, &matDouble, TypeTag<Matrix4d>());
mat->Set(matDouble); mat->Set(matDouble);
return ret; return ret;
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param params Resulting parameters for a mesh
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MeshParams* params, TypeTag<MeshParams>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MeshParams* params, TypeTag<MeshParams>)
{ {
instance.CheckType(index, Nz::LuaType_Table); instance.CheckType(index, Nz::LuaType_Table);
params->animated = instance.CheckField<bool>("Animated", params->animated); params->animated = instance.CheckField<bool>("Animated", params->animated);
params->center = instance.CheckField<bool>("Center", params->center); params->center = instance.CheckField<bool>("Center", params->center);
params->flipUVs = instance.CheckField<bool>("FlipUVs", params->flipUVs);
params->matrix = instance.CheckField<Matrix4f>("Matrix", params->matrix); params->matrix = instance.CheckField<Matrix4f>("Matrix", params->matrix);
params->optimizeIndexBuffers = instance.CheckField<bool>("OptimizeIndexBuffers", params->optimizeIndexBuffers); params->optimizeIndexBuffers = instance.CheckField<bool>("OptimizeIndexBuffers", params->optimizeIndexBuffers);
params->texCoordOffset = instance.CheckField<Vector2f>("TexCoordOffset", params->texCoordOffset);
params->texCoordScale = instance.CheckField<Vector2f>("TexCoordScale", params->texCoordScale);
return 1; return 1;
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param quat Resulting quaternion
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Quaterniond* quat, TypeTag<Quaterniond>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Quaterniond* quat, TypeTag<Quaterniond>)
{ {
switch (instance.GetType(index)) switch (instance.GetType(index))
@ -281,15 +184,6 @@ namespace Nz
} }
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param quat Resulting quaternion
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Quaternionf* quat, TypeTag<Quaternionf>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Quaternionf* quat, TypeTag<Quaternionf>)
{ {
Quaterniond quatDouble; Quaterniond quatDouble;
@ -299,15 +193,6 @@ namespace Nz
return ret; return ret;
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param rect Resulting rectangle
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Rectd* rect, TypeTag<Rectd>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Rectd* rect, TypeTag<Rectd>)
{ {
instance.CheckType(index, LuaType_Table); instance.CheckType(index, LuaType_Table);
@ -320,15 +205,6 @@ namespace Nz
return 1; return 1;
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param rect Resulting rectangle
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Rectf* rect, TypeTag<Rectf>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Rectf* rect, TypeTag<Rectf>)
{ {
Rectd rectDouble; Rectd rectDouble;
@ -338,14 +214,14 @@ namespace Nz
return ret; return ret;
} }
/*! inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Recti* rect, TypeTag<Recti>)
* \brief Queries arguments for Lua {
* \return 1 in case of success Rectd rectDouble;
* unsigned int ret = LuaImplQueryArg(instance, index, &rectDouble, TypeTag<Rectd>());
* \param instance Lua instance to interact with
* \param index Index type rect->Set(rectDouble);
* \param rect Resulting rectangle return ret;
*/ }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Rectui* rect, TypeTag<Rectui>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Rectui* rect, TypeTag<Rectui>)
{ {
@ -356,15 +232,6 @@ namespace Nz
return ret; return ret;
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param vec Resulting vector2D
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector2d* vec, TypeTag<Vector2d>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector2d* vec, TypeTag<Vector2d>)
{ {
switch (instance.GetType(index)) switch (instance.GetType(index))
@ -386,15 +253,6 @@ namespace Nz
} }
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param vec Resulting vector2D
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector2f* vec, TypeTag<Vector2f>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector2f* vec, TypeTag<Vector2f>)
{ {
Vector2d vecDouble; Vector2d vecDouble;
@ -404,15 +262,6 @@ namespace Nz
return ret; return ret;
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param vec Resulting vector2D
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector2ui* vec, TypeTag<Vector2ui>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector2ui* vec, TypeTag<Vector2ui>)
{ {
Vector2d vecDouble; Vector2d vecDouble;
@ -422,15 +271,6 @@ namespace Nz
return ret; return ret;
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param vec Resulting vector3D
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector3d* vec, TypeTag<Vector3d>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector3d* vec, TypeTag<Vector3d>)
{ {
switch (instance.GetType(index)) switch (instance.GetType(index))
@ -452,15 +292,6 @@ namespace Nz
} }
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param vec Resulting vector3D
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector3f* vec, TypeTag<Vector3f>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector3f* vec, TypeTag<Vector3f>)
{ {
Vector3d vecDouble; Vector3d vecDouble;
@ -470,15 +301,6 @@ namespace Nz
return ret; return ret;
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param vec Resulting vector3D
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector3ui* vec, TypeTag<Vector3ui>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector3ui* vec, TypeTag<Vector3ui>)
{ {
Vector3d vecDouble; Vector3d vecDouble;
@ -488,15 +310,6 @@ namespace Nz
return ret; return ret;
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param handle Resulting entity
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Ndk::EntityHandle* handle, TypeTag<Ndk::EntityHandle>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Ndk::EntityHandle* handle, TypeTag<Ndk::EntityHandle>)
{ {
*handle = *static_cast<Ndk::EntityHandle*>(instance.CheckUserdata(index, "Entity")); *handle = *static_cast<Ndk::EntityHandle*>(instance.CheckUserdata(index, "Entity"));
@ -504,15 +317,6 @@ namespace Nz
return 1; return 1;
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param handle Resulting world
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Ndk::WorldHandle* handle, TypeTag<Ndk::WorldHandle>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Ndk::WorldHandle* handle, TypeTag<Ndk::WorldHandle>)
{ {
*handle = *static_cast<Ndk::WorldHandle*>(instance.CheckUserdata(index, "World")); *handle = *static_cast<Ndk::WorldHandle*>(instance.CheckUserdata(index, "World"));
@ -521,16 +325,6 @@ namespace Nz
} }
#ifndef NDK_SERVER #ifndef NDK_SERVER
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param renderable Resulting reference to a instanced renderable
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, InstancedRenderableRef* renderable, TypeTag<InstancedRenderableRef>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, InstancedRenderableRef* renderable, TypeTag<InstancedRenderableRef>)
{ {
if (instance.IsOfType(index, "InstancedRenderable") || if (instance.IsOfType(index, "InstancedRenderable") ||
@ -545,15 +339,6 @@ namespace Nz
return 1; return 1;
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param renderable Resulting reference to a material
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MaterialRef* materialRef, TypeTag<MaterialRef>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MaterialRef* materialRef, TypeTag<MaterialRef>)
{ {
*materialRef = *static_cast<MaterialRef*>(instance.CheckUserdata(index, "Material")); *materialRef = *static_cast<MaterialRef*>(instance.CheckUserdata(index, "Material"));
@ -561,15 +346,6 @@ namespace Nz
return 1; return 1;
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param params Resulting parameters for a material
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MaterialParams* params, TypeTag<MaterialParams>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MaterialParams* params, TypeTag<MaterialParams>)
{ {
instance.CheckType(index, Nz::LuaType_Table); instance.CheckType(index, Nz::LuaType_Table);
@ -585,15 +361,6 @@ namespace Nz
return 1; return 1;
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param params Resulting parameters for a model
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, ModelParameters* params, TypeTag<ModelParameters>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, ModelParameters* params, TypeTag<ModelParameters>)
{ {
instance.CheckType(index, Nz::LuaType_Table); instance.CheckType(index, Nz::LuaType_Table);
@ -606,15 +373,6 @@ namespace Nz
return 1; return 1;
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param params Resulting parameters for a music
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MusicParams* params, TypeTag<MusicParams>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MusicParams* params, TypeTag<MusicParams>)
{ {
instance.CheckType(index, Nz::LuaType_Table); instance.CheckType(index, Nz::LuaType_Table);
@ -624,15 +382,6 @@ namespace Nz
return 1; return 1;
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param params Resulting parameters for a sound buffer
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, SoundBufferParams* params, TypeTag<SoundBufferParams>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, SoundBufferParams* params, TypeTag<SoundBufferParams>)
{ {
instance.CheckType(index, Nz::LuaType_Table); instance.CheckType(index, Nz::LuaType_Table);
@ -642,15 +391,6 @@ namespace Nz
return 1; return 1;
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param renderable Resulting reference to a sprite
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, SpriteRef* spriteRef, TypeTag<SpriteRef>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, SpriteRef* spriteRef, TypeTag<SpriteRef>)
{ {
*spriteRef = *static_cast<SpriteRef*>(instance.CheckUserdata(index, "Sprite")); *spriteRef = *static_cast<SpriteRef*>(instance.CheckUserdata(index, "Sprite"));
@ -658,32 +398,14 @@ namespace Nz
return 1; return 1;
} }
/*!
* \brief Queries arguments for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param index Index type
* \param fontRef Resulting reference to a font
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, TextureRef* textureRef, TypeTag<TextureRef>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, TextureRef* textureRef, TypeTag<TextureRef>)
{ {
*textureRef = *static_cast<TextureRef*>(instance.CheckUserdata(index, "Texture")); *textureRef = *static_cast<TextureRef*>(instance.CheckUserdata(index, "Texture"));
return 1; return 1;
} }
#endif #endif
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param val Resulting color
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Color&& val, TypeTag<Color>) inline int LuaImplReplyVal(const LuaInstance& instance, Color&& val, TypeTag<Color>)
{ {
instance.PushTable(); instance.PushTable();
@ -695,56 +417,24 @@ namespace Nz
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param val Resulting euler angles
*/
inline int LuaImplReplyVal(const LuaInstance& instance, EulerAnglesd&& val, TypeTag<EulerAnglesd>) inline int LuaImplReplyVal(const LuaInstance& instance, EulerAnglesd&& val, TypeTag<EulerAnglesd>)
{ {
instance.PushInstance<EulerAnglesd>("EulerAngles", val); instance.PushInstance<EulerAnglesd>("EulerAngles", val);
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param val Resulting euler angles
*/
inline int LuaImplReplyVal(const LuaInstance& instance, EulerAnglesf&& val, TypeTag<EulerAnglesf>) inline int LuaImplReplyVal(const LuaInstance& instance, EulerAnglesf&& val, TypeTag<EulerAnglesf>)
{ {
instance.PushInstance<EulerAnglesd>("EulerAngles", val); instance.PushInstance<EulerAnglesd>("EulerAngles", val);
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param val Resulting reference to a font
*/
inline int LuaImplReplyVal(const LuaInstance& instance, FontRef&& val, TypeTag<FontRef>) inline int LuaImplReplyVal(const LuaInstance& instance, FontRef&& val, TypeTag<FontRef>)
{ {
instance.PushInstance<FontRef>("Font", val); instance.PushInstance<FontRef>("Font", val);
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param val Resulting size information for a font
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Font::SizeInfo&& val, TypeTag<Font::SizeInfo>) inline int LuaImplReplyVal(const LuaInstance& instance, Font::SizeInfo&& val, TypeTag<Font::SizeInfo>)
{ {
instance.PushTable(); instance.PushTable();
@ -756,14 +446,6 @@ namespace Nz
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param val Resulting ImageParams
*/
inline int LuaImplReplyVal(const LuaInstance& instance, ImageParams&& val, TypeTag<ImageParams>) inline int LuaImplReplyVal(const LuaInstance& instance, ImageParams&& val, TypeTag<ImageParams>)
{ {
instance.PushTable(0, 2); instance.PushTable(0, 2);
@ -773,111 +455,53 @@ namespace Nz
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param val Resulting IP address
*/
inline int LuaImplReplyVal(const LuaInstance& instance, IpAddress&& val, TypeTag<IpAddress>) inline int LuaImplReplyVal(const LuaInstance& instance, IpAddress&& val, TypeTag<IpAddress>)
{ {
instance.PushInstance<IpAddress>("IpAddress", val); instance.PushInstance<IpAddress>("IpAddress", val);
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param val Resulting rectangle
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Matrix4d&& val, TypeTag<Matrix4d>) inline int LuaImplReplyVal(const LuaInstance& instance, Matrix4d&& val, TypeTag<Matrix4d>)
{ {
instance.PushInstance<Matrix4d>("Matrix4", val); instance.PushInstance<Matrix4d>("Matrix4", val);
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param val Resulting rectangle
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Matrix4f&& val, TypeTag<Matrix4f>) inline int LuaImplReplyVal(const LuaInstance& instance, Matrix4f&& val, TypeTag<Matrix4f>)
{ {
instance.PushInstance<Matrix4d>("Matrix4", val); instance.PushInstance<Matrix4d>("Matrix4", val);
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param val Resulting quaternion
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Quaterniond&& val, TypeTag<Quaterniond>) inline int LuaImplReplyVal(const LuaInstance& instance, Quaterniond&& val, TypeTag<Quaterniond>)
{ {
instance.PushInstance<Quaterniond>("Quaternion", val); instance.PushInstance<Quaterniond>("Quaternion", val);
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param val Resulting quaternion
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Quaternionf&& val, TypeTag<Quaternionf>) inline int LuaImplReplyVal(const LuaInstance& instance, Quaternionf&& val, TypeTag<Quaternionf>)
{ {
instance.PushInstance<Quaterniond>("Quaternion", val); instance.PushInstance<Quaterniond>("Quaternion", val);
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param val Resulting rectangle
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Rectd&& val, TypeTag<Rectd>) inline int LuaImplReplyVal(const LuaInstance& instance, Rectd&& val, TypeTag<Rectd>)
{ {
instance.PushInstance<Rectd>("Rect", val); instance.PushInstance<Rectd>("Rect", val);
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param val Resulting rectangle
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Rectf&& val, TypeTag<Rectf>) inline int LuaImplReplyVal(const LuaInstance& instance, Rectf&& val, TypeTag<Rectf>)
{ {
instance.PushInstance<Rectd>("Rect", val); instance.PushInstance<Rectd>("Rect", val);
return 1; return 1;
} }
/*! inline int LuaImplReplyVal(const LuaInstance& instance, Recti&& val, TypeTag<Recti>)
* \brief Replies by value for Lua {
* \return 1 in case of success instance.PushInstance<Rectd>("Rect", val);
* return 1;
* \param instance Lua instance to interact with }
* \param val Resulting rectangle
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Rectui&& val, TypeTag<Rectui>) inline int LuaImplReplyVal(const LuaInstance& instance, Rectui&& val, TypeTag<Rectui>)
{ {
@ -885,182 +509,78 @@ namespace Nz
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param val Resulting vector2D
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Vector2d&& val, TypeTag<Vector2d>) inline int LuaImplReplyVal(const LuaInstance& instance, Vector2d&& val, TypeTag<Vector2d>)
{ {
instance.PushInstance<Vector2d>("Vector2", val); instance.PushInstance<Vector2d>("Vector2", val);
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param val Resulting vector2D
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Vector2f&& val, TypeTag<Vector2f>) inline int LuaImplReplyVal(const LuaInstance& instance, Vector2f&& val, TypeTag<Vector2f>)
{ {
instance.PushInstance<Vector2d>("Vector2", val); instance.PushInstance<Vector2d>("Vector2", val);
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param val Resulting vector2D
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Vector2ui&& val, TypeTag<Vector2ui>) inline int LuaImplReplyVal(const LuaInstance& instance, Vector2ui&& val, TypeTag<Vector2ui>)
{ {
instance.PushInstance<Vector2d>("Vector2", val); instance.PushInstance<Vector2d>("Vector2", val);
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param val Resulting vector3D
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Vector3d&& val, TypeTag<Vector3d>) inline int LuaImplReplyVal(const LuaInstance& instance, Vector3d&& val, TypeTag<Vector3d>)
{ {
instance.PushInstance<Vector3d>("Vector3", val); instance.PushInstance<Vector3d>("Vector3", val);
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param val Resulting vector3D
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Vector3f&& val, TypeTag<Vector3f>) inline int LuaImplReplyVal(const LuaInstance& instance, Vector3f&& val, TypeTag<Vector3f>)
{ {
instance.PushInstance<Vector3d>("Vector3", val); instance.PushInstance<Vector3d>("Vector3", val);
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param val Resulting vector3D
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Vector3ui&& val, TypeTag<Vector3ui>) inline int LuaImplReplyVal(const LuaInstance& instance, Vector3ui&& val, TypeTag<Vector3ui>)
{ {
instance.PushInstance<Vector3d>("Vector3", val); instance.PushInstance<Vector3d>("Vector3", val);
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param ptr Resulting entity
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::Entity* ptr, TypeTag<Ndk::Entity*>) inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::Entity* ptr, TypeTag<Ndk::Entity*>)
{ {
instance.PushInstance<Ndk::EntityHandle>("Entity", ptr); instance.PushInstance<Ndk::EntityHandle>("Entity", ptr);
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param ptr Resulting application
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::Application* ptr, TypeTag<Ndk::Application*>) inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::Application* ptr, TypeTag<Ndk::Application*>)
{ {
instance.PushInstance<Ndk::Application*>("Application", ptr); instance.PushInstance<Ndk::Application*>("Application", ptr);
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param handle Resulting entity
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::EntityHandle&& handle, TypeTag<Ndk::EntityHandle>) inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::EntityHandle&& handle, TypeTag<Ndk::EntityHandle>)
{ {
instance.PushInstance<Ndk::EntityHandle>("Entity", handle); instance.PushInstance<Ndk::EntityHandle>("Entity", handle);
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param handle Resulting node component
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::NodeComponentHandle&& handle, TypeTag<Ndk::NodeComponentHandle>) inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::NodeComponentHandle&& handle, TypeTag<Ndk::NodeComponentHandle>)
{ {
instance.PushInstance<Ndk::NodeComponentHandle>("NodeComponent", handle); instance.PushInstance<Ndk::NodeComponentHandle>("NodeComponent", handle);
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param handle Resulting velocity component
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::VelocityComponentHandle&& handle, TypeTag<Ndk::VelocityComponentHandle>) inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::VelocityComponentHandle&& handle, TypeTag<Ndk::VelocityComponentHandle>)
{ {
instance.PushInstance<Ndk::VelocityComponentHandle>("VelocityComponent", handle); instance.PushInstance<Ndk::VelocityComponentHandle>("VelocityComponent", handle);
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param ptr Resulting world
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::World* ptr, TypeTag<Ndk::World*>) inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::World* ptr, TypeTag<Ndk::World*>)
{ {
instance.PushInstance<Ndk::WorldHandle>("World", ptr); instance.PushInstance<Ndk::WorldHandle>("World", ptr);
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param ptr Resulting world
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::WorldHandle&& handle, TypeTag<Ndk::WorldHandle>) inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::WorldHandle&& handle, TypeTag<Ndk::WorldHandle>)
{ {
instance.PushInstance<Ndk::WorldHandle>("World", handle); instance.PushInstance<Ndk::WorldHandle>("World", handle);
@ -1068,70 +588,35 @@ namespace Nz
} }
#ifndef NDK_SERVER #ifndef NDK_SERVER
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param handle Resulting material
*/
inline int LuaImplReplyVal(const LuaInstance& instance, MaterialRef&& handle, TypeTag<MaterialRef>) inline int LuaImplReplyVal(const LuaInstance& instance, MaterialRef&& handle, TypeTag<MaterialRef>)
{ {
instance.PushInstance<MaterialRef>("Material", handle); instance.PushInstance<MaterialRef>("Material", handle);
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param val Resulting sound buffer
*/
inline int LuaImplReplyVal(const LuaInstance& instance, const SoundBuffer* val, TypeTag<const SoundBuffer*>) inline int LuaImplReplyVal(const LuaInstance& instance, const SoundBuffer* val, TypeTag<const SoundBuffer*>)
{ {
instance.PushInstance<SoundBufferConstRef>("SoundBuffer", val); instance.PushInstance<SoundBufferConstRef>("SoundBuffer", val);
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param handle Resulting sprite
*/
inline int LuaImplReplyVal(const LuaInstance& instance, SpriteRef&& handle, TypeTag<SpriteRef>) inline int LuaImplReplyVal(const LuaInstance& instance, SpriteRef&& handle, TypeTag<SpriteRef>)
{ {
instance.PushInstance<SpriteRef>("Sprite", handle); instance.PushInstance<SpriteRef>("Sprite", handle);
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param handle Resulting texture
*/
inline int LuaImplReplyVal(const LuaInstance& instance, TextureRef&& handle, TypeTag<TextureRef>) inline int LuaImplReplyVal(const LuaInstance& instance, TextureRef&& handle, TypeTag<TextureRef>)
{ {
instance.PushInstance<TextureRef>("Texture", handle); instance.PushInstance<TextureRef>("Texture", handle);
return 1; return 1;
} }
/*! inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::CameraComponentHandle&& handle, TypeTag<Ndk::CameraComponentHandle>)
* \brief Replies by value for Lua {
* \return 1 in case of success instance.PushInstance<Ndk::CameraComponentHandle>("CameraComponent", handle);
* return 1;
* \param instance Lua instance to interact with }
* \param handle Resulting console
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::ConsoleHandle&& handle, TypeTag<Ndk::ConsoleHandle>) inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::ConsoleHandle&& handle, TypeTag<Ndk::ConsoleHandle>)
{ {
@ -1139,14 +624,6 @@ namespace Nz
return 1; return 1;
} }
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param handle Resulting graphics component
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::GraphicsComponentHandle&& handle, TypeTag<Ndk::GraphicsComponentHandle>) inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::GraphicsComponentHandle&& handle, TypeTag<Ndk::GraphicsComponentHandle>)
{ {
instance.PushInstance<Ndk::GraphicsComponentHandle>("GraphicsComponent", handle); instance.PushInstance<Ndk::GraphicsComponentHandle>("GraphicsComponent", handle);

View File

@ -1,144 +0,0 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#pragma once
#ifndef NDK_LUABINDING_HPP
#define NDK_LUABINDING_HPP
#include <Nazara/Core.hpp>
#include <Nazara/Lua.hpp>
#include <Nazara/Math.hpp>
#include <Nazara/Network.hpp>
#include <Nazara/Utility.hpp>
#include <NDK/Application.hpp>
#include <NDK/Components.hpp>
#include <NDK/Entity.hpp>
#include <NDK/Systems.hpp>
#include <NDK/World.hpp>
#ifndef NDK_SERVER
#include <Nazara/Audio.hpp>
#include <Nazara/Graphics.hpp>
#include <Nazara/Renderer.hpp>
#include <NDK/Console.hpp>
#endif
namespace Ndk
{
class NDK_API LuaBinding
{
public:
LuaBinding();
~LuaBinding() = default;
template<typename T> void BindComponent(const Nz::String& name);
void RegisterClasses(Nz::LuaInstance& instance);
// Core
Nz::LuaClass<Nz::Clock> clock;
Nz::LuaClass<Nz::Directory> directory;
Nz::LuaClass<Nz::File> file;
Nz::LuaClass<Nz::Stream> stream;
// Math
Nz::LuaClass<Nz::EulerAnglesd> eulerAngles;
Nz::LuaClass<Nz::Matrix4d> matrix4d;
Nz::LuaClass<Nz::Quaterniond> quaternion;
Nz::LuaClass<Nz::Rectd> rect;
Nz::LuaClass<Nz::Vector2d> vector2d;
Nz::LuaClass<Nz::Vector3d> vector3d;
// Network
Nz::LuaClass<Nz::AbstractSocket> abstractSocket;
Nz::LuaClass<Nz::IpAddress> ipAddress;
// Utility
Nz::LuaClass<Nz::AbstractImageRef> abstractImage;
Nz::LuaClass<Nz::FontRef> font;
Nz::LuaClass<Nz::Node> node;
// SDK
Nz::LuaClass<Application*> application;
Nz::LuaClass<EntityHandle> entity;
Nz::LuaClass<NodeComponentHandle> nodeComponent;
Nz::LuaClass<VelocityComponentHandle> velocityComponent;
Nz::LuaClass<WorldHandle> world;
#ifndef NDK_SERVER
// Audio
Nz::LuaClass<Nz::Music> music;
Nz::LuaClass<Nz::Sound> sound;
Nz::LuaClass<Nz::SoundBufferRef> soundBuffer;
Nz::LuaClass<Nz::SoundEmitter> soundEmitter;
// Graphics
Nz::LuaClass<Nz::InstancedRenderableRef> instancedRenderable;
Nz::LuaClass<Nz::MaterialRef> material;
Nz::LuaClass<Nz::ModelRef> model;
Nz::LuaClass<Nz::SpriteRef> sprite;
Nz::LuaClass<Nz::SpriteLibrary> spriteLibrary;
Nz::LuaClass<Nz::TextureLibrary> textureLibrary;
Nz::LuaClass<Nz::TextureManager> textureManager;
// Renderer
Nz::LuaClass<Nz::TextureRef> texture;
// SDK
Nz::LuaClass<ConsoleHandle> console;
Nz::LuaClass<GraphicsComponentHandle> graphicsComponent;
#endif
private:
void BindCore();
void BindMath();
void BindNetwork();
void BindSDK();
void BindUtility();
void RegisterCore(Nz::LuaInstance& instance);
void RegisterMath(Nz::LuaInstance& instance);
void RegisterNetwork(Nz::LuaInstance& instance);
void RegisterSDK(Nz::LuaInstance& instance);
void RegisterUtility(Nz::LuaInstance& instance);
#ifndef NDK_SERVER
void BindAudio();
void BindGraphics();
void BindRenderer();
void RegisterAudio(Nz::LuaInstance& instance);
void RegisterGraphics(Nz::LuaInstance& instance);
void RegisterRenderer(Nz::LuaInstance& instance);
#endif
using AddComponentFunc = int(*)(Nz::LuaInstance&, EntityHandle&);
using GetComponentFunc = int(*)(Nz::LuaInstance&, BaseComponent&);
struct ComponentBinding
{
AddComponentFunc adder;
ComponentIndex index;
GetComponentFunc getter;
Nz::String name;
};
ComponentBinding* QueryComponentIndex(Nz::LuaInstance& lua, int argIndex = 2);
std::vector<ComponentBinding> m_componentBinding;
std::unordered_map<Nz::String, ComponentIndex> m_componentBindingByName;
};
template<typename T>
int AddComponentOfType(Nz::LuaInstance& lua, EntityHandle& handle);
template<typename T>
int PushComponentOfType(Nz::LuaInstance& lua, BaseComponent& component);
}
#include <NDK/LuaBinding.inl>
#endif // NDK_LUABINDING_HPP

View File

@ -25,11 +25,16 @@
#ifndef NDK_PREREQUESITES_HPP #ifndef NDK_PREREQUESITES_HPP
#define NDK_PREREQUESITES_HPP #define NDK_PREREQUESITES_HPP
/*!
* \defgroup NDK (NazaraSDK) Nazara Development Kit
* A library grouping every modules of Nazara into multiple higher-level features suchs as scene management (handled by an ECS), application, lua binding, etc.
*/
#include <Nazara/Prerequesites.hpp> #include <Nazara/Prerequesites.hpp>
// Importation/Exportation of the API // Importation/Exportation of the API
#if defined(NAZARA_STATIC) #if defined(NAZARA_STATIC)
#define #define NDK_API #define NDK_API
#else #else
#ifdef NDK_BUILD #ifdef NDK_BUILD
#define NDK_API NAZARA_EXPORT #define NDK_API NAZARA_EXPORT

View File

@ -1,4 +1,4 @@
// This file was automatically generated on 30 Jul 2016 at 15:29:16 // This file was automatically generated
#pragma once #pragma once
@ -7,6 +7,7 @@
#include <NDK/Systems/ListenerSystem.hpp> #include <NDK/Systems/ListenerSystem.hpp>
#include <NDK/Systems/ParticleSystem.hpp> #include <NDK/Systems/ParticleSystem.hpp>
#include <NDK/Systems/PhysicsSystem2D.hpp>
#include <NDK/Systems/PhysicsSystem3D.hpp> #include <NDK/Systems/PhysicsSystem3D.hpp>
#include <NDK/Systems/RenderSystem.hpp> #include <NDK/Systems/RenderSystem.hpp>
#include <NDK/Systems/VelocitySystem.hpp> #include <NDK/Systems/VelocitySystem.hpp>

View File

@ -0,0 +1,42 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#pragma once
#ifndef NDK_SYSTEMS_PHYSICSSYSTEM2D_HPP
#define NDK_SYSTEMS_PHYSICSSYSTEM2D_HPP
#include <Nazara/Physics2D/PhysWorld2D.hpp>
#include <NDK/EntityList.hpp>
#include <NDK/System.hpp>
#include <memory>
namespace Ndk
{
class NDK_API PhysicsSystem2D : public System<PhysicsSystem2D>
{
public:
PhysicsSystem2D();
PhysicsSystem2D(const PhysicsSystem2D& system);
~PhysicsSystem2D() = default;
Nz::PhysWorld2D& GetWorld();
const Nz::PhysWorld2D& GetWorld() const;
static SystemIndex systemIndex;
private:
void CreatePhysWorld() const;
void OnEntityValidation(Entity* entity, bool justAdded) override;
void OnUpdate(float elapsedTime) override;
EntityList m_dynamicObjects;
EntityList m_staticObjects;
mutable std::unique_ptr<Nz::PhysWorld2D> m_world; ///TODO: std::optional (Should I make a Nz::Optional class?)
};
}
#include <NDK/Systems/PhysicsSystem2D.inl>
#endif // NDK_SYSTEMS_PHYSICSSYSTEM2D_HPP

View File

@ -0,0 +1,32 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
namespace Ndk
{
/*!
* \brief Gets the physical world
* \return A reference to the physical world
*/
inline Nz::PhysWorld2D& PhysicsSystem2D::GetWorld()
{
if (!m_world)
CreatePhysWorld();
return *m_world;
}
/*!
* \brief Gets the physical world
* \return A constant reference to the physical world
*/
inline const Nz::PhysWorld2D& PhysicsSystem2D::GetWorld() const
{
if (!m_world)
CreatePhysWorld();
return *m_world;
}
}

View File

@ -9,9 +9,11 @@
#define NDK_SYSTEMS_RENDERSYSTEM_HPP #define NDK_SYSTEMS_RENDERSYSTEM_HPP
#include <Nazara/Graphics/AbstractBackground.hpp> #include <Nazara/Graphics/AbstractBackground.hpp>
#include <Nazara/Graphics/CullingList.hpp>
#include <Nazara/Graphics/DepthRenderTechnique.hpp> #include <Nazara/Graphics/DepthRenderTechnique.hpp>
#include <Nazara/Graphics/ForwardRenderTechnique.hpp> #include <Nazara/Graphics/ForwardRenderTechnique.hpp>
#include <Nazara/Renderer/RenderTexture.hpp> #include <Nazara/Renderer/RenderTexture.hpp>
#include <NDK/Components/GraphicsComponent.hpp>
#include <NDK/EntityList.hpp> #include <NDK/EntityList.hpp>
#include <NDK/System.hpp> #include <NDK/System.hpp>
#include <unordered_map> #include <unordered_map>
@ -19,8 +21,6 @@
namespace Ndk namespace Ndk
{ {
class GraphicsComponent;
class NDK_API RenderSystem : public System<RenderSystem> class NDK_API RenderSystem : public System<RenderSystem>
{ {
public: public:
@ -51,21 +51,25 @@ namespace Ndk
void OnEntityRemoved(Entity* entity) override; void OnEntityRemoved(Entity* entity) override;
void OnEntityValidation(Entity* entity, bool justAdded) override; void OnEntityValidation(Entity* entity, bool justAdded) override;
void OnUpdate(float elapsedTime) override; void OnUpdate(float elapsedTime) override;
void UpdateDirectionalShadowMaps(const Nz::AbstractViewer& viewer); void UpdateDirectionalShadowMaps(const Nz::AbstractViewer& viewer);
void UpdatePointSpotShadowMaps(); void UpdatePointSpotShadowMaps();
std::unique_ptr<Nz::AbstractRenderTechnique> m_renderTechnique; std::unique_ptr<Nz::AbstractRenderTechnique> m_renderTechnique;
std::vector<GraphicsComponentCullingList::VolumeEntry> m_volumeEntries;
EntityList m_cameras; EntityList m_cameras;
EntityList m_drawables; EntityList m_drawables;
EntityList m_directionalLights; EntityList m_directionalLights;
EntityList m_lights; EntityList m_lights;
EntityList m_pointSpotLights; EntityList m_pointSpotLights;
EntityList m_particleGroups; EntityList m_particleGroups;
GraphicsComponentCullingList m_drawableCulling;
Nz::BackgroundRef m_background; Nz::BackgroundRef m_background;
Nz::DepthRenderTechnique m_shadowTechnique; Nz::DepthRenderTechnique m_shadowTechnique;
Nz::Matrix4f m_coordinateSystemMatrix; Nz::Matrix4f m_coordinateSystemMatrix;
Nz::RenderTexture m_shadowRT; Nz::RenderTexture m_shadowRT;
bool m_coordinateSystemInvalidated; bool m_coordinateSystemInvalidated;
bool m_forceRenderQueueInvalidation;
}; };
} }

View File

@ -1,4 +1,4 @@
// This file was automatically generated on 27 Oct 2016 at 21:39:00 // This file was automatically generated
#pragma once #pragma once

View File

@ -24,6 +24,7 @@ namespace Ndk
class NDK_API World : public Nz::HandledObject<World> class NDK_API World : public Nz::HandledObject<World>
{ {
friend BaseSystem;
friend Entity; friend Entity;
public: public:
@ -72,6 +73,8 @@ namespace Ndk
private: private:
inline void Invalidate(); inline void Invalidate();
inline void Invalidate(EntityId id); inline void Invalidate(EntityId id);
inline void InvalidateSystemOrder();
void ReorderSystems();
struct EntityBlock struct EntityBlock
{ {
@ -83,15 +86,17 @@ namespace Ndk
EntityBlock(EntityBlock&& block) = default; EntityBlock(EntityBlock&& block) = default;
Entity entity; Entity entity;
unsigned int aliveIndex; std::size_t aliveIndex;
}; };
std::vector<std::unique_ptr<BaseSystem>> m_systems; std::vector<std::unique_ptr<BaseSystem>> m_systems;
std::vector<BaseSystem*> m_orderedSystems;
std::vector<EntityBlock> m_entities; std::vector<EntityBlock> m_entities;
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;
Nz::Bitset<Nz::UInt64> m_killedEntities; Nz::Bitset<Nz::UInt64> m_killedEntities;
bool m_orderedSystemsUpdated;
}; };
} }

View File

@ -53,6 +53,7 @@ namespace Ndk
m_systems[index]->SetWorld(this); m_systems[index]->SetWorld(this);
Invalidate(); // We force an update for every entities Invalidate(); // We force an update for every entities
InvalidateSystemOrder(); // And regenerate the system update list
return *m_systems[index].get(); return *m_systems[index].get();
} }
@ -206,6 +207,8 @@ namespace Ndk
inline void World::RemoveAllSystems() inline void World::RemoveAllSystems()
{ {
m_systems.clear(); m_systems.clear();
InvalidateSystemOrder();
} }
/*! /*!
@ -219,7 +222,11 @@ namespace Ndk
inline void World::RemoveSystem(SystemIndex index) inline void World::RemoveSystem(SystemIndex index)
{ {
if (HasSystem(index)) if (HasSystem(index))
{
m_systems[index].reset(); m_systems[index].reset();
InvalidateSystemOrder();
}
} }
/*! /*!
@ -246,32 +253,8 @@ namespace Ndk
Update(); //< Update entities Update(); //< Update entities
// And then update systems // And then update systems
for (auto& systemPtr : m_systems) for (auto& systemPtr : m_orderedSystems)
{ systemPtr->Update(elapsedTime);
if (systemPtr)
systemPtr->Update(elapsedTime);
}
}
/*!
* \brief Invalidates each entity in the world
*/
inline void World::Invalidate()
{
m_dirtyEntities.Resize(m_entities.size(), false);
m_dirtyEntities.Set(true); // Activation of all bits
}
/*!
* \brief Invalidates an entity in the world
*
* \param id Identifier of the entity
*/
inline void World::Invalidate(EntityId id)
{
m_dirtyEntities.UnboundedSet(id, true);
} }
/*! /*!
@ -281,10 +264,12 @@ namespace Ndk
inline World& World::operator=(World&& world) noexcept inline World& World::operator=(World&& world) noexcept
{ {
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_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_orderedSystemsUpdated = world.m_orderedSystemsUpdated;
m_entities = std::move(world.m_entities); m_entities = std::move(world.m_entities);
for (EntityBlock& block : m_entities) for (EntityBlock& block : m_entities)
@ -296,4 +281,20 @@ namespace Ndk
return *this; return *this;
} }
inline void World::Invalidate()
{
m_dirtyEntities.Resize(m_entities.size(), false);
m_dirtyEntities.Set(true); // Activation of all bits
}
inline void World::Invalidate(EntityId id)
{
m_dirtyEntities.UnboundedSet(id, true);
}
inline void World::InvalidateSystemOrder()
{
m_orderedSystemsUpdated = false;
}
} }

View File

@ -152,7 +152,7 @@ namespace Ndk
windowDimensions.MakeZero(); windowDimensions.MakeZero();
overlay->console = std::make_unique<Console>(*info.overlayWorld, Nz::Vector2f(windowDimensions), overlay->lua); overlay->console = std::make_unique<Console>(*info.overlayWorld, Nz::Vector2f(windowDimensions), overlay->lua);
Console& consoleRef = *overlay->console; Console& consoleRef = *overlay->console;
// Redirect logs toward the console // Redirect logs toward the console
@ -248,4 +248,4 @@ namespace Ndk
#endif #endif
Application* Application::s_application = nullptr; Application* Application::s_application = nullptr;
} }

View File

@ -3,6 +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/BaseSystem.hpp> #include <NDK/BaseSystem.hpp>
#include <NDK/World.hpp>
namespace Ndk namespace Ndk
{ {
@ -56,6 +57,26 @@ namespace Ndk
return true; return true;
} }
/*!
* \brief Sets the update order of this system
*
* The system update order is used by the world it belongs to in order to know in which order they should be updated, as some application logic may rely a specific update order.
* A system with a greater update order (ex: 1) is guaranteed to be updated after a system with a lesser update order (ex: -1), otherwise the order is unspecified (and is not guaranteed to be stable).
*
* \param updateOrder The relative update order of the system
*
* \remark The update order is only used by World::Update(float) and does not have any effect regarding a call to BaseSystem::Update(float)
*
* \see GetUpdateOrder
*/
void BaseSystem::SetUpdateOrder(int updateOrder)
{
m_updateOrder = updateOrder;
if (m_world)
m_world->InvalidateSystemOrder();
}
/*! /*!
* \brief Operation to perform when entity is added to the system * \brief Operation to perform when entity is added to the system
* *

View File

@ -141,6 +141,7 @@ namespace Ndk
{ {
return m_zNear; return m_zNear;
} }
/*! /*!
* \brief Sets the layer of the camera in case of multiples fields * \brief Sets the layer of the camera in case of multiples fields
* *

View File

@ -0,0 +1,118 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#include <NDK/Components/CollisionComponent2D.hpp>
#include <Nazara/Physics2D/RigidBody2D.hpp>
#include <NDK/Algorithm.hpp>
#include <NDK/World.hpp>
#include <NDK/Components/NodeComponent.hpp>
#include <NDK/Components/PhysicsComponent2D.hpp>
#include <NDK/Systems/PhysicsSystem2D.hpp>
namespace Ndk
{
/*!
* \ingroup NDK
* \class Ndk::CollisionComponent2D
* \brief NDK class that represents a two-dimensional collision geometry
*/
/*!
* \brief Sets geometry for the entity
*
* \param geom Geometry used for collisions
*
* \remark Produces a NazaraAssert if the entity has no physics component and has no static body
*/
void CollisionComponent2D::SetGeom(Nz::Collider2DRef geom)
{
m_geom = std::move(geom);
if (m_entity->HasComponent<PhysicsComponent2D>())
{
// We update the geometry of the PhysiscsObject linked to the PhysicsComponent2D
PhysicsComponent2D& physComponent = m_entity->GetComponent<PhysicsComponent2D>();
physComponent.GetRigidBody().SetGeom(m_geom);
}
else
{
NazaraAssert(m_staticBody, "An entity without physics component should have a static body");
m_staticBody->SetGeom(m_geom);
}
}
/*!
* \brief Initializes the static body
*
* \remark Produces a NazaraAssert if entity is invalid
* \remark Produces a NazaraAssert if entity is not linked to a world, or the world has no physics system
*/
void CollisionComponent2D::InitializeStaticBody()
{
NazaraAssert(m_entity, "Invalid entity");
World* entityWorld = m_entity->GetWorld();
NazaraAssert(entityWorld, "Entity must have world");
NazaraAssert(entityWorld->HasSystem<PhysicsSystem2D>(), "World must have a physics system");
Nz::PhysWorld2D& physWorld = entityWorld->GetSystem<PhysicsSystem2D>().GetWorld();
m_staticBody.reset(new Nz::RigidBody2D(&physWorld, 0.f, m_geom));
Nz::Matrix4f matrix;
if (m_entity->HasComponent<NodeComponent>())
matrix = m_entity->GetComponent<NodeComponent>().GetTransformMatrix();
else
matrix.MakeIdentity();
m_staticBody->SetPosition(Nz::Vector2f(matrix.GetTranslation()));
}
/*!
* \brief Operation to perform when component is attached to an entity
*/
void CollisionComponent2D::OnAttached()
{
if (!m_entity->HasComponent<PhysicsComponent2D>())
InitializeStaticBody();
}
/*!
* \brief Operation to perform when component is attached to this component
*
* \param component Component being attached
*/
void CollisionComponent2D::OnComponentAttached(BaseComponent& component)
{
if (IsComponent<PhysicsComponent2D>(component))
m_staticBody.reset();
}
/*!
* \brief Operation to perform when component is detached from this component
*
* \param component Component being detached
*/
void CollisionComponent2D::OnComponentDetached(BaseComponent& component)
{
if (IsComponent<PhysicsComponent2D>(component))
InitializeStaticBody();
}
/*!
* \brief Operation to perform when component is detached from an entity
*/
void CollisionComponent2D::OnDetached()
{
m_staticBody.reset();
}
ComponentIndex CollisionComponent2D::componentIndex;
}

View File

@ -33,7 +33,7 @@ namespace Ndk
{ {
// We update the geometry of the PhysiscsObject linked to the PhysicsComponent3D // We update the geometry of the PhysiscsObject linked to the PhysicsComponent3D
PhysicsComponent3D& physComponent = m_entity->GetComponent<PhysicsComponent3D>(); PhysicsComponent3D& physComponent = m_entity->GetComponent<PhysicsComponent3D>();
physComponent.GetPhysObject().SetGeom(m_geom); physComponent.GetRigidBody().SetGeom(m_geom);
} }
else else
{ {

View File

@ -15,6 +15,62 @@ namespace Ndk
* \brief NDK class that represents the component for graphics * \brief NDK class that represents the component for graphics
*/ */
/*!
* \brief Adds the renderable elements to the render queue
*
* \param renderQueue Queue to be added
*/
void GraphicsComponent::AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue) const
{
EnsureTransformMatrixUpdate();
RenderSystem& renderSystem = m_entity->GetWorld()->GetSystem<RenderSystem>();
for (const Renderable& object : m_renderables)
{
if (!object.dataUpdated)
{
object.data.transformMatrix = Nz::Matrix4f::ConcatenateAffine(renderSystem.GetCoordinateSystemMatrix(), Nz::Matrix4f::ConcatenateAffine(object.data.localMatrix, m_transformMatrix));
object.renderable->UpdateData(&object.data);
object.dataUpdated = true;
}
object.renderable->AddToRenderQueue(renderQueue, object.data);
}
}
/*!
* \brief Attaches a renderable to the entity
*
* \param renderable Reference to a renderable element
* \param renderOrder Render order of the element
*/
void GraphicsComponent::Attach(Nz::InstancedRenderableRef renderable, int renderOrder)
{
return Attach(renderable, Nz::Matrix4f::Identity(), renderOrder);
}
/*!
* \brief Attaches a renderable to the entity with a specific matrix
*
* \param renderable Reference to a renderable element
* \param localMatrix Local matrix that will be applied to the instanced renderable
* \param renderOrder Render order of the element
*/
void GraphicsComponent::Attach(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& localMatrix, int renderOrder)
{
m_renderables.emplace_back(m_transformMatrix);
Renderable& r = m_renderables.back();
r.data.localMatrix = localMatrix;
r.data.renderOrder = renderOrder;
r.renderable = std::move(renderable);
r.renderableBoundingVolumeInvalidationSlot.Connect(r.renderable->OnInstancedRenderableInvalidateBoundingVolume, [this] (const Nz::InstancedRenderable*) { InvalidateBoundingVolume(); });
r.renderableDataInvalidationSlot.Connect(r.renderable->OnInstancedRenderableInvalidateData, std::bind(&GraphicsComponent::InvalidateRenderableData, this, std::placeholders::_1, std::placeholders::_2, m_renderables.size() - 1));
r.renderableReleaseSlot.Connect(r.renderable->OnInstancedRenderableRelease, this, &GraphicsComponent::Detach);
InvalidateBoundingVolume();
}
/*! /*!
* \brief Invalidates the data for renderable * \brief Invalidates the data for renderable
* *
@ -33,6 +89,9 @@ namespace Ndk
Renderable& r = m_renderables[index]; Renderable& r = m_renderables[index];
r.dataUpdated = false; r.dataUpdated = false;
r.renderable->InvalidateData(&r.data, flags); r.renderable->InvalidateData(&r.data, flags);
for (VolumeCullingEntry& entry : m_volumeCullingEntries)
entry.listEntry.ForceInvalidation();
} }
/*! /*!
@ -102,7 +161,11 @@ namespace Ndk
NazaraUnused(node); NazaraUnused(node);
// Our view matrix depends on NodeComponent position/rotation // Our view matrix depends on NodeComponent position/rotation
InvalidateBoundingVolume();
InvalidateTransformMatrix(); InvalidateTransformMatrix();
for (VolumeCullingEntry& entry : m_volumeCullingEntries)
entry.listEntry.ForceInvalidation(); //< Force invalidation on movement
} }
/*! /*!
@ -115,10 +178,29 @@ namespace Ndk
m_boundingVolume.MakeNull(); m_boundingVolume.MakeNull();
for (const Renderable& r : m_renderables) for (const Renderable& r : m_renderables)
m_boundingVolume.ExtendTo(r.renderable->GetBoundingVolume()); {
Nz::BoundingVolumef boundingVolume = r.renderable->GetBoundingVolume();
m_boundingVolume.Update(m_transformMatrix); // Adjust renderable bounding volume by local matrix
if (boundingVolume.IsFinite())
{
Nz::Boxf localBox = boundingVolume.obb.localBox;
Nz::Vector3f newPos = r.data.localMatrix * localBox.GetPosition();
Nz::Vector3f newLengths = r.data.localMatrix * localBox.GetLengths();
boundingVolume.Set(Nz::Boxf(newPos.x, newPos.y, newPos.z, newLengths.x, newLengths.y, newLengths.z));
}
m_boundingVolume.ExtendTo(r.renderable->GetBoundingVolume());
}
RenderSystem& renderSystem = m_entity->GetWorld()->GetSystem<RenderSystem>();
m_boundingVolume.Update(Nz::Matrix4f::ConcatenateAffine(renderSystem.GetCoordinateSystemMatrix(), m_transformMatrix));
m_boundingVolumeUpdated = true; m_boundingVolumeUpdated = true;
for (VolumeCullingEntry& entry : m_volumeCullingEntries)
entry.listEntry.UpdateVolume(m_boundingVolume);
} }
/*! /*!

View File

@ -0,0 +1,92 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#include <NDK/Components/PhysicsComponent2D.hpp>
#include <Nazara/Physics2D/RigidBody2D.hpp>
#include <NDK/Algorithm.hpp>
#include <NDK/World.hpp>
#include <NDK/Components/CollisionComponent2D.hpp>
#include <NDK/Components/NodeComponent.hpp>
#include <NDK/Systems/PhysicsSystem3D.hpp>
namespace Ndk
{
/*!
* \ingroup NDK
* \class Ndk::PhysicsComponent2D
* \brief NDK class that represents a physics point, without any collision
*/
/*!
* \brief Operation to perform when component is attached to an entity
*
* \remark Produces a NazaraAssert if the world does not have a physics system
*/
void PhysicsComponent2D::OnAttached()
{
World* entityWorld = m_entity->GetWorld();
NazaraAssert(entityWorld->HasSystem<PhysicsSystem2D>(), "World must have a 2D physics system");
Nz::PhysWorld2D& world = entityWorld->GetSystem<PhysicsSystem2D>().GetWorld();
Nz::Collider2DRef geom;
if (m_entity->HasComponent<CollisionComponent2D>())
geom = m_entity->GetComponent<CollisionComponent2D>().GetGeom();
Nz::Matrix4f matrix;
if (m_entity->HasComponent<NodeComponent>())
matrix = m_entity->GetComponent<NodeComponent>().GetTransformMatrix();
else
matrix.MakeIdentity();
m_object.reset(new Nz::RigidBody2D(&world, 1.f, geom));
m_object->SetPosition(Nz::Vector2f(matrix.GetTranslation()));
}
/*!
* \brief Operation to perform when component is attached to this component
*
* \param component Component being attached
*
* \remark Produces a NazaraAssert if physical object is invalid
*/
void PhysicsComponent2D::OnComponentAttached(BaseComponent& component)
{
if (IsComponent<CollisionComponent2D>(component))
{
NazaraAssert(m_object, "Invalid object");
m_object->SetGeom(static_cast<CollisionComponent2D&>(component).GetGeom());
}
}
/*!
* \brief Operation to perform when component is detached from this component
*
* \param component Component being detached
*
* \remark Produces a NazaraAssert if physical object is invalid
*/
void PhysicsComponent2D::OnComponentDetached(BaseComponent& component)
{
if (IsComponent<CollisionComponent2D>(component))
{
NazaraAssert(m_object, "Invalid object");
m_object->SetGeom(Nz::NullCollider2D::New());
}
}
/*!
* \brief Operation to perform when component is detached from an entity
*/
void PhysicsComponent2D::OnDetached()
{
m_object.reset();
}
ComponentIndex PhysicsComponent2D::componentIndex;
}

View File

@ -167,7 +167,6 @@ namespace Ndk
* *
* \param event Event to be takin into consideration by the console * \param event Event to be takin into consideration by the console
*/ */
void Console::SendEvent(const Nz::WindowEvent& event) void Console::SendEvent(const Nz::WindowEvent& event)
{ {
switch (event.type) switch (event.type)

View File

@ -148,9 +148,11 @@ namespace Ndk
// 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))
{ {
if (m_world->HasSystem(index)) auto sysIndex = static_cast<Ndk::SystemIndex>(index);
if (m_world->HasSystem(sysIndex))
{ {
BaseSystem& system = m_world->GetSystem(index); BaseSystem& system = m_world->GetSystem(sysIndex);
system.RemoveEntity(this); system.RemoveEntity(this);
} }
} }

View File

@ -0,0 +1,66 @@
// This file was automatically generated on 26 May 2014 at 01:05:31
#include <NDK/Lua/LuaBinding.hpp>
namespace Ndk
{
/*!
* \ingroup NDK
* \class Ndk::LuaBinding
* \brief NDK class that represents the binding between the engine & the SDK with the Lua scripting
*/
/*!
* \brief Binds modules to Lua
*/
LuaBinding::LuaBinding()
{
core = LuaBinding_Base::BindCore(*this);
math = LuaBinding_Base::BindMath(*this);
network = LuaBinding_Base::BindNetwork(*this);
utility = LuaBinding_Base::BindUtility(*this);
#ifndef NDK_SERVER
audio = LuaBinding_Base::BindAudio(*this);
renderer = LuaBinding_Base::BindRenderer(*this);
graphics = LuaBinding_Base::BindGraphics(*this);
#endif
sdk = LuaBinding_Base::BindSDK(*this);
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the engine & SDK
*/
void LuaBinding::RegisterClasses(Nz::LuaInstance& instance)
{
core->Register(instance);
math->Register(instance);
network->Register(instance);
sdk->Register(instance);
utility->Register(instance);
#ifndef NDK_SERVER
audio->Register(instance);
graphics->Register(instance);
renderer->Register(instance);
#endif
// ComponentType (fake enumeration to expose component indexes)
instance.PushTable(0, m_componentBinding.size());
{
for (const ComponentBinding& entry : m_componentBinding)
{
if (entry.name.IsEmpty())
continue;
instance.PushField(entry.name, entry.index);
}
}
instance.SetGlobal("ComponentType");
}
}

View File

@ -0,0 +1,198 @@
// This file was automatically generated on 26 May 2014 at 01:05:31
#include <NDK/Lua/LuaBinding_Audio.hpp>
#include <Nazara/Core/MemoryHelper.hpp>
#include <NDK/LuaAPI.hpp>
namespace Ndk
{
std::unique_ptr<LuaBinding_Base> LuaBinding_Base::BindAudio(LuaBinding& binding)
{
return std::make_unique<LuaBinding_Audio>(binding);
}
LuaBinding_Audio::LuaBinding_Audio(LuaBinding& binding) :
LuaBinding_Base(binding)
{
/*********************************** Nz::SoundEmitter **********************************/
soundEmitter.Reset("SoundEmitter");
{
soundEmitter.BindMethod("EnableLooping", &Nz::SoundEmitter::EnableLooping);
soundEmitter.BindMethod("EnableSpatialization", &Nz::SoundEmitter::EnableSpatialization);
soundEmitter.BindMethod("GetAttenuation", &Nz::SoundEmitter::GetAttenuation);
soundEmitter.BindMethod("GetDuration", &Nz::SoundEmitter::GetDuration);
soundEmitter.BindMethod("GetMinDistance", &Nz::SoundEmitter::GetMinDistance);
soundEmitter.BindMethod("GetPitch", &Nz::SoundEmitter::GetPitch);
soundEmitter.BindMethod("GetPlayingOffset", &Nz::SoundEmitter::GetPlayingOffset);
soundEmitter.BindMethod("GetPosition", &Nz::Sound::GetPosition);
soundEmitter.BindMethod("GetStatus", &Nz::SoundEmitter::GetStatus);
soundEmitter.BindMethod("GetVelocity", &Nz::Sound::GetVelocity);
soundEmitter.BindMethod("GetVolume", &Nz::SoundEmitter::GetVolume);
soundEmitter.BindMethod("IsLooping", &Nz::SoundEmitter::IsLooping);
soundEmitter.BindMethod("IsSpatialized", &Nz::SoundEmitter::IsSpatialized);
soundEmitter.BindMethod("Pause", &Nz::SoundEmitter::Pause);
soundEmitter.BindMethod("Play", &Nz::SoundEmitter::Play);
soundEmitter.BindMethod("SetAttenuation", &Nz::SoundEmitter::SetAttenuation);
soundEmitter.BindMethod("SetMinDistance", &Nz::SoundEmitter::SetMinDistance);
soundEmitter.BindMethod("SetPitch", &Nz::SoundEmitter::SetPitch);
soundEmitter.BindMethod("SetPosition", (void(Nz::SoundEmitter::*)(const Nz::Vector3f&)) &Nz::SoundEmitter::SetPosition);
soundEmitter.BindMethod("SetVelocity", (void(Nz::SoundEmitter::*)(const Nz::Vector3f&)) &Nz::SoundEmitter::SetVelocity);
soundEmitter.BindMethod("SetVolume", &Nz::SoundEmitter::SetVolume);
soundEmitter.BindMethod("Stop", &Nz::SoundEmitter::Stop);
}
/*********************************** Nz::Music **********************************/
music.Reset("Music");
{
music.Inherit(soundEmitter);
music.BindDefaultConstructor();
//musicClass.SetMethod("Create", &Nz::Music::Create);
//musicClass.SetMethod("Destroy", &Nz::Music::Destroy);
music.BindMethod("EnableLooping", &Nz::Music::EnableLooping);
music.BindMethod("GetDuration", &Nz::Music::GetDuration);
music.BindMethod("GetFormat", &Nz::Music::GetFormat);
music.BindMethod("GetPlayingOffset", &Nz::Music::GetPlayingOffset);
music.BindMethod("GetSampleCount", &Nz::Music::GetSampleCount);
music.BindMethod("GetSampleRate", &Nz::Music::GetSampleRate);
music.BindMethod("GetStatus", &Nz::Music::GetStatus);
music.BindMethod("IsLooping", &Nz::Music::IsLooping);
music.BindMethod("OpenFromFile", &Nz::Music::OpenFromFile, Nz::MusicParams());
music.BindMethod("Pause", &Nz::Music::Pause);
music.BindMethod("Play", &Nz::Music::Play);
music.BindMethod("SetPlayingOffset", &Nz::Music::SetPlayingOffset);
music.BindMethod("Stop", &Nz::Music::Stop);
// Manual
music.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Music& instance, std::size_t /*argumentCount*/) -> int
{
Nz::StringStream ss("Music(");
ss << instance.GetFilePath() << ')';
lua.PushString(ss);
return 1;
});
}
/*********************************** Nz::Sound **********************************/
sound.Reset("Sound");
{
sound.Inherit(soundEmitter);
sound.BindDefaultConstructor();
sound.BindMethod("GetBuffer", &Nz::Sound::GetBuffer);
sound.BindMethod("IsPlayable", &Nz::Sound::IsPlayable);
sound.BindMethod("IsPlaying", &Nz::Sound::IsPlaying);
sound.BindMethod("LoadFromFile", &Nz::Sound::LoadFromFile, Nz::SoundBufferParams());
sound.BindMethod("SetPlayingOffset", &Nz::Sound::SetPlayingOffset);
// Manual
sound.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Sound& instance, std::size_t /*argumentCount*/) -> int
{
Nz::StringStream ss("Sound(");
if (const Nz::SoundBuffer* buffer = instance.GetBuffer())
ss << buffer;
ss << ')';
lua.PushString(ss);
return 1;
});
}
/*********************************** Nz::SoundBuffer **********************************/
soundBuffer.Reset("SoundBuffer");
{
soundBuffer.SetConstructor([] (Nz::LuaInstance& lua, Nz::SoundBufferRef* instance, std::size_t argumentCount)
{
NazaraUnused(lua);
NazaraUnused(argumentCount);
Nz::PlacementNew(instance, Nz::SoundBuffer::New());
return true;
});
soundBuffer.BindMethod("Destroy", &Nz::SoundBuffer::Destroy);
soundBuffer.BindMethod("GetDuration", &Nz::SoundBuffer::GetDuration);
soundBuffer.BindMethod("GetFormat", &Nz::SoundBuffer::GetFormat);
soundBuffer.BindMethod("GetSampleCount", &Nz::SoundBuffer::GetSampleCount);
soundBuffer.BindMethod("GetSampleRate", &Nz::SoundBuffer::GetSampleRate);
soundBuffer.BindMethod("IsValid", &Nz::SoundBuffer::IsValid);
soundBuffer.BindMethod("LoadFromFile", &Nz::SoundBuffer::LoadFromFile, Nz::SoundBufferParams());
soundBuffer.BindStaticMethod("IsFormatSupported", &Nz::SoundBuffer::IsFormatSupported);
// Manual
soundBuffer.BindMethod("Create", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int
{
int index = 2;
Nz::AudioFormat format = lua.Check<Nz::AudioFormat>(&index);
unsigned int sampleCount = lua.Check<unsigned int>(&index);
unsigned int sampleRate = lua.Check<unsigned int>(&index);
std::size_t bufferSize = 0;
const char* buffer = lua.CheckString(index, &bufferSize);
lua.ArgCheck(buffer && bufferSize >= sampleCount * sizeof(Nz::Int16), index, "Invalid buffer");
lua.PushBoolean(instance->Create(format, sampleCount, sampleRate, reinterpret_cast<const Nz::Int16*>(buffer)));
return 1;
});
soundBuffer.BindMethod("GetSamples", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int
{
lua.PushString(reinterpret_cast<const char*>(instance->GetSamples()), instance->GetSampleCount() * sizeof(Nz::Int16));
return 1;
});
soundBuffer.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int
{
Nz::StringStream ss("SoundBuffer(");
if (instance->IsValid())
{
Nz::String filePath = instance->GetFilePath();
if (!filePath.IsEmpty())
ss << "File: " << filePath << ", ";
ss << "Duration: " << instance->GetDuration() / 1000.f << "s";
}
ss << ')';
lua.PushString(ss);
return 1;
});
}
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the Audio classes
*/
void LuaBinding_Audio::Register(Nz::LuaInstance& instance)
{
music.Register(instance);
sound.Register(instance);
soundBuffer.Register(instance);
soundEmitter.Register(instance);
}
}

View File

@ -0,0 +1,13 @@
// This file was automatically generated on 26 May 2014 at 01:05:31
#include <NDK/Lua/LuaBinding_Base.hpp>
namespace Ndk
{
LuaBinding_Base::LuaBinding_Base(LuaBinding& binding) :
m_binding(binding)
{
}
LuaBinding_Base::~LuaBinding_Base() = default;
}

View File

@ -0,0 +1,354 @@
// This file was automatically generated on 26 May 2014 at 01:05:31
#include <NDK/Lua/LuaBinding_Core.hpp>
#include <Nazara/Core/MemoryHelper.hpp>
#include <NDK/LuaAPI.hpp>
namespace Ndk
{
std::unique_ptr<LuaBinding_Base> LuaBinding_Base::BindCore(LuaBinding& binding)
{
return std::make_unique<LuaBinding_Core>(binding);
}
LuaBinding_Core::LuaBinding_Core(LuaBinding& binding) :
LuaBinding_Base(binding)
{
/*********************************** Nz::Stream ***********************************/
stream.Reset("Stream");
{
stream.BindMethod("EnableTextMode", &Nz::Stream::EnableTextMode);
stream.BindMethod("Flush", &Nz::Stream::Flush);
stream.BindMethod("GetCursorPos", &Nz::Stream::GetCursorPos);
stream.BindMethod("GetDirectory", &Nz::Stream::GetDirectory);
stream.BindMethod("GetPath", &Nz::Stream::GetPath);
stream.BindMethod("GetOpenMode", &Nz::Stream::GetOpenMode);
stream.BindMethod("GetStreamOptions", &Nz::Stream::GetStreamOptions);
stream.BindMethod("GetSize", &Nz::Stream::GetSize);
stream.BindMethod("ReadLine", &Nz::Stream::ReadLine, 0U);
stream.BindMethod("IsReadable", &Nz::Stream::IsReadable);
stream.BindMethod("IsSequential", &Nz::Stream::IsSequential);
stream.BindMethod("IsTextModeEnabled", &Nz::Stream::IsTextModeEnabled);
stream.BindMethod("IsWritable", &Nz::Stream::IsWritable);
stream.BindMethod("SetCursorPos", &Nz::Stream::SetCursorPos);
stream.BindMethod("Read", [] (Nz::LuaInstance& lua, Nz::Stream& instance, std::size_t /*argumentCount*/) -> int {
int argIndex = 2;
std::size_t length = lua.Check<std::size_t>(&argIndex);
std::unique_ptr<char[]> buffer(new char[length]);
std::size_t readLength = instance.Read(buffer.get(), length);
lua.PushString(Nz::String(buffer.get(), readLength));
return 1;
});
stream.BindMethod("Write", [] (Nz::LuaInstance& lua, Nz::Stream& instance, std::size_t /*argumentCount*/) -> int {
int argIndex = 2;
std::size_t bufferSize = 0;
const char* buffer = lua.CheckString(argIndex, &bufferSize);
if (instance.IsTextModeEnabled())
lua.Push(instance.Write(Nz::String(buffer, bufferSize)));
else
lua.Push(instance.Write(buffer, bufferSize));
return 1;
});
}
/*********************************** Nz::Clock **********************************/
clock.Reset("Clock");
{
clock.SetConstructor([] (Nz::LuaInstance& lua, Nz::Clock* instance, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
int argIndex = 2;
switch (argCount)
{
case 0:
Nz::PlacementNew(instance);
return true;
case 1:
{
Nz::Int64 startingValue = lua.Check<Nz::Int64>(&argIndex, 0);
Nz::PlacementNew(instance, startingValue);
return true;
}
case 2:
{
Nz::Int64 startingValue = lua.Check<Nz::Int64>(&argIndex, 0);
bool paused = lua.Check<bool>(&argIndex, false);
Nz::PlacementNew(instance, startingValue, paused);
return true;
}
}
lua.Error("No matching overload for Clock constructor");
return false;
});
clock.BindMethod("GetMicroseconds", &Nz::Clock::GetMicroseconds);
clock.BindMethod("GetMilliseconds", &Nz::Clock::GetMilliseconds);
clock.BindMethod("GetSeconds", &Nz::Clock::GetSeconds);
clock.BindMethod("IsPaused", &Nz::Clock::IsPaused);
clock.BindMethod("Pause", &Nz::Clock::Pause);
clock.BindMethod("Restart", &Nz::Clock::Restart);
clock.BindMethod("Unpause", &Nz::Clock::Unpause);
// Manual
clock.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Clock& instance, std::size_t /*argumentCount*/) -> int {
Nz::StringStream ss("Clock(Elapsed: ");
ss << instance.GetSeconds();
ss << "s, Paused: ";
ss << instance.IsPaused();
ss << ')';
lua.PushString(ss);
return 1;
});
}
/********************************* Nz::Directory ********************************/
directory.Reset("Directory");
{
directory.SetConstructor([] (Nz::LuaInstance& lua, Nz::Directory* instance, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 1U);
int argIndex = 2;
switch (argCount)
{
case 0:
Nz::PlacementNew(instance);
return true;
case 1:
Nz::PlacementNew(instance, lua.Check<Nz::String>(&argIndex));
return true;
}
return false;
});
directory.BindMethod("Close", &Nz::Directory::Close);
directory.BindMethod("Exists", &Nz::Directory::Exists);
directory.BindMethod("GetPath", &Nz::Directory::GetPath);
directory.BindMethod("GetPattern", &Nz::Directory::GetPattern);
directory.BindMethod("GetResultName", &Nz::Directory::GetResultName);
directory.BindMethod("GetResultPath", &Nz::Directory::GetResultPath);
directory.BindMethod("GetResultSize", &Nz::Directory::GetResultSize);
directory.BindMethod("IsOpen", &Nz::Directory::IsOpen);
directory.BindMethod("IsResultDirectory", &Nz::Directory::IsResultDirectory);
directory.BindMethod("NextResult", &Nz::Directory::NextResult, true);
directory.BindMethod("Open", &Nz::Directory::Open);
directory.BindMethod("SetPath", &Nz::Directory::SetPath);
directory.BindMethod("SetPattern", &Nz::Directory::SetPattern);
directory.BindStaticMethod("Copy", Nz::Directory::Copy);
directory.BindStaticMethod("Create", Nz::Directory::Create);
directory.BindStaticMethod("Exists", Nz::Directory::Exists);
directory.BindStaticMethod("GetCurrent", Nz::Directory::GetCurrent);
directory.BindStaticMethod("Remove", Nz::Directory::Remove);
directory.BindStaticMethod("SetCurrent", Nz::Directory::SetCurrent);
// Manual
directory.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Directory& instance, std::size_t /*argumentCount*/) -> int {
Nz::StringStream ss("Directory(");
ss << instance.GetPath();
ss << ')';
lua.PushString(ss);
return 1;
});
}
/*********************************** Nz::File ***********************************/
file.Reset("Stream");
{
file.Inherit(stream);
file.SetConstructor([] (Nz::LuaInstance& lua, Nz::File* instance, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 1U);
int argIndex = 2;
switch (argCount)
{
case 0:
Nz::PlacementNew(instance);
return true;
case 1:
{
Nz::String filePath = lua.Check<Nz::String>(&argIndex);
Nz::PlacementNew(instance, filePath);
return true;
}
case 2:
{
Nz::String filePath = lua.Check<Nz::String>(&argIndex);
Nz::UInt32 openMode = lua.Check<Nz::UInt32>(&argIndex);
Nz::PlacementNew(instance, filePath, openMode);
return true;
}
}
lua.Error("No matching overload for File constructor");
return false;
});
file.BindMethod("Close", &Nz::File::Close);
file.BindMethod("Copy", &Nz::File::Copy);
file.BindMethod("Delete", &Nz::File::Delete);
file.BindMethod("EndOfFile", &Nz::File::EndOfFile);
file.BindMethod("Exists", &Nz::File::Exists);
file.BindMethod("GetCreationTime", &Nz::File::GetCreationTime);
file.BindMethod("GetFileName", &Nz::File::GetFileName);
file.BindMethod("GetLastAccessTime", &Nz::File::GetLastAccessTime);
file.BindMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime);
file.BindMethod("IsOpen", &Nz::File::IsOpen);
file.BindMethod("Rename", &Nz::File::GetLastWriteTime);
file.BindMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime);
file.BindMethod("SetFile", &Nz::File::GetLastWriteTime);
file.BindStaticMethod("AbsolutePath", &Nz::File::AbsolutePath);
file.BindStaticMethod("ComputeHash", (Nz::ByteArray(*)(Nz::HashType, const Nz::String&)) &Nz::File::ComputeHash);
file.BindStaticMethod("Copy", &Nz::File::Copy);
file.BindStaticMethod("Delete", &Nz::File::Delete);
file.BindStaticMethod("Exists", &Nz::File::Exists);
//fileClass.SetStaticMethod("GetCreationTime", &Nz::File::GetCreationTime);
file.BindStaticMethod("GetDirectory", &Nz::File::GetDirectory);
//fileClass.SetStaticMethod("GetLastAccessTime", &Nz::File::GetLastAccessTime);
//fileClass.SetStaticMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime);
file.BindStaticMethod("GetSize", &Nz::File::GetSize);
file.BindStaticMethod("IsAbsolute", &Nz::File::IsAbsolute);
file.BindStaticMethod("NormalizePath", &Nz::File::NormalizePath);
file.BindStaticMethod("NormalizeSeparators", &Nz::File::NormalizeSeparators);
file.BindStaticMethod("Rename", &Nz::File::Rename);
// Manual
file.BindMethod("Open", [] (Nz::LuaInstance& lua, Nz::File& instance, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
int argIndex = 2;
switch (argCount)
{
case 0:
case 1:
return lua.Push(instance.Open(lua.Check<Nz::UInt32>(&argIndex, Nz::OpenMode_NotOpen)));
case 2:
{
Nz::String filePath = lua.Check<Nz::String>(&argIndex);
Nz::UInt32 openMode = lua.Check<Nz::UInt32>(&argIndex, Nz::OpenMode_NotOpen);
return lua.Push(instance.Open(filePath, openMode));
}
}
lua.Error("No matching overload for method Open");
return 0;
});
file.BindMethod("SetCursorPos", [] (Nz::LuaInstance& lua, Nz::File& instance, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
int argIndex = 2;
switch (argCount)
{
case 1:
return lua.Push(instance.SetCursorPos(lua.Check<Nz::UInt64>(&argIndex)));
case 2:
{
Nz::CursorPosition curPos = lua.Check<Nz::CursorPosition>(&argIndex);
Nz::Int64 offset = lua.Check<Nz::Int64>(&argIndex);
return lua.Push(instance.SetCursorPos(curPos, offset));
}
}
lua.Error("No matching overload for method SetCursorPos");
return 0;
});
file.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::File& instance, std::size_t /*argumentCount*/) -> int {
Nz::StringStream ss("File(");
if (instance.IsOpen())
ss << "Path: " << instance.GetPath();
ss << ')';
lua.PushString(ss);
return 1;
});
}
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the Core classes
*/
void LuaBinding_Core::Register(Nz::LuaInstance& instance)
{
// Classes
clock.Register(instance);
directory.Register(instance);
file.Register(instance);
stream.Register(instance);
// Enums
// Nz::CursorPosition
static_assert(Nz::CursorPosition_Max + 1 == 3, "Nz::CursorPosition has been updated but change was not reflected to Lua binding");
instance.PushTable(0, 3);
{
instance.PushField("AtBegin", Nz::CursorPosition_AtBegin);
instance.PushField("AtCurrent", Nz::CursorPosition_AtCurrent);
instance.PushField("AtEnd", Nz::CursorPosition_AtEnd);
}
instance.SetGlobal("CursorPosition");
// Nz::HashType
static_assert(Nz::HashType_Max + 1 == 9, "Nz::HashType has been updated but change was not reflected to Lua binding");
instance.PushTable(0, 9);
{
instance.PushField("CRC32", Nz::HashType_CRC32);
instance.PushField("Fletcher16", Nz::HashType_Fletcher16);
instance.PushField("MD5", Nz::HashType_MD5);
instance.PushField("SHA1", Nz::HashType_SHA1);
instance.PushField("SHA224", Nz::HashType_SHA224);
instance.PushField("SHA256", Nz::HashType_SHA256);
instance.PushField("SHA384", Nz::HashType_SHA384);
instance.PushField("SHA512", Nz::HashType_SHA512);
instance.PushField("Whirlpool", Nz::HashType_Whirlpool);
}
instance.SetGlobal("HashType");
// Nz::OpenMode
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);
{
instance.PushField("Append", Nz::OpenMode_Append);
instance.PushField("NotOpen", Nz::OpenMode_NotOpen);
instance.PushField("Lock", Nz::OpenMode_Lock);
instance.PushField("ReadOnly", Nz::OpenMode_ReadOnly);
instance.PushField("ReadWrite", Nz::OpenMode_ReadWrite);
instance.PushField("Text", Nz::OpenMode_Text);
instance.PushField("Truncate", Nz::OpenMode_Truncate);
instance.PushField("WriteOnly", Nz::OpenMode_WriteOnly);
}
instance.SetGlobal("OpenMode");
}
}

View File

@ -0,0 +1,370 @@
// 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_Graphics.hpp>
#include <NDK/LuaAPI.hpp>
namespace Ndk
{
std::unique_ptr<LuaBinding_Base> LuaBinding_Base::BindGraphics(LuaBinding& binding)
{
return std::make_unique<LuaBinding_Graphics>(binding);
}
LuaBinding_Graphics::LuaBinding_Graphics(LuaBinding& binding) :
LuaBinding_Base(binding)
{
/*********************************** Nz::AbstractViewer ***********************************/
abstractViewer.Reset("AbstractViewer");
{
abstractViewer.BindMethod("GetAspectRatio", &Nz::AbstractViewer::GetAspectRatio);
abstractViewer.BindMethod("GetEyePosition", &Nz::AbstractViewer::GetEyePosition);
abstractViewer.BindMethod("GetForward", &Nz::AbstractViewer::GetForward);
//abstractViewer.BindMethod("GetFrustum", &Nz::AbstractViewer::GetFrustum);
abstractViewer.BindMethod("GetProjectionMatrix", &Nz::AbstractViewer::GetProjectionMatrix);
//abstractViewer.BindMethod("GetTarget", &Nz::AbstractViewer::GetTarget);
abstractViewer.BindMethod("GetViewMatrix", &Nz::AbstractViewer::GetViewMatrix);
abstractViewer.BindMethod("GetViewport", &Nz::AbstractViewer::GetViewport);
abstractViewer.BindMethod("GetZFar", &Nz::AbstractViewer::GetZFar);
abstractViewer.BindMethod("GetZNear", &Nz::AbstractViewer::GetZNear);
}
/*********************************** Nz::InstancedRenderable ***********************************/
instancedRenderable.Reset("InstancedRenderable");
{
}
/*********************************** Nz::Material ***********************************/
material.Reset("Material");
{
material.SetConstructor([] (Nz::LuaInstance& lua, Nz::MaterialRef* instance, std::size_t argumentCount)
{
switch (argumentCount)
{
case 0:
Nz::PlacementNew(instance, Nz::Material::New());
return true;
case 1:
{
int argIndex = 1;
if (lua.IsOfType(argIndex, "MaterialPipeline"))
{
Nz::PlacementNew(instance, Nz::Material::New(*static_cast<Nz::MaterialPipelineRef*>(lua.ToUserdata(argIndex))));
return true;
}
else if (lua.IsOfType(argIndex, "Material"))
{
Nz::PlacementNew(instance, Nz::Material::New(**static_cast<Nz::MaterialRef*>(lua.ToUserdata(argIndex))));
return true;
}
else
{
Nz::PlacementNew(instance, Nz::Material::New(lua.Check<Nz::String>(&argIndex)));
return true;
}
}
}
lua.Error("No matching overload for constructor");
return false;
});
material.BindMethod("Configure", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "MaterialPipeline"))
{
instance->Configure(*static_cast<Nz::MaterialPipelineRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
{
lua.Push(instance->Configure(lua.Check<Nz::String>(&argIndex)));
return 1;
}
});
material.BindMethod("EnableAlphaTest", &Nz::Material::EnableAlphaTest);
material.BindMethod("EnableBlending", &Nz::Material::EnableBlending);
material.BindMethod("EnableColorWrite", &Nz::Material::EnableColorWrite);
material.BindMethod("EnableDepthBuffer", &Nz::Material::EnableDepthBuffer);
material.BindMethod("EnableDepthSorting", &Nz::Material::EnableDepthSorting);
material.BindMethod("EnableDepthWrite", &Nz::Material::EnableDepthWrite);
material.BindMethod("EnableFaceCulling", &Nz::Material::EnableFaceCulling);
material.BindMethod("EnableScissorTest", &Nz::Material::EnableScissorTest);
material.BindMethod("EnableShadowCasting", &Nz::Material::EnableShadowCasting);
material.BindMethod("EnableShadowReceive", &Nz::Material::EnableShadowReceive);
material.BindMethod("EnableStencilTest", &Nz::Material::EnableStencilTest);
material.BindMethod("EnsurePipelineUpdate", &Nz::Material::EnsurePipelineUpdate);
material.BindMethod("GetAlphaMap", &Nz::Material::GetAlphaMap);
material.BindMethod("GetAlphaThreshold", &Nz::Material::GetAlphaThreshold);
material.BindMethod("GetAmbientColor", &Nz::Material::GetAmbientColor);
material.BindMethod("GetDepthFunc", &Nz::Material::GetDepthFunc);
material.BindMethod("GetDepthMaterial", &Nz::Material::GetDepthMaterial);
material.BindMethod("GetDiffuseColor", &Nz::Material::GetDiffuseColor);
material.BindMethod("GetDiffuseMap", &Nz::Material::GetDiffuseMap);
//material.BindMethod("GetDiffuseSampler", &Nz::Material::GetDiffuseSampler);
material.BindMethod("GetDstBlend", &Nz::Material::GetDstBlend);
material.BindMethod("GetEmissiveMap", &Nz::Material::GetEmissiveMap);
material.BindMethod("GetFaceCulling", &Nz::Material::GetFaceCulling);
material.BindMethod("GetFaceFilling", &Nz::Material::GetFaceFilling);
material.BindMethod("GetHeightMap", &Nz::Material::GetHeightMap);
material.BindMethod("GetLineWidth", &Nz::Material::GetLineWidth);
material.BindMethod("GetNormalMap", &Nz::Material::GetNormalMap);
//material.BindMethod("GetPipeline", &Nz::Material::GetPipeline);
//material.BindMethod("GetPipelineInfo", &Nz::Material::GetPipelineInfo);
material.BindMethod("GetPointSize", &Nz::Material::GetPointSize);
//material.BindMethod("GetShader", &Nz::Material::GetShader);
material.BindMethod("GetShininess", &Nz::Material::GetShininess);
material.BindMethod("GetSpecularColor", &Nz::Material::GetSpecularColor);
material.BindMethod("GetSpecularMap", &Nz::Material::GetSpecularMap);
//material.BindMethod("GetSpecularSampler", &Nz::Material::GetSpecularSampler);
material.BindMethod("GetSrcBlend", &Nz::Material::GetSrcBlend);
material.BindMethod("HasAlphaMap", &Nz::Material::HasAlphaMap);
material.BindMethod("HasDepthMaterial", &Nz::Material::HasDepthMaterial);
material.BindMethod("HasDiffuseMap", &Nz::Material::HasDiffuseMap);
material.BindMethod("HasEmissiveMap", &Nz::Material::HasEmissiveMap);
material.BindMethod("HasHeightMap", &Nz::Material::HasHeightMap);
material.BindMethod("HasNormalMap", &Nz::Material::HasNormalMap);
material.BindMethod("HasSpecularMap", &Nz::Material::HasSpecularMap);
material.BindMethod("IsAlphaTestEnabled", &Nz::Material::IsAlphaTestEnabled);
material.BindMethod("IsBlendingEnabled", &Nz::Material::IsBlendingEnabled);
material.BindMethod("IsColorWriteEnabled", &Nz::Material::IsColorWriteEnabled);
material.BindMethod("IsDepthBufferEnabled", &Nz::Material::IsDepthBufferEnabled);
material.BindMethod("IsDepthSortingEnabled", &Nz::Material::IsDepthSortingEnabled);
material.BindMethod("IsDepthWriteEnabled", &Nz::Material::IsDepthWriteEnabled);
material.BindMethod("IsFaceCullingEnabled", &Nz::Material::IsFaceCullingEnabled);
material.BindMethod("IsScissorTestEnabled", &Nz::Material::IsScissorTestEnabled);
material.BindMethod("IsStencilTestEnabled", &Nz::Material::IsStencilTestEnabled);
material.BindMethod("IsShadowCastingEnabled", &Nz::Material::IsShadowCastingEnabled);
material.BindMethod("IsShadowReceiveEnabled", &Nz::Material::IsShadowReceiveEnabled);
material.BindMethod("LoadFromFile", &Nz::Material::LoadFromFile, Nz::MaterialParams());
material.BindMethod("Reset", &Nz::Material::Reset);
material.BindMethod("SetAlphaThreshold", &Nz::Material::SetAlphaThreshold);
material.BindMethod("SetAmbientColor", &Nz::Material::SetAmbientColor);
material.BindMethod("SetDepthFunc", &Nz::Material::SetDepthFunc);
material.BindMethod("SetDepthFunc", &Nz::Material::SetDepthFunc);
material.BindMethod("SetDepthMaterial", &Nz::Material::SetDepthMaterial);
material.BindMethod("SetDiffuseColor", &Nz::Material::SetDiffuseColor);
//material.BindMethod("SetDiffuseSampler", &Nz::Material::SetDiffuseSampler);
material.BindMethod("SetDstBlend", &Nz::Material::SetDstBlend);
material.BindMethod("SetFaceCulling", &Nz::Material::SetFaceCulling);
material.BindMethod("SetFaceFilling", &Nz::Material::SetFaceFilling);
material.BindMethod("SetLineWidth", &Nz::Material::SetLineWidth);
material.BindMethod("SetPointSize", &Nz::Material::SetPointSize);
material.BindMethod("SetShininess", &Nz::Material::SetShininess);
material.BindMethod("SetSpecularColor", &Nz::Material::SetSpecularColor);
material.BindMethod("SetSpecularColor", &Nz::Material::SetSpecularColor);
//material.BindMethod("SetSpecularSampler", &Nz::Material::SetSpecularSampler);
material.BindMethod("SetSrcBlend", &Nz::Material::SetSrcBlend);
material.BindStaticMethod("GetDefault", &Nz::Material::GetDefault);
material.BindMethod("SetAlphaMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
instance->SetAlphaMap(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetAlphaMap(lua.Check<Nz::String>(&argIndex)));
});
material.BindMethod("SetDiffuseMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
instance->SetDiffuseMap(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetDiffuseMap(lua.Check<Nz::String>(&argIndex)));
});
material.BindMethod("SetEmissiveMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
instance->SetEmissiveMap(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetEmissiveMap(lua.Check<Nz::String>(&argIndex)));
});
material.BindMethod("SetHeightMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
instance->SetHeightMap(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetHeightMap(lua.Check<Nz::String>(&argIndex)));
});
material.BindMethod("SetNormalMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
instance->SetNormalMap(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetNormalMap(lua.Check<Nz::String>(&argIndex)));
});
material.BindMethod("SetShader", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "UberShader"))
{
instance->SetShader(*static_cast<Nz::UberShaderRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetShader(lua.Check<Nz::String>(&argIndex)));
});
material.BindMethod("SetSpecularMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
instance->SetSpecularMap(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetSpecularMap(lua.Check<Nz::String>(&argIndex)));
});
}
/*********************************** Nz::Model ***********************************/
model.Reset("Model");
{
model.Inherit<Nz::InstancedRenderableRef>(instancedRenderable, [] (Nz::ModelRef* modelRef) -> Nz::InstancedRenderableRef*
{
return reinterpret_cast<Nz::InstancedRenderableRef*>(modelRef); //TODO: Make a ObjectRefCast
});
model.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::ModelRef* instance, std::size_t /*argumentCount*/)
{
Nz::PlacementNew(instance, Nz::Model::New());
return true;
});
//model.BindMethod("GetMaterial", &Nz::Model::GetMaterial);
model.BindMethod("GetMaterialCount", &Nz::Model::GetMaterialCount);
//modelClass.SetMethod("GetMesh", &Nz::Model::GetMesh);
model.BindMethod("GetSkin", &Nz::Model::GetSkin);
model.BindMethod("GetSkinCount", &Nz::Model::GetSkinCount);
model.BindMethod("IsAnimated", &Nz::Model::IsAnimated);
model.BindMethod("LoadFromFile", &Nz::Model::LoadFromFile, Nz::ModelParameters());
model.BindMethod("Reset", &Nz::Model::Reset);
//model.BindMethod("SetMaterial", &Nz::Model::SetMaterial);
//modelClass.SetMethod("SetMesh", &Nz::Model::SetMesh);
//modelClass.SetMethod("SetSequence", &Nz::Model::SetSequence);
model.BindMethod("SetSkin", &Nz::Model::SetSkin);
model.BindMethod("SetSkinCount", &Nz::Model::SetSkinCount);
}
/*********************************** Nz::Sprite ***********************************/
sprite.Reset("Sprite");
{
sprite.Inherit<Nz::InstancedRenderableRef>(instancedRenderable, [] (Nz::SpriteRef* spriteRef) -> Nz::InstancedRenderableRef*
{
return reinterpret_cast<Nz::InstancedRenderableRef*>(spriteRef); //TODO: Make a ObjectRefCast
});
sprite.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::SpriteRef* instance, std::size_t /*argumentCount*/)
{
Nz::PlacementNew(instance, Nz::Sprite::New());
return true;
});
sprite.BindMethod("GetColor", &Nz::Sprite::GetColor);
sprite.BindMethod("GetCornerColor", &Nz::Sprite::GetCornerColor);
sprite.BindMethod("GetMaterial", &Nz::Sprite::GetMaterial);
sprite.BindMethod("GetOrigin", &Nz::Sprite::GetOrigin);
sprite.BindMethod("GetSize", &Nz::Sprite::GetSize);
sprite.BindMethod("GetTextureCoords", &Nz::Sprite::GetTextureCoords);
sprite.BindMethod("SetColor", &Nz::Sprite::SetColor);
sprite.BindMethod("SetCornerColor", &Nz::Sprite::SetCornerColor);
sprite.BindMethod("SetDefaultMaterial", &Nz::Sprite::SetDefaultMaterial);
sprite.BindMethod("SetOrigin", &Nz::Sprite::SetOrigin);
sprite.BindMethod("SetSize", (void(Nz::Sprite::*)(const Nz::Vector2f&)) &Nz::Sprite::SetSize);
sprite.BindMethod("SetTextureCoords", &Nz::Sprite::SetTextureCoords);
sprite.BindMethod("SetTextureRect", &Nz::Sprite::SetTextureRect);
sprite.BindMethod("SetMaterial", [] (Nz::LuaInstance& lua, Nz::SpriteRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
bool resizeSprite = lua.CheckBoolean(argIndex + 1, true);
if (lua.IsOfType(argIndex, "Material"))
instance->SetMaterial(*static_cast<Nz::MaterialRef*>(lua.ToUserdata(argIndex)), resizeSprite);
else
instance->SetMaterial(lua.Check<Nz::String>(&argIndex), resizeSprite);
return 0;
});
sprite.BindMethod("SetTexture", [] (Nz::LuaInstance& lua, Nz::SpriteRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
bool resizeSprite = lua.CheckBoolean(argIndex + 1, true);
if (lua.IsOfType(argIndex, "Texture"))
instance->SetTexture(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)), resizeSprite);
else
instance->SetTexture(lua.Check<Nz::String>(&argIndex), resizeSprite);
return 0;
});
}
/*********************************** Nz::SpriteLibrary ***********************************/
spriteLibrary.Reset("SpriteLibrary");
{
spriteLibrary.BindStaticMethod("Get", &Nz::SpriteLibrary::Get);
spriteLibrary.BindStaticMethod("Has", &Nz::SpriteLibrary::Has);
spriteLibrary.BindStaticMethod("Register", &Nz::SpriteLibrary::Register);
spriteLibrary.BindStaticMethod("Query", &Nz::SpriteLibrary::Query);
spriteLibrary.BindStaticMethod("Unregister", &Nz::SpriteLibrary::Unregister);
}
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the Graphics classes
*/
void LuaBinding_Graphics::Register(Nz::LuaInstance& instance)
{
abstractViewer.Register(instance);
instancedRenderable.Register(instance);
material.Register(instance);
model.Register(instance);
sprite.Register(instance);
spriteLibrary.Register(instance);
}
}

View File

@ -0,0 +1,986 @@
// This file was automatically generated on 26 May 2014 at 01:05:31
#include <NDK/Lua/LuaBinding_Math.hpp>
#include <Nazara/Core/MemoryHelper.hpp>
#include <NDK/LuaAPI.hpp>
#include <cstring>
namespace Ndk
{
std::unique_ptr<LuaBinding_Base> LuaBinding_Base::BindMath(LuaBinding& binding)
{
return std::make_unique<LuaBinding_Math>(binding);
}
LuaBinding_Math::LuaBinding_Math(LuaBinding& binding) :
LuaBinding_Base(binding)
{
/*********************************** Nz::EulerAngles **********************************/
eulerAngles.Reset("EulerAngles");
{
eulerAngles.SetConstructor([] (Nz::LuaInstance& lua, Nz::EulerAnglesd* instance, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 1U);
switch (argCount)
{
case 0:
Nz::PlacementNew(instance, Nz::EulerAnglesd::Zero());
return true;
case 1:
Nz::PlacementNew(instance, *static_cast<Nz::EulerAnglesd*>(lua.CheckUserdata(1, "EulerAngles")));
return true;
case 3:
Nz::PlacementNew(instance, lua.CheckNumber(1), lua.CheckNumber(2), lua.CheckNumber(3));
return true;
}
lua.Error("No matching overload for EulerAngles constructor");
return false;
});
eulerAngles.BindMethod("Normalize", &Nz::EulerAnglesd::Normalize);
eulerAngles.BindMethod("ToQuaternion", &Nz::EulerAnglesd::ToQuaternion);
eulerAngles.BindMethod("__tostring", &Nz::EulerAnglesd::ToString);
eulerAngles.SetGetter([] (Nz::LuaInstance& lua, Nz::EulerAnglesd& instance)
{
std::size_t length;
const char* ypr = lua.CheckString(2, &length);
switch (length)
{
case 1:
{
switch (ypr[0])
{
case 'p':
lua.Push(instance.pitch);
return true;
case 'y':
lua.Push(instance.yaw);
return true;
case 'r':
lua.Push(instance.roll);
return true;
}
break;
}
case 3:
{
if (std::memcmp(ypr, "yaw", 3) != 0)
break;
lua.Push(instance.yaw);
return true;
}
case 4:
{
if (std::memcmp(ypr, "roll", 4) != 0)
break;
lua.Push(instance.roll);
return true;
}
case 5:
{
if (std::memcmp(ypr, "pitch", 5) != 0)
break;
lua.Push(instance.pitch);
return true;
}
}
return false;
});
eulerAngles.SetSetter([] (Nz::LuaInstance& lua, Nz::EulerAnglesd& instance)
{
std::size_t length;
const char* ypr = lua.CheckString(2, &length);
double value = lua.CheckNumber(3);
switch (length)
{
case 1:
{
switch (ypr[0])
{
case 'p':
instance.pitch = value;
return true;
case 'y':
instance.yaw = value;
return true;
case 'r':
instance.roll = value;
return true;
}
break;
}
case 3:
{
if (std::memcmp(ypr, "yaw", 3) != 0)
break;
instance.yaw = value;
return true;
}
case 4:
{
if (std::memcmp(ypr, "roll", 4) != 0)
break;
instance.roll = value;
return true;
}
case 5:
{
if (std::memcmp(ypr, "pitch", 5) != 0)
break;
instance.pitch = value;
return true;
}
}
return false;
});
}
/*********************************** Nz::Matrix4 **********************************/
matrix4d.Reset("Matrix4");
{
matrix4d.SetConstructor([] (Nz::LuaInstance& lua, Nz::Matrix4d* matrix, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 3U);
switch (argCount)
{
case 0:
Nz::PlacementNew(matrix, Nz::Matrix4d::Zero());
return true;
case 1:
if (lua.IsOfType(1, "Matrix4"))
Nz::PlacementNew(matrix, *static_cast<Nz::Matrix4d*>(lua.ToUserdata(1)));
break;
case 16:
{
double values[16];
for (int i = 0; i < 16; ++i)
values[i] = lua.CheckNumber(i);
Nz::PlacementNew(matrix, values);
return true;
}
}
lua.Error("No matching overload for constructor");
return false;
});
matrix4d.BindMethod("ApplyRotation", &Nz::Matrix4d::ApplyRotation);
matrix4d.BindMethod("ApplyScale", &Nz::Matrix4d::ApplyScale);
matrix4d.BindMethod("ApplyTranslation", &Nz::Matrix4d::ApplyTranslation);
matrix4d.BindMethod("Concatenate", &Nz::Matrix4d::Concatenate);
matrix4d.BindMethod("ConcatenateAffine", &Nz::Matrix4d::ConcatenateAffine);
//matrix4d.BindMethod("GetColumn", &Nz::Matrix4d::GetColumn);
matrix4d.BindMethod("GetDeterminant", &Nz::Matrix4d::GetDeterminant);
matrix4d.BindMethod("GetDeterminantAffine", &Nz::Matrix4d::GetDeterminantAffine);
matrix4d.BindMethod("GetInverse", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{
Nz::Matrix4d result;
if (instance.GetInverse(&result))
return lua.Push(true, result);
else
return lua.Push(false);
});
matrix4d.BindMethod("GetInverseAffine", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{
Nz::Matrix4d result;
if (instance.GetInverseAffine(&result))
return lua.Push(true, result);
else
return lua.Push(false);
});
matrix4d.BindMethod("GetRotation", &Nz::Matrix4d::GetRotation);
//matrix4d.BindMethod("GetRow", &Nz::Matrix4d::GetRow);
matrix4d.BindMethod("GetScale", &Nz::Matrix4d::GetScale);
matrix4d.BindMethod("GetSquaredScale", &Nz::Matrix4d::GetSquaredScale);
matrix4d.BindMethod("GetTranslation", &Nz::Matrix4d::GetTranslation);
matrix4d.BindMethod("GetTransposed", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{
Nz::Matrix4d result;
instance.GetTransposed(&result);
return lua.Push(result);
});
matrix4d.BindMethod("HasNegativeScale", &Nz::Matrix4d::HasNegativeScale);
matrix4d.BindMethod("HasScale", &Nz::Matrix4d::HasScale);
matrix4d.BindMethod("Inverse", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{
bool succeeded;
instance.Inverse(&succeeded);
return lua.Push(succeeded);
});
matrix4d.BindMethod("InverseAffine", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{
bool succeeded;
instance.InverseAffine(&succeeded);
return lua.Push(succeeded);
});
matrix4d.BindMethod("IsAffine", &Nz::Matrix4d::IsAffine);
matrix4d.BindMethod("IsIdentity", &Nz::Matrix4d::IsIdentity);
matrix4d.BindMethod("MakeIdentity", &Nz::Matrix4d::MakeIdentity);
matrix4d.BindMethod("MakeLookAt", &Nz::Matrix4d::MakeLookAt, Nz::Vector3d::Up());
matrix4d.BindMethod("MakeOrtho", &Nz::Matrix4d::MakeOrtho, -1.0, 1.0);
matrix4d.BindMethod("MakePerspective", &Nz::Matrix4d::MakePerspective);
matrix4d.BindMethod("MakeRotation", &Nz::Matrix4d::MakeRotation);
matrix4d.BindMethod("MakeScale", &Nz::Matrix4d::MakeScale);
matrix4d.BindMethod("MakeTranslation", &Nz::Matrix4d::MakeTranslation);
matrix4d.BindMethod("MakeTransform", (Nz::Matrix4d&(Nz::Matrix4d::*)(const Nz::Vector3d&, const Nz::Quaterniond&, const Nz::Vector3d&)) &Nz::Matrix4d::MakeTransform, Nz::Vector3d::Unit());
matrix4d.BindMethod("MakeViewMatrix", &Nz::Matrix4d::MakeViewMatrix);
matrix4d.BindMethod("MakeZero", &Nz::Matrix4d::MakeZero);
matrix4d.BindMethod("Set", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 3U);
int argIndex = 2;
switch (argCount)
{
case 1:
if (lua.IsOfType(argIndex, "Matrix4"))
instance.Set(*static_cast<Nz::Matrix4d*>(lua.ToUserdata(argIndex)));
break;
case 16:
{
double values[16];
for (std::size_t i = 0; i < 16; ++i)
values[i] = lua.CheckNumber(argIndex++);
instance.Set(values);
return 0;
}
}
lua.Error("No matching overload for method Set");
return 0;
});
matrix4d.BindMethod("SetRotation", &Nz::Matrix4d::SetRotation);
matrix4d.BindMethod("SetScale", &Nz::Matrix4d::SetScale);
matrix4d.BindMethod("SetTranslation", &Nz::Matrix4d::SetTranslation);
matrix4d.BindMethod("Transform", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Vector2"))
{
double z(lua.CheckNumber(argIndex + 1, 0.0));
double w(lua.CheckNumber(argIndex + 2, 1.0));
return lua.Push(instance.Transform(*static_cast<Nz::Vector2d*>(lua.ToUserdata(argIndex)), z, w));
}
else if (lua.IsOfType(argIndex, "Vector3"))
{
double w(lua.CheckNumber(argIndex + 1, 1.0));
return lua.Push(instance.Transform(*static_cast<Nz::Vector3d*>(lua.ToUserdata(argIndex)), w));
}
//else if (lua.IsOfType(2, "Vector4"))
// return lua.Push(instance.Transform(*static_cast<Nz::Vector4d*>(lua.ToUserdata(1))));
lua.Error("No matching overload for method Transform");
return 0;
});
matrix4d.BindMethod("Transpose", &Nz::Matrix4d::Transpose);
matrix4d.BindMethod("__tostring", &Nz::Matrix4d::ToString);
matrix4d.BindStaticMethod("Concatenate", &Nz::Matrix4d::Concatenate);
matrix4d.BindStaticMethod("ConcatenateAffine", &Nz::Matrix4d::ConcatenateAffine);
matrix4d.BindStaticMethod("Identity", &Nz::Matrix4d::Identity);
matrix4d.BindStaticMethod("LookAt", &Nz::Matrix4d::LookAt, Nz::Vector3d::Up());
matrix4d.BindStaticMethod("Ortho", &Nz::Matrix4d::Ortho, -1.0, 1.0);
matrix4d.BindStaticMethod("Perspective", &Nz::Matrix4d::Perspective);
matrix4d.BindStaticMethod("Rotate", &Nz::Matrix4d::Rotate);
matrix4d.BindStaticMethod("Scale", &Nz::Matrix4d::Scale);
matrix4d.BindStaticMethod("Translate", &Nz::Matrix4d::Translate);
matrix4d.BindStaticMethod("Transform", (Nz::Matrix4d(*)(const Nz::Vector3d&, const Nz::Quaterniond&, const Nz::Vector3d&)) &Nz::Matrix4d::Transform, Nz::Vector3d::Unit());
matrix4d.BindStaticMethod("ViewMatrix", &Nz::Matrix4d::ViewMatrix);
matrix4d.BindStaticMethod("Zero", &Nz::Matrix4d::Zero);
matrix4d.SetGetter([] (Nz::LuaInstance& lua, Nz::Matrix4d& instance)
{
bool succeeded = false;
std::size_t index = static_cast<std::size_t>(lua.ToInteger(2, &succeeded));
if (!succeeded || index < 1 || index > 16)
return false;
lua.Push(instance[index - 1]);
return true;
});
matrix4d.SetSetter([] (Nz::LuaInstance& lua, Nz::Matrix4d& instance)
{
bool succeeded = false;
std::size_t index = static_cast<std::size_t>(lua.ToInteger(2, &succeeded));
if (!succeeded || index < 1 || index > 16)
return false;
instance[index - 1] = lua.CheckNumber(3);
return true;
});
}
/*********************************** Nz::Rect **********************************/
rect.Reset("Rect");
{
rect.SetConstructor([] (Nz::LuaInstance& lua, Nz::Rectd* instance, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
switch (argCount)
{
case 0:
case 4:
PlacementNew(instance, lua.CheckNumber(1, 0.0), lua.CheckNumber(2, 0.0), lua.CheckNumber(3, 0.0), lua.CheckNumber(4, 0.0));
return true;
case 1:
{
if (lua.IsOfType(1, "Rect"))
PlacementNew(instance, *static_cast<Nz::Rectd*>(lua.ToUserdata(1)));
else if (lua.IsOfType(1, Nz::LuaType_Table))
{
// TODO => Faire sans avoir à mettre de nom dans la table et prendre les éléments un à un pour créer le Rectd
PlacementNew(instance, lua.CheckField<double>("x", 1),
lua.CheckField<double>("y", 1),
lua.CheckField<double>("width", 1),
lua.CheckField<double>("height", 1));
}
else if (lua.IsOfType(1, "Vector2"))
PlacementNew(instance, *static_cast<Nz::Vector2d*>(lua.ToUserdata(1)));
else
break;
return true;
}
case 2:
{
if (lua.IsOfType(1, Nz::LuaType_Number) && lua.IsOfType(2, Nz::LuaType_Number))
PlacementNew(instance, lua.CheckNumber(1), lua.CheckNumber(2));
else if (lua.IsOfType(1, "Vector2") && lua.IsOfType(2, "Vector2"))
PlacementNew(instance, *static_cast<Nz::Vector2d*>(lua.ToUserdata(1)), *static_cast<Nz::Vector2d*>(lua.ToUserdata(2)));
else
break;
return true;
}
}
lua.Error("No matching overload for Rect constructor");
return false;
});
rect.BindMethod("__tostring", &Nz::Rectd::ToString);
rect.SetGetter([] (Nz::LuaInstance& lua, Nz::Rectd& instance)
{
switch (lua.GetType(2))
{
case Nz::LuaType_Number:
{
auto index = lua.CheckBoundInteger<std::size_t>(2);
if (index < 1 || index > 4)
return false;
lua.Push(instance[index - 1]);
return true;
}
case Nz::LuaType_String:
{
std::size_t length;
const char* xywh = lua.CheckString(2, &length);
if (length != 1)
break;
switch (xywh[0])
{
case 'x':
lua.Push(instance.x);
return true;
case 'y':
lua.Push(instance.y);
return true;
case 'w':
lua.Push(instance.width);
return true;
case 'h':
lua.Push(instance.height);
return true;
default:
break;
}
break;
}
default:
break;
}
return false;
});
rect.SetSetter([] (Nz::LuaInstance& lua, Nz::Rectd& instance)
{
switch (lua.GetType(2))
{
case Nz::LuaType_Number:
{
auto index = lua.CheckBoundInteger<std::size_t>(2);
if (index < 1 || index > 4)
return false;
instance[index - 1] = lua.CheckNumber(2);
return true;
}
case Nz::LuaType_String:
{
std::size_t length;
const char* xywh = lua.CheckString(2, &length);
if (length != 1)
break;
double value = lua.CheckNumber(3);
switch (xywh[0])
{
case 'x':
instance.x = value;
return true;
case 'y':
instance.y = value;
return true;
case 'w':
instance.width = value;
return true;
case 'h':
instance.height = value;
return true;
}
break;
}
default:
break;
}
return false;
});
}
/*********************************** Nz::Quaternion **********************************/
quaternion.Reset("Quaternion");
{
quaternion.SetConstructor([] (Nz::LuaInstance& lua, Nz::Quaterniond* instance, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
switch (argCount)
{
case 0:
Nz::PlacementNew(instance, Nz::Quaterniond::Zero());
return true;
case 1:
{
if (lua.IsOfType(1, "EulerAngles"))
Nz::PlacementNew(instance, *static_cast<Nz::EulerAnglesd*>(lua.ToUserdata(1)));
else if (lua.IsOfType(1, "Quaternion"))
Nz::PlacementNew(instance, *static_cast<Nz::Quaterniond*>(lua.ToUserdata(1)));
else
break;
return true;
}
case 2:
Nz::PlacementNew(instance, lua.CheckNumber(1), *static_cast<Nz::Vector3d*>(lua.CheckUserdata(2, "Vector3")));
return true;
case 4:
Nz::PlacementNew(instance, lua.CheckNumber(1), lua.CheckNumber(2), lua.CheckNumber(3), lua.CheckNumber(4));
return true;
default:
break;
}
lua.Error("No matching overload for Quaternion constructor");
return false;
});
quaternion.BindMethod("ComputeW", &Nz::Quaterniond::ComputeW);
quaternion.BindMethod("Conjugate", &Nz::Quaterniond::Conjugate);
quaternion.BindMethod("DotProduct", &Nz::Quaterniond::DotProduct);
quaternion.BindMethod("GetConjugate", &Nz::Quaterniond::GetConjugate);
quaternion.BindMethod("GetInverse", &Nz::Quaterniond::GetInverse);
quaternion.BindMethod("Inverse", &Nz::Quaterniond::Inverse);
quaternion.BindMethod("Magnitude", &Nz::Quaterniond::Magnitude);
quaternion.BindMethod("SquaredMagnitude", &Nz::Quaterniond::SquaredMagnitude);
quaternion.BindMethod("ToEulerAngles", &Nz::Quaterniond::ToEulerAngles);
quaternion.BindMethod("__tostring", &Nz::Quaterniond::ToString);
quaternion.BindStaticMethod("Lerp", &Nz::Quaterniond::Lerp);
quaternion.BindStaticMethod("RotationBetween", &Nz::Quaterniond::RotationBetween);
quaternion.BindStaticMethod("Slerp", &Nz::Quaterniond::Slerp);
quaternion.BindMethod("GetNormal", [] (Nz::LuaInstance& lua, Nz::Quaterniond& instance, std::size_t /*argumentCount*/) -> int
{
double length;
lua.Push(instance.GetNormal(&length));
lua.Push(length);
return 2;
});
quaternion.BindMethod("Normalize", [] (Nz::LuaInstance& lua, Nz::Quaterniond& instance, std::size_t /*argumentCount*/) -> int
{
double length;
instance.Normalize(&length);
lua.Push(1); //< instance
lua.Push(length);
return 2;
});
quaternion.BindStaticMethod("Normalize", [] (Nz::LuaInstance& instance) -> int
{
int argIndex = 1;
Nz::Quaterniond quat = instance.Check<Nz::Quaterniond>(&argIndex);
double length;
instance.Push(Nz::Quaterniond::Normalize(quat, &length));
instance.Push(length);
return 2;
});
quaternion.SetGetter([] (Nz::LuaInstance& lua, Nz::Quaterniond& instance)
{
std::size_t length;
const char* wxyz = lua.CheckString(2, &length);
if (length != 1)
return false;
switch (wxyz[0])
{
case 'w':
lua.Push(instance.w);
return true;
case 'x':
lua.Push(instance.x);
return true;
case 'y':
lua.Push(instance.y);
return true;
case 'z':
lua.Push(instance.z);
return true;
}
return false;
});
quaternion.SetSetter([] (Nz::LuaInstance& lua, Nz::Quaterniond& instance)
{
std::size_t length;
const char* wxyz = lua.CheckString(2, &length);
if (length != 1)
return false;
double value = lua.CheckNumber(3);
switch (wxyz[0])
{
case 'w':
instance.w = value;
return true;
case 'x':
instance.x = value;
return true;
case 'y':
instance.y = value;
return true;
case 'z':
instance.z = value;
return true;
default:
break;
}
return false;
});
}
/*********************************** Nz::Vector2 **********************************/
vector2d.Reset("Vector2");
{
vector2d.SetConstructor([] (Nz::LuaInstance& lua, Nz::Vector2d* vector, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
switch (argCount)
{
case 0:
case 2:
Nz::PlacementNew(vector, lua.CheckNumber(1, 0.0), lua.CheckNumber(2, 0.0));
return true;
case 1:
{
if (lua.IsOfType(1, Nz::LuaType_Number))
Nz::PlacementNew(vector, lua.CheckNumber(1));
else if (lua.IsOfType(1, "Vector2"))
Nz::PlacementNew(vector, *static_cast<Nz::Vector2d*>(lua.ToUserdata(1)));
else
break;
return true;
}
}
lua.Error("No matching overload for Vector2 constructor");
return false;
});
vector2d.BindMethod("__tostring", &Nz::Vector2d::ToString);
vector2d.SetGetter([] (Nz::LuaInstance& lua, Nz::Vector2d& instance)
{
switch (lua.GetType(2))
{
case Nz::LuaType_Number:
{
long long index = lua.CheckInteger(2);
if (index < 1 || index > 2)
return false;
lua.Push(instance[index - 1]);
return true;
}
case Nz::LuaType_String:
{
std::size_t length;
const char* xy = lua.CheckString(2, &length);
if (length != 1)
break;
switch (xy[0])
{
case 'x':
lua.Push(instance.x);
return true;
case 'y':
lua.Push(instance.y);
return true;
default:
break;
}
break;
}
default:
break;
}
return false;
});
vector2d.SetSetter([] (Nz::LuaInstance& lua, Nz::Vector2d& instance)
{
switch (lua.GetType(2))
{
case Nz::LuaType_Number:
{
long long index = lua.CheckInteger(2);
if (index < 1 || index > 2)
return false;
instance[index - 1] = lua.CheckNumber(3);
return true;
}
case Nz::LuaType_String:
{
std::size_t length;
const char* xy = lua.CheckString(2, &length);
if (length != 1)
break;
double value = lua.CheckNumber(3);
switch (xy[0])
{
case 'x':
instance.x = value;
return true;
case 'y':
instance.y = value;
return true;
default:
break;
}
break;
}
default:
break;
}
return false;
});
}
/*********************************** Nz::Vector3 **********************************/
vector3d.Reset("Vector3");
{
vector3d.SetConstructor([] (Nz::LuaInstance& lua, Nz::Vector3d* vector, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 3U);
switch (argCount)
{
case 0:
case 3:
Nz::PlacementNew(vector, lua.CheckNumber(1, 0.0), lua.CheckNumber(2, 0.0), lua.CheckNumber(3, 0.0));
return true;
case 1:
{
if (lua.IsOfType(1, Nz::LuaType_Number))
Nz::PlacementNew(vector, lua.CheckNumber(1));
else if (lua.IsOfType(1, "Vector2"))
Nz::PlacementNew(vector, *static_cast<Nz::Vector2d*>(lua.ToUserdata(1)));
else if (lua.IsOfType(1, "Vector3"))
Nz::PlacementNew(vector, *static_cast<Nz::Vector3d*>(lua.ToUserdata(1)));
else
break;
return true;
}
case 2:
{
if (lua.IsOfType(1, Nz::LuaType_Number))
Nz::PlacementNew(vector, lua.CheckNumber(1), *static_cast<Nz::Vector2d*>(lua.CheckUserdata(2, "Vector2")));
else if (lua.IsOfType(1, "Vector2"))
Nz::PlacementNew(vector, *static_cast<Nz::Vector2d*>(lua.ToUserdata(1)), lua.CheckNumber(2));
else
break;
return true;
}
}
lua.Error("No matching overload for constructor");
return false;
});
vector3d.BindMethod("__tostring", &Nz::Vector3d::ToString);
vector3d.SetGetter([] (Nz::LuaInstance& lua, Nz::Vector3d& instance)
{
switch (lua.GetType(2))
{
case Nz::LuaType_Number:
{
long long index = lua.CheckInteger(2);
if (index < 1 || index > 3)
return false;
lua.Push(instance[index - 1]);
return true;
}
case Nz::LuaType_String:
{
std::size_t length;
const char* xyz = lua.CheckString(2, &length);
if (length != 1)
break;
switch (xyz[0])
{
case 'x':
lua.Push(instance.x);
return true;
case 'y':
lua.Push(instance.y);
return true;
case 'z':
lua.Push(instance.z);
return true;
default:
break;
}
break;
}
default:
break;
}
return false;
});
vector3d.SetSetter([] (Nz::LuaInstance& lua, Nz::Vector3d& instance)
{
switch (lua.GetType(2))
{
case Nz::LuaType_Number:
{
long long index = lua.CheckInteger(2);
if (index < 1 || index > 3)
return false;
instance[index - 1] = lua.CheckNumber(3);
return true;
}
case Nz::LuaType_String:
{
std::size_t length;
const char* xyz = lua.CheckString(2, &length);
if (length != 1)
break;
double value = lua.CheckNumber(3);
switch (xyz[0])
{
case 'x':
instance.x = value;
return true;
case 'y':
instance.y = value;
return true;
case 'z':
instance.z = value;
return true;
default:
break;
}
break;
}
default:
break;
}
return false;
});
}
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the Math classes
*/
void LuaBinding_Math::Register(Nz::LuaInstance& instance)
{
eulerAngles.Register(instance);
matrix4d.Register(instance);
quaternion.Register(instance);
rect.Register(instance);
vector2d.Register(instance);
vector3d.Register(instance);
quaternion.PushGlobalTable(instance);
{
instance.PushField("Identity", Nz::Quaterniond::Identity());
instance.PushField("Zero", Nz::Quaterniond::Zero());
}
instance.Pop();
}
}

View File

@ -1,139 +1,147 @@
// This file was automatically generated on 26 May 2014 at 01:05:31 // This file was automatically generated on 26 May 2014 at 01:05:31
#include <NDK/LuaBinding.hpp> #include <NDK/Lua/LuaBinding_Network.hpp>
#include <NDK/LuaAPI.hpp> #include <NDK/LuaAPI.hpp>
namespace Ndk namespace Ndk
{ {
/*! std::unique_ptr<LuaBinding_Base> LuaBinding_Base::BindNetwork(LuaBinding& binding)
* \brief Binds Network module to Lua {
*/ return std::make_unique<LuaBinding_Network>(binding);
}
void LuaBinding::BindNetwork() LuaBinding_Network::LuaBinding_Network(LuaBinding& binding) :
LuaBinding_Base(binding)
{ {
/*********************************** Nz::AbstractSocket **********************************/ /*********************************** Nz::AbstractSocket **********************************/
abstractSocket.BindMethod("Close", &Nz::AbstractSocket::Close); abstractSocket.Reset("AbstractSocket");
abstractSocket.BindMethod("EnableBlocking", &Nz::AbstractSocket::EnableBlocking); {
abstractSocket.BindMethod("GetLastError", &Nz::AbstractSocket::GetLastError); abstractSocket.BindMethod("Close", &Nz::AbstractSocket::Close);
abstractSocket.BindMethod("GetState", &Nz::AbstractSocket::GetState); abstractSocket.BindMethod("EnableBlocking", &Nz::AbstractSocket::EnableBlocking);
abstractSocket.BindMethod("GetType", &Nz::AbstractSocket::GetType); abstractSocket.BindMethod("GetLastError", &Nz::AbstractSocket::GetLastError);
abstractSocket.BindMethod("IsBlockingEnabled", &Nz::AbstractSocket::IsBlockingEnabled); abstractSocket.BindMethod("GetState", &Nz::AbstractSocket::GetState);
abstractSocket.BindMethod("QueryAvailableBytes", &Nz::AbstractSocket::QueryAvailableBytes); abstractSocket.BindMethod("GetType", &Nz::AbstractSocket::GetType);
abstractSocket.BindMethod("IsBlockingEnabled", &Nz::AbstractSocket::IsBlockingEnabled);
abstractSocket.BindMethod("QueryAvailableBytes", &Nz::AbstractSocket::QueryAvailableBytes);
}
/*********************************** Nz::IpAddress **********************************/ /*********************************** Nz::IpAddress **********************************/
ipAddress.SetConstructor([] (Nz::LuaInstance& lua, Nz::IpAddress* address, std::size_t argumentCount) ipAddress.Reset("IpAddress");
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 9U); ipAddress.SetConstructor([] (Nz::LuaInstance& lua, Nz::IpAddress* instance, std::size_t argumentCount)
int argIndex = 2;
switch (argCount)
{ {
case 0: std::size_t argCount = std::min<std::size_t>(argumentCount, 9U);
Nz::PlacementNew(address);
return true;
case 1: int argIndex = 2;
Nz::PlacementNew(address, lua.CheckString(argIndex)); switch (argCount)
return true;
case 4:
case 5:
{ {
Nz::UInt8 a = lua.Check<Nz::UInt8>(&argIndex); case 0:
Nz::UInt8 b = lua.Check<Nz::UInt8>(&argIndex); Nz::PlacementNew(instance);
Nz::UInt8 c = lua.Check<Nz::UInt8>(&argIndex); return true;
Nz::UInt8 d = lua.Check<Nz::UInt8>(&argIndex);
Nz::UInt16 port = lua.Check<Nz::UInt16>(&argIndex, 0);
Nz::PlacementNew(address, a, b, c, d, port); case 1:
return true; Nz::PlacementNew(instance, lua.CheckString(argIndex));
return true;
case 4:
case 5:
{
Nz::UInt8 a = lua.Check<Nz::UInt8>(&argIndex);
Nz::UInt8 b = lua.Check<Nz::UInt8>(&argIndex);
Nz::UInt8 c = lua.Check<Nz::UInt8>(&argIndex);
Nz::UInt8 d = lua.Check<Nz::UInt8>(&argIndex);
Nz::UInt16 port = lua.Check<Nz::UInt16>(&argIndex, 0);
Nz::PlacementNew(instance, a, b, c, d, port);
return true;
}
case 8:
case 9:
{
Nz::UInt16 a = lua.Check<Nz::UInt16>(&argIndex);
Nz::UInt16 b = lua.Check<Nz::UInt16>(&argIndex);
Nz::UInt16 c = lua.Check<Nz::UInt16>(&argIndex);
Nz::UInt16 d = lua.Check<Nz::UInt16>(&argIndex);
Nz::UInt16 e = lua.Check<Nz::UInt16>(&argIndex);
Nz::UInt16 f = lua.Check<Nz::UInt16>(&argIndex);
Nz::UInt16 g = lua.Check<Nz::UInt16>(&argIndex);
Nz::UInt16 h = lua.Check<Nz::UInt16>(&argIndex);
Nz::UInt16 port = lua.Check<Nz::UInt16>(&argIndex, 0);
Nz::PlacementNew(instance, a, b, c, d, e, f, g, h, port);
return true;
}
} }
case 8: lua.Error("No matching overload for constructor");
case 9: return false;
});
ipAddress.BindMethod("GetPort", &Nz::IpAddress::GetPort);
ipAddress.BindMethod("GetProtocol", &Nz::IpAddress::GetProtocol);
ipAddress.BindMethod("IsLoopback", &Nz::IpAddress::IsLoopback);
ipAddress.BindMethod("IsValid", &Nz::IpAddress::IsValid);
ipAddress.BindMethod("ToUInt32", &Nz::IpAddress::ToUInt32);
ipAddress.BindMethod("__tostring", &Nz::IpAddress::ToString);
ipAddress.BindStaticMethod("ResolveAddress", [] (Nz::LuaInstance& instance) -> int
{
Nz::String service;
Nz::ResolveError error = Nz::ResolveError_Unknown;
int argIndex = 2;
Nz::String hostName = Nz::IpAddress::ResolveAddress(instance.Check<Nz::IpAddress>(&argIndex), &service, &error);
if (error == Nz::ResolveError_NoError)
{ {
Nz::UInt16 a = lua.Check<Nz::UInt16>(&argIndex); instance.Push(hostName);
Nz::UInt16 b = lua.Check<Nz::UInt16>(&argIndex); instance.Push(service);
Nz::UInt16 c = lua.Check<Nz::UInt16>(&argIndex); return 2;
Nz::UInt16 d = lua.Check<Nz::UInt16>(&argIndex);
Nz::UInt16 e = lua.Check<Nz::UInt16>(&argIndex);
Nz::UInt16 f = lua.Check<Nz::UInt16>(&argIndex);
Nz::UInt16 g = lua.Check<Nz::UInt16>(&argIndex);
Nz::UInt16 h = lua.Check<Nz::UInt16>(&argIndex);
Nz::UInt16 port = lua.Check<Nz::UInt16>(&argIndex, 0);
Nz::PlacementNew(address, a, b, c, d, e, f, g, h, port);
return true;
} }
} else
lua.Error("No matching overload for constructor");
return false;
});
ipAddress.BindMethod("GetPort", &Nz::IpAddress::GetPort);
ipAddress.BindMethod("GetProtocol", &Nz::IpAddress::GetProtocol);
ipAddress.BindMethod("IsLoopback", &Nz::IpAddress::IsLoopback);
ipAddress.BindMethod("IsValid", &Nz::IpAddress::IsValid);
ipAddress.BindMethod("ToUInt32", &Nz::IpAddress::ToUInt32);
ipAddress.BindMethod("__tostring", &Nz::IpAddress::ToString);
ipAddress.BindStaticMethod("ResolveAddress", [] (Nz::LuaInstance& instance) -> int
{
Nz::String service;
Nz::ResolveError error = Nz::ResolveError_Unknown;
int argIndex = 2;
Nz::String hostName = Nz::IpAddress::ResolveAddress(instance.Check<Nz::IpAddress>(&argIndex), &service, &error);
if (error == Nz::ResolveError_NoError)
{
instance.Push(hostName);
instance.Push(service);
return 2;
}
else
{
instance.PushBoolean(false);
instance.Push(error);
return 2;
}
});
ipAddress.BindStaticMethod("ResolveHostname", [] (Nz::LuaInstance& instance) -> int
{
Nz::ResolveError error = Nz::ResolveError_Unknown;
int argIndex = 2;
Nz::NetProtocol protocol = instance.Check<Nz::NetProtocol>(&argIndex);
Nz::String hostname = instance.Check<Nz::String>(&argIndex);
Nz::String service = instance.Check<Nz::String>(&argIndex, "http");
std::vector<Nz::HostnameInfo> addresses = Nz::IpAddress::ResolveHostname(protocol, hostname, service, &error);
if (error == Nz::ResolveError_NoError)
{
int index = 1;
instance.PushTable(addresses.size());
for (Nz::HostnameInfo& info : addresses)
{ {
instance.PushInteger(index++); instance.PushBoolean(false);
instance.PushTable(0, 4); instance.Push(error);
instance.PushField("Address", std::move(info.address)); return 2;
instance.PushField("CanonicalName", std::move(info.canonicalName));
instance.PushField("Protocol", std::move(info.protocol));
instance.PushField("SocketType", std::move(info.socketType));
instance.SetTable();
} }
});
return 1; ipAddress.BindStaticMethod("ResolveHostname", [] (Nz::LuaInstance& instance) -> int
}
else
{ {
instance.PushBoolean(false); Nz::ResolveError error = Nz::ResolveError_Unknown;
instance.Push(error);
return 2; int argIndex = 2;
} Nz::NetProtocol protocol = instance.Check<Nz::NetProtocol>(&argIndex);
}); Nz::String hostname = instance.Check<Nz::String>(&argIndex);
Nz::String service = instance.Check<Nz::String>(&argIndex, "http");
std::vector<Nz::HostnameInfo> addresses = Nz::IpAddress::ResolveHostname(protocol, hostname, service, &error);
if (error == Nz::ResolveError_NoError)
{
int index = 1;
instance.PushTable(addresses.size());
for (Nz::HostnameInfo& info : addresses)
{
instance.PushInteger(index++);
instance.PushTable(0, 4);
instance.PushField("Address", std::move(info.address));
instance.PushField("CanonicalName", std::move(info.canonicalName));
instance.PushField("Protocol", std::move(info.protocol));
instance.PushField("SocketType", std::move(info.socketType));
instance.SetTable();
}
return 1;
}
else
{
instance.PushBoolean(false);
instance.Push(error);
return 2;
}
});
}
} }
/*! /*!
@ -141,8 +149,7 @@ 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::RegisterNetwork(Nz::LuaInstance& instance)
{ {
// Classes // Classes
abstractSocket.Register(instance); abstractSocket.Register(instance);
@ -199,7 +206,7 @@ namespace Ndk
instance.PushField("Unknown", Nz::ResolveError_Unknown); instance.PushField("Unknown", Nz::ResolveError_Unknown);
} }
instance.SetGlobal("ResolveError"); instance.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); instance.PushTable(0, 15);

View File

@ -0,0 +1,110 @@
// Copyright (C) 2016 Jérôme Leclercq, Arnaud Cadot
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#include <NDK/Lua/LuaBinding_Renderer.hpp>
#include <NDK/LuaAPI.hpp>
#include <NDK/Lua/LuaBinding.hpp>
#include <NDK/Lua/LuaBinding_Utility.hpp>
namespace Ndk
{
std::unique_ptr<LuaBinding_Base> LuaBinding_Base::BindRenderer(LuaBinding& binding)
{
return std::make_unique<LuaBinding_Renderer>(binding);
}
LuaBinding_Renderer::LuaBinding_Renderer(LuaBinding& binding) :
LuaBinding_Base(binding)
{
LuaBinding_Utility& utility = static_cast<LuaBinding_Utility&>(*m_binding.utility);
/*********************************** Nz::Texture ***********************************/
texture.Reset("Texture");
{
texture.Inherit<Nz::AbstractImageRef>(utility.abstractImage, [] (Nz::TextureRef* textureRef) -> Nz::AbstractImageRef*
{
return reinterpret_cast<Nz::AbstractImageRef*>(textureRef); //TODO: Make a ObjectRefCast
});
texture.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::TextureRef* instance, std::size_t /*argumentCount*/)
{
Nz::PlacementNew(instance, Nz::Texture::New());
return true;
});
texture.BindMethod("Create", &Nz::Texture::Create, static_cast<Nz::UInt8>(1), 1U);
texture.BindMethod("Destroy", &Nz::Texture::Destroy);
//texture.BindMethod("Download", &Nz::Texture::Download);
texture.BindMethod("EnableMipmapping", &Nz::Texture::EnableMipmapping);
texture.BindMethod("EnsureMipmapsUpdate", &Nz::Texture::EnsureMipmapsUpdate);
texture.BindMethod("HasMipmaps", &Nz::Texture::HasMipmaps);
texture.BindMethod("InvalidateMipmaps", &Nz::Texture::InvalidateMipmaps);
texture.BindMethod("IsValid", &Nz::Texture::IsValid);
texture.BindMethod("LoadFromFile", &Nz::Texture::LoadFromFile, true, Nz::ImageParams());
//bool LoadFromImage(const Image& image, bool generateMipmaps = true);
//bool LoadFromMemory(const void* data, std::size_t size, const ImageParams& params = ImageParams(), bool generateMipmaps = true);
//bool LoadFromStream(Stream& stream, const ImageParams& params = ImageParams(), bool generateMipmaps = true);
texture.BindMethod("LoadArrayFromFile", &Nz::Texture::LoadArrayFromFile, Nz::Vector2ui(2, 2), true, Nz::ImageParams());
//bool LoadArrayFromImage(const Image& image, bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2));
//bool LoadArrayFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2));
//bool LoadArrayFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2));
//bool LoadCubemapFromFile(const String& filePath, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams());
//bool LoadCubemapFromImage(const Image& image, bool generateMipmaps = true, const CubemapParams& params = CubemapParams());
//bool LoadCubemapFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams());
//bool LoadCubemapFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams());
texture.BindMethod("LoadFaceFromFile", &Nz::Texture::LoadFaceFromFile, Nz::ImageParams());
//bool LoadFaceFromMemory(CubemapFace face, const void* data, std::size_t size, const ImageParams& params = ImageParams());
//bool LoadFaceFromStream(CubemapFace face, Stream& stream, const ImageParams& params = ImageParams());
texture.BindMethod("SaveToFile", &Nz::Texture::SaveToFile, Nz::ImageParams());
//bool SaveToStream(Stream& stream, const String& format, const ImageParams& params = ImageParams());
texture.BindMethod("SetMipmapRange", &Nz::Texture::SetMipmapRange);
texture.BindStaticMethod("IsFormatSupported", &Nz::Texture::IsFormatSupported);
texture.BindStaticMethod("IsMipmappingSupported", &Nz::Texture::IsMipmappingSupported);
texture.BindStaticMethod("IsTypeSupported", &Nz::Texture::IsTypeSupported);
}
/*********************************** Nz::TextureLibrary ***********************************/
textureLibrary.Reset("TextureLibrary");
{
textureLibrary.BindStaticMethod("Get", &Nz::TextureLibrary::Get);
textureLibrary.BindStaticMethod("Has", &Nz::TextureLibrary::Has);
textureLibrary.BindStaticMethod("Register", &Nz::TextureLibrary::Register);
textureLibrary.BindStaticMethod("Query", &Nz::TextureLibrary::Query);
textureLibrary.BindStaticMethod("Unregister", &Nz::TextureLibrary::Unregister);
}
/*********************************** Nz::TextureManager ***********************************/
textureManager.Reset("textureManager");
{
textureManager.BindStaticMethod("Clear", &Nz::TextureManager::Clear);
textureManager.BindStaticMethod("Get", &Nz::TextureManager::Get);
textureManager.BindStaticMethod("GetDefaultParameters", &Nz::TextureManager::GetDefaultParameters);
textureManager.BindStaticMethod("Purge", &Nz::TextureManager::Purge);
textureManager.BindStaticMethod("Register", &Nz::TextureManager::Register);
textureManager.BindStaticMethod("SetDefaultParameters", &Nz::TextureManager::SetDefaultParameters);
textureManager.BindStaticMethod("Unregister", &Nz::TextureManager::Unregister);
}
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the Renderer classes
*/
void LuaBinding_Renderer::Register(Nz::LuaInstance& instance)
{
texture.Register(instance);
textureLibrary.Register(instance);
textureManager.Register(instance);
}
}

View File

@ -0,0 +1,338 @@
// Copyright (C) 2016 Jérôme Leclercq, Arnaud Cadot
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#include <NDK/Lua/LuaBinding_SDK.hpp>
#include <NDK/LuaAPI.hpp>
#include <NDK/Lua/LuaBinding.hpp>
#include <NDK/Lua/LuaBinding_Utility.hpp>
#ifndef NDK_SERVER
#include <NDK/Lua/LuaBinding_Graphics.hpp>
#endif
namespace Ndk
{
std::unique_ptr<LuaBinding_Base> LuaBinding_Base::BindSDK(LuaBinding& binding)
{
return std::make_unique<LuaBinding_SDK>(binding);
}
LuaBinding_SDK::LuaBinding_SDK(LuaBinding& binding) :
LuaBinding_Base(binding)
{
#ifndef NDK_SERVER
LuaBinding_Graphics& graphics = static_cast<LuaBinding_Graphics&>(*m_binding.graphics);
#endif
LuaBinding_Utility& utility = static_cast<LuaBinding_Utility&>(*m_binding.utility);
/*********************************** Ndk::Application **********************************/
application.Reset("Application");
{
#ifndef NDK_SERVER
//application.SetMethod("AddWindow", &Application::AddWindow);
application.BindMethod("EnableConsole", &Application::EnableConsole);
application.BindMethod("EnableFPSCounter", &Application::EnableFPSCounter);
application.BindMethod("IsConsoleEnabled", &Application::IsConsoleEnabled);
application.BindMethod("IsFPSCounterEnabled", &Application::IsFPSCounterEnabled);
#endif
application.BindMethod("AddWorld", [] (Nz::LuaInstance& lua, Application* instance, std::size_t /*argumentCount*/) -> int
{
lua.Push(instance->AddWorld().CreateHandle());
return 1;
});
application.BindMethod("GetUpdateTime", &Application::GetUpdateTime);
application.BindMethod("Quit", &Application::Quit);
}
/*********************************** Ndk::Console **********************************/
#ifndef NDK_SERVER
console.Reset("Console");
{
console.Inherit<Nz::Node>(utility.node, [] (ConsoleHandle* handle) -> Nz::Node*
{
return handle->GetObject();
});
console.BindMethod("AddLine", &Console::AddLine, Nz::Color::White);
console.BindMethod("Clear", &Console::Clear);
console.BindMethod("GetCharacterSize", &Console::GetCharacterSize);
console.BindMethod("GetHistory", &Console::GetHistory);
console.BindMethod("GetHistoryBackground", &Console::GetHistoryBackground);
console.BindMethod("GetInput", &Console::GetInput);
console.BindMethod("GetInputBackground", &Console::GetInputBackground);
console.BindMethod("GetSize", &Console::GetSize);
console.BindMethod("GetTextFont", &Console::GetTextFont);
console.BindMethod("IsVisible", &Console::IsVisible);
console.BindMethod("SendCharacter", &Console::SendCharacter);
//consoleClass.SetMethod("SendEvent", &Console::SendEvent);
console.BindMethod("SetCharacterSize", &Console::SetCharacterSize);
console.BindMethod("SetSize", &Console::SetSize);
console.BindMethod("SetTextFont", &Console::SetTextFont);
console.BindMethod("Show", &Console::Show, true);
}
#endif
/*********************************** Ndk::Entity **********************************/
entity.Reset("Entity");
{
entity.BindMethod("Enable", &Entity::Enable, true);
entity.BindMethod("GetId", &Entity::GetId);
entity.BindMethod("GetWorld", &Entity::GetWorld);
entity.BindMethod("Kill", &Entity::Kill);
entity.BindMethod("IsEnabled", &Entity::IsEnabled);
entity.BindMethod("IsValid", &Entity::IsValid);
entity.BindMethod("RemoveAllComponents", &Entity::RemoveAllComponents);
entity.BindMethod("__tostring", &EntityHandle::ToString);
entity.BindMethod("AddComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle, std::size_t /*argumentCount*/) -> int
{
LuaBinding::ComponentBinding* binding = m_binding.QueryComponentIndex(instance);
return binding->adder(instance, handle);
});
entity.BindMethod("GetComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle, std::size_t /*argumentCount*/) -> int
{
LuaBinding::ComponentBinding* binding = m_binding.QueryComponentIndex(instance);
return binding->getter(instance, handle->GetComponent(binding->index));
});
entity.BindMethod("RemoveComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle, std::size_t /*argumentCount*/) -> int
{
LuaBinding::ComponentBinding* binding = m_binding.QueryComponentIndex(instance);
handle->RemoveComponent(binding->index);
return 0;
});
}
/*********************************** Ndk::NodeComponent **********************************/
nodeComponent.Reset("NodeComponent");
{
nodeComponent.Inherit<Nz::Node>(utility.node, [] (NodeComponentHandle* handle) -> Nz::Node*
{
return handle->GetObject();
});
}
/*********************************** Ndk::VelocityComponent **********************************/
velocityComponent.Reset("VelocityComponent");
{
velocityComponent.SetGetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance)
{
std::size_t length;
const char* member = lua.CheckString(2, &length);
if (std::strcmp(member, "Linear") == 0)
{
lua.Push(instance->linearVelocity);
return true;
}
return false;
});
velocityComponent.SetSetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance)
{
std::size_t length;
const char* member = lua.CheckString(2, &length);
int argIndex = 3;
if (std::strcmp(member, "Linear") == 0)
{
instance->linearVelocity = lua.Check<Nz::Vector3f>(&argIndex);
return true;
}
return false;
});
}
/*********************************** Ndk::World **********************************/
world.Reset("World");
{
world.BindMethod("CreateEntity", &World::CreateEntity);
world.BindMethod("CreateEntities", &World::CreateEntities);
world.BindMethod("Clear", &World::Clear);
}
#ifndef NDK_SERVER
/*********************************** Ndk::CameraComponent **********************************/
cameraComponent.Reset("CameraComponent");
{
cameraComponent.Inherit<Nz::AbstractViewer>(graphics.abstractViewer, [] (CameraComponentHandle* handle) -> Nz::AbstractViewer*
{
return handle->GetObject();
});
cameraComponent.BindMethod("GetFOV", &Ndk::CameraComponent::GetFOV);
cameraComponent.BindMethod("GetLayer", &Ndk::CameraComponent::GetLayer);
cameraComponent.BindMethod("SetFOV", &Ndk::CameraComponent::SetFOV);
cameraComponent.BindMethod("SetLayer", &Ndk::CameraComponent::SetLayer);
cameraComponent.BindMethod("SetProjectionType", &Ndk::CameraComponent::SetProjectionType);
cameraComponent.BindMethod("SetSize", (void(Ndk::CameraComponent::*)(const Nz::Vector2f&)) &Ndk::CameraComponent::SetSize);
//cameraComponent.BindMethod("SetTarget", &Ndk::CameraComponent::SetTarget);
cameraComponent.BindMethod("SetTargetRegion", &Ndk::CameraComponent::SetTargetRegion);
cameraComponent.BindMethod("SetViewport", &Ndk::CameraComponent::SetViewport);
cameraComponent.BindMethod("SetZFar", &Ndk::CameraComponent::SetZFar);
cameraComponent.BindMethod("SetZNear", &Ndk::CameraComponent::SetZNear);
}
/*********************************** Ndk::GraphicsComponent **********************************/
graphicsComponent.Reset("GraphicsComponent");
{
graphicsComponent.BindMethod("Attach", [] (Nz::LuaInstance& lua, Ndk::GraphicsComponent* instance, std::size_t argumentCount) -> int
{
/*
void Attach(Nz::InstancedRenderableRef renderable, int renderOrder = 0);
void Attach(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& localMatrix, int renderOrder = 0);
*/
std::size_t argCount = std::min<std::size_t>(argumentCount, 3U);
switch (argCount)
{
case 1:
{
int argIndex = 2;
instance->Attach(lua.Check<Nz::InstancedRenderableRef>(&argIndex));
return 0;
}
case 2:
{
int argIndex = 2;
Nz::InstancedRenderableRef renderable = lua.Check<Nz::InstancedRenderableRef>(&argIndex);
if (lua.IsOfType(argIndex, Nz::LuaType_Number))
{
int renderOrder = lua.Check<int>(&argIndex);
instance->Attach(renderable, renderOrder);
}
else if (lua.IsOfType(argIndex, "Matrix4"))
{
Nz::Matrix4f localMatrix = lua.Check<Nz::Matrix4f>(&argIndex);
instance->Attach(renderable, localMatrix);
}
else
break;
return 0;
}
case 3:
{
int argIndex = 2;
Nz::InstancedRenderableRef renderable = lua.Check<Nz::InstancedRenderableRef>(&argIndex);
Nz::Matrix4f localMatrix = lua.Check<Nz::Matrix4f>(&argIndex);
int renderOrder = lua.Check<int>(&argIndex);
instance->Attach(renderable, localMatrix, renderOrder);
return 0;
}
}
lua.Error("No matching overload for method GetMemoryUsage");
return 0;
});
}
#endif
// Components functions
m_binding.BindComponent<NodeComponent>("Node");
m_binding.BindComponent<VelocityComponent>("Velocity");
#ifndef NDK_SERVER
m_binding.BindComponent<CameraComponent>("Camera");
m_binding.BindComponent<GraphicsComponent>("Graphics");
#endif
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the SDK classes
*/
void LuaBinding_SDK::Register(Nz::LuaInstance& instance)
{
// Classes
application.Register(instance);
entity.Register(instance);
nodeComponent.Register(instance);
velocityComponent.Register(instance);
world.Register(instance);
#ifndef NDK_SERVER
cameraComponent.Register(instance);
console.Register(instance);
graphicsComponent.Register(instance);
#endif
// Enums
}
/*!
* \brief Gets the index of the component
* \return A pointer to the binding linked to a component
*
* \param instance Lua instance that will interact with the component
* \param argIndex Index of the component
*/
LuaBinding::ComponentBinding* LuaBinding::QueryComponentIndex(Nz::LuaInstance& instance, int argIndex)
{
switch (instance.GetType(argIndex))
{
case Nz::LuaType_Number:
{
ComponentIndex componentIndex = instance.Check<ComponentIndex>(&argIndex);
if (componentIndex > m_componentBinding.size())
{
instance.Error("Invalid component index");
return nullptr;
}
ComponentBinding& binding = m_componentBinding[componentIndex];
if (binding.name.IsEmpty())
{
instance.Error("Invalid component index");
return nullptr;
}
return &binding;
}
case Nz::LuaType_String:
{
const char* key = instance.CheckString(argIndex);
auto it = m_componentBindingByName.find(key);
if (it == m_componentBindingByName.end())
{
instance.Error("Invalid component name");
return nullptr;
}
return &m_componentBinding[it->second];
}
default:
break;
}
instance.Error("Invalid component index at #" + Nz::String::Number(argIndex));
return nullptr;
}
}

View File

@ -0,0 +1,446 @@
// 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_Utility.hpp>
#include <NDK/LuaAPI.hpp>
namespace Ndk
{
std::unique_ptr<LuaBinding_Base> LuaBinding_Base::BindUtility(LuaBinding& binding)
{
return std::make_unique<LuaBinding_Utility>(binding);
}
LuaBinding_Utility::LuaBinding_Utility(LuaBinding& binding) :
LuaBinding_Base(binding)
{
/*********************************** Nz::AbstractImage **********************************/
abstractImage.Reset("AbstractImage");
{
abstractImage.BindMethod("GetBytesPerPixel", &Nz::AbstractImage::GetBytesPerPixel);
abstractImage.BindMethod("GetDepth", &Nz::AbstractImage::GetDepth, static_cast<Nz::UInt8>(0));
abstractImage.BindMethod("GetFormat", &Nz::AbstractImage::GetFormat);
abstractImage.BindMethod("GetHeight", &Nz::AbstractImage::GetHeight, static_cast<Nz::UInt8>(0));
abstractImage.BindMethod("GetLevelCount", &Nz::AbstractImage::GetLevelCount);
abstractImage.BindMethod("GetMaxLevel", &Nz::AbstractImage::GetMaxLevel);
abstractImage.BindMethod("GetSize", &Nz::AbstractImage::GetSize, static_cast<Nz::UInt8>(0));
abstractImage.BindMethod("GetType", &Nz::AbstractImage::GetType);
abstractImage.BindMethod("GetWidth", &Nz::AbstractImage::GetWidth, static_cast<Nz::UInt8>(0));
abstractImage.BindMethod("IsCompressed", &Nz::AbstractImage::IsCompressed);
abstractImage.BindMethod("IsCubemap", &Nz::AbstractImage::IsCubemap);
abstractImage.BindMethod("GetMemoryUsage", [] (Nz::LuaInstance& lua, Nz::AbstractImage* instance, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 1U);
switch (argCount)
{
case 0:
return lua.Push(instance->GetMemoryUsage());
case 1:
{
int argIndex = 2;
Nz::UInt8 level(lua.Check<Nz::UInt8>(&argIndex));
return lua.Push(instance->GetMemoryUsage(level));
}
}
lua.Error("No matching overload for method GetMemoryUsage");
return 0;
});
abstractImage.BindMethod("Update", [] (Nz::LuaInstance& lua, Nz::AbstractImage* instance, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 6U);
int argIndex = 2;
std::size_t bufferSize = 0;
const Nz::UInt8* pixels = reinterpret_cast<const Nz::UInt8*>(lua.CheckString(argIndex++, &bufferSize));
if (argCount < 2 || lua.IsOfType(2, Nz::LuaType_Number))
{
// bool Update(const UInt8* pixels, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0)
unsigned int srcWidth = lua.Check<unsigned int>(&argIndex, 0);
unsigned int srcHeight = lua.Check<unsigned int>(&argIndex, 0);
Nz::UInt8 level = lua.Check<Nz::UInt8>(&argIndex, 0);
///TODO: Buffer checks (Nz::ByteBufferView ?)
return lua.Push(instance->Update(pixels, srcWidth, srcHeight, level));
}
/* Disabled until Box and Rect have been ported
else if (lua.IsOfType(2, "Box"))
{
// bool Update(const UInt8* pixels, const Boxui& box, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0)
Nz::Boxui box = lua.Check<Nz::Boxui>(&argIndex);
unsigned int srcWidth = lua.Check<unsigned int>(&argIndex, 0);
unsigned int srcHeight = lua.Check<unsigned int>(&argIndex, 0);
Nz::UInt8 level = lua.Check<Nz::UInt8>(&argIndex, 0);
///TODO: Buffer checks (Nz::ByteBufferView ?)
return lua.Push(abstractImage->Update(pixels, srcWidth, srcHeight, level));
}
else if (lua.IsOfType(2, "Rect"))
{
// bool Update(const UInt8* pixels, const Rectui& rect, unsigned int z = 0, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0)
Nz::Rectui box = lua.Check<Nz::Rectui>(&argIndex);
unsigned int srcWidth = lua.Check<unsigned int>(&argIndex, 0);
unsigned int srcHeight = lua.Check<unsigned int>(&argIndex, 0);
Nz::UInt8 level = lua.Check<Nz::UInt8>(&argIndex, 0);
///TODO: Buffer checks (Nz::ByteBufferView ?)
return lua.Push(abstractImage->Update(pixels, srcWidth, srcHeight, level));
}*/
lua.Error("No matching overload for method Update");
return 0;
});
}
/*********************************** Nz::Font **********************************/
font.Reset("Font");
{
font.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::FontRef* instance, std::size_t /*argumentCount*/)
{
Nz::PlacementNew(instance, Nz::Font::New());
return true;
});
font.BindMethod("ClearGlyphCache", &Nz::Font::ClearGlyphCache);
font.BindMethod("ClearKerningCache", &Nz::Font::ClearKerningCache);
font.BindMethod("ClearSizeInfoCache", &Nz::Font::ClearSizeInfoCache);
font.BindMethod("Destroy", &Nz::Font::Destroy);
font.BindMethod("GetCachedGlyphCount", [] (Nz::LuaInstance& lua, Nz::FontRef& instance, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
int argIndex = 2;
switch (argCount)
{
case 0:
lua.Push(instance->GetCachedGlyphCount());
return 1;
case 2:
{
unsigned int characterSize = lua.Check<unsigned int>(&argIndex);
Nz::UInt32 style = lua.Check<Nz::UInt32>(&argIndex);
lua.Push(instance->GetCachedGlyphCount(characterSize, style));
return 1;
}
}
lua.Error("No matching overload for method GetCachedGlyphCount");
return 0;
});
font.BindMethod("GetFamilyName", &Nz::Font::GetFamilyName);
font.BindMethod("GetKerning", &Nz::Font::GetKerning);
font.BindMethod("GetGlyphBorder", &Nz::Font::GetGlyphBorder);
font.BindMethod("GetMinimumStepSize", &Nz::Font::GetMinimumStepSize);
font.BindMethod("GetSizeInfo", &Nz::Font::GetSizeInfo);
font.BindMethod("GetStyleName", &Nz::Font::GetStyleName);
font.BindMethod("IsValid", &Nz::Font::IsValid);
font.BindMethod("Precache", (bool(Nz::Font::*)(unsigned int, Nz::UInt32, const Nz::String&) const) &Nz::Font::Precache);
font.BindMethod("OpenFromFile", &Nz::Font::OpenFromFile, Nz::FontParams());
font.BindMethod("SetGlyphBorder", &Nz::Font::SetGlyphBorder);
font.BindMethod("SetMinimumStepSize", &Nz::Font::SetMinimumStepSize);
font.BindStaticMethod("GetDefault", &Nz::Font::GetDefault);
font.BindStaticMethod("GetDefaultGlyphBorder", &Nz::Font::GetDefaultGlyphBorder);
font.BindStaticMethod("GetDefaultMinimumStepSize", &Nz::Font::GetDefaultMinimumStepSize);
font.BindStaticMethod("SetDefaultGlyphBorder", &Nz::Font::SetDefaultGlyphBorder);
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 **********************************/
node.Reset("Node");
{
node.BindMethod("GetBackward", &Nz::Node::GetBackward);
//nodeClass.SetMethod("GetChilds", &Nz::Node::GetChilds);
node.BindMethod("GetDown", &Nz::Node::GetDown);
node.BindMethod("GetForward", &Nz::Node::GetForward);
node.BindMethod("GetInheritPosition", &Nz::Node::GetInheritPosition);
node.BindMethod("GetInheritRotation", &Nz::Node::GetInheritRotation);
node.BindMethod("GetInheritScale", &Nz::Node::GetInheritScale);
node.BindMethod("GetInitialPosition", &Nz::Node::GetInitialPosition);
//nodeClass.SetMethod("GetInitialRotation", &Nz::Node::GetInitialRotation);
node.BindMethod("GetInitialScale", &Nz::Node::GetInitialScale);
node.BindMethod("GetLeft", &Nz::Node::GetLeft);
node.BindMethod("GetNodeType", &Nz::Node::GetNodeType);
//nodeClass.SetMethod("GetParent", &Nz::Node::GetParent);
node.BindMethod("GetPosition", &Nz::Node::GetPosition, Nz::CoordSys_Global);
node.BindMethod("GetRight", &Nz::Node::GetRight);
//nodeClass.SetMethod("GetRotation", &Nz::Node::GetRotation, Nz::CoordSys_Global);
node.BindMethod("GetScale", &Nz::Node::GetScale, Nz::CoordSys_Global);
//nodeClass.SetMethod("GetTransformMatrix", &Nz::Node::GetTransformMatrix);
node.BindMethod("GetUp", &Nz::Node::GetUp);
node.BindMethod("HasChilds", &Nz::Node::HasChilds);
node.BindMethod("GetBackward", &Nz::Node::GetBackward);
node.BindMethod("GetDown", &Nz::Node::GetDown);
node.BindMethod("GetForward", &Nz::Node::GetForward);
node.BindMethod("GetInheritPosition", &Nz::Node::GetInheritPosition);
node.BindMethod("GetInheritRotation", &Nz::Node::GetInheritRotation);
node.BindMethod("GetInheritScale", &Nz::Node::GetInheritScale);
node.BindMethod("GetInitialPosition", &Nz::Node::GetInitialPosition);
node.BindMethod("GetInitialRotation", &Nz::Node::GetInitialRotation);
node.BindMethod("GetInitialScale", &Nz::Node::GetInitialScale);
node.BindMethod("GetLeft", &Nz::Node::GetLeft);
node.BindMethod("GetNodeType", &Nz::Node::GetNodeType);
node.BindMethod("GetPosition", &Nz::Node::GetPosition, Nz::CoordSys_Global);
node.BindMethod("GetRight", &Nz::Node::GetRight);
node.BindMethod("GetRotation", &Nz::Node::GetRotation, Nz::CoordSys_Global);
node.BindMethod("GetScale", &Nz::Node::GetScale, Nz::CoordSys_Global);
node.BindMethod("GetUp", &Nz::Node::GetUp);
node.BindMethod("SetInitialPosition", (void(Nz::Node::*)(const Nz::Vector3f&)) &Nz::Node::SetInitialPosition);
node.BindMethod("SetInitialRotation", (void(Nz::Node::*)(const Nz::Quaternionf&)) &Nz::Node::SetInitialRotation);
node.BindMethod("SetPosition", (void(Nz::Node::*)(const Nz::Vector3f&, Nz::CoordSys)) &Nz::Node::SetPosition, Nz::CoordSys_Local);
node.BindMethod("SetRotation", (void(Nz::Node::*)(const Nz::Quaternionf&, Nz::CoordSys)) &Nz::Node::SetRotation, Nz::CoordSys_Local);
node.BindMethod("Move", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
Nz::Vector3f offset = lua.Check<Nz::Vector3f>(&argIndex);
Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local);
instance.Move(offset, coordSys);
return 0;
});
node.BindMethod("Rotate", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
Nz::Quaternionf rotation = lua.Check<Nz::Quaternionf>(&argIndex);
Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local);
instance.Rotate(rotation, coordSys);
return 0;
});
node.BindMethod("Scale", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
int argIndex = 2;
switch (argCount)
{
case 1:
{
if (lua.IsOfType(argIndex, Nz::LuaType_Number))
instance.Scale(lua.Check<float>(&argIndex));
else
instance.Scale(lua.Check<Nz::Vector3f>(&argIndex));
return 0;
}
case 3:
instance.Scale(lua.Check<Nz::Vector3f>(&argIndex));
return 0;
}
lua.Error("No matching overload for method Scale");
return 0;
});
node.BindMethod("SetScale", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
int argIndex = 2;
switch (argCount)
{
case 1:
case 2:
{
if (lua.IsOfType(argIndex, Nz::LuaType_Number))
{
float scale = lua.Check<float>(&argIndex);
Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local);
instance.SetScale(scale, coordSys);
}
else
instance.SetScale(lua.Check<Nz::Vector3f>(&argIndex));
return 0;
}
case 3:
case 4:
{
Nz::Vector3f scale = lua.Check<Nz::Vector3f>(&argIndex);
Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local);
instance.SetScale(scale, coordSys);
return 0;
}
}
lua.Error("No matching overload for method SetScale");
return 0;
});
node.BindMethod("SetInitialScale", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
int argIndex = 2;
switch (argCount)
{
case 1:
{
if (lua.IsOfType(argIndex, Nz::LuaType_Number))
instance.SetInitialScale(lua.Check<float>(&argIndex));
else
instance.SetInitialScale(lua.Check<Nz::Vector2f>(&argIndex));
return 0;
}
case 2:
case 3:
instance.SetInitialScale(lua.Check<Nz::Vector3f>(&argIndex));
return 0;
}
lua.Error("No matching overload for method SetInitialScale");
return 0;
});
}
}
/*!
* \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_Utility::Register(Nz::LuaInstance& instance)
{
abstractImage.Register(instance);
font.Register(instance);
keyboard.Register(instance);
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

@ -2,7 +2,7 @@
#include <NDK/LuaAPI.hpp> #include <NDK/LuaAPI.hpp>
#include <Nazara/Core/ErrorFlags.hpp> #include <Nazara/Core/ErrorFlags.hpp>
#include <NDK/LuaBinding.hpp> #include <NDK/Lua/LuaBinding.hpp>
namespace Ndk namespace Ndk
{ {

View File

@ -1,107 +0,0 @@
// This file was automatically generated on 26 May 2014 at 01:05:31
#include <NDK/LuaBinding.hpp>
namespace Ndk
{
/*!
* \ingroup NDK
* \class Ndk::LuaBinding
* \brief NDK class that represents the binding between the engine & the SDK with the Lua scripting
*/
/*!
* \brief Binds modules to Lua
*/
LuaBinding::LuaBinding() :
// Core
clock("Clock"),
directory("Directory"),
file("File"),
stream("Stream"),
// Math
eulerAngles("EulerAngles"),
matrix4d("Matrix4"),
quaternion("Quaternion"),
rect("Rect"),
vector2d("Vector2"),
vector3d("Vector3"),
// Network
abstractSocket("AbstractSocket"),
ipAddress("IpAddress"),
// Utility
abstractImage("AbstractImage"),
font("Font"),
node("Node"),
// SDK
application("Application"),
entity("Entity"),
nodeComponent("NodeComponent"),
velocityComponent("VelocityComponent"),
world("World")
#ifndef NDK_SERVER
,
// Audio
music("Music"),
sound("Sound"),
soundBuffer("SoundBuffer"),
soundEmitter("SoundEmitter"),
// Graphics
instancedRenderable("InstancedRenderable"),
material("Material"),
model("Model"),
sprite("Sprite"),
spriteLibrary("SpriteLibrary"),
textureLibrary("TextureLibrary"),
textureManager("TextureManager"),
// Renderer
texture("Texture"),
// SDK
console("Console"),
graphicsComponent("GraphicsComponent")
#endif
{
BindCore();
BindMath();
BindNetwork();
BindSDK();
BindUtility();
#ifndef NDK_SERVER
BindAudio();
BindGraphics();
BindRenderer();
#endif
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the engine & SDK
*/
void LuaBinding::RegisterClasses(Nz::LuaInstance& instance)
{
RegisterCore(instance);
RegisterMath(instance);
RegisterNetwork(instance);
RegisterSDK(instance);
RegisterUtility(instance);
#ifndef NDK_SERVER
RegisterAudio(instance);
RegisterGraphics(instance);
RegisterRenderer(instance);
#endif
}
}

View File

@ -1,185 +0,0 @@
// This file was automatically generated on 26 May 2014 at 01:05:31
#include <NDK/LuaBinding.hpp>
#include <Nazara/Core/MemoryHelper.hpp>
#include <NDK/LuaAPI.hpp>
namespace Ndk
{
/*!
* \brief Binds Audio module to Lua
*/
void LuaBinding::BindAudio()
{
/*********************************** Nz::Music **********************************/
music.Inherit(soundEmitter);
music.BindDefaultConstructor();
//musicClass.SetMethod("Create", &Nz::Music::Create);
//musicClass.SetMethod("Destroy", &Nz::Music::Destroy);
music.BindMethod("EnableLooping", &Nz::Music::EnableLooping);
music.BindMethod("GetDuration", &Nz::Music::GetDuration);
music.BindMethod("GetFormat", &Nz::Music::GetFormat);
music.BindMethod("GetPlayingOffset", &Nz::Music::GetPlayingOffset);
music.BindMethod("GetSampleCount", &Nz::Music::GetSampleCount);
music.BindMethod("GetSampleRate", &Nz::Music::GetSampleRate);
music.BindMethod("GetStatus", &Nz::Music::GetStatus);
music.BindMethod("IsLooping", &Nz::Music::IsLooping);
music.BindMethod("OpenFromFile", &Nz::Music::OpenFromFile, Nz::MusicParams());
music.BindMethod("Pause", &Nz::Music::Pause);
music.BindMethod("Play", &Nz::Music::Play);
music.BindMethod("SetPlayingOffset", &Nz::Music::SetPlayingOffset);
music.BindMethod("Stop", &Nz::Music::Stop);
// Manual
music.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Music& music, std::size_t /*argumentCount*/) -> int
{
Nz::StringStream stream("Music(");
stream << music.GetFilePath() << ')';
lua.PushString(stream);
return 1;
});
/*********************************** Nz::Sound **********************************/
sound.Inherit(soundEmitter);
sound.BindDefaultConstructor();
sound.BindMethod("GetBuffer", &Nz::Sound::GetBuffer);
sound.BindMethod("IsPlayable", &Nz::Sound::IsPlayable);
sound.BindMethod("IsPlaying", &Nz::Sound::IsPlaying);
sound.BindMethod("LoadFromFile", &Nz::Sound::LoadFromFile, Nz::SoundBufferParams());
sound.BindMethod("SetPlayingOffset", &Nz::Sound::SetPlayingOffset);
// Manual
sound.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Sound& sound, std::size_t /*argumentCount*/) -> int
{
Nz::StringStream stream("Sound(");
if (const Nz::SoundBuffer* buffer = sound.GetBuffer())
stream << buffer;
stream << ')';
lua.PushString(stream);
return 1;
});
/*********************************** Nz::SoundBuffer **********************************/
soundBuffer.SetConstructor([] (Nz::LuaInstance& lua, Nz::SoundBufferRef* instance, std::size_t argumentCount)
{
NazaraUnused(lua);
NazaraUnused(argumentCount);
Nz::PlacementNew(instance, Nz::SoundBuffer::New());
return true;
});
soundBuffer.BindMethod("Destroy", &Nz::SoundBuffer::Destroy);
soundBuffer.BindMethod("GetDuration", &Nz::SoundBuffer::GetDuration);
soundBuffer.BindMethod("GetFormat", &Nz::SoundBuffer::GetFormat);
soundBuffer.BindMethod("GetSampleCount", &Nz::SoundBuffer::GetSampleCount);
soundBuffer.BindMethod("GetSampleRate", &Nz::SoundBuffer::GetSampleRate);
soundBuffer.BindMethod("IsValid", &Nz::SoundBuffer::IsValid);
soundBuffer.BindMethod("LoadFromFile", &Nz::SoundBuffer::LoadFromFile, Nz::SoundBufferParams());
soundBuffer.BindStaticMethod("IsFormatSupported", &Nz::SoundBuffer::IsFormatSupported);
// Manual
soundBuffer.BindMethod("Create", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int
{
int index = 2;
Nz::AudioFormat format = lua.Check<Nz::AudioFormat>(&index);
unsigned int sampleCount = lua.Check<unsigned int>(&index);
unsigned int sampleRate = lua.Check<unsigned int>(&index);
std::size_t bufferSize = 0;
const char* buffer = lua.CheckString(index, &bufferSize);
lua.ArgCheck(buffer && bufferSize >= sampleCount * sizeof(Nz::Int16), index, "Invalid buffer");
lua.PushBoolean(instance->Create(format, sampleCount, sampleRate, reinterpret_cast<const Nz::Int16*>(buffer)));
return 1;
});
soundBuffer.BindMethod("GetSamples", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int
{
lua.PushString(reinterpret_cast<const char*>(instance->GetSamples()), instance->GetSampleCount() * sizeof(Nz::Int16));
return 1;
});
soundBuffer.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int
{
Nz::StringStream stream("SoundBuffer(");
if (instance->IsValid())
{
Nz::String filePath = instance->GetFilePath();
if (!filePath.IsEmpty())
stream << "File: " << filePath << ", ";
stream << "Duration: " << instance->GetDuration() / 1000.f << "s";
}
stream << ')';
lua.PushString(stream);
return 1;
});
/*********************************** Nz::SoundEmitter **********************************/
soundEmitter.BindMethod("EnableLooping", &Nz::SoundEmitter::EnableLooping);
soundEmitter.BindMethod("EnableSpatialization", &Nz::SoundEmitter::EnableSpatialization);
soundEmitter.BindMethod("GetAttenuation", &Nz::SoundEmitter::GetAttenuation);
soundEmitter.BindMethod("GetDuration", &Nz::SoundEmitter::GetDuration);
soundEmitter.BindMethod("GetMinDistance", &Nz::SoundEmitter::GetMinDistance);
soundEmitter.BindMethod("GetPitch", &Nz::SoundEmitter::GetPitch);
soundEmitter.BindMethod("GetPlayingOffset", &Nz::SoundEmitter::GetPlayingOffset);
soundEmitter.BindMethod("GetPosition", &Nz::Sound::GetPosition);
soundEmitter.BindMethod("GetStatus", &Nz::SoundEmitter::GetStatus);
soundEmitter.BindMethod("GetVelocity", &Nz::Sound::GetVelocity);
soundEmitter.BindMethod("GetVolume", &Nz::SoundEmitter::GetVolume);
soundEmitter.BindMethod("IsLooping", &Nz::SoundEmitter::IsLooping);
soundEmitter.BindMethod("IsSpatialized", &Nz::SoundEmitter::IsSpatialized);
soundEmitter.BindMethod("Pause", &Nz::SoundEmitter::Pause);
soundEmitter.BindMethod("Play", &Nz::SoundEmitter::Play);
soundEmitter.BindMethod("SetAttenuation", &Nz::SoundEmitter::SetAttenuation);
soundEmitter.BindMethod("SetMinDistance", &Nz::SoundEmitter::SetMinDistance);
soundEmitter.BindMethod("SetPitch", &Nz::SoundEmitter::SetPitch);
soundEmitter.BindMethod("SetPosition", (void(Nz::SoundEmitter::*)(const Nz::Vector3f&)) &Nz::SoundEmitter::SetPosition);
soundEmitter.BindMethod("SetVelocity", (void(Nz::SoundEmitter::*)(const Nz::Vector3f&)) &Nz::SoundEmitter::SetVelocity);
soundEmitter.BindMethod("SetVolume", &Nz::SoundEmitter::SetVolume);
soundEmitter.BindMethod("Stop", &Nz::SoundEmitter::Stop);
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the Audio classes
*/
void LuaBinding::RegisterAudio(Nz::LuaInstance& instance)
{
music.Register(instance);
sound.Register(instance);
soundBuffer.Register(instance);
soundEmitter.Register(instance);
}
}

View File

@ -1,318 +0,0 @@
// This file was automatically generated on 26 May 2014 at 01:05:31
#include <NDK/LuaBinding.hpp>
#include <Nazara/Core/MemoryHelper.hpp>
#include <NDK/LuaAPI.hpp>
namespace Ndk
{
/*!
* \brief Binds Core module to Lua
*/
void LuaBinding::BindCore()
{
/*********************************** Nz::Clock **********************************/
clock.SetConstructor([](Nz::LuaInstance& lua, Nz::Clock* clock, std::size_t /*argumentCount*/)
{
int argIndex = 2;
Nz::Int64 startingValue = lua.Check<Nz::Int64>(&argIndex, 0);
bool paused = lua.Check<bool>(&argIndex, false);
Nz::PlacementNew(clock, startingValue, paused);
return true;
});
clock.BindMethod("GetMicroseconds", &Nz::Clock::GetMicroseconds);
clock.BindMethod("GetMilliseconds", &Nz::Clock::GetMilliseconds);
clock.BindMethod("GetSeconds", &Nz::Clock::GetSeconds);
clock.BindMethod("IsPaused", &Nz::Clock::IsPaused);
clock.BindMethod("Pause", &Nz::Clock::Pause);
clock.BindMethod("Restart", &Nz::Clock::Restart);
clock.BindMethod("Unpause", &Nz::Clock::Unpause);
// Manual
clock.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Clock& clock, std::size_t /*argumentCount*/) -> int {
Nz::StringStream stream("Clock(Elapsed: ");
stream << clock.GetSeconds();
stream << "s, Paused: ";
stream << clock.IsPaused();
stream << ')';
lua.PushString(stream);
return 1;
});
/********************************* Nz::Directory ********************************/
directory.SetConstructor([](Nz::LuaInstance& lua, Nz::Directory* directory, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 1U);
int argIndex = 2;
switch (argCount)
{
case 0:
Nz::PlacementNew(directory);
return true;
case 1:
Nz::PlacementNew(directory, lua.Check<Nz::String>(&argIndex));
return true;
}
return false;
});
directory.BindMethod("Close", &Nz::Directory::Close);
directory.BindMethod("Exists", &Nz::Directory::Exists);
directory.BindMethod("GetPath", &Nz::Directory::GetPath);
directory.BindMethod("GetPattern", &Nz::Directory::GetPattern);
directory.BindMethod("GetResultName", &Nz::Directory::GetResultName);
directory.BindMethod("GetResultPath", &Nz::Directory::GetResultPath);
directory.BindMethod("GetResultSize", &Nz::Directory::GetResultSize);
directory.BindMethod("IsOpen", &Nz::Directory::IsOpen);
directory.BindMethod("IsResultDirectory", &Nz::Directory::IsResultDirectory);
directory.BindMethod("NextResult", &Nz::Directory::NextResult, true);
directory.BindMethod("Open", &Nz::Directory::Open);
directory.BindMethod("SetPath", &Nz::Directory::SetPath);
directory.BindMethod("SetPattern", &Nz::Directory::SetPattern);
directory.BindStaticMethod("Copy", Nz::Directory::Copy);
directory.BindStaticMethod("Create", Nz::Directory::Create);
directory.BindStaticMethod("Exists", Nz::Directory::Exists);
directory.BindStaticMethod("GetCurrent", Nz::Directory::GetCurrent);
directory.BindStaticMethod("Remove", Nz::Directory::Remove);
directory.BindStaticMethod("SetCurrent", Nz::Directory::SetCurrent);
// Manual
directory.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Directory& directory, std::size_t /*argumentCount*/) -> int {
Nz::StringStream stream("Directory(");
stream << directory.GetPath();
stream << ')';
lua.PushString(stream);
return 1;
});
/*********************************** Nz::Stream ***********************************/
stream.BindMethod("EnableTextMode", &Nz::Stream::EnableTextMode);
stream.BindMethod("Flush", &Nz::Stream::Flush);
stream.BindMethod("GetCursorPos", &Nz::Stream::GetCursorPos);
stream.BindMethod("GetDirectory", &Nz::Stream::GetDirectory);
stream.BindMethod("GetPath", &Nz::Stream::GetPath);
stream.BindMethod("GetOpenMode", &Nz::Stream::GetOpenMode);
stream.BindMethod("GetStreamOptions", &Nz::Stream::GetStreamOptions);
stream.BindMethod("GetSize", &Nz::Stream::GetSize);
stream.BindMethod("ReadLine", &Nz::Stream::ReadLine, 0U);
stream.BindMethod("IsReadable", &Nz::Stream::IsReadable);
stream.BindMethod("IsSequential", &Nz::Stream::IsSequential);
stream.BindMethod("IsTextModeEnabled", &Nz::Stream::IsTextModeEnabled);
stream.BindMethod("IsWritable", &Nz::Stream::IsWritable);
stream.BindMethod("SetCursorPos", &Nz::Stream::SetCursorPos);
stream.BindMethod("Read", [] (Nz::LuaInstance& lua, Nz::Stream& stream, std::size_t /*argumentCount*/) -> int {
int argIndex = 2;
std::size_t length = lua.Check<std::size_t>(&argIndex);
std::unique_ptr<char[]> buffer(new char[length]);
std::size_t readLength = stream.Read(buffer.get(), length);
lua.PushString(Nz::String(buffer.get(), readLength));
return 1;
});
stream.BindMethod("Write", [] (Nz::LuaInstance& lua, Nz::Stream& stream, std::size_t /*argumentCount*/) -> int {
int argIndex = 2;
std::size_t bufferSize = 0;
const char* buffer = lua.CheckString(argIndex, &bufferSize);
if (stream.IsTextModeEnabled())
lua.Push(stream.Write(Nz::String(buffer, bufferSize)));
else
lua.Push(stream.Write(buffer, bufferSize));
return 1;
});
/*********************************** Nz::File ***********************************/
file.Inherit(stream);
file.SetConstructor([] (Nz::LuaInstance& lua, Nz::File* file, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 1U);
int argIndex = 2;
switch (argCount)
{
case 0:
Nz::PlacementNew(file);
return true;
case 1:
{
Nz::String filePath = lua.Check<Nz::String>(&argIndex);
Nz::PlacementNew(file, filePath);
return true;
}
case 2:
{
Nz::String filePath = lua.Check<Nz::String>(&argIndex);
Nz::UInt32 openMode = lua.Check<Nz::UInt32>(&argIndex);
Nz::PlacementNew(file, filePath, openMode);
return true;
}
}
lua.Error("No matching overload for File constructor");
return false;
});
file.BindMethod("Close", &Nz::File::Close);
file.BindMethod("Copy", &Nz::File::Copy);
file.BindMethod("Delete", &Nz::File::Delete);
file.BindMethod("EndOfFile", &Nz::File::EndOfFile);
file.BindMethod("Exists", &Nz::File::Exists);
file.BindMethod("GetCreationTime", &Nz::File::GetCreationTime);
file.BindMethod("GetFileName", &Nz::File::GetFileName);
file.BindMethod("GetLastAccessTime", &Nz::File::GetLastAccessTime);
file.BindMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime);
file.BindMethod("IsOpen", &Nz::File::IsOpen);
file.BindMethod("Rename", &Nz::File::GetLastWriteTime);
file.BindMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime);
file.BindMethod("SetFile", &Nz::File::GetLastWriteTime);
file.BindStaticMethod("AbsolutePath", &Nz::File::AbsolutePath);
file.BindStaticMethod("ComputeHash", (Nz::ByteArray (*)(Nz::HashType, const Nz::String&)) &Nz::File::ComputeHash);
file.BindStaticMethod("Copy", &Nz::File::Copy);
file.BindStaticMethod("Delete", &Nz::File::Delete);
file.BindStaticMethod("Exists", &Nz::File::Exists);
//fileClass.SetStaticMethod("GetCreationTime", &Nz::File::GetCreationTime);
file.BindStaticMethod("GetDirectory", &Nz::File::GetDirectory);
//fileClass.SetStaticMethod("GetLastAccessTime", &Nz::File::GetLastAccessTime);
//fileClass.SetStaticMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime);
file.BindStaticMethod("GetSize", &Nz::File::GetSize);
file.BindStaticMethod("IsAbsolute", &Nz::File::IsAbsolute);
file.BindStaticMethod("NormalizePath", &Nz::File::NormalizePath);
file.BindStaticMethod("NormalizeSeparators", &Nz::File::NormalizeSeparators);
file.BindStaticMethod("Rename", &Nz::File::Rename);
// Manual
file.BindMethod("Open", [] (Nz::LuaInstance& lua, Nz::File& file, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
int argIndex = 2;
switch (argCount)
{
case 0:
case 1:
return lua.Push(file.Open(lua.Check<Nz::UInt32>(&argIndex, Nz::OpenMode_NotOpen)));
case 2:
{
Nz::String filePath = lua.Check<Nz::String>(&argIndex);
Nz::UInt32 openMode = lua.Check<Nz::UInt32>(&argIndex, Nz::OpenMode_NotOpen);
return lua.Push(file.Open(filePath, openMode));
}
}
lua.Error("No matching overload for method Open");
return 0;
});
file.BindMethod("SetCursorPos", [] (Nz::LuaInstance& lua, Nz::File& file, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
int argIndex = 2;
switch (argCount)
{
case 1:
return lua.Push(file.SetCursorPos(lua.Check<Nz::UInt64>(&argIndex)));
case 2:
{
Nz::CursorPosition curPos = lua.Check<Nz::CursorPosition>(&argIndex);
Nz::Int64 offset = lua.Check<Nz::Int64>(&argIndex);
return lua.Push(file.SetCursorPos(curPos, offset));
}
}
lua.Error("No matching overload for method SetCursorPos");
return 0;
});
file.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::File& file, std::size_t /*argumentCount*/) -> int {
Nz::StringStream stream("File(");
if (file.IsOpen())
stream << "Path: " << file.GetPath();
stream << ')';
lua.PushString(stream);
return 1;
});
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the Core classes
*/
void LuaBinding::RegisterCore(Nz::LuaInstance& instance)
{
// Classes
clock.Register(instance);
directory.Register(instance);
file.Register(instance);
stream.Register(instance);
// Enums
// Nz::CursorPosition
static_assert(Nz::CursorPosition_Max + 1 == 3, "Nz::CursorPosition has been updated but change was not reflected to Lua binding");
instance.PushTable(0, 3);
{
instance.PushField("AtBegin", Nz::CursorPosition_AtBegin);
instance.PushField("AtCurrent", Nz::CursorPosition_AtCurrent);
instance.PushField("AtEnd", Nz::CursorPosition_AtEnd);
}
instance.SetGlobal("CursorPosition");
// Nz::HashType
static_assert(Nz::HashType_Max + 1 == 9, "Nz::HashType has been updated but change was not reflected to Lua binding");
instance.PushTable(0, 9);
{
instance.PushField("CRC32", Nz::HashType_CRC32);
instance.PushField("Fletcher16", Nz::HashType_Fletcher16);
instance.PushField("MD5", Nz::HashType_MD5);
instance.PushField("SHA1", Nz::HashType_SHA1);
instance.PushField("SHA224", Nz::HashType_SHA224);
instance.PushField("SHA256", Nz::HashType_SHA256);
instance.PushField("SHA384", Nz::HashType_SHA384);
instance.PushField("SHA512", Nz::HashType_SHA512);
instance.PushField("Whirlpool", Nz::HashType_Whirlpool);
}
instance.SetGlobal("HashType");
// Nz::OpenMode
static_assert(Nz::OpenMode_Max + 1 == 2 * (64), "Nz::OpenModeFlags has been updated but change was not reflected to Lua binding");
instance.PushTable(0, 8);
{
instance.PushField("Append", Nz::OpenMode_Append);
instance.PushField("NotOpen", Nz::OpenMode_NotOpen);
instance.PushField("Lock", Nz::OpenMode_Lock);
instance.PushField("ReadOnly", Nz::OpenMode_ReadOnly);
instance.PushField("ReadWrite", Nz::OpenMode_ReadWrite);
instance.PushField("Text", Nz::OpenMode_Text);
instance.PushField("Truncate", Nz::OpenMode_Truncate);
instance.PushField("WriteOnly", Nz::OpenMode_WriteOnly);
}
instance.SetGlobal("OpenMode");
}
}

View File

@ -1,334 +0,0 @@
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#include <NDK/LuaBinding.hpp>
#include <NDK/LuaAPI.hpp>
namespace Ndk
{
/*!
* \brief Binds Graphics module to Lua
*/
void LuaBinding::BindGraphics()
{
/*********************************** Nz::InstancedRenderable ***********************************/
/*********************************** Nz::Material ***********************************/
material.SetConstructor([] (Nz::LuaInstance& lua, Nz::MaterialRef* instance, std::size_t argumentCount)
{
switch (argumentCount)
{
case 0:
Nz::PlacementNew(instance, Nz::Material::New());
return true;
case 1:
{
int argIndex = 1;
if (lua.IsOfType(argIndex, "MaterialPipeline"))
{
Nz::PlacementNew(instance, Nz::Material::New(*static_cast<Nz::MaterialPipelineRef*>(lua.ToUserdata(argIndex))));
return true;
}
else if (lua.IsOfType(argIndex, "Material"))
{
Nz::PlacementNew(instance, Nz::Material::New(**static_cast<Nz::MaterialRef*>(lua.ToUserdata(argIndex))));
return true;
}
else
{
Nz::PlacementNew(instance, Nz::Material::New(lua.Check<Nz::String>(&argIndex)));
return true;
}
}
}
lua.Error("No matching overload for constructor");
return false;
});
material.BindMethod("Configure", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "MaterialPipeline"))
{
instance->Configure(*static_cast<Nz::MaterialPipelineRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
{
lua.Push(instance->Configure(lua.Check<Nz::String>(&argIndex)));
return 1;
}
});
material.BindMethod("EnableAlphaTest", &Nz::Material::EnableAlphaTest);
material.BindMethod("EnableBlending", &Nz::Material::EnableBlending);
material.BindMethod("EnableColorWrite", &Nz::Material::EnableColorWrite);
material.BindMethod("EnableDepthBuffer", &Nz::Material::EnableDepthBuffer);
material.BindMethod("EnableDepthSorting", &Nz::Material::EnableDepthSorting);
material.BindMethod("EnableDepthWrite", &Nz::Material::EnableDepthWrite);
material.BindMethod("EnableFaceCulling", &Nz::Material::EnableFaceCulling);
material.BindMethod("EnableScissorTest", &Nz::Material::EnableScissorTest);
material.BindMethod("EnableShadowCasting", &Nz::Material::EnableShadowCasting);
material.BindMethod("EnableShadowReceive", &Nz::Material::EnableShadowReceive);
material.BindMethod("EnableStencilTest", &Nz::Material::EnableStencilTest);
material.BindMethod("EnsurePipelineUpdate", &Nz::Material::EnsurePipelineUpdate);
material.BindMethod("GetAlphaMap", &Nz::Material::GetAlphaMap);
material.BindMethod("GetAlphaThreshold", &Nz::Material::GetAlphaThreshold);
material.BindMethod("GetAmbientColor", &Nz::Material::GetAmbientColor);
material.BindMethod("GetDepthFunc", &Nz::Material::GetDepthFunc);
material.BindMethod("GetDepthMaterial", &Nz::Material::GetDepthMaterial);
material.BindMethod("GetDiffuseColor", &Nz::Material::GetDiffuseColor);
material.BindMethod("GetDiffuseMap", &Nz::Material::GetDiffuseMap);
//material.BindMethod("GetDiffuseSampler", &Nz::Material::GetDiffuseSampler);
material.BindMethod("GetDstBlend", &Nz::Material::GetDstBlend);
material.BindMethod("GetEmissiveMap", &Nz::Material::GetEmissiveMap);
material.BindMethod("GetFaceCulling", &Nz::Material::GetFaceCulling);
material.BindMethod("GetFaceFilling", &Nz::Material::GetFaceFilling);
material.BindMethod("GetHeightMap", &Nz::Material::GetHeightMap);
material.BindMethod("GetLineWidth", &Nz::Material::GetLineWidth);
material.BindMethod("GetNormalMap", &Nz::Material::GetNormalMap);
//material.BindMethod("GetPipeline", &Nz::Material::GetPipeline);
//material.BindMethod("GetPipelineInfo", &Nz::Material::GetPipelineInfo);
material.BindMethod("GetPointSize", &Nz::Material::GetPointSize);
//material.BindMethod("GetShader", &Nz::Material::GetShader);
material.BindMethod("GetShininess", &Nz::Material::GetShininess);
material.BindMethod("GetSpecularColor", &Nz::Material::GetSpecularColor);
material.BindMethod("GetSpecularMap", &Nz::Material::GetSpecularMap);
//material.BindMethod("GetSpecularSampler", &Nz::Material::GetSpecularSampler);
material.BindMethod("GetSrcBlend", &Nz::Material::GetSrcBlend);
material.BindMethod("HasAlphaMap", &Nz::Material::HasAlphaMap);
material.BindMethod("HasDepthMaterial", &Nz::Material::HasDepthMaterial);
material.BindMethod("HasDiffuseMap", &Nz::Material::HasDiffuseMap);
material.BindMethod("HasEmissiveMap", &Nz::Material::HasEmissiveMap);
material.BindMethod("HasHeightMap", &Nz::Material::HasHeightMap);
material.BindMethod("HasNormalMap", &Nz::Material::HasNormalMap);
material.BindMethod("HasSpecularMap", &Nz::Material::HasSpecularMap);
material.BindMethod("IsAlphaTestEnabled", &Nz::Material::IsAlphaTestEnabled);
material.BindMethod("IsBlendingEnabled", &Nz::Material::IsBlendingEnabled);
material.BindMethod("IsColorWriteEnabled", &Nz::Material::IsColorWriteEnabled);
material.BindMethod("IsDepthBufferEnabled", &Nz::Material::IsDepthBufferEnabled);
material.BindMethod("IsDepthSortingEnabled", &Nz::Material::IsDepthSortingEnabled);
material.BindMethod("IsDepthWriteEnabled", &Nz::Material::IsDepthWriteEnabled);
material.BindMethod("IsFaceCullingEnabled", &Nz::Material::IsFaceCullingEnabled);
material.BindMethod("IsScissorTestEnabled", &Nz::Material::IsScissorTestEnabled);
material.BindMethod("IsStencilTestEnabled", &Nz::Material::IsStencilTestEnabled);
material.BindMethod("IsShadowCastingEnabled", &Nz::Material::IsShadowCastingEnabled);
material.BindMethod("IsShadowReceiveEnabled", &Nz::Material::IsShadowReceiveEnabled);
material.BindMethod("LoadFromFile", &Nz::Material::LoadFromFile);
material.BindMethod("Reset", &Nz::Material::Reset);
material.BindMethod("SetAlphaThreshold", &Nz::Material::SetAlphaThreshold);
material.BindMethod("SetAmbientColor", &Nz::Material::SetAmbientColor);
material.BindMethod("SetDepthFunc", &Nz::Material::SetDepthFunc);
material.BindMethod("SetDepthFunc", &Nz::Material::SetDepthFunc);
material.BindMethod("SetDepthMaterial", &Nz::Material::SetDepthMaterial);
material.BindMethod("SetDiffuseColor", &Nz::Material::SetDiffuseColor);
//material.BindMethod("SetDiffuseSampler", &Nz::Material::SetDiffuseSampler);
material.BindMethod("SetDstBlend", &Nz::Material::SetDstBlend);
material.BindMethod("SetFaceCulling", &Nz::Material::SetFaceCulling);
material.BindMethod("SetFaceFilling", &Nz::Material::SetFaceFilling);
material.BindMethod("SetLineWidth", &Nz::Material::SetLineWidth);
material.BindMethod("SetPointSize", &Nz::Material::SetPointSize);
material.BindMethod("SetShininess", &Nz::Material::SetShininess);
material.BindMethod("SetSpecularColor", &Nz::Material::SetSpecularColor);
material.BindMethod("SetSpecularColor", &Nz::Material::SetSpecularColor);
//material.BindMethod("SetSpecularSampler", &Nz::Material::SetSpecularSampler);
material.BindMethod("SetSrcBlend", &Nz::Material::SetSrcBlend);
material.BindStaticMethod("GetDefault", &Nz::Material::GetDefault);
material.BindMethod("SetAlphaMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
instance->SetAlphaMap(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetAlphaMap(lua.Check<Nz::String>(&argIndex)));
});
material.BindMethod("SetDiffuseMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
instance->SetDiffuseMap(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetDiffuseMap(lua.Check<Nz::String>(&argIndex)));
});
material.BindMethod("SetEmissiveMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
instance->SetEmissiveMap(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetEmissiveMap(lua.Check<Nz::String>(&argIndex)));
});
material.BindMethod("SetHeightMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
instance->SetHeightMap(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetHeightMap(lua.Check<Nz::String>(&argIndex)));
});
material.BindMethod("SetNormalMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
instance->SetNormalMap(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetNormalMap(lua.Check<Nz::String>(&argIndex)));
});
material.BindMethod("SetShader", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "UberShader"))
{
instance->SetShader(*static_cast<Nz::UberShaderRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetShader(lua.Check<Nz::String>(&argIndex)));
});
material.BindMethod("SetSpecularMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
instance->SetSpecularMap(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetSpecularMap(lua.Check<Nz::String>(&argIndex)));
});
/*********************************** Nz::Model ***********************************/
model.Inherit<Nz::InstancedRenderableRef>(instancedRenderable, [] (Nz::ModelRef* model) -> Nz::InstancedRenderableRef*
{
return reinterpret_cast<Nz::InstancedRenderableRef*>(model); //TODO: Make a ObjectRefCast
});
model.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::ModelRef* model, std::size_t /*argumentCount*/)
{
Nz::PlacementNew(model, Nz::Model::New());
return true;
});
//model.BindMethod("GetMaterial", &Nz::Model::GetMaterial);
model.BindMethod("GetMaterialCount", &Nz::Model::GetMaterialCount);
//modelClass.SetMethod("GetMesh", &Nz::Model::GetMesh);
model.BindMethod("GetSkin", &Nz::Model::GetSkin);
model.BindMethod("GetSkinCount", &Nz::Model::GetSkinCount);
model.BindMethod("IsAnimated", &Nz::Model::IsAnimated);
model.BindMethod("LoadFromFile", &Nz::Model::LoadFromFile, Nz::ModelParameters());
model.BindMethod("Reset", &Nz::Model::Reset);
//model.BindMethod("SetMaterial", &Nz::Model::SetMaterial);
//modelClass.SetMethod("SetMesh", &Nz::Model::SetMesh);
//modelClass.SetMethod("SetSequence", &Nz::Model::SetSequence);
model.BindMethod("SetSkin", &Nz::Model::SetSkin);
model.BindMethod("SetSkinCount", &Nz::Model::SetSkinCount);
/*********************************** Nz::Sprite ***********************************/
sprite.Inherit<Nz::InstancedRenderableRef>(instancedRenderable, [] (Nz::SpriteRef* sprite) -> Nz::InstancedRenderableRef*
{
return reinterpret_cast<Nz::InstancedRenderableRef*>(sprite); //TODO: Make a ObjectRefCast
});
sprite.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::SpriteRef* sprite, std::size_t /*argumentCount*/)
{
Nz::PlacementNew(sprite, Nz::Sprite::New());
return true;
});
sprite.BindMethod("GetColor", &Nz::Sprite::GetColor);
sprite.BindMethod("GetCornerColor", &Nz::Sprite::GetCornerColor);
sprite.BindMethod("GetMaterial", &Nz::Sprite::GetMaterial);
sprite.BindMethod("GetOrigin", &Nz::Sprite::GetOrigin);
sprite.BindMethod("GetSize", &Nz::Sprite::GetSize);
sprite.BindMethod("GetTextureCoords", &Nz::Sprite::GetTextureCoords);
sprite.BindMethod("SetColor", &Nz::Sprite::SetColor);
sprite.BindMethod("SetCornerColor", &Nz::Sprite::SetCornerColor);
sprite.BindMethod("SetDefaultMaterial", &Nz::Sprite::SetDefaultMaterial);
sprite.BindMethod("SetMaterial", &Nz::Sprite::SetMaterial, true);
sprite.BindMethod("SetOrigin", &Nz::Sprite::SetOrigin);
sprite.BindMethod("SetSize", (void(Nz::Sprite::*)(const Nz::Vector2f&)) &Nz::Sprite::SetSize);
sprite.BindMethod("SetTexture", &Nz::Sprite::SetTexture, true);
sprite.BindMethod("SetTextureCoords", &Nz::Sprite::SetTextureCoords);
sprite.BindMethod("SetTextureRect", &Nz::Sprite::SetTextureRect);
/*********************************** Nz::SpriteLibrary ***********************************/
spriteLibrary.BindStaticMethod("Get", &Nz::SpriteLibrary::Get);
spriteLibrary.BindStaticMethod("Has", &Nz::SpriteLibrary::Has);
spriteLibrary.BindStaticMethod("Register", &Nz::SpriteLibrary::Register);
spriteLibrary.BindStaticMethod("Query", &Nz::SpriteLibrary::Query);
spriteLibrary.BindStaticMethod("Unregister", &Nz::SpriteLibrary::Unregister);
/*********************************** Nz::TextureLibrary ***********************************/
textureLibrary.BindStaticMethod("Get", &Nz::TextureLibrary::Get);
textureLibrary.BindStaticMethod("Has", &Nz::TextureLibrary::Has);
textureLibrary.BindStaticMethod("Register", &Nz::TextureLibrary::Register);
textureLibrary.BindStaticMethod("Query", &Nz::TextureLibrary::Query);
textureLibrary.BindStaticMethod("Unregister", &Nz::TextureLibrary::Unregister);
/*********************************** Nz::TextureManager ***********************************/
textureManager.BindStaticMethod("Clear", &Nz::TextureManager::Clear);
textureManager.BindStaticMethod("Get", &Nz::TextureManager::Get);
textureManager.BindStaticMethod("GetDefaultParameters", &Nz::TextureManager::GetDefaultParameters);
textureManager.BindStaticMethod("Purge", &Nz::TextureManager::Purge);
textureManager.BindStaticMethod("Register", &Nz::TextureManager::Register);
textureManager.BindStaticMethod("SetDefaultParameters", &Nz::TextureManager::SetDefaultParameters);
textureManager.BindStaticMethod("Unregister", &Nz::TextureManager::Unregister);
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the Graphics classes
*/
void LuaBinding::RegisterGraphics(Nz::LuaInstance& instance)
{
instancedRenderable.Register(instance);
material.Register(instance);
model.Register(instance);
sprite.Register(instance);
spriteLibrary.Register(instance);
textureLibrary.Register(instance);
textureManager.Register(instance);
}
}

View File

@ -1,908 +0,0 @@
// This file was automatically generated on 26 May 2014 at 01:05:31
#include <NDK/LuaBinding.hpp>
#include <Nazara/Core/MemoryHelper.hpp>
#include <NDK/LuaAPI.hpp>
#include <cstring>
namespace Ndk
{
/*!
* \brief Binds Math module to Lua
*/
void LuaBinding::BindMath()
{
/*********************************** Nz::EulerAngles **********************************/
eulerAngles.SetConstructor([] (Nz::LuaInstance& lua, Nz::EulerAnglesd* angles, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 1U);
switch (argCount)
{
case 0:
Nz::PlacementNew(angles, Nz::EulerAnglesd::Zero());
return true;
case 1:
Nz::PlacementNew(angles, *static_cast<Nz::EulerAnglesd*>(lua.CheckUserdata(1, "EulerAngles")));
return true;
case 3:
Nz::PlacementNew(angles, lua.CheckNumber(1), lua.CheckNumber(2), lua.CheckNumber(3));
return true;
}
lua.Error("No matching overload for EulerAngles constructor");
return false;
});
eulerAngles.BindMethod("__tostring", &Nz::EulerAnglesd::ToString);
eulerAngles.SetGetter([] (Nz::LuaInstance& lua, Nz::EulerAnglesd& instance)
{
std::size_t length;
const char* ypr = lua.CheckString(2, &length);
switch (length)
{
case 1:
{
switch (ypr[0])
{
case 'p':
lua.Push(instance.pitch);
return true;
case 'y':
lua.Push(instance.yaw);
return true;
case 'r':
lua.Push(instance.roll);
return true;
}
break;
}
case 3:
{
if (std::memcmp(ypr, "yaw", 3) != 0)
break;
lua.Push(instance.yaw);
return true;
}
case 4:
{
if (std::memcmp(ypr, "roll", 4) != 0)
break;
lua.Push(instance.roll);
return true;
}
case 5:
{
if (std::memcmp(ypr, "pitch", 5) != 0)
break;
lua.Push(instance.pitch);
return true;
}
}
return false;
});
eulerAngles.SetSetter([] (Nz::LuaInstance& lua, Nz::EulerAnglesd& instance)
{
std::size_t length;
const char* ypr = lua.CheckString(2, &length);
double value = lua.CheckNumber(3);
switch (length)
{
case 1:
{
switch (ypr[0])
{
case 'p':
instance.pitch = value;
return true;
case 'y':
instance.yaw = value;
return true;
case 'r':
instance.roll = value;
return true;
}
break;
}
case 3:
{
if (std::memcmp(ypr, "yaw", 3) != 0)
break;
instance.yaw = value;
return true;
}
case 4:
{
if (std::memcmp(ypr, "roll", 4) != 0)
break;
instance.roll = value;
return true;
}
case 5:
{
if (std::memcmp(ypr, "pitch", 5) != 0)
break;
instance.pitch = value;
return true;
}
}
return false;
});
/*********************************** Nz::Matrix4 **********************************/
matrix4d.SetConstructor([] (Nz::LuaInstance& lua, Nz::Matrix4d* matrix, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 3U);
switch (argCount)
{
case 0:
Nz::PlacementNew(matrix, Nz::Matrix4d::Zero());
return true;
case 1:
if (lua.IsOfType(1, "Matrix4"))
Nz::PlacementNew(matrix, *static_cast<Nz::Matrix4d*>(lua.ToUserdata(1)));
break;
case 16:
{
double values[16];
for (std::size_t i = 0; i < 16; ++i)
values[i] = lua.CheckNumber(i);
Nz::PlacementNew(matrix, values);
return true;
}
}
lua.Error("No matching overload for constructor");
return false;
});
matrix4d.BindMethod("ApplyRotation", &Nz::Matrix4d::ApplyRotation);
matrix4d.BindMethod("ApplyScale", &Nz::Matrix4d::ApplyScale);
matrix4d.BindMethod("ApplyTranslation", &Nz::Matrix4d::ApplyTranslation);
matrix4d.BindMethod("Concatenate", &Nz::Matrix4d::Concatenate);
matrix4d.BindMethod("ConcatenateAffine", &Nz::Matrix4d::ConcatenateAffine);
//matrix4d.BindMethod("GetColumn", &Nz::Matrix4d::GetColumn);
matrix4d.BindMethod("GetDeterminant", &Nz::Matrix4d::GetDeterminant);
matrix4d.BindMethod("GetDeterminantAffine", &Nz::Matrix4d::GetDeterminantAffine);
matrix4d.BindMethod("GetInverse", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{
Nz::Matrix4d result;
if (instance.GetInverse(&result))
return lua.Push(true, result);
else
return lua.Push(false);
});
matrix4d.BindMethod("GetInverseAffine", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{
Nz::Matrix4d result;
if (instance.GetInverseAffine(&result))
return lua.Push(true, result);
else
return lua.Push(false);
});
matrix4d.BindMethod("GetRotation", &Nz::Matrix4d::GetRotation);
//matrix4d.BindMethod("GetRow", &Nz::Matrix4d::GetRow);
matrix4d.BindMethod("GetScale", &Nz::Matrix4d::GetScale);
matrix4d.BindMethod("GetSquaredScale", &Nz::Matrix4d::GetSquaredScale);
matrix4d.BindMethod("GetTranslation", &Nz::Matrix4d::GetTranslation);
matrix4d.BindMethod("GetTransposed", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{
Nz::Matrix4d result;
instance.GetTransposed(&result);
return lua.Push(result);
});
matrix4d.BindMethod("HasNegativeScale", &Nz::Matrix4d::HasNegativeScale);
matrix4d.BindMethod("HasScale", &Nz::Matrix4d::HasScale);
matrix4d.BindMethod("Inverse", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{
bool succeeded;
instance.Inverse(&succeeded);
return lua.Push(succeeded);
});
matrix4d.BindMethod("InverseAffine", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{
bool succeeded;
instance.InverseAffine(&succeeded);
return lua.Push(succeeded);
});
matrix4d.BindMethod("IsAffine", &Nz::Matrix4d::IsAffine);
matrix4d.BindMethod("IsIdentity", &Nz::Matrix4d::IsIdentity);
matrix4d.BindMethod("MakeIdentity", &Nz::Matrix4d::MakeIdentity);
matrix4d.BindMethod("MakeLookAt", &Nz::Matrix4d::MakeLookAt, Nz::Vector3d::Up());
matrix4d.BindMethod("MakeOrtho", &Nz::Matrix4d::MakeOrtho, -1.0, 1.0);
matrix4d.BindMethod("MakePerspective", &Nz::Matrix4d::MakePerspective);
matrix4d.BindMethod("MakeRotation", &Nz::Matrix4d::MakeRotation);
matrix4d.BindMethod("MakeScale", &Nz::Matrix4d::MakeScale);
matrix4d.BindMethod("MakeTranslation", &Nz::Matrix4d::MakeTranslation);
matrix4d.BindMethod("MakeTransform", (Nz::Matrix4d&(Nz::Matrix4d::*)(const Nz::Vector3d&, const Nz::Quaterniond&, const Nz::Vector3d&)) &Nz::Matrix4d::MakeTransform, Nz::Vector3d::Unit());
matrix4d.BindMethod("MakeViewMatrix", &Nz::Matrix4d::MakeViewMatrix);
matrix4d.BindMethod("MakeZero", &Nz::Matrix4d::MakeZero);
matrix4d.BindMethod("Set", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 3U);
int argIndex = 2;
switch (argCount)
{
case 1:
if (lua.IsOfType(argIndex, "Matrix4"))
instance.Set(*static_cast<Nz::Matrix4d*>(lua.ToUserdata(argIndex)));
break;
case 16:
{
double values[16];
for (std::size_t i = 0; i < 16; ++i)
values[i] = lua.CheckNumber(argIndex++);
instance.Set(values);
return 0;
}
}
lua.Error("No matching overload for method Set");
return 0;
});
matrix4d.BindMethod("SetRotation", &Nz::Matrix4d::SetRotation);
matrix4d.BindMethod("SetScale", &Nz::Matrix4d::SetScale);
matrix4d.BindMethod("SetTranslation", &Nz::Matrix4d::SetTranslation);
matrix4d.BindMethod("Transform", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Vector2"))
{
double z(lua.CheckNumber(argIndex+1, 0.0));
double w(lua.CheckNumber(argIndex+2, 1.0));
return lua.Push(instance.Transform(*static_cast<Nz::Vector2d*>(lua.ToUserdata(argIndex)), z, w));
}
else if (lua.IsOfType(argIndex, "Vector3"))
{
double w(lua.CheckNumber(argIndex+1, 1.0));
return lua.Push(instance.Transform(*static_cast<Nz::Vector3d*>(lua.ToUserdata(argIndex)), w));
}
//else if (lua.IsOfType(2, "Vector4"))
// return lua.Push(instance.Transform(*static_cast<Nz::Vector4d*>(lua.ToUserdata(1))));
lua.Error("No matching overload for method Transform");
return 0;
});
matrix4d.BindMethod("Transpose", &Nz::Matrix4d::Transpose);
matrix4d.BindMethod("__tostring", &Nz::Matrix4d::ToString);
matrix4d.BindStaticMethod("Concatenate", &Nz::Matrix4d::Concatenate);
matrix4d.BindStaticMethod("ConcatenateAffine", &Nz::Matrix4d::ConcatenateAffine);
matrix4d.BindStaticMethod("Identity", &Nz::Matrix4d::Identity);
matrix4d.BindStaticMethod("LookAt", &Nz::Matrix4d::LookAt, Nz::Vector3d::Up());
matrix4d.BindStaticMethod("Ortho", &Nz::Matrix4d::Ortho, -1.0, 1.0);
matrix4d.BindStaticMethod("Perspective", &Nz::Matrix4d::Perspective);
matrix4d.BindStaticMethod("Rotate", &Nz::Matrix4d::Rotate);
matrix4d.BindStaticMethod("Scale", &Nz::Matrix4d::Scale);
matrix4d.BindStaticMethod("Translate", &Nz::Matrix4d::Translate);
matrix4d.BindStaticMethod("Transform", (Nz::Matrix4d(*)(const Nz::Vector3d&, const Nz::Quaterniond&, const Nz::Vector3d&)) &Nz::Matrix4d::Transform, Nz::Vector3d::Unit());
matrix4d.BindStaticMethod("ViewMatrix", &Nz::Matrix4d::ViewMatrix);
matrix4d.BindStaticMethod("Zero", &Nz::Matrix4d::Zero);
matrix4d.SetGetter([] (Nz::LuaInstance& lua, Nz::Matrix4d& instance)
{
bool succeeded = false;
std::size_t index = static_cast<std::size_t>(lua.ToInteger(2, &succeeded));
if (!succeeded || index < 1 || index > 16)
return false;
lua.Push(instance[index - 1]);
return true;
});
matrix4d.SetSetter([] (Nz::LuaInstance& lua, Nz::Matrix4d& instance)
{
bool succeeded = false;
std::size_t index = static_cast<std::size_t>(lua.ToInteger(2, &succeeded));
if (!succeeded || index < 1 || index > 16)
return false;
instance[index - 1] = lua.CheckNumber(3);
return true;
});
/*********************************** Nz::Rect **********************************/
rect.SetConstructor([] (Nz::LuaInstance& lua, Nz::Rectd* rect, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
switch (argCount)
{
case 0:
case 4:
PlacementNew(rect, lua.CheckNumber(1, 0.0), lua.CheckNumber(2, 0.0), lua.CheckNumber(3, 0.0), lua.CheckNumber(4, 0.0));
return true;
case 1:
{
if (lua.IsOfType(1, "Rect"))
PlacementNew(rect, *static_cast<Nz::Rectd*>(lua.ToUserdata(1)));
else if (lua.IsOfType(1, Nz::LuaType_Table))
{
// TODO => Faire sans avoir à mettre de nom dans la table et prendre les éléments un à un pour créer le Rectd
PlacementNew(rect, lua.CheckField<double>("x", 1),
lua.CheckField<double>("y", 1),
lua.CheckField<double>("width", 1),
lua.CheckField<double>("height", 1));
}
else if (lua.IsOfType(1, "Vector2"))
PlacementNew(rect, *static_cast<Nz::Vector2d*>(lua.ToUserdata(1)));
else
break;
return true;
}
case 2:
{
if (lua.IsOfType(1, Nz::LuaType_Number) && lua.IsOfType(2, Nz::LuaType_Number))
PlacementNew(rect, lua.CheckNumber(1), lua.CheckNumber(2));
else if (lua.IsOfType(1, "Vector2") && lua.IsOfType(2, "Vector2"))
PlacementNew(rect, *static_cast<Nz::Vector2d*>(lua.ToUserdata(1)), *static_cast<Nz::Vector2d*>(lua.ToUserdata(2)));
else
break;
return true;
}
}
lua.Error("No matching overload for Rect constructor");
return false;
});
rect.BindMethod("__tostring", &Nz::Rectd::ToString);
rect.SetGetter([] (Nz::LuaInstance& lua, Nz::Rectd& instance)
{
switch (lua.GetType(2))
{
case Nz::LuaType_Number:
{
auto index = lua.CheckBoundInteger<std::size_t>(2);
if (index < 1 || index > 4)
return false;
lua.Push(instance[index - 1]);
return true;
}
case Nz::LuaType_String:
{
std::size_t length;
const char* xywh = lua.CheckString(2, &length);
if (length != 1)
break;
switch (xywh[0])
{
case 'x':
lua.Push(instance.x);
return true;
case 'y':
lua.Push(instance.y);
return true;
case 'w':
lua.Push(instance.width);
return true;
case 'h':
lua.Push(instance.height);
return true;
default:
break;
}
break;
}
default:
break;
}
return false;
});
rect.SetSetter([] (Nz::LuaInstance& lua, Nz::Rectd& instance)
{
switch (lua.GetType(2))
{
case Nz::LuaType_Number:
{
auto index = lua.CheckBoundInteger<std::size_t>(2);
if (index < 1 || index > 4)
return false;
instance[index - 1] = lua.CheckNumber(2);
return true;
}
case Nz::LuaType_String:
{
std::size_t length;
const char* xywh = lua.CheckString(2, &length);
if (length != 1)
break;
double value = lua.CheckNumber(3);
switch (xywh[0])
{
case 'x':
instance.x = value;
return true;
case 'y':
instance.y = value;
return true;
case 'w':
instance.width = value;
return true;
case 'h':
instance.height = value;
return true;
}
break;
}
default:
break;
}
return false;
});
/*********************************** Nz::Quaternion **********************************/
quaternion.SetConstructor([] (Nz::LuaInstance& lua, Nz::Quaterniond* quaternion, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
switch (argCount)
{
case 0:
Nz::PlacementNew(quaternion, Nz::Quaterniond::Zero());
return true;
case 1:
{
if (lua.IsOfType(1, "EulerAngles"))
Nz::PlacementNew(quaternion, *static_cast<Nz::EulerAnglesd*>(lua.ToUserdata(1)));
else if (lua.IsOfType(1, "Quaternion"))
Nz::PlacementNew(quaternion, *static_cast<Nz::Quaterniond*>(lua.ToUserdata(1)));
else
break;
return true;
}
case 2:
Nz::PlacementNew(quaternion, lua.CheckNumber(1), *static_cast<Nz::Vector3d*>(lua.CheckUserdata(2, "Vector3")));
return true;
case 4:
Nz::PlacementNew(quaternion, lua.CheckNumber(1), lua.CheckNumber(2), lua.CheckNumber(3), lua.CheckNumber(4));
return true;
default:
break;
}
lua.Error("No matching overload for Quaternion constructor");
return false;
});
quaternion.BindMethod("__tostring", &Nz::Quaterniond::ToString);
quaternion.SetGetter([] (Nz::LuaInstance& lua, Nz::Quaterniond& instance)
{
std::size_t length;
const char* wxyz = lua.CheckString(2, &length);
if (length != 1)
return false;
switch (wxyz[0])
{
case 'w':
lua.Push(instance.w);
return true;
case 'x':
lua.Push(instance.x);
return true;
case 'y':
lua.Push(instance.y);
return true;
case 'z':
lua.Push(instance.z);
return true;
}
return false;
});
quaternion.SetSetter([] (Nz::LuaInstance& lua, Nz::Quaterniond& instance)
{
std::size_t length;
const char* wxyz = lua.CheckString(2, &length);
if (length != 1)
return false;
double value = lua.CheckNumber(3);
switch (wxyz[0])
{
case 'w':
instance.w = value;
return true;
case 'x':
instance.x = value;
return true;
case 'y':
instance.y = value;
return true;
case 'z':
instance.z = value;
return true;
default:
break;
}
return false;
});
/*********************************** Nz::Vector2 **********************************/
vector2d.SetConstructor([] (Nz::LuaInstance& lua, Nz::Vector2d* vector, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
switch (argCount)
{
case 0:
case 2:
Nz::PlacementNew(vector, lua.CheckNumber(1, 0.0), lua.CheckNumber(2, 0.0));
return true;
case 1:
{
if (lua.IsOfType(1, Nz::LuaType_Number))
Nz::PlacementNew(vector, lua.CheckNumber(1));
else if (lua.IsOfType(1, "Vector2"))
Nz::PlacementNew(vector, *static_cast<Nz::Vector2d*>(lua.ToUserdata(1)));
else
break;
return true;
}
}
lua.Error("No matching overload for Vector2 constructor");
return false;
});
vector2d.BindMethod("__tostring", &Nz::Vector2d::ToString);
vector2d.SetGetter([](Nz::LuaInstance& lua, Nz::Vector2d& instance)
{
switch (lua.GetType(2))
{
case Nz::LuaType_Number:
{
long long index = lua.CheckInteger(2);
if (index < 1 || index > 2)
return false;
lua.Push(instance[index - 1]);
return true;
}
case Nz::LuaType_String:
{
std::size_t length;
const char* xy = lua.CheckString(2, &length);
if (length != 1)
break;
switch (xy[0])
{
case 'x':
lua.Push(instance.x);
return true;
case 'y':
lua.Push(instance.y);
return true;
default:
break;
}
break;
}
default:
break;
}
return false;
});
vector2d.SetSetter([](Nz::LuaInstance& lua, Nz::Vector2d& instance)
{
switch (lua.GetType(2))
{
case Nz::LuaType_Number:
{
long long index = lua.CheckInteger(2);
if (index < 1 || index > 2)
return false;
instance[index - 1] = lua.CheckNumber(3);
return true;
}
case Nz::LuaType_String:
{
std::size_t length;
const char* xy = lua.CheckString(2, &length);
if (length != 1)
break;
double value = lua.CheckNumber(3);
switch (xy[0])
{
case 'x':
instance.x = value;
return true;
case 'y':
instance.y = value;
return true;
default:
break;
}
break;
}
default:
break;
}
return false;
});
/*********************************** Nz::Vector3 **********************************/
vector3d.SetConstructor([] (Nz::LuaInstance& lua, Nz::Vector3d* vector, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 3U);
switch (argCount)
{
case 0:
case 3:
Nz::PlacementNew(vector, lua.CheckNumber(1, 0.0), lua.CheckNumber(2, 0.0), lua.CheckNumber(3, 0.0));
return true;
case 1:
{
if (lua.IsOfType(1, Nz::LuaType_Number))
Nz::PlacementNew(vector, lua.CheckNumber(1));
else if (lua.IsOfType(1, "Vector2"))
Nz::PlacementNew(vector, *static_cast<Nz::Vector2d*>(lua.ToUserdata(1)));
else if (lua.IsOfType(1, "Vector3"))
Nz::PlacementNew(vector, *static_cast<Nz::Vector3d*>(lua.ToUserdata(1)));
else
break;
return true;
}
case 2:
{
if (lua.IsOfType(1, Nz::LuaType_Number))
Nz::PlacementNew(vector, lua.CheckNumber(1), *static_cast<Nz::Vector2d*>(lua.CheckUserdata(2, "Vector2")));
else if (lua.IsOfType(1, "Vector2"))
Nz::PlacementNew(vector, *static_cast<Nz::Vector2d*>(lua.ToUserdata(1)), lua.CheckNumber(2));
else
break;
return true;
}
}
lua.Error("No matching overload for constructor");
return false;
});
vector3d.BindMethod("__tostring", &Nz::Vector3d::ToString);
vector3d.SetGetter([] (Nz::LuaInstance& lua, Nz::Vector3d& instance)
{
switch (lua.GetType(2))
{
case Nz::LuaType_Number:
{
long long index = lua.CheckInteger(2);
if (index < 1 || index > 3)
return false;
lua.Push(instance[index - 1]);
return true;
}
case Nz::LuaType_String:
{
std::size_t length;
const char* xyz = lua.CheckString(2, &length);
if (length != 1)
break;
switch (xyz[0])
{
case 'x':
lua.Push(instance.x);
return true;
case 'y':
lua.Push(instance.y);
return true;
case 'z':
lua.Push(instance.z);
return true;
default:
break;
}
break;
}
default:
break;
}
return false;
});
vector3d.SetSetter([] (Nz::LuaInstance& lua, Nz::Vector3d& instance)
{
switch (lua.GetType(2))
{
case Nz::LuaType_Number:
{
long long index = lua.CheckInteger(2);
if (index < 1 || index > 3)
return false;
instance[index - 1] = lua.CheckNumber(3);
return true;
}
case Nz::LuaType_String:
{
std::size_t length;
const char* xyz = lua.CheckString(2, &length);
if (length != 1)
break;
double value = lua.CheckNumber(3);
switch (xyz[0])
{
case 'x':
instance.x = value;
return true;
case 'y':
instance.y = value;
return true;
case 'z':
instance.z = value;
return true;
default:
break;
}
break;
}
default:
break;
}
return false;
});
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the Math classes
*/
void LuaBinding::RegisterMath(Nz::LuaInstance& instance)
{
eulerAngles.Register(instance);
matrix4d.Register(instance);
quaternion.Register(instance);
rect.Register(instance);
vector2d.Register(instance);
vector3d.Register(instance);
}
}

View File

@ -1,76 +0,0 @@
// Copyright (C) 2016 Jérôme Leclercq, Arnaud Cadot
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#include <NDK/LuaBinding.hpp>
#include <NDK/LuaAPI.hpp>
namespace Ndk
{
/*!
* \brief Binds Renderer module to Lua
*/
void LuaBinding::BindRenderer()
{
/*********************************** Nz::Texture ***********************************/
texture.Inherit<Nz::AbstractImageRef>(abstractImage, [] (Nz::TextureRef* texture) -> Nz::AbstractImageRef*
{
return reinterpret_cast<Nz::AbstractImageRef*>(texture); //TODO: Make a ObjectRefCast
});
texture.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::TextureRef* texture, std::size_t /*argumentCount*/)
{
Nz::PlacementNew(texture, Nz::Texture::New());
return true;
});
texture.BindMethod("Create", &Nz::Texture::Create, static_cast<Nz::UInt8>(1), 1U);
texture.BindMethod("Destroy", &Nz::Texture::Destroy);
//texture.BindMethod("Download", &Nz::Texture::Download);
texture.BindMethod("EnableMipmapping", &Nz::Texture::EnableMipmapping);
texture.BindMethod("EnsureMipmapsUpdate", &Nz::Texture::EnsureMipmapsUpdate);
texture.BindMethod("HasMipmaps", &Nz::Texture::HasMipmaps);
texture.BindMethod("InvalidateMipmaps", &Nz::Texture::InvalidateMipmaps);
texture.BindMethod("IsValid", &Nz::Texture::IsValid);
texture.BindMethod("LoadFromFile", &Nz::Texture::LoadFromFile, true, Nz::ImageParams());
//bool LoadFromImage(const Image& image, bool generateMipmaps = true);
//bool LoadFromMemory(const void* data, std::size_t size, const ImageParams& params = ImageParams(), bool generateMipmaps = true);
//bool LoadFromStream(Stream& stream, const ImageParams& params = ImageParams(), bool generateMipmaps = true);
texture.BindMethod("LoadArrayFromFile", &Nz::Texture::LoadArrayFromFile, Nz::Vector2ui(2, 2), true, Nz::ImageParams());
//bool LoadArrayFromImage(const Image& image, bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2));
//bool LoadArrayFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2));
//bool LoadArrayFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2));
//bool LoadCubemapFromFile(const String& filePath, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams());
//bool LoadCubemapFromImage(const Image& image, bool generateMipmaps = true, const CubemapParams& params = CubemapParams());
//bool LoadCubemapFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams());
//bool LoadCubemapFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams());
texture.BindMethod("LoadFaceFromFile", &Nz::Texture::LoadFaceFromFile, Nz::ImageParams());
//bool LoadFaceFromMemory(CubemapFace face, const void* data, std::size_t size, const ImageParams& params = ImageParams());
//bool LoadFaceFromStream(CubemapFace face, Stream& stream, const ImageParams& params = ImageParams());
texture.BindMethod("SaveToFile", &Nz::Texture::SaveToFile, Nz::ImageParams());
//bool SaveToStream(Stream& stream, const String& format, const ImageParams& params = ImageParams());
texture.BindMethod("SetMipmapRange", &Nz::Texture::SetMipmapRange);
texture.BindStaticMethod("IsFormatSupported", &Nz::Texture::IsFormatSupported);
texture.BindStaticMethod("IsMipmappingSupported", &Nz::Texture::IsMipmappingSupported);
texture.BindStaticMethod("IsTypeSupported", &Nz::Texture::IsTypeSupported);
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the Renderer classes
*/
void LuaBinding::RegisterRenderer(Nz::LuaInstance& instance)
{
texture.Register(instance);
}
}

View File

@ -1,299 +0,0 @@
// Copyright (C) 2016 Jérôme Leclercq, Arnaud Cadot
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#include <NDK/LuaBinding.hpp>
#include <NDK/LuaAPI.hpp>
namespace Ndk
{
/*!
* \brief Binds SDK module to Lua
*/
void LuaBinding::BindSDK()
{
/*********************************** Ndk::Application **********************************/
#ifndef NDK_SERVER
//application.SetMethod("AddWindow", &Application::AddWindow);
application.BindMethod("EnableConsole", &Application::EnableConsole);
application.BindMethod("EnableFPSCounter", &Application::EnableFPSCounter);
application.BindMethod("IsConsoleEnabled", &Application::IsConsoleEnabled);
application.BindMethod("IsFPSCounterEnabled", &Application::IsFPSCounterEnabled);
#endif
application.BindMethod("AddWorld", [] (Nz::LuaInstance& instance, Application* application, std::size_t /*argumentCount*/) -> int
{
instance.Push(application->AddWorld().CreateHandle());
return 1;
});
application.BindMethod("GetUpdateTime", &Application::GetUpdateTime);
application.BindMethod("Quit", &Application::Quit);
/*********************************** Ndk::Console **********************************/
#ifndef NDK_SERVER
console.Inherit<Nz::Node>(node, [] (ConsoleHandle* handle) -> Nz::Node*
{
return handle->GetObject();
});
console.BindMethod("AddLine", &Console::AddLine, Nz::Color::White);
console.BindMethod("Clear", &Console::Clear);
console.BindMethod("GetCharacterSize", &Console::GetCharacterSize);
console.BindMethod("GetHistory", &Console::GetHistory);
console.BindMethod("GetHistoryBackground", &Console::GetHistoryBackground);
console.BindMethod("GetInput", &Console::GetInput);
console.BindMethod("GetInputBackground", &Console::GetInputBackground);
console.BindMethod("GetSize", &Console::GetSize);
console.BindMethod("GetTextFont", &Console::GetTextFont);
console.BindMethod("IsVisible", &Console::IsVisible);
console.BindMethod("SendCharacter", &Console::SendCharacter);
//consoleClass.SetMethod("SendEvent", &Console::SendEvent);
console.BindMethod("SetCharacterSize", &Console::SetCharacterSize);
console.BindMethod("SetSize", &Console::SetSize);
console.BindMethod("SetTextFont", &Console::SetTextFont);
console.BindMethod("Show", &Console::Show, true);
#endif
/*********************************** Ndk::Entity **********************************/
entity.BindMethod("Enable", &Entity::Enable, true);
entity.BindMethod("GetId", &Entity::GetId);
entity.BindMethod("GetWorld", &Entity::GetWorld);
entity.BindMethod("Kill", &Entity::Kill);
entity.BindMethod("IsEnabled", &Entity::IsEnabled);
entity.BindMethod("IsValid", &Entity::IsValid);
entity.BindMethod("RemoveAllComponents", &Entity::RemoveAllComponents);
entity.BindMethod("__tostring", &EntityHandle::ToString);
entity.BindMethod("AddComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle, std::size_t /*argumentCount*/) -> int
{
ComponentBinding* binding = QueryComponentIndex(instance);
return binding->adder(instance, handle);
});
entity.BindMethod("GetComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle, std::size_t /*argumentCount*/) -> int
{
ComponentBinding* binding = QueryComponentIndex(instance);
return binding->getter(instance, handle->GetComponent(binding->index));
});
entity.BindMethod("RemoveComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle, std::size_t /*argumentCount*/) -> int
{
ComponentBinding* binding = QueryComponentIndex(instance);
handle->RemoveComponent(binding->index);
return 0;
});
/*********************************** Ndk::NodeComponent **********************************/
nodeComponent.Inherit<Nz::Node>(node, [] (NodeComponentHandle* handle) -> Nz::Node*
{
return handle->GetObject();
});
/*********************************** Ndk::VelocityComponent **********************************/
velocityComponent.SetGetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance)
{
std::size_t length;
const char* member = lua.CheckString(2, &length);
if (std::strcmp(member, "Linear") == 0)
{
lua.Push(instance->linearVelocity);
return true;
}
return false;
});
velocityComponent.SetSetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance)
{
std::size_t length;
const char* member = lua.CheckString(2, &length);
int argIndex = 3;
if (std::strcmp(member, "Linear") == 0)
{
instance->linearVelocity = lua.Check<Nz::Vector3f>(&argIndex);
return true;
}
return false;
});
/*********************************** Ndk::World **********************************/
world.BindMethod("CreateEntity", &World::CreateEntity);
world.BindMethod("CreateEntities", &World::CreateEntities);
world.BindMethod("Clear", &World::Clear);
#ifndef NDK_SERVER
/*********************************** Ndk::GraphicsComponent **********************************/
graphicsComponent.BindMethod("Attach", [] (Nz::LuaInstance& lua, Ndk::GraphicsComponent *gfxComponent, std::size_t argumentCount) -> int
{
/*
void Attach(Nz::InstancedRenderableRef renderable, int renderOrder = 0);
void Attach(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& localMatrix, int renderOrder = 0);
*/
std::size_t argCount = std::min<std::size_t>(argumentCount, 3U);
switch (argCount)
{
case 1:
{
int argIndex = 2;
gfxComponent->Attach(lua.Check<Nz::InstancedRenderableRef>(&argIndex));
return 0;
}
case 2:
{
int argIndex = 2;
Nz::InstancedRenderableRef renderable = lua.Check<Nz::InstancedRenderableRef>(&argIndex);
if (lua.IsOfType(argIndex, Nz::LuaType_Number))
{
int renderOrder = lua.Check<int>(&argIndex);
gfxComponent->Attach(renderable, renderOrder);
}
else if (lua.IsOfType(argIndex, "Matrix4"))
{
Nz::Matrix4f localMatrix = lua.Check<Nz::Matrix4f>(&argIndex);
gfxComponent->Attach(renderable, localMatrix);
}
else
break;
return 0;
}
case 3:
{
int argIndex = 2;
Nz::InstancedRenderableRef renderable = lua.Check<Nz::InstancedRenderableRef>(&argIndex);
Nz::Matrix4f localMatrix = lua.Check<Nz::Matrix4f>(&argIndex);
int renderOrder = lua.Check<int>(&argIndex);
gfxComponent->Attach(renderable, localMatrix, renderOrder);
return 0;
}
}
lua.Error("No matching overload for method GetMemoryUsage");
return 0;
});
#endif
// Components functions
m_componentBinding.resize(BaseComponent::GetMaxComponentIndex());
BindComponent<NodeComponent>("Node");
BindComponent<VelocityComponent>("Velocity");
#ifndef NDK_SERVER
BindComponent<GraphicsComponent>("Graphics");
#endif
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the SDK classes
*/
void LuaBinding::RegisterSDK(Nz::LuaInstance& instance)
{
// Classes
application.Register(instance);
entity.Register(instance);
nodeComponent.Register(instance);
velocityComponent.Register(instance);
world.Register(instance);
#ifndef NDK_SERVER
console.Register(instance);
graphicsComponent.Register(instance);
#endif
// Enums
// ComponentType (fake enumeration to expose component indexes)
instance.PushTable(0, m_componentBinding.size());
{
for (const ComponentBinding& entry : m_componentBinding)
{
if (entry.name.IsEmpty())
continue;
instance.PushField(entry.name, entry.index);
}
}
instance.SetGlobal("ComponentType");
}
/*!
* \brief Gets the index of the component
* \return A pointer to the binding linked to a component
*
* \param instance Lua instance that will interact with the component
* \param argIndex Index of the component
*/
LuaBinding::ComponentBinding* LuaBinding::QueryComponentIndex(Nz::LuaInstance& instance, int argIndex)
{
switch (instance.GetType(argIndex))
{
case Nz::LuaType_Number:
{
ComponentIndex componentIndex = instance.Check<ComponentIndex>(&argIndex);
if (componentIndex > m_componentBinding.size())
{
instance.Error("Invalid component index");
return nullptr;
}
ComponentBinding& binding = m_componentBinding[componentIndex];
if (binding.name.IsEmpty())
{
instance.Error("Invalid component index");
return nullptr;
}
return &binding;
}
case Nz::LuaType_String:
{
const char* key = instance.CheckString(argIndex);
auto it = m_componentBindingByName.find(key);
if (it == m_componentBindingByName.end())
{
instance.Error("Invalid component name");
return nullptr;
}
return &m_componentBinding[it->second];
}
default:
break;
}
instance.Error("Invalid component index at #" + Nz::String::Number(argIndex));
return nullptr;
}
}

View File

@ -1,327 +0,0 @@
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#include <NDK/LuaBinding.hpp>
#include <NDK/LuaAPI.hpp>
namespace Ndk
{
/*!
* \brief Binds Utility module to Lua
*/
void LuaBinding::BindUtility()
{
/*********************************** Nz::AbstractImage **********************************/
abstractImage.BindMethod("GetBytesPerPixel", &Nz::AbstractImage::GetBytesPerPixel);
abstractImage.BindMethod("GetDepth", &Nz::AbstractImage::GetDepth, static_cast<Nz::UInt8>(0));
abstractImage.BindMethod("GetFormat", &Nz::AbstractImage::GetFormat);
abstractImage.BindMethod("GetHeight", &Nz::AbstractImage::GetHeight, static_cast<Nz::UInt8>(0));
abstractImage.BindMethod("GetLevelCount", &Nz::AbstractImage::GetLevelCount);
abstractImage.BindMethod("GetMaxLevel", &Nz::AbstractImage::GetMaxLevel);
abstractImage.BindMethod("GetSize", &Nz::AbstractImage::GetSize, static_cast<Nz::UInt8>(0));
abstractImage.BindMethod("GetType", &Nz::AbstractImage::GetType);
abstractImage.BindMethod("GetWidth", &Nz::AbstractImage::GetWidth, static_cast<Nz::UInt8>(0));
abstractImage.BindMethod("IsCompressed", &Nz::AbstractImage::IsCompressed);
abstractImage.BindMethod("IsCubemap", &Nz::AbstractImage::IsCubemap);
abstractImage.BindMethod("GetMemoryUsage", [] (Nz::LuaInstance& lua, Nz::AbstractImage* abstractImage, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 1U);
switch (argCount)
{
case 0:
return lua.Push(abstractImage->GetMemoryUsage());
case 1:
{
int argIndex = 2;
Nz::UInt8 level(lua.Check<Nz::UInt8>(&argIndex));
return lua.Push(abstractImage->GetMemoryUsage(level));
}
}
lua.Error("No matching overload for method GetMemoryUsage");
return 0;
});
abstractImage.BindMethod("Update", [] (Nz::LuaInstance& lua, Nz::AbstractImage* abstractImage, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 6U);
int argIndex = 2;
std::size_t bufferSize = 0;
const Nz::UInt8* pixels = reinterpret_cast<const Nz::UInt8*>(lua.CheckString(argIndex++, &bufferSize));
if (argCount < 2 || lua.IsOfType(2, Nz::LuaType_Number))
{
// bool Update(const UInt8* pixels, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0)
unsigned int srcWidth = lua.Check<unsigned int>(&argIndex, 0);
unsigned int srcHeight = lua.Check<unsigned int>(&argIndex, 0);
Nz::UInt8 level = lua.Check<Nz::UInt8>(&argIndex, 0);
///TODO: Buffer checks (Nz::ByteBufferView ?)
return lua.Push(abstractImage->Update(pixels, srcWidth, srcHeight, level));
}
/* Disabled until Box and Rect have been ported
else if (lua.IsOfType(2, "Box"))
{
// bool Update(const UInt8* pixels, const Boxui& box, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0)
Nz::Boxui box = lua.Check<Nz::Boxui>(&argIndex);
unsigned int srcWidth = lua.Check<unsigned int>(&argIndex, 0);
unsigned int srcHeight = lua.Check<unsigned int>(&argIndex, 0);
Nz::UInt8 level = lua.Check<Nz::UInt8>(&argIndex, 0);
///TODO: Buffer checks (Nz::ByteBufferView ?)
return lua.Push(abstractImage->Update(pixels, srcWidth, srcHeight, level));
}
else if (lua.IsOfType(2, "Rect"))
{
// bool Update(const UInt8* pixels, const Rectui& rect, unsigned int z = 0, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0)
Nz::Rectui box = lua.Check<Nz::Rectui>(&argIndex);
unsigned int srcWidth = lua.Check<unsigned int>(&argIndex, 0);
unsigned int srcHeight = lua.Check<unsigned int>(&argIndex, 0);
Nz::UInt8 level = lua.Check<Nz::UInt8>(&argIndex, 0);
///TODO: Buffer checks (Nz::ByteBufferView ?)
return lua.Push(abstractImage->Update(pixels, srcWidth, srcHeight, level));
}*/
lua.Error("No matching overload for method Update");
return 0;
});
/*********************************** Nz::Font **********************************/
font.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::FontRef* font, std::size_t /*argumentCount*/)
{
Nz::PlacementNew(font, Nz::Font::New());
return true;
});
font.BindMethod("ClearGlyphCache", &Nz::Font::ClearGlyphCache);
font.BindMethod("ClearKerningCache", &Nz::Font::ClearKerningCache);
font.BindMethod("ClearSizeInfoCache", &Nz::Font::ClearSizeInfoCache);
font.BindMethod("Destroy", &Nz::Font::Destroy);
font.BindMethod("GetCachedGlyphCount", [] (Nz::LuaInstance& lua, Nz::FontRef& instance, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
int argIndex = 2;
switch (argCount)
{
case 0:
lua.Push(instance->GetCachedGlyphCount());
return 1;
case 2:
{
unsigned int characterSize = lua.Check<unsigned int>(&argIndex);
Nz::UInt32 style = lua.Check<Nz::UInt32>(&argIndex);
lua.Push(instance->GetCachedGlyphCount(characterSize, style));
return 1;
}
}
lua.Error("No matching overload for method GetCachedGlyphCount");
return 0;
});
font.BindMethod("GetFamilyName", &Nz::Font::GetFamilyName);
font.BindMethod("GetKerning", &Nz::Font::GetKerning);
font.BindMethod("GetGlyphBorder", &Nz::Font::GetGlyphBorder);
font.BindMethod("GetMinimumStepSize", &Nz::Font::GetMinimumStepSize);
font.BindMethod("GetSizeInfo", &Nz::Font::GetSizeInfo);
font.BindMethod("GetStyleName", &Nz::Font::GetStyleName);
font.BindMethod("IsValid", &Nz::Font::IsValid);
font.BindMethod("Precache", (bool(Nz::Font::*)(unsigned int, Nz::UInt32, const Nz::String&) const) &Nz::Font::Precache);
font.BindMethod("OpenFromFile", &Nz::Font::OpenFromFile, Nz::FontParams());
font.BindMethod("SetGlyphBorder", &Nz::Font::SetGlyphBorder);
font.BindMethod("SetMinimumStepSize", &Nz::Font::SetMinimumStepSize);
font.BindStaticMethod("GetDefault", &Nz::Font::GetDefault);
font.BindStaticMethod("GetDefaultGlyphBorder", &Nz::Font::GetDefaultGlyphBorder);
font.BindStaticMethod("GetDefaultMinimumStepSize", &Nz::Font::GetDefaultMinimumStepSize);
font.BindStaticMethod("SetDefaultGlyphBorder", &Nz::Font::SetDefaultGlyphBorder);
font.BindStaticMethod("SetDefaultMinimumStepSize", &Nz::Font::SetDefaultMinimumStepSize);
/*********************************** Nz::Node **********************************/
node.BindMethod("GetBackward", &Nz::Node::GetBackward);
//nodeClass.SetMethod("GetChilds", &Nz::Node::GetChilds);
node.BindMethod("GetDown", &Nz::Node::GetDown);
node.BindMethod("GetForward", &Nz::Node::GetForward);
node.BindMethod("GetInheritPosition", &Nz::Node::GetInheritPosition);
node.BindMethod("GetInheritRotation", &Nz::Node::GetInheritRotation);
node.BindMethod("GetInheritScale", &Nz::Node::GetInheritScale);
node.BindMethod("GetInitialPosition", &Nz::Node::GetInitialPosition);
//nodeClass.SetMethod("GetInitialRotation", &Nz::Node::GetInitialRotation);
node.BindMethod("GetInitialScale", &Nz::Node::GetInitialScale);
node.BindMethod("GetLeft", &Nz::Node::GetLeft);
node.BindMethod("GetNodeType", &Nz::Node::GetNodeType);
//nodeClass.SetMethod("GetParent", &Nz::Node::GetParent);
node.BindMethod("GetPosition", &Nz::Node::GetPosition, Nz::CoordSys_Global);
node.BindMethod("GetRight", &Nz::Node::GetRight);
//nodeClass.SetMethod("GetRotation", &Nz::Node::GetRotation, Nz::CoordSys_Global);
node.BindMethod("GetScale", &Nz::Node::GetScale, Nz::CoordSys_Global);
//nodeClass.SetMethod("GetTransformMatrix", &Nz::Node::GetTransformMatrix);
node.BindMethod("GetUp", &Nz::Node::GetUp);
node.BindMethod("HasChilds", &Nz::Node::HasChilds);
node.BindMethod("GetBackward", &Nz::Node::GetBackward);
node.BindMethod("GetDown", &Nz::Node::GetDown);
node.BindMethod("GetForward", &Nz::Node::GetForward);
node.BindMethod("GetInheritPosition", &Nz::Node::GetInheritPosition);
node.BindMethod("GetInheritRotation", &Nz::Node::GetInheritRotation);
node.BindMethod("GetInheritScale", &Nz::Node::GetInheritScale);
node.BindMethod("GetInitialPosition", &Nz::Node::GetInitialPosition);
node.BindMethod("GetInitialRotation", &Nz::Node::GetInitialRotation);
node.BindMethod("GetInitialScale", &Nz::Node::GetInitialScale);
node.BindMethod("GetLeft", &Nz::Node::GetLeft);
node.BindMethod("GetNodeType", &Nz::Node::GetNodeType);
node.BindMethod("GetPosition", &Nz::Node::GetPosition, Nz::CoordSys_Global);
node.BindMethod("GetRight", &Nz::Node::GetRight);
node.BindMethod("GetRotation", &Nz::Node::GetRotation, Nz::CoordSys_Global);
node.BindMethod("GetScale", &Nz::Node::GetScale, Nz::CoordSys_Global);
node.BindMethod("GetUp", &Nz::Node::GetUp);
node.BindMethod("SetInitialPosition", (void(Nz::Node::*)(const Nz::Vector3f&)) &Nz::Node::SetInitialPosition);
node.BindMethod("SetInitialRotation", (void(Nz::Node::*)(const Nz::Quaternionf&)) &Nz::Node::SetInitialRotation);
node.BindMethod("SetPosition", (void(Nz::Node::*)(const Nz::Vector3f&, Nz::CoordSys)) &Nz::Node::SetPosition, Nz::CoordSys_Local);
node.BindMethod("SetRotation", (void(Nz::Node::*)(const Nz::Quaternionf&, Nz::CoordSys)) &Nz::Node::SetRotation, Nz::CoordSys_Local);
node.BindMethod("Move", [] (Nz::LuaInstance& lua, Nz::Node& node, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
Nz::Vector3f offset = lua.Check<Nz::Vector3f>(&argIndex);
Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local);
node.Move(offset, coordSys);
return 0;
});
node.BindMethod("Rotate", [] (Nz::LuaInstance& lua, Nz::Node& node, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
Nz::Quaternionf rotation = lua.Check<Nz::Quaternionf>(&argIndex);
Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local);
node.Rotate(rotation, coordSys);
return 0;
});
node.BindMethod("Scale", [] (Nz::LuaInstance& lua, Nz::Node& node, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
int argIndex = 2;
switch (argCount)
{
case 1:
{
if (lua.IsOfType(argIndex, Nz::LuaType_Number))
node.Scale(lua.Check<float>(&argIndex));
else
node.Scale(lua.Check<Nz::Vector3f>(&argIndex));
return 0;
}
case 3:
node.Scale(lua.Check<Nz::Vector3f>(&argIndex));
return 0;
}
lua.Error("No matching overload for method Scale");
return 0;
});
node.BindMethod("SetScale", [] (Nz::LuaInstance& lua, Nz::Node& node, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
int argIndex = 2;
switch (argCount)
{
case 1:
case 2:
{
if (lua.IsOfType(argIndex, Nz::LuaType_Number))
{
float scale = lua.Check<float>(&argIndex);
Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local);
node.SetScale(scale, coordSys);
}
else
node.SetScale(lua.Check<Nz::Vector3f>(&argIndex));
return 0;
}
case 3:
case 4:
{
Nz::Vector3f scale = lua.Check<Nz::Vector3f>(&argIndex);
Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local);
node.SetScale(scale, coordSys);
return 0;
}
}
lua.Error("No matching overload for method SetScale");
return 0;
});
node.BindMethod("SetInitialScale", [] (Nz::LuaInstance& lua, Nz::Node& node, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
int argIndex = 2;
switch (argCount)
{
case 1:
{
if (lua.IsOfType(argIndex, Nz::LuaType_Number))
node.SetInitialScale(lua.Check<float>(&argIndex));
else
node.SetInitialScale(lua.Check<Nz::Vector2f>(&argIndex));
return 0;
}
case 2:
case 3:
node.SetInitialScale(lua.Check<Nz::Vector3f>(&argIndex));
return 0;
}
lua.Error("No matching overload for method SetInitialScale");
return 0;
});
}
/*!
* \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::RegisterUtility(Nz::LuaInstance& instance)
{
abstractImage.Register(instance);
font.Register(instance);
node.Register(instance);
}
}

View File

@ -9,14 +9,18 @@
#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/Physics3D/Physics3D.hpp> #include <Nazara/Physics3D/Physics3D.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>
#include <NDK/Components/CollisionComponent2D.hpp>
#include <NDK/Components/CollisionComponent3D.hpp> #include <NDK/Components/CollisionComponent3D.hpp>
#include <NDK/Components/NodeComponent.hpp> #include <NDK/Components/NodeComponent.hpp>
#include <NDK/Components/PhysicsComponent2D.hpp>
#include <NDK/Components/PhysicsComponent3D.hpp> #include <NDK/Components/PhysicsComponent3D.hpp>
#include <NDK/Components/VelocityComponent.hpp> #include <NDK/Components/VelocityComponent.hpp>
#include <NDK/Systems/PhysicsSystem2D.hpp>
#include <NDK/Systems/PhysicsSystem3D.hpp> #include <NDK/Systems/PhysicsSystem3D.hpp>
#include <NDK/Systems/VelocitySystem.hpp> #include <NDK/Systems/VelocitySystem.hpp>
@ -68,6 +72,7 @@ namespace Ndk
Nz::Lua::Initialize(); Nz::Lua::Initialize();
Nz::Noise::Initialize(); Nz::Noise::Initialize();
Nz::Physics2D::Initialize();
Nz::Physics3D::Initialize(); Nz::Physics3D::Initialize();
Nz::Utility::Initialize(); Nz::Utility::Initialize();
@ -83,9 +88,11 @@ namespace Ndk
BaseComponent::Initialize(); BaseComponent::Initialize();
// Shared components // Shared components
InitializeComponent<CollisionComponent3D>("NdkColli"); InitializeComponent<CollisionComponent2D>("NdkColl2");
InitializeComponent<CollisionComponent3D>("NdkColl3");
InitializeComponent<NodeComponent>("NdkNode"); InitializeComponent<NodeComponent>("NdkNode");
InitializeComponent<PhysicsComponent3D>("NdkPhys"); InitializeComponent<PhysicsComponent2D>("NdkPhys2");
InitializeComponent<PhysicsComponent3D>("NdkPhys3");
InitializeComponent<VelocityComponent>("NdkVeloc"); InitializeComponent<VelocityComponent>("NdkVeloc");
#ifndef NDK_SERVER #ifndef NDK_SERVER
@ -103,6 +110,7 @@ namespace Ndk
BaseSystem::Initialize(); BaseSystem::Initialize();
// Shared systems // Shared systems
InitializeSystem<PhysicsSystem2D>();
InitializeSystem<PhysicsSystem3D>(); InitializeSystem<PhysicsSystem3D>();
InitializeSystem<VelocitySystem>(); InitializeSystem<VelocitySystem>();
@ -161,6 +169,7 @@ namespace Ndk
// Shared modules // Shared modules
Nz::Lua::Uninitialize(); Nz::Lua::Uninitialize();
Nz::Noise::Uninitialize(); Nz::Noise::Uninitialize();
Nz::Physics2D::Uninitialize();
Nz::Physics3D::Uninitialize(); Nz::Physics3D::Uninitialize();
Nz::Utility::Uninitialize(); Nz::Utility::Uninitialize();

View File

@ -25,6 +25,7 @@ namespace Ndk
ListenerSystem::ListenerSystem() ListenerSystem::ListenerSystem()
{ {
Requires<ListenerComponent, NodeComponent>(); Requires<ListenerComponent, NodeComponent>();
SetUpdateOrder(100); //< Update last, after every movement is done
} }
/*! /*!
@ -33,11 +34,9 @@ namespace Ndk
* \param elapsedTime Delta time used for the update * \param elapsedTime Delta time used for the update
*/ */
void ListenerSystem::OnUpdate(float elapsedTime) void ListenerSystem::OnUpdate(float /*elapsedTime*/)
{ {
NazaraUnused(elapsedTime); std::size_t activeListenerCount = 0;
unsigned int activeListenerCount = 0;
for (const Ndk::EntityHandle& entity : GetEntities()) for (const Ndk::EntityHandle& entity : GetEntities())
{ {

View File

@ -0,0 +1,140 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#include <NDK/Systems/PhysicsSystem2D.hpp>
#include <Nazara/Physics2D/RigidBody2D.hpp>
#include <NDK/Components/CollisionComponent2D.hpp>
#include <NDK/Components/NodeComponent.hpp>
#include <NDK/Components/PhysicsComponent2D.hpp>
#include <NDK/Components/PhysicsComponent3D.hpp>
namespace Ndk
{
/*!
* \ingroup NDK
* \class Ndk::PhysicsSystem2D
* \brief NDK class that represents a two-dimensional physics system
*
* \remark This system is enabled if the entity has the trait: NodeComponent and any of these two: CollisionComponent3D or PhysicsComponent3D
* \remark Static objects do not have a velocity specified by the physical engine
*/
/*!
* \brief Constructs an PhysicsSystem object by default
*/
PhysicsSystem2D::PhysicsSystem2D()
{
Requires<NodeComponent>();
RequiresAny<CollisionComponent2D, PhysicsComponent2D>();
Excludes<PhysicsComponent3D>();
}
/*!
* \brief Constructs a PhysicsSystem object by copy semantic
*
* \param system PhysicsSystem to copy
*/
PhysicsSystem2D::PhysicsSystem2D(const PhysicsSystem2D& system) :
System(system),
m_world()
{
}
void PhysicsSystem2D::CreatePhysWorld() const
{
NazaraAssert(!m_world, "Physics world should not be created twice");
m_world = std::make_unique<Nz::PhysWorld2D>();
}
/*!
* \brief Operation to perform when entity is validated for the system
*
* \param entity Pointer to the entity
* \param justAdded Is the entity newly added
*/
void PhysicsSystem2D::OnEntityValidation(Entity* entity, bool justAdded)
{
// It's possible our entity got revalidated because of the addition/removal of a PhysicsComponent3D
if (!justAdded)
{
// We take the opposite array from which the entity should belong to
auto& entities = (entity->HasComponent<PhysicsComponent2D>()) ? m_staticObjects : m_dynamicObjects;
entities.Remove(entity);
}
auto& entities = (entity->HasComponent<PhysicsComponent2D>()) ? m_dynamicObjects : m_staticObjects;
entities.Insert(entity);
if (!m_world)
CreatePhysWorld();
}
/*!
* \brief Operation to perform when system is updated
*
* \param elapsedTime Delta time used for the update
*/
void PhysicsSystem2D::OnUpdate(float elapsedTime)
{
if (!m_world)
return;
m_world->Step(elapsedTime);
for (const Ndk::EntityHandle& entity : m_dynamicObjects)
{
NodeComponent& node = entity->GetComponent<NodeComponent>();
PhysicsComponent2D& phys = entity->GetComponent<PhysicsComponent2D>();
Nz::RigidBody2D& body = phys.GetRigidBody();
node.SetRotation(Nz::EulerAnglesf(0.f, 0.f, body.GetRotation()), Nz::CoordSys_Global);
node.SetPosition(Nz::Vector3f(body.GetPosition(), node.GetPosition(Nz::CoordSys_Global).z), Nz::CoordSys_Global);
}
float invElapsedTime = 1.f / elapsedTime;
for (const Ndk::EntityHandle& entity : m_staticObjects)
{
CollisionComponent2D& collision = entity->GetComponent<CollisionComponent2D>();
NodeComponent& node = entity->GetComponent<NodeComponent>();
Nz::RigidBody2D* body = collision.GetStaticBody();
Nz::Vector2f oldPosition = body->GetPosition();
Nz::Vector2f newPosition = Nz::Vector2f(node.GetPosition(Nz::CoordSys_Global));
// To move static objects and ensure their collisions, we have to specify them a velocity
// (/!\: the physical motor does not apply the speed on static objects)
if (newPosition != oldPosition)
{
body->SetPosition(newPosition);
body->SetVelocity((newPosition - oldPosition) * invElapsedTime);
}
else
body->SetVelocity(Nz::Vector2f::Zero());
/*
if (newRotation != oldRotation)
{
Nz::Quaternionf transition = newRotation * oldRotation.GetConjugate();
Nz::EulerAnglesf angles = transition.ToEulerAngles();
Nz::Vector3f angularVelocity(Nz::ToRadians(angles.pitch * invElapsedTime),
Nz::ToRadians(angles.yaw * invElapsedTime),
Nz::ToRadians(angles.roll * invElapsedTime));
physObj->SetRotation(oldRotation);
physObj->SetAngularVelocity(angularVelocity);
}
else
physObj->SetAngularVelocity(Nz::Vector3f::Zero());
*/
}
}
SystemIndex PhysicsSystem2D::systemIndex;
}

View File

@ -6,6 +6,7 @@
#include <Nazara/Physics3D/RigidBody3D.hpp> #include <Nazara/Physics3D/RigidBody3D.hpp>
#include <NDK/Components/CollisionComponent3D.hpp> #include <NDK/Components/CollisionComponent3D.hpp>
#include <NDK/Components/NodeComponent.hpp> #include <NDK/Components/NodeComponent.hpp>
#include <NDK/Components/PhysicsComponent2D.hpp>
#include <NDK/Components/PhysicsComponent3D.hpp> #include <NDK/Components/PhysicsComponent3D.hpp>
namespace Ndk namespace Ndk
@ -27,6 +28,7 @@ namespace Ndk
{ {
Requires<NodeComponent>(); Requires<NodeComponent>();
RequiresAny<CollisionComponent3D, PhysicsComponent3D>(); RequiresAny<CollisionComponent3D, PhysicsComponent3D>();
Excludes<PhysicsComponent2D>();
} }
/*! /*!
@ -90,7 +92,7 @@ namespace Ndk
NodeComponent& node = entity->GetComponent<NodeComponent>(); NodeComponent& node = entity->GetComponent<NodeComponent>();
PhysicsComponent3D& phys = entity->GetComponent<PhysicsComponent3D>(); PhysicsComponent3D& phys = entity->GetComponent<PhysicsComponent3D>();
Nz::RigidBody3D& physObj = phys.GetPhysObject(); Nz::RigidBody3D& physObj = phys.GetRigidBody();
node.SetRotation(physObj.GetRotation(), Nz::CoordSys_Global); node.SetRotation(physObj.GetRotation(), Nz::CoordSys_Global);
node.SetPosition(physObj.GetPosition(), Nz::CoordSys_Global); node.SetPosition(physObj.GetPosition(), Nz::CoordSys_Global);
} }

View File

@ -28,14 +28,15 @@ namespace Ndk
/*! /*!
* \brief Constructs an RenderSystem object by default * \brief Constructs an RenderSystem object by default
*/ */
RenderSystem::RenderSystem() : RenderSystem::RenderSystem() :
m_coordinateSystemMatrix(Nz::Matrix4f::Identity()), m_coordinateSystemMatrix(Nz::Matrix4f::Identity()),
m_coordinateSystemInvalidated(true) m_coordinateSystemInvalidated(true),
m_forceRenderQueueInvalidation(false)
{ {
ChangeRenderTechnique<Nz::ForwardRenderTechnique>(); ChangeRenderTechnique<Nz::ForwardRenderTechnique>();
SetDefaultBackground(Nz::ColorBackground::New()); SetDefaultBackground(Nz::ColorBackground::New());
SetUpdateRate(0.f); SetUpdateOrder(100); //< Render last, after every movement is done
SetUpdateRate(0.f); //< We don't want any rate limit
} }
/*! /*!
@ -43,15 +44,22 @@ namespace Ndk
* *
* \param entity Pointer to the entity * \param entity Pointer to the entity
*/ */
void RenderSystem::OnEntityRemoved(Entity* entity) void RenderSystem::OnEntityRemoved(Entity* entity)
{ {
m_forceRenderQueueInvalidation = true; //< Hackfix until lights and particles are handled by culling list
m_cameras.Remove(entity); m_cameras.Remove(entity);
m_directionalLights.Remove(entity); m_directionalLights.Remove(entity);
m_drawables.Remove(entity); m_drawables.Remove(entity);
m_lights.Remove(entity); m_lights.Remove(entity);
m_particleGroups.Remove(entity); m_particleGroups.Remove(entity);
m_pointSpotLights.Remove(entity); m_pointSpotLights.Remove(entity);
if (entity->HasComponent<GraphicsComponent>())
{
GraphicsComponent& gfxComponent = entity->GetComponent<GraphicsComponent>();
gfxComponent.RemoveFromCullingList(&m_drawableCulling);
}
} }
/*! /*!
@ -60,7 +68,6 @@ namespace Ndk
* \param entity Pointer to the entity * \param entity Pointer to the entity
* \param justAdded Is the entity newly added * \param justAdded Is the entity newly added
*/ */
void RenderSystem::OnEntityValidation(Entity* entity, bool justAdded) void RenderSystem::OnEntityValidation(Entity* entity, bool justAdded)
{ {
NazaraUnused(justAdded); NazaraUnused(justAdded);
@ -77,12 +84,30 @@ namespace Ndk
m_cameras.Remove(entity); m_cameras.Remove(entity);
if (entity->HasComponent<GraphicsComponent>() && entity->HasComponent<NodeComponent>()) if (entity->HasComponent<GraphicsComponent>() && entity->HasComponent<NodeComponent>())
{
m_drawables.Insert(entity); m_drawables.Insert(entity);
if (justAdded)
{
GraphicsComponent& gfxComponent = entity->GetComponent<GraphicsComponent>();
gfxComponent.AddToCullingList(&m_drawableCulling);
}
}
else else
{
m_drawables.Remove(entity); m_drawables.Remove(entity);
if (entity->HasComponent<GraphicsComponent>())
{
GraphicsComponent& gfxComponent = entity->GetComponent<GraphicsComponent>();
gfxComponent.RemoveFromCullingList(&m_drawableCulling);
}
}
if (entity->HasComponent<LightComponent>() && entity->HasComponent<NodeComponent>()) if (entity->HasComponent<LightComponent>() && entity->HasComponent<NodeComponent>())
{ {
m_forceRenderQueueInvalidation = true; //< Hackfix until lights and particles are handled by culling list
LightComponent& lightComponent = entity->GetComponent<LightComponent>(); LightComponent& lightComponent = entity->GetComponent<LightComponent>();
if (lightComponent.GetLightType() == Nz::LightType_Directional) if (lightComponent.GetLightType() == Nz::LightType_Directional)
{ {
@ -99,15 +124,25 @@ namespace Ndk
} }
else else
{ {
m_forceRenderQueueInvalidation = true; //< Hackfix until lights and particles are handled by culling list
m_directionalLights.Remove(entity); m_directionalLights.Remove(entity);
m_lights.Remove(entity); m_lights.Remove(entity);
m_pointSpotLights.Remove(entity); m_pointSpotLights.Remove(entity);
} }
if (entity->HasComponent<ParticleGroupComponent>()) if (entity->HasComponent<ParticleGroupComponent>())
{
m_forceRenderQueueInvalidation = true; //< Hackfix until lights and particles are handled by culling list
m_particleGroups.Insert(entity); m_particleGroups.Insert(entity);
}
else else
{
m_forceRenderQueueInvalidation = true; //< Hackfix until lights and particles are handled by culling list
m_particleGroups.Remove(entity); m_particleGroups.Remove(entity);
}
} }
/*! /*!
@ -116,10 +151,8 @@ namespace Ndk
* \param elapsedTime Delta time used for the update * \param elapsedTime Delta time used for the update
*/ */
void RenderSystem::OnUpdate(float elapsedTime) void RenderSystem::OnUpdate(float /*elapsedTime*/)
{ {
NazaraUnused(elapsedTime);
// Invalidate every renderable if the coordinate system changed // Invalidate every renderable if the coordinate system changed
if (m_coordinateSystemInvalidated) if (m_coordinateSystemInvalidated)
{ {
@ -141,30 +174,45 @@ namespace Ndk
//UpdateDirectionalShadowMaps(camComponent); //UpdateDirectionalShadowMaps(camComponent);
Nz::AbstractRenderQueue* renderQueue = m_renderTechnique->GetRenderQueue(); Nz::AbstractRenderQueue* renderQueue = m_renderTechnique->GetRenderQueue();
renderQueue->Clear();
//TODO: Culling // To make sure the bounding volume used by the culling list is updated
for (const Ndk::EntityHandle& drawable : m_drawables) for (const Ndk::EntityHandle& drawable : m_drawables)
{ {
GraphicsComponent& graphicsComponent = drawable->GetComponent<GraphicsComponent>(); GraphicsComponent& graphicsComponent = drawable->GetComponent<GraphicsComponent>();
graphicsComponent.EnsureBoundingVolumeUpdate();
graphicsComponent.AddToRenderQueue(renderQueue);
} }
bool forceInvalidation = false;
for (const Ndk::EntityHandle& light : m_lights) std::size_t visibilityHash = m_drawableCulling.Cull(camComponent.GetFrustum(), &forceInvalidation);
// Always regenerate renderqueue if particle groups are present for now (FIXME)
if (!m_particleGroups.empty())
forceInvalidation = true;
if (camComponent.UpdateVisibility(visibilityHash) || m_forceRenderQueueInvalidation || forceInvalidation)
{ {
LightComponent& lightComponent = light->GetComponent<LightComponent>(); renderQueue->Clear();
NodeComponent& lightNode = light->GetComponent<NodeComponent>(); for (const GraphicsComponent* gfxComponent : m_drawableCulling)
gfxComponent->AddToRenderQueue(renderQueue);
///TODO: Cache somehow? for (const Ndk::EntityHandle& light : m_lights)
lightComponent.AddToRenderQueue(renderQueue, Nz::Matrix4f::ConcatenateAffine(m_coordinateSystemMatrix, lightNode.GetTransformMatrix())); {
} LightComponent& lightComponent = light->GetComponent<LightComponent>();
NodeComponent& lightNode = light->GetComponent<NodeComponent>();
for (const Ndk::EntityHandle& particleGroup : m_particleGroups) ///TODO: Cache somehow?
{ lightComponent.AddToRenderQueue(renderQueue, Nz::Matrix4f::ConcatenateAffine(m_coordinateSystemMatrix, lightNode.GetTransformMatrix()));
ParticleGroupComponent& groupComponent = particleGroup->GetComponent<ParticleGroupComponent>(); }
groupComponent.AddToRenderQueue(renderQueue, Nz::Matrix4f::Identity()); //< ParticleGroup doesn't use Matrix4f for (const Ndk::EntityHandle& particleGroup : m_particleGroups)
{
ParticleGroupComponent& groupComponent = particleGroup->GetComponent<ParticleGroupComponent>();
groupComponent.AddToRenderQueue(renderQueue, Nz::Matrix4f::Identity()); //< ParticleGroup doesn't use any transform matrix (yet)
}
m_forceRenderQueueInvalidation = false;
} }
camComponent.ApplyView(); camComponent.ApplyView();

View File

@ -4,6 +4,7 @@
#include <NDK/Systems/VelocitySystem.hpp> #include <NDK/Systems/VelocitySystem.hpp>
#include <NDK/Components/NodeComponent.hpp> #include <NDK/Components/NodeComponent.hpp>
#include <NDK/Components/PhysicsComponent2D.hpp>
#include <NDK/Components/PhysicsComponent3D.hpp> #include <NDK/Components/PhysicsComponent3D.hpp>
#include <NDK/Components/VelocityComponent.hpp> #include <NDK/Components/VelocityComponent.hpp>
@ -14,8 +15,8 @@ namespace Ndk
* \class Ndk::VelocitySystem * \class Ndk::VelocitySystem
* \brief NDK class that represents the velocity system * \brief NDK class that represents the velocity system
* *
* \remark This system is enabled if the entity owns the trait: NodeComponent and VelocityComponent * \remark This system is enabled if the entity owns the traits NodeComponent and VelocityComponent
* but it's disabled with the trait: PhysicsComponent3D * but it's disabled with the traits: PhysicsComponent2D, PhysicsComponent3D
*/ */
/*! /*!
@ -24,8 +25,9 @@ namespace Ndk
VelocitySystem::VelocitySystem() VelocitySystem::VelocitySystem()
{ {
Excludes<PhysicsComponent2D, PhysicsComponent3D>();
Requires<NodeComponent, VelocityComponent>(); Requires<NodeComponent, VelocityComponent>();
Excludes<PhysicsComponent3D>(); SetUpdateOrder(10); //< Since some systems may want to stop us
} }
/*! /*!

View File

@ -5,6 +5,7 @@
#include <NDK/World.hpp> #include <NDK/World.hpp>
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <NDK/BaseComponent.hpp> #include <NDK/BaseComponent.hpp>
#include <NDK/Systems/PhysicsSystem2D.hpp>
#include <NDK/Systems/PhysicsSystem3D.hpp> #include <NDK/Systems/PhysicsSystem3D.hpp>
#include <NDK/Systems/VelocitySystem.hpp> #include <NDK/Systems/VelocitySystem.hpp>
@ -40,6 +41,7 @@ namespace Ndk
void World::AddDefaultSystems() void World::AddDefaultSystems()
{ {
AddSystem<PhysicsSystem2D>();
AddSystem<PhysicsSystem3D>(); AddSystem<PhysicsSystem3D>();
AddSystem<VelocitySystem>(); AddSystem<VelocitySystem>();
@ -67,7 +69,7 @@ namespace Ndk
else else
{ {
// We allocate a new entity // We allocate a new entity
id = m_entities.size(); id = static_cast<Ndk::EntityId>(m_entities.size());
// We can't use emplace_back due to the scope // We can't use emplace_back due to the scope
m_entities.push_back(Entity(this, id)); m_entities.push_back(Entity(this, id));
@ -172,6 +174,9 @@ namespace Ndk
void World::Update() void World::Update()
{ {
if (!m_orderedSystemsUpdated)
ReorderSystems();
// 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))
{ {
@ -218,15 +223,11 @@ namespace Ndk
Nz::Bitset<>& removedComponents = entity->GetRemovedComponentBits(); Nz::Bitset<>& removedComponents = entity->GetRemovedComponentBits();
for (std::size_t j = removedComponents.FindFirst(); j != m_dirtyEntities.npos; j = removedComponents.FindNext(j)) for (std::size_t j = removedComponents.FindFirst(); j != m_dirtyEntities.npos; j = removedComponents.FindNext(j))
entity->DestroyComponent(j); entity->DestroyComponent(static_cast<Ndk::ComponentIndex>(j));
removedComponents.Reset(); removedComponents.Reset();
for (auto& system : m_systems) for (auto& system : m_orderedSystems)
{ {
// Ignore non-existent systems
if (!system)
continue;
// Is our entity already part of this system? // Is our entity already part of this system?
bool partOfSystem = system->HasEntity(entity); bool partOfSystem = system->HasEntity(entity);
@ -249,4 +250,22 @@ namespace Ndk
} }
m_dirtyEntities.Reset(); m_dirtyEntities.Reset();
} }
void World::ReorderSystems()
{
m_orderedSystems.clear();
for (auto& systemPtr : m_systems)
{
if (systemPtr)
m_orderedSystems.push_back(systemPtr.get());
}
std::sort(m_orderedSystems.begin(), m_orderedSystems.end(), [] (BaseSystem* first, BaseSystem* second)
{
return first->GetUpdateOrder() < second->GetUpdateOrder();
});
m_orderedSystemsUpdated = true;
}
} }

View File

@ -1 +1 @@
premake4 codeblocks premake5 codeblocks

View File

@ -0,0 +1,4 @@
dofile("codeblocks/_codeblocks.lua")
dofile("codeblocks/codeblocks.lua")
ACTION.Manual = true

View File

@ -0,0 +1,44 @@
--
-- _codeblocks.lua
-- Define the Code::Blocks action(s).
-- Copyright (c) 2002-2011 Jason Perkins and the Premake project
--
local p = premake
p.modules.codeblocks = {}
p.modules.codeblocks._VERSION = p._VERSION
local codeblocks = p.modules.codeblocks
newaction {
trigger = "codeblocks",
shortname = "Code::Blocks",
description = "Generate Code::Blocks project files",
valid_kinds = { "ConsoleApp", "WindowedApp", "StaticLib", "SharedLib" },
valid_languages = { "C", "C++" },
valid_tools = {
cc = { "clang", "gcc", "ow" },
},
onWorkspace = function(wks)
p.modules.codeblocks.generateWorkspace(wks)
end,
onProject = function(prj)
p.modules.codeblocks.generateProject(prj)
end,
onCleanWorkspace = function(wks)
p.clean.file(wks, wks.name .. ".workspace")
p.clean.file(wks, wks.name .. ".workspace.layout")
end,
onCleanProject = function(prj)
p.clean.file(prj, prj.name .. ".workspace")
p.clean.file(prj, prj.name .. ".depend")
p.clean.file(prj, prj.name .. ".layout")
end
}

View File

@ -0,0 +1,67 @@
--
-- codeblocks_workspace.lua
-- Generate a Code::Blocks workspace.
-- Copyright (c) 2009 Jason Perkins and the Premake project
--
local p = premake
p.modules.codeblocks = {}
p.modules.codeblocks._VERSION = p._VERSION
local codeblocks = p.modules.codeblocks
local project = p.project
function codeblocks.cfgname(cfg)
local cfgname = cfg.buildcfg
if codeblocks.workspace.multiplePlatforms then
cfgname = string.format("%s|%s", cfg.platform, cfg.buildcfg)
end
return cfgname
end
function codeblocks.esc(value)
local result = value:gsub('"', '&quot;')
result = result:gsub('<', '&lt;')
result = result:gsub('>', '&gt;')
return result
end
function codeblocks.generateWorkspace(wks)
p.eol("\r\n")
p.indent("\t")
p.escaper(codeblocks.esc)
p.generate(wks, ".workspace", codeblocks.workspace.generate)
end
function codeblocks.generateProject(prj)
p.eol("\r\n")
p.indent("\t")
p.escaper(codeblocks.esc)
if project.iscpp(prj) then
p.generate(prj, ".cbp", codeblocks.project.generate)
end
end
function codeblocks.cleanWorkspace(wks)
p.clean.file(wks, wks.name .. ".workspace")
p.clean.file(wks, wks.name .. ".workspace.layout")
end
function codeblocks.cleanProject(prj)
p.clean.file(prj, prj.name .. ".workspace")
p.clean.file(prj, prj.name .. ".depend")
p.clean.file(prj, prj.name .. ".layout")
end
function codeblocks.cleanTarget(prj)
-- TODO..
end
include("codeblocks_workspace.lua")
include("codeblocks_project.lua")

View File

@ -0,0 +1,243 @@
--
-- codeblocks_cbp.lua
-- Generate a Code::Blocks C/C++ project.
-- Copyright (c) 2009, 2011 Jason Perkins and the Premake project
--
local p = premake
local project = p.project
local config = p.config
local tree = p.tree
local codeblocks = p.modules.codeblocks
codeblocks.project = {}
local m = codeblocks.project
m.elements = {}
m.ctools = {
gcc = "gcc",
msc = "Visual C++",
}
function m.getcompilername(cfg)
local tool = _OPTIONS.cc or cfg.toolset or p.GCC
local toolset = p.tools[tool]
if not toolset then
error("Invalid toolset '" + (_OPTIONS.cc or cfg.toolset) + "'")
end
return m.ctools[tool]
end
function m.getcompiler(cfg)
local toolset = p.tools[_OPTIONS.cc or cfg.toolset or p.GCC]
if not toolset then
error("Invalid toolset '" + (_OPTIONS.cc or cfg.toolset) + "'")
end
return toolset
end
function m.header(prj)
_p('<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>')
_p('<CodeBlocks_project_file>')
_p(1,'<FileVersion major="1" minor="6" />')
-- write project block header
_p(1,'<Project>')
_p(2,'<Option title="%s" />', prj.name)
_p(2,'<Option pch_mode="2" />')
end
function m.footer(prj)
-- write project block footer
_p(1,'</Project>')
_p('</CodeBlocks_project_file>')
end
m.elements.project = function(prj)
return {
m.header,
m.configurations,
m.files,
m.extensions,
m.footer
}
end
--
-- Project: Generate the CodeBlocks project file.
--
function m.generate(prj)
p.utf8()
p.callArray(m.elements.project, prj)
end
function m.configurations(prj)
-- write configuration blocks
_p(2,'<Build>')
local platforms = {}
for cfg in project.eachconfig(prj) do
local found = false
for k,v in pairs(platforms) do
if (v.platform == cfg.platform) then
table.insert(v.configs, cfg)
found = true
break
end
end
if (not found) then
table.insert(platforms, {platform = cfg.platform, configs = {cfg}})
end
end
for k,platform in pairs(platforms) do
for k,cfg in pairs(platform.configs) do
local compiler = m.getcompiler(cfg)
_p(3,'<Target title="%s">', cfg.longname)
_p(4,'<Option output="%s" prefix_auto="0" extension_auto="0" />', p.esc(cfg.buildtarget.relpath))
if cfg.debugdir then
_p(4,'<Option working_dir="%s" />', p.esc(path.getrelative(prj.location, cfg.debugdir)))
end
_p(4,'<Option object_output="%s" />', p.esc(path.getrelative(prj.location, cfg.objdir)))
-- identify the type of binary
local types = { WindowedApp = 0, ConsoleApp = 1, StaticLib = 2, SharedLib = 3 }
_p(4,'<Option type="%d" />', types[cfg.kind])
_p(4,'<Option compiler="%s" />', m.getcompilername(cfg))
if (cfg.kind == "SharedLib") then
_p(4,'<Option createDefFile="0" />')
_p(4,'<Option createStaticLib="%s" />', iif(cfg.flags.NoImportLib, 0, 1))
end
-- begin compiler block --
_p(4,'<Compiler>')
for _,flag in ipairs(table.join(compiler.getcflags(cfg), compiler.getcxxflags(cfg), compiler.getdefines(cfg.defines), cfg.buildoptions)) do
_p(5,'<Add option="%s" />', p.esc(flag))
end
if not cfg.flags.NoPCH and cfg.pchheader then
_p(5,'<Add option="-Winvalid-pch" />')
_p(5,'<Add option="-include &quot;%s&quot;" />', p.esc(cfg.pchheader))
end
for _,v in ipairs(cfg.includedirs) do
_p(5,'<Add directory="%s" />', p.esc(path.getrelative(prj.location, v)))
end
_p(4,'</Compiler>')
-- end compiler block --
-- begin linker block --
_p(4,'<Linker>')
for _,flag in ipairs(table.join(compiler.getldflags(cfg), cfg.linkoptions)) do
_p(5,'<Add option="%s" />', p.esc(flag))
end
for _,v in ipairs(config.getlinks(cfg, "all", "directory")) do
_p(5,'<Add directory="%s" />', p.esc(v))
end
for _,v in ipairs(config.getlinks(cfg, "all", "basename")) do
_p(5,'<Add library="%s" />', p.esc(v))
end
_p(4,'</Linker>')
-- end linker block --
-- begin resource compiler block --
if config.findfile(cfg, ".rc") then
_p(4,'<ResourceCompiler>')
for _,v in ipairs(cfg.includedirs) do
_p(5,'<Add directory="%s" />', p.esc(v))
end
for _,v in ipairs(cfg.resincludedirs) do
_p(5,'<Add directory="%s" />', p.esc(v))
end
_p(4,'</ResourceCompiler>')
end
-- end resource compiler block --
-- begin build steps --
if #cfg.prebuildcommands > 0 or #cfg.postbuildcommands > 0 then
_p(4,'<ExtraCommands>')
for _,v in ipairs(cfg.prebuildcommands) do
_p(5,'<Add before="%s" />', p.esc(v))
end
for _,v in ipairs(cfg.postbuildcommands) do
_p(5,'<Add after="%s" />', p.esc(v))
end
_p(4,'</ExtraCommands>')
end
-- end build steps --
_p(3,'</Target>')
end
end
_p(2,'</Build>')
end
--
-- Write out a list of the source code files in the project.
--
function m.files(prj)
local pchheader
if (prj.pchheader) then
pchheader = path.getrelative(prj.location, prj.pchheader)
end
local tr = project.getsourcetree(prj)
tree.traverse(tr, {
-- source files are handled at the leaves
onleaf = function(node, depth)
if node.relpath == node.vpath then
_p(2,'<Unit filename="%s">', node.relpath)
else
_p(2,'<Unit filename="%s">', node.name)
_p(3,'<Option virtualFolder="%s" />', path.getdirectory(node.vpath))
end
if path.isresourcefile(node.name) then
_p(3,'<Option compilerVar="WINDRES" />')
elseif path.iscfile(node.name) and prj.language == "C++" then
_p(3,'<Option compilerVar="CC" />')
end
if not prj.flags.NoPCH and node.name == pchheader then
_p(3,'<Option compilerVar="%s" />', iif(prj.language == "C", "CC", "CPP"))
_p(3,'<Option compile="1" />')
_p(3,'<Option weight="0" />')
_p(3,'<Add option="-x c++-header" />')
end
_p(2,'</Unit>')
end,
}, false, 1)
end
function m.extensions(prj)
for cfg in project.eachconfig(prj) do
if cfg.debugenvs and #cfg.debugenvs > 0 then
--Assumption: if gcc is being used then so is gdb although this section will be ignored by
--other debuggers. If using gcc and not gdb it will silently not pass the
--environment arguments to the debugger
if m.getcompilername(cfg) == "gcc" then
_p(3,'<debugger>')
_p(4,'<remote_debugging target="%s">', p.esc(cfg.longname))
local args = ''
local sz = #cfg.debugenvs
for idx, v in ipairs(cfg.debugenvs) do
args = args .. 'set env ' .. v
if sz ~= idx then args = args .. '&#x0A;' end
end
_p(5,'<options additional_cmds_before="%s" />',args)
_p(4,'</remote_debugging>')
_p(3,'</debugger>')
else
error('Sorry at this moment there is no support for debug environment variables with this debugger and codeblocks')
end
end
end
end

View File

@ -0,0 +1,44 @@
--
-- Name: codelite/codelite_workspace.lua
-- Purpose: Generate a CodeLite workspace.
-- Author: Ryan Pusztai
-- Modified by: Andrea Zanellato
-- Manu Evans
-- Created: 2013/05/06
-- Copyright: (c) 2008-2015 Jason Perkins and the Premake project
--
local p = premake
local project = p.project
local workspace = p.workspace
local tree = p.tree
local codeblocks = p.modules.codeblocks
codeblocks.workspace = {}
local m = codeblocks.workspace
--
-- Generate a CodeBlocks workspace
--
function m.generate(wks)
p.utf8()
_p('<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>')
_p('<CodeBlocks_workspace_file>')
_p(1,'<Workspace title="%s">', wks.name)
for prj in workspace.eachproject(wks) do
local fname = path.join(path.getrelative(wks.location, prj.location), prj.name)
local active = iif(prj.project == wks.projects[1], ' active="1"', '')
_p(2,'<Project filename="%s.cbp"%s>', fname, active)
for _,dep in ipairs(project.getdependencies(prj)) do
_p(3,'<Depends filename="%s.cbp" />', path.join(path.getrelative(wks.location, dep.location), dep.name))
end
_p(2,'</Project>')
end
_p(1,'</Workspace>')
_p('</CodeBlocks_workspace_file>')
end

View File

@ -76,7 +76,7 @@ ACTION.Function = function ()
error("Failed to create header file (" .. v.Target .. "): " .. err) error("Failed to create header file (" .. v.Target .. "): " .. err)
end end
header:write("// This file was automatically generated on " .. os.date("%d %b %Y at %X") .. "\n\n") header:write("// This file was automatically generated\n\n")
if (v.Header) then if (v.Header) then
header:write(v.Header) header:write(v.Header)
end end

View File

@ -1,4 +1,7 @@
NazaraBuild = {} -- L'équivalent d'un namespace en Lua est une table NazaraBuild = {}
-- I wish Premake had a way to know the compiler in advance
local clangGccActions = "action:" .. table.concat({"codeblocks", "codelite", "gmake", "xcode3", "xcode4"}, " or ")
function NazaraBuild:AddExecutablePath(path) function NazaraBuild:AddExecutablePath(path)
self.ExecutableDir[path] = true self.ExecutableDir[path] = true
@ -9,21 +12,47 @@ function NazaraBuild:AddInstallPath(path)
self.InstallDir[path] = true self.InstallDir[path] = true
end end
function NazaraBuild:FilterLibDirectory(prefix, func)
filter({"action:codeblocks or codelite or gmake", "architecture:x86", "system:Windows"})
func(prefix .. "mingw/x86")
filter({"action:codeblocks or codelite or gmake", "architecture:x86_64", "system:Windows"})
func(prefix .. "mingw/x64")
filter({"action:codeblocks or codelite or gmake", "architecture:x86", "system:not Windows"})
func(prefix .. "gmake/x86")
filter({"action:codeblocks or codelite or gmake", "architecture:x86_64", "system:not Windows"})
func(prefix .. "gmake/x64")
filter({"action:vs*", "architecture:x86"})
func(prefix .. "msvc/x86")
filter({"action:vs*", "architecture:x86_64"})
func(prefix .. "msvc/x64")
filter({"action:xcode3 or xcode4", "architecture:x86"})
func(prefix .. "xcode/x86")
filter({"action:xcode3 or xcode4", "architecture:x86_64"})
func(prefix .. "xcode/x64")
filter({})
end
function NazaraBuild:Execute() function NazaraBuild:Execute()
if (_ACTION == nil) then -- Si aucune action n'est spécifiée if (_ACTION == nil) then -- If no action is specified, the user probably only wants to know how all of this works
return -- Alors l'utilisateur voulait probablement savoir comment utiliser le programme, on ne fait rien return -- Alors l'utilisateur voulait probablement savoir comment utiliser le programme, on ne fait rien
end end
local platformData local platformData
if (os.is64bit()) then if (os.is64bit()) then
platformData = {"x64", "x32"} platformData = {"x64", "x86"}
else else
platformData = {"x32", "x64"} platformData = {"x86", "x64"}
end end
if (self.Actions[_ACTION] == nil) then if (self.Actions[_ACTION] == nil) then
local makeLibDir = os.is("windows") and "mingw" or "gmake"
if (self.Config["BuildDependencies"]) then if (self.Config["BuildDependencies"]) then
workspace("NazaraExtlibs") workspace("NazaraExtlibs")
platforms(platformData) platforms(platformData)
@ -34,63 +63,19 @@ function NazaraBuild:Execute()
"ReleaseStatic" "ReleaseStatic"
}) })
self:PrepareGeneric()
self:FilterLibDirectory("../extlibs/lib/", targetdir)
filter(clangGccActions)
buildoptions("-U__STRICT_ANSI__")
filter({})
includedirs("../extlibs/include") includedirs("../extlibs/include")
libdirs("../extlibs/lib/common") libdirs("../extlibs/lib/common")
location(_ACTION) location(_ACTION)
kind("StaticLib") kind("StaticLib")
configuration({"codeblocks or codelite or gmake", "x32"})
libdirs("../extlibs/lib/" .. makeLibDir .. "/x86")
targetdir("../extlibs/lib/" .. makeLibDir .. "/x86")
configuration({"codeblocks or codelite or gmake", "x64"})
libdirs("../extlibs/lib/" .. makeLibDir .. "/x64")
targetdir("../extlibs/lib/" .. makeLibDir .. "/x64")
configuration("vs*")
buildoptions({"/MP", "/bigobj"}) -- Multiprocessus build and big .obj
configuration({"vs*", "x32"})
libdirs("../extlibs/lib/msvc/x86")
targetdir("../extlibs/lib/msvc/x86")
configuration({"vs*", "x64"})
libdirs("../extlibs/lib/msvc/x64")
targetdir("../extlibs/lib/msvc/x64")
configuration({"xcode3 or xcode4", "x32"})
libdirs("../extlibs/lib/xcode/x86")
targetdir("../extlibs/lib/xcode/x86")
configuration({"xcode3 or xcode4", "x64"})
libdirs("../extlibs/lib/xcode/x64")
targetdir("../extlibs/lib/xcode/x64")
configuration("Debug*")
flags("Symbols")
configuration("Release*")
flags("NoFramePointer")
optimize("Speed")
rtti("Off")
vectorextensions("SSE2")
configuration({"Release*", "codeblocks or codelite or gmake or xcode3 or xcode4"})
buildoptions("-mfpmath=sse") -- Utilisation du SSE pour les calculs flottants
buildoptions("-ftree-vectorize") -- Activation de la vectorisation du code
configuration("DebugStatic")
targetsuffix("-s-d")
configuration("ReleaseStatic")
targetsuffix("-s")
configuration({"not windows", "codeblocks or codelite or gmake or xcode3 or xcode4"})
buildoptions("-fPIC")
configuration("codeblocks or codelite or gmake or xcode3 or xcode4")
buildoptions({"-std=c++14", "-U__STRICT_ANSI__"})
for k, libTable in ipairs(self.OrderedExtLibs) do for k, libTable in ipairs(self.OrderedExtLibs) do
project(libTable.Name) project(libTable.Name)
@ -105,25 +90,30 @@ function NazaraBuild:Execute()
includedirs(libTable.Includes) includedirs(libTable.Includes)
links(libTable.Libraries) links(libTable.Libraries)
configuration("x32") filter("architecture:x86")
libdirs(libTable.LibraryPaths.x86) libdirs(libTable.LibraryPaths.x86)
configuration("x64") filter("architecture:x86_64")
libdirs(libTable.LibraryPaths.x64) libdirs(libTable.LibraryPaths.x64)
for k,v in pairs(libTable.ConfigurationLibraries) do for k,v in pairs(libTable.ConfigurationLibraries) do
configuration(k) filter(k)
links(v) links(v)
end end
configuration({}) filter({})
end end
end end
-- Start defining projects
workspace("NazaraEngine") workspace("NazaraEngine")
platforms(platformData) platforms(platformData)
-- Configuration générale self:PrepareMainWorkspace()
-- Add lib/conf/arch to library search path
self:FilterLibDirectory("../lib/", libdirs)
configurations({ configurations({
-- "DebugStatic", -- "DebugStatic",
-- "ReleaseStatic", -- "ReleaseStatic",
@ -134,36 +124,7 @@ function NazaraBuild:Execute()
language("C++") language("C++")
location(_ACTION) location(_ACTION)
configuration("Debug*") -- Modules
defines("NAZARA_DEBUG")
flags("Symbols")
configuration("Release*")
flags("NoFramePointer")
optimize("Speed")
vectorextensions("SSE2")
configuration({"Release*", "codeblocks or codelite or gmake or xcode3 or xcode4"})
buildoptions("-mfpmath=sse") -- Utilisation du SSE pour les calculs flottants
buildoptions("-ftree-vectorize") -- Activation de la vectorisation du code
configuration("*Static")
defines("NAZARA_STATIC")
configuration("codeblocks or codelite or gmake or xcode3 or xcode4")
buildoptions("-std=c++14")
configuration({"linux or bsd or macosx", "gmake"})
buildoptions("-fvisibility=hidden")
configuration("vs*")
buildoptions({"/MP", "/bigobj"}) -- Multiprocessus build and big .obj
flags("NoMinimalRebuild")
defines("_CRT_SECURE_NO_WARNINGS")
defines("_SCL_SECURE_NO_WARNINGS")
-- Spécification des modules
if (_OPTIONS["united"]) then if (_OPTIONS["united"]) then
project("NazaraEngine") project("NazaraEngine")
end end
@ -175,78 +136,12 @@ function NazaraBuild:Execute()
location(_ACTION .. "/modules") location(_ACTION .. "/modules")
defines("NAZARA_BUILD")
includedirs({ includedirs({
"../include", "../include",
"../src/", "../src/",
"../extlibs/include" "../extlibs/include"
}) })
libdirs("../lib")
libdirs("../extlibs/lib/common")
configuration("x32")
libdirs(moduleTable.LibraryPaths.x86)
configuration("x64")
defines("NAZARA_PLATFORM_x64")
libdirs(moduleTable.LibraryPaths.x64)
configuration({"codeblocks or codelite or gmake", "x32"})
libdirs("../extlibs/lib/" .. makeLibDir .. "/x86")
libdirs("../lib/" .. makeLibDir .. "/x86")
targetdir("../lib/" .. makeLibDir .. "/x86")
configuration({"codeblocks or codelite or gmake", "x64"})
libdirs("../extlibs/lib/" .. makeLibDir .. "/x64")
libdirs("../lib/" .. makeLibDir .. "/x64")
targetdir("../lib/" .. makeLibDir .. "/x64")
-- Copy the module binaries to the example folder
self:MakeInstallCommands(moduleTable)
configuration({"vs*", "x32"})
libdirs("../extlibs/lib/msvc/x86")
libdirs("../lib/msvc/x86")
targetdir("../lib/msvc/x86")
configuration({"vs*", "x64"})
libdirs("../extlibs/lib/msvc/x64")
libdirs("../lib/msvc/x64")
targetdir("../lib/msvc/x64")
configuration({"xcode3 or xcode4", "x32"})
libdirs("../extlibs/lib/xcode/x86")
libdirs("../lib/xcode/x86")
targetdir("../lib/xcode/x86")
configuration({"xcode3 or xcode4", "x64"})
libdirs("../extlibs/lib/xcode/x64")
libdirs("../lib/xcode/x64")
targetdir("../lib/xcode/x64")
configuration("*Static")
defines("NAZARA_STATIC")
kind("StaticLib")
configuration("*Dynamic")
kind("SharedLib")
configuration("DebugStatic")
targetsuffix("-s-d")
configuration("ReleaseStatic")
targetsuffix("-s")
configuration("DebugDynamic")
targetsuffix("-d")
configuration("Release*")
rtti(moduleTable.EnableRTTI and "On" or "Off")
configuration({})
files(moduleTable.Files) files(moduleTable.Files)
excludes(moduleTable.FilesExcluded) excludes(moduleTable.FilesExcluded)
@ -255,12 +150,29 @@ function NazaraBuild:Execute()
includedirs(moduleTable.Includes) includedirs(moduleTable.Includes)
links(moduleTable.Libraries) links(moduleTable.Libraries)
libdirs({
"../extlibs/lib/common",
"../lib"
})
-- Output to lib/conf/arch
self:FilterLibDirectory("../lib/", targetdir)
-- Copy the module binaries to the example folder
self:MakeInstallCommands(moduleTable)
filter("architecture:x86")
libdirs(moduleTable.LibraryPaths.x86)
filter("architecture:x86_64")
libdirs(moduleTable.LibraryPaths.x64)
for k,v in pairs(moduleTable.ConfigurationLibraries) do for k,v in pairs(moduleTable.ConfigurationLibraries) do
configuration(k) filter(k)
links(v) links(v)
end end
configuration({}) filter({})
end end
-- Tools -- Tools
@ -288,7 +200,7 @@ function NazaraBuild:Execute()
kind("WindowedApp") kind("WindowedApp")
end end
else else
assert(false, "Invalid tool Kind") assert(false, "Invalid tool kind")
end end
includedirs({ includedirs({
@ -296,94 +208,10 @@ function NazaraBuild:Execute()
"../extlibs/include" "../extlibs/include"
}) })
libdirs("../lib") libdirs({
libdirs("../extlibs/lib/common") "../extlibs/lib/common",
"../lib"
configuration("x32") })
libdirs(toolTable.LibraryPaths.x86)
configuration("x64")
defines("NAZARA_PLATFORM_x64")
libdirs(toolTable.LibraryPaths.x64)
configuration({"codeblocks or codelite or gmake", "x32"})
libdirs("../extlibs/lib/" .. makeLibDir .. "/x86")
libdirs("../lib/" .. makeLibDir .. "/x86")
if (toolTable.Kind == "library") then
targetdir(toolTable.TargetDirectory .. "/" .. makeLibDir .. "/x86")
elseif (toolTable.Kind == "plugin") then
targetdir("../plugins/lib/" .. makeLibDir .. "/x86")
end
configuration({"codeblocks or codelite or gmake", "x64"})
libdirs("../extlibs/lib/" .. makeLibDir .. "/x64")
libdirs("../lib/" .. makeLibDir .. "/x64")
if (toolTable.Kind == "library") then
targetdir(toolTable.TargetDirectory .. "/" .. makeLibDir .. "/x64")
elseif (toolTable.Kind == "plugin") then
targetdir("../plugins/lib/" .. makeLibDir .. "/x64")
end
configuration({"vs*", "x32"})
libdirs("../extlibs/lib/msvc/x86")
libdirs("../lib/msvc/x86")
if (toolTable.Kind == "library") then
targetdir(toolTable.TargetDirectory .. "/msvc/x86")
elseif (toolTable.Kind == "plugin") then
targetdir("../plugins/lib/msvc/x86")
end
configuration({"vs*", "x64"})
libdirs("../extlibs/lib/msvc/x64")
libdirs("../lib/msvc/x64")
if (toolTable.Kind == "library") then
targetdir(toolTable.TargetDirectory .. "/msvc/x64")
elseif (toolTable.Kind == "plugin") then
targetdir("../plugins/lib/msvc/x64")
end
configuration({"xcode3 or xcode4", "x32"})
libdirs("../extlibs/lib/xcode/x86")
libdirs("../lib/xcode/x86")
if (toolTable.Kind == "library") then
targetdir(toolTable.TargetDirectory .. "/xcode/x86")
elseif (toolTable.Kind == "plugin") then
targetdir("../plugins/lib/xcode/x86")
end
configuration({"xcode3 or xcode4", "x64"})
libdirs("../extlibs/lib/xcode/x64")
libdirs("../lib/xcode/x64")
if (toolTable.Kind == "library") then
targetdir(toolTable.TargetDirectory .. "/xcode/x64")
elseif (toolTable.Kind == "plugin") then
targetdir("../plugins/lib/xcode/x64")
end
configuration("*Static")
defines("NAZARA_STATIC")
configuration("Release*")
rtti(toolTable.EnableRTTI and "On" or "Off")
if (toolTable.Kind == "library" or toolTable.Kind == "plugin") then
configuration("*Static")
kind("StaticLib")
configuration("*Dynamic")
kind("SharedLib")
configuration("DebugStatic")
targetsuffix("-s-d")
configuration("ReleaseStatic")
targetsuffix("-s")
configuration("DebugDynamic")
targetsuffix("-d")
end
configuration({})
files(toolTable.Files) files(toolTable.Files)
excludes(toolTable.FilesExcluded) excludes(toolTable.FilesExcluded)
@ -393,12 +221,25 @@ function NazaraBuild:Execute()
includedirs(toolTable.Includes) includedirs(toolTable.Includes)
links(toolTable.Libraries) links(toolTable.Libraries)
-- Output to lib/conf/arch
if (toolTable.Kind == "library") then
self:FilterLibDirectory(toolTable.TargetDirectory .. "/", targetdir)
elseif (toolTable.Kind == "plugin") then
self:FilterLibDirectory("../plugins/lib/", targetdir)
end
filter("architecture:x86")
libdirs(toolTable.LibraryPaths.x86)
filter("architecture:x86_64")
libdirs(toolTable.LibraryPaths.x64)
for k,v in pairs(toolTable.ConfigurationLibraries) do for k,v in pairs(toolTable.ConfigurationLibraries) do
configuration(k) filter(k)
links(v) links(v)
end end
configuration({}) filter({})
end end
for k, exampleTable in ipairs(self.OrderedExamples) do for k, exampleTable in ipairs(self.OrderedExamples) do
@ -429,7 +270,6 @@ function NazaraBuild:Execute()
"../extlibs/include" "../extlibs/include"
}) })
libdirs("../lib") libdirs("../lib")
targetdir(destPath)
files(exampleTable.Files) files(exampleTable.Files)
excludes(exampleTable.FilesExcluded) excludes(exampleTable.FilesExcluded)
@ -438,41 +278,14 @@ function NazaraBuild:Execute()
flags(exampleTable.Flags) flags(exampleTable.Flags)
includedirs(exampleTable.Includes) includedirs(exampleTable.Includes)
links(exampleTable.Libraries) links(exampleTable.Libraries)
targetdir(destPath)
configuration("Release*")
rtti(exampleTable.EnableRTTI and "On" or "Off")
configuration("x32")
libdirs(exampleTable.LibraryPaths.x86)
configuration("x64")
defines("NAZARA_PLATFORM_x64")
libdirs(exampleTable.LibraryPaths.x64)
configuration({"codeblocks or codelite or gmake", "x32"})
libdirs("../lib/" .. makeLibDir .. "/x86")
configuration({"codeblocks or codelite or gmake", "x64"})
libdirs("../lib/" .. makeLibDir .. "/x64")
configuration({"vs*", "x32"})
libdirs("../lib/msvc/x86")
configuration({"vs*", "x64"})
libdirs("../lib/msvc/x64")
configuration({"xcode3 or xcode4", "x32"})
libdirs("../lib/xcode/x86")
configuration({"xcode3 or xcode4", "x64"})
libdirs("../lib/xcode/x64")
for k,v in pairs(exampleTable.ConfigurationLibraries) do for k,v in pairs(exampleTable.ConfigurationLibraries) do
configuration(k) filter(k)
links(v) links(v)
end end
configuration({}) filter({})
end end
end end
end end
@ -712,39 +525,37 @@ function NazaraBuild:LoadConfig()
end end
function NazaraBuild:MakeInstallCommands(infoTable) function NazaraBuild:MakeInstallCommands(infoTable)
if (PremakeVersion < 50) then
return
end
if (os.is("windows")) then if (os.is("windows")) then
configuration("*Dynamic") filter("kind:SharedLib")
postbuildmessage("Copying " .. infoTable.Name .. " library and its dependencies to install/executable directories...")
for k,v in pairs(self.InstallDir) do for k,v in pairs(self.InstallDir) do
local destPath = path.translate(path.isabsolute(k) and k or "../../" .. k) local destPath = path.translate(path.isabsolute(k) and k or "../../" .. k)
postbuildcommands({[[xcopy "%{path.translate(cfg.linktarget.relpath):sub(1, -5) .. ".dll"}" "]] .. destPath .. [[\" /E /Y]]}) postbuildcommands({[[xcopy "%{path.translate(cfg.buildtarget.relpath)}" "]] .. destPath .. [[\" /E /Y]]})
end end
for k,fileName in pairs(table.join(infoTable.Libraries, infoTable.DynLib)) do for k,fileName in pairs(table.join(infoTable.Libraries, infoTable.DynLib)) do
local paths = {} local paths = {}
for k,v in pairs(infoTable.BinaryPaths.x86) do for k,v in pairs(infoTable.BinaryPaths.x86) do
table.insert(paths, {"x32", v .. "/" .. fileName .. ".dll"}) table.insert(paths, {"x86", v .. "/" .. fileName .. ".dll"})
table.insert(paths, {"x32", v .. "/lib" .. fileName .. ".dll"}) table.insert(paths, {"x86", v .. "/lib" .. fileName .. ".dll"})
end end
for k,v in pairs(infoTable.BinaryPaths.x64) do for k,v in pairs(infoTable.BinaryPaths.x64) do
table.insert(paths, {"x64", v .. "/" .. fileName .. ".dll"}) table.insert(paths, {"x86_64", v .. "/" .. fileName .. ".dll"})
table.insert(paths, {"x64", v .. "/lib" .. fileName .. ".dll"}) table.insert(paths, {"x86_64", v .. "/lib" .. fileName .. ".dll"})
end end
for k,v in pairs(paths) do for k,v in pairs(paths) do
local config = v[1] local arch = v[1]
local srcPath = v[2] local srcPath = v[2]
if (os.isfile(srcPath)) then if (os.isfile(srcPath)) then
if (infoTable.Kind == "plugin") then if (infoTable.Kind == "plugin") then
srcPath = "../../" .. srcPath srcPath = "../../" .. srcPath
end end
configuration(config) filter("architecture:" .. arch)
for k,v in pairs(self.ExecutableDir) do for k,v in pairs(self.ExecutableDir) do
local srcPath = path.isabsolute(srcPath) and path.translate(srcPath) or [[%{path.translate(cfg.linktarget.relpath:sub(1, -#cfg.linktarget.name - 1) .. "../../]] .. srcPath .. [[")}]] local srcPath = path.isabsolute(srcPath) and path.translate(srcPath) or [[%{path.translate(cfg.linktarget.relpath:sub(1, -#cfg.linktarget.name - 1) .. "../../]] .. srcPath .. [[")}]]
@ -754,6 +565,8 @@ function NazaraBuild:MakeInstallCommands(infoTable)
end end
end end
end end
filter({})
end end
end end
@ -876,41 +689,125 @@ function NazaraBuild:Process(infoTable)
return true return true
end end
function NazaraBuild:PrepareGeneric()
flags({
"C++14",
"MultiProcessorCompile",
"NoMinimalRebuild",
"RelativeLinks",
"ShadowedVariables",
"UndefinedIdentifiers"
})
self:FilterLibDirectory("../extlibs/lib/", libdirs)
-- Fixes Premake stuff
filter({"kind:SharedLib", clangGccActions})
implibprefix("lib")
filter({"kind:*Lib", clangGccActions, "system:Windows"})
implibextension(".a")
filter({"kind:StaticLib", clangGccActions})
targetextension(".a")
targetprefix("lib")
-- General configuration
filter("kind:*Lib")
pic("On")
filter({"kind:*Lib", "configurations:DebugStatic"})
targetsuffix("-s-d")
filter({"kind:*Lib", "configurations:ReleaseStatic"})
targetsuffix("-s")
filter({"kind:*Lib", "configurations:DebugDynamic"})
targetsuffix("-d")
filter("configurations:Debug*")
symbols("On")
-- Setup some optimizations for release
filter("configurations:Release*")
flags("NoFramePointer")
optimize("Speed")
vectorextensions("SSE2")
filter("configurations:*Static")
kind("StaticLib")
filter("configurations:*Dynamic")
kind("SharedLib")
-- Enable SSE math and vectorization optimizations
filter({"configurations:Release*", clangGccActions})
buildoptions("-mfpmath=sse")
buildoptions("-ftree-vectorize")
filter({})
end
function NazaraBuild:PrepareMainWorkspace()
self:PrepareGeneric()
filter("action:vs*")
buildoptions({"/MP", "/bigobj"}) -- Multiprocessus build and big .obj
defines("_CRT_SECURE_NO_WARNINGS")
defines("_SCL_SECURE_NO_WARNINGS")
filter("architecture:x86_64")
defines("NAZARA_PLATFORM_x64")
filter("configurations:Debug*")
defines("NAZARA_DEBUG")
filter("configurations:*Static")
defines("NAZARA_STATIC")
filter("kind:*Lib")
defines("NAZARA_BUILD")
filter({"system:Windows", clangGccActions})
buildoptions("-Wa,-mbig-obj") -- big object
filter({"system:not Windows", clangGccActions})
buildoptions("-fvisibility=hidden")
filter({})
end
function NazaraBuild:RegisterAction(actionTable) function NazaraBuild:RegisterAction(actionTable)
if (actionTable.Name == nil or type(actionTable.Name) ~= "string" or string.len(actionTable.Name) == 0) then if (not actionTable.Manual) then
return false, "Invalid action name" if (actionTable.Name == nil or type(actionTable.Name) ~= "string" or string.len(actionTable.Name) == 0) then
return false, "Invalid action name"
end
local lowerCaseName = string.lower(actionTable.Name)
if (self.Actions[lowerCaseName] ~= nil) then
return false, "This action name is already in use"
end
if (actionTable.Description == nil or type(actionTable.Description) ~= "string") then
return false, "Action description is invalid"
end
if (string.len(actionTable.Description) == 0) then
return false, "Action description is empty"
end
if (actionTable.Function == nil or type(actionTable.Function) ~= "function") then
return false, "Action function is invalid"
end
self.Actions[lowerCaseName] = actionTable
newaction
{
trigger = lowerCaseName,
description = actionTable.Description,
execute = function () actionTable:Function() end
}
end end
local lowerCaseName = string.lower(actionTable.Name)
if (self.Actions[lowerCaseName] ~= nil) then
return false, "This action name is already in use"
end
if (actionTable.Description == nil or type(actionTable.Description) ~= "string") then
return false, "Action description is invalid"
end
if (string.len(actionTable.Description) == 0) then
return false, "Action description is empty"
end
if (self.Actions[actionTable.name] ~= nil) then
return false, "Action name \"" .. actionTable.name .. " is already registred"
end
if (actionTable.Function == nil or type(actionTable.Function) ~= "function") then
return false, "Action function is invalid"
end
self.Actions[lowerCaseName] = actionTable
newaction
{
trigger = lowerCaseName,
description = actionTable.Description,
execute = function () actionTable:Function() end
}
return true return true
end end

View File

@ -96,7 +96,7 @@ int main()
// Les UVs de ce fichier sont retournées (repère OpenGL, origine coin bas-gauche) par rapport à ce que le moteur attend (haut-gauche) // Les UVs de ce fichier sont retournées (repère OpenGL, origine coin bas-gauche) par rapport à ce que le moteur attend (haut-gauche)
// Nous devons donc indiquer au moteur de les retourner lors du chargement // Nous devons donc indiquer au moteur de les retourner lors du chargement
params.mesh.flipUVs = true; params.mesh.texCoordScale.Set(1.f, -1.f);
// Nazara va par défaut optimiser les modèles pour un rendu plus rapide, cela peut prendre du temps et n'est pas nécessaire ici // Nazara va par défaut optimiser les modèles pour un rendu plus rapide, cela peut prendre du temps et n'est pas nécessaire ici
params.mesh.optimizeIndexBuffers = false; params.mesh.optimizeIndexBuffers = false;

View File

@ -0,0 +1,70 @@
#include "Common.hpp"
#include <Nazara/Core/Error.hpp>
#include <Nazara/Utility/SimpleTextDrawer.hpp>
#include <NDK/Components/ParticleGroupComponent.hpp>
#include <NDK/Systems/RenderSystem.hpp>
ParticleDemo::ParticleDemo(const Nz::String& name, const ExampleShared& exampleShared) :
m_shared(exampleShared),
m_index(s_demoIndex++),
m_name(name)
{
}
void ParticleDemo::Enter(Ndk::StateMachine& fsm)
{
m_shared.demoName->Update(Nz::SimpleTextDrawer::Draw(Nz::String::Number(m_index+1) + " - " + m_name, 48));
m_fpsCounter = 0;
m_updateClock.Restart();
Ndk::RenderSystem& renderSystem2D = m_shared.world2D->GetSystem<Ndk::RenderSystem>();
Ndk::RenderSystem& renderSystem3D = m_shared.world3D->GetSystem<Ndk::RenderSystem>();
m_oldBackground2D = renderSystem2D.GetDefaultBackground();
m_oldBackground3D = renderSystem3D.GetDefaultBackground();
}
void ParticleDemo::Leave(Ndk::StateMachine& fsm)
{
m_shared.world2D->GetSystem<Ndk::RenderSystem>().SetDefaultBackground(m_oldBackground2D);
m_shared.world3D->GetSystem<Ndk::RenderSystem>().SetDefaultBackground(m_oldBackground3D);
m_entities.clear();
m_particleGroups.clear();
}
bool ParticleDemo::Update(Ndk::StateMachine& fsm, float elapsedTime)
{
m_fpsCounter++;
if (m_updateClock.GetMilliseconds() > 1000)
{
m_updateClock.Restart();
m_shared.fpsCount->Update(Nz::SimpleTextDrawer::Draw(Nz::String::Number(m_fpsCounter) + " FPS", 24));
m_fpsCounter = 0;
unsigned int particleCount = 0;
for (const Ndk::EntityHandle& entity : m_particleGroups)
{
const Ndk::ParticleGroupComponent& group = entity->GetComponent<Ndk::ParticleGroupComponent>();
particleCount += group.GetParticleCount();
}
m_shared.particleCount->Update(Nz::SimpleTextDrawer::Draw(Nz::String::Number(particleCount) + " particles", 36));
}
return true;
}
void ParticleDemo::RegisterEntity(const Ndk::EntityHandle& entity)
{
m_entities.emplace_back(entity);
}
void ParticleDemo::RegisterParticleGroup(const Ndk::EntityHandle& entity)
{
NazaraAssert(entity->HasComponent<Ndk::ParticleGroupComponent>(), "Must have particle group component");
m_particleGroups.emplace_back(entity);
}
std::size_t ParticleDemo::s_demoIndex = 0;

View File

@ -0,0 +1,64 @@
#pragma once
#ifndef NAZARA_EXAMPLES_PARTICLES_COMMON_HPP
#define NAZARA_EXAMPLES_PARTICLES_COMMON_HPP
#include <Nazara/Core/Clock.hpp>
#include <Nazara/Graphics/AbstractBackground.hpp>
#include <Nazara/Graphics/TextSprite.hpp>
#include <Nazara/Renderer/RenderWindow.hpp>
#include <NDK/Components/ParticleGroupComponent.hpp>
#include <NDK/EntityOwner.hpp>
#include <NDK/StateMachine.hpp>
#include <NDK/World.hpp>
#include <memory>
#include <random>
#include <vector>
class ParticleDemo;
struct ExampleShared
{
mutable std::mt19937 randomGen;
std::vector<std::shared_ptr<ParticleDemo>> demos;
Nz::RenderWindow* target;
Nz::TextSpriteRef demoName;
Nz::TextSpriteRef fpsCount;
Nz::TextSpriteRef particleCount;
Ndk::EntityHandle viewer2D;
Ndk::EntityHandle viewer3D;
Ndk::WorldHandle world2D;
Ndk::WorldHandle world3D;
};
class ParticleDemo : public Ndk::State
{
public:
ParticleDemo(const Nz::String& name, const ExampleShared& exampleShared);
~ParticleDemo() = default;
void Enter(Ndk::StateMachine& fsm) override;
void Leave(Ndk::StateMachine& fsm) override;
bool Update(Ndk::StateMachine& fsm, float elapsedTime) override;
protected:
const ExampleShared& m_shared;
void RegisterEntity(const Ndk::EntityHandle& entity);
void RegisterParticleGroup(const Ndk::EntityHandle& entity);
private:
std::size_t m_index;
std::vector<Ndk::EntityOwner> m_entities;
std::vector<Ndk::EntityOwner> m_particleGroups;
Nz::BackgroundRef m_oldBackground2D;
Nz::BackgroundRef m_oldBackground3D;
Nz::Clock m_updateClock;
Nz::String m_name;
unsigned int m_fpsCounter;
static std::size_t s_demoIndex;
};
#endif // NAZARA_EXAMPLES_PARTICLES_COMMON_HPP

View File

@ -0,0 +1,170 @@
#include "LogoDemo.hpp"
#include <Nazara/Graphics.hpp>
#include <Nazara/Utility.hpp>
#include <NDK/Components.hpp>
#include <NDK/Systems.hpp>
#include <iostream>
namespace
{
const float duration = 10.f;
const float maxVel = 50.f;
const float pauseTime = 3.f;
const float startTime = 2.f;
const float speed = 3.f;
}
struct SpriteController : public Nz::ParticleController
{
void Apply(Nz::ParticleGroup& system, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, float elapsedTime) override
{
if (!enabled)
return;
auto posPtr = mapper.GetComponentPtr<Nz::Vector3f>(Nz::ParticleComponent_Position);
auto velPtr = mapper.GetComponentPtr<Nz::Vector3f>(Nz::ParticleComponent_Velocity);
for (unsigned int i = startId; i <= endId; ++i)
posPtr[i] += velPtr[i] * elapsedTime * factor;
}
bool enabled = false;
float factor = 1.f;
};
class SpriteRenderer : public Nz::ParticleRenderer
{
public:
SpriteRenderer(Nz::MaterialRef mat) :
m_material(mat)
{
}
void Render(const Nz::ParticleGroup& system, const Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, Nz::AbstractRenderQueue* renderQueue)
{
Nz::Vector2f size(1.f, 1.f);
Nz::SparsePtr<const Nz::Vector2f> sizePtr(&size, 0);
Nz::SparsePtr<const Nz::Vector2f> sinCosPtr(nullptr, 0);
renderQueue->AddBillboards(0, m_material, endId - startId + 1, mapper.GetComponentPtr<const Nz::Vector3f>(Nz::ParticleComponent_Position), sizePtr, sinCosPtr, mapper.GetComponentPtr<const Nz::Color>(Nz::ParticleComponent_Color));
}
private:
Nz::MaterialRef m_material;
};
LogoExample::LogoExample(ExampleShared& sharedData) :
ParticleDemo("Logo", sharedData)
{
Nz::ImageParams params;
params.loadFormat = Nz::PixelFormatType_RGBA8;
if (!m_logo.LoadFromFile("resources/Logo.png", params))
NazaraError("Failed to load logo!");
unsigned int width = m_logo.GetWidth();
unsigned int height = m_logo.GetHeight();
m_pixels.reserve(width * height);
for (unsigned int y = 0; y < height; ++y)
{
for (unsigned int x = 0; x < width; ++x)
{
Nz::Color color = m_logo.GetPixelColor(x, y);
if (color.a == 0)
continue;
PixelData data;
data.pos.Set(x, y);
data.color = color;
m_pixels.push_back(data);
}
}
Nz::MaterialRef material = Nz::Material::New();
material->EnableBlending(true);
material->EnableDepthWrite(false);
material->EnableFaceCulling(false);
material->SetDstBlend(Nz::BlendFunc_InvSrcAlpha);
material->SetSrcBlend(Nz::BlendFunc_SrcAlpha);
m_controller = new SpriteController;
m_renderer = new SpriteRenderer(std::move(material));
}
void LogoExample::Enter(Ndk::StateMachine& fsm)
{
ParticleDemo::Enter(fsm);
m_shared.world3D->GetSystem<Ndk::RenderSystem>().SetDefaultBackground(nullptr);
Nz::TextureRef backgroundTexture = Nz::Texture::New();
if (backgroundTexture->LoadFromFile("resources/stars-background.jpg"))
m_shared.world2D->GetSystem<Ndk::RenderSystem>().SetDefaultBackground(Nz::TextureBackground::New(std::move(backgroundTexture)));
Ndk::EntityHandle particleGroupEntity = m_shared.world2D->CreateEntity();
Ndk::ParticleGroupComponent& particleGroup = particleGroupEntity->AddComponent<Ndk::ParticleGroupComponent>(m_pixels.size(), Nz::ParticleLayout_Sprite);
RegisterParticleGroup(particleGroupEntity);
particleGroup.AddController(m_controller);
particleGroup.SetRenderer(m_renderer);
m_particles = static_cast<Nz::ParticleStruct_Sprite*>(particleGroup.CreateParticles(m_pixels.size()));
ResetParticles(-duration * (speed / 2.f));
m_accumulator = pauseTime + duration;
m_totalAccumulator = 0.f;
}
void LogoExample::Leave(Ndk::StateMachine & fsm)
{
ParticleDemo::Leave(fsm);
}
bool LogoExample::Update(Ndk::StateMachine& fsm, float elapsedTime)
{
if (!ParticleDemo::Update(fsm, elapsedTime))
return false;
m_totalAccumulator += elapsedTime;
if (m_totalAccumulator <= startTime)
return true;
m_accumulator += elapsedTime;
SpriteController* controller = static_cast<SpriteController*>(m_controller.Get());
if (m_accumulator > pauseTime + 2.f * duration)
{
ResetParticles(0.f);
m_accumulator = 0.f;
}
controller->enabled = (m_accumulator > pauseTime);
controller->factor = -speed + speed * (m_accumulator - pauseTime) / (duration);
return true;
}
void LogoExample::ResetParticles(float elapsed)
{
Nz::Vector2f center = {m_shared.target->GetWidth() / 2.f, m_shared.target->GetHeight() / 2.f};
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(-maxVel * ratio, maxVel * ratio);
std::uniform_real_distribution<float> disY(-maxVel, maxVel);
Nz::ParticleStruct_Sprite* sprite = m_particles;
for (PixelData& data : m_pixels)
{
sprite->color = data.color;
sprite->position = offset + Nz::Vector2f(data.pos);
sprite->rotation = 0.f;
sprite->velocity.Set(disX(m_shared.randomGen), disY(m_shared.randomGen), 0.f);
sprite->position += sprite->velocity * elapsed;
sprite++;
}
}

View File

@ -0,0 +1,41 @@
#pragma once
#ifndef NAZARA_EXAMPLES_PARTICLES_LOGO_HPP
#define NAZARA_EXAMPLES_PARTICLES_LOGO_HPP
#include <Nazara/Math/Vector2.hpp>
#include <Nazara/Graphics/ParticleStruct.hpp>
#include <NDK/State.hpp>
#include <vector>
#include "Common.hpp"
class LogoExample : public ParticleDemo
{
public:
LogoExample(ExampleShared& sharedData);
~LogoExample() = default;
void Enter(Ndk::StateMachine& fsm) override;
void Leave(Ndk::StateMachine& fsm) override;
bool Update(Ndk::StateMachine& fsm, float elapsedTime) override;
private:
void ResetParticles(float elapsed);
struct PixelData
{
Nz::Vector2ui pos;
Nz::Color color;
};
std::vector<PixelData> m_pixels;
Nz::BackgroundRef m_oldBackground;
Nz::ParticleStruct_Sprite* m_particles;
Nz::Image m_logo;
Nz::ParticleControllerRef m_controller;
Nz::ParticleRendererRef m_renderer;
float m_accumulator;
float m_totalAccumulator;
};
#endif // NAZARA_EXAMPLES_PARTICLES_LOGO_HPP

View File

@ -0,0 +1,826 @@
#include "SpacebattleDemo.hpp"
#include <Nazara/Audio/Sound.hpp>
#include <Nazara/Core/OffsetOf.hpp>
#include <Nazara/Graphics.hpp>
#include <Nazara/Utility.hpp>
#include <NDK/Components.hpp>
#include <NDK/Systems.hpp>
namespace
{
const float maxLaserLife = 15.f;
const float maxSmokeLife = 20.f;
}
struct SpaceshipComponent : public Ndk::Component<SpaceshipComponent>
{
SpaceshipComponent()
{
engineSound.SetBuffer(Nz::SoundBufferManager::Get("resources/spaceship_loop.wav"));
engineSound.EnableSpatialization(true);
engineSound.SetMinDistance(10.f);
engineSound.SetPitch(1.5f);
hitSound.SetBuffer(Nz::SoundBufferManager::Get("resources/explosion.wav"));
hitSound.EnableSpatialization(true);
hitSound.SetMinDistance(150.f);
laserSound.SetBuffer(Nz::SoundBufferManager::Get("resources/laser.wav"));
laserSound.EnableSpatialization(true);
laserSound.SetMinDistance(150.f);
laserSound.SetVolume(60.f);
}
std::array<Nz::SpriteRef, 2> laserBeamSprites;
Nz::Sound engineSound;
Nz::Sound hitSound;
Nz::Sound laserSound;
Nz::UInt64 hitTime = 0;
Nz::Vector3f targetPos = Nz::Vector3f::Zero();
bool attacking = true;
static Ndk::ComponentIndex componentIndex;
};
Ndk::ComponentIndex SpaceshipComponent::componentIndex;
struct LaserBeamComponent : public Ndk::Component<LaserBeamComponent>
{
LaserBeamComponent()
{
Nz::MaterialRef laserBeamMaterial = Nz::MaterialLibrary::Get("LaserBeam");
for (Nz::Sprite& sprite : sprites)
{
sprite.SetMaterial(laserBeamMaterial);
sprite.SetOrigin(Nz::Vector2f(0.f, 0.5f));
sprite.SetTextureCoords(Nz::Rectf(0.f, 0.f, 50.f, 1.f));
}
}
void OnAttached() override
{
auto& spaceshipCom = m_entity->GetComponent<SpaceshipComponent>();
spaceshipCom.laserSound.Play();
}
std::array<Nz::Sprite, 2> sprites;
Nz::Vector3f origin = Nz::Vector3f::Zero();
float length = 1500.f;
float life = 2.f;
float width = 2.f;
static Ndk::ComponentIndex componentIndex;
};
Ndk::ComponentIndex LaserBeamComponent::componentIndex;
class LaserBeamSystem : public Ndk::System<LaserBeamSystem>
{
public:
LaserBeamSystem(const ExampleShared& sharedData) :
m_sharedData(sharedData)
{
Requires<Ndk::GraphicsComponent, LaserBeamComponent>();
}
void OnEntityAdded(Ndk::Entity* entity) override
{
auto& laserComponent = entity->GetComponent<LaserBeamComponent>();
auto& gfxComponent = entity->GetComponent<Ndk::GraphicsComponent>();
for (Nz::Sprite& sprite : laserComponent.sprites)
sprite.SetSize({laserComponent.length, laserComponent.width});
gfxComponent.Attach(&laserComponent.sprites[0], Nz::Matrix4f::Transform(laserComponent.origin, Nz::EulerAnglesf(0.f, 90.f, 0.f)));
gfxComponent.Attach(&laserComponent.sprites[1], Nz::Matrix4f::Transform(laserComponent.origin, Nz::EulerAnglesf(90.f, 90.f, 0.f)));
}
void OnUpdate(float elapsedTime) override
{
const float scrollSpeed = 2.f;
for (const Ndk::EntityHandle& entity : GetEntities())
{
auto& laserComponent = entity->GetComponent<LaserBeamComponent>();
for (Nz::Sprite& sprite : laserComponent.sprites)
{
Nz::Rectf rect = sprite.GetTextureCoords();
rect.x = std::fmod(rect.x - elapsedTime * scrollSpeed, rect.width);
sprite.SetTextureCoords(rect);
}
}
}
static Ndk::SystemIndex systemIndex;
private:
const ExampleShared& m_sharedData;
};
Ndk::SystemIndex LaserBeamSystem::systemIndex;
class SpaceshipSystem : public Ndk::System<SpaceshipSystem>
{
public:
SpaceshipSystem(const ExampleShared& sharedData) :
m_sharedData(sharedData)
{
Requires<Ndk::NodeComponent, Ndk::VelocityComponent, SpaceshipComponent>();
}
void OnEntityAdded(Ndk::Entity* entity) override
{
std::uniform_real_distribution<float> pitchDis(0.8f, 1.5f);
auto& nodeComponent = entity->GetComponent<Ndk::NodeComponent>();
auto& spaceshipComponent = entity->GetComponent<SpaceshipComponent>();
spaceshipComponent.engineSound.SetPosition(nodeComponent.GetPosition());
spaceshipComponent.engineSound.Play();
spaceshipComponent.engineSound.EnableLooping(true);
spaceshipComponent.laserSound.SetPitch(pitchDis(m_sharedData.randomGen));
}
void OnUpdate(float elapsedTime) override
{
const float escapeMaxDist = 50.f;
const float speed = 200.f;
Nz::UInt64 curTime = Nz::GetElapsedMilliseconds();
std::uniform_real_distribution<float> dis(-escapeMaxDist, escapeMaxDist);
for (const Ndk::EntityHandle& entity : GetEntities())
{
auto& nodeComponent = entity->GetComponent<Ndk::NodeComponent>();
auto& spaceshipComponent = entity->GetComponent<SpaceshipComponent>();
auto& velocityComponent = entity->GetComponent<Ndk::VelocityComponent>();
//< I agree, I need some kind of SoundEmitterComponent
spaceshipComponent.engineSound.SetPosition(nodeComponent.GetPosition());
spaceshipComponent.engineSound.SetVelocity(velocityComponent.linearVelocity);
spaceshipComponent.hitSound.SetPosition(nodeComponent.GetPosition());
spaceshipComponent.hitSound.SetVelocity(velocityComponent.linearVelocity);
spaceshipComponent.laserSound.SetPosition(nodeComponent.GetPosition());
spaceshipComponent.laserSound.SetVelocity(velocityComponent.linearVelocity);
Nz::Vector3f targetDir = spaceshipComponent.targetPos - nodeComponent.GetPosition();
targetDir.Normalize();
Nz::Quaternionf targetRotation = Nz::Quaternionf::RotationBetween(Nz::Vector3f::Forward(), targetDir);
nodeComponent.SetRotation(Nz::Quaternionf::Slerp(nodeComponent.GetRotation(), targetRotation, elapsedTime * 1.5f));
Nz::Vector3f actualDir = nodeComponent.GetForward();
float sqDistance = spaceshipComponent.targetPos.SquaredDistance(nodeComponent.GetPosition());
if (spaceshipComponent.attacking)
{
float dotProduct = targetDir.DotProduct(actualDir);
if (dotProduct > 0.9f && sqDistance < (150.f * 150.f) && !entity->HasComponent<LaserBeamComponent>())
{
auto& laserBeam = entity->AddComponent<LaserBeamComponent>();
laserBeam.origin = Nz::Vector3f::Forward() * 12.f + Nz::Vector3f::Down() * 2.f;
}
if (sqDistance < (100.f * 100.f))
{
entity->RemoveComponent<LaserBeamComponent>();
spaceshipComponent.targetPos -= Nz::Vector3f(dis(m_sharedData.randomGen), dis(m_sharedData.randomGen), dis(m_sharedData.randomGen)) * -actualDir * escapeMaxDist / 2.f;
spaceshipComponent.attacking = false;
}
}
else if (sqDistance < (50.f * 50.f) && spaceshipComponent.hitTime == 0)
{
spaceshipComponent.targetPos = Nz::Vector3f::Zero();
spaceshipComponent.attacking = true;
}
if (spaceshipComponent.hitTime == 0 || curTime - spaceshipComponent.hitTime <= 1000)
velocityComponent.linearVelocity = actualDir * speed;
else if (curTime - spaceshipComponent.hitTime > 10000)
entity->Kill();
}
}
static Ndk::SystemIndex systemIndex;
private:
const ExampleShared& m_sharedData;
};
Ndk::SystemIndex SpaceshipSystem::systemIndex;
struct TorpedoParticle
{
Nz::Color color;
Nz::Vector2f size;
Nz::Vector3f position;
Nz::Vector3f velocity;
float rotation;
float life;
};
SpacebattleExample::SpacebattleExample(ExampleShared& sharedData) :
ParticleDemo("Space battle", sharedData)
{
Ndk::InitializeComponent<LaserBeamComponent>("Lasrbeam");
Ndk::InitializeComponent<SpaceshipComponent>("Spceship");
Ndk::InitializeSystem<LaserBeamSystem>();
Ndk::InitializeSystem<SpaceshipSystem>();
Nz::ModelParameters parameters;
parameters.mesh.optimizeIndexBuffers = false;
Nz::Color grey(100, 100, 100);
if (!m_turret.baseModel.LoadFromFile("resources/Turret/base.obj", parameters))
NazaraWarning("Failed to load base.obj");
for (unsigned int i = 0; i < m_turret.baseModel.GetMaterialCount(); ++i)
m_turret.baseModel.GetMaterial(i)->SetDiffuseColor(grey);
if (!m_turret.rotatingBaseModel.LoadFromFile("resources/Turret/rotating_base.obj", parameters))
NazaraWarning("Failed to load rotating_base.obj");
for (unsigned int i = 0; i < m_turret.rotatingBaseModel.GetMaterialCount(); ++i)
m_turret.rotatingBaseModel.GetMaterial(i)->SetDiffuseColor(grey);
if (!m_turret.cannonBaseModel.LoadFromFile("resources/Turret/cannon_base.obj", parameters))
NazaraWarning("Failed to load cannon_base.obj");
for (unsigned int i = 0; i < m_turret.cannonBaseModel.GetMaterialCount(); ++i)
m_turret.cannonBaseModel.GetMaterial(i)->SetDiffuseColor(grey);
parameters.mesh.texCoordScale.Set(40.f, 40.f);
parameters.mesh.matrix = Nz::Matrix4f::Rotate(Nz::EulerAnglesf(0.f, 180.f, 0.f));
if (!m_turret.cannonModel.LoadFromFile("resources/Turret/cannon.obj", parameters))
NazaraWarning("Failed to load cannon.obj");
// Since OBJ don't support normal maps..
m_turret.cannonModel.GetMaterial(0)->SetNormalMap("resources/Turret/198_norm.jpg");
parameters.mesh.matrix.MakeIdentity();
parameters.mesh.texCoordScale.Set(1.f, 1.f);
parameters.mesh.center = true;
if (!m_spacestationModel.LoadFromFile("resources/SpaceStation/space_station.obj", parameters))
NazaraWarning("Failed to load space_station.obj");
parameters.mesh.texCoordScale.Set(1.f, -1.f);
parameters.mesh.matrix.MakeRotation(Nz::EulerAnglesf(0.f, -90.f, 0.f));
if (!m_spaceshipModel.LoadFromFile("resources/space_frigate_6/space_frigate_6.obj", parameters))
NazaraWarning("Failed to load space_frigate_6.obj");
// Since OBJ don't support normal maps..
for (unsigned int i = 0; i < m_spaceshipModel.GetMaterialCount(); ++i)
{
m_spaceshipModel.GetMaterial(i)->SetEmissiveMap("resources/space_frigate_6/space_frigate_6_illumination.jpg");
m_spaceshipModel.GetMaterial(i)->SetNormalMap("resources/space_frigate_6/space_frigate_6_normal.png");
}
Nz::TextureRef skyboxCubemap = Nz::Texture::New();
if (skyboxCubemap->Create(Nz::ImageType_Cubemap, Nz::PixelFormatType_RGBA8, 2048, 2048))
{
skyboxCubemap->LoadFaceFromFile(Nz::CubemapFace_PositiveX, "resources/purple_nebula_skybox/purple_nebula_skybox_right1.png");
skyboxCubemap->LoadFaceFromFile(Nz::CubemapFace_PositiveY, "resources/purple_nebula_skybox/purple_nebula_skybox_top3.png");
skyboxCubemap->LoadFaceFromFile(Nz::CubemapFace_PositiveZ, "resources/purple_nebula_skybox/purple_nebula_skybox_front5.png");
skyboxCubemap->LoadFaceFromFile(Nz::CubemapFace_NegativeX, "resources/purple_nebula_skybox/purple_nebula_skybox_left2.png");
skyboxCubemap->LoadFaceFromFile(Nz::CubemapFace_NegativeY, "resources/purple_nebula_skybox/purple_nebula_skybox_bottom4.png");
skyboxCubemap->LoadFaceFromFile(Nz::CubemapFace_NegativeZ, "resources/purple_nebula_skybox/purple_nebula_skybox_back6.png");
m_skybox.SetTexture(std::move(skyboxCubemap));
}
m_torpedoDeclaration = Nz::ParticleDeclaration::New();
m_torpedoDeclaration->EnableComponent(Nz::ParticleComponent_Color, Nz::ComponentType_Color, NazaraOffsetOf(TorpedoParticle, color));
m_torpedoDeclaration->EnableComponent(Nz::ParticleComponent_Position, Nz::ComponentType_Float3, NazaraOffsetOf(TorpedoParticle, position));
m_torpedoDeclaration->EnableComponent(Nz::ParticleComponent_Rotation, Nz::ComponentType_Float1, NazaraOffsetOf(TorpedoParticle, rotation));
m_torpedoDeclaration->EnableComponent(Nz::ParticleComponent_Size, Nz::ComponentType_Float2, NazaraOffsetOf(TorpedoParticle, size));
m_torpedoDeclaration->EnableComponent(Nz::ParticleComponent_Life, Nz::ComponentType_Float1, NazaraOffsetOf(TorpedoParticle, life));
m_torpedoDeclaration->EnableComponent(Nz::ParticleComponent_Velocity, Nz::ComponentType_Float3, NazaraOffsetOf(TorpedoParticle, velocity));
Nz::TextureSampler diffuseSampler;
diffuseSampler.SetWrapMode(Nz::SamplerWrap_Repeat);
Nz::MaterialRef material = Nz::Material::New("Translucent3D");
material->SetDiffuseMap("resources/LaserBeam.png");
material->SetDiffuseSampler(diffuseSampler);
Nz::MaterialLibrary::Register("LaserBeam", std::move(material));
Nz::MaterialRef sparkleMat1 = Nz::Material::New("Translucent3D");
sparkleMat1->SetDiffuseMap("resources/flare1.png");
Nz::MaterialLibrary::Register("TorpedoFlare1", std::move(sparkleMat1));
m_spaceshipTemplate = m_shared.world3D->CreateEntity();
m_spaceshipTemplate->Enable(false);
auto& gfxComponent = m_spaceshipTemplate->AddComponent<Ndk::GraphicsComponent>();
auto& nodeComponent = m_spaceshipTemplate->AddComponent<Ndk::NodeComponent>();
auto& velocityComponent = m_spaceshipTemplate->AddComponent<Ndk::VelocityComponent>();
auto& spaceshipComponent = m_spaceshipTemplate->AddComponent<SpaceshipComponent>();
gfxComponent.Attach(&m_spaceshipModel);
m_ambientMusic.OpenFromFile("resources/ambience.ogg");
m_ambientMusic.SetVolume(60.f);
}
void SpacebattleExample::Enter(Ndk::StateMachine& fsm)
{
ParticleDemo::Enter(fsm);
m_shared.world3D->AddSystem<LaserBeamSystem>(m_shared);
m_shared.world3D->AddSystem<SpaceshipSystem>(m_shared);
Ndk::RenderSystem& renderSystem2D = m_shared.world2D->GetSystem<Ndk::RenderSystem>();
Ndk::RenderSystem& renderSystem3D = m_shared.world3D->GetSystem<Ndk::RenderSystem>();
renderSystem2D.SetDefaultBackground(nullptr);
renderSystem3D.SetDefaultBackground(&m_skybox);
CreateSpaceShip();
CreateTurret();
Ndk::EntityHandle light = m_shared.world3D->CreateEntity();
Ndk::NodeComponent& lightNode = light->AddComponent<Ndk::NodeComponent>();
Ndk::LightComponent& lightComp = light->AddComponent<Ndk::LightComponent>(Nz::LightType_Directional);
lightNode.SetRotation(Nz::EulerAnglesf(-30.f, 0.f, 0.f));
RegisterEntity(light);
Ndk::NodeComponent& cameraNode = m_shared.viewer3D->GetComponent<Ndk::NodeComponent>();
cameraNode.SetParent(m_turret.cannonAnchorEntity);
cameraNode.SetPosition(Nz::Vector3f::Up() * 4.f - Nz::Vector3f::Backward() * 6.f);
cameraNode.SetRotation(Nz::EulerAnglesf(0.f, 180.f, 0.f));
m_introTimer = 10.f;
m_spaceshipSpawnCounter = -5.f;
m_turretBaseRotation = 0.f;
m_turretCannonBaseRotation = 0.f;
m_turretShootTimer = 0.f;
Ndk::EntityHandle torpedoGroupEntity = m_shared.world3D->CreateEntity();
m_torpedoGroup = torpedoGroupEntity->AddComponent<Ndk::ParticleGroupComponent>(200, m_torpedoDeclaration).CreateHandle();
RegisterParticleGroup(torpedoGroupEntity);
m_torpedoGroup->AddController(Nz::ParticleFunctionController::New([] (Nz::ParticleGroup& group, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, float elapsedTime)
{
auto positionPtr = mapper.GetComponentPtr<Nz::Vector3f>(Nz::ParticleComponent_Position);
auto lifePtr = mapper.GetComponentPtr<float>(Nz::ParticleComponent_Life);
auto rotationPtr = mapper.GetComponentPtr<float>(Nz::ParticleComponent_Rotation);
auto velocityPtr = mapper.GetComponentPtr<Nz::Vector3f>(Nz::ParticleComponent_Velocity);
for (unsigned int i = startId; i <= endId; ++i)
{
rotationPtr[i] += elapsedTime * 90.f;
positionPtr[i] += velocityPtr[i] * elapsedTime;
lifePtr[i] -= elapsedTime;
if (lifePtr[i] < 0.f)
group.KillParticle(i);
}
}));
m_torpedoGroup->AddController(Nz::ParticleFunctionController::New([this] (Nz::ParticleGroup& group, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, float elapsedTime)
{
auto positionPtr = mapper.GetComponentPtr<Nz::Vector3f>(Nz::ParticleComponent_Position);
auto rotationPtr = mapper.GetComponentPtr<float>(Nz::ParticleComponent_Rotation);
auto sizePtr = mapper.GetComponentPtr<Nz::Vector2f>(Nz::ParticleComponent_Size);
auto velocityPtr = mapper.GetComponentPtr<Nz::Vector3f>(Nz::ParticleComponent_Velocity);
auto& spaceshipSystem = m_shared.world3D->GetSystem<SpaceshipSystem>();
for (unsigned int i = startId; i <= endId; ++i)
{
Nz::Spheref torpedoSphere(positionPtr[i], std::max(sizePtr[i].x, sizePtr[i].y) * 0.1f);
for (const Ndk::EntityHandle& entity : spaceshipSystem.GetEntities())
{
auto& spaceshipNode = entity->GetComponent<Ndk::NodeComponent>();
Nz::Spheref spaceshipSphere(spaceshipNode.GetPosition(), 10.f);
if (torpedoSphere.Intersect(spaceshipSphere))
{
entity->RemoveComponent<LaserBeamComponent>();
group.KillParticle(i);
const float hitMaxDist = 500.f;
std::uniform_real_distribution<float> dis(-hitMaxDist, hitMaxDist);
auto& spaceshipComponent = entity->GetComponent<SpaceshipComponent>();
spaceshipComponent.attacking = false;
spaceshipComponent.engineSound.Stop();
spaceshipComponent.hitSound.Play();
spaceshipComponent.hitTime = Nz::GetElapsedMilliseconds();
spaceshipComponent.targetPos = Nz::Vector3f(dis(m_shared.randomGen), dis(m_shared.randomGen), dis(m_shared.randomGen));
auto& emitter = entity->AddComponent<Ndk::ParticleEmitterComponent>();
emitter.SetEmissionCount(2);
emitter.SetEmissionRate(200.f);
emitter.SetSetupFunc([this] (const Ndk::EntityHandle& entity, Nz::ParticleMapper& mapper, unsigned int count)
{
auto& gen = m_shared.randomGen;
const float maxFireVel = 15.f;
std::uniform_real_distribution<float> lifeDis(-0.5f, 0.5f);
std::uniform_real_distribution<float> normalDis(-1.f, 1.f);
std::uniform_real_distribution<float> posDis(-0.1f, 0.1f);
std::uniform_real_distribution<float> rotDis(-180.f, 180.f);
std::uniform_real_distribution<float> sizeDis(1.0f, 4.f);
std::uniform_real_distribution<float> velDis(-maxFireVel, maxFireVel);
Nz::Vector3f pos = entity->GetComponent<Ndk::NodeComponent>().GetPosition();
Nz::ParticleStruct_Billboard* billboards = static_cast<Nz::ParticleStruct_Billboard*>(mapper.GetPointer());
Nz::ParticleStruct_Billboard* smokeParticles = static_cast<Nz::ParticleStruct_Billboard*>(m_smokeGroup->CreateParticles(count));
for (unsigned int i = 0; i < count; ++i)
{
billboards[i].color = Nz::Color::White;
billboards[i].life = 1.f + lifeDis(gen);
billboards[i].position = pos + Nz::Vector3f(posDis(gen), posDis(gen), posDis(gen));
billboards[i].rotation = rotDis(gen);
billboards[i].size = {1.28f, 1.28f};
billboards[i].size *= sizeDis(gen);
billboards[i].velocity.Set(normalDis(gen), normalDis(gen), normalDis(gen));
billboards[i].velocity.Normalize();
billboards[i].velocity *= velDis(gen);
smokeParticles[i].color = Nz::Color(128, 128, 128, 0);
smokeParticles[i].life = maxSmokeLife;
smokeParticles[i].position = billboards[i].position;
smokeParticles[i].rotation = billboards[i].rotation;
smokeParticles[i].size = {2.56f, 2.56f};
smokeParticles[i].size *= sizeDis(gen);
smokeParticles[i].velocity = billboards[i].velocity / 2.f;
}
});
m_fireGroup->AddEmitter(entity);
break;
}
}
}
}));
m_torpedoGroup->SetRenderer(Nz::ParticleFunctionRenderer::New([sparkleMat1 = Nz::MaterialLibrary::Get("TorpedoFlare1")] (const Nz::ParticleGroup& group, const Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, Nz::AbstractRenderQueue* renderQueue)
{
auto positionPtr = mapper.GetComponentPtr<const Nz::Vector3f>(Nz::ParticleComponent_Position);
auto rotationPtr = mapper.GetComponentPtr<const float>(Nz::ParticleComponent_Rotation);
auto sizePtr = mapper.GetComponentPtr<const Nz::Vector2f>(Nz::ParticleComponent_Size);
auto velocityPtr = mapper.GetComponentPtr<const Nz::Vector3f>(Nz::ParticleComponent_Velocity);
renderQueue->AddBillboards(0, sparkleMat1, endId - startId + 1, positionPtr, sizePtr, rotationPtr);
for (unsigned int i = startId; i <= endId; ++i)
{
Nz::AbstractRenderQueue::PointLight pointLight;
pointLight.ambientFactor = 0.f;
pointLight.attenuation = 0.9f;
pointLight.color = Nz::Color::Cyan;
pointLight.diffuseFactor = 1.f;
pointLight.position = positionPtr[i];
pointLight.radius = std::max(sizePtr[i].x, sizePtr[i].y) * 2.f;
pointLight.invRadius = 1.f / pointLight.radius;
pointLight.shadowMap = nullptr;
renderQueue->AddPointLight(pointLight);
}
}));
//////////////////////////////////////////////////////////////////////////
Ndk::EntityHandle fireGroupEntity = m_shared.world3D->CreateEntity();
m_fireGroup = fireGroupEntity->AddComponent<Ndk::ParticleGroupComponent>(40000, Nz::ParticleDeclaration::Get(Nz::ParticleLayout_Billboard)).CreateHandle();
RegisterParticleGroup(fireGroupEntity);
Ndk::EntityHandle smokeGroupEntity = m_shared.world3D->CreateEntity();
m_smokeGroup = smokeGroupEntity->AddComponent<Ndk::ParticleGroupComponent>(40000, Nz::ParticleDeclaration::Get(Nz::ParticleLayout_Billboard)).CreateHandle();
RegisterParticleGroup(smokeGroupEntity);
auto movementController = Nz::ParticleFunctionController::New([this] (Nz::ParticleGroup& group, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, float elapsedTime)
{
auto lifePtr = mapper.GetComponentPtr<float>(Nz::ParticleComponent_Life);
auto posPtr = mapper.GetComponentPtr<Nz::Vector3f>(Nz::ParticleComponent_Position);
auto sizePtr = mapper.GetComponentPtr<Nz::Vector2f>(Nz::ParticleComponent_Size);
auto velPtr = mapper.GetComponentPtr<Nz::Vector3f>(Nz::ParticleComponent_Velocity);
auto& spaceshipSystem = m_shared.world3D->GetSystem<SpaceshipSystem>();
const Nz::Vector2f sizeGrowth(0.5f);
float velFactor = std::pow(0.9f, elapsedTime * 15.f);
for (unsigned int i = startId; i <= endId; ++i)
{
float& remainingLife = lifePtr[i];
remainingLife -= elapsedTime;
if (remainingLife <= 0.f)
{
group.KillParticle(i);
continue;
}
Nz::Vector3f& position = posPtr[i];
Nz::Vector2f& size = sizePtr[i];
Nz::Vector3f& velocity = velPtr[i];
position += velPtr[i] * elapsedTime;
size += sizeGrowth * elapsedTime;
velocity *= (velocity.GetSquaredLength() >= 1.f) ? velFactor : 1.f;
if (remainingLife <= 18.f)
{
for (const Ndk::EntityHandle& entity : spaceshipSystem.GetEntities())
{
auto& spaceshipNode = entity->GetComponent<Ndk::NodeComponent>();
Nz::Spheref spaceshipSphere(spaceshipNode.GetPosition(), 5.f);
if (spaceshipSphere.Contains(position))
{
auto& spaceshipVel = entity->GetComponent<Ndk::VelocityComponent>();
Nz::Vector3f force = spaceshipVel.linearVelocity * 2.f + (position - spaceshipSphere.GetPosition()) * 10.f;
velocity += force * elapsedTime;
}
}
TorpedoParticle* torpedos = static_cast<TorpedoParticle*>(m_torpedoGroup->GetBuffer());
std::size_t torpedoCount = m_torpedoGroup->GetParticleCount();
for (std::size_t j = 0; j < torpedoCount; ++j)
{
Nz::Spheref tordedoSphere(torpedos[j].position, 5.f);
if (tordedoSphere.Contains(position))
{
Nz::Spheref tordedoCenter(torpedos[j].position, 2.f);
if (tordedoCenter.Contains(position))
{
group.KillParticle(i);
break;
}
Nz::Vector3f dir = (torpedos[j].position - position);
float length;
dir.Normalize(&length);
remainingLife -= 100.f * elapsedTime / length;
size -= 100.f * sizeGrowth * elapsedTime / length;
velocity += 500.f * dir * elapsedTime / length;
velocity += torpedos[j].velocity * elapsedTime;
break; //< There's no way a particle would be in multiple torpedo at once
}
}
}
}
});
m_fireGroup->AddController(movementController);
m_fireGroup->AddController(Nz::ParticleFunctionController::New([] (Nz::ParticleGroup& group, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, float elapsedTime)
{
auto colorPtr = mapper.GetComponentPtr<Nz::Color>(Nz::ParticleComponent_Color);
auto lifePtr = mapper.GetComponentPtr<float>(Nz::ParticleComponent_Life);
float velFactor = std::pow(0.9f, elapsedTime / 0.1f);
for (unsigned int i = startId; i <= endId; ++i)
colorPtr[i].a = static_cast<Nz::UInt8>(Nz::Clamp(lifePtr[i] * 255.f, 0.f, 255.f));
}));
m_smokeGroup->AddController(movementController);
m_smokeGroup->AddController(Nz::ParticleFunctionController::New([] (Nz::ParticleGroup& group, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, float elapsedTime)
{
auto colorPtr = mapper.GetComponentPtr<Nz::Color>(Nz::ParticleComponent_Color);
auto lifePtr = mapper.GetComponentPtr<float>(Nz::ParticleComponent_Life);
for (unsigned int i = startId; i <= endId; ++i)
{
float alpha = std::min((maxSmokeLife - lifePtr[i]) * 255.f / 5.f, 255.f);
alpha -= std::max((maxSmokeLife - lifePtr[i]) / maxSmokeLife * 255.f, 0.f);
colorPtr[i].a = static_cast<Nz::UInt8>(Nz::Clamp(alpha, 0.f, 255.f));
}
}));
Nz::MaterialRef fireMat = Nz::Material::New("Translucent3D");
fireMat->EnableFaceCulling(true);
fireMat->SetDiffuseMap("resources/fire_particle.png");
// Additive blending for fire
fireMat->SetDstBlend(Nz::BlendFunc_One);
fireMat->SetSrcBlend(Nz::BlendFunc_SrcAlpha);
Nz::MaterialRef smokeMat = Nz::Material::New("Translucent3D");
smokeMat->EnableFaceCulling(true);
smokeMat->SetDiffuseColor(Nz::Color(128, 128, 128));
smokeMat->SetDiffuseMap("resources/smoke.png");
m_fireGroup->SetRenderer(Nz::ParticleFunctionRenderer::New([fireMat] (const Nz::ParticleGroup& group, const Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, Nz::AbstractRenderQueue* renderQueue)
{
auto colorPtr = mapper.GetComponentPtr<const Nz::Color>(Nz::ParticleComponent_Color);
auto posPtr = mapper.GetComponentPtr<const Nz::Vector3f>(Nz::ParticleComponent_Position);
auto rotPtr = mapper.GetComponentPtr<const float>(Nz::ParticleComponent_Rotation);
auto sizePtr = mapper.GetComponentPtr<const Nz::Vector2f>(Nz::ParticleComponent_Size);
renderQueue->AddBillboards(0, fireMat, endId - startId + 1, posPtr, sizePtr, rotPtr, colorPtr);
}));
m_smokeGroup->SetRenderer(Nz::ParticleFunctionRenderer::New([smokeMat] (const Nz::ParticleGroup& group, const Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, Nz::AbstractRenderQueue* renderQueue)
{
auto colorPtr = mapper.GetComponentPtr<const Nz::Color>(Nz::ParticleComponent_Color);
auto posPtr = mapper.GetComponentPtr<const Nz::Vector3f>(Nz::ParticleComponent_Position);
auto rotPtr = mapper.GetComponentPtr<const float>(Nz::ParticleComponent_Rotation);
auto sizePtr = mapper.GetComponentPtr<const Nz::Vector2f>(Nz::ParticleComponent_Size);
renderQueue->AddBillboards(0, smokeMat, endId - startId + 1, posPtr, sizePtr, rotPtr, colorPtr);
}));
//////////////////////////////////////////////////////////////////////////
m_ambientMusic.Play();
m_turretFireSound.LoadFromFile("resources/turretFire.wav");
m_turretReloadSound.LoadFromFile("resources/turretReload.wav");
//m_onMouseMoved.Connect(m_shared.target->GetEventHandler().OnMouseMoved, this, &SpacebattleExample::OnMouseMoved);
//m_shared.target->SetCursor(Nz::WindowCursor_None);
//////////////////////////////////////////////////////////////////////////
Nz::TextSpriteRef introText = Nz::TextSprite::New();
introText->Update(Nz::SimpleTextDrawer::Draw("--Tourelle de défense du secteur A407M2--\nLes contrôles ont été adaptés à vos contrôleurs:\nZQSD pour orienter la tourelle, espace pour tirer.\n", 72));
introText->SetScale(0.5f);
m_introText = m_shared.world3D->CreateEntity();
Ndk::NodeComponent& introNode = m_introText->AddComponent<Ndk::NodeComponent>();
Ndk::GraphicsComponent& introGfx = m_introText->AddComponent<Ndk::GraphicsComponent>();
introGfx.Attach(introText, 1);
RegisterEntity(m_introText);
Ndk::NodeComponent& cannonNode = m_turret.cannonEntity->GetComponent<Ndk::NodeComponent>();
Nz::Boxf introAABB = introGfx.GetBoundingVolume().aabb;
introNode.SetPosition(cannonNode.GetForward() * 500.f + introNode.GetLeft() * introAABB.width / 2.f + introNode.GetUp() * introAABB.height / 2.f);
}
void SpacebattleExample::Leave(Ndk::StateMachine& fsm)
{
m_ambientMusic.Stop();
m_shared.world3D->RemoveSystem<LaserBeamSystem>();
m_shared.world3D->RemoveSystem<SpaceshipSystem>();
m_turretFireSound.Stop();
m_turretReloadSound.Stop();
ParticleDemo::Leave(fsm);
}
bool SpacebattleExample::Update(Ndk::StateMachine& fsm, float elapsedTime)
{
if (!ParticleDemo::Update(fsm, elapsedTime))
return false;
const float speed = 100.f;
if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::Z))
m_turretCannonBaseRotation = std::max(m_turretCannonBaseRotation - speed * elapsedTime, -65.f);
if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::S))
m_turretCannonBaseRotation = std::min(m_turretCannonBaseRotation + speed * elapsedTime, 40.f);
if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::Q))
m_turretBaseRotation += speed * elapsedTime;
if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::D))
m_turretBaseRotation -= speed * elapsedTime;
m_turret.cannonBaseEntity->GetComponent<Ndk::NodeComponent>().SetRotation(Nz::EulerAnglesf(m_turretCannonBaseRotation, 0.f, 0.f));
m_turret.rotatingBaseEntity->GetComponent<Ndk::NodeComponent>().SetRotation(Nz::EulerAnglesf(0.f, m_turretBaseRotation, 0.f));
bool discharged = m_turretShootTimer < 1.f;
if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::Space) && !discharged)
{
m_turretFireSound.Play();
m_turretShootTimer = -1.f;
Ndk::NodeComponent& cannonNode = m_turret.cannonEntity->GetComponent<Ndk::NodeComponent>();
TorpedoParticle* particle = static_cast<TorpedoParticle*>(m_torpedoGroup->CreateParticle());
particle->color = Nz::Color::White;
particle->position = cannonNode.ToGlobalPosition(Nz::Vector3f::Forward() * 10.f);
particle->rotation = 0.f;
particle->life = 15.f;
particle->size.Set(13.34f, 7.41f);
particle->size *= 2.f;
particle->velocity = cannonNode.GetForward() * 100.f;
}
m_turretShootTimer += elapsedTime * 2.f;
if (discharged && m_turretShootTimer >= 1.f)
m_turretReloadSound.Play();
m_turret.cannonEntity->GetComponent<Ndk::NodeComponent>().SetPosition(Nz::Vector3f::Backward() * std::sin(std::min(m_turretShootTimer, 0.f) * float(M_PI)) * 3.f);
m_spaceshipSpawnCounter += elapsedTime;
if (m_spaceshipSpawnCounter >= 10.f)
{
m_spaceshipSpawnCounter -= 10.f;
auto& spacestationNode = m_spacestationEntity->GetComponent<Ndk::NodeComponent>();
Ndk::EntityHandle spaceship = m_spaceshipTemplate->Clone();
RegisterEntity(spaceship);
auto& nodeComponent = spaceship->GetComponent<Ndk::NodeComponent>();
auto& spaceshipComponent = spaceship->GetComponent<SpaceshipComponent>();
spaceshipComponent.targetPos = m_shared.viewer3D->GetComponent<Ndk::NodeComponent>().GetPosition();
nodeComponent.SetPosition(spacestationNode.GetPosition());
nodeComponent.SetRotation(Nz::Quaternionf::RotationBetween(Nz::Vector3f::Forward(), spacestationNode.GetRight()));
nodeComponent.Move(Nz::Vector3f::Forward() * 15.f + Nz::Vector3f::Down() * 5.f, Nz::CoordSys_Local);
}
m_introTimer -= elapsedTime;
if (m_introTimer <= 0.f && m_introText)
m_introText->Kill();
return true;
}
void SpacebattleExample::CreateSpaceShip()
{
m_spacestationEntity = m_shared.world3D->CreateEntity();
RegisterEntity(m_spacestationEntity);
Ndk::NodeComponent& spacestationNode = m_spacestationEntity->AddComponent<Ndk::NodeComponent>();
spacestationNode.SetPosition(Nz::Vector3f::Forward() * 500.f + Nz::Vector3f::Up() * 200.f + Nz::Vector3f::Right() * 250.f);
spacestationNode.SetRotation(Nz::EulerAnglesf(0.f, 15.f, 0.f));
spacestationNode.SetScale(0.1f);
Ndk::GraphicsComponent& spacestationGfx = m_spacestationEntity->AddComponent<Ndk::GraphicsComponent>();
spacestationGfx.Attach(&m_spacestationModel);
}
void SpacebattleExample::CreateTurret()
{
// Fixed base
m_turret.baseEntity = m_shared.world3D->CreateEntity();
RegisterEntity(m_turret.baseEntity);
Ndk::NodeComponent& baseNode = m_turret.baseEntity->AddComponent<Ndk::NodeComponent>();
//baseNode.SetParent(m_spacestationEntity);
baseNode.SetRotation(Nz::EulerAnglesf(0.f, 180.f, 0.f));
Ndk::GraphicsComponent& baseGfx = m_turret.baseEntity->AddComponent<Ndk::GraphicsComponent>();
baseGfx.Attach(&m_turret.baseModel);
// Rotating base
m_turret.rotatingBaseEntity = m_shared.world3D->CreateEntity();
RegisterEntity(m_turret.rotatingBaseEntity);
Ndk::NodeComponent& rotatingBaseNode = m_turret.rotatingBaseEntity->AddComponent<Ndk::NodeComponent>();
rotatingBaseNode.SetParent(m_turret.baseEntity);
Ndk::GraphicsComponent& rotatingBaseGfx = m_turret.rotatingBaseEntity->AddComponent<Ndk::GraphicsComponent>();
rotatingBaseGfx.Attach(&m_turret.rotatingBaseModel);
// Cannon base
m_turret.cannonBaseEntity = m_shared.world3D->CreateEntity();
RegisterEntity(m_turret.cannonBaseEntity);
Ndk::NodeComponent& cannonBaseNode = m_turret.cannonBaseEntity->AddComponent<Ndk::NodeComponent>();
cannonBaseNode.SetPosition({0.f, 3.39623547f, 0.f});
cannonBaseNode.SetParent(m_turret.rotatingBaseEntity);
Ndk::GraphicsComponent& cannonBaseGfx = m_turret.cannonBaseEntity->AddComponent<Ndk::GraphicsComponent>();
cannonBaseGfx.Attach(&m_turret.cannonBaseModel);
// Cannon anchor
m_turret.cannonAnchorEntity = m_shared.world3D->CreateEntity();
RegisterEntity(m_turret.cannonAnchorEntity);
Ndk::NodeComponent& cannonAnchorNode = m_turret.cannonAnchorEntity->AddComponent<Ndk::NodeComponent>();
cannonAnchorNode.SetPosition({0.f, 2.96482944f, 3.20705462f});
cannonAnchorNode.SetParent(m_turret.cannonBaseEntity);
// Cannon
m_turret.cannonEntity = m_shared.world3D->CreateEntity();
RegisterEntity(m_turret.cannonEntity);
Ndk::NodeComponent& cannonNode = m_turret.cannonEntity->AddComponent<Ndk::NodeComponent>();
cannonNode.SetParent(m_turret.cannonAnchorEntity);
cannonNode.SetRotation(Nz::EulerAnglesf(0.f, 180.f, 0.f));
Ndk::GraphicsComponent& cannonGfx = m_turret.cannonEntity->AddComponent<Ndk::GraphicsComponent>();
cannonGfx.Attach(&m_turret.cannonModel);
}
void SpacebattleExample::OnMouseMoved(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseMoveEvent& event)
{
const float speed = 0.1f;
m_turretCannonBaseRotation = Nz::Clamp(m_turretCannonBaseRotation + speed * event.deltaY, -65.f, 40.f);
m_turretBaseRotation -= event.deltaX * speed;
Nz::Mouse::SetPosition(m_shared.target->GetWidth() / 2, m_shared.target->GetHeight() / 2, *m_shared.target);
}

View File

@ -0,0 +1,71 @@
#pragma once
#ifndef NAZARA_EXAMPLES_PARTICLES_SPACEBATTLE_HPP
#define NAZARA_EXAMPLES_PARTICLES_SPACEBATTLE_HPP
#include <Nazara/Audio/Music.hpp>
#include <Nazara/Audio/Sound.hpp>
#include <Nazara/Graphics/AbstractBackground.hpp>
#include <Nazara/Graphics/Model.hpp>
#include <Nazara/Graphics/ParticleStruct.hpp>
#include <Nazara/Graphics/SkyboxBackground.hpp>
#include <Nazara/Math/Vector2.hpp>
#include <Nazara/Utility/EventHandler.hpp>
#include <NDK/Entity.hpp>
#include <NDK/State.hpp>
#include <vector>
#include "Common.hpp"
class SpacebattleExample : public ParticleDemo
{
public:
SpacebattleExample(ExampleShared& sharedData);
~SpacebattleExample() = default;
void Enter(Ndk::StateMachine& fsm) override;
void Leave(Ndk::StateMachine& fsm) override;
bool Update(Ndk::StateMachine& fsm, float elapsedTime) override;
private:
void CreateSpaceShip();
void CreateTurret();
void OnMouseMoved(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseMoveEvent& event);
struct Turret
{
Nz::Model baseModel;
Nz::Model cannonModel;
Nz::Model cannonBaseModel;
Nz::Model rotatingBaseModel;
Ndk::EntityHandle baseEntity;
Ndk::EntityHandle cannonAnchorEntity;
Ndk::EntityHandle cannonEntity;
Ndk::EntityHandle cannonBaseEntity;
Ndk::EntityHandle rotatingBaseEntity;
};
Turret m_turret;
float m_introTimer;
float m_spaceshipSpawnCounter;
float m_turretBaseRotation;
float m_turretCannonBaseRotation;
float m_turretShootTimer;
Nz::Model m_spaceshipModel;
Nz::Model m_spacestationModel;
Nz::Music m_ambientMusic;
Nz::ParticleDeclarationRef m_torpedoDeclaration;
Nz::ParticleRendererRef m_laserBeamRenderer;
Nz::Sound m_turretFireSound;
Nz::Sound m_turretReloadSound;
Nz::SkyboxBackground m_skybox;
Ndk::EntityHandle m_introText;
Ndk::EntityHandle m_spaceshipTemplate;
Ndk::EntityHandle m_spacestationEntity;
Ndk::ParticleGroupComponentHandle m_fireGroup;
Ndk::ParticleGroupComponentHandle m_smokeGroup;
Ndk::ParticleGroupComponentHandle m_torpedoGroup;
NazaraSlot(Nz::EventHandler, OnMouseMoved, m_onMouseMoved);
};
#endif // NAZARA_EXAMPLES_PARTICLES_SPACEBATTLE_HPP

View File

@ -0,0 +1,13 @@
EXAMPLE.Name = "Particles"
EXAMPLE.EnableConsole = true
EXAMPLE.Files = {
"*.hpp",
"*.inl",
"*.cpp"
}
EXAMPLE.Libraries = {
"NazaraSDK"
}

202
examples/Particles/main.cpp Normal file
View File

@ -0,0 +1,202 @@
#include <Nazara/Audio.hpp>
#include <Nazara/Core.hpp>
#include <Nazara/Graphics.hpp>
#include <Nazara/Lua.hpp>
#include <Nazara/Network.hpp>
#include <Nazara/Noise.hpp>
#include <Nazara/Physics3D.hpp>
#include <Nazara/Renderer.hpp>
#include <Nazara/Utility.hpp>
#include <NDK/Application.hpp>
#include <NDK/Components.hpp>
#include <NDK/Systems.hpp>
#include <NDK/StateMachine.hpp>
#include "LogoDemo.hpp"
#include "SpacebattleDemo.hpp"
#include <iostream>
int main()
{
Nz::ContextParameters::defaultCompatibilityProfile = true;
Ndk::Application app;
// Mix all sounds in mono (in order to give them 3D position)
Nz::SoundBufferParams soundParams;
soundParams.forceMono = true;
Nz::SoundBufferManager::SetDefaultParameters(soundParams);
// Pour commencer le mode vidéo, celui-ci va définir la taille de la zone de rendu et le nombre de bits par pixels
Nz::VideoMode mode = Nz::VideoMode::GetDesktopMode(); // Nous récupérons le mode vidéo du bureau
// Nous allons prendre les trois quarts de la résolution du bureau pour notre fenêtre
mode.width = 3 * mode.width / 4;
mode.height = 3 * mode.height / 4;
Nz::ContextParameters targetParams;
targetParams.antialiasingLevel = 0;
Nz::RenderWindow& window = app.AddWindow<Nz::RenderWindow>(mode, "Nazara demo - Particles", Nz::WindowStyle_Closable, targetParams);
//Nz::RenderWindow& window = app.AddWindow<Nz::RenderWindow>(Nz::VideoMode(1920, 1080), "Nazara demo - Particles", Nz::WindowStyle_Fullscreen, targetParams);
Ndk::World& world3D = app.AddWorld();
Ndk::World& world2D = app.AddWorld();
std::random_device randomDevice;
ExampleShared shared;
shared.randomGen.seed(randomDevice());
shared.target = &window;
shared.world2D = &world2D;
shared.world3D = &world3D;
shared.demoName = Nz::TextSprite::New();
shared.demoName->Update(Nz::SimpleTextDrawer::Draw("XX - DemoName", 48));
shared.fpsCount = Nz::TextSprite::New();
shared.fpsCount->Update(Nz::SimpleTextDrawer::Draw("XXXXX FPS", 24));
shared.particleCount = Nz::TextSprite::New();
shared.particleCount->Update(Nz::SimpleTextDrawer::Draw("XXXXX particles", 36));
world2D.GetSystem<Ndk::RenderSystem>().SetGlobalUp(Nz::Vector3f::Down());
world3D.GetSystem<Ndk::RenderSystem>().ChangeRenderTechnique<Nz::DeferredRenderTechnique>();
Ndk::EntityHandle viewEntity = world2D.CreateEntity();
viewEntity->AddComponent<Ndk::NodeComponent>();
Ndk::CameraComponent& viewer = viewEntity->AddComponent<Ndk::CameraComponent>();
viewer.SetTarget(&window);
viewer.SetProjectionType(Nz::ProjectionType_Orthogonal);
shared.viewer2D = viewEntity;
Ndk::EntityHandle cameraEntity = world3D.CreateEntity();
cameraEntity->AddComponent<Ndk::NodeComponent>();
cameraEntity->AddComponent<Ndk::ListenerComponent>();
Ndk::CameraComponent& camera = cameraEntity->AddComponent<Ndk::CameraComponent>();
camera.SetTarget(&window);
camera.SetZFar(10000.f);
shared.viewer3D = cameraEntity;
Ndk::EntityHandle demoNameEntity = world2D.CreateEntity();
Ndk::NodeComponent& demoNameNode = demoNameEntity->AddComponent<Ndk::NodeComponent>();
Ndk::GraphicsComponent& demoNameGfx = demoNameEntity->AddComponent<Ndk::GraphicsComponent>();
demoNameGfx.Attach(shared.demoName, 1);
Ndk::EntityHandle fpsCountEntity = world2D.CreateEntity();
Ndk::NodeComponent& fpsNode = fpsCountEntity->AddComponent<Ndk::NodeComponent>();
Ndk::GraphicsComponent& fpsGfx = fpsCountEntity->AddComponent<Ndk::GraphicsComponent>();
fpsGfx.Attach(shared.fpsCount, 1);
Ndk::EntityHandle particleCountEntity = world2D.CreateEntity();
Ndk::NodeComponent& particleCountNode = particleCountEntity->AddComponent<Ndk::NodeComponent>();
Ndk::GraphicsComponent& particleCountGfx = particleCountEntity->AddComponent<Ndk::GraphicsComponent>();
particleCountGfx.Attach(shared.particleCount, 1);
Nz::Boxf fpsCountBox = fpsGfx.GetBoundingVolume().aabb;
Nz::Boxf particleCountBox = particleCountGfx.GetBoundingVolume().aabb;
demoNameNode.SetPosition(5.f, 5.f);
particleCountNode.SetPosition(5.f, window.GetHeight() - particleCountBox.height - 5.f);
fpsNode.SetPosition(5.f, window.GetHeight() - fpsCountBox.height - particleCountBox.height - 5.f);
//shared.demos.push_back(std::make_shared<LogoExample>(shared));
shared.demos.push_back(std::make_shared<SpacebattleExample>(shared));
std::size_t demoIndex = 0;
Ndk::StateMachine stateMachine(shared.demos[demoIndex]);
window.EnableEventPolling(true);
while (app.Run())
{
Nz::WindowEvent event;
while (window.PollEvent(&event))
{
switch (event.type)
{
case Nz::WindowEventType_KeyPressed:
{
switch (event.key.code)
{
case Nz::Keyboard::Backspace:
stateMachine.ChangeState(stateMachine.GetCurrentState());
break;
case Nz::Keyboard::Escape:
app.Quit();
break;
case Nz::Keyboard::Left:
{
if (shared.demos.size() <= 1)
break;
if (demoIndex == 0)
demoIndex = shared.demos.size();
demoIndex--;
stateMachine.ChangeState(shared.demos[demoIndex]);
break;
}
case Nz::Keyboard::Right:
{
if (shared.demos.size() <= 1)
break;
demoIndex++;
if (demoIndex == shared.demos.size())
demoIndex = 0;
stateMachine.ChangeState(shared.demos[demoIndex]);
break;
}
case Nz::Keyboard::Pause:
{
auto& velocitySystem = shared.world3D->GetSystem<Ndk::VelocitySystem>();
velocitySystem.Enable(!velocitySystem.IsEnabled());
break;
}
case Nz::Keyboard::F5:
{
Nz::Image screenshot;
screenshot.Create(Nz::ImageType_2D, Nz::PixelFormatType_RGBA8, 1920, 1080);
window.CopyToImage(&screenshot);
static unsigned int counter = 1;
screenshot.SaveToFile("screenshot_" + Nz::String::Number(counter++) + ".png");
break;
}
default:
break;
}
break;
}
case Nz::WindowEventType_Quit:
window.Close();
break;
default:
break;
}
}
stateMachine.Update(app.GetUpdateTime());
window.Display();
}
return EXIT_SUCCESS;
}

View File

@ -1,4 +1,4 @@
// This file was automatically generated on 24 Jun 2015 at 13:55:50 // This file was automatically generated
/* /*
Nazara Engine - Audio module Nazara Engine - Audio module

View File

@ -73,6 +73,7 @@ namespace Nz
bool FillAndQueueBuffer(unsigned int buffer); bool FillAndQueueBuffer(unsigned int buffer);
void MusicThread(); void MusicThread();
void StopThread();
static MusicLoader::LoaderList s_loaders; static MusicLoader::LoaderList s_loaders;
}; };

View File

@ -1,4 +1,4 @@
// This file was automatically generated on 09 May 2016 at 17:07:09 // This file was automatically generated
/* /*
Nazara Engine - Core module Nazara Engine - Core module

View File

@ -1,10 +0,0 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
/*!
* \ingroup core
* \class Nz::AbstractLogger
* \brief Logger interface
*/

View File

@ -22,6 +22,7 @@ namespace Nz
template<typename F, typename Tuple> decltype(auto) Apply(F&& fn, Tuple&& t); template<typename F, typename Tuple> decltype(auto) Apply(F&& fn, Tuple&& t);
template<typename O, typename F, typename Tuple> decltype(auto) Apply(O& object, F&& fn, Tuple&& t); template<typename O, typename F, typename Tuple> decltype(auto) Apply(O& object, F&& fn, Tuple&& t);
template<typename T> constexpr std::size_t BitCount();
template<typename T> ByteArray ComputeHash(HashType hash, const T& v); template<typename T> ByteArray ComputeHash(HashType hash, const T& v);
template<typename T> ByteArray ComputeHash(AbstractHash* hash, const T& v); template<typename T> ByteArray ComputeHash(AbstractHash* hash, const T& v);
template<typename T, std::size_t N> constexpr std::size_t CountOf(T(&name)[N]) noexcept; template<typename T, std::size_t N> constexpr std::size_t CountOf(T(&name)[N]) noexcept;

View File

@ -11,6 +11,7 @@
#include <Nazara/Core/ByteArray.hpp> #include <Nazara/Core/ByteArray.hpp>
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <Nazara/Core/Stream.hpp> #include <Nazara/Core/Stream.hpp>
#include <climits>
#include <Nazara/Core/Debug.hpp> #include <Nazara/Core/Debug.hpp>
namespace Nz namespace Nz
@ -70,6 +71,17 @@ namespace Nz
return Detail::ApplyImplMethod(object, std::forward<F>(fn), std::forward<Tuple>(t), std::make_index_sequence<tSize>()); return Detail::ApplyImplMethod(object, std::forward<F>(fn), std::forward<Tuple>(t), std::make_index_sequence<tSize>());
} }
/*!
* \ingroup core
* \brief Returns the number of bits occupied by the type T
* \return Number of bits occupied by the type
*/
template<typename T>
constexpr std::size_t BitCount()
{
return CHAR_BIT * sizeof(T);
}
/*! /*!
* \ingroup core * \ingroup core
* \brief Computes the hash of a hashable object * \brief Computes the hash of a hashable object

View File

@ -8,6 +8,7 @@
#define NAZARA_BITSET_HPP #define NAZARA_BITSET_HPP
#include <Nazara/Prerequesites.hpp> #include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Algorithm.hpp>
#include <Nazara/Core/String.hpp> #include <Nazara/Core/String.hpp>
#include <limits> #include <limits>
#include <memory> #include <memory>
@ -24,6 +25,7 @@ namespace Nz
public: public:
class Bit; class Bit;
using PointerSequence = std::pair<const void*, std::size_t>; //< Start pointer, bit offset
Bitset(); Bitset();
explicit Bitset(std::size_t bitCount, bool val); explicit Bitset(std::size_t bitCount, bool val);
@ -35,6 +37,8 @@ namespace Nz
Bitset(Bitset&& bitset) noexcept = default; Bitset(Bitset&& bitset) noexcept = default;
~Bitset() noexcept = default; ~Bitset() noexcept = default;
template<typename T> void AppendBits(T bits, std::size_t bitCount);
void Clear() noexcept; void Clear() noexcept;
std::size_t Count() const; std::size_t Count() const;
void Flip(); void Flip();
@ -47,6 +51,9 @@ namespace Nz
std::size_t GetCapacity() const; std::size_t GetCapacity() const;
std::size_t GetSize() const; std::size_t GetSize() const;
PointerSequence Read(const void* ptr, std::size_t bitCount);
PointerSequence Read(const PointerSequence& sequence, std::size_t bitCount);
void PerformsAND(const Bitset& a, const Bitset& b); void PerformsAND(const Bitset& a, const Bitset& b);
void PerformsNOT(const Bitset& a); void PerformsNOT(const Bitset& a);
void PerformsOR(const Bitset& a, const Bitset& b); void PerformsOR(const Bitset& a, const Bitset& b);
@ -60,6 +67,8 @@ namespace Nz
void Reset(); void Reset();
void Reset(std::size_t bit); void Reset(std::size_t bit);
void Reverse();
void Set(bool val = true); void Set(bool val = true);
void Set(std::size_t bit, bool val = true); void Set(std::size_t bit, bool val = true);
void SetBlock(std::size_t i, Block block); void SetBlock(std::size_t i, Block block);
@ -102,9 +111,11 @@ namespace Nz
Bitset& operator^=(const Bitset& bitset); Bitset& operator^=(const Bitset& bitset);
static constexpr Block fullBitMask = std::numeric_limits<Block>::max(); static constexpr Block fullBitMask = std::numeric_limits<Block>::max();
static constexpr std::size_t bitsPerBlock = std::numeric_limits<Block>::digits; static constexpr std::size_t bitsPerBlock = BitCount<Block>();
static constexpr std::size_t npos = std::numeric_limits<std::size_t>::max(); static constexpr std::size_t npos = std::numeric_limits<std::size_t>::max();
static Bitset FromPointer(const void* ptr, std::size_t bitCount, PointerSequence* sequence = nullptr);
private: private:
std::size_t FindFirstFrom(std::size_t blockIndex) const; std::size_t FindFirstFrom(std::size_t blockIndex) const;
Block GetLastBlockMask() const; Block GetLastBlockMask() const;
@ -154,6 +165,9 @@ namespace Nz
Block m_mask; Block m_mask;
}; };
template<typename Block, class Allocator>
std::ostream& operator<<(std::ostream& out, const Bitset<Block, Allocator>& bitset);
template<typename Block, class Allocator> template<typename Block, class Allocator>
bool operator==(const Bitset<Block, Allocator>& lhs, const Nz::Bitset<Block, Allocator>& rhs); bool operator==(const Bitset<Block, Allocator>& lhs, const Nz::Bitset<Block, Allocator>& rhs);

View File

@ -6,7 +6,6 @@
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <Nazara/Math/Algorithm.hpp> #include <Nazara/Math/Algorithm.hpp>
#include <cstdlib> #include <cstdlib>
#include <limits>
#include <utility> #include <utility>
#include <Nazara/Core/Debug.hpp> #include <Nazara/Core/Debug.hpp>
@ -122,13 +121,13 @@ namespace Nz
{ {
if (sizeof(T) <= sizeof(Block)) if (sizeof(T) <= sizeof(Block))
{ {
m_bitCount = std::numeric_limits<T>::digits; m_bitCount = BitCount<T>();
m_blocks.push_back(static_cast<Block>(value)); m_blocks.push_back(static_cast<Block>(value));
} }
else else
{ {
// Note: I was kinda tired when I wrote this, there's probably a much easier method than checking bits to write bits // Note: I was kinda tired when I wrote this, there's probably a much easier method than checking bits to write bits
for (std::size_t bitPos = 0; bitPos < std::numeric_limits<T>::digits; bitPos++) for (std::size_t bitPos = 0; bitPos < BitCount<T>(); bitPos++)
{ {
if (value & (T(1U) << bitPos)) if (value & (T(1U) << bitPos))
UnboundedSet(bitPos, true); UnboundedSet(bitPos, true);
@ -137,11 +136,63 @@ namespace Nz
} }
/*! /*!
* \brief Clears the content of the bitset, GetSize() is now equals to 0 * \brief Appends bits to the bitset
* *
* \remark The memory allocated is not released * This function extends the bitset with bits extracted from an integer value
*
* \param bits An integer value from where bits will be extracted
* \param bitCount Number of bits to extract from the value
*
* \remark This function does not require bitCount to be lower or equal to the number of bits of T, thus
* reading 32 bits from a UInt8 will work (by extracting the first 8 bits values and appending 24 zeros afterneath).
*
* \see AppendBits
* \see Read
*/ */
template<typename Block, class Allocator>
template<typename T>
void Bitset<Block, Allocator>::AppendBits(T bits, std::size_t bitCount)
{
std::size_t bitShift = m_bitCount % bitsPerBlock;
m_bitCount += bitCount;
if (bitShift != 0)
{
std::size_t remainingBits = bitsPerBlock - bitShift;
m_blocks.back() |= Block(bits) << bitShift;
bits >>= bitsPerBlock - bitShift;
bitCount -= std::min(remainingBits, bitCount);
}
if (bitCount > 0)
{
std::size_t blockCount = ComputeBlockCount(bitCount);
for (std::size_t block = 0; block < blockCount - 1; ++block)
{
m_blocks.push_back(static_cast<Block>(bits));
bits = (BitCount<Block>() < BitCount<T>()) ? bits >> BitCount<Block>() : 0U;
bitCount -= BitCount<Block>();
}
// For the last iteration, mask out the bits we don't want
std::size_t remainingBits = bitCount;
bits &= ((Block(1U) << remainingBits) - 1U);
m_blocks.push_back(static_cast<Block>(bits));
}
}
/*!
* \brief Clears the content of the bitset
*
* This function clears the bitset content, resetting its bit and block count at zero.
*
* \remark This does not changes the bits values to zero but empties the bitset, to reset the bits use the Reset() function
* \remark This call does not changes the bitset capacity
*
* \see Reset()
*/
template<typename Block, class Allocator> template<typename Block, class Allocator>
void Bitset<Block, Allocator>::Clear() noexcept void Bitset<Block, Allocator>::Clear() noexcept
{ {
@ -151,9 +202,9 @@ namespace Nz
/*! /*!
* \brief Counts the number of bits set to 1 * \brief Counts the number of bits set to 1
*
* \return Number of bits set to 1 * \return Number of bits set to 1
*/ */
template<typename Block, class Allocator> template<typename Block, class Allocator>
std::size_t Bitset<Block, Allocator>::Count() const std::size_t Bitset<Block, Allocator>::Count() const
{ {
@ -169,8 +220,9 @@ namespace Nz
/*! /*!
* \brief Flips each bit of the bitset * \brief Flips each bit of the bitset
*
* This function flips every bit of the bitset, which means every '1' turns into a '0' and conversely.
*/ */
template<typename Block, class Allocator> template<typename Block, class Allocator>
void Bitset<Block, Allocator>::Flip() void Bitset<Block, Allocator>::Flip()
{ {
@ -182,9 +234,9 @@ namespace Nz
/*! /*!
* \brief Finds the first bit set to one in the bitset * \brief Finds the first bit set to one in the bitset
* \return Index of the first bit *
* \return The 0-based index of the first bit enabled
*/ */
template<typename Block, class Allocator> template<typename Block, class Allocator>
std::size_t Bitset<Block, Allocator>::FindFirst() const std::size_t Bitset<Block, Allocator>::FindFirst() const
{ {
@ -192,14 +244,14 @@ namespace Nz
} }
/*! /*!
* \brief Finds the next bit set to one in the bitset * \brief Finds the next enabled in the bitset
* \return Index of the next bit if exists or npos
* *
* \param bit Index of the bit, the search begin with bit + 1 * \param bit Index of the last bit found, which will not be treated by this function
* *
* \remark Produce a NazaraAssert if bit is greather than number of bits in bitset * \return Index of the next enabled bit or npos if all the following bits are disabled
*
* \remark This function is typically used in for-loops to iterate on bits
*/ */
template<typename Block, class Allocator> template<typename Block, class Allocator>
std::size_t Bitset<Block, Allocator>::FindNext(std::size_t bit) const std::size_t Bitset<Block, Allocator>::FindNext(std::size_t bit) const
{ {
@ -275,6 +327,76 @@ namespace Nz
return m_bitCount; return m_bitCount;
} }
/*!
* \brief Read a byte sequence into a bitset
*
* This function extends the bitset with bits read from a byte sequence
*
* \param ptr A pointer to the start of the byte sequence
* \param bitCount Number of bits to read from the byte sequence
*
* \returns A pointer to the next byte to read along with the next bit index (useful when reading multiple times)
*
* \remark For technical reasons, ceil(bitCount / 8) bytes from the sequence will always be read (even with non-multiple-of-8 bitCount)
*
* \see AppendBits
* \see Read
*/
template<typename Block, class Allocator>
typename Bitset<Block, Allocator>::PointerSequence Bitset<Block, Allocator>::Read(const void* ptr, std::size_t bitCount)
{
return Read(PointerSequence(ptr, 0U), bitCount);
}
/*!
* \brief Read a byte sequence into a bitset
*
* This function extends the bitset with bits read from a pointer sequence (made of a pointer and a bit index)
*
* \param sequence A pointer sequence to the start of the byte sequence
* \param bitCount Number of bits to read from the byte sequence
*
* \returns A pointer to the next byte to read along with the next bit index (useful when reading multiple times)
*
* \remark For technical reasons, ceil(bitCount / 8) bytes from the sequence will always be read (even with non-multiple-of-8 bitCount)
*
* \see AppendBits
* \see Read
*/
template<typename Block, class Allocator>
typename Bitset<Block, Allocator>::PointerSequence Bitset<Block, Allocator>::Read(const PointerSequence& sequence, std::size_t bitCount)
{
NazaraAssert(sequence.first, "Invalid pointer sequence");
NazaraAssert(sequence.second < 8, "Invalid next bit index (must be < 8)");
std::size_t totalBitCount = sequence.second + bitCount;
const UInt8* u8Ptr = static_cast<const UInt8*>(sequence.first);
const UInt8* endPtr = u8Ptr + ((totalBitCount != 0) ? (totalBitCount - 1) / 8 : 0);
const UInt8* nextPtr = endPtr + ((totalBitCount % 8 != 0) ? 0 : 1);
// Read the first block apart to apply a mask on the first byte if necessary
if (sequence.second != 0)
{
UInt8 mask = ~((1U << sequence.second) - 1U);
std::size_t readCount = std::min(bitCount, 8 - sequence.second);
AppendBits(Block(*u8Ptr++ & mask) >> sequence.second, readCount);
bitCount -= readCount;
}
// And then read the remaining bytes
while (u8Ptr <= endPtr)
{
std::size_t bitToRead = std::min<std::size_t>(bitCount, 8);
AppendBits(*u8Ptr++, bitToRead);
bitCount -= bitToRead;
}
// Returns informations to continue reading
return PointerSequence(nextPtr, totalBitCount % 8);
}
/*! /*!
* \brief Performs the "AND" operator between two bitsets * \brief Performs the "AND" operator between two bitsets
* *
@ -289,15 +411,17 @@ namespace Nz
{ {
std::pair<std::size_t, std::size_t> minmax = std::minmax(a.GetBlockCount(), b.GetBlockCount()); std::pair<std::size_t, std::size_t> minmax = std::minmax(a.GetBlockCount(), b.GetBlockCount());
// We reinitialise our blocks with zero m_blocks.resize(minmax.second);
m_blocks.clear();
m_blocks.resize(minmax.second, 0U);
m_bitCount = std::max(a.GetSize(), b.GetSize()); m_bitCount = std::max(a.GetSize(), b.GetSize());
// In case of the "AND", we can stop with the smallest size (because x & 0 = 0) // In case of the "AND", we can stop with the smallest size (because x & 0 = 0)
for (std::size_t i = 0; i < minmax.first; ++i) for (std::size_t i = 0; i < minmax.first; ++i)
m_blocks[i] = a.GetBlock(i) & b.GetBlock(i); m_blocks[i] = a.GetBlock(i) & b.GetBlock(i);
// And then reset every other block to zero
for (std::size_t i = minmax.first; i < minmax.second; ++i)
m_blocks[i] = 0U;
ResetExtraBits(); ResetExtraBits();
} }
@ -458,6 +582,30 @@ namespace Nz
Set(bit, false); Set(bit, false);
} }
/*!
* \brief Reverse the order of bits in a bitset
*
* Reverse the order of bits in the bitset (first bit swap with the last one, etc.)
*/
template<typename Block, class Allocator>
void Bitset<Block, Allocator>::Reverse()
{
if (m_bitCount == 0)
return;
std::size_t i = 0;
std::size_t j = m_bitCount - 1;
while (i < j)
{
bool bit1 = Test(i);
bool bit2 = Test(j);
Set(i++, bit2);
Set(j--, bit1);
}
}
/*! /*!
* \brief Sets the bitset to val * \brief Sets the bitset to val
* *
@ -535,27 +683,28 @@ namespace Nz
return; return;
} }
auto div = std::lldiv(pos, bitsPerBlock); std::size_t blockShift = pos / bitsPerBlock;
if (div.rem != 0) std::size_t remainder = pos % bitsPerBlock;
if (remainder != 0)
{ {
std::size_t lastIndex = m_blocks.size() - 1; std::size_t lastIndex = m_blocks.size() - 1;
std::size_t remaining = bitsPerBlock - div.rem; std::size_t remaining = bitsPerBlock - remainder;
for (std::size_t i = lastIndex - div.quot; i > 0; --i) for (std::size_t i = lastIndex - blockShift; i > 0; --i)
m_blocks[i + div.quot] = (m_blocks[i] << div.rem) | (m_blocks[i - 1] >> remaining); m_blocks[i + blockShift] = (m_blocks[i] << remainder) | (m_blocks[i - 1] >> remaining);
m_blocks[div.quot] = m_blocks[0] << div.rem; m_blocks[blockShift] = m_blocks[0] << remainder;
std::fill_n(m_blocks.begin(), div.quot, Block(0)); std::fill_n(m_blocks.begin(), blockShift, Block(0));
} }
else else
{ {
for (auto it = m_blocks.rbegin(); it != m_blocks.rend(); ++it) for (auto it = m_blocks.rbegin(); it != m_blocks.rend(); ++it)
{ {
if (static_cast<std::size_t>(std::distance(m_blocks.rbegin(), it) + div.quot) < m_blocks.size()) if (static_cast<std::size_t>(std::distance(m_blocks.rbegin(), it) + blockShift) < m_blocks.size())
{ {
auto shiftedIt = it; auto shiftedIt = it;
std::advance(shiftedIt, div.quot); std::advance(shiftedIt, blockShift);
*it = *shiftedIt; *it = *shiftedIt;
} }
@ -588,27 +737,28 @@ namespace Nz
return; return;
} }
auto div = std::lldiv(pos, bitsPerBlock); std::size_t blockShift = pos / bitsPerBlock;
if (div.rem != 0) std::size_t remainder = pos % bitsPerBlock;
if (remainder != 0)
{ {
std::size_t lastIndex = m_blocks.size() - 1; std::size_t lastIndex = m_blocks.size() - 1;
std::size_t remaining = bitsPerBlock - div.rem; std::size_t remaining = bitsPerBlock - remainder;
for (std::size_t i = div.quot; i < lastIndex; ++i) for (std::size_t i = blockShift; i < lastIndex; ++i)
m_blocks[i - div.quot] = (m_blocks[i] >> div.rem) | (m_blocks[i + 1] << remaining); m_blocks[i - blockShift] = (m_blocks[i] >> remainder) | (m_blocks[i + 1] << remaining);
m_blocks[lastIndex - div.quot] = m_blocks[lastIndex] >> div.rem; m_blocks[lastIndex - blockShift] = m_blocks[lastIndex] >> remainder;
std::fill_n(m_blocks.begin() + (m_blocks.size() - div.quot), div.quot, Block(0)); std::fill_n(m_blocks.begin() + (m_blocks.size() - blockShift), blockShift, Block(0));
} }
else else
{ {
for (auto it = m_blocks.begin(); it != m_blocks.end(); ++it) for (auto it = m_blocks.begin(); it != m_blocks.end(); ++it)
{ {
if (static_cast<std::size_t>(std::distance(m_blocks.begin(), it) + div.quot) < m_blocks.size()) if (static_cast<std::size_t>(std::distance(m_blocks.begin(), it) + blockShift) < m_blocks.size())
{ {
auto shiftedIt = it; auto shiftedIt = it;
std::advance(shiftedIt, div.quot); std::advance(shiftedIt, blockShift);
*it = *shiftedIt; *it = *shiftedIt;
} }
@ -716,7 +866,7 @@ namespace Nz
{ {
static_assert(std::is_integral<T>() && std::is_unsigned<T>(), "T must be a unsigned integral type"); static_assert(std::is_integral<T>() && std::is_unsigned<T>(), "T must be a unsigned integral type");
NazaraAssert(m_bitCount <= std::numeric_limits<T>::digits, "Bit count cannot be greater than T bit count"); NazaraAssert(m_bitCount <= BitCount<T>(), "Bit count cannot be greater than T bit count");
T value = 0; T value = 0;
for (std::size_t i = 0; i < m_blocks.size(); ++i) for (std::size_t i = 0; i < m_blocks.size(); ++i)
@ -989,13 +1139,41 @@ namespace Nz
return *this; return *this;
} }
/*!
* \brief Builds a bitset from a byte sequence
*
* This function builds a bitset using a byte sequence by reading bitCount bits from it
*
* \param ptr A pointer to the start of the byte sequence
* \param bitCount Number of bits to read from the byte sequence
* \param sequence Optional data to pass to a next call to Read
*
* \return The constructed bitset
*
* \remark For technical reasons, ceil(bitCount / 8) bytes from the sequence will always be read (even with non-multiple-of-8 bitCount)
*
* \see AppendBits
* \see Read
*/
template<typename Block, class Allocator>
Bitset<Block, Allocator> Bitset<Block, Allocator>::FromPointer(const void* ptr, std::size_t bitCount, PointerSequence* sequence)
{
Bitset bitset;
if (sequence)
*sequence = bitset.Read(ptr, bitCount);
else
bitset.Read(ptr, bitCount);
return bitset;
}
/*! /*!
* \brief Finds the position of the first bit set to true after the blockIndex * \brief Finds the position of the first bit set to true after the blockIndex
* \return The position of the bit * \return The position of the bit
* *
* \param blockIndex Index of the block * \param blockIndex Index of the block
*/ */
template<typename Block, class Allocator> template<typename Block, class Allocator>
std::size_t Bitset<Block, Allocator>::FindFirstFrom(std::size_t blockIndex) const std::size_t Bitset<Block, Allocator>::FindFirstFrom(std::size_t blockIndex) const
{ {
@ -1124,7 +1302,7 @@ namespace Nz
template<typename Block, class Allocator> template<typename Block, class Allocator>
bool Bitset<Block, Allocator>::Bit::Test() const bool Bitset<Block, Allocator>::Bit::Test() const
{ {
return m_block & m_mask; return (m_block & m_mask) != 0;
} }
/*! /*!
@ -1269,6 +1447,14 @@ namespace Nz
return *this; return *this;
} }
template<typename Block, class Allocator>
std::ostream& operator<<(std::ostream& out, const Bitset<Block, Allocator>& bitset)
{
return out << bitset.ToString();
}
/*! /*!
* \brief Compares two bitsets * \brief Compares two bitsets
* \return true if the two bitsets are the same * \return true if the two bitsets are the same

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