Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7fc83d1471 | |||
| 65e5729118 | |||
| 26d6f4c7cf | |||
| e513059522 |
@@ -4,3 +4,7 @@ bin/
|
||||
lib/
|
||||
# Because apparently nobody has any self control
|
||||
*.orig
|
||||
|
||||
tools/LiveTexturing/mayaPluginRTT/mayaPluginRTT/x64/Debug/
|
||||
tools/LiveTexturing/mayaPluginRTT/x64/Debug/
|
||||
*.suo
|
||||
|
||||
+1
-1
Submodule assets updated: b37468222e...e4dc9529f2
@@ -1,13 +1,13 @@
|
||||
# Xerces_FOUND
|
||||
# Xerces_INCLUDE_DIRS
|
||||
# Xerces_LIBRARIES
|
||||
# XERCES_FOUND
|
||||
# XERCES_INCLUDE_DIRS
|
||||
# XERCES_LIBRARIES
|
||||
|
||||
find_path(Xerces_INCLUDE_DIR xercesc/dom/dom.hpp
|
||||
find_path(XERCES_INCLUDE_DIR xercesc/dom/dom.hpp
|
||||
/usr/local/include
|
||||
/usr/include
|
||||
)
|
||||
|
||||
find_library(Xerces_LIBRARY
|
||||
find_library(XERCES_LIBRARY
|
||||
NAMES
|
||||
xerces-c_3
|
||||
xerces-c_3D
|
||||
@@ -16,8 +16,8 @@ find_library(Xerces_LIBRARY
|
||||
/usr/lib
|
||||
)
|
||||
|
||||
set(Xerces_INCLUDE_DIRS ${Xerces_INCLUDE_DIR})
|
||||
set(Xerces_LIBRARIES ${Xerces_LIBRARY})
|
||||
set(XERCES_INCLUDE_DIRS ${XERCES_INCLUDE_DIR})
|
||||
set(XERCES_LIBRARIES ${XERCES_LIBRARY})
|
||||
|
||||
find_package_handle_standard_args(Xerces DEFAULT_MSG Xerces_LIBRARY Xerces_INCLUDE_DIR)
|
||||
mark_as_advanced(Xerces_FOUND Xerces_INCLUDE_DIR Xerces_LIBRARY)
|
||||
find_package_handle_standard_args(Xerces DEFAULT_MSG XERCES_LIBRARY XERCES_INCLUDE_DIR)
|
||||
mark_as_advanced(Xerces_FOUND XERCES_INCLUDE_DIR XERCES_LIBRARY)
|
||||
@@ -2,7 +2,7 @@
|
||||
#define ComponentWrapper_h__
|
||||
|
||||
#include "../Common.h"
|
||||
#include "Entity.h"
|
||||
#include "EntityWrapper.h"
|
||||
#include "ComponentInfo.h"
|
||||
#include "Util/Any.h"
|
||||
|
||||
@@ -11,7 +11,7 @@ struct ComponentWrapper
|
||||
ComponentWrapper(const ComponentInfo& componentInfo, char* data)
|
||||
: Info(componentInfo)
|
||||
, EntityID(*reinterpret_cast<::EntityID*>(data))
|
||||
, Data(data + sizeof(::EntityID))
|
||||
, Data(data + sizeof(EntityID))
|
||||
{ }
|
||||
|
||||
const ComponentInfo& Info;
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
#ifndef Entity_h__
|
||||
#define Entity_h__
|
||||
|
||||
typedef unsigned int EntityID;
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,12 @@
|
||||
#include "ResourceManager.h"
|
||||
|
||||
class EntityFile : public Resource
|
||||
{
|
||||
friend class ResourceManager;
|
||||
|
||||
private:
|
||||
EntityFile(std::string path);
|
||||
|
||||
public:
|
||||
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
#ifndef Entity_h__
|
||||
#define Entity_h__
|
||||
|
||||
typedef unsigned int EntityID;
|
||||
|
||||
struct EntityWrapper
|
||||
{
|
||||
EntityWrapper(EntityID entityID)
|
||||
: ID(entityID)
|
||||
{ }
|
||||
|
||||
EntityID ID;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -1,141 +0,0 @@
|
||||
#ifndef EntityXMLFile_h__
|
||||
#define EntityXMLFile_h__
|
||||
|
||||
#include <sstream>
|
||||
|
||||
#include "../Common.h"
|
||||
#include "../GLM.h"
|
||||
#include <xercesc/dom/DOM.hpp>
|
||||
#include <xercesc/dom/DOMLSInput.hpp>
|
||||
#include <xercesc/dom/DOMElement.hpp>
|
||||
#include <xercesc/framework/Wrapper4InputSource.hpp>
|
||||
#include <xercesc/framework/LocalFileInputSource.hpp>
|
||||
#include <xercesc/framework/LocalFileFormatTarget.hpp>
|
||||
#include <xercesc/framework/MemBufFormatTarget.hpp>
|
||||
#include <xercesc/framework/MemBufInputSource.hpp>
|
||||
#include <xercesc/sax/HandlerBase.hpp>
|
||||
#include <xercesc/util/PlatformUtils.hpp>
|
||||
#include <xercesc/util/XMLFloat.hpp>
|
||||
#include <xercesc/framework/XMLGrammarPoolImpl.hpp>
|
||||
#include <xercesc/parsers/XercesDOMParser.hpp>
|
||||
#include <xercesc/framework/psvi/XSElementDeclaration.hpp>
|
||||
#include <xercesc/framework/psvi/XSComplexTypeDefinition.hpp>
|
||||
#include <xercesc/framework/psvi/XSParticle.hpp>
|
||||
#include <xercesc/framework/psvi/XSModelGroup.hpp>
|
||||
#include <xercesc/framework/psvi/XSAnnotation.hpp>
|
||||
#include <xercesc/framework/psvi/XSValue.hpp>
|
||||
#include <xercesc/framework/XMLValidator.hpp>
|
||||
|
||||
#include "ResourceManager.h"
|
||||
#include "Entity.h"
|
||||
#include "ComponentInfo.h"
|
||||
class World;
|
||||
|
||||
class EntityPreprocessorXMLErrorHandler : public xercesc::DOMErrorHandler
|
||||
{
|
||||
public:
|
||||
bool handleError(const xercesc::DOMError &e) override
|
||||
{
|
||||
char* message = xercesc::XMLString::transcode(e.getMessage());
|
||||
std::cerr << "Preprocessor DOMError: " << message << std::endl;
|
||||
xercesc::XMLString::release(&message);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
class EntityParserXMLErrorHandler : public xercesc::ErrorHandler
|
||||
{
|
||||
public:
|
||||
void warning(const xercesc::SAXParseException& e) override
|
||||
{
|
||||
reportParseException("Warning", e);
|
||||
}
|
||||
void error(const xercesc::SAXParseException& e) override
|
||||
{
|
||||
reportParseException("Error", e);
|
||||
}
|
||||
void fatalError(const xercesc::SAXParseException& e) override
|
||||
{
|
||||
reportParseException("FATAL ERROR", e);
|
||||
}
|
||||
void resetErrors() override { }
|
||||
|
||||
private:
|
||||
void reportParseException(std::string type, const xercesc::SAXParseException& e)
|
||||
{
|
||||
char* message = xercesc::XMLString::transcode(e.getMessage());
|
||||
char* systemID = xercesc::XMLString::transcode(e.getSystemId());
|
||||
std::cerr << systemID << ":" << e.getLineNumber() << ":" << e.getColumnNumber() << std::endl;
|
||||
std::cerr << type << ": " << message << std::endl;
|
||||
xercesc::XMLString::release(&systemID);
|
||||
xercesc::XMLString::release(&message);
|
||||
}
|
||||
};
|
||||
|
||||
class XSTR
|
||||
{
|
||||
public:
|
||||
XSTR(const XMLCh* const xmlString)
|
||||
{
|
||||
m_AsChar = xercesc::XMLString::transcode(xmlString);
|
||||
}
|
||||
|
||||
XSTR(const char* normalString)
|
||||
{
|
||||
m_AsXMLCh = xercesc::XMLString::transcode(normalString);
|
||||
}
|
||||
|
||||
~XSTR()
|
||||
{
|
||||
if (m_AsChar != nullptr) {
|
||||
xercesc::XMLString::release(&m_AsChar);
|
||||
}
|
||||
if (m_AsXMLCh != nullptr) {
|
||||
xercesc::XMLString::release(&m_AsXMLCh);
|
||||
}
|
||||
}
|
||||
|
||||
operator const char*() const { return m_AsChar; }
|
||||
operator const XMLCh*() const { return m_AsXMLCh; }
|
||||
|
||||
private:
|
||||
char* m_AsChar = nullptr;
|
||||
XMLCh* m_AsXMLCh = nullptr;
|
||||
};
|
||||
|
||||
class EntityXMLFile : public Resource
|
||||
{
|
||||
friend class ResourceManager;
|
||||
|
||||
private:
|
||||
EntityXMLFile(std::string path);
|
||||
|
||||
public:
|
||||
~EntityXMLFile();
|
||||
|
||||
void PopulateWorld(World* world);
|
||||
|
||||
private:
|
||||
static unsigned int InstanceCount;
|
||||
|
||||
std::string m_EntityFile;
|
||||
xercesc::XMLGrammarPool* m_GrammarPool = nullptr;
|
||||
EntityParserXMLErrorHandler* m_ErrorHandler = nullptr;
|
||||
xercesc::XercesDOMParser* m_DOMParser = nullptr;
|
||||
xercesc::DOMDocument* m_DOMDocument = nullptr;
|
||||
std::map<std::string, ComponentInfo> m_ComponentInfo;
|
||||
|
||||
// Preprocesses the entity file to insert include-by-copy child entities
|
||||
// TODO: Make this work in memory instead of saving to file
|
||||
void preprocess(std::string inPath, std::string outPath);
|
||||
|
||||
void parseComponentInfo();
|
||||
void parseDefaults();
|
||||
void predictComponentAllocation();
|
||||
void parseEntityGraph(World* world, xercesc::DOMElement* parent, EntityID parentEntity);
|
||||
std::size_t getTypeStride(std::string typeName);
|
||||
float getFloatAttribute(const xercesc::DOMElement* element, const char* attribute) const;
|
||||
void writeData(const xercesc::DOMElement* element, std::string typeName, char* outData);
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -17,119 +17,119 @@ class EventBroker;
|
||||
|
||||
class BaseEventRelay
|
||||
{
|
||||
friend class EventBroker;
|
||||
friend class EventBroker;
|
||||
|
||||
protected:
|
||||
BaseEventRelay(std::string contextTypeName, std::string eventTypeName)
|
||||
: m_ContextTypeName(contextTypeName)
|
||||
, m_EventTypeName(eventTypeName)
|
||||
, m_Broker(nullptr)
|
||||
{ }
|
||||
~BaseEventRelay();
|
||||
BaseEventRelay(std::string contextTypeName, std::string eventTypeName)
|
||||
: m_ContextTypeName(contextTypeName)
|
||||
, m_EventTypeName(eventTypeName)
|
||||
, m_Broker(nullptr)
|
||||
{ }
|
||||
~BaseEventRelay();
|
||||
|
||||
public:
|
||||
virtual bool Receive(const std::shared_ptr<Event> event) = 0;
|
||||
virtual bool Receive(const std::shared_ptr<Event> event) = 0;
|
||||
|
||||
protected:
|
||||
std::string m_ContextTypeName;
|
||||
std::string m_EventTypeName;
|
||||
EventBroker* m_Broker;
|
||||
std::string m_ContextTypeName;
|
||||
std::string m_EventTypeName;
|
||||
EventBroker* m_Broker;
|
||||
};
|
||||
|
||||
template <typename ContextType, typename EventType>
|
||||
class EventRelay : public BaseEventRelay
|
||||
{
|
||||
public:
|
||||
typedef std::function<bool(const EventType&)> CallbackType;
|
||||
typedef std::function<bool(const EventType&)> CallbackType;
|
||||
|
||||
EventRelay()
|
||||
: m_Callback(nullptr)
|
||||
, BaseEventRelay(typeid(ContextType).name(), typeid(EventType).name())
|
||||
{ }
|
||||
EventRelay(CallbackType callback)
|
||||
: m_Callback(callback)
|
||||
, BaseEventRelay(typeid(ContextType).name(), typeid(EventType).name())
|
||||
{ }
|
||||
EventRelay()
|
||||
: m_Callback(nullptr)
|
||||
, BaseEventRelay(typeid(ContextType).name(), typeid(EventType).name())
|
||||
{ }
|
||||
EventRelay(CallbackType callback)
|
||||
: m_Callback(callback)
|
||||
, BaseEventRelay(typeid(ContextType).name(), typeid(EventType).name())
|
||||
{ }
|
||||
|
||||
protected:
|
||||
bool Receive(const std::shared_ptr<Event> event) override;
|
||||
bool Receive(const std::shared_ptr<Event> event) override;
|
||||
|
||||
private:
|
||||
CallbackType m_Callback;
|
||||
CallbackType m_Callback;
|
||||
};
|
||||
|
||||
template <typename ContextType, typename EventType>
|
||||
bool EventRelay<ContextType, EventType>::Receive(const std::shared_ptr<Event> event)
|
||||
{
|
||||
if (m_Callback != nullptr) {
|
||||
return m_Callback(*static_cast<const EventType*>(event.get()));
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
if (m_Callback != nullptr) {
|
||||
return m_Callback(*static_cast<const EventType*>(event.get()));
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
class EventBroker
|
||||
{
|
||||
template <typename ContextType, typename EventType> friend class EventRelay;
|
||||
template <typename ContextType, typename EventType> friend class EventRelay;
|
||||
|
||||
public:
|
||||
EventBroker()
|
||||
{
|
||||
m_EventQueueRead = std::make_shared<EventQueue_t>();
|
||||
m_EventQueueWrite = std::make_shared<EventQueue_t>();
|
||||
}
|
||||
EventBroker()
|
||||
{
|
||||
m_EventQueueRead = std::make_shared<EventQueue_t>();
|
||||
m_EventQueueWrite = std::make_shared<EventQueue_t>();
|
||||
}
|
||||
|
||||
void Subscribe(BaseEventRelay &relay);
|
||||
template <typename EventType>
|
||||
void Publish(const EventType &event);
|
||||
/*
|
||||
Process all events in a given context.
|
||||
Returns: Number of events processed
|
||||
*/
|
||||
template <typename ContextType>
|
||||
int Process();
|
||||
int Process(std::string contextTypeName);
|
||||
void Swap();
|
||||
void Clear();
|
||||
void Unsubscribe(BaseEventRelay &relay);
|
||||
void Subscribe(BaseEventRelay &relay);
|
||||
template <typename EventType>
|
||||
void Publish(const EventType &event);
|
||||
/*
|
||||
Process all events in a given context.
|
||||
Returns: Number of events processed
|
||||
*/
|
||||
template <typename ContextType>
|
||||
int Process();
|
||||
int Process(std::string contextTypeName);
|
||||
void Swap();
|
||||
void Clear();
|
||||
void Unsubscribe(BaseEventRelay &relay);
|
||||
|
||||
private:
|
||||
bool m_IsProcessing = false;
|
||||
bool m_IsProcessing = false;
|
||||
|
||||
typedef std::string ContextTypeName_t; // typeid(ContextType).name()
|
||||
typedef std::string EventTypeName_t; // typeid(EventType).name()
|
||||
typedef std::string ContextTypeName_t; // typeid(ContextType).name()
|
||||
typedef std::string EventTypeName_t; // typeid(EventType).name()
|
||||
|
||||
typedef std::unordered_multimap<EventTypeName_t, BaseEventRelay*> EventRelays_t;
|
||||
typedef std::unordered_map<ContextTypeName_t, EventRelays_t> ContextRelays_t;
|
||||
ContextRelays_t m_ContextRelays;
|
||||
std::vector<BaseEventRelay*> m_RelaysToSubscribe;
|
||||
std::vector<BaseEventRelay*> m_RelaysToUnsubscribe;
|
||||
typedef std::unordered_multimap<EventTypeName_t, BaseEventRelay*> EventRelays_t;
|
||||
typedef std::unordered_map<ContextTypeName_t, EventRelays_t> ContextRelays_t;
|
||||
ContextRelays_t m_ContextRelays;
|
||||
std::vector<BaseEventRelay*> m_RelaysToSubscribe;
|
||||
std::vector<BaseEventRelay*> m_RelaysToUnsubscribe;
|
||||
|
||||
typedef std::list<std::pair<EventTypeName_t, std::shared_ptr<Event>>> EventQueue_t;
|
||||
std::shared_ptr<EventQueue_t> m_EventQueueRead;
|
||||
std::shared_ptr<EventQueue_t> m_EventQueueWrite;
|
||||
typedef std::list<std::pair<EventTypeName_t, std::shared_ptr<Event>>> EventQueue_t;
|
||||
std::shared_ptr<EventQueue_t> m_EventQueueRead;
|
||||
std::shared_ptr<EventQueue_t> m_EventQueueWrite;
|
||||
|
||||
void subscribeImmediate(BaseEventRelay& relay);
|
||||
void unsubscribeImmediate(BaseEventRelay& relay);
|
||||
void subscribeImmediate(BaseEventRelay& relay);
|
||||
void unsubscribeImmediate(BaseEventRelay& relay);
|
||||
};
|
||||
|
||||
template <typename EventType>
|
||||
void EventBroker::Publish(const EventType &event)
|
||||
{
|
||||
/*auto itpair = m_Subscribers.equal_range(typeid(EventType).name());
|
||||
for (auto it = itpair.first; it != itpair.second; ++it)
|
||||
{
|
||||
it->second->Receive(event);
|
||||
}*/
|
||||
/*auto itpair = m_Subscribers.equal_range(typeid(EventType).name());
|
||||
for (auto it = itpair.first; it != itpair.second; ++it)
|
||||
{
|
||||
it->second->Receive(event);
|
||||
}*/
|
||||
|
||||
m_EventQueueWrite->push_back(std::make_pair(typeid(EventType).name(), std::shared_ptr<EventType>(new EventType(event))));
|
||||
m_EventQueueWrite->push_back(std::make_pair(typeid(EventType).name(), std::shared_ptr<EventType>(new EventType(event))));
|
||||
}
|
||||
|
||||
template <typename ContextType>
|
||||
int EventBroker::Process()
|
||||
{
|
||||
const std::string contextTypeName = typeid(ContextType).name();
|
||||
return Process(contextTypeName);
|
||||
const std::string contextTypeName = typeid(ContextType).name();
|
||||
return Process(contextTypeName);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
@@ -81,8 +81,6 @@ public:
|
||||
@param resourceName Fully qualified name of the resource to reload.
|
||||
*/
|
||||
static void Reload(std::string resourceName);
|
||||
|
||||
static void Release(std::string resourceType, std::string resourceName);
|
||||
|
||||
static void Update();
|
||||
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
#ifndef System_h__
|
||||
#define System_h__
|
||||
|
||||
#include "EventBroker.h"
|
||||
#include "World.h"
|
||||
#include "ComponentWrapper.h"
|
||||
|
||||
class System
|
||||
{
|
||||
friend class SystemPipeline;
|
||||
|
||||
public:
|
||||
System(EventBroker* eventBroker, std::string componentType)
|
||||
: m_EventBroker(eventBroker)
|
||||
, m_ComponentType(componentType)
|
||||
{ }
|
||||
|
||||
virtual void Update(World* world, ComponentWrapper& component, double dt) = 0;
|
||||
|
||||
protected:
|
||||
std::string m_ComponentType;
|
||||
EventBroker* m_EventBroker;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -1,58 +0,0 @@
|
||||
#ifndef SystemPipeline_h__
|
||||
#define SystemPipeline_h__
|
||||
|
||||
#include "../Common.h"
|
||||
#include "EventBroker.h"
|
||||
#include "System.h"
|
||||
#include "World.h"
|
||||
|
||||
class SystemPipeline
|
||||
{
|
||||
public:
|
||||
SystemPipeline(EventBroker* eventBroker)
|
||||
: m_EventBroker(eventBroker)
|
||||
{ }
|
||||
~SystemPipeline()
|
||||
{
|
||||
for (auto& pair : m_Systems) {
|
||||
for (auto& system : pair.second) {
|
||||
delete system;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T, typename... Arguments>
|
||||
void AddSystem(Arguments... args)
|
||||
{
|
||||
System* system = new T(m_EventBroker, args...);
|
||||
if (!system->m_ComponentType.empty()) {
|
||||
m_Systems[system->m_ComponentType].push_back(system);
|
||||
} else {
|
||||
LOG_ERROR("Failed to add system \"%s\": Missing component type!", typeid(T).name());
|
||||
delete system;
|
||||
}
|
||||
}
|
||||
|
||||
void Update(World* world, double dt)
|
||||
{
|
||||
for (auto& pair : m_Systems) {
|
||||
const std::string& componentName = pair.first;
|
||||
auto& systems = pair.second;
|
||||
const ComponentPool* pool = world->GetComponents(componentName);
|
||||
if (pool == nullptr) {
|
||||
continue;
|
||||
}
|
||||
for (auto& component : *pool) {
|
||||
for (auto& system : systems) {
|
||||
system->Update(world, component, dt);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
EventBroker* m_EventBroker;
|
||||
std::unordered_map<std::string, std::vector<System*>> m_Systems;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -2,7 +2,7 @@
|
||||
#define World_h__
|
||||
|
||||
#include "../Common.h"
|
||||
#include "Entity.h"
|
||||
#include "EntityWrapper.h"
|
||||
#include "ObjectPool.h"
|
||||
#include "ComponentPool.h"
|
||||
|
||||
@@ -12,7 +12,6 @@ public:
|
||||
World() = default;
|
||||
~World();
|
||||
|
||||
// Create empty entity
|
||||
EntityID CreateEntity(EntityID parent = 0);
|
||||
|
||||
// Register a component type and allocate space for it
|
||||
@@ -22,12 +21,10 @@ public:
|
||||
// Get a component of an entity
|
||||
ComponentWrapper GetComponent(EntityID entity, std::string componentType);
|
||||
// Get all components of the specified type
|
||||
const ComponentPool* GetComponents(std::string componentType);
|
||||
// Get entity parent
|
||||
EntityID GetParent(EntityID entity);
|
||||
const ComponentPool& GetComponents(std::string componentType);
|
||||
|
||||
private:
|
||||
EntityID m_CurrentEntityID = 1;
|
||||
EntityID m_CurrentEntityID = 0;
|
||||
|
||||
std::unordered_map<EntityID, EntityID> m_EntityParents;
|
||||
std::unordered_multimap<EntityID, EntityID> m_EntityChildren;
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
#ifndef DrawScenePass_h__
|
||||
#define DrawScenePass_h__
|
||||
|
||||
#include "IRenderer.h"
|
||||
#include "DrawScenePassState.h"
|
||||
#include "FrameBuffer.h"
|
||||
#include "ShaderProgram.h"
|
||||
#include "Util/UnorderedMapVec2.h"
|
||||
#include "Texture.h"
|
||||
|
||||
class DrawScenePass
|
||||
{
|
||||
public:
|
||||
DrawScenePass(IRenderer* renderer);
|
||||
~DrawScenePass() { }
|
||||
void InitializeTextures();
|
||||
void InitializeFrameBuffers();
|
||||
void InitializeShaderPrograms();
|
||||
|
||||
void Draw(RenderQueueCollection& rq);
|
||||
|
||||
//Getters
|
||||
|
||||
|
||||
private:
|
||||
void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const;
|
||||
|
||||
Texture* m_WhiteTexture;
|
||||
|
||||
const IRenderer* m_Renderer;
|
||||
|
||||
ShaderProgram* m_BasicForwardProgram;
|
||||
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -1,15 +0,0 @@
|
||||
#ifndef DrawScenePassState_h__
|
||||
#define DrawScenePassState_h__
|
||||
|
||||
#include "Rendering/RenderState.h"
|
||||
|
||||
class DrawScenePassState : public RenderState
|
||||
{
|
||||
public:
|
||||
DrawScenePassState();
|
||||
~DrawScenePassState();
|
||||
private:
|
||||
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -1,69 +0,0 @@
|
||||
#ifndef Events_Picking_h__
|
||||
#define Events_Picking_h__
|
||||
|
||||
#include "../OpenGL.h"
|
||||
#include "../GLM.h"
|
||||
|
||||
#include "../Core/EventBroker.h"
|
||||
#include "Util/ScreenCoords.h"
|
||||
#include "FrameBuffer.h"
|
||||
#include "../Core/Entity.h"
|
||||
#include "Util/UnorderedMapVec2.h"
|
||||
|
||||
namespace Events
|
||||
{
|
||||
|
||||
/** Thrown Every frame, use functions to pick*/
|
||||
struct Picking : Event
|
||||
{
|
||||
public:
|
||||
Picking(FrameBuffer* pickingBuffer, GLuint* depthBuffer, glm::mat4 projectionMatrix, glm::mat4 viewMatrix, Rectangle resolution, const std::unordered_map<glm::vec2, EntityID>* pickingColorsToEntity)
|
||||
: PickingBuffer(pickingBuffer)
|
||||
, DepthBuffer(depthBuffer)
|
||||
, ProjectionMatrix(projectionMatrix)
|
||||
, ViewMatrix(viewMatrix)
|
||||
, Resolution(resolution)
|
||||
, PickingColorsToEntity(pickingColorsToEntity)
|
||||
{ }
|
||||
|
||||
|
||||
|
||||
struct PickData
|
||||
{
|
||||
//Picked Entity
|
||||
EntityID Entity;
|
||||
//World position of the "pick"
|
||||
glm::vec3 Position;
|
||||
};
|
||||
|
||||
PickData Pick(glm::vec2 screenCoord) const
|
||||
{
|
||||
PickData pickData;
|
||||
|
||||
ScreenCoords::PixelData data = ScreenCoords::ToPixelData(screenCoord, PickingBuffer, *DepthBuffer);
|
||||
|
||||
auto it = PickingColorsToEntity->find(glm::vec2(data.Color[0], data.Color[1]));
|
||||
if (it != PickingColorsToEntity->end()) {
|
||||
pickData.Entity = it->second;
|
||||
} else {
|
||||
pickData.Entity = -1;
|
||||
}
|
||||
pickData.Position = ScreenCoords::ToWorldPos(screenCoord.x, Resolution.Width - screenCoord.y, data.Depth, Resolution, ProjectionMatrix, ViewMatrix);
|
||||
|
||||
return pickData;
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
FrameBuffer* PickingBuffer;
|
||||
GLuint* DepthBuffer;
|
||||
const glm::mat4 ProjectionMatrix;
|
||||
const glm::mat4 ViewMatrix;
|
||||
const Rectangle Resolution;
|
||||
const std::unordered_map<glm::vec2, EntityID>* PickingColorsToEntity;
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,49 +0,0 @@
|
||||
#ifndef PickingPass_h__
|
||||
#define PickingPass_h__
|
||||
|
||||
#include "IRenderer.h"
|
||||
#include "PickingPassState.h"
|
||||
#include "FrameBuffer.h"
|
||||
#include "ShaderProgram.h"
|
||||
#include "Util/UnorderedMapVec2.h"
|
||||
#include "../Core/EventBroker.h"
|
||||
#include "EPicking.h"
|
||||
|
||||
class PickingPass
|
||||
{
|
||||
public:
|
||||
PickingPass(IRenderer* renderer, EventBroker* eb);
|
||||
~PickingPass();
|
||||
void InitializeTextures();
|
||||
void InitializeFrameBuffers();
|
||||
void InitializeShaderPrograms();
|
||||
|
||||
void Draw(RenderQueueCollection& rq);
|
||||
|
||||
|
||||
//Getters
|
||||
const ShaderProgram& PickingProgram() const { return *m_PickingProgram; }
|
||||
const std::unordered_map<glm::vec2, EntityID>& PickingColorsToEntity() const { return m_PickingColorsToEntity; }
|
||||
GLuint PickingTexture() const { return m_PickingTexture; }
|
||||
GLuint DepthBuffer() const { return m_DepthBuffer; }
|
||||
const FrameBuffer& PickingBuffer() const { return m_PickingBuffer; }
|
||||
|
||||
|
||||
private:
|
||||
void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const;
|
||||
|
||||
EventBroker* m_EventBroker;
|
||||
|
||||
const IRenderer* m_Renderer;
|
||||
|
||||
ShaderProgram* m_PickingProgram;
|
||||
|
||||
std::unordered_map<glm::vec2, EntityID> m_PickingColorsToEntity;
|
||||
|
||||
GLuint m_PickingTexture;
|
||||
GLuint m_DepthBuffer;
|
||||
|
||||
FrameBuffer m_PickingBuffer;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -1,15 +0,0 @@
|
||||
#ifndef PickingPassState_h__
|
||||
#define PickingPassState_h__
|
||||
|
||||
#include "Rendering/RenderState.h"
|
||||
|
||||
class PickingPassState : public RenderState
|
||||
{
|
||||
public:
|
||||
PickingPassState(GLuint frameBuffer);
|
||||
~PickingPassState();
|
||||
|
||||
private:
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -7,7 +7,7 @@
|
||||
#include "../Common.h"
|
||||
#include "../GLM.h"
|
||||
#include "../Core/Util/Rectangle.h"
|
||||
#include "../Core/Entity.h"
|
||||
#include "../Core/EntityWrapper.h"
|
||||
|
||||
class Model;
|
||||
class Skeleton;
|
||||
|
||||
@@ -22,10 +22,7 @@ private:
|
||||
void FillLights(World* world, RenderQueue* renderQueue);
|
||||
|
||||
glm::mat4 ModelMatrix(World* world, EntityID entity);
|
||||
|
||||
glm::vec3 AbsolutePosition(World* world, EntityID entity);
|
||||
glm::quat AbsoluteOrientation(World* world, EntityID entity);
|
||||
glm::vec3 AbsoluteScale(World* world, EntityID entity);
|
||||
glm::vec3 GetAbsolutePosition(World* world, ComponentWrapper transformComponent);
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -1,23 +0,0 @@
|
||||
#ifndef RenderState_h__
|
||||
#define RenderState_h__
|
||||
|
||||
#include "../Common.h"
|
||||
#include "../OpenGL.h"
|
||||
#include "../GLM.h"
|
||||
|
||||
class RenderState
|
||||
{
|
||||
public:
|
||||
RenderState();
|
||||
~RenderState();
|
||||
bool Enable(GLenum GLEnable);
|
||||
bool CullFace(GLenum GlFaceToCull);
|
||||
bool ClearColor(glm::vec4 color);
|
||||
bool Clear(GLbitfield mask);
|
||||
bool BindBuffer(GLint buffer);
|
||||
private:
|
||||
std::vector<GLenum> m_Enables;
|
||||
float m_preClearColor[4];
|
||||
int m_preBuffer;
|
||||
};
|
||||
#endif
|
||||
@@ -10,109 +10,48 @@
|
||||
#include "Util/UnorderedMapVec2.h"
|
||||
#include "FrameBuffer.h"
|
||||
#include "../Core/World.h"
|
||||
#include "PickingPass.h"
|
||||
#include "DrawScenePass.h"
|
||||
|
||||
|
||||
#define TILE_SIZE 16
|
||||
#define NUM_LIGHTS 5000
|
||||
|
||||
|
||||
#include "../Core/EventBroker.h"
|
||||
#include "EPicking.h"
|
||||
|
||||
class Renderer : public IRenderer
|
||||
{
|
||||
public:
|
||||
Renderer(EventBroker* eventBroker)
|
||||
: m_EventBroker(eventBroker)
|
||||
{ }
|
||||
|
||||
virtual void Initialize() override;
|
||||
virtual void Update(double dt) override;
|
||||
virtual void Draw(RenderQueueCollection& rq) override;
|
||||
virtual void Initialize() override;
|
||||
virtual void Update(double dt) override;
|
||||
virtual void Draw(RenderQueueCollection& rq) override;
|
||||
|
||||
private:
|
||||
//----------------------Variables----------------------//
|
||||
EventBroker* m_EventBroker;
|
||||
|
||||
Texture* m_ErrorTexture;
|
||||
Texture* m_WhiteTexture;
|
||||
float m_CameraMoveSpeed;
|
||||
//----------------------Variables----------------------//
|
||||
Texture* m_ErrorTexture;
|
||||
Texture* m_WhiteTexture;
|
||||
float m_CameraMoveSpeed;
|
||||
FrameBuffer m_PickingBuffer;
|
||||
GLuint m_PickingTexture;
|
||||
GLuint m_DepthBuffer;
|
||||
|
||||
Model* m_ScreenQuad;
|
||||
Model* m_UnitQuad;
|
||||
Model* m_UnitSphere;
|
||||
|
||||
DrawScenePass* m_DrawScenePass;
|
||||
PickingPass* m_PickingPass;
|
||||
|
||||
//----------------------Functions----------------------//
|
||||
void InitializeWindow();
|
||||
void InitializeShaders();
|
||||
|
||||
std::unordered_map<glm::vec2, EntityID> m_PickingColorsToEntity;
|
||||
|
||||
//----------------------Functions----------------------//
|
||||
void InitializeWindow();
|
||||
void InitializeShaders();
|
||||
void InitializeTextures();
|
||||
void InitializeSSBOs();
|
||||
void InitializeRenderPasses();
|
||||
void InitializeFrameBuffers();
|
||||
//TODO: Renderer: Get InputUpdate out of renderer
|
||||
void InputUpdate(double dt);
|
||||
//void PickingPass(RenderQueueCollection& rq);
|
||||
void InputUpdate(double dt);
|
||||
void PickingPass(RenderQueueCollection& rq);
|
||||
void DrawScreenQuad(GLuint textureToDraw);
|
||||
void DrawScene(RenderQueueCollection& rq);
|
||||
|
||||
//----------------------Forward+-----------------------//
|
||||
void CalculateFrustum();
|
||||
void CullLights();
|
||||
void DrawForwardPlus(RenderQueueCollection& rq);
|
||||
//Frustum
|
||||
struct Plane {
|
||||
glm::vec3 Normal;
|
||||
float d;
|
||||
};
|
||||
|
||||
struct Frustum {
|
||||
Plane Planes[4];
|
||||
};
|
||||
Frustum m_Frustums[80*45]; //TODO: Renderer: Make this change with resolution
|
||||
|
||||
//Lights
|
||||
void TEMPCreateLights();
|
||||
//TODO: Renderer: Add Directionllights, spotlights and area lights to this as type.
|
||||
struct PointLight {
|
||||
glm::vec4 Position = glm::vec4(0.f);
|
||||
glm::vec4 Color = glm::vec4(1.f);
|
||||
float Radius = 5.f;
|
||||
float Intensity = 0.8f;
|
||||
float Falloff = 0.3f;
|
||||
float Padding = 1337;
|
||||
};
|
||||
PointLight m_PointLights[NUM_LIGHTS];
|
||||
|
||||
struct LightGrid {
|
||||
float Start;
|
||||
float Amount;
|
||||
glm::vec2 Padding;
|
||||
};
|
||||
|
||||
LightGrid m_LightGrid[80*45];
|
||||
|
||||
int m_LightOffset = 0;
|
||||
|
||||
float m_LightIndex[80*45*200];
|
||||
|
||||
//-------------------------SSBO------------------------//
|
||||
GLuint m_FrustumSSBO = 0;
|
||||
GLuint m_LightSSBO = 0;
|
||||
GLuint m_LightGridSSBO = 0;
|
||||
GLuint m_LightOffsetSSBO = 0;
|
||||
GLuint m_LightIndexSSBO = 0;
|
||||
|
||||
void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type);
|
||||
//--------------------ShaderPrograms-------------------//
|
||||
ShaderProgram* m_BasicForwardProgram;
|
||||
ShaderProgram* m_DrawScreenQuadProgram;
|
||||
ShaderProgram* m_CalculateFrustumProgram;
|
||||
ShaderProgram* m_LightCullProgram;
|
||||
ShaderProgram* m_ForwardPlusProgram;
|
||||
|
||||
ShaderProgram m_BasicForwardProgram;
|
||||
ShaderProgram m_PickingProgram;
|
||||
ShaderProgram m_DrawScreenQuadProgram;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -1,9 +1,6 @@
|
||||
#ifndef ShaderProgram_h__
|
||||
#define ShaderProgram_h__
|
||||
|
||||
#include "../Common.h"
|
||||
#include "../OpenGL.h"
|
||||
#include "../Core/ResourceManager.h"
|
||||
#include <fstream>
|
||||
|
||||
class Shader
|
||||
@@ -63,13 +60,11 @@ public:
|
||||
: ShaderType(fileName) { }
|
||||
};
|
||||
|
||||
class ShaderProgram : public Resource
|
||||
class ShaderProgram
|
||||
{
|
||||
friend class ResourceManager;
|
||||
private:
|
||||
ShaderProgram(std::string)
|
||||
: m_ShaderProgramHandle(0) { }
|
||||
public:
|
||||
ShaderProgram()
|
||||
: m_ShaderProgramHandle(0) { }
|
||||
~ShaderProgram();
|
||||
|
||||
void AddShader(std::shared_ptr<Shader> shader);
|
||||
@@ -84,5 +79,3 @@ private:
|
||||
GLuint m_ShaderProgramHandle;
|
||||
std::vector<std::shared_ptr<Shader>> m_Shaders;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -9,7 +9,7 @@ inline bool _GLERROR(const char* info, const char* file, const char* func, unsig
|
||||
GLenum error = glGetError();
|
||||
if (error != GL_NO_ERROR)
|
||||
{
|
||||
_LOG(LOG_LEVEL_ERROR, file, func, line, "GL Error: %s, %i, %s", info, error, gluErrorString(error));
|
||||
_LOG(LOG_LEVEL_ERROR, file, func, line, "GL Error: %s %i %s", info, error, gluErrorString(error));
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -11,13 +11,6 @@ class ScreenCoords
|
||||
{
|
||||
public:
|
||||
ScreenCoords() = delete;
|
||||
|
||||
struct PixelData
|
||||
{
|
||||
int Color[2];
|
||||
float Depth;
|
||||
};
|
||||
|
||||
//Return world position from given screenspace coordinates and depth value in viewspace.
|
||||
static glm::vec3 ToWorldPos(glm::vec2 screenCoord, float depth, Rectangle resolution, glm::mat4 cameraProjectionMat, glm::mat4 cameraViewMat);
|
||||
static glm::vec3 ToWorldPos(float x, float y, float depth, Rectangle resolution, glm::mat4 cameraProjectionMat, glm::mat4 cameraViewMat);
|
||||
@@ -25,8 +18,8 @@ public:
|
||||
static glm::vec3 ToWorldPos(float x, float y, float depth, float screenWidth, float screenHeight, glm::mat4 cameraProjectionMat, glm::mat4 cameraViewMat);
|
||||
//Return data from the given buffers at the coordinates given in screenspace. Buffer should probably have a texture that covers the screen.
|
||||
//Data is given as R = x, B = y, and
|
||||
static PixelData ToPixelData(glm::vec2 screenCoord, FrameBuffer* PickDataBuffer, GLuint DepthBuffer);
|
||||
static PixelData ToPixelData(float x, float y, FrameBuffer* PickDataBuffer, GLuint DepthBuffer);
|
||||
static glm::vec3 ToPixelData(glm::vec2 screenCoord, FrameBuffer* PickDataBuffer, GLuint DepthBuffer);
|
||||
static glm::vec3 ToPixelData(float x, float y, FrameBuffer* PickDataBuffer, GLuint DepthBuffer);
|
||||
//Return EntityID of the clicked coordinate in given screenspace coordinates.
|
||||
//EntityID ScreenCoordsToEntityID(glm::vec2 screenCoord, float depth);
|
||||
|
||||
|
||||
@@ -9,11 +9,6 @@
|
||||
#include "GUI/Frame.h"
|
||||
#include "Core/World.h"
|
||||
#include "Rendering/RenderQueueFactory.h"
|
||||
#include "Core/EKeyDown.h"
|
||||
#include "Core/EntityXMLFile.h"
|
||||
#include "Core/SystemPipeline.h"
|
||||
#include "RaptorCopterSystem.h"
|
||||
#include "PlayerSystem.h"
|
||||
|
||||
class Game
|
||||
{
|
||||
@@ -32,14 +27,7 @@ private:
|
||||
InputManager* m_InputManager;
|
||||
GUI::Frame* m_FrameStack;
|
||||
World* m_World;
|
||||
SystemPipeline* m_SystemPipeline;
|
||||
RenderQueueFactory* m_RenderQueueFactory;
|
||||
|
||||
EventRelay<Game, Events::KeyUp> m_EKeyUp;
|
||||
bool testOnKeyUp(const Events::KeyUp& e);
|
||||
|
||||
void testIntialize();
|
||||
void testTick(double dt);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
#include <list>
|
||||
#include <tuple>
|
||||
#include <boost/any.hpp>
|
||||
#include "GLM.h"
|
||||
#include "Core/World.h"
|
||||
#include "Core/Util/Any.h"
|
||||
|
||||
class HardcodedTestWorld : public World
|
||||
{
|
||||
public:
|
||||
HardcodedTestWorld()
|
||||
: World()
|
||||
{
|
||||
registerTestComponents();
|
||||
createTestEntities();
|
||||
}
|
||||
|
||||
private:
|
||||
void registerTestComponents()
|
||||
{
|
||||
ComponentWrapperFactory f;
|
||||
|
||||
|
||||
f = ComponentWrapperFactory("Test");
|
||||
f.AddProperty("TestInteger", 1337);
|
||||
f.AddProperty("TestFloat", 13.37f);
|
||||
f.AddProperty("TestString", std::string("Carlito"));
|
||||
RegisterComponent(f);
|
||||
|
||||
f = ComponentWrapperFactory("Debug");
|
||||
f.AddProperty("Name", std::string("Unnamed"));
|
||||
RegisterComponent(f);
|
||||
|
||||
f = ComponentWrapperFactory("Transform");
|
||||
f.AddProperty("Position", glm::vec3(0.f, 0.f, 0.f));
|
||||
f.AddProperty("Orientation", glm::quat());
|
||||
f.AddProperty("Scale", glm::vec3(1.f, 1.f, 1.f));
|
||||
RegisterComponent(f);
|
||||
|
||||
f = ComponentWrapperFactory("Model");
|
||||
f.AddProperty("Resource", std::string());
|
||||
f.AddProperty("Color", glm::vec4(1.f, 1.f, 1.f, 1.f));
|
||||
f.AddProperty("Visible", true);
|
||||
RegisterComponent(f);
|
||||
}
|
||||
|
||||
void createTestEntities()
|
||||
{
|
||||
World& world = *this;
|
||||
|
||||
// Create an entity
|
||||
EntityID e = world.CreateEntity();
|
||||
|
||||
// Attach a Debug component
|
||||
ComponentWrapper debug = world.AttachComponent(e, "Debug");
|
||||
// Set the Name field of the Debug component using subscript operator
|
||||
debug["Name"] = "Carlito";
|
||||
|
||||
// Attach a Transform component
|
||||
world.AttachComponent(e, "Transform");
|
||||
// Fetch the component based on EntityID and component type
|
||||
ComponentWrapper transform = world.GetComponent(e, "Transform");
|
||||
// Set the fields of the Transform component
|
||||
transform["Position"] = glm::vec3(0.f, 0.f, 0.f);
|
||||
transform["Scale"] = glm::vec3(1.f, 1.f, 1.f);
|
||||
|
||||
// Move on the X axis by fetching field as reference
|
||||
((glm::vec3&)transform["Position"]).x += 10.f;
|
||||
// Shrink by a factor of 100
|
||||
((glm::vec3&)transform["Scale"]) /= 100.f;
|
||||
|
||||
// Loop through all Transform components and print them
|
||||
for (auto& transform : world.GetComponents("Transform")) {
|
||||
glm::vec3 pos = transform["Position"];
|
||||
std::cout << "Position: " << pos.x << " " << pos.y << " " << pos.z << std::endl;
|
||||
glm::vec3 scale = transform["Scale"];
|
||||
std::cout << "Scale: " << scale.x << " " << scale.y << " " << scale.z << std::endl;
|
||||
|
||||
// Fetch the Debug component also present in this entity
|
||||
ComponentWrapper debug = world.GetComponent(transform.EntityID, "Debug");
|
||||
std::cout << "Name: " << (std::string)debug["Name"] << std::endl;
|
||||
}
|
||||
|
||||
//Create some test widgets
|
||||
{
|
||||
EntityID entityScaleWidget = world.CreateEntity();
|
||||
ComponentWrapper transform = world.AttachComponent(entityScaleWidget, "Transform");
|
||||
transform["Position"] = glm::vec3(-1.5f, 0.f, 0.f);
|
||||
ComponentWrapper model = world.AttachComponent(entityScaleWidget, "Model");
|
||||
model["Resource"] = "Models/ScaleWidget.obj";
|
||||
}
|
||||
{
|
||||
EntityID entityRotationWidget = world.CreateEntity();
|
||||
ComponentWrapper transform = world.AttachComponent(entityRotationWidget, "Transform");
|
||||
transform["Position"] = glm::vec3(1.5f, 0.f, 0.f);
|
||||
ComponentWrapper model = world.AttachComponent(entityRotationWidget, "Model");
|
||||
model["Resource"] = "Models/RotationWidget.obj";
|
||||
}
|
||||
{
|
||||
EntityID entityDummyScene = world.CreateEntity();
|
||||
ComponentWrapper transform = world.AttachComponent(entityDummyScene, "Transform");
|
||||
transform["Position"] = glm::vec3(0, 0.f, 0.f);
|
||||
ComponentWrapper model = world.AttachComponent(entityDummyScene, "Model");
|
||||
model["Resource"] = "Models/DummyScene.obj";
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
};
|
||||
@@ -1,44 +0,0 @@
|
||||
#ifndef PlayerSystem_h__
|
||||
#define PlayerSystem_h__
|
||||
|
||||
#include <GLFW/glfw3.h>
|
||||
#include <glm/common.hpp>
|
||||
|
||||
#include "Common.h"
|
||||
#include "Core/System.h"
|
||||
#include "Core/EventBroker.h"
|
||||
#include "Core/EKeyDown.h"
|
||||
#include "Core/EKeyUp.h"
|
||||
|
||||
struct KeyInput
|
||||
{
|
||||
bool Forward = false;
|
||||
bool Left = false;
|
||||
bool Back = false;
|
||||
bool Right = false;
|
||||
};
|
||||
|
||||
class PlayerSystem : public System
|
||||
{
|
||||
public:
|
||||
PlayerSystem(EventBroker* eventBroker)
|
||||
: System(eventBroker, "Player")
|
||||
{
|
||||
EVENT_SUBSCRIBE_MEMBER(m_EKeyDown, &PlayerSystem::OnKeyDown);
|
||||
EVENT_SUBSCRIBE_MEMBER(m_EKeyUp, &PlayerSystem::OnKeyUp);
|
||||
}
|
||||
|
||||
virtual void Update(World* world, ComponentWrapper& player, double dt) override;
|
||||
|
||||
private:
|
||||
float m_Speed = 5;
|
||||
glm::vec3 m_Direction;
|
||||
KeyInput input;
|
||||
|
||||
EventRelay<PlayerSystem, Events::KeyDown> m_EKeyDown;
|
||||
bool OnKeyDown(const Events::KeyDown &event);
|
||||
EventRelay<PlayerSystem, Events::KeyUp> m_EKeyUp;
|
||||
bool OnKeyUp(const Events::KeyUp &event);
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -1,18 +0,0 @@
|
||||
#include "Common.h"
|
||||
#include "Core/System.h"
|
||||
|
||||
class RaptorCopterSystem : public System
|
||||
{
|
||||
public:
|
||||
RaptorCopterSystem(EventBroker* eventBroker)
|
||||
: System(eventBroker, "RaptorCopter")
|
||||
{ }
|
||||
|
||||
virtual void Initialize() { }
|
||||
|
||||
virtual void Update(World* world, ComponentWrapper& raptorCopter, double dt) override
|
||||
{
|
||||
ComponentWrapper& transform = world->GetComponent(raptorCopter.EntityID, "Transform");
|
||||
(glm::vec3&)transform["Orientation"] += (float)(double)raptorCopter["Speed"] * (float)dt * (glm::vec3)raptorCopter["Axis"];
|
||||
}
|
||||
};
|
||||
@@ -1,10 +1,8 @@
|
||||
[Debug]
|
||||
LogLevel=1
|
||||
LoadMap=
|
||||
|
||||
[Video]
|
||||
Fullscreen=false
|
||||
VSYNC=false
|
||||
Width=1280
|
||||
Height=720
|
||||
FOV=45
|
||||
Height=720
|
||||
@@ -2,8 +2,5 @@
|
||||
|
||||
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="components" elementFormDefault="qualified">
|
||||
<xs:include schemaLocation="Components/Transform.xsd"/>
|
||||
<xs:include schemaLocation="Components/Model.xsd"/>
|
||||
<xs:include schemaLocation="Components/Test.xsd"/>
|
||||
<xs:include schemaLocation="Components/RaptorCopter.xsd"/>
|
||||
<xs:include schemaLocation="Components/Player.xsd"/>
|
||||
</xs:schema>
|
||||
@@ -1,5 +0,0 @@
|
||||
<c:Model>
|
||||
<Resource></Resource>
|
||||
<Color R="1" G="1" B="1" A="1"/>
|
||||
<Visible>true</Visible>
|
||||
</c:Model>
|
||||
@@ -1,24 +0,0 @@
|
||||
<?xml version="1.0"?>
|
||||
|
||||
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:t="types">
|
||||
<xs:import schemaLocation="../Types.xsd" namespace="types"/>
|
||||
|
||||
<xs:element name="Model">
|
||||
<xs:annotation>
|
||||
<xs:documentation>A visible model loaded from disk</xs:documentation>
|
||||
</xs:annotation>
|
||||
<xs:complexType>
|
||||
<xs:all>
|
||||
<xs:element name="Resource" type="t:string" minOccurs="0">
|
||||
<xs:annotation><xs:documentation>Model file</xs:documentation></xs:annotation>
|
||||
</xs:element>
|
||||
<xs:element name="Color" type="t:Color" minOccurs="0">
|
||||
<xs:annotation><xs:documentation>Color tint</xs:documentation></xs:annotation>
|
||||
</xs:element>
|
||||
<xs:element name="Visible" type="t:bool" minOccurs="0">
|
||||
<xs:annotation><xs:documentation>Wether the model is visible or not</xs:documentation></xs:annotation>
|
||||
</xs:element>
|
||||
</xs:all>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
</xs:schema>
|
||||
@@ -1,3 +0,0 @@
|
||||
<c:Player>
|
||||
<Velocity X="0" Y="0" Z="0"/>
|
||||
</c:Player>
|
||||
@@ -1,13 +0,0 @@
|
||||
<?xml version="1.0"?>
|
||||
|
||||
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:t="types">
|
||||
<xs:import schemaLocation="../Types.xsd" namespace="types"/>
|
||||
|
||||
<xs:element name="Player">
|
||||
<xs:complexType>
|
||||
<xs:all>
|
||||
<xs:element name="Velocity" type="t:Vector" minOccurs="0"/>
|
||||
</xs:all>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
</xs:schema>
|
||||
@@ -1,4 +0,0 @@
|
||||
<c:RaptorCopter>
|
||||
<Speed>0</Speed>
|
||||
<Axis X="0" Y="0" Z="0"/>
|
||||
</c:RaptorCopter>
|
||||
@@ -1,14 +0,0 @@
|
||||
<?xml version="1.0"?>
|
||||
|
||||
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:t="types">
|
||||
<xs:import schemaLocation="../Types.xsd" namespace="types"/>
|
||||
|
||||
<xs:element name="RaptorCopter">
|
||||
<xs:complexType>
|
||||
<xs:all>
|
||||
<xs:element name="Speed" type="t:double" minOccurs="0"/>
|
||||
<xs:element name="Axis" type="t:Vector" minOccurs="0"/>
|
||||
</xs:all>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
</xs:schema>
|
||||
@@ -2,5 +2,5 @@
|
||||
<Integer>1</Integer>
|
||||
<Float>1.333</Float>
|
||||
<Vector X="1.33333" Y="2.33333" Z="3.33333"/>
|
||||
<Quaternion X="1.33333" Y="2.33333" Z="3.33333" W="4.44444"/>
|
||||
<Quaternion I="1.33333" J="2.33333" K="3.33333"/>
|
||||
</c:Test>
|
||||
@@ -1,5 +1,5 @@
|
||||
<c:Transform>
|
||||
<TransformComponent>
|
||||
<Position X="0" Y="0" Z="0"/>
|
||||
<Orientation X="0" Y="0" Z="0" W="0"/>
|
||||
<Orientation I="0" J="0" K="0"/>
|
||||
<Scale X="1" Y="1" Z="1"/>
|
||||
</c:Transform>
|
||||
</TransformComponent>
|
||||
@@ -12,7 +12,7 @@
|
||||
<xs:element name="Position" type="t:Vector" minOccurs="0">
|
||||
<xs:annotation><xs:documentation>The position vector</xs:documentation></xs:annotation>
|
||||
</xs:element>
|
||||
<xs:element name="Orientation" type="t:Vector" minOccurs="0"/>
|
||||
<xs:element name="Orientation" type="t:Quaternion" minOccurs="0"/>
|
||||
<xs:element name="Scale" type="t:Vector" minOccurs="0"/>
|
||||
</xs:all>
|
||||
</xs:complexType>
|
||||
|
||||
@@ -3,122 +3,18 @@
|
||||
<Entity xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xi="http://www.w3.org/2001/XInclude" xsi:noNamespaceSchemaLocation="../Types/Entity.xsd" xmlns:c="components">
|
||||
<Components>
|
||||
<c:Transform>
|
||||
<Orientation X="0" Y="0" Z="0"/>
|
||||
<Position X="1.02" Y="3.123123" Z="41.123"/>
|
||||
<Orientation I="1.234" J="1.234" K="1.234"/>
|
||||
<Scale X="1.02" Y="3.123123" Z="41.123"/>
|
||||
</c:Transform>
|
||||
<c:Test>
|
||||
<Integer>12</Integer>
|
||||
<Double>11.11</Double>
|
||||
<String>Hello World</String>
|
||||
</c:Test>
|
||||
</Components>
|
||||
<Children>
|
||||
<Entity>
|
||||
<Components>
|
||||
<c:Transform>
|
||||
<Scale X="10000" Y="10000" Z="10000"/>
|
||||
</c:Transform>
|
||||
<c:Model>
|
||||
<Resource>Models/Core/UnitPlane.obj</Resource>
|
||||
</c:Model>
|
||||
</Components>
|
||||
</Entity>
|
||||
<Entity>
|
||||
<Components>
|
||||
<c:Transform>
|
||||
<Position X="-1.5"/>
|
||||
<Scale X="1" Y="1" Z="1"/>
|
||||
</c:Transform>
|
||||
<c:Model>
|
||||
<Resource>Models/ScaleWidget.obj</Resource>
|
||||
</c:Model>
|
||||
</Components>
|
||||
</Entity>
|
||||
<Entity>
|
||||
<Components>
|
||||
<c:Transform>
|
||||
<Position X="1.5"/>
|
||||
</c:Transform>
|
||||
<c:Model>
|
||||
<Resource>Models/RotationWidget.obj</Resource>
|
||||
</c:Model>
|
||||
</Components>
|
||||
</Entity>
|
||||
<Entity>
|
||||
<Components>
|
||||
<c:Player>
|
||||
<Velocity X="0" Y="0" Z="0"/>
|
||||
</c:Player>
|
||||
<c:Transform>
|
||||
<Position X="2.5"/>
|
||||
</c:Transform>
|
||||
<c:Model>
|
||||
<Resource>Models/Core/UnitCube.obj</Resource>
|
||||
</c:Model>
|
||||
</Components>
|
||||
</Entity>
|
||||
<Entity>
|
||||
<Components>
|
||||
<c:Transform>
|
||||
<Position X="0" Y="-0"/>
|
||||
<Scale X="1" Y="1" Z="1"/>
|
||||
</c:Transform>
|
||||
<!--<c:Move>
|
||||
<Speed>1</Speed>
|
||||
<Direction X="-1"/>
|
||||
<Rotation Y="3.14"/>
|
||||
</c:Move>-->
|
||||
</Components>
|
||||
<Children>
|
||||
<Entity>
|
||||
<Components>
|
||||
<c:Transform>
|
||||
<Position X="0" Y="0"/>
|
||||
<Orientation X="0.0" Y="0" Z="1.0"/>
|
||||
</c:Transform>
|
||||
<c:Model>
|
||||
<Resource>Models/Core/UnitRaptor.obj</Resource>
|
||||
<Color R="1" G="0.4" B="0.8"/>
|
||||
</c:Model>
|
||||
</Components>
|
||||
<Children>
|
||||
<Entity>
|
||||
<Components>
|
||||
<c:Transform>
|
||||
<Position X="-0.01" Y="0.55"/>
|
||||
<Orientation X="0" Y="0" Z="-1"/>
|
||||
</c:Transform>
|
||||
<c:RaptorCopter>
|
||||
<Speed>20</Speed>
|
||||
<Axis Y="1"/>
|
||||
</c:RaptorCopter>
|
||||
</Components>
|
||||
<Children>
|
||||
<Entity>
|
||||
<Components>
|
||||
<c:Transform>
|
||||
<Position X="0" Y="0"/>
|
||||
<Scale X="1.7" Y="0.03" Z="0.1"/>
|
||||
<Orientation X="0" Y="0" Z="0"/>
|
||||
</c:Transform>
|
||||
<c:Model>
|
||||
<Resource>Models/Core/UnitCube.obj</Resource>
|
||||
<Color R="1" G="0.4" B="0.8"/>
|
||||
</c:Model>
|
||||
</Components>
|
||||
</Entity>
|
||||
<Entity>
|
||||
<Components>
|
||||
<c:Transform>
|
||||
<Position X="0" Y="0"/>
|
||||
<Scale X="1.7" Y="0.03" Z="0.1"/>
|
||||
<Orientation X="0" Y="1.57" Z="0"/>
|
||||
</c:Transform>
|
||||
<c:Model>
|
||||
<Resource>Models/Core/UnitCube.obj</Resource>
|
||||
<Color R="1" G="0.4" B="0.8"/>
|
||||
</c:Model>
|
||||
</Components>
|
||||
</Entity>
|
||||
</Children>
|
||||
</Entity>
|
||||
</Children>
|
||||
</Entity>
|
||||
</Children>
|
||||
</Entity>
|
||||
<xi:include href="OtherEntity.xml"/>
|
||||
<xi:include href="OtherEntity.xml"/>
|
||||
</Children>
|
||||
</Entity>
|
||||
@@ -3,10 +3,6 @@
|
||||
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="types" elementFormDefault="qualified">
|
||||
<xs:include schemaLocation="Types/Quaternion.xsd"/>
|
||||
<xs:include schemaLocation="Types/Vector.xsd"/>
|
||||
<xs:include schemaLocation="Types/Color.xsd"/>
|
||||
<xs:simpleType name="bool">
|
||||
<xs:restriction base="xs:boolean"></xs:restriction>
|
||||
</xs:simpleType>
|
||||
<xs:simpleType name="int">
|
||||
<xs:restriction base="xs:integer"></xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0"?>
|
||||
|
||||
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="types" elementFormDefault="qualified">
|
||||
<xs:complexType name="Color">
|
||||
<xs:attribute name="R" type="xs:decimal" default="0.0"/>
|
||||
<xs:attribute name="G" type="xs:decimal" default="0.0"/>
|
||||
<xs:attribute name="B" type="xs:decimal" default="0.0"/>
|
||||
<xs:attribute name="A" type="xs:decimal" default="1.0"/>
|
||||
</xs:complexType>
|
||||
</xs:schema>
|
||||
@@ -7,14 +7,11 @@
|
||||
<xs:element name="Entity">
|
||||
<xs:complexType>
|
||||
<xs:all>
|
||||
<xs:element name="Components" minOccurs="0">
|
||||
<xs:element name="Components">
|
||||
<xs:complexType>
|
||||
<xs:all>
|
||||
<xs:element ref="c:Transform" minOccurs="0"/>
|
||||
<xs:element ref="c:Model" minOccurs="0"/>
|
||||
<xs:element ref="c:Test" minOccurs="0"/>
|
||||
<xs:element ref="c:RaptorCopter" minOccurs="0"/>
|
||||
<xs:element ref="c:Player" minOccurs="0"/>
|
||||
</xs:all>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
|
||||
@@ -1,131 +0,0 @@
|
||||
#version 430
|
||||
|
||||
uniform mat4 M;
|
||||
uniform mat4 V;
|
||||
uniform mat4 P;
|
||||
uniform vec4 Color;
|
||||
|
||||
uniform sampler2D texture0;
|
||||
|
||||
#define TILE_SIZE 16
|
||||
|
||||
struct PointLight {
|
||||
vec4 Position;
|
||||
vec4 Color;
|
||||
float Radius;
|
||||
float Intensity;
|
||||
float Falloff;
|
||||
float Padding;
|
||||
};
|
||||
|
||||
layout (std430, binding = 1) buffer LightBuffer
|
||||
{
|
||||
PointLight List[];
|
||||
} PointLights;
|
||||
|
||||
struct LightGrid {
|
||||
float Start;
|
||||
float Amount;
|
||||
vec2 Padding;
|
||||
};
|
||||
|
||||
layout (std430, binding = 2) buffer LightGridBuffer
|
||||
{
|
||||
LightGrid Data[];
|
||||
} LightGrids;
|
||||
|
||||
layout (std430, binding = 4) buffer LightIndexBuffer
|
||||
{
|
||||
float LightIndex[];
|
||||
};
|
||||
|
||||
|
||||
in VertexData{
|
||||
vec3 Position;
|
||||
vec3 Normal;
|
||||
vec2 TextureCoordinate;
|
||||
vec4 DiffuseColor;
|
||||
}Input;
|
||||
|
||||
out vec4 fragmentColor;
|
||||
|
||||
vec4 scene_ambient = vec4(0.3,0.3,0.3,1);
|
||||
|
||||
struct LightResult {
|
||||
vec4 Diffuse;
|
||||
vec4 Specular;
|
||||
};
|
||||
|
||||
float CalcAttenuation(float radius, float dist) {
|
||||
return 1.0 - smoothstep(radius * 0.3, radius, dist);
|
||||
}
|
||||
|
||||
vec4 CalcSpecular(vec4 lightColor, vec4 viewVec, vec4 lightVec, vec4 normal) {
|
||||
vec4 R = normalize( reflect(-lightVec, normal));
|
||||
float RdotV = max( dot(R, viewVec), 0.0);
|
||||
return lightColor * pow(RdotV, 90.0);
|
||||
}
|
||||
|
||||
vec4 CalcDiffuse(vec4 lightColor, vec4 lightVec, vec4 normal) {
|
||||
float power = max( dot(normal, lightVec), 0.0);
|
||||
return lightColor * power;
|
||||
}
|
||||
|
||||
LightResult CalcPointLight(vec4 lightPos, float lightRadius, vec4 lightColor, float intensity, vec4 viewVec, vec4 position, vec4 normal)
|
||||
{
|
||||
vec4 L = lightPos - position;
|
||||
float dist = length(L);
|
||||
L = normalize(L);
|
||||
|
||||
float attenuation = CalcAttenuation(lightRadius, dist);
|
||||
|
||||
LightResult result;
|
||||
result.Diffuse = CalcDiffuse(lightColor, L, normal) * attenuation * intensity;
|
||||
result.Specular = CalcSpecular(lightColor, viewVec, L, normal) * attenuation * intensity;
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
void main()
|
||||
{
|
||||
vec4 texel = texture2D(texture0, Input.TextureCoordinate);
|
||||
vec4 position = V * M * vec4(Input.Position, 1.0);
|
||||
vec4 normal = V * vec4(Input.Normal, 0.0);
|
||||
vec4 viewVec = normalize(-position);
|
||||
|
||||
vec2 tilePos;
|
||||
tilePos.x = int(gl_FragCoord.x/16);
|
||||
tilePos.y = int(gl_FragCoord.y/16);
|
||||
|
||||
LightResult totalLighting;
|
||||
totalLighting.Diffuse = scene_ambient;
|
||||
int currentTile = int(floor(gl_FragCoord.x/TILE_SIZE) + (floor(gl_FragCoord.y/TILE_SIZE) * 80));
|
||||
|
||||
int start = int(LightGrids.Data[currentTile].Start);
|
||||
int amount = int(LightGrids.Data[currentTile].Amount);
|
||||
//for(int i = 0; i < 3; i++)
|
||||
for(int i = start; i < start + amount; i++)
|
||||
{
|
||||
int l = int(LightIndex[i]);
|
||||
|
||||
LightResult result = CalcPointLight(V * PointLights.List[l].Position, PointLights.List[l].Radius, PointLights.List[l].Color, PointLights.List[l].Intensity, viewVec, position, normal);
|
||||
|
||||
totalLighting.Diffuse += result.Diffuse;
|
||||
totalLighting.Specular += result.Specular;
|
||||
}
|
||||
|
||||
fragmentColor += Input.DiffuseColor * (totalLighting.Diffuse + totalLighting.Specular) * texel * Color;
|
||||
//fragmentColor += vec4(0.0, LightGrids.Data[currentTile].Amount/3.0, 0, 1);
|
||||
//fragmentColor = texel * Input.DiffuseColor * Color;
|
||||
if(int(gl_FragCoord.x)%16 == 0 || int(gl_FragCoord.y)%16 == 0 )
|
||||
{
|
||||
//fragmentColor += vec4(0.5, 0, 0, 0);
|
||||
} else {
|
||||
//fragmentColor += vec4(LightGrids.Data[int(tilePos.x + tilePos.y*80)].Amount/3.0, 0, 0, 1);
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
#version 430
|
||||
|
||||
uniform mat4 M;
|
||||
uniform mat4 V;
|
||||
uniform mat4 P;
|
||||
|
||||
layout(location = 0) in vec3 Position;
|
||||
layout(location = 1) in vec3 Normal;
|
||||
layout(location = 2) in vec3 Tangent;
|
||||
layout(location = 3) in vec3 BiTangent;
|
||||
layout(location = 4) in vec2 TextureCoords;
|
||||
layout(location = 5) in vec4 DiffuseVertexColor;
|
||||
layout(location = 6) in vec4 SpecularVertexColor;
|
||||
layout(location = 7) in vec4 BoneIndices1;
|
||||
layout(location = 8) in vec4 BoneIndices2;
|
||||
layout(location = 9) in vec4 BoneWeights1;
|
||||
layout(location = 10) in vec4 BoneWeights2;
|
||||
|
||||
out VertexData{
|
||||
vec3 Position;
|
||||
vec3 Normal;
|
||||
vec2 TextureCoordinate;
|
||||
vec4 DiffuseColor;
|
||||
}Output;
|
||||
|
||||
void main()
|
||||
{
|
||||
gl_Position = P*V*M * vec4(Position, 1.0);
|
||||
|
||||
Output.Position = Position;
|
||||
Output.TextureCoordinate = TextureCoords;
|
||||
Output.Normal = Normal;
|
||||
Output.DiffuseColor = DiffuseVertexColor;
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
#version 430
|
||||
|
||||
#define TILE_SIZE 16
|
||||
#define NUM_TILES 3600
|
||||
|
||||
uniform mat4 P;
|
||||
uniform vec2 ScreenDimensions;
|
||||
|
||||
struct Plane {
|
||||
vec3 Normal;
|
||||
float d;
|
||||
};
|
||||
struct Frustum {
|
||||
Plane Planes[4];
|
||||
};
|
||||
|
||||
layout (std430, binding = 0) buffer FrustumBuffer
|
||||
{
|
||||
Frustum Data[];
|
||||
} Frustums;
|
||||
|
||||
vec4 ConvertToView(vec4 ScreenCoords)
|
||||
{
|
||||
vec2 normalizedScreenCoords = ScreenCoords.xy / ScreenDimensions;
|
||||
vec4 clipSpace = vec4( vec2(normalizedScreenCoords.x, normalizedScreenCoords.y) * 2.0 - 1.0, ScreenCoords.z, ScreenCoords.w);
|
||||
vec4 view = inverse(P) * clipSpace;
|
||||
view = view / view.w;
|
||||
return view;
|
||||
}
|
||||
|
||||
Plane ComputePlane( vec3 p0, vec3 p1, vec3 p2 )
|
||||
{
|
||||
Plane plane;
|
||||
|
||||
vec3 v0 = p1 - p0;
|
||||
vec3 v2 = p2 - p0;
|
||||
|
||||
plane.Normal = normalize( cross( v0, v2 ) );
|
||||
plane.d = dot( vec3(plane.Normal), p0 ); // Always 0 probably
|
||||
return plane;
|
||||
}
|
||||
|
||||
layout (local_size_x = 16, local_size_y = 16, local_size_z = 1) in;
|
||||
void main ()
|
||||
{
|
||||
//Top-Left = 0 | Top-Right = 1
|
||||
//Bottom-Left = 2 | Bottom-Right = 3
|
||||
vec4 ScreenCoords[4];
|
||||
ScreenCoords[0] = vec4(gl_GlobalInvocationID.x * TILE_SIZE, (gl_GlobalInvocationID.y + 1) * TILE_SIZE, -1.0, 1.0);
|
||||
ScreenCoords[1] = vec4((gl_GlobalInvocationID.x + 1) * TILE_SIZE, (gl_GlobalInvocationID.y + 1) * TILE_SIZE, -1.0, 1.0);
|
||||
ScreenCoords[2] = vec4(gl_GlobalInvocationID.x * TILE_SIZE, (gl_GlobalInvocationID.y) * TILE_SIZE, -1.0, 1.0);
|
||||
ScreenCoords[3] = vec4((gl_GlobalInvocationID.x + 1) * TILE_SIZE, (gl_GlobalInvocationID.y) * TILE_SIZE, -1.0, 1.0);
|
||||
|
||||
|
||||
|
||||
vec3 ViewVectors[4];
|
||||
for(int i = 0; i < 4; i++) {
|
||||
ViewVectors[i] = vec3(ConvertToView(ScreenCoords[i]));
|
||||
}
|
||||
|
||||
vec3 EyePos = vec3(0.0, 0.0 ,0.0);
|
||||
|
||||
Frustum f;
|
||||
f.Planes[0] = ComputePlane(EyePos, ViewVectors[2], ViewVectors[0]); // left plane
|
||||
f.Planes[1] = ComputePlane(EyePos, ViewVectors[1], ViewVectors[3]); // right plane
|
||||
f.Planes[2] = ComputePlane(EyePos, ViewVectors[0], ViewVectors[1]); // top plane
|
||||
f.Planes[3] = ComputePlane(EyePos, ViewVectors[3], ViewVectors[2]); // bottom plane
|
||||
|
||||
|
||||
|
||||
|
||||
if ( gl_GlobalInvocationID.x < ScreenDimensions.x / TILE_SIZE && gl_GlobalInvocationID.y < ScreenDimensions.y / TILE_SIZE ) { // inside the screen
|
||||
Frustums.Data[gl_GlobalInvocationID.x + gl_GlobalInvocationID.y*80] = f;
|
||||
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ out vec4 TextureFragment;
|
||||
|
||||
void main()
|
||||
{
|
||||
TextureFragment = vec4(PickingColor/255, 0, 1);
|
||||
TextureFragment = vec4(PickingColor, 0, 1);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
#version 430
|
||||
|
||||
//in uvec3 gl_NumWorkGroups; //contains the number of workgroups that have been dispatched to a compute shader
|
||||
//in uvec3 gl_WorkGroupID; //contains the index of the workgroup currently being operated on by a compute shader
|
||||
//in uvec3 gl_LocalInvocationID; //contains the index of work item currently being operated on by a compute shader
|
||||
//in uvec3 gl_GlobalInvocationID; //contains the global index of work item currently being operated on by a compute shader
|
||||
//in uint gl_LocalInvocationIndex; //contains the local linear index of work item currently being operated on by a compute shader
|
||||
|
||||
|
||||
|
||||
#define MAX_LIGHTS_PER_TILE 1024
|
||||
#define NUM_TILES 3600
|
||||
#define TILE_SIZE 16
|
||||
|
||||
uniform mat4 V;
|
||||
|
||||
struct Plane {
|
||||
vec3 Normal;
|
||||
float d;
|
||||
};
|
||||
struct Frustum {
|
||||
Plane Planes[4];
|
||||
};
|
||||
|
||||
layout (std430, binding = 0) buffer FrustumBuffer
|
||||
{
|
||||
Frustum Data[];
|
||||
} Frustums;
|
||||
|
||||
struct PointLight {
|
||||
vec4 Position;
|
||||
vec4 Color;
|
||||
float Radius;
|
||||
float Intensity;
|
||||
float Falloff;
|
||||
float Padding;
|
||||
};
|
||||
|
||||
layout (std430, binding = 1) buffer LightBuffer
|
||||
{
|
||||
PointLight List[];
|
||||
} PointLights;
|
||||
|
||||
struct LightGrid {
|
||||
float Start;
|
||||
float Amount;
|
||||
vec2 Padding;
|
||||
};
|
||||
|
||||
layout (std430, binding = 2) buffer LightGridBuffer
|
||||
{
|
||||
LightGrid Data[];
|
||||
} LightGrids;
|
||||
|
||||
layout (std430, binding = 3) buffer LightOffsetBuffer
|
||||
{
|
||||
int LightOffset[];
|
||||
};
|
||||
|
||||
layout (std430, binding = 4) buffer LightIndexBuffer
|
||||
{
|
||||
float LightIndex[];
|
||||
};
|
||||
|
||||
shared int GroupLightCount;
|
||||
shared int GroupLightIndexStartOffset;
|
||||
shared int GroupLightIndex[MAX_LIGHTS_PER_TILE];
|
||||
shared Frustum GroupFrustum;
|
||||
int GroupIndex;
|
||||
|
||||
bool SphereInsidePlane(vec3 center, float radius, Plane plane)
|
||||
{
|
||||
return dot(plane.Normal, center) - plane.d > -radius;
|
||||
}
|
||||
|
||||
bool SphereInsideFrustrum(vec3 center, float radius, Frustum frustum/*, float zNear, float zFar*/)
|
||||
{
|
||||
|
||||
//Check depth here
|
||||
//if ( sphere.c.z - sphere.r > zNear || sphere.c.z + sphere.r < zFar )
|
||||
//{
|
||||
// result = false;
|
||||
//}
|
||||
|
||||
for (int i =0; i < 4; i++)
|
||||
{
|
||||
if(! SphereInsidePlane(center, radius, frustum.Planes[i]))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void AppendLight(int li)
|
||||
{
|
||||
int index;
|
||||
index = atomicAdd(GroupLightCount, 1);
|
||||
if( index < MAX_LIGHTS_PER_TILE )
|
||||
{
|
||||
GroupLightIndex[index] = int(li);
|
||||
}
|
||||
}
|
||||
|
||||
layout (local_size_x = 16, local_size_y = 16, local_size_z = 1) in;
|
||||
void main ()
|
||||
{
|
||||
GroupIndex = int(gl_WorkGroupID.x + (gl_WorkGroupID.y * 80));
|
||||
if(gl_LocalInvocationIndex == 0)
|
||||
{
|
||||
GroupLightCount = 0;
|
||||
GroupFrustum = Frustums.Data[GroupIndex];
|
||||
}
|
||||
|
||||
barrier();
|
||||
memoryBarrierShared();
|
||||
|
||||
for(int i = int(gl_LocalInvocationIndex); i < PointLights.List.length(); i += TILE_SIZE*TILE_SIZE)
|
||||
{
|
||||
PointLight light = PointLights.List[i];
|
||||
|
||||
//if pointlight
|
||||
//Pos i view antagligen
|
||||
if(SphereInsideFrustrum( vec3(V * light.Position), light.Radius, GroupFrustum))
|
||||
{
|
||||
//TODO: Fix transparent and opaque list, and depth test.
|
||||
AppendLight( i );
|
||||
}
|
||||
|
||||
|
||||
//if conelight
|
||||
|
||||
//if directional
|
||||
|
||||
}
|
||||
|
||||
barrier();
|
||||
memoryBarrierShared();
|
||||
|
||||
if(gl_LocalInvocationIndex == 0)
|
||||
{
|
||||
GroupLightIndexStartOffset = atomicAdd(LightOffset[0], GroupLightCount);
|
||||
LightGrids.Data[GroupIndex].Start = GroupLightIndexStartOffset;
|
||||
LightGrids.Data[GroupIndex].Amount = GroupLightCount;
|
||||
}
|
||||
|
||||
barrier();
|
||||
|
||||
|
||||
for (uint i = gl_LocalInvocationIndex; i < GroupLightCount; i += TILE_SIZE * TILE_SIZE )
|
||||
{
|
||||
LightIndex[GroupLightIndexStartOffset + i] = GroupLightIndex[i];
|
||||
}
|
||||
}
|
||||
@@ -1,481 +0,0 @@
|
||||
#include "Core/EntityXMLFile.h"
|
||||
#include "Core/World.h"
|
||||
|
||||
unsigned int EntityXMLFile::InstanceCount = 0;
|
||||
|
||||
EntityXMLFile::EntityXMLFile(std::string path)
|
||||
: m_EntityFile(path)
|
||||
{
|
||||
using namespace xercesc;
|
||||
|
||||
if (InstanceCount == 0) {
|
||||
XMLPlatformUtils::Initialize();
|
||||
}
|
||||
InstanceCount++;
|
||||
|
||||
m_GrammarPool = new XMLGrammarPoolImpl();
|
||||
m_ErrorHandler = new EntityParserXMLErrorHandler();
|
||||
m_DOMParser = new XercesDOMParser(nullptr, XMLPlatformUtils::fgMemoryManager, m_GrammarPool);
|
||||
m_DOMParser->setErrorHandler(m_ErrorHandler);
|
||||
m_DOMParser->setDoNamespaces(true);
|
||||
m_DOMParser->setDoXInclude(true);
|
||||
m_DOMParser->setDoSchema(true);
|
||||
m_DOMParser->setValidationSchemaFullChecking(true);
|
||||
m_DOMParser->setValidationScheme(xercesc::XercesDOMParser::Val_Auto);
|
||||
m_DOMParser->setValidationSchemaFullChecking(true);
|
||||
m_DOMParser->setValidationConstraintFatal(false);
|
||||
m_DOMParser->setIncludeIgnorableWhitespace(false);
|
||||
// Make sure schema grammar is kept after validation
|
||||
m_DOMParser->cacheGrammarFromParse(true);
|
||||
|
||||
// HACK: Use Sax2 parser instead so the entire DOM doesn't have to reside in memory
|
||||
m_DOMParser->parse(m_EntityFile.c_str());
|
||||
m_DOMDocument = m_DOMParser->getDocument();
|
||||
|
||||
// 1. Fill in ComponentInfo name, fields, default values and metadata from PSVI
|
||||
parseComponentInfo();
|
||||
// 2. Parse default value files for those components
|
||||
parseDefaults();
|
||||
// 3. Allocate component structures
|
||||
predictComponentAllocation();
|
||||
}
|
||||
|
||||
EntityXMLFile::~EntityXMLFile()
|
||||
{
|
||||
using namespace xercesc;
|
||||
|
||||
if (m_DOMParser != nullptr) {
|
||||
delete m_DOMParser;
|
||||
}
|
||||
if (m_ErrorHandler != nullptr) {
|
||||
delete m_ErrorHandler;
|
||||
}
|
||||
if (m_GrammarPool != nullptr) {
|
||||
delete m_GrammarPool;
|
||||
}
|
||||
|
||||
InstanceCount--;
|
||||
if (InstanceCount == 0) {
|
||||
XMLPlatformUtils::Terminate();
|
||||
}
|
||||
}
|
||||
|
||||
void EntityXMLFile::PopulateWorld(World* world)
|
||||
{
|
||||
for (auto& pair : m_ComponentInfo) {
|
||||
world->RegisterComponent(pair.second);
|
||||
}
|
||||
|
||||
// 4. Parse entity hierarchy
|
||||
auto root = m_DOMDocument->getDocumentElement();
|
||||
parseEntityGraph(world, root, 0);
|
||||
}
|
||||
|
||||
|
||||
void EntityXMLFile::preprocess(std::string inPath, std::string outPath)
|
||||
{
|
||||
using namespace xercesc;
|
||||
|
||||
static const XMLCh gLS[] = { 'L', 'S', '\0' };
|
||||
DOMImplementationLS* di = static_cast<DOMImplementationLS*>(DOMImplementationRegistry::getDOMImplementation(gLS));
|
||||
|
||||
// Parse the file
|
||||
DOMLSParser* parser = di->createLSParser(DOMImplementationLS::MODE_SYNCHRONOUS, nullptr);
|
||||
DOMConfiguration* config = parser->getDomConfig();
|
||||
config->setParameter(XMLUni::fgDOMNamespaces, true);
|
||||
config->setParameter(XMLUni::fgXercesSchema, true);
|
||||
config->setParameter(XMLUni::fgXercesHandleMultipleImports, true);
|
||||
config->setParameter(XMLUni::fgXercesSchemaFullChecking, true);
|
||||
config->setParameter(XMLUni::fgXercesDoXInclude, true);
|
||||
auto errHandler = new EntityPreprocessorXMLErrorHandler();
|
||||
config->setParameter(XMLUni::fgDOMErrorHandler, errHandler);
|
||||
|
||||
auto source = new LocalFileInputSource(XSTR(inPath.c_str()));
|
||||
Wrapper4InputSource* domSourceWrapper = new Wrapper4InputSource(source);
|
||||
DOMDocument* doc = parser->parse(dynamic_cast<DOMLSInput*>(domSourceWrapper));
|
||||
|
||||
// Serialize and output the new XML
|
||||
DOMLSSerializer* writer = di->createLSSerializer();
|
||||
DOMLSOutput* output = di->createLSOutput();
|
||||
XMLFormatTarget* formatTarget = new LocalFileFormatTarget(outPath.c_str());
|
||||
// TODO: MemBufFormatTarget* formatTarget = new MemBufFormatTarget()
|
||||
output->setByteStream(formatTarget);
|
||||
writer->write(doc, output);
|
||||
|
||||
delete formatTarget;
|
||||
output->release();
|
||||
writer->release();
|
||||
parser->release();
|
||||
}
|
||||
|
||||
void EntityXMLFile::parseComponentInfo()
|
||||
{
|
||||
using namespace xercesc;
|
||||
bool wasChanged;
|
||||
XSModel* xsModel = m_GrammarPool->getXSModel(wasChanged);
|
||||
|
||||
// Find component xsd element declarations
|
||||
std::cout << "Enumerating components..." << std::endl;
|
||||
// <xs:element name="ComponentName">
|
||||
auto topLevelElements = xsModel->getComponents(XSConstants::ELEMENT_DECLARATION);
|
||||
for (unsigned int i = 0; i < topLevelElements->getLength(); ++i) {
|
||||
auto element = static_cast<XSElementDeclaration*>(topLevelElements->item(i));
|
||||
|
||||
std::string nameSpace(XSTR(element->getNamespace()));
|
||||
if (nameSpace != "components") {
|
||||
continue;
|
||||
}
|
||||
|
||||
ComponentInfo compInfo;
|
||||
|
||||
// Name
|
||||
compInfo.Name = XSTR(element->getName());
|
||||
// Annotation
|
||||
auto componentAnnotation = element->getAnnotation();
|
||||
if (componentAnnotation != nullptr) {
|
||||
// Parse annotation XML
|
||||
char* annotationString = XMLString::transcode(componentAnnotation->getAnnotationString());
|
||||
MemBufInputSource annotationInput(reinterpret_cast<const XMLByte*>(annotationString), strlen(annotationString), "MemBuf: Annotation String");
|
||||
XercesDOMParser parser(nullptr, XMLPlatformUtils::fgMemoryManager, m_GrammarPool);
|
||||
parser.setErrorHandler(m_ErrorHandler);
|
||||
parser.parse(annotationInput);
|
||||
XMLString::release(&annotationString);
|
||||
auto doc = parser.getDocument();
|
||||
|
||||
// Add allocation estimation(s)
|
||||
auto allocationTags = doc->getElementsByTagName(XSTR("meta:allocation"));
|
||||
for (int i = 0; i < allocationTags->getLength(); ++i) {
|
||||
auto allocation = dynamic_cast<DOMElement*>(allocationTags->item(i));
|
||||
auto child = allocation->getFirstChild();
|
||||
if (child == nullptr) {
|
||||
continue;
|
||||
}
|
||||
|
||||
XSValue::Status status;
|
||||
XSValue* val = XSValue::getActualValue(child->getNodeValue(), XSValue::dt_integer, status);
|
||||
compInfo.Meta.Allocation += val->fData.fValue.f_int;
|
||||
}
|
||||
|
||||
// Save documentation string
|
||||
auto documentationTags = doc->getElementsByTagName(XSTR("xs:documentation"));
|
||||
if (documentationTags->getLength() != 0) {
|
||||
auto child = documentationTags->item(0)->getFirstChild();
|
||||
if (child != nullptr) {
|
||||
compInfo.Meta.Annotation = XSTR(child->getNodeValue());
|
||||
}
|
||||
}
|
||||
// TODO: Parse annotation string XML
|
||||
// compInfo.Meta.Allocation = ...
|
||||
} else {
|
||||
std::cout << "Warning: Component is missing an annotation!" << std::endl;
|
||||
}
|
||||
|
||||
// <xs:complexType>
|
||||
auto typeDefinition = element->getTypeDefinition();
|
||||
if (typeDefinition->getTypeCategory() != XSTypeDefinition::COMPLEX_TYPE) {
|
||||
std::cerr << "Error: Type definition wasn't COMPLEX_TYPE! Skipping." << std::endl;
|
||||
continue;
|
||||
}
|
||||
auto complexTypeDefinition = dynamic_cast<XSComplexTypeDefinition*>(typeDefinition);
|
||||
|
||||
// <xs:all>
|
||||
auto modelGroupParticle = complexTypeDefinition->getParticle();
|
||||
if (modelGroupParticle->getTermType() != XSParticle::TERM_MODELGROUP) {
|
||||
std::cerr << "Error: Model group particle wasn't TERM_MODELGROUP! Skipping." << std::endl;
|
||||
continue;
|
||||
}
|
||||
auto modelGroup = modelGroupParticle->getModelGroupTerm();
|
||||
|
||||
// <xs:element...
|
||||
// <xs:attribute...
|
||||
unsigned int fieldOffset = 0;
|
||||
auto particles = modelGroup->getParticles();
|
||||
for (unsigned int i = 0; i < particles->size(); ++i) {
|
||||
auto particle = particles->elementAt(i);
|
||||
if (particle->getTermType() != XSParticle::TERM_ELEMENT) {
|
||||
std::cerr << "Error: Particle wasn't TERM_ELEMENT! Skipping." << std::endl;
|
||||
continue;
|
||||
}
|
||||
auto elementDeclaration = particle->getElementTerm();
|
||||
|
||||
std::string name = XSTR(elementDeclaration->getName());
|
||||
std::string type = XSTR(elementDeclaration->getTypeDefinition()->getName());
|
||||
|
||||
size_t stride = getTypeStride(type);
|
||||
if (stride == 0) {
|
||||
std::cout << "Warning: Field \"" << name << "\" in component \"" << compInfo.Name << "\" uses unexpected field type \"" << type << "\". Skipping." << std::endl;
|
||||
continue;
|
||||
}
|
||||
|
||||
compInfo.FieldTypes[name] = type;
|
||||
compInfo.FieldOffsets[name] = fieldOffset;
|
||||
fieldOffset += getTypeStride(type);
|
||||
}
|
||||
|
||||
compInfo.Meta.Stride = fieldOffset;
|
||||
m_ComponentInfo[compInfo.Name] = compInfo;
|
||||
}
|
||||
}
|
||||
|
||||
void EntityXMLFile::parseDefaults()
|
||||
{
|
||||
using namespace xercesc;
|
||||
|
||||
for (auto& ci : m_ComponentInfo) {
|
||||
// Allocate memory for default values
|
||||
ci.second.Defaults = std::shared_ptr<char>(new char[ci.second.Meta.Stride]);
|
||||
memset(ci.second.Defaults.get(), 0, ci.second.Meta.Stride);
|
||||
|
||||
XercesDOMParser parser(nullptr, XMLPlatformUtils::fgMemoryManager);
|
||||
parser.setErrorHandler(m_ErrorHandler);
|
||||
|
||||
std::string componentName = ci.first;
|
||||
LOG_DEBUG("Parsing defaults for component %s", componentName.c_str());
|
||||
boost::filesystem::path defaultsFile = "Schema/Components/" + componentName + ".xml";
|
||||
|
||||
parser.parse(defaultsFile.string().c_str());
|
||||
auto doc = parser.getDocument();
|
||||
if (doc == nullptr) {
|
||||
LOG_ERROR("%s not found! Skipping.", defaultsFile.string().c_str());
|
||||
continue;
|
||||
}
|
||||
|
||||
// Find the node in the components namespace matching the component name
|
||||
std::string tagName = "c:" + componentName;
|
||||
auto rootNodes = doc->getElementsByTagName(XSTR(tagName.c_str()));
|
||||
if (rootNodes->getLength() == 0) {
|
||||
LOG_ERROR("Couldn't find defaults for component \"%s\"! Skipping.", componentName.c_str());
|
||||
continue;
|
||||
}
|
||||
auto componentElement = dynamic_cast<DOMElement*>(rootNodes->item(0));
|
||||
|
||||
// Fill the default value buffer with values
|
||||
for (auto& field : ci.second.FieldOffsets) {
|
||||
std::string fieldName = field.first;
|
||||
auto fieldNodes = componentElement->getElementsByTagName(XSTR(fieldName.c_str()));
|
||||
auto fieldNode = fieldNodes->item(0);
|
||||
if (fieldNode == nullptr) {
|
||||
LOG_ERROR("Defaults for component \"%s\" is missing field \"%s\"!", componentName.c_str(), fieldName.c_str());
|
||||
continue;
|
||||
}
|
||||
auto fieldElement = dynamic_cast<DOMElement*>(fieldNode);
|
||||
|
||||
std::string fieldType = ci.second.FieldTypes.at(fieldName);
|
||||
unsigned int fieldOffset = ci.second.FieldOffsets.at(fieldName);
|
||||
writeData(fieldElement, fieldType, ci.second.Defaults.get() + fieldOffset);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void EntityXMLFile::predictComponentAllocation()
|
||||
{
|
||||
using namespace xercesc;
|
||||
|
||||
auto root = m_DOMDocument->getDocumentElement();
|
||||
|
||||
// Count static instances of components present in entity hierarchy
|
||||
auto components = m_DOMDocument->getElementsByTagNameNS(XSTR("components"), XSTR("*"));
|
||||
for (int i = 0; i < components->getLength(); ++i) {
|
||||
auto component = dynamic_cast<DOMElement*>(components->item(i));
|
||||
|
||||
std::string componentName = XSTR(component->getLocalName());
|
||||
auto& compInfo = m_ComponentInfo.at(componentName);
|
||||
compInfo.Meta.Allocation += 1;
|
||||
}
|
||||
|
||||
std::cout << "COMPONENT INFO" << std::endl;
|
||||
for (auto& pair : m_ComponentInfo) {
|
||||
ComponentInfo& ci = pair.second;
|
||||
std::cout << "Component: " << ci.Name << " (" << ci.Meta.Annotation << ")" << std::endl;
|
||||
std::cout << " Allocation: " << ci.Meta.Allocation << std::endl;
|
||||
std::cout << " Fields:" << std::endl;
|
||||
|
||||
// Calculate component size
|
||||
std::size_t stride = 0;
|
||||
// Add size of fields
|
||||
for (auto& field : ci.FieldTypes) {
|
||||
std::cout << " " << field.second << " " << field.first << " (" << getTypeStride(field.second) << " byte)" << std::endl;
|
||||
stride += getTypeStride(field.second);
|
||||
}
|
||||
std::cout << " Stride: " << ci.Meta.Stride << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
void EntityXMLFile::parseEntityGraph(World* world, xercesc::DOMElement* element, EntityID parentEntity)
|
||||
{
|
||||
using namespace xercesc;
|
||||
|
||||
// Create entity
|
||||
EntityID entity = world->CreateEntity(parentEntity);
|
||||
LOG_DEBUG("Created entity %i, parent %i", entity, parentEntity);
|
||||
|
||||
// Add components
|
||||
auto components = m_DOMDocument->evaluate(XSTR("Components/*"), element, nullptr, DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE, nullptr);
|
||||
for (int i = 0; i < components->getSnapshotLength(); i++) {
|
||||
components->snapshotItem(i);
|
||||
auto componentElement = dynamic_cast<DOMElement*>(components->getNodeValue());
|
||||
std::string componentName = XSTR(componentElement->getLocalName());
|
||||
auto& ci = m_ComponentInfo.at(componentName);
|
||||
|
||||
// Attach the component
|
||||
auto c = world->AttachComponent(entity, componentName);
|
||||
LOG_DEBUG("Attached %s component", componentName.c_str());
|
||||
|
||||
// Write field data
|
||||
auto fields = componentElement->getChildNodes();
|
||||
for (int j = 0; j < fields->getLength(); ++j) {
|
||||
auto fieldNode = fields->item(j);
|
||||
auto nodeType = fieldNode->getNodeType();
|
||||
if (nodeType != DOMNode::ELEMENT_NODE) {
|
||||
continue;
|
||||
}
|
||||
auto field = dynamic_cast<DOMElement*>(fields->item(j));
|
||||
//const XMLCh* value = fields->item(j)->getTextContent();
|
||||
std::string fieldName(XSTR(field->getLocalName()));
|
||||
if (ci.FieldTypes.find(fieldName) == ci.FieldTypes.end()) {
|
||||
std::cout << "Warning: Component \"" << componentName << "\" contains invalid field \"" << fieldName << "\". Skipping." << std::endl;
|
||||
continue;
|
||||
}
|
||||
|
||||
std::string fieldType = ci.FieldTypes.at(fieldName);
|
||||
unsigned int fieldOffset = ci.FieldOffsets.at(fieldName);
|
||||
std::string fieldValue(XSTR(field->getTextContent()));
|
||||
LOG_DEBUG(" %s %s = %s", fieldType.c_str(), fieldName.c_str(), fieldValue.c_str());
|
||||
writeData(field, fieldType, c.Data + fieldOffset);
|
||||
}
|
||||
}
|
||||
|
||||
// Recurse children
|
||||
auto children = m_DOMDocument->evaluate(XSTR("Children/Entity"), element, nullptr, DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE, nullptr);
|
||||
for (int i = 0; i < children->getSnapshotLength(); i++) {
|
||||
children->snapshotItem(i);
|
||||
parseEntityGraph(world, dynamic_cast<DOMElement*>(children->getNodeValue()), entity);
|
||||
}
|
||||
|
||||
//auto components = m_DOMDocument->getElementsByTagNameNS(XSTR("components"), XSTR("*"));
|
||||
//for (int i = 0; i < components->getLength(); ++i) {
|
||||
// auto component = dynamic_cast<DOMElement*>(components->item(i));
|
||||
|
||||
// std::string componentName = XSTR(component->getLocalName());
|
||||
// auto& compStore = m_ComponentStore.at(componentName);
|
||||
// auto& compInfo = compStore.Info;
|
||||
|
||||
// char* data = &compStore.Data[compStore.Size*compStore.Stride];
|
||||
// compStore.Size += 1;
|
||||
|
||||
// auto fields = component->getChildNodes();
|
||||
// for (int j = 0; j < fields->getLength(); ++j) {
|
||||
// auto field = fields->item(j);
|
||||
// auto nodeType = field->getNodeType();
|
||||
// if (nodeType != DOMNode::ELEMENT_NODE) {
|
||||
// continue;
|
||||
// }
|
||||
// //auto field = dynamic_cast<DOMElement*>(fields->item(j));
|
||||
// //const XMLCh* value = fields->item(j)->getTextContent();
|
||||
// std::string fieldName = XSTR(field->getLocalName());
|
||||
// if (compInfo.FieldTypes.find(fieldName) == compInfo.FieldTypes.end()) {
|
||||
// std::cout << "Warning: Component \"" << componentName << "\" contains invalid field \"" << fieldName << "\". Skipping." << std::endl;
|
||||
// continue;
|
||||
// }
|
||||
|
||||
// std::string fieldType = compInfo.FieldTypes.at(fieldName);
|
||||
// unsigned int fieldOffset = compInfo.FieldOffsets.at(fieldName);
|
||||
|
||||
// XSValue::DataType dataType = XSValue::getDataType(XSTR(fieldType.c_str()));
|
||||
// if (dataType == XSValue::DataType::dt_MAXCOUNT) {
|
||||
// // TODO:
|
||||
// continue;
|
||||
// }
|
||||
// if (dataType == XSValue::DataType::dt_string) {
|
||||
// char* str = XMLString::transcode(field->getTextContent());
|
||||
// std::string standardString(str);
|
||||
// XMLString::release(&str);
|
||||
// memcpy(&data[fieldOffset], reinterpret_cast<char*>(&standardString), getTypeStride(fieldType));
|
||||
// } else {
|
||||
// XSValue::Status status;
|
||||
// XSValue* val = XSValue::getActualValue(field->getTextContent(), dataType, status);
|
||||
// memcpy(&data[fieldOffset], reinterpret_cast<char*>(&val->fData.fValue), getTypeStride(fieldType));
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
|
||||
//auto entities = m_DOMDocument->getElementsByTagName(XSTR("Entity"));
|
||||
//for (int i = 0; i < entities->getLength(); ++i) {
|
||||
// auto entity = dynamic_cast<DOMElement*>(entities->item(i));
|
||||
|
||||
|
||||
// //entity->setIdAttribute()
|
||||
|
||||
// std::cout << "ENTITY " << i + 1 << std::endl;
|
||||
//}
|
||||
}
|
||||
|
||||
std::size_t EntityXMLFile::getTypeStride(std::string typeName)
|
||||
{
|
||||
std::map<std::string, size_t> typeStrides{
|
||||
{ "bool", sizeof(bool) },
|
||||
{ "int", sizeof(int) },
|
||||
{ "double", sizeof(double) },
|
||||
{ "string", sizeof(std::string) },
|
||||
{ "Vector", sizeof(glm::vec3) },
|
||||
{ "Quaternion", sizeof(glm::quat) },
|
||||
{ "Color", sizeof(glm::vec4) }
|
||||
};
|
||||
|
||||
auto it = typeStrides.find(typeName);
|
||||
return (it != typeStrides.end()) ? it->second : 0;
|
||||
}
|
||||
|
||||
float EntityXMLFile::getFloatAttribute(const xercesc::DOMElement* element, const char* attribute) const
|
||||
{
|
||||
using namespace xercesc;
|
||||
XSValue::Status status;
|
||||
XSValue* val = XSValue::getActualValue(element->getAttribute(XSTR(attribute)), xercesc::XSValue::DataType::dt_float, status);
|
||||
if (val == nullptr) {
|
||||
LOG_ERROR("Element \"%s\" doesn't have an \"%s\" attribute!", XSTR(element->getTagName()), attribute);
|
||||
return 0.f;
|
||||
} else {
|
||||
return val->fData.fValue.f_float;
|
||||
}
|
||||
}
|
||||
|
||||
void EntityXMLFile::writeData(const xercesc::DOMElement* element, std::string typeName, char* outData)
|
||||
{
|
||||
using namespace xercesc;
|
||||
|
||||
XSValue::DataType dataType = XSValue::getDataType(XSTR(typeName.c_str()));
|
||||
if (dataType == XSValue::DataType::dt_MAXCOUNT) {
|
||||
if (typeName == "Vector") {
|
||||
glm::vec3 vec;
|
||||
vec.x = getFloatAttribute(element, "X");
|
||||
vec.y = getFloatAttribute(element, "Y");
|
||||
vec.z = getFloatAttribute(element, "Z");
|
||||
memcpy(outData, reinterpret_cast<char*>(&vec), getTypeStride(typeName));
|
||||
} else if (typeName == "Color") {
|
||||
glm::vec4 vec;
|
||||
vec.r = getFloatAttribute(element, "R");
|
||||
vec.g = getFloatAttribute(element, "G");
|
||||
vec.b = getFloatAttribute(element, "B");
|
||||
vec.a = getFloatAttribute(element, "A");
|
||||
memcpy(outData, reinterpret_cast<char*>(&vec), getTypeStride(typeName));
|
||||
} else if (typeName == "Quaternion") {
|
||||
glm::quat q;
|
||||
q.x = getFloatAttribute(element, "X");
|
||||
q.y = getFloatAttribute(element, "Y");
|
||||
q.z = getFloatAttribute(element, "Z");
|
||||
q.w = getFloatAttribute(element, "W");
|
||||
memcpy(outData, reinterpret_cast<char*>(&q), getTypeStride(typeName));
|
||||
}
|
||||
} else if (dataType == XSValue::DataType::dt_string) {
|
||||
char* str = XMLString::transcode(element->getTextContent());
|
||||
std::string standardString(str);
|
||||
new (outData) std::string(str);
|
||||
XMLString::release(&str);
|
||||
//memcpy(outData, reinterpret_cast<char*>(&standardString), getTypeStride(typeName));
|
||||
} else {
|
||||
XSValue::Status status;
|
||||
XSValue* val = XSValue::getActualValue(element->getTextContent(), dataType, status);
|
||||
memcpy(outData, reinterpret_cast<char*>(&val->fData.fValue), getTypeStride(typeName));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,20 +35,6 @@ void ResourceManager::Reload(std::string resourceName)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void ResourceManager::Release(std::string resourceType, std::string resourceName)
|
||||
{
|
||||
auto key = std::make_pair(resourceType, resourceName);
|
||||
if (m_ResourceCache.find(key) == m_ResourceCache.end()) {
|
||||
return;
|
||||
}
|
||||
auto resource = m_ResourceCache.at(key);
|
||||
m_ResourceCache.erase(key);
|
||||
m_ResourceFromName.erase(resourceName);
|
||||
m_ResourceParents.erase(resource);
|
||||
delete resource;
|
||||
}
|
||||
|
||||
unsigned int ResourceManager::GetNewResourceID(unsigned int typeID)
|
||||
{
|
||||
return m_ResourceCount[typeID]++;
|
||||
|
||||
@@ -41,16 +41,9 @@ ComponentWrapper World::GetComponent(EntityID entity, std::string componentType)
|
||||
return pool->GetByEntity(entity);
|
||||
}
|
||||
|
||||
const ComponentPool* World::GetComponents(std::string componentType)
|
||||
const ComponentPool& World::GetComponents(std::string componentType)
|
||||
{
|
||||
auto it = m_ComponentPools.find(componentType);
|
||||
return (it != m_ComponentPools.end()) ? it->second : nullptr;
|
||||
}
|
||||
|
||||
|
||||
EntityID World::GetParent(EntityID entity)
|
||||
{
|
||||
return m_EntityParents.at(entity);
|
||||
return *m_ComponentPools.at(componentType);
|
||||
}
|
||||
|
||||
EntityID World::generateEntityID()
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
#include "Rendering/DrawScenePass.h"
|
||||
|
||||
DrawScenePass::DrawScenePass(IRenderer* renderer)
|
||||
{
|
||||
m_Renderer = renderer;
|
||||
InitializeTextures();
|
||||
InitializeShaderPrograms();
|
||||
}
|
||||
|
||||
void DrawScenePass::InitializeTextures()
|
||||
{
|
||||
m_WhiteTexture = ResourceManager::Load<Texture>("Textures/Core/Blank.png");
|
||||
}
|
||||
|
||||
void DrawScenePass::InitializeShaderPrograms()
|
||||
{
|
||||
//Gör så att shaders är en resource, tex som texture classen. Konstruktorn måste vara privat.
|
||||
m_BasicForwardProgram = ResourceManager::Load<ShaderProgram>("#BasicForwardProgram");
|
||||
|
||||
m_BasicForwardProgram->AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/BasicForward.vert.glsl")));
|
||||
m_BasicForwardProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/BasicForward.frag.glsl")));
|
||||
m_BasicForwardProgram->Compile();
|
||||
m_BasicForwardProgram->Link();
|
||||
|
||||
|
||||
}
|
||||
|
||||
void DrawScenePass::Draw(RenderQueueCollection& rq)
|
||||
{
|
||||
//glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||
GLERROR("DrawScenePass::Draw: Pre");
|
||||
|
||||
DrawScenePassState state;
|
||||
m_BasicForwardProgram->Bind();
|
||||
|
||||
|
||||
//TODO: Render: Add code for more jobs than modeljobs.
|
||||
for (auto &job : rq.Forward) {
|
||||
auto modelJob = std::dynamic_pointer_cast<ModelJob>(job);
|
||||
if (modelJob) {
|
||||
GLuint ShaderHandle = m_BasicForwardProgram->GetHandle();
|
||||
|
||||
//TODO: Kolla upp "header/include/common" shader saken så man slipper skicka in asmycket uniforms
|
||||
glUniformMatrix4fv(glGetUniformLocation(ShaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->ModelMatrix));
|
||||
glUniformMatrix4fv(glGetUniformLocation(ShaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(m_Renderer->Camera()->ViewMatrix()));
|
||||
glUniformMatrix4fv(glGetUniformLocation(ShaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(m_Renderer->Camera()->ProjectionMatrix()));
|
||||
glUniform4fv(glGetUniformLocation(ShaderHandle, "Color"), 1, glm::value_ptr(modelJob->Color));
|
||||
|
||||
//TODO: Renderer: bättre textur felhantering samt fler texturer stöd
|
||||
if (modelJob->DiffuseTexture != nullptr) {
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, modelJob->DiffuseTexture->m_Texture);
|
||||
} else {
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture);
|
||||
}
|
||||
|
||||
glBindVertexArray(modelJob->Model->VAO);
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer);
|
||||
glDrawElementsBaseVertex(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, 0, modelJob->StartIndex);
|
||||
|
||||
continue;
|
||||
}
|
||||
}
|
||||
GLERROR("DrawScenePass::Draw: End");
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
#include "Rendering/DrawScenePassState.h"
|
||||
|
||||
|
||||
DrawScenePassState::DrawScenePassState()
|
||||
{
|
||||
GLERROR("---");
|
||||
BindBuffer(0);
|
||||
GLERROR("---");
|
||||
Enable(GL_DEPTH_TEST);
|
||||
Enable(GL_CULL_FACE);
|
||||
ClearColor(glm::vec4(255.f / 255, 163.f / 255, 176.f / 255, 0.f));
|
||||
Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
|
||||
}
|
||||
|
||||
DrawScenePassState::~DrawScenePassState()
|
||||
{
|
||||
|
||||
}
|
||||
@@ -48,21 +48,13 @@ void FrameBuffer::Generate()
|
||||
switch ((*it)->m_ResourceType) {
|
||||
case GL_TEXTURE_2D:
|
||||
glFramebufferTexture2D(GL_FRAMEBUFFER, (*it)->m_Attachment, (*it)->m_ResourceType, *(*it)->m_ResourceHandle, 0);
|
||||
GLERROR("FrameBuffer generate: glFramebufferTexture2D");
|
||||
|
||||
break;
|
||||
case GL_RENDERBUFFER:
|
||||
glFramebufferRenderbuffer(GL_FRAMEBUFFER, (*it)->m_Attachment, (*it)->m_ResourceType, *(*it)->m_ResourceHandle);
|
||||
GLERROR("FrameBuffer generate: glFramebufferRenderbuffer");
|
||||
if ( (*it)->m_Attachment != GL_COLOR_ATTACHMENT0 ||
|
||||
(*it)->m_Attachment != GL_DEPTH_ATTACHMENT ||
|
||||
(*it)->m_Attachment != GL_STENCIL_ATTACHMENT)
|
||||
{
|
||||
LOG_ERROR("RenderBuffer Attachment not valid.");
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
GLERROR("FrameBuffer generate");
|
||||
|
||||
if ((*it)->m_Attachment != GL_DEPTH_ATTACHMENT) {
|
||||
attachments.push_back((*it)->m_Attachment);
|
||||
|
||||
@@ -1,118 +0,0 @@
|
||||
#include "Rendering/PickingPass.h"
|
||||
|
||||
PickingPass::PickingPass(IRenderer* renderer, EventBroker* eb)
|
||||
{
|
||||
m_Renderer = renderer;
|
||||
m_EventBroker = eb;
|
||||
|
||||
InitializeTextures();
|
||||
InitializeFrameBuffers();
|
||||
InitializeShaderPrograms();
|
||||
}
|
||||
|
||||
PickingPass::~PickingPass()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void PickingPass::InitializeTextures()
|
||||
{
|
||||
GenerateTexture(&m_PickingTexture, GL_CLAMP_TO_BORDER, GL_LINEAR,
|
||||
glm::vec2(m_Renderer->Resolution().Width, m_Renderer->Resolution().Height), GL_RG8, GL_RG, GL_UNSIGNED_BYTE);
|
||||
}
|
||||
|
||||
void PickingPass::InitializeFrameBuffers()
|
||||
{
|
||||
glGenRenderbuffers(1, &m_DepthBuffer);
|
||||
glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer);
|
||||
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Renderer->Resolution().Width, m_Renderer->Resolution().Height);
|
||||
|
||||
m_PickingBuffer.AddResource(std::shared_ptr<BufferResource>(new RenderBuffer(&m_DepthBuffer, GL_DEPTH_ATTACHMENT)));
|
||||
m_PickingBuffer.AddResource(std::shared_ptr<BufferResource>(new Texture2D(&m_PickingTexture, GL_COLOR_ATTACHMENT0)));
|
||||
m_PickingBuffer.Generate();
|
||||
}
|
||||
|
||||
void PickingPass::InitializeShaderPrograms()
|
||||
{
|
||||
m_PickingProgram = ResourceManager::Load<ShaderProgram>("#PickingProgram");
|
||||
|
||||
m_PickingProgram->AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/Picking.vert.glsl")));
|
||||
m_PickingProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/Picking.frag.glsl")));
|
||||
m_PickingProgram->Compile();
|
||||
m_PickingProgram->BindFragDataLocation(0, "TextureFragment");
|
||||
m_PickingProgram->Link();
|
||||
}
|
||||
|
||||
void PickingPass::Draw(RenderQueueCollection& rq)
|
||||
{
|
||||
m_PickingColorsToEntity.clear();
|
||||
PickingPassState* state = new PickingPassState(m_PickingBuffer.GetHandle());
|
||||
|
||||
int r = 1;
|
||||
int g = 0;
|
||||
//TODO: Render: Add code for more jobs than modeljobs.
|
||||
|
||||
GLuint ShaderHandle = m_PickingProgram->GetHandle();
|
||||
m_PickingProgram->Bind();
|
||||
|
||||
for (auto &job : rq.Forward) {
|
||||
auto modelJob = std::dynamic_pointer_cast<ModelJob>(job);
|
||||
|
||||
if (modelJob) {
|
||||
//---------------
|
||||
//TODO: Renderer: IMPORTANT: Fixa detta så det inte loopar igenom listan varje frame.
|
||||
//---------------
|
||||
int pickColor[2] = { r, g };
|
||||
for (auto i : m_PickingColorsToEntity) {
|
||||
if (modelJob->Entity == i.second) {
|
||||
pickColor[0] = i.first.x;
|
||||
pickColor[1] = i.first.y;
|
||||
r -= 1;
|
||||
}
|
||||
}
|
||||
m_PickingColorsToEntity[glm::vec2(pickColor[0], pickColor[1])] = modelJob->Entity;
|
||||
|
||||
//Render picking stuff
|
||||
//TODO: Kolla upp "header/include/common" shader saken så man slipper skicka in asmycket uniforms
|
||||
glUniformMatrix4fv(glGetUniformLocation(ShaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->ModelMatrix));
|
||||
glUniformMatrix4fv(glGetUniformLocation(ShaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(m_Renderer->Camera()->ViewMatrix()));
|
||||
glUniformMatrix4fv(glGetUniformLocation(ShaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(m_Renderer->Camera()->ProjectionMatrix()));
|
||||
glUniform2fv(glGetUniformLocation(ShaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1])));
|
||||
|
||||
glBindVertexArray(modelJob->Model->VAO);
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer);
|
||||
glDrawElementsBaseVertex(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, nullptr, modelJob->StartIndex);
|
||||
r += 1;
|
||||
if (r > 255) {
|
||||
r = 0;
|
||||
g += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
m_PickingBuffer.Unbind();
|
||||
GLERROR("PickingPass Error");
|
||||
|
||||
//Publish pick event every frame with the pick data that can be picked by the event
|
||||
Events::Picking pickEvent = Events::Picking(
|
||||
&m_PickingBuffer,
|
||||
&m_DepthBuffer,
|
||||
m_Renderer->Camera()->ProjectionMatrix(),
|
||||
m_Renderer->Camera()->ViewMatrix(),
|
||||
m_Renderer->Resolution(),
|
||||
&m_PickingColorsToEntity);
|
||||
|
||||
m_EventBroker->Publish(pickEvent);
|
||||
}
|
||||
|
||||
void PickingPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const
|
||||
{
|
||||
//TODO: Renderer: Make this in a sparate class
|
||||
glGenTextures(1, texture);
|
||||
glBindTexture(GL_TEXTURE_2D, *texture);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering);
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, dimensions.x, dimensions.y, 0, format, type, nullptr);//TODO: Renderer: Fix the precision and Resolution
|
||||
GLERROR("Texture initialization failed");
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
#include "Rendering/PickingPassState.h"
|
||||
|
||||
|
||||
PickingPassState::PickingPassState(GLuint frameBuffer)
|
||||
{
|
||||
GLERROR("---2");
|
||||
BindBuffer(frameBuffer);
|
||||
GLERROR("---3");
|
||||
Enable(GL_DEPTH_TEST);
|
||||
Enable(GL_CULL_FACE);
|
||||
|
||||
glm::vec4 clearColor = glm::vec4(0.f);
|
||||
ClearColor(clearColor);
|
||||
Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
|
||||
}
|
||||
|
||||
PickingPassState::~PickingPassState()
|
||||
{
|
||||
|
||||
}
|
||||
@@ -34,10 +34,10 @@ RawModel::RawModel(std::string fileName)
|
||||
numIndices += face.mNumIndices;
|
||||
}
|
||||
}
|
||||
//LOG_DEBUG("Vertex count %i", numVertices);
|
||||
//LOG_DEBUG("Index count %i", numIndices);
|
||||
LOG_DEBUG("Vertex count %i", numVertices);
|
||||
LOG_DEBUG("Index count %i", numIndices);
|
||||
|
||||
//LOG_DEBUG("Model has %i embedded textures", scene->mNumTextures);
|
||||
LOG_DEBUG("Model has %i embedded textures", scene->mNumTextures);
|
||||
|
||||
std::vector<std::tuple<std::string, glm::mat4>> boneInfo;
|
||||
std::map<std::string, int> boneNameMapping;
|
||||
@@ -132,35 +132,35 @@ RawModel::RawModel(std::string fileName)
|
||||
matGroup.EndIndex = m_Indices.size() - 1;
|
||||
// Material shininess
|
||||
material->Get(AI_MATKEY_SHININESS, matGroup.Shininess);
|
||||
//LOG_DEBUG("Shininess: %f", matGroup.Shininess);
|
||||
LOG_DEBUG("Shininess: %f", matGroup.Shininess);
|
||||
// Diffuse texture
|
||||
//LOG_DEBUG("%i diffuse textures found", material->GetTextureCount(aiTextureType_DIFFUSE));
|
||||
LOG_DEBUG("%i diffuse textures found", material->GetTextureCount(aiTextureType_DIFFUSE));
|
||||
if (material->GetTextureCount(aiTextureType_DIFFUSE)) {
|
||||
aiString path;
|
||||
aiTextureMapping mapping;
|
||||
material->GetTexture(aiTextureType_DIFFUSE, 0, &path, &mapping);
|
||||
std::string absolutePath = (boost::filesystem::path(fileName).branch_path() / path.C_Str()).string();
|
||||
//LOG_DEBUG("Diffuse texture: %s", absolutePath.c_str());
|
||||
LOG_DEBUG("Diffuse texture: %s", absolutePath.c_str());
|
||||
matGroup.Texture = std::shared_ptr<Texture>(ResourceManager::Load<Texture>(absolutePath));
|
||||
}
|
||||
// Normal map
|
||||
//LOG_DEBUG("%i normal maps found", material->GetTextureCount(aiTextureType_HEIGHT));
|
||||
LOG_DEBUG("%i normal maps found", material->GetTextureCount(aiTextureType_HEIGHT));
|
||||
if (material->GetTextureCount(aiTextureType_HEIGHT)) {
|
||||
aiString path;
|
||||
aiTextureMapping mapping;
|
||||
material->GetTexture(aiTextureType_HEIGHT, 0, &path, &mapping);
|
||||
std::string absolutePath = (boost::filesystem::path(fileName).branch_path() / path.C_Str()).string();
|
||||
//LOG_DEBUG("Normal map: %s", absolutePath.c_str());
|
||||
LOG_DEBUG("Normal map: %s", absolutePath.c_str());
|
||||
matGroup.NormalMap = std::shared_ptr<Texture>(ResourceManager::Load<Texture>(absolutePath));
|
||||
}
|
||||
// Specular map
|
||||
//LOG_DEBUG("%i specular maps found", material->GetTextureCount(aiTextureType_SPECULAR));
|
||||
LOG_DEBUG("%i specular maps found", material->GetTextureCount(aiTextureType_SPECULAR));
|
||||
if (material->GetTextureCount(aiTextureType_SPECULAR)) {
|
||||
aiString path;
|
||||
aiTextureMapping mapping;
|
||||
material->GetTexture(aiTextureType_SPECULAR, 0, &path, &mapping);
|
||||
std::string absolutePath = (boost::filesystem::path(fileName).branch_path() / path.C_Str()).string();
|
||||
//LOG_DEBUG("Specular map: %s", absolutePath.c_str());
|
||||
LOG_DEBUG("Specular map: %s", absolutePath.c_str());
|
||||
matGroup.SpecularMap = std::shared_ptr<Texture>(ResourceManager::Load<Texture>(absolutePath));
|
||||
}
|
||||
TextureGroups.push_back(matGroup);
|
||||
@@ -216,20 +216,20 @@ RawModel::RawModel(std::string fileName)
|
||||
m_Skeleton = new Skeleton();
|
||||
CreateSkeleton(boneInfo, boneNameMapping, scene->mRootNode, -1);
|
||||
int numBones = m_Skeleton->Bones.size();
|
||||
//LOG_DEBUG("Bone count: %i", numBones);
|
||||
LOG_DEBUG("Bone count: %i", numBones);
|
||||
if (numBones > 0) {
|
||||
m_Skeleton->PrintSkeleton();
|
||||
}
|
||||
}
|
||||
|
||||
// Animations
|
||||
//LOG_DEBUG("Animation count: %i", scene->mNumAnimations);
|
||||
LOG_DEBUG("Animation count: %i", scene->mNumAnimations);
|
||||
for (int i = 0; i < scene->mNumAnimations; ++i) {
|
||||
auto animation = scene->mAnimations[i];
|
||||
std::string animationName = animation->mName.C_Str();
|
||||
//LOG_DEBUG("Animation: %s", animationName.c_str());
|
||||
//LOG_DEBUG("Duration: %f", animation->mDuration);
|
||||
//LOG_DEBUG("Ticks per second: %f", animation->mTicksPerSecond);
|
||||
LOG_DEBUG("Animation: %s", animationName.c_str());
|
||||
LOG_DEBUG("Duration: %f", animation->mDuration);
|
||||
LOG_DEBUG("Ticks per second: %f", animation->mTicksPerSecond);
|
||||
|
||||
Skeleton::Animation skelAnim;
|
||||
skelAnim.Name = animationName;
|
||||
@@ -303,7 +303,7 @@ void RawModel::CreateSkeleton(std::vector<std::tuple<std::string, glm::mat4>> &b
|
||||
|
||||
// Find the bone by name in the bone info list
|
||||
if (boneNameMapping.find(nodeName) == boneNameMapping.end()) {
|
||||
//LOG_DEBUG("Node \"%s\" was not a bone", nodeName.c_str());
|
||||
LOG_DEBUG("Node \"%s\" was not a bone", nodeName.c_str());
|
||||
} else {
|
||||
glm::mat4 offsetMatrix;
|
||||
int ID = boneNameMapping[nodeName];
|
||||
|
||||
@@ -15,87 +15,49 @@ void RenderQueueFactory::Update(World* world)
|
||||
|
||||
glm::mat4 RenderQueueFactory::ModelMatrix(World* world, EntityID entity)
|
||||
{
|
||||
glm::vec3 position = AbsolutePosition(world, entity);
|
||||
glm::quat orientation = AbsoluteOrientation(world, entity);
|
||||
glm::vec3 scale = AbsoluteScale(world, entity);
|
||||
//should really return absolute model matrix based on parents position, scale and orientation
|
||||
//GetAbsolutePosition(World* world, ComponentWrapper transformComponent)
|
||||
|
||||
glm::mat4 modelMatrix = glm::translate(glm::mat4(), position) * glm::toMat4(orientation) * glm::scale(scale);
|
||||
ComponentWrapper transformComponent = world->GetComponent(entity, "Transform");
|
||||
glm::vec3 position = transformComponent["Position"];
|
||||
glm::vec3 scale = transformComponent["Scale"];
|
||||
glm::quat oritentation = transformComponent["Orientation"];
|
||||
|
||||
glm::mat4 modelMatrix = glm::translate(glm::mat4(), position) * glm::toMat4(oritentation) * glm::scale(scale);
|
||||
return modelMatrix;
|
||||
}
|
||||
|
||||
|
||||
glm::vec3 RenderQueueFactory::AbsolutePosition(World* world, EntityID entity)
|
||||
glm::vec3 GetAbsolutePosition(World* world, ComponentWrapper transformComponent)
|
||||
{
|
||||
glm::vec3 position;
|
||||
|
||||
do {
|
||||
ComponentWrapper transform = world->GetComponent(entity, "Transform");
|
||||
position += (glm::vec3)transform["Position"];
|
||||
entity = world->GetParent(entity);
|
||||
} while (entity != 0);
|
||||
|
||||
return position;
|
||||
}
|
||||
|
||||
glm::quat RenderQueueFactory::AbsoluteOrientation(World* world, EntityID entity)
|
||||
{
|
||||
glm::quat orientation;
|
||||
|
||||
do {
|
||||
ComponentWrapper transform = world->GetComponent(entity, "Transform");
|
||||
orientation = glm::quat((glm::vec3)transform["Orientation"]) * orientation;
|
||||
entity = world->GetParent(entity);
|
||||
} while (entity != 0);
|
||||
|
||||
return orientation;
|
||||
}
|
||||
|
||||
glm::vec3 RenderQueueFactory::AbsoluteScale(World* world, EntityID entity)
|
||||
{
|
||||
ComponentWrapper transform = world->GetComponent(entity, "Transform");
|
||||
glm::vec3 scale = (glm::vec3)transform["Scale"];
|
||||
|
||||
EntityID parent = world->GetParent(entity);
|
||||
if (parent != 0) {
|
||||
return AbsoluteScale(world, parent) * scale;
|
||||
} else {
|
||||
return scale;
|
||||
}
|
||||
// positionComponent.EntityID
|
||||
return glm::vec3();
|
||||
}
|
||||
|
||||
void RenderQueueFactory::FillModels(World* world, RenderQueue* renderQueue)
|
||||
{
|
||||
auto models = world->GetComponents("Model");
|
||||
if (models == nullptr) {
|
||||
return;
|
||||
}
|
||||
for(auto& modelC : world->GetComponents("Model")) {
|
||||
ModelJob job;
|
||||
std::string resource = modelC["Resource"];
|
||||
glm::vec4 color = modelC["Color"];
|
||||
Model* model = ResourceManager::Load<Model>(resource);
|
||||
|
||||
for (auto& modelC : *models) {
|
||||
std::string resource = modelC["Resource"];
|
||||
if (resource.empty()) {
|
||||
continue;
|
||||
}
|
||||
glm::vec4 color = modelC["Color"];
|
||||
Model* model = ResourceManager::Load<Model>(resource);
|
||||
for (auto texGroup : model->TextureGroups) {
|
||||
job.TextureID = (texGroup.Texture) ? texGroup.Texture->ResourceID : 0;
|
||||
job.DiffuseTexture = texGroup.Texture.get();
|
||||
job.NormalTexture = texGroup.NormalMap.get();
|
||||
job.SpecularTexture = texGroup.SpecularMap.get();
|
||||
job.Model = model;
|
||||
job.StartIndex = texGroup.StartIndex;
|
||||
job.EndIndex = texGroup.EndIndex;
|
||||
job.ModelMatrix = model->m_Matrix * ModelMatrix(world, modelC.EntityID);
|
||||
job.Color = color;
|
||||
|
||||
for (auto texGroup : model->TextureGroups) {
|
||||
ModelJob job;
|
||||
job.TextureID = (texGroup.Texture) ? texGroup.Texture->ResourceID : 0;
|
||||
job.DiffuseTexture = texGroup.Texture.get();
|
||||
job.NormalTexture = texGroup.NormalMap.get();
|
||||
job.SpecularTexture = texGroup.SpecularMap.get();
|
||||
job.Model = model;
|
||||
job.StartIndex = texGroup.StartIndex;
|
||||
job.EndIndex = texGroup.EndIndex;
|
||||
job.ModelMatrix = model->m_Matrix * ModelMatrix(world, modelC.EntityID);
|
||||
job.Color = color;
|
||||
//TODO: RENDERER: Not sure if the best solution for pickingColor to entity link is this
|
||||
job.Entity = modelC.EntityID;
|
||||
|
||||
//TODO: RENDERER: Not sure if the best solution for pickingColor to entity link is this
|
||||
job.Entity = modelC.EntityID;
|
||||
|
||||
renderQueue->Add(job);
|
||||
}
|
||||
}
|
||||
renderQueue->Add(job);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void RenderQueueFactory::FillLights(World* world, RenderQueue* renderQueue)
|
||||
|
||||
@@ -1,105 +0,0 @@
|
||||
#include "Rendering/RenderState.h"
|
||||
|
||||
RenderState::RenderState()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
bool RenderState::Enable(GLenum GLEnable)
|
||||
{
|
||||
if(glIsEnabled(GLEnable))
|
||||
{
|
||||
//LOG_WARNING("Trying to enable somthing that is already enabled.");
|
||||
return false;
|
||||
}
|
||||
m_Enables.push_back(GLEnable);
|
||||
glEnable(GLEnable);
|
||||
if (GLERROR("RenderState::Enable"))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RenderState::CullFace(GLenum GLCullFace)
|
||||
{
|
||||
if(!glIsEnabled(GL_CULL_FACE))
|
||||
{
|
||||
//LOG_ERROR("Setting GL_CULL_FACE without enabling it.");
|
||||
Enable(GL_CULL_FACE);
|
||||
}
|
||||
|
||||
glCullFace(GLCullFace);
|
||||
if (GLERROR("RenderState::CullFace"))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RenderState::ClearColor(glm::vec4 color)
|
||||
{
|
||||
glGetFloatv(GL_COLOR_CLEAR_VALUE, &m_preClearColor[0]);
|
||||
glClearColor(color.r, color.g, color.b, color.a);
|
||||
if (GLERROR("RenderState::ClearColor")) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RenderState::Clear(GLbitfield mask)
|
||||
{
|
||||
glClear(mask);
|
||||
if (GLERROR("RenderState::Clear")) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RenderState::BindBuffer(GLint buffer)
|
||||
{
|
||||
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &m_preBuffer);
|
||||
if (buffer == m_preBuffer)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, buffer);
|
||||
if (GLERROR("RenderState::BindBuffer"))
|
||||
{
|
||||
printf("BufferID: %i\npreBufferID: %i\n", buffer, m_preBuffer);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
RenderState::~RenderState()
|
||||
{
|
||||
GLERROR("RenderState::~RenderState Pre");
|
||||
GLint n_buffer = -1;
|
||||
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &n_buffer);
|
||||
|
||||
//Set cullface to default
|
||||
if (glIsEnabled(GL_CULL_FACE)) {
|
||||
glCullFace(GL_BACK);
|
||||
}
|
||||
GLERROR("RenderState::~RenderState glCullFace");
|
||||
|
||||
//Set color to default
|
||||
glClearColor(m_preClearColor[0], m_preClearColor[1], m_preClearColor[2], m_preClearColor[3]);
|
||||
GLERROR("RenderState::~RenderState glClearColor");
|
||||
|
||||
//Disable Enables
|
||||
for (auto i : m_Enables)
|
||||
{
|
||||
glDisable(i);
|
||||
}
|
||||
GLERROR("RenderState::~RenderState glDisable");
|
||||
|
||||
if(m_preBuffer != 0)
|
||||
{
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||
}
|
||||
m_Enables.clear();
|
||||
GLERROR("RenderState::~RenderState glBindFramebuffer");
|
||||
}
|
||||
|
||||
+162
-178
@@ -3,20 +3,19 @@
|
||||
void Renderer::Initialize()
|
||||
{
|
||||
InitializeWindow();
|
||||
|
||||
// Create default camera
|
||||
m_DefaultCamera = new ::Camera((float)m_Resolution.Width / m_Resolution.Height, glm::radians(90.0f), 0.01f, 5000.f);
|
||||
m_DefaultCamera->SetPosition(glm::vec3(0, 1, 10));
|
||||
m_DefaultCamera = new ::Camera((float)m_Resolution.Width / m_Resolution.Height, glm::radians(45.f), 0.01f, 5000.f);
|
||||
m_DefaultCamera->SetPosition(glm::vec3(0, 0, 10));
|
||||
if (m_Camera == nullptr) {
|
||||
m_Camera = m_DefaultCamera;
|
||||
}
|
||||
TEMPCreateLights();
|
||||
InitializeRenderPasses();
|
||||
|
||||
glfwSwapInterval(m_VSYNC);
|
||||
InitializeShaders();
|
||||
InitializeTextures();
|
||||
InitializeSSBOs();
|
||||
CalculateFrustum();
|
||||
InitializeFrameBuffers();
|
||||
|
||||
|
||||
m_ScreenQuad = ResourceManager::Load<Model>("Models/Core/ScreenQuad.obj");
|
||||
m_UnitQuad = ResourceManager::Load<Model>("Models/Core/UnitQuad.obj");
|
||||
@@ -65,29 +64,22 @@ void Renderer::InitializeWindow()
|
||||
|
||||
void Renderer::InitializeShaders()
|
||||
{
|
||||
m_BasicForwardProgram = ResourceManager::Load<ShaderProgram>("#m_BasicForwardProgram");
|
||||
m_BasicForwardProgram.AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/BasicForward.vert.glsl")));
|
||||
m_BasicForwardProgram.AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/BasicForward.frag.glsl")));
|
||||
m_BasicForwardProgram.Compile();
|
||||
m_BasicForwardProgram.Link();
|
||||
|
||||
m_DrawScreenQuadProgram = ResourceManager::Load<ShaderProgram>("#DrawScreenQuadProgram");
|
||||
m_DrawScreenQuadProgram->AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/DrawScreenQuad.vert.glsl")));
|
||||
m_DrawScreenQuadProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/DrawScreenQuad.frag.glsl")));
|
||||
m_DrawScreenQuadProgram->Compile();
|
||||
m_DrawScreenQuadProgram->Link();
|
||||
m_PickingProgram.AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/Picking.vert.glsl")));
|
||||
m_PickingProgram.AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/Picking.frag.glsl")));
|
||||
m_PickingProgram.Compile();
|
||||
m_PickingProgram.BindFragDataLocation(0, "TextureFragment");
|
||||
m_PickingProgram.Link();
|
||||
|
||||
m_CalculateFrustumProgram = ResourceManager::Load<ShaderProgram>("#CalculateFrustumProgram");
|
||||
m_CalculateFrustumProgram->AddShader(std::shared_ptr<Shader>(new ComputeShader("Shaders/GridFrustum.comp.glsl")));
|
||||
m_CalculateFrustumProgram->Compile();
|
||||
m_CalculateFrustumProgram->Link();
|
||||
m_DrawScreenQuadProgram.AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/DrawScreenQuad.vert.glsl")));
|
||||
m_DrawScreenQuadProgram.AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/DrawScreenQuad.frag.glsl")));
|
||||
m_DrawScreenQuadProgram.Compile();
|
||||
m_DrawScreenQuadProgram.Link();
|
||||
|
||||
m_LightCullProgram = ResourceManager::Load<ShaderProgram>("#LightCullProgram");
|
||||
m_LightCullProgram->AddShader(std::shared_ptr<Shader>(new ComputeShader("Shaders/cullLights.comp.glsl")));
|
||||
m_LightCullProgram->Compile();
|
||||
m_LightCullProgram->Link();
|
||||
|
||||
m_ForwardPlusProgram = ResourceManager::Load<ShaderProgram>("#ForwardPlusProgram");
|
||||
m_ForwardPlusProgram->AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/ForwardPlus.vert.glsl")));
|
||||
m_ForwardPlusProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/ForwardPlus.frag.glsl")));
|
||||
m_ForwardPlusProgram->Compile();
|
||||
m_ForwardPlusProgram->Link();
|
||||
}
|
||||
|
||||
void Renderer::InputUpdate(double dt)
|
||||
@@ -121,8 +113,26 @@ void Renderer::InputUpdate(double dt)
|
||||
m_CameraMoveSpeed = 0.5f;
|
||||
}
|
||||
|
||||
|
||||
static double mousePosX, mousePosY;
|
||||
glfwGetCursorPos(m_Window, &mousePosX, &mousePosY);
|
||||
if (glfwGetMouseButton(m_Window, GLFW_MOUSE_BUTTON_1) == GLFW_PRESS) {
|
||||
glm::vec3 data = ScreenCoords::ToPixelData(mousePosX, m_Resolution.Height - mousePosY, &m_PickingBuffer, m_DepthBuffer);
|
||||
glm::vec2 color = glm::vec2(data);
|
||||
float depth = data.z;
|
||||
|
||||
glm::vec3 viewPos = ScreenCoords::ToWorldPos(mousePosX, m_Resolution.Height - mousePosY, depth, m_Resolution, m_Camera->ProjectionMatrix(), m_Camera->ViewMatrix());
|
||||
// glm::vec3 worldPos = glm::vec3(glm::inverse(m_Camera->ViewMatrix()) * glm::vec4(viewPos, 1.f));
|
||||
|
||||
//printf("R: %f, G: %f, Depth: %f\n", color.r, color.g, depth);
|
||||
//printf("view: x: %f, y: %f z: %f, Length: %f\n\n", viewPos.x, viewPos.y, viewPos.z, glm::length(viewPos));
|
||||
|
||||
if (color != glm::vec2(0, 0)) {
|
||||
EntityID pickedEntity = m_PickingColorsToEntity[color];
|
||||
printf("Picked Entity: %i", pickedEntity);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
if (glfwGetKey(m_Window, GLFW_KEY_SPACE) == GLFW_PRESS) {
|
||||
|
||||
@@ -148,176 +158,39 @@ void Renderer::InputUpdate(double dt)
|
||||
|
||||
void Renderer::Update(double dt)
|
||||
{
|
||||
m_EventBroker->Process<Renderer>();
|
||||
InputUpdate(dt);
|
||||
InputUpdate(dt);
|
||||
|
||||
}
|
||||
|
||||
void Renderer::Draw(RenderQueueCollection& rq)
|
||||
{
|
||||
m_PickingPass->Draw(rq);
|
||||
//DrawScreenQuad(m_PickingPass->PickingTexture());
|
||||
CullLights();
|
||||
//TODO: Renderer: Kanske borde vara längst upp i update.
|
||||
PickingPass(rq);
|
||||
DrawScreenQuad(m_PickingTexture);
|
||||
|
||||
//m_DrawScenePass->Draw(rq);
|
||||
DrawForwardPlus(rq);
|
||||
GLERROR("Renderer::Draw m_DrawScenePass->Draw");
|
||||
DrawScene(rq);
|
||||
glfwSwapBuffers(m_Window);
|
||||
}
|
||||
|
||||
void Renderer::DrawScreenQuad(GLuint textureToDraw)
|
||||
void Renderer::DrawScene(RenderQueueCollection& rq)
|
||||
{
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||
|
||||
glDisable(GL_DEPTH_TEST);
|
||||
glDisable(GL_CULL_FACE);
|
||||
|
||||
glClearColor(0.f, 0.f, 0.f, 1.f);
|
||||
glClear(GL_COLOR_BUFFER_BIT);
|
||||
|
||||
|
||||
m_DrawScreenQuadProgram->Bind();
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, textureToDraw);
|
||||
|
||||
glBindVertexArray(m_ScreenQuad->VAO);
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer);
|
||||
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->TextureGroups[0].EndIndex - m_ScreenQuad->TextureGroups[0].StartIndex +1
|
||||
, GL_UNSIGNED_INT, 0, m_ScreenQuad->TextureGroups[0].StartIndex);
|
||||
}
|
||||
|
||||
void Renderer::InitializeTextures()
|
||||
{
|
||||
m_ErrorTexture=ResourceManager::Load<Texture>("Textures/Core/ErrorTexture.png");
|
||||
m_WhiteTexture=ResourceManager::Load<Texture>("Textures/Core/Blank.png");
|
||||
}
|
||||
|
||||
void Renderer::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type)
|
||||
{
|
||||
glGenTextures(1, texture);
|
||||
glBindTexture(GL_TEXTURE_2D, *texture);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering);
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, dimensions.x, dimensions.y, 0, format, type, NULL);//TODO: Renderer: Fix the precision and Resolution
|
||||
GLERROR("Texture initialization failed");
|
||||
}
|
||||
|
||||
void Renderer::InitializeSSBOs()
|
||||
{
|
||||
printf("Size: %i\n", sizeof(m_Frustums));
|
||||
glGenBuffers(1, &m_FrustumSSBO);
|
||||
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_FrustumSSBO);
|
||||
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(m_Frustums), &m_Frustums, GL_DYNAMIC_COPY);
|
||||
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
|
||||
GLERROR("m_FrustumSSBO");
|
||||
|
||||
glGenBuffers(1, &m_LightSSBO);
|
||||
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightSSBO);
|
||||
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(m_PointLights), &m_PointLights, GL_DYNAMIC_COPY);
|
||||
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
|
||||
GLERROR("m_LightSSBO");
|
||||
|
||||
|
||||
|
||||
glGenBuffers(1, &m_LightGridSSBO);
|
||||
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightGridSSBO);
|
||||
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(m_LightGrid), &m_LightGrid, GL_DYNAMIC_COPY);
|
||||
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
|
||||
GLERROR("m_LightGridSSBO");
|
||||
|
||||
|
||||
glGenBuffers(1, &m_LightOffsetSSBO);
|
||||
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightOffsetSSBO);
|
||||
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(m_LightOffset), &m_LightOffset, GL_DYNAMIC_COPY);
|
||||
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
|
||||
GLERROR("m_LightOffsetSSBO");
|
||||
|
||||
|
||||
glGenBuffers(1, &m_LightIndexSSBO);
|
||||
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightIndexSSBO);
|
||||
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(m_LightIndex), &m_LightIndex, GL_DYNAMIC_COPY);
|
||||
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
|
||||
GLERROR("m_LightIndexSSBO");
|
||||
|
||||
}
|
||||
|
||||
void Renderer::InitializeRenderPasses()
|
||||
{
|
||||
m_DrawScenePass = new DrawScenePass(this);
|
||||
m_PickingPass = new PickingPass(this, m_EventBroker);
|
||||
}
|
||||
|
||||
void Renderer::CalculateFrustum()
|
||||
{
|
||||
GLERROR("CalculateFrustum Error: Pre");
|
||||
|
||||
m_CalculateFrustumProgram->Bind();
|
||||
|
||||
|
||||
|
||||
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, m_FrustumSSBO);
|
||||
glUniformMatrix4fv(glGetUniformLocation(m_CalculateFrustumProgram->GetHandle(), "P"), 1, false, glm::value_ptr(m_Camera->ProjectionMatrix()));
|
||||
glUniform2f(glGetUniformLocation(m_CalculateFrustumProgram->GetHandle(), "ScreenDimensions"), m_Resolution.Width, m_Resolution.Height);
|
||||
glDispatchCompute(5, 3, 1);
|
||||
|
||||
GLERROR("CalculateFrustum Error: End");
|
||||
}
|
||||
|
||||
void Renderer::TEMPCreateLights()
|
||||
{
|
||||
for (int i = 0; i < NUM_LIGHTS; i++)
|
||||
{
|
||||
glm::vec3 pos = glm::vec3(cos(i) * i/10.f , 0.5f, sin(i) * i/10.f);
|
||||
m_PointLights[i].Position = glm::vec4(pos, 1.f);
|
||||
m_PointLights[i].Color = glm::vec4(rand()%255 / 255.f, rand()%255 / 255.f, rand()%255 / 255.f, 1.f);
|
||||
m_PointLights[i].Radius = 5.0f;
|
||||
}
|
||||
}
|
||||
|
||||
void Renderer::CullLights()
|
||||
{
|
||||
GLERROR("CullLights Error: Pre");
|
||||
m_LightOffset = 0;
|
||||
|
||||
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightOffsetSSBO);
|
||||
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(m_LightOffset), &m_LightOffset, GL_DYNAMIC_COPY);
|
||||
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
|
||||
|
||||
|
||||
m_LightCullProgram->Bind();
|
||||
glUniformMatrix4fv(glGetUniformLocation(m_LightCullProgram->GetHandle(), "V"), 1, false, glm::value_ptr(m_Camera->ViewMatrix()));
|
||||
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, m_FrustumSSBO);
|
||||
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, m_LightSSBO);
|
||||
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightGridSSBO);
|
||||
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, m_LightOffsetSSBO);
|
||||
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightIndexSSBO);
|
||||
glDispatchCompute(m_Resolution.Width / TILE_SIZE, m_Resolution.Height / TILE_SIZE, 1);
|
||||
|
||||
GLERROR("CullLights Error: End");
|
||||
|
||||
}
|
||||
|
||||
void Renderer::DrawForwardPlus(RenderQueueCollection& rq)
|
||||
{
|
||||
GLERROR("Renderer::DrawForwardPlus: Pre");
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||
|
||||
//TODO: Render: Clean up draw code
|
||||
glEnable(GL_DEPTH_TEST);
|
||||
glEnable(GL_CULL_FACE);
|
||||
glClearColor(200.f / 255, 0.f / 255, 200.f / 255, 0.f);
|
||||
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
|
||||
m_ForwardPlusProgram->Bind();
|
||||
GLuint ShaderHandle = m_ForwardPlusProgram->GetHandle();
|
||||
glCullFace(GL_BACK);
|
||||
|
||||
glClearColor(255.f / 255, 163.f / 255, 176.f / 255, 0.f);
|
||||
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
|
||||
|
||||
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, m_LightSSBO);
|
||||
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightGridSSBO);
|
||||
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightIndexSSBO);
|
||||
//TODO: Render: Add code for more jobs than modeljobs.
|
||||
for (auto &job : rq.Forward) {
|
||||
auto modelJob = std::dynamic_pointer_cast<ModelJob>(job);
|
||||
if (modelJob) {
|
||||
GLuint ShaderHandle = m_BasicForwardProgram.GetHandle();
|
||||
|
||||
m_BasicForwardProgram.Bind();
|
||||
//TODO: Kolla upp "header/include/common" shader saken så man slipper skicka in asmycket uniforms
|
||||
glUniformMatrix4fv(glGetUniformLocation(ShaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->ModelMatrix));
|
||||
glUniformMatrix4fv(glGetUniformLocation(ShaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(m_Camera->ViewMatrix()));
|
||||
@@ -340,6 +213,117 @@ void Renderer::DrawForwardPlus(RenderQueueCollection& rq)
|
||||
continue;
|
||||
}
|
||||
}
|
||||
GLERROR("Renderer::DrawForwardPlus: End");
|
||||
}
|
||||
|
||||
void Renderer::PickingPass(RenderQueueCollection& rq)
|
||||
{
|
||||
m_PickingBuffer.Bind();
|
||||
|
||||
glEnable(GL_DEPTH_TEST);
|
||||
glEnable(GL_CULL_FACE);
|
||||
glCullFace(GL_BACK);
|
||||
|
||||
glClearColor(0.f, 0.f, 0.f, 1.f);
|
||||
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
|
||||
int r = 30;
|
||||
int g = 0;
|
||||
//TODO: Render: Add code for more jobs than modeljobs.
|
||||
|
||||
|
||||
GLuint ShaderHandle = m_PickingProgram.GetHandle();
|
||||
m_PickingProgram.Bind();
|
||||
|
||||
for (auto &job : rq.Forward) {
|
||||
auto modelJob = std::dynamic_pointer_cast<ModelJob>(job);
|
||||
|
||||
if (modelJob) {
|
||||
glm::vec2 pickColor = glm::vec2(r/255.f, g/255.f);
|
||||
m_PickingColorsToEntity[pickColor] = modelJob->Entity;
|
||||
|
||||
|
||||
//Render picking stuff
|
||||
//TODO: Kolla upp "header/include/common" shader saken så man slipper skicka in asmycket uniforms
|
||||
glUniformMatrix4fv(glGetUniformLocation(ShaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->ModelMatrix));
|
||||
glUniformMatrix4fv(glGetUniformLocation(ShaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(m_Camera->ViewMatrix()));
|
||||
glUniformMatrix4fv(glGetUniformLocation(ShaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(m_Camera->ProjectionMatrix()));
|
||||
glUniform2fv(glGetUniformLocation(ShaderHandle, "PickingColor"), 1, glm::value_ptr(pickColor));
|
||||
|
||||
glBindVertexArray(modelJob->Model->VAO);
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer);
|
||||
glDrawElementsBaseVertex(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, 0, modelJob->StartIndex);
|
||||
r+=50;
|
||||
if(r > 255) {
|
||||
r = 0;
|
||||
g+=50;
|
||||
}
|
||||
}
|
||||
}
|
||||
m_PickingBuffer.Unbind();
|
||||
}
|
||||
|
||||
|
||||
void Renderer::DrawScreenQuad(GLuint textureToDraw)
|
||||
{
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||
|
||||
glDisable(GL_DEPTH_TEST);
|
||||
glDisable(GL_CULL_FACE);
|
||||
|
||||
glClearColor(0.f, 0.f, 0.f, 1.f);
|
||||
glClear(GL_COLOR_BUFFER_BIT);
|
||||
|
||||
|
||||
m_DrawScreenQuadProgram.Bind();
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, textureToDraw);
|
||||
|
||||
glBindVertexArray(m_ScreenQuad->VAO);
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer);
|
||||
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->TextureGroups[0].EndIndex - m_ScreenQuad->TextureGroups[0].StartIndex +1
|
||||
, GL_UNSIGNED_INT, 0, m_ScreenQuad->TextureGroups[0].StartIndex);
|
||||
}
|
||||
|
||||
|
||||
void Renderer::InitializeTextures()
|
||||
{
|
||||
m_ErrorTexture=ResourceManager::Load<Texture>("Textures/Core/ErrorTexture.png");
|
||||
m_WhiteTexture=ResourceManager::Load<Texture>("Textures/Core/Blank.png");
|
||||
/*
|
||||
glGenTextures(1, &m_PickingTexture);
|
||||
glBindTexture(GL_TEXTURE_2D, m_PickingTexture);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, m_Resolution.Width, m_Resolution.Height, 0, GL_RG, GL_FLOAT, NULL);//TODO: Renderer: Fix the precision and Resolution
|
||||
GLERROR("m_PickingTexture initialization failed");
|
||||
*/
|
||||
|
||||
GenerateTexture(&m_PickingTexture, GL_CLAMP_TO_BORDER, GL_LINEAR,
|
||||
glm::vec2(m_Resolution.Width, m_Resolution.Height), GL_RG8, GL_RG, GL_FLOAT);
|
||||
}
|
||||
|
||||
void Renderer::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type)
|
||||
{
|
||||
glGenTextures(1, texture);
|
||||
glBindTexture(GL_TEXTURE_2D, *texture);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering);
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, dimensions.x, dimensions.y, 0, format, type, NULL);//TODO: Renderer: Fix the precision and Resolution
|
||||
GLERROR("Texture initialization failed");
|
||||
}
|
||||
|
||||
|
||||
|
||||
void Renderer::InitializeFrameBuffers()//TODO: Renderer: Get this to a better location, as its really big
|
||||
{
|
||||
glGenRenderbuffers(1, &m_DepthBuffer);
|
||||
glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer);
|
||||
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Resolution.Width, m_Resolution.Height);
|
||||
|
||||
m_PickingBuffer.AddResource(std::shared_ptr<BufferResource>(new RenderBuffer(&m_DepthBuffer, GL_DEPTH_ATTACHMENT)));
|
||||
m_PickingBuffer.AddResource(std::shared_ptr<BufferResource>(new Texture2D(&m_PickingTexture, GL_COLOR_ATTACHMENT0)));
|
||||
m_PickingBuffer.Generate();
|
||||
}
|
||||
@@ -29,31 +29,22 @@ glm::vec3 ScreenCoords::ToWorldPos(glm::vec2 screenCoord, float depth, float scr
|
||||
return ToWorldPos(screenCoord.x, screenCoord.y, depth, screenWidth, screenHeight, cameraProjectionMat, cameraViewMat);
|
||||
}
|
||||
|
||||
ScreenCoords::PixelData ScreenCoords::ToPixelData(float x, float y, FrameBuffer* PickDataBuffer, GLuint DepthBuffer)
|
||||
glm::vec3 ScreenCoords::ToPixelData(float x, float y, FrameBuffer* PickDataBuffer, GLuint DepthBuffer)
|
||||
{
|
||||
PickDataBuffer->Bind();
|
||||
unsigned char pdata[2];
|
||||
glReadPixels(x, y, 1, 1, GL_RG, GL_UNSIGNED_BYTE, &pdata);
|
||||
glm::vec2 pixelData;
|
||||
glReadPixels(x, y, 1, 1, GL_RG, GL_FLOAT, &pixelData);
|
||||
PickDataBuffer->Unbind();
|
||||
|
||||
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, DepthBuffer);
|
||||
float depthData;
|
||||
glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depthData);
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||
|
||||
PixelData p;
|
||||
p.Color[0] = (int)pdata[0];
|
||||
p.Color[1] = (int)pdata[1];
|
||||
p.Depth = depthData;
|
||||
|
||||
GLERROR("ScreenCoords::ToPixelData Error");
|
||||
|
||||
return p;
|
||||
return glm::vec3(pixelData, depthData);
|
||||
}
|
||||
|
||||
ScreenCoords::PixelData ScreenCoords::ToPixelData(glm::vec2 screenCoord, FrameBuffer* PickDataBuffer, GLuint DepthBuffer)
|
||||
glm::vec3 ScreenCoords::ToPixelData(glm::vec2 screenCoord, FrameBuffer* PickDataBuffer, GLuint DepthBuffer)
|
||||
{
|
||||
return ToPixelData(screenCoord.x, screenCoord.y, PickDataBuffer, DepthBuffer);
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,6 @@ file(GLOB SOURCE_FILES
|
||||
set(SOURCE_FILES
|
||||
${SOURCE_FILES}
|
||||
"Game.cpp"
|
||||
"PlayerSystem.cpp"
|
||||
)
|
||||
|
||||
set(LIBRARIES
|
||||
|
||||
+43
-88
@@ -1,114 +1,69 @@
|
||||
#include "Game.h"
|
||||
#include "HardcodedTestWorld.h"
|
||||
|
||||
Game::Game(int argc, char* argv[])
|
||||
{
|
||||
ResourceManager::RegisterType<ConfigFile>("ConfigFile");
|
||||
ResourceManager::RegisterType<Model>("Model");
|
||||
ResourceManager::RegisterType<Texture>("Texture");
|
||||
ResourceManager::RegisterType<EntityXMLFile>("EntityXMLFile");
|
||||
ResourceManager::RegisterType<ShaderProgram>("ShaderProgram");
|
||||
ResourceManager::RegisterType<ConfigFile>("ConfigFile");
|
||||
ResourceManager::RegisterType<Model>("Model");
|
||||
ResourceManager::RegisterType<Texture>("Texture");
|
||||
|
||||
m_Config = ResourceManager::Load<ConfigFile>("Config.ini");
|
||||
LOG_LEVEL = static_cast<_LOG_LEVEL>(m_Config->Get<int>("Debug.LogLevel", 1));
|
||||
m_Config = ResourceManager::Load<ConfigFile>("Config.ini");
|
||||
LOG_LEVEL = static_cast<_LOG_LEVEL>(m_Config->Get<int>("Debug.LogLevel", 1));
|
||||
|
||||
// Create the core event broker
|
||||
m_EventBroker = new EventBroker();
|
||||
// Create the core event broker
|
||||
m_EventBroker = new EventBroker();
|
||||
|
||||
m_RenderQueueFactory = new RenderQueueFactory();
|
||||
|
||||
// Create the renderer
|
||||
m_Renderer = new Renderer(m_EventBroker);
|
||||
m_Renderer->SetFullscreen(m_Config->Get<bool>("Video.Fullscreen", false));
|
||||
m_Renderer->SetVSYNC(m_Config->Get<bool>("Video.VSYNC", false));
|
||||
m_Renderer->SetResolution(Rectangle(
|
||||
0,
|
||||
0,
|
||||
m_Config->Get<int>("Video.Width", 1280),
|
||||
m_Config->Get<int>("Video.Height", 720)
|
||||
));
|
||||
m_Renderer->Initialize();
|
||||
m_Renderer->Camera()->SetFOV(glm::radians(m_Config->Get<float>("Video.FOV", 90.f)));
|
||||
// Create the renderer
|
||||
m_Renderer = new Renderer();
|
||||
m_Renderer->SetFullscreen(m_Config->Get<bool>("Video.Fullscreen", false));
|
||||
m_Renderer->SetVSYNC(m_Config->Get<bool>("Video.VSYNC", false));
|
||||
m_Renderer->SetResolution(Rectangle(
|
||||
0,
|
||||
0,
|
||||
m_Config->Get<int>("Video.Width", 1280),
|
||||
m_Config->Get<int>("Video.Height", 720)
|
||||
));
|
||||
m_Renderer->Initialize();
|
||||
|
||||
// Create input manager
|
||||
m_InputManager = new InputManager(m_Renderer->Window(), m_EventBroker);
|
||||
// Create input manager
|
||||
m_InputManager = new InputManager(m_Renderer->Window(), m_EventBroker);
|
||||
|
||||
// Create the root level GUI frame
|
||||
m_FrameStack = new GUI::Frame(m_EventBroker);
|
||||
m_FrameStack->Width = m_Renderer->Resolution().Width;
|
||||
m_FrameStack->Height = m_Renderer->Resolution().Height;
|
||||
// Create the root level GUI frame
|
||||
m_FrameStack = new GUI::Frame(m_EventBroker);
|
||||
m_FrameStack->Width = m_Renderer->Resolution().Width;
|
||||
m_FrameStack->Height = m_Renderer->Resolution().Height;
|
||||
|
||||
// Create a world
|
||||
m_World = new World();
|
||||
std::string mapToLoad = m_Config->Get<std::string>("Debug.LoadMap", "");
|
||||
if (!mapToLoad.empty()) {
|
||||
ResourceManager::Load<EntityXMLFile>(mapToLoad)->PopulateWorld(m_World);
|
||||
}
|
||||
// Create a TEST WORLD
|
||||
m_World = new HardcodedTestWorld();
|
||||
|
||||
// Create system pipeline
|
||||
m_SystemPipeline = new SystemPipeline(m_EventBroker);
|
||||
m_SystemPipeline->AddSystem<RaptorCopterSystem>();
|
||||
m_SystemPipeline->AddSystem<PlayerSystem>();
|
||||
|
||||
|
||||
|
||||
m_LastTime = glfwGetTime();
|
||||
|
||||
testIntialize();
|
||||
m_LastTime = glfwGetTime();
|
||||
}
|
||||
|
||||
Game::~Game()
|
||||
{
|
||||
delete m_FrameStack;
|
||||
delete m_EventBroker;
|
||||
delete m_FrameStack;
|
||||
delete m_EventBroker;
|
||||
}
|
||||
|
||||
void Game::Tick()
|
||||
{
|
||||
double currentTime = glfwGetTime();
|
||||
double dt = currentTime - m_LastTime;
|
||||
m_LastTime = currentTime;
|
||||
double currentTime = glfwGetTime();
|
||||
double dt = currentTime - m_LastTime;
|
||||
m_LastTime = currentTime;
|
||||
|
||||
m_EventBroker->Swap();
|
||||
m_InputManager->Update(dt);
|
||||
m_EventBroker->Swap();
|
||||
|
||||
// Iterate through systems and update world!
|
||||
m_SystemPipeline->Update(m_World, dt);
|
||||
testTick(dt);
|
||||
m_Renderer->Update(dt);
|
||||
m_EventBroker->Swap();
|
||||
m_InputManager->Update(dt);
|
||||
m_Renderer->Update(dt);
|
||||
m_EventBroker->Swap();
|
||||
|
||||
m_RenderQueueFactory->Update(m_World);
|
||||
GLERROR("Game::Tick m_RenderQueueFactory->Update");
|
||||
m_Renderer->Draw(m_RenderQueueFactory->RenderQueues());
|
||||
GLERROR("Game::Tick m_Renderer->Draw");
|
||||
m_EventBroker->Swap();
|
||||
m_EventBroker->Clear();
|
||||
|
||||
glfwPollEvents();
|
||||
}
|
||||
|
||||
|
||||
bool Game::testOnKeyUp(const Events::KeyUp& e)
|
||||
{
|
||||
if (e.KeyCode == GLFW_KEY_R) {
|
||||
std::string mapToLoad = m_Config->Get<std::string>("Debug.LoadMap", "");
|
||||
if (!mapToLoad.empty()) {
|
||||
delete m_World;
|
||||
m_World = new World();
|
||||
ResourceManager::Release("EntityXMLFile", mapToLoad);
|
||||
ResourceManager::Load<EntityXMLFile>(mapToLoad)->PopulateWorld(m_World);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void Game::testIntialize()
|
||||
{
|
||||
EVENT_SUBSCRIBE_MEMBER(m_EKeyUp, &Game::testOnKeyUp);
|
||||
}
|
||||
|
||||
void Game::testTick(double dt)
|
||||
{
|
||||
m_EventBroker->Process<Game>();
|
||||
m_Renderer->Draw(m_RenderQueueFactory->RenderQueues());
|
||||
|
||||
m_EventBroker->Swap();
|
||||
m_EventBroker->Clear();
|
||||
|
||||
glfwPollEvents();
|
||||
}
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
#include "PlayerSystem.h"
|
||||
|
||||
|
||||
void PlayerSystem::Update(World * world, ComponentWrapper & player, double dt)
|
||||
{
|
||||
if (input.Forward) {
|
||||
m_Direction.z = -1;
|
||||
} else if (input.Back) {
|
||||
m_Direction.z = 1;
|
||||
} else {
|
||||
m_Direction.z = 0;
|
||||
}
|
||||
if (input.Left) {
|
||||
m_Direction.x = -1;
|
||||
} else if (input.Right) {
|
||||
m_Direction.x = 1;
|
||||
} else {
|
||||
m_Direction.x = 0;
|
||||
}
|
||||
m_EventBroker->Process<PlayerSystem>();
|
||||
ComponentWrapper& transform = world->GetComponent(player.EntityID, "Transform");
|
||||
(glm::vec3&)player["Velocity"] = m_Speed * float(dt) * m_Direction;
|
||||
(glm::vec3&)transform["Position"] += (glm::vec3)player["Velocity"];
|
||||
}
|
||||
|
||||
bool PlayerSystem::OnKeyDown(const Events::KeyDown & event)
|
||||
{
|
||||
if (event.KeyCode == GLFW_KEY_W) {
|
||||
input.Forward = true;
|
||||
}
|
||||
if (event.KeyCode == GLFW_KEY_A) {
|
||||
input.Left = true;
|
||||
}
|
||||
if (event.KeyCode == GLFW_KEY_S) {
|
||||
input.Back = true;
|
||||
}
|
||||
if (event.KeyCode == GLFW_KEY_D) {
|
||||
input.Right = true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool PlayerSystem::OnKeyUp(const Events::KeyUp & event)
|
||||
{
|
||||
if (event.KeyCode == GLFW_KEY_W) {
|
||||
input.Forward = false;
|
||||
}
|
||||
if (event.KeyCode == GLFW_KEY_A) {
|
||||
input.Left = false;
|
||||
}
|
||||
if (event.KeyCode == GLFW_KEY_S) {
|
||||
input.Back = false;
|
||||
}
|
||||
if (event.KeyCode == GLFW_KEY_D) {
|
||||
input.Right = false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
/*
|
||||
* Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
* DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
*/
|
||||
|
||||
(function () {
|
||||
"use strict";
|
||||
var start = 0;
|
||||
var zmq = require('zmq');
|
||||
var publisher = zmq.socket('pub');
|
||||
|
||||
publisher.bind('tcp://*:5555', function (err) {
|
||||
if (err) {
|
||||
console.log(err);
|
||||
}
|
||||
else {
|
||||
console.log("5555");
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
|
||||
process.on('SIGINT', function () {
|
||||
publisher.close();
|
||||
});
|
||||
|
||||
|
||||
var PLUGIN_ID = require("./package.json").name,
|
||||
MENU_ID = "TeamFisk plugins",
|
||||
MENU_LABEL = "$$$/JavaScripts/Generator/TeamFisk plugins/Menu=Live Texturing RAMDisk";
|
||||
|
||||
var _generator = null;
|
||||
|
||||
// Initialize script here
|
||||
function init(generator, config) {
|
||||
_generator = generator;
|
||||
_generator.addMenuItem(MENU_ID, MENU_LABEL, true, false)
|
||||
.then(
|
||||
function () {
|
||||
console.log("Menu created", MENU_ID);
|
||||
}, function () {
|
||||
console.error("Menu creation failed", MENU_ID);
|
||||
}
|
||||
);
|
||||
|
||||
_generator.onPhotoshopEvent("imageChanged", handleImageChanged);
|
||||
}
|
||||
|
||||
var lastSent = 0;
|
||||
var isSaving = false;
|
||||
function handleImageChanged(document) {
|
||||
|
||||
var start = new Date().getTime();
|
||||
if (start - lastSent > 100 && !isSaving) {
|
||||
isSaving = true;
|
||||
//console.log("DOC: " + document.id);
|
||||
_generator.getDocumentInfo(document.id).then(
|
||||
function (document) {
|
||||
// console.log(new Date().getTime() / 1000);
|
||||
// console.log(stringify(document.timeStamp));
|
||||
//console.log("HELLO 1");
|
||||
//lastSent = document.timeStamp
|
||||
// console.log(stringify(document));
|
||||
//console.log("Received complete document:", stringify(document));
|
||||
//var str = 'var options = new PNGSaveOptions(); app.activeDocument.saveAs (new File("D:/HejHej.png"),options, false);';
|
||||
var str = 'app.activeDocument.save()';
|
||||
|
||||
_generator.evaluateJSXString(str).then(function () {
|
||||
isSaving = false;
|
||||
//console.log("Save succes");
|
||||
var size = (4 + document.file.length + 1);
|
||||
var message = new Buffer(size);
|
||||
|
||||
var offset = 0;
|
||||
|
||||
//console.log("document.file.length: " + document.file.length);
|
||||
//console.log("document.fileName: " + document.file);
|
||||
|
||||
message.writeInt32LE(document.file.length + 1, offset);
|
||||
|
||||
offset += 4;
|
||||
|
||||
var fileName = document.file.replace(/\\/g, "/");
|
||||
message.write(fileName, offset, fileName.length, 'utf8');
|
||||
offset += fileName.length;
|
||||
message.writeUInt8(0, offset); //Null byte
|
||||
offset += 1;
|
||||
|
||||
publisher.send(message);
|
||||
|
||||
var asd = new Date().getTime();
|
||||
var time = asd - start;
|
||||
//console.log(time);
|
||||
lastSent = new Date().getTime();
|
||||
//console.log("LastSent: " + lastSent);
|
||||
|
||||
},
|
||||
function () {
|
||||
console.log("Save Failure");
|
||||
isSaving = false;
|
||||
}).done();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function stringify(object) {
|
||||
try {
|
||||
return JSON.stringify(object, null, " ");
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
return String(object);
|
||||
}
|
||||
|
||||
//Declare entery function in the script
|
||||
exports.init = init;
|
||||
}());
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.js]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
|
||||
[*.cc]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
*.swp
|
||||
*.swo
|
||||
*.o
|
||||
build
|
||||
*.lock*
|
||||
binding.node
|
||||
examples/stress-test-client
|
||||
node_modules
|
||||
Makefile.gyp
|
||||
binding.Makefile
|
||||
binding.target.gyp.mk
|
||||
gyp-mac-tool
|
||||
out/
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
addons:
|
||||
apt:
|
||||
sources:
|
||||
- ubuntu-toolchain-r-test
|
||||
packages:
|
||||
- g++-4.8
|
||||
env:
|
||||
- ZMQ="git://github.com/zeromq/zeromq2-x.git"
|
||||
- ZMQ="git://github.com/zeromq/zeromq3-x.git -b v3.1.0"
|
||||
- ZMQ="git://github.com/zeromq/zeromq3-x.git -b v3.2.5"
|
||||
- ZMQ="git://github.com/zeromq/zeromq4-x.git -b v4.0.5" SODIUM="git://github.com/jedisct1/libsodium.git -b 0.4.5"
|
||||
before_install:
|
||||
- export CXX=g++-4.8
|
||||
- sudo apt-get install uuid-dev
|
||||
- '[ -z "$SODIUM" ] || git clone --depth 1 $SODIUM libsodium'
|
||||
- '[ -z "$SODIUM" ] || cd libsodium'
|
||||
- '[ -z "$SODIUM" ] || ./autogen.sh'
|
||||
- '[ -z "$SODIUM" ] || ./configure'
|
||||
- '[ -z "$SODIUM" ] || make'
|
||||
- '[ -z "$SODIUM" ] || sudo make install'
|
||||
- '[ -z "$SODIUM" ] || cd ..'
|
||||
- git clone --depth 1 $ZMQ zmqlib
|
||||
- cd zmqlib
|
||||
- ./autogen.sh
|
||||
- ./configure
|
||||
- make
|
||||
- sudo make install
|
||||
- sudo /sbin/ldconfig
|
||||
- cd ..
|
||||
language: node_js
|
||||
node_js:
|
||||
- "0.8"
|
||||
- "0.10"
|
||||
- "0.12"
|
||||
- "4"
|
||||
- "5"
|
||||
script: travis_retry npm test
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
2.14.0 / 2015-11-20
|
||||
===================
|
||||
|
||||
* A socket.read() method was added to retrieve messages while paused [sshutovskyi]
|
||||
* socket.send() now takes a callback as 3rd argument which is called once the message is sent [ronkorving]
|
||||
* Now tested on Node.js 0.8, 0.10, 0.12, 4 and 5 [ronkorving]
|
||||
|
||||
2.13.0 / 2015-08-26
|
||||
===================
|
||||
|
||||
* io.js 3.x compatible [kkoopa]
|
||||
* corrections to type casting operations [kkoopa]
|
||||
* "make clean" now also removes node_modules [reqshark]
|
||||
|
||||
2.12.0 / 2015-07-10
|
||||
===================
|
||||
|
||||
* Massive improvements to monitoring code, with new documentation and tests [ValYouW]
|
||||
* Improved documentation [reqshark]
|
||||
* Updated bindings from ~1.1.1 to ~1.2.1 [reqshark]
|
||||
* Test suite improvements [reqshark]
|
||||
* Updated the Windows bundle to ZeroMQ 4.0.4 [kkoopa]
|
||||
* License attribute added to package.json [pdehaan]
|
||||
|
||||
2.11.1 / 2015-05-21
|
||||
===================
|
||||
|
||||
* io.js 2.x compatible [transcranial]
|
||||
* replaced asserts with proper exceptions [reqshark]
|
||||
|
||||
2.11.0 / 2015-03-31
|
||||
===================
|
||||
|
||||
* Added pause() and resume() APIs on sockets to allow backpressure [philip1986]
|
||||
* Elegant handling of EINTR return codes [hurricaneLTG]
|
||||
* Small performance improvements in send() and internal flush methods [ronkorving]
|
||||
* Updated test suite to cover io.js and Node 0.12 (removed 0.11) [ronkorving]
|
||||
* Added "make perf" for easy benchmarking [ronkorving]
|
||||
|
||||
2.10.0 / 2015-01-22
|
||||
===================
|
||||
|
||||
* Added ZMQ_STREAM socket type [reqshark]
|
||||
* Update NAN to io.js compatible 1.5.0 [kkoopa]
|
||||
* Hitting open file descriptor limit now throws an error during zmq.socket() [briansorahan]
|
||||
* More reliable benchmarking [maxired]
|
||||
|
||||
2.9.0 / 2015-01-05
|
||||
==================
|
||||
|
||||
* More unit tests [bluebery and reqshark]
|
||||
* More reliable testing [f34rdotcom and kkoopa]
|
||||
* Improved ReadMe [dminkovsky and skibz]
|
||||
* Support for zmq_proxy sockets [reqshark]
|
||||
* Removed "docs" and related deps in favor of ReadMe [reqshark]
|
||||
|
||||
2.8.0 / 2014-08-27
|
||||
==================
|
||||
|
||||
* Fixed: monitor API would keep CPU busy at 100% [f34rdotcom]
|
||||
* Fixed: an exception during flush could render a socket unusable [ronkorving]
|
||||
* Fixed: Travis changed behavior and broke our tests [ronkorving]
|
||||
* Code cleanup [kkoopa and ronkorving]
|
||||
* Removed legacy nextTick event emission during flush [utvara and ronkorving]
|
||||
* Context API added: setMaxThreads, getMaxThreads, setMaxSockets, getMaxSockets [yoneal]
|
||||
* Changed unit test suite to Mocha [skeggse and yoneal]
|
||||
* NAN updated to ~1.3.0 [kkoopa]
|
||||
|
||||
2.7.0 / 2014-04-24
|
||||
==================
|
||||
|
||||
* Fixed memory leak when closing socket [rasky]
|
||||
* Fixed high water mark [soplwang, kkoopa]
|
||||
* Added socket opts for zeromq 4.x security mechanisms [msealand]
|
||||
* Use MakeCallback [kkoopa]
|
||||
* Remove useless setImmediate [kkoopa]
|
||||
* Use `zmq_msg_send` for ZMQ >= 4.0 [kkoopa]
|
||||
* Expose the Socket class as zmq.Socket [tcr]
|
||||
|
||||
2.6.0 / 2014-01-23
|
||||
==================
|
||||
|
||||
* Monitor support [f34rdotcom, dr-fozzy]
|
||||
* Unbind support [kkoopa]
|
||||
* Node 0.11.9 compatibility [kkoopa]
|
||||
* Support for ZMQ 4 [atrniv]
|
||||
* Fixed memory leak [utvara]
|
||||
* OSX Homebrew support [jwalton]
|
||||
* Fix unit tests [ryanlelek]
|
||||
|
||||
2.5.1 / 2013-08-28
|
||||
==================
|
||||
|
||||
* Regression fix for IPC socket bind failure [christopherobin]
|
||||
|
||||
2.5.0 / 2013-08-20
|
||||
==================
|
||||
|
||||
* Added testing against Node.js v0.11 [AlexeyKupershtokh]
|
||||
* Add support for Joyent SmartMachines [JonGretar]
|
||||
* Use pkg-config on OS X too [blalor]
|
||||
* Patch for Node 0.11.3 [kkoopa]
|
||||
* Fix for bind / connect / send problem [kkoopa]
|
||||
* Fixed multiple bugs in perf tests and changed them to push/pull [ronkorving]
|
||||
* Add definitions for building on openbsd & freebsd [Minjung]
|
||||
|
||||
2.4.0 / 2013-04-09
|
||||
==================
|
||||
|
||||
* added: Windows support [mscdex]
|
||||
* added: support for all options ever [AlexeyKupershtokh]
|
||||
* fixed: prevent zeromq sockets from being destroyed by GC [AlexeyKupershtokh]
|
||||
|
||||
2.3.0 / 2013-03-15
|
||||
==================
|
||||
|
||||
* added: xpub/xsub socket types [xla]
|
||||
* added: support for zmq_disconnect [matehat]
|
||||
* added: LAST_ENDPOINT socket option [ronkorving]
|
||||
* added: local/remote_lat local/remote_thr perf test [wavded]
|
||||
* fixed: tests improved [qubyte, jeremybarnes, ronkorving]
|
||||
* fixed: Node v0.9.4+ compatibility [mscdex]
|
||||
* fixed: SNDHWM and RCVHWM options were given the wrong type [freehaha]
|
||||
* removed: waf support [mscdex]
|
||||
|
||||
2.2.0 / 2012-10-17
|
||||
==================
|
||||
|
||||
* add support for pkg-config
|
||||
* add libzmq 3.x support [aaudis]
|
||||
* fix: prevent GC happening too soon for connect/bindSync
|
||||
|
||||
2.1.0 / 2012-06-29
|
||||
==================
|
||||
|
||||
* fix require() for 0.8.0
|
||||
* change: use uv_poll in place of IOWatcher
|
||||
* remove stupid engines field
|
||||
|
||||
2.0.3 / 2012-03-14
|
||||
==================
|
||||
|
||||
* Removed -Wall (libuv unused vars caused the build to fail...)
|
||||
|
||||
2.0.2 / 2012-02-16
|
||||
==================
|
||||
|
||||
* Added back `.createSocket()` for BC. Closes #86
|
||||
|
||||
2.0.1 / 2012-01-26
|
||||
==================
|
||||
|
||||
* Added `.zmqVersion` [patricklucas]
|
||||
* Fixed multipart support [joshrtay]
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
Copyright (c) 2011 TJ Holowaychuk
|
||||
Copyright (c) 2010, 2011 Justin Tulloss
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
|
||||
build/Release/binding.node: binding.cc binding.gyp
|
||||
npm install
|
||||
|
||||
test:
|
||||
npm test
|
||||
|
||||
clean:
|
||||
rm -fr build node_modules
|
||||
|
||||
distclean:
|
||||
node-gyp clean
|
||||
|
||||
perf:
|
||||
node perf/local_lat.js tcp://127.0.0.1:5555 1 100000& node perf/remote_lat.js tcp://127.0.0.1:5555 1 100000
|
||||
node perf/local_thr.js tcp://127.0.0.1:5556 1 100000& node perf/remote_thr.js tcp://127.0.0.1:5556 1 100000
|
||||
|
||||
.PHONY: test clean distclean perf
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
# zmq [](https://travis-ci.org/JustinTulloss/zeromq.node) [](https://ci.appveyor.com/project/reqshark/zeromq-node)
|
||||
|
||||
[ØMQ](http://www.zeromq.org/) bindings for node.js.
|
||||
|
||||
## Installation
|
||||
|
||||
### on Windows:
|
||||
First install [Visual Studio](https://www.visualstudio.com/) and either
|
||||
[Node.js](https://nodejs.org/download/) or [io.js](https://iojs.org/dist/latest/).
|
||||
|
||||
Ensure you're building zmq from a conservative location on disk, one without
|
||||
unusual characters or spaces, for example somewhere like: `C:\sources\myproject`.
|
||||
|
||||
Installing the ZeroMQ library is optional and not required on Windows. We
|
||||
recommend running `npm install` and node executable commands from a
|
||||
[github for windows](https://windows.github.com/) shell or similar environment.
|
||||
|
||||
### installing on Unix/POSIX (and osx):
|
||||
|
||||
First install `pkg-config` and the [ZeroMQ library](http://www.zeromq.org/intro:get-the-software).
|
||||
|
||||
This module is compatible with ZeroMQ versions 2, 3 and 4. The installation
|
||||
process varies by platform, but headers are mandatory. Most Linux distributions
|
||||
provide these headers with `-devel` packages like `zeromq-devel` or
|
||||
`zeromq3-devel`. Homebrew for OS X provides versions 4 and 3 with packages
|
||||
`zeromq` and `zeromq3`, respectively. A
|
||||
[Chris Lea PPA](https://launchpad.net/~chris-lea/+archive/ubuntu/zeromq)
|
||||
is available for Debian-like users who want a version newer than currently
|
||||
provided by their distribution. Windows is supported but not actively
|
||||
maintained.
|
||||
|
||||
Note: For zap support with versions >=4 you need to have libzmq built and linked
|
||||
against libsodium. Check the [Travis configuration](.travis.yml) for a list of what is tested
|
||||
and therefore known to work.
|
||||
|
||||
#### with your platform-specifics taken care of, install and use this module:
|
||||
|
||||
$ npm install zmq
|
||||
|
||||
## Examples
|
||||
|
||||
### Push/Pull
|
||||
|
||||
```js
|
||||
// producer.js
|
||||
var zmq = require('zmq')
|
||||
, sock = zmq.socket('push');
|
||||
|
||||
sock.bindSync('tcp://127.0.0.1:3000');
|
||||
console.log('Producer bound to port 3000');
|
||||
|
||||
setInterval(function(){
|
||||
console.log('sending work');
|
||||
sock.send('some work');
|
||||
}, 500);
|
||||
```
|
||||
|
||||
```js
|
||||
// worker.js
|
||||
var zmq = require('zmq')
|
||||
, sock = zmq.socket('pull');
|
||||
|
||||
sock.connect('tcp://127.0.0.1:3000');
|
||||
console.log('Worker connected to port 3000');
|
||||
|
||||
sock.on('message', function(msg){
|
||||
console.log('work: %s', msg.toString());
|
||||
});
|
||||
```
|
||||
|
||||
### Pub/Sub
|
||||
|
||||
```js
|
||||
// pubber.js
|
||||
var zmq = require('zmq')
|
||||
, sock = zmq.socket('pub');
|
||||
|
||||
sock.bindSync('tcp://127.0.0.1:3000');
|
||||
console.log('Publisher bound to port 3000');
|
||||
|
||||
setInterval(function(){
|
||||
console.log('sending a multipart message envelope');
|
||||
sock.send(['kitty cats', 'meow!']);
|
||||
}, 500);
|
||||
```
|
||||
|
||||
```js
|
||||
// subber.js
|
||||
var zmq = require('zmq')
|
||||
, sock = zmq.socket('sub');
|
||||
|
||||
sock.connect('tcp://127.0.0.1:3000');
|
||||
sock.subscribe('kitty cats');
|
||||
console.log('Subscriber connected to port 3000');
|
||||
|
||||
sock.on('message', function(topic, message) {
|
||||
console.log('received a message related to:', topic, 'containing message:', message);
|
||||
});
|
||||
```
|
||||
## Monitoring
|
||||
|
||||
You can get socket state changes events by calling to the `monitor` function.
|
||||
The supported events are (see ZMQ [docs](http://api.zeromq.org/4-2:zmq-socket-monitor) for full description):
|
||||
* connect - ZMQ_EVENT_CONNECTED
|
||||
* connect_delay - ZMQ_EVENT_CONNECT_DELAYED
|
||||
* connect_retry - ZMQ_EVENT_CONNECT_RETRIED
|
||||
* listen - ZMQ_EVENT_LISTENING
|
||||
* bind_error - ZMQ_EVENT_BIND_FAILED
|
||||
* accept - ZMQ_EVENT_ACCEPTED
|
||||
* accept_error - ZMQ_EVENT_ACCEPT_FAILED
|
||||
* close - ZMQ_EVENT_CLOSED
|
||||
* close_error - ZMQ_EVENT_CLOSE_FAILED
|
||||
* disconnect - ZMQ_EVENT_DISCONNECTED
|
||||
|
||||
All events get 2 arguments:
|
||||
* fd - The file descriptor of the underlying socket (if available)
|
||||
* endpoint - The underlying socket endpoint
|
||||
|
||||
A special `monitor_error` event will be raised when there was an error in the monitoring process, after this event no more
|
||||
monitoring events will be sent, you can try and call `monitor` again to restart the monitoring process.
|
||||
|
||||
### monitor(interval, numOfEvents)
|
||||
Will create an inproc PAIR socket where zmq will publish socket state changes events, the events from this socket will
|
||||
be read every `interval` (defaults to 10ms).
|
||||
By default only 1 message will be read every interval, this can be configured by using the `numOfEvents` parameter,
|
||||
where passing 0 will read all available messages per interval.
|
||||
|
||||
### unmonitor()
|
||||
Stop the monitoring process
|
||||
|
||||
### example
|
||||
|
||||
```js
|
||||
// Create a socket
|
||||
var zmq = require('zmq');
|
||||
socket = zmq.socket('req');
|
||||
|
||||
// Register to monitoring events
|
||||
socket.on('connect', function(fd, ep) {console.log('connect, endpoint:', ep);});
|
||||
socket.on('connect_delay', function(fd, ep) {console.log('connect_delay, endpoint:', ep);});
|
||||
socket.on('connect_retry', function(fd, ep) {console.log('connect_retry, endpoint:', ep);});
|
||||
socket.on('listen', function(fd, ep) {console.log('listen, endpoint:', ep);});
|
||||
socket.on('bind_error', function(fd, ep) {console.log('bind_error, endpoint:', ep);});
|
||||
socket.on('accept', function(fd, ep) {console.log('accept, endpoint:', ep);});
|
||||
socket.on('accept_error', function(fd, ep) {console.log('accept_error, endpoint:', ep);});
|
||||
socket.on('close', function(fd, ep) {console.log('close, endpoint:', ep);});
|
||||
socket.on('close_error', function(fd, ep) {console.log('close_error, endpoint:', ep);});
|
||||
socket.on('disconnect', function(fd, ep) {console.log('disconnect, endpoint:', ep);});
|
||||
|
||||
// Handle monitor error
|
||||
socket.on('monitor_error', function(err) {
|
||||
console.log('Error in monitoring: %s, will restart monitoring in 5 seconds', err);
|
||||
setTimeout(function() { socket.monitor(500, 0); }, 5000);
|
||||
});
|
||||
|
||||
// Call monitor, check for events every 500ms and get all available events.
|
||||
console.log('Start monitoring...');
|
||||
socket.monitor(500, 0);
|
||||
socket.connect('tcp://127.0.0.1:1234');
|
||||
|
||||
setTimeout(function() {
|
||||
console.log('Stop the monitoring...');
|
||||
socket.unmonitor();
|
||||
}, 20000);
|
||||
|
||||
```
|
||||
|
||||
## Running tests
|
||||
|
||||
#### Install dev deps:
|
||||
```sh
|
||||
$ git clone https://github.com/JustinTulloss/zeromq.node.git zmq && cd zmq
|
||||
$ npm i
|
||||
```
|
||||
#### Build:
|
||||
```sh
|
||||
# on unix:
|
||||
$ make
|
||||
|
||||
# building on windows:
|
||||
> npm i
|
||||
```
|
||||
#### Test:
|
||||
```sh
|
||||
# on unix:
|
||||
$ make test
|
||||
|
||||
# testing on windows:
|
||||
> npm t
|
||||
```
|
||||
## Running benchmarks
|
||||
|
||||
Benchmarks are available in the `perf` directory, and have been implemented
|
||||
according to the zmq documentation:
|
||||
[How to run performance tests](http://www.zeromq.org/results:perf-howto)
|
||||
|
||||
In the following examples, the arguments are respectively:
|
||||
- the host to connect to/bind on
|
||||
- message size (in bytes)
|
||||
- message count
|
||||
|
||||
You can run a latency benchmark by running these two commands in two separate
|
||||
shells:
|
||||
|
||||
```sh
|
||||
node ./local_lat.js tcp://127.0.0.1:5555 1 100000
|
||||
```
|
||||
|
||||
```sh
|
||||
node ./remote_lat.js tcp://127.0.0.1:5555 1 100000
|
||||
```
|
||||
|
||||
And you can run throughput tests by running these two commands in two
|
||||
separate shells:
|
||||
|
||||
```sh
|
||||
node ./local_thr.js tcp://127.0.0.1:5555 1 100000
|
||||
```
|
||||
|
||||
```sh
|
||||
node ./remote_thr.js tcp://127.0.0.1:5555 1 100000
|
||||
```
|
||||
|
||||
Running `make perf` will run the commands listed above.
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
environment:
|
||||
matrix:
|
||||
- nodejs_version: "0.10"
|
||||
- nodejs_version: "0.12"
|
||||
- nodejs_version: "2"
|
||||
|
||||
#platform:
|
||||
# - x86
|
||||
# - x64
|
||||
|
||||
install:
|
||||
- ps: Install-Product node $env:nodejs_version #$env:platform
|
||||
- npm install
|
||||
|
||||
test_script:
|
||||
- node --version
|
||||
- npm --version
|
||||
- npm test
|
||||
|
||||
build: off
|
||||
|
||||
matrix:
|
||||
allow_failures:
|
||||
- nodejs_version: "2"
|
||||
+1393
File diff suppressed because it is too large
Load Diff
+76
@@ -0,0 +1,76 @@
|
||||
{
|
||||
'targets': [
|
||||
{
|
||||
'target_name': 'zmq',
|
||||
'sources': [ 'binding.cc' ],
|
||||
'include_dirs' : [
|
||||
"<!(node -e \"require('nan')\")"
|
||||
],
|
||||
'conditions': [
|
||||
['OS=="win"', {
|
||||
'win_delay_load_hook': 'true',
|
||||
'include_dirs': ['windows/include'],
|
||||
'link_settings': {
|
||||
'libraries': [
|
||||
'Delayimp.lib',
|
||||
],
|
||||
'conditions': [
|
||||
['target_arch=="ia32"', {
|
||||
'libraries': [
|
||||
'<(PRODUCT_DIR)/../../windows/lib/x86/libzmq-v100-mt-4_0_4.lib',
|
||||
]
|
||||
},{
|
||||
'libraries': [
|
||||
'<(PRODUCT_DIR)/../../windows/lib/x64/libzmq-v100-mt-4_0_4.lib',
|
||||
]
|
||||
}]
|
||||
],
|
||||
},
|
||||
'msvs_settings': {
|
||||
'VCLinkerTool': {
|
||||
'DelayLoadDLLs': ['libzmq-v100-mt-4_0_4.dll']
|
||||
}
|
||||
},
|
||||
}, {
|
||||
'libraries': ['-lzmq'],
|
||||
'cflags!': ['-fno-exceptions'],
|
||||
'cflags_cc!': ['-fno-exceptions'],
|
||||
}],
|
||||
['OS=="mac" or OS=="solaris"', {
|
||||
'xcode_settings': {
|
||||
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES'
|
||||
},
|
||||
# add macports include & lib dirs, homebrew include & lib dirs
|
||||
'include_dirs': [
|
||||
'<!@(pkg-config libzmq --cflags-only-I | sed s/-I//g)',
|
||||
'/opt/local/include',
|
||||
'/usr/local/include',
|
||||
],
|
||||
'libraries': [
|
||||
'<!@(pkg-config libzmq --libs)',
|
||||
'-L/opt/local/lib',
|
||||
'-L/usr/local/lib',
|
||||
]
|
||||
}],
|
||||
['OS=="openbsd" or OS=="freebsd"', {
|
||||
'include_dirs': [
|
||||
'<!@(pkg-config libzmq --cflags-only-I | sed s/-I//g)',
|
||||
'/usr/local/include',
|
||||
],
|
||||
'libraries': [
|
||||
'<!@(pkg-config libzmq --libs)',
|
||||
'-L/usr/local/lib',
|
||||
]
|
||||
}],
|
||||
['OS=="linux"', {
|
||||
'cflags': [
|
||||
'<!(pkg-config libzmq --cflags 2>/dev/null || echo "")',
|
||||
],
|
||||
'libraries': [
|
||||
'<!(pkg-config libzmq --libs 2>/dev/null || echo "")',
|
||||
],
|
||||
}],
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
*
|
||||
* One client two servers (round roobin)
|
||||
*
|
||||
*/
|
||||
|
||||
var cluster = require('cluster')
|
||||
, zmq = require('../')
|
||||
, port = 'tcp://127.0.0.1:12345';
|
||||
|
||||
if (cluster.isMaster) {
|
||||
for (var i = 0; i < 2; i++) cluster.fork();
|
||||
|
||||
cluster.on('death', function(worker) {
|
||||
console.log('worker ' + worker.pid + ' died');
|
||||
});
|
||||
|
||||
//dealer = client
|
||||
|
||||
var socket = zmq.socket('dealer');
|
||||
|
||||
socket.identity = 'client' + process.pid;
|
||||
|
||||
socket.bind(port, function(err) {
|
||||
if (err) throw err;
|
||||
console.log('bound!');
|
||||
|
||||
setInterval(function() {
|
||||
var value = Math.floor(Math.random()*100);
|
||||
|
||||
console.log(socket.identity + ': asking ' + value);
|
||||
socket.send(value);
|
||||
}, 100);
|
||||
|
||||
|
||||
socket.on('message', function(data) {
|
||||
console.log(socket.identity + ': answer data ' + data);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
//router = server
|
||||
|
||||
var socket = zmq.socket('router');
|
||||
|
||||
socket.identity = 'server' + process.pid;
|
||||
|
||||
socket.connect(port);
|
||||
console.log('connected!');
|
||||
|
||||
socket.on('message', function(envelope, data) {
|
||||
console.log(socket.identity + ': received ' + envelope + ' - ' + data.toString());
|
||||
socket.send([envelope, data * 2]);
|
||||
});
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
*
|
||||
* Forwarder device
|
||||
*
|
||||
*/
|
||||
|
||||
var zmq = require('../../')
|
||||
, frontPort = 'tcp://127.0.0.1:12345'
|
||||
, backPort = 'tcp://127.0.0.1:12346';
|
||||
|
||||
function createClient (port) {
|
||||
var socket = zmq.socket('pub');
|
||||
|
||||
socket.identity = 'client' + process.pid;
|
||||
|
||||
socket.connect(port);
|
||||
console.log('client connected!');
|
||||
|
||||
setInterval(function() {
|
||||
var value = Math.floor(Math.random()*100);
|
||||
|
||||
console.log(socket.identity + ': broadcasting ' + value);
|
||||
socket.send(value);
|
||||
}, 100);
|
||||
};
|
||||
|
||||
function createWorker (port) {
|
||||
var socket = zmq.socket('sub');
|
||||
|
||||
socket.identity = 'worker' + process.pid;
|
||||
|
||||
socket.subscribe('');
|
||||
socket.on('message', function(data) {
|
||||
console.log(socket.identity + ': got ' + data.toString());
|
||||
});
|
||||
|
||||
socket.connect(port, function(err) {
|
||||
if (err) throw err;
|
||||
console.log('worker connected!');
|
||||
});
|
||||
};
|
||||
|
||||
function createForwarderDevice(frontPort, backPort) {
|
||||
var frontSocket = zmq.socket('sub'),
|
||||
backSocket = zmq.socket('pub');
|
||||
|
||||
frontSocket.identity = 'sub' + process.pid;
|
||||
backSocket.identity = 'pub' + process.pid;
|
||||
|
||||
frontSocket.subscribe('');
|
||||
frontSocket.bind(frontPort, function (err) {
|
||||
console.log('bound', frontPort);
|
||||
});
|
||||
|
||||
frontSocket.on('message', function() {
|
||||
//pass to back
|
||||
console.log('forwarder: recasting', arguments[0].toString());
|
||||
backSocket.send(Array.prototype.slice.call(arguments));
|
||||
});
|
||||
|
||||
backSocket.bind(backPort, function (err) {
|
||||
console.log('bound', backPort);
|
||||
});
|
||||
}
|
||||
|
||||
createForwarderDevice(frontPort, backPort);
|
||||
|
||||
createClient(frontPort);
|
||||
createWorker(backPort);
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
*
|
||||
* Queue device
|
||||
*
|
||||
*/
|
||||
|
||||
var zmq = require('../../')
|
||||
, frontPort = 'tcp://127.0.0.1:12345'
|
||||
, backPort = 'tcp://127.0.0.1:12346';
|
||||
|
||||
function createClient (port) {
|
||||
var socket = zmq.socket('req');
|
||||
|
||||
socket.identity = 'client' + process.pid;
|
||||
|
||||
socket.on('message', function(data) {
|
||||
console.log(socket.identity + ': answer data ' + data);
|
||||
});
|
||||
|
||||
socket.connect(port);
|
||||
console.log('client connected!');
|
||||
|
||||
setInterval(function() {
|
||||
var value = Math.floor(Math.random()*100);
|
||||
|
||||
console.log(socket.identity + ': asking ' + value);
|
||||
socket.send(value);
|
||||
}, 100);
|
||||
};
|
||||
|
||||
function createServer (port) {
|
||||
var socket = zmq.socket('rep');
|
||||
|
||||
socket.identity = 'server' + process.pid;
|
||||
|
||||
socket.on('message', function(data) {
|
||||
console.log(socket.identity + ': received ' + data.toString());
|
||||
socket.send(data * 2);
|
||||
});
|
||||
|
||||
socket.connect(port, function(err) {
|
||||
if (err) throw err;
|
||||
console.log('server connected!');
|
||||
});
|
||||
};
|
||||
|
||||
function createQueueDevice(frontPort, backPort) {
|
||||
var frontSocket = zmq.socket('router'),
|
||||
backSocket = zmq.socket('dealer');
|
||||
|
||||
frontSocket.identity = 'router' + process.pid;
|
||||
backSocket.identity = 'dealer' + process.pid;
|
||||
|
||||
frontSocket.bind(frontPort, function (err) {
|
||||
console.log('bound', frontPort);
|
||||
});
|
||||
|
||||
frontSocket.on('message', function() {
|
||||
//pass to back
|
||||
console.log('router: sending to server', arguments[0].toString(), arguments[2].toString());
|
||||
backSocket.send(Array.prototype.slice.call(arguments));
|
||||
});
|
||||
|
||||
backSocket.bind(backPort, function (err) {
|
||||
console.log('bound', backPort);
|
||||
});
|
||||
|
||||
backSocket.on('message', function() {
|
||||
//pass to front
|
||||
console.log('dealer: sending to client', arguments[0].toString(), arguments[2].toString());
|
||||
frontSocket.send(Array.prototype.slice.call(arguments));
|
||||
});
|
||||
}
|
||||
|
||||
createQueueDevice(frontPort, backPort);
|
||||
|
||||
createClient(frontPort);
|
||||
createServer(backPort);
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
*
|
||||
* Forwarder device
|
||||
*
|
||||
*/
|
||||
|
||||
var zmq = require('../../')
|
||||
, frontPort = 'tcp://127.0.0.1:12345'
|
||||
, backPort = 'tcp://127.0.0.1:12346';
|
||||
|
||||
function createClient (port) {
|
||||
var socket = zmq.socket('push');
|
||||
|
||||
socket.identity = 'client' + process.pid;
|
||||
|
||||
socket.connect(port);
|
||||
console.log('client connected!');
|
||||
|
||||
setInterval(function() {
|
||||
var value = Math.floor(Math.random()*100);
|
||||
|
||||
console.log(socket.identity + ': pushing ' + value);
|
||||
socket.send(value);
|
||||
}, 100);
|
||||
};
|
||||
|
||||
function createWorker (port) {
|
||||
var socket = zmq.socket('pull');
|
||||
|
||||
socket.identity = 'worker' + process.pid;
|
||||
|
||||
socket.on('message', function(data) {
|
||||
console.log(socket.identity + ': pulled ' + data.toString());
|
||||
});
|
||||
|
||||
socket.connect(port, function(err) {
|
||||
if (err) throw err;
|
||||
console.log('worker connected!');
|
||||
});
|
||||
};
|
||||
|
||||
function createStreamerDevice(frontPort, backPort) {
|
||||
var frontSocket = zmq.socket('pull'),
|
||||
backSocket = zmq.socket('push');
|
||||
|
||||
frontSocket.identity = 'sub' + process.pid;
|
||||
backSocket.identity = 'pub' + process.pid;
|
||||
|
||||
frontSocket.bind(frontPort, function (err) {
|
||||
console.log('bound', frontPort);
|
||||
});
|
||||
|
||||
frontSocket.on('message', function() {
|
||||
//pass to back
|
||||
console.log('forwarder: sending downstream', arguments[0].toString());
|
||||
backSocket.send(Array.prototype.slice.call(arguments));
|
||||
});
|
||||
|
||||
backSocket.bind(backPort, function (err) {
|
||||
console.log('bound', backPort);
|
||||
});
|
||||
}
|
||||
|
||||
createStreamerDevice(frontPort, backPort);
|
||||
|
||||
createClient(frontPort);
|
||||
createWorker(backPort);
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
*
|
||||
* Publisher subscriber pattern
|
||||
*
|
||||
*/
|
||||
|
||||
var cluster = require('cluster')
|
||||
, zmq = require('../')
|
||||
, port = 'tcp://127.0.0.1:12345';
|
||||
|
||||
if (cluster.isMaster) {
|
||||
for (var i = 0; i < 2; i++) cluster.fork();
|
||||
|
||||
cluster.on('death', function(worker) {
|
||||
console.log('worker ' + worker.pid + ' died');
|
||||
});
|
||||
|
||||
//publisher = send only
|
||||
|
||||
var socket = zmq.socket('pub');
|
||||
|
||||
socket.identity = 'publisher' + process.pid;
|
||||
|
||||
var stocks = ['AAPL', 'GOOG', 'YHOO', 'MSFT', 'INTC'];
|
||||
|
||||
socket.bind(port, function(err) {
|
||||
if (err) throw err;
|
||||
console.log('bound!');
|
||||
|
||||
setInterval(function() {
|
||||
var symbol = stocks[Math.floor(Math.random()*stocks.length)]
|
||||
, value = Math.random()*1000;
|
||||
|
||||
console.log(socket.identity + ': sent ' + symbol + ' ' + value);
|
||||
socket.send(symbol + ' ' + value);
|
||||
}, 100);
|
||||
});
|
||||
} else {
|
||||
//subscriber = receive only
|
||||
|
||||
var socket = zmq.socket('sub');
|
||||
|
||||
socket.identity = 'subscriber' + process.pid;
|
||||
|
||||
socket.connect(port);
|
||||
|
||||
socket.subscribe('AAPL');
|
||||
socket.subscribe('GOOG');
|
||||
|
||||
console.log('connected!');
|
||||
|
||||
socket.on('message', function(data) {
|
||||
console.log(socket.identity + ': received data ' + data.toString());
|
||||
});
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
*
|
||||
* Pipeline
|
||||
*
|
||||
*/
|
||||
|
||||
var cluster = require('cluster')
|
||||
, zmq = require('../')
|
||||
, port = 'tcp://127.0.0.1:12345';
|
||||
|
||||
if (cluster.isMaster) {
|
||||
for (var i = 0; i < 2; i++) cluster.fork();
|
||||
|
||||
cluster.on('death', function(worker) {
|
||||
console.log('worker ' + worker.pid + ' died');
|
||||
});
|
||||
|
||||
//push = upstream
|
||||
|
||||
var socket = zmq.socket('push');
|
||||
|
||||
socket.identity = 'upstream' + process.pid;
|
||||
|
||||
socket.bind(port, function(err) {
|
||||
if (err) throw err;
|
||||
console.log('bound!');
|
||||
|
||||
setInterval(function() {
|
||||
var date = new Date();
|
||||
|
||||
console.log(socket.identity + ': sending data ' + date.toString());
|
||||
socket.send(date.toString());
|
||||
}, 500);
|
||||
});
|
||||
} else {
|
||||
//pull = downstream
|
||||
|
||||
var socket = zmq.socket('pull');
|
||||
|
||||
socket.identity = 'downstream' + process.pid;
|
||||
|
||||
socket.connect(port);
|
||||
console.log('connected!');
|
||||
|
||||
socket.on('message', function(data) {
|
||||
console.log(socket.identity + ': received data ' + data.toString());
|
||||
});
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
*
|
||||
* One responseder two requesters
|
||||
*
|
||||
*/
|
||||
|
||||
var cluster = require('cluster')
|
||||
, zmq = require('../')
|
||||
, port = 'tcp://127.0.0.1:12345';
|
||||
|
||||
if (cluster.isMaster) {
|
||||
for (var i = 0; i < 2; i++) cluster.fork();
|
||||
|
||||
cluster.on('death', function(worker) {
|
||||
console.log('worker ' + worker.pid + ' died');
|
||||
});
|
||||
|
||||
//responseder = server
|
||||
|
||||
var socket = zmq.socket('rep');
|
||||
|
||||
socket.identity = 'server' + process.pid;
|
||||
|
||||
socket.bind(port, function(err) {
|
||||
if (err) throw err;
|
||||
console.log('bound!');
|
||||
|
||||
socket.on('message', function(data) {
|
||||
console.log(socket.identity + ': received ' + data.toString());
|
||||
socket.send(2 * data);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
//requester = client
|
||||
|
||||
var socket = zmq.socket('req');
|
||||
|
||||
socket.identity = 'client' + process.pid;
|
||||
|
||||
socket.connect(port);
|
||||
console.log('connected!');
|
||||
|
||||
setInterval(function() {
|
||||
var value = Math.floor(Math.random()*100);
|
||||
|
||||
socket.send(value);
|
||||
console.log(socket.identity + ': asking ' + value);
|
||||
}, 100);
|
||||
|
||||
socket.on('message', function(data) {
|
||||
console.log(socket.identity + ': answer data ' + data);
|
||||
});
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
*
|
||||
* One requester two responders (round robin)
|
||||
*
|
||||
*/
|
||||
|
||||
var cluster = require('cluster')
|
||||
, zeromq = require('../')
|
||||
, port = 'tcp://127.0.0.1:12345';
|
||||
|
||||
if (cluster.isMaster) {
|
||||
//Fork servers.
|
||||
for (var i = 0; i < 2; i++) {
|
||||
cluster.fork();
|
||||
}
|
||||
|
||||
cluster.on('death', function(worker) {
|
||||
console.log('worker ' + worker.pid + ' died');
|
||||
});
|
||||
|
||||
//requester = client
|
||||
|
||||
var socket = zeromq.socket('req');
|
||||
|
||||
socket.identity = 'client' + process.pid;
|
||||
|
||||
socket.bind(port, function(err) {
|
||||
if (err) throw err;
|
||||
console.log('bound!');
|
||||
|
||||
setInterval(function() {
|
||||
var value = Math.floor(Math.random()*100);
|
||||
|
||||
console.log(socket.identity + ': asking ' + value);
|
||||
socket.send(value);
|
||||
}, 100);
|
||||
|
||||
|
||||
socket.on('message', function(data) {
|
||||
console.log(socket.identity + ': answer data ' + data);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
//responder = server
|
||||
|
||||
var socket = zeromq.socket('rep');
|
||||
|
||||
socket.identity = 'server' + process.pid;
|
||||
|
||||
socket.connect(port);
|
||||
console.log('connected!');
|
||||
|
||||
socket.on('message', function(data) {
|
||||
console.log(socket.identity + ': received ' + data.toString());
|
||||
socket.send(data * 2);
|
||||
});
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
*
|
||||
* One server two clients
|
||||
*
|
||||
*/
|
||||
|
||||
var cluster = require('cluster')
|
||||
, zeromq = require('../')
|
||||
, port = 'tcp://127.0.0.1:12345';
|
||||
|
||||
if (cluster.isMaster) {
|
||||
for (var i = 0; i < 2; i++) cluster.fork();
|
||||
|
||||
cluster.on('death', function(worker) {
|
||||
console.log('worker ' + worker.pid + ' died');
|
||||
});
|
||||
|
||||
//router = server
|
||||
|
||||
var socket = zeromq.socket('router');
|
||||
|
||||
socket.identity = 'server' + process.pid;
|
||||
|
||||
socket.bind(port, function(err) {
|
||||
if (err) throw err;
|
||||
console.log('bound!');
|
||||
|
||||
socket.on('message', function(envelope, data) {
|
||||
console.log(socket.identity + ': received ' + envelope + ' - ' + data.toString());
|
||||
socket.send([envelope, data * 2]);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
//dealer = client
|
||||
|
||||
var socket = zeromq.socket('dealer');
|
||||
|
||||
socket.identity = 'client' + process.pid;
|
||||
|
||||
socket.connect(port);
|
||||
console.log('connected!');
|
||||
|
||||
setInterval(function() {
|
||||
var value = Math.floor(Math.random()*100);
|
||||
|
||||
socket.send(value);
|
||||
console.log(socket.identity + ': asking ' + value);
|
||||
}, 100);
|
||||
|
||||
socket.on('message', function(data) {
|
||||
console.log(socket.identity + ': answer data ' + data);
|
||||
});
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
|
||||
/**
|
||||
* One server two clients
|
||||
*/
|
||||
|
||||
var cluster = require('cluster')
|
||||
, zmq = require('../')
|
||||
, port = 'tcp://127.0.0.1:12345';
|
||||
|
||||
if (cluster.isMaster) {
|
||||
for (var i = 0; i < 2; i++) cluster.fork();
|
||||
|
||||
|
||||
} else {
|
||||
var sock = zmq.socket('dealer');
|
||||
sock.connect(port);
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
|
||||
var zmq = require('../../')
|
||||
, sock = zmq.socket('push');
|
||||
|
||||
sock.bindSync('tcp://127.0.0.1:3000');
|
||||
console.log('Producer bound to port 3000');
|
||||
|
||||
setInterval(function(){
|
||||
console.log('sending work');
|
||||
sock.send('some work');
|
||||
}, 500);
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
|
||||
var zmq = require('../../')
|
||||
, sock = zmq.socket('pull');
|
||||
|
||||
sock.connect('tcp://127.0.0.1:3000');
|
||||
console.log('Worker connected to port 3000');
|
||||
|
||||
sock.on('message', function(msg){
|
||||
console.log('work: %s', msg.toString());
|
||||
});
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
|
||||
module.exports = require('./lib');
|
||||
Generated
Vendored
+97
@@ -0,0 +1,97 @@
|
||||
node-bindings
|
||||
=============
|
||||
### Helper module for loading your native module's .node file
|
||||
|
||||
This is a helper module for authors of Node.js native addon modules.
|
||||
It is basically the "swiss army knife" of `require()`ing your native module's
|
||||
`.node` file.
|
||||
|
||||
Throughout the course of Node's native addon history, addons have ended up being
|
||||
compiled in a variety of different places, depending on which build tool and which
|
||||
version of node was used. To make matters worse, now the _gyp_ build tool can
|
||||
produce either a _Release_ or _Debug_ build, each being built into different
|
||||
locations.
|
||||
|
||||
This module checks _all_ the possible locations that a native addon would be built
|
||||
at, and returns the first one that loads successfully.
|
||||
|
||||
|
||||
Installation
|
||||
------------
|
||||
|
||||
Install with `npm`:
|
||||
|
||||
``` bash
|
||||
$ npm install bindings
|
||||
```
|
||||
|
||||
Or add it to the `"dependencies"` section of your _package.json_ file.
|
||||
|
||||
|
||||
Example
|
||||
-------
|
||||
|
||||
`require()`ing the proper bindings file for the current node version, platform
|
||||
and architecture is as simple as:
|
||||
|
||||
``` js
|
||||
var bindings = require('bindings')('binding.node')
|
||||
|
||||
// Use your bindings defined in your C files
|
||||
bindings.your_c_function()
|
||||
```
|
||||
|
||||
|
||||
Nice Error Output
|
||||
-----------------
|
||||
|
||||
When the `.node` file could not be loaded, `node-bindings` throws an Error with
|
||||
a nice error message telling you exactly what was tried. You can also check the
|
||||
`err.tries` Array property.
|
||||
|
||||
```
|
||||
Error: Could not load the bindings file. Tried:
|
||||
→ /Users/nrajlich/ref/build/binding.node
|
||||
→ /Users/nrajlich/ref/build/Debug/binding.node
|
||||
→ /Users/nrajlich/ref/build/Release/binding.node
|
||||
→ /Users/nrajlich/ref/out/Debug/binding.node
|
||||
→ /Users/nrajlich/ref/Debug/binding.node
|
||||
→ /Users/nrajlich/ref/out/Release/binding.node
|
||||
→ /Users/nrajlich/ref/Release/binding.node
|
||||
→ /Users/nrajlich/ref/build/default/binding.node
|
||||
→ /Users/nrajlich/ref/compiled/0.8.2/darwin/x64/binding.node
|
||||
at bindings (/Users/nrajlich/ref/node_modules/bindings/bindings.js:84:13)
|
||||
at Object.<anonymous> (/Users/nrajlich/ref/lib/ref.js:5:47)
|
||||
at Module._compile (module.js:449:26)
|
||||
at Object.Module._extensions..js (module.js:467:10)
|
||||
at Module.load (module.js:356:32)
|
||||
at Function.Module._load (module.js:312:12)
|
||||
...
|
||||
```
|
||||
|
||||
|
||||
License
|
||||
-------
|
||||
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2012 Nathan Rajlich <nathan@tootallnate.net>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
'Software'), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
Generated
Vendored
+166
@@ -0,0 +1,166 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var fs = require('fs')
|
||||
, path = require('path')
|
||||
, join = path.join
|
||||
, dirname = path.dirname
|
||||
, exists = fs.existsSync || path.existsSync
|
||||
, defaults = {
|
||||
arrow: process.env.NODE_BINDINGS_ARROW || ' → '
|
||||
, compiled: process.env.NODE_BINDINGS_COMPILED_DIR || 'compiled'
|
||||
, platform: process.platform
|
||||
, arch: process.arch
|
||||
, version: process.versions.node
|
||||
, bindings: 'bindings.node'
|
||||
, try: [
|
||||
// node-gyp's linked version in the "build" dir
|
||||
[ 'module_root', 'build', 'bindings' ]
|
||||
// node-waf and gyp_addon (a.k.a node-gyp)
|
||||
, [ 'module_root', 'build', 'Debug', 'bindings' ]
|
||||
, [ 'module_root', 'build', 'Release', 'bindings' ]
|
||||
// Debug files, for development (legacy behavior, remove for node v0.9)
|
||||
, [ 'module_root', 'out', 'Debug', 'bindings' ]
|
||||
, [ 'module_root', 'Debug', 'bindings' ]
|
||||
// Release files, but manually compiled (legacy behavior, remove for node v0.9)
|
||||
, [ 'module_root', 'out', 'Release', 'bindings' ]
|
||||
, [ 'module_root', 'Release', 'bindings' ]
|
||||
// Legacy from node-waf, node <= 0.4.x
|
||||
, [ 'module_root', 'build', 'default', 'bindings' ]
|
||||
// Production "Release" buildtype binary (meh...)
|
||||
, [ 'module_root', 'compiled', 'version', 'platform', 'arch', 'bindings' ]
|
||||
]
|
||||
}
|
||||
|
||||
/**
|
||||
* The main `bindings()` function loads the compiled bindings for a given module.
|
||||
* It uses V8's Error API to determine the parent filename that this function is
|
||||
* being invoked from, which is then used to find the root directory.
|
||||
*/
|
||||
|
||||
function bindings (opts) {
|
||||
|
||||
// Argument surgery
|
||||
if (typeof opts == 'string') {
|
||||
opts = { bindings: opts }
|
||||
} else if (!opts) {
|
||||
opts = {}
|
||||
}
|
||||
opts.__proto__ = defaults
|
||||
|
||||
// Get the module root
|
||||
if (!opts.module_root) {
|
||||
opts.module_root = exports.getRoot(exports.getFileName())
|
||||
}
|
||||
|
||||
// Ensure the given bindings name ends with .node
|
||||
if (path.extname(opts.bindings) != '.node') {
|
||||
opts.bindings += '.node'
|
||||
}
|
||||
|
||||
var tries = []
|
||||
, i = 0
|
||||
, l = opts.try.length
|
||||
, n
|
||||
, b
|
||||
, err
|
||||
|
||||
for (; i<l; i++) {
|
||||
n = join.apply(null, opts.try[i].map(function (p) {
|
||||
return opts[p] || p
|
||||
}))
|
||||
tries.push(n)
|
||||
try {
|
||||
b = opts.path ? require.resolve(n) : require(n)
|
||||
if (!opts.path) {
|
||||
b.path = n
|
||||
}
|
||||
return b
|
||||
} catch (e) {
|
||||
if (!/not find/i.test(e.message)) {
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
err = new Error('Could not locate the bindings file. Tried:\n'
|
||||
+ tries.map(function (a) { return opts.arrow + a }).join('\n'))
|
||||
err.tries = tries
|
||||
throw err
|
||||
}
|
||||
module.exports = exports = bindings
|
||||
|
||||
|
||||
/**
|
||||
* Gets the filename of the JavaScript file that invokes this function.
|
||||
* Used to help find the root directory of a module.
|
||||
* Optionally accepts an filename argument to skip when searching for the invoking filename
|
||||
*/
|
||||
|
||||
exports.getFileName = function getFileName (calling_file) {
|
||||
var origPST = Error.prepareStackTrace
|
||||
, origSTL = Error.stackTraceLimit
|
||||
, dummy = {}
|
||||
, fileName
|
||||
|
||||
Error.stackTraceLimit = 10
|
||||
|
||||
Error.prepareStackTrace = function (e, st) {
|
||||
for (var i=0, l=st.length; i<l; i++) {
|
||||
fileName = st[i].getFileName()
|
||||
if (fileName !== __filename) {
|
||||
if (calling_file) {
|
||||
if (fileName !== calling_file) {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// run the 'prepareStackTrace' function above
|
||||
Error.captureStackTrace(dummy)
|
||||
dummy.stack
|
||||
|
||||
// cleanup
|
||||
Error.prepareStackTrace = origPST
|
||||
Error.stackTraceLimit = origSTL
|
||||
|
||||
return fileName
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the root directory of a module, given an arbitrary filename
|
||||
* somewhere in the module tree. The "root directory" is the directory
|
||||
* containing the `package.json` file.
|
||||
*
|
||||
* In: /home/nate/node-native-module/lib/index.js
|
||||
* Out: /home/nate/node-native-module
|
||||
*/
|
||||
|
||||
exports.getRoot = function getRoot (file) {
|
||||
var dir = dirname(file)
|
||||
, prev
|
||||
while (true) {
|
||||
if (dir === '.') {
|
||||
// Avoids an infinite loop in rare cases, like the REPL
|
||||
dir = process.cwd()
|
||||
}
|
||||
if (exists(join(dir, 'package.json')) || exists(join(dir, 'node_modules'))) {
|
||||
// Found the 'package.json' file or 'node_modules' dir; we're done
|
||||
return dir
|
||||
}
|
||||
if (prev === dir) {
|
||||
// Got to the top
|
||||
throw new Error('Could not find module root given file: "' + file
|
||||
+ '". Do you have a `package.json` file? ')
|
||||
}
|
||||
// Try the parent dir next
|
||||
prev = dir
|
||||
dir = join(dir, '..')
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+56
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"name": "bindings",
|
||||
"description": "Helper module for loading your native module's .node file",
|
||||
"keywords": [
|
||||
"native",
|
||||
"addon",
|
||||
"bindings",
|
||||
"gyp",
|
||||
"waf",
|
||||
"c",
|
||||
"c++"
|
||||
],
|
||||
"version": "1.2.1",
|
||||
"author": {
|
||||
"name": "Nathan Rajlich",
|
||||
"email": "nathan@tootallnate.net",
|
||||
"url": "http://tootallnate.net"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/TooTallNate/node-bindings.git"
|
||||
},
|
||||
"main": "./bindings.js",
|
||||
"bugs": {
|
||||
"url": "https://github.com/TooTallNate/node-bindings/issues"
|
||||
},
|
||||
"homepage": "https://github.com/TooTallNate/node-bindings",
|
||||
"license": "MIT",
|
||||
"gitHead": "e404152ee27f8478ccbc7122ee051246e8e5ec02",
|
||||
"_id": "bindings@1.2.1",
|
||||
"scripts": {},
|
||||
"_shasum": "14ad6113812d2d37d72e67b4cacb4bb726505f11",
|
||||
"_from": "bindings@>=1.2.1 <1.3.0",
|
||||
"_npmVersion": "1.4.14",
|
||||
"_npmUser": {
|
||||
"name": "tootallnate",
|
||||
"email": "nathan@tootallnate.net"
|
||||
},
|
||||
"maintainers": [
|
||||
{
|
||||
"name": "TooTallNate",
|
||||
"email": "nathan@tootallnate.net"
|
||||
},
|
||||
{
|
||||
"name": "tootallnate",
|
||||
"email": "nathan@tootallnate.net"
|
||||
}
|
||||
],
|
||||
"dist": {
|
||||
"shasum": "14ad6113812d2d37d72e67b4cacb4bb726505f11",
|
||||
"tarball": "http://registry.npmjs.org/bindings/-/bindings-1.2.1.tgz"
|
||||
},
|
||||
"directories": {},
|
||||
"_resolved": "https://registry.npmjs.org/bindings/-/bindings-1.2.1.tgz",
|
||||
"readme": "ERROR: No README data found!"
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
## DNT config file
|
||||
## see https://github.com/rvagg/dnt
|
||||
|
||||
NODE_VERSIONS="\
|
||||
master \
|
||||
v0.11.13 \
|
||||
v0.10.30 \
|
||||
v0.10.29 \
|
||||
v0.10.28 \
|
||||
v0.10.26 \
|
||||
v0.10.25 \
|
||||
v0.10.24 \
|
||||
v0.10.23 \
|
||||
v0.10.22 \
|
||||
v0.10.21 \
|
||||
v0.10.20 \
|
||||
v0.10.19 \
|
||||
v0.8.28 \
|
||||
v0.8.27 \
|
||||
v0.8.26 \
|
||||
v0.8.24 \
|
||||
"
|
||||
OUTPUT_PREFIX="nan-"
|
||||
TEST_CMD=" \
|
||||
cd /dnt/ && \
|
||||
npm install && \
|
||||
node_modules/.bin/node-gyp --nodedir /usr/src/node/ rebuild --directory test && \
|
||||
node_modules/.bin/tap --gc test/js/*-test.js \
|
||||
"
|
||||
|
||||
+374
@@ -0,0 +1,374 @@
|
||||
# NAN ChangeLog
|
||||
|
||||
**Version 2.0.9: current Node 4.0.0, Node 12: 0.12.7, Node 10: 0.10.40, iojs: 3.2.0**
|
||||
|
||||
### 2.0.9 Sep 8 2015
|
||||
|
||||
- Bugfix: EscapableHandleScope in Nan::NewBuffer for Node 0.8 and 0.10 b1654d7
|
||||
|
||||
### 2.0.8 Aug 28 2015
|
||||
|
||||
- Work around duplicate linking bug in clang 11902da
|
||||
|
||||
### 2.0.7 Aug 26 2015
|
||||
|
||||
- Build: Repackage
|
||||
|
||||
### 2.0.6 Aug 26 2015
|
||||
|
||||
- Bugfix: Properly handle null callback in FunctionTemplate factory 6e99cb1
|
||||
- Bugfix: Remove unused static std::map instances 525bddc
|
||||
- Bugfix: Make better use of maybe versions of APIs bfba85b
|
||||
- Bugfix: Fix shadowing issues with handle in ObjectWrap 0a9072d
|
||||
|
||||
### 2.0.5 Aug 10 2015
|
||||
|
||||
- Bugfix: Reimplement weak callback in ObjectWrap 98d38c1
|
||||
- Bugfix: Make sure callback classes are not assignable, copyable or movable 81f9b1d
|
||||
|
||||
### 2.0.4 Aug 6 2015
|
||||
|
||||
- Build: Repackage
|
||||
|
||||
### 2.0.3 Aug 6 2015
|
||||
|
||||
- Bugfix: Don't use clang++ / g++ syntax extension. 231450e
|
||||
|
||||
### 2.0.2 Aug 6 2015
|
||||
|
||||
- Build: Repackage
|
||||
|
||||
### 2.0.1 Aug 6 2015
|
||||
|
||||
- Bugfix: Add workaround for missing REPLACE_INVALID_UTF8 60d6687
|
||||
- Bugfix: Reimplement ObjectWrap from scratch to prevent memory leaks 6484601
|
||||
- Bugfix: Fix Persistent leak in FunctionCallbackInfo and PropertyCallbackInfo 641ef5f
|
||||
- Bugfix: Add missing overload for Nan::NewInstance that takes argc/argv 29450ed
|
||||
|
||||
### 2.0.0 Jul 31 2015
|
||||
|
||||
- Change: Renamed identifiers with leading underscores b5932b4
|
||||
- Change: Replaced NanObjectWrapHandle with class NanObjectWrap 464f1e1
|
||||
- Change: Replace NanScope and NanEscpableScope macros with classes 47751c4
|
||||
- Change: Rename NanNewBufferHandle to NanNewBuffer 6745f99
|
||||
- Change: Rename NanBufferUse to NanNewBuffer 3e8b0a5
|
||||
- Change: Rename NanNewBuffer to NanCopyBuffer d6af78d
|
||||
- Change: Remove Nan prefix from all names 72d1f67
|
||||
- Change: Update Buffer API for new upstream changes d5d3291
|
||||
- Change: Rename Scope and EscapableScope to HandleScope and EscapableHandleScope 21a7a6a
|
||||
- Change: Get rid of Handles e6c0daf
|
||||
- Feature: Support io.js 3 with V8 4.4
|
||||
- Feature: Introduce NanPersistent 7fed696
|
||||
- Feature: Introduce NanGlobal 4408da1
|
||||
- Feature: Added NanTryCatch 10f1ca4
|
||||
- Feature: Update for V8 v4.3 4b6404a
|
||||
- Feature: Introduce NanNewOneByteString c543d32
|
||||
- Feature: Introduce namespace Nan 67ed1b1
|
||||
- Removal: Remove NanLocker and NanUnlocker dd6e401
|
||||
- Removal: Remove string converters, except NanUtf8String, which now follows the node implementation b5d00a9
|
||||
- Removal: Remove NanReturn* macros d90a25c
|
||||
- Removal: Remove HasInstance e8f84fe
|
||||
|
||||
|
||||
### 1.9.0 Jul 31 2015
|
||||
|
||||
- Feature: Added `NanFatalException` 81d4a2c
|
||||
- Feature: Added more error types 4265f06
|
||||
- Feature: Added dereference and function call operators to NanCallback c4b2ed0
|
||||
- Feature: Added indexed GetFromPersistent and SaveToPersistent edd510c
|
||||
- Feature: Added more overloads of SaveToPersistent and GetFromPersistent 8b1cef6
|
||||
- Feature: Added NanErrnoException dd87d9e
|
||||
- Correctness: Prevent assign, copy, and move for classes that do not support it 1f55c59, 4b808cb, c96d9b2, fba4a29, 3357130
|
||||
- Deprecation: Deprecate `NanGetPointerSafe` and `NanSetPointerSafe` 81d4a2c
|
||||
- Deprecation: Deprecate `NanBooleanOptionValue` and `NanUInt32OptionValue` 0ad254b
|
||||
|
||||
### 1.8.4 Apr 26 2015
|
||||
|
||||
- Build: Repackage
|
||||
|
||||
### 1.8.3 Apr 26 2015
|
||||
|
||||
- Bugfix: Include missing header 1af8648
|
||||
|
||||
### 1.8.2 Apr 23 2015
|
||||
|
||||
- Build: Repackage
|
||||
|
||||
### 1.8.1 Apr 23 2015
|
||||
|
||||
- Bugfix: NanObjectWrapHandle should take a pointer 155f1d3
|
||||
|
||||
### 1.8.0 Apr 23 2015
|
||||
|
||||
- Feature: Allow primitives with NanReturnValue 2e4475e
|
||||
- Feature: Added comparison operators to NanCallback 55b075e
|
||||
- Feature: Backport thread local storage 15bb7fa
|
||||
- Removal: Remove support for signatures with arguments 8a2069d
|
||||
- Correcteness: Replaced NanObjectWrapHandle macro with function 0bc6d59
|
||||
|
||||
### 1.7.0 Feb 28 2015
|
||||
|
||||
- Feature: Made NanCallback::Call accept optional target 8d54da7
|
||||
- Feature: Support atom-shell 0.21 0b7f1bb
|
||||
|
||||
### 1.6.2 Feb 6 2015
|
||||
|
||||
- Bugfix: NanEncode: fix argument type for node::Encode on io.js 2be8639
|
||||
|
||||
### 1.6.1 Jan 23 2015
|
||||
|
||||
- Build: version bump
|
||||
|
||||
### 1.5.3 Jan 23 2015
|
||||
|
||||
- Build: repackage
|
||||
|
||||
### 1.6.0 Jan 23 2015
|
||||
|
||||
- Deprecated `NanNewContextHandle` in favor of `NanNew<Context>` 49259af
|
||||
- Support utility functions moved in newer v8 versions (Node 0.11.15, io.js 1.0) a0aa179
|
||||
- Added `NanEncode`, `NanDecodeBytes` and `NanDecodeWrite` 75e6fb9
|
||||
|
||||
### 1.5.2 Jan 23 2015
|
||||
|
||||
- Bugfix: Fix non-inline definition build error with clang++ 21d96a1, 60fadd4
|
||||
- Bugfix: Readded missing String constructors 18d828f
|
||||
- Bugfix: Add overload handling NanNew<FunctionTemplate>(..) 5ef813b
|
||||
- Bugfix: Fix uv_work_cb versioning 997e4ae
|
||||
- Bugfix: Add function factory and test 4eca89c
|
||||
- Bugfix: Add object template factory and test cdcb951
|
||||
- Correctness: Lifted an io.js related typedef c9490be
|
||||
- Correctness: Make explicit downcasts of String lengths 00074e6
|
||||
- Windows: Limit the scope of disabled warning C4530 83d7deb
|
||||
|
||||
### 1.5.1 Jan 15 2015
|
||||
|
||||
- Build: version bump
|
||||
|
||||
### 1.4.3 Jan 15 2015
|
||||
|
||||
- Build: version bump
|
||||
|
||||
### 1.4.2 Jan 15 2015
|
||||
|
||||
- Feature: Support io.js 0dbc5e8
|
||||
|
||||
### 1.5.0 Jan 14 2015
|
||||
|
||||
- Feature: Support io.js b003843
|
||||
- Correctness: Improved NanNew internals 9cd4f6a
|
||||
- Feature: Implement progress to NanAsyncWorker 8d6a160
|
||||
|
||||
### 1.4.1 Nov 8 2014
|
||||
|
||||
- Bugfix: Handle DEBUG definition correctly
|
||||
- Bugfix: Accept int as Boolean
|
||||
|
||||
### 1.4.0 Nov 1 2014
|
||||
|
||||
- Feature: Added NAN_GC_CALLBACK 6a5c245
|
||||
- Performance: Removed unnecessary local handle creation 18a7243, 41fe2f8
|
||||
- Correctness: Added constness to references in NanHasInstance 02c61cd
|
||||
- Warnings: Fixed spurious warnings from -Wundef and -Wshadow, 541b122, 99d8cb6
|
||||
- Windoze: Shut Visual Studio up when compiling 8d558c1
|
||||
- License: Switch to plain MIT from custom hacked MIT license 11de983
|
||||
- Build: Added test target to Makefile e232e46
|
||||
- Performance: Removed superfluous scope in NanAsyncWorker f4b7821
|
||||
- Sugar/Feature: Added NanReturnThis() and NanReturnHolder() shorthands 237a5ff, d697208
|
||||
- Feature: Added suitable overload of NanNew for v8::Integer::NewFromUnsigned b27b450
|
||||
|
||||
### 1.3.0 Aug 2 2014
|
||||
|
||||
- Added NanNew<v8::String, std::string>(std::string)
|
||||
- Added NanNew<v8::String, std::string&>(std::string&)
|
||||
- Added NanAsciiString helper class
|
||||
- Added NanUtf8String helper class
|
||||
- Added NanUcs2String helper class
|
||||
- Deprecated NanRawString()
|
||||
- Deprecated NanCString()
|
||||
- Added NanGetIsolateData(v8::Isolate *isolate)
|
||||
- Added NanMakeCallback(v8::Handle<v8::Object> target, v8::Handle<v8::Function> func, int argc, v8::Handle<v8::Value>* argv)
|
||||
- Added NanMakeCallback(v8::Handle<v8::Object> target, v8::Handle<v8::String> symbol, int argc, v8::Handle<v8::Value>* argv)
|
||||
- Added NanMakeCallback(v8::Handle<v8::Object> target, const char* method, int argc, v8::Handle<v8::Value>* argv)
|
||||
- Added NanSetTemplate(v8::Handle<v8::Template> templ, v8::Handle<v8::String> name , v8::Handle<v8::Data> value, v8::PropertyAttribute attributes)
|
||||
- Added NanSetPrototypeTemplate(v8::Local<v8::FunctionTemplate> templ, v8::Handle<v8::String> name, v8::Handle<v8::Data> value, v8::PropertyAttribute attributes)
|
||||
- Added NanSetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ, const char *name, v8::Handle<v8::Data> value)
|
||||
- Added NanSetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ, v8::Handle<v8::String> name, v8::Handle<v8::Data> value, v8::PropertyAttribute attributes)
|
||||
|
||||
### 1.2.0 Jun 5 2014
|
||||
|
||||
- Add NanSetPrototypeTemplate
|
||||
- Changed NAN_WEAK_CALLBACK internals, switched _NanWeakCallbackData to class,
|
||||
introduced _NanWeakCallbackDispatcher
|
||||
- Removed -Wno-unused-local-typedefs from test builds
|
||||
- Made test builds Windows compatible ('Sleep()')
|
||||
|
||||
### 1.1.2 May 28 2014
|
||||
|
||||
- Release to fix more stuff-ups in 1.1.1
|
||||
|
||||
### 1.1.1 May 28 2014
|
||||
|
||||
- Release to fix version mismatch in nan.h and lack of changelog entry for 1.1.0
|
||||
|
||||
### 1.1.0 May 25 2014
|
||||
|
||||
- Remove nan_isolate, use v8::Isolate::GetCurrent() internally instead
|
||||
- Additional explicit overloads for NanNew(): (char*,int), (uint8_t*[,int]),
|
||||
(uint16_t*[,int), double, int, unsigned int, bool, v8::String::ExternalStringResource*,
|
||||
v8::String::ExternalAsciiStringResource*
|
||||
- Deprecate NanSymbol()
|
||||
- Added SetErrorMessage() and ErrorMessage() to NanAsyncWorker
|
||||
|
||||
### 1.0.0 May 4 2014
|
||||
|
||||
- Heavy API changes for V8 3.25 / Node 0.11.13
|
||||
- Use cpplint.py
|
||||
- Removed NanInitPersistent
|
||||
- Removed NanPersistentToLocal
|
||||
- Removed NanFromV8String
|
||||
- Removed NanMakeWeak
|
||||
- Removed NanNewLocal
|
||||
- Removed NAN_WEAK_CALLBACK_OBJECT
|
||||
- Removed NAN_WEAK_CALLBACK_DATA
|
||||
- Introduce NanNew, replaces NanNewLocal, NanPersistentToLocal, adds many overloaded typed versions
|
||||
- Introduce NanUndefined, NanNull, NanTrue and NanFalse
|
||||
- Introduce NanEscapableScope and NanEscapeScope
|
||||
- Introduce NanMakeWeakPersistent (requires a special callback to work on both old and new node)
|
||||
- Introduce NanMakeCallback for node::MakeCallback
|
||||
- Introduce NanSetTemplate
|
||||
- Introduce NanGetCurrentContext
|
||||
- Introduce NanCompileScript and NanRunScript
|
||||
- Introduce NanAdjustExternalMemory
|
||||
- Introduce NanAddGCEpilogueCallback, NanAddGCPrologueCallback, NanRemoveGCEpilogueCallback, NanRemoveGCPrologueCallback
|
||||
- Introduce NanGetHeapStatistics
|
||||
- Rename NanAsyncWorker#SavePersistent() to SaveToPersistent()
|
||||
|
||||
### 0.8.0 Jan 9 2014
|
||||
|
||||
- NanDispose -> NanDisposePersistent, deprecate NanDispose
|
||||
- Extract _NAN_*_RETURN_TYPE, pull up NAN_*()
|
||||
|
||||
### 0.7.1 Jan 9 2014
|
||||
|
||||
- Fixes to work against debug builds of Node
|
||||
- Safer NanPersistentToLocal (avoid reinterpret_cast)
|
||||
- Speed up common NanRawString case by only extracting flattened string when necessary
|
||||
|
||||
### 0.7.0 Dec 17 2013
|
||||
|
||||
- New no-arg form of NanCallback() constructor.
|
||||
- NanCallback#Call takes Handle rather than Local
|
||||
- Removed deprecated NanCallback#Run method, use NanCallback#Call instead
|
||||
- Split off _NAN_*_ARGS_TYPE from _NAN_*_ARGS
|
||||
- Restore (unofficial) Node 0.6 compatibility at NanCallback#Call()
|
||||
- Introduce NanRawString() for char* (or appropriate void*) from v8::String
|
||||
(replacement for NanFromV8String)
|
||||
- Introduce NanCString() for null-terminated char* from v8::String
|
||||
|
||||
### 0.6.0 Nov 21 2013
|
||||
|
||||
- Introduce NanNewLocal<T>(v8::Handle<T> value) for use in place of
|
||||
v8::Local<T>::New(...) since v8 started requiring isolate in Node 0.11.9
|
||||
|
||||
### 0.5.2 Nov 16 2013
|
||||
|
||||
- Convert SavePersistent and GetFromPersistent in NanAsyncWorker from protected and public
|
||||
|
||||
### 0.5.1 Nov 12 2013
|
||||
|
||||
- Use node::MakeCallback() instead of direct v8::Function::Call()
|
||||
|
||||
### 0.5.0 Nov 11 2013
|
||||
|
||||
- Added @TooTallNate as collaborator
|
||||
- New, much simpler, "include_dirs" for binding.gyp
|
||||
- Added full range of NAN_INDEX_* macros to match NAN_PROPERTY_* macros
|
||||
|
||||
### 0.4.4 Nov 2 2013
|
||||
|
||||
- Isolate argument from v8::Persistent::MakeWeak removed for 0.11.8+
|
||||
|
||||
### 0.4.3 Nov 2 2013
|
||||
|
||||
- Include node_object_wrap.h, removed from node.h for Node 0.11.8.
|
||||
|
||||
### 0.4.2 Nov 2 2013
|
||||
|
||||
- Handle deprecation of v8::Persistent::Dispose(v8::Isolate* isolate)) for
|
||||
Node 0.11.8 release.
|
||||
|
||||
### 0.4.1 Sep 16 2013
|
||||
|
||||
- Added explicit `#include <uv.h>` as it was removed from node.h for v0.11.8
|
||||
|
||||
### 0.4.0 Sep 2 2013
|
||||
|
||||
- Added NAN_INLINE and NAN_DEPRECATED and made use of them
|
||||
- Added NanError, NanTypeError and NanRangeError
|
||||
- Cleaned up code
|
||||
|
||||
### 0.3.2 Aug 30 2013
|
||||
|
||||
- Fix missing scope declaration in GetFromPersistent() and SaveToPersistent
|
||||
in NanAsyncWorker
|
||||
|
||||
### 0.3.1 Aug 20 2013
|
||||
|
||||
- fix "not all control paths return a value" compile warning on some platforms
|
||||
|
||||
### 0.3.0 Aug 19 2013
|
||||
|
||||
- Made NAN work with NPM
|
||||
- Lots of fixes to NanFromV8String, pulling in features from new Node core
|
||||
- Changed node::encoding to Nan::Encoding in NanFromV8String to unify the API
|
||||
- Added optional error number argument for NanThrowError()
|
||||
- Added NanInitPersistent()
|
||||
- Added NanReturnNull() and NanReturnEmptyString()
|
||||
- Added NanLocker and NanUnlocker
|
||||
- Added missing scopes
|
||||
- Made sure to clear disposed Persistent handles
|
||||
- Changed NanAsyncWorker to allocate error messages on the heap
|
||||
- Changed NanThrowError(Local<Value>) to NanThrowError(Handle<Value>)
|
||||
- Fixed leak in NanAsyncWorker when errmsg is used
|
||||
|
||||
### 0.2.2 Aug 5 2013
|
||||
|
||||
- Fixed usage of undefined variable with node::BASE64 in NanFromV8String()
|
||||
|
||||
### 0.2.1 Aug 5 2013
|
||||
|
||||
- Fixed 0.8 breakage, node::BUFFER encoding type not available in 0.8 for
|
||||
NanFromV8String()
|
||||
|
||||
### 0.2.0 Aug 5 2013
|
||||
|
||||
- Added NAN_PROPERTY_GETTER, NAN_PROPERTY_SETTER, NAN_PROPERTY_ENUMERATOR,
|
||||
NAN_PROPERTY_DELETER, NAN_PROPERTY_QUERY
|
||||
- Extracted _NAN_METHOD_ARGS, _NAN_GETTER_ARGS, _NAN_SETTER_ARGS,
|
||||
_NAN_PROPERTY_GETTER_ARGS, _NAN_PROPERTY_SETTER_ARGS,
|
||||
_NAN_PROPERTY_ENUMERATOR_ARGS, _NAN_PROPERTY_DELETER_ARGS,
|
||||
_NAN_PROPERTY_QUERY_ARGS
|
||||
- Added NanGetInternalFieldPointer, NanSetInternalFieldPointer
|
||||
- Added NAN_WEAK_CALLBACK, NAN_WEAK_CALLBACK_OBJECT,
|
||||
NAN_WEAK_CALLBACK_DATA, NanMakeWeak
|
||||
- Renamed THROW_ERROR to _NAN_THROW_ERROR
|
||||
- Added NanNewBufferHandle(char*, size_t, node::smalloc::FreeCallback, void*)
|
||||
- Added NanBufferUse(char*, uint32_t)
|
||||
- Added NanNewContextHandle(v8::ExtensionConfiguration*,
|
||||
v8::Handle<v8::ObjectTemplate>, v8::Handle<v8::Value>)
|
||||
- Fixed broken NanCallback#GetFunction()
|
||||
- Added optional encoding and size arguments to NanFromV8String()
|
||||
- Added NanGetPointerSafe() and NanSetPointerSafe()
|
||||
- Added initial test suite (to be expanded)
|
||||
- Allow NanUInt32OptionValue to convert any Number object
|
||||
|
||||
### 0.1.0 Jul 21 2013
|
||||
|
||||
- Added `NAN_GETTER`, `NAN_SETTER`
|
||||
- Added `NanThrowError` with single Local<Value> argument
|
||||
- Added `NanNewBufferHandle` with single uint32_t argument
|
||||
- Added `NanHasInstance(Persistent<FunctionTemplate>&, Handle<Value>)`
|
||||
- Added `Local<Function> NanCallback#GetFunction()`
|
||||
- Added `NanCallback#Call(int, Local<Value>[])`
|
||||
- Deprecated `NanCallback#Run(int, Local<Value>[])` in favour of Call
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
The MIT License (MIT)
|
||||
=====================
|
||||
|
||||
Copyright (c) 2015 NAN contributors
|
||||
-----------------------------------
|
||||
|
||||
*NAN contributors listed at <https://github.com/nodejs/nan#contributors>*
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+367
@@ -0,0 +1,367 @@
|
||||
Native Abstractions for Node.js
|
||||
===============================
|
||||
|
||||
**A header file filled with macro and utility goodness for making add-on development for Node.js easier across versions 0.8, 0.10 and 0.12 as well as io.js.**
|
||||
|
||||
***Current version: 2.0.9***
|
||||
|
||||
*(See [CHANGELOG.md](https://github.com/nodejs/nan/blob/master/CHANGELOG.md) for complete ChangeLog)*
|
||||
|
||||
[](https://nodei.co/npm/nan/) [](https://nodei.co/npm/nan/)
|
||||
|
||||
[](http://travis-ci.org/nodejs/nan)
|
||||
[](https://ci.appveyor.com/project/RodVagg/nan)
|
||||
|
||||
Thanks to the crazy changes in V8 (and some in Node core), keeping native addons compiling happily across versions, particularly 0.10 to 0.12, is a minor nightmare. The goal of this project is to store all logic necessary to develop native Node.js addons without having to inspect `NODE_MODULE_VERSION` and get yourself into a macro-tangle.
|
||||
|
||||
This project also contains some helper utilities that make addon development a bit more pleasant.
|
||||
|
||||
* **[News & Updates](#news)**
|
||||
* **[Usage](#usage)**
|
||||
* **[Example](#example)**
|
||||
* **[API](#api)**
|
||||
* **[Tests](#tests)**
|
||||
* **[Governance & Contributing](#governance)**
|
||||
|
||||
<a name="news"></a>
|
||||
## News & Updates
|
||||
|
||||
<a name="usage"></a>
|
||||
## Usage
|
||||
|
||||
Simply add **NAN** as a dependency in the *package.json* of your Node addon:
|
||||
|
||||
``` bash
|
||||
$ npm install --save nan
|
||||
```
|
||||
|
||||
Pull in the path to **NAN** in your *binding.gyp* so that you can use `#include <nan.h>` in your *.cpp* files:
|
||||
|
||||
``` python
|
||||
"include_dirs" : [
|
||||
"<!(node -e \"require('nan')\")"
|
||||
]
|
||||
```
|
||||
|
||||
This works like a `-I<path-to-NAN>` when compiling your addon.
|
||||
|
||||
<a name="example"></a>
|
||||
## Example
|
||||
|
||||
Just getting started with Nan? Refer to a [quick-start **Nan** Boilerplate](https://github.com/fcanas/node-native-boilerplate) for a ready-to-go project that utilizes basic Nan functionality.
|
||||
|
||||
For a simpler example, see the **[async pi estimation example](https://github.com/nodejs/nan/tree/master/examples/async_pi_estimate)** in the examples directory for full code and an explanation of what this Monte Carlo Pi estimation example does. Below are just some parts of the full example that illustrate the use of **NAN**.
|
||||
|
||||
For another example, see **[nan-example-eol](https://github.com/CodeCharmLtd/nan-example-eol)**. It shows newline detection implemented as a native addon.
|
||||
|
||||
<a name="api"></a>
|
||||
## API
|
||||
|
||||
Additional to the NAN documentation below, please consult:
|
||||
|
||||
* [The V8 Getting Started Guide](https://developers.google.com/v8/get_started)
|
||||
* [The V8 Embedders Guide](https://developers.google.com/v8/embed)
|
||||
* [V8 API Documentation](http://v8docs.nodesource.com/)
|
||||
|
||||
<!-- START API -->
|
||||
|
||||
### JavaScript-accessible methods
|
||||
|
||||
A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://developers.google.com/v8/embed#templates) for further information.
|
||||
|
||||
In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type.
|
||||
|
||||
* **Method argument types**
|
||||
- <a href="doc/methods.md#api_nan_function_callback_info"><b><code>Nan::FunctionCallbackInfo</code></b></a>
|
||||
- <a href="doc/methods.md#api_nan_property_callback_info"><b><code>Nan::PropertyCallbackInfo</code></b></a>
|
||||
- <a href="doc/methods.md#api_nan_return_value"><b><code>Nan::ReturnValue</code></b></a>
|
||||
* **Method declarations**
|
||||
- <a href="doc/methods.md#api_nan_method"><b>Method declaration</b></a>
|
||||
- <a href="doc/methods.md#api_nan_getter"><b>Getter declaration</b></a>
|
||||
- <a href="doc/methods.md#api_nan_setter"><b>Setter declaration</b></a>
|
||||
- <a href="doc/methods.md#api_nan_property_getter"><b>Property getter declaration</b></a>
|
||||
- <a href="doc/methods.md#api_nan_property_setter"><b>Property setter declaration</b></a>
|
||||
- <a href="doc/methods.md#api_nan_property_enumerator"><b>Property enumerator declaration</b></a>
|
||||
- <a href="doc/methods.md#api_nan_property_deleter"><b>Property deleter declaration</b></a>
|
||||
- <a href="doc/methods.md#api_nan_property_query"><b>Property query declaration</b></a>
|
||||
- <a href="doc/methods.md#api_nan_index_getter"><b>Index getter declaration</b></a>
|
||||
- <a href="doc/methods.md#api_nan_index_setter"><b>Index setter declaration</b></a>
|
||||
- <a href="doc/methods.md#api_nan_index_enumerator"><b>Index enumerator declaration</b></a>
|
||||
- <a href="doc/methods.md#api_nan_index_deleter"><b>Index deleter declaration</b></a>
|
||||
- <a href="doc/methods.md#api_nan_index_query"><b>Index query declaration</b></a>
|
||||
* Method and template helpers
|
||||
- <a href="doc/methods.md#api_nan_set_method"><b><code>Nan::SetMethod()</code></b></a>
|
||||
- <a href="doc/methods.md#api_nan_set_named_property_handler"><b><code>Nan::SetNamedPropertyHandler()</code></b></a>
|
||||
- <a href="doc/methods.md#api_nan_set_indexed_property_handler"><b><code>Nan::SetIndexedPropertyHandler()</code></b></a>
|
||||
- <a href="doc/methods.md#api_nan_set_prototype_method"><b><code>Nan::SetPrototypeMethod()</code></b></a>
|
||||
- <a href="doc/methods.md#api_nan_set_template"><b><code>Nan::SetTemplate()</code></b></a>
|
||||
- <a href="doc/methods.md#api_nan_set_prototype_template"><b><code>Nan::SetPrototypeTemplate()</code></b></a>
|
||||
- <a href="doc/methods.md#api_nan_set_instance_template"><b><code>Nan::SetInstanceTemplate()</code></b></a>
|
||||
|
||||
### Scopes
|
||||
|
||||
A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works.
|
||||
|
||||
A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope.
|
||||
|
||||
The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these.
|
||||
|
||||
- <a href="doc/scopes.md#api_nan_handle_scope"><b><code>Nan::HandleScope</code></b></a>
|
||||
- <a href="doc/scopes.md#api_nan_escapable_handle_scope"><b><code>Nan::EscapableHandleScope</code></b></a>
|
||||
|
||||
Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles).
|
||||
|
||||
### Persistent references
|
||||
|
||||
An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed.
|
||||
|
||||
Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported.
|
||||
|
||||
- <a href="doc/persistent.md#api_nan_persistent_base"><b><code>Nan::PersistentBase & v8::PersistentBase</code></b></a>
|
||||
- <a href="doc/persistent.md#api_nan_non_copyable_persistent_traits"><b><code>Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits</code></b></a>
|
||||
- <a href="doc/persistent.md#api_nan_copyable_persistent_traits"><b><code>Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits</code></b></a>
|
||||
- <a href="doc/persistent.md#api_nan_persistent"><b><code>Nan::Persistent</code></b></a>
|
||||
- <a href="doc/persistent.md#api_nan_global"><b><code>Nan::Global</code></b></a>
|
||||
- <a href="doc/persistent.md#api_nan_weak_callback_info"><b><code>Nan::WeakCallbackInfo</code></b></a>
|
||||
- <a href="doc/persistent.md#api_nan_weak_callback_type"><b><code>Nan::WeakCallbackType</code></b></a>
|
||||
|
||||
Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles).
|
||||
|
||||
### New
|
||||
|
||||
NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8.
|
||||
|
||||
- <a href="doc/new.md#api_nan_new"><b><code>Nan::New()</code></b></a>
|
||||
- <a href="doc/new.md#api_nan_undefined"><b><code>Nan::Undefined()</code></b></a>
|
||||
- <a href="doc/new.md#api_nan_null"><b><code>Nan::Null()</code></b></a>
|
||||
- <a href="doc/new.md#api_nan_true"><b><code>Nan::True()</code></b></a>
|
||||
- <a href="doc/new.md#api_nan_false"><b><code>Nan::False()</code></b></a>
|
||||
- <a href="doc/new.md#api_nan_empty_string"><b><code>Nan::EmptyString()</code></b></a>
|
||||
|
||||
|
||||
### Converters
|
||||
|
||||
NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN.
|
||||
|
||||
- <a href="doc/converters.md#api_nan_to"><b><code>Nan::To()</code></b></a>
|
||||
|
||||
### Maybe Types
|
||||
|
||||
The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_.
|
||||
|
||||
* **Maybe Types**
|
||||
- <a href="doc/maybe_types.md#api_nan_maybe_local"><b><code>Nan::MaybeLocal</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_maybe"><b><code>Nan::Maybe</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_nothing"><b><code>Nan::Nothing</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_just"><b><code>Nan::Just</code></b></a>
|
||||
* **Maybe Helpers**
|
||||
- <a href="doc/maybe_types.md#api_nan_to_detail_string"><b><code>Nan::ToDetailString()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_to_array_index"><b><code>Nan::ToArrayIndex()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_equals"><b><code>Nan::Equals()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_new_instance"><b><code>Nan::NewInstance()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_get_function"><b><code>Nan::GetFunction()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_set"><b><code>Nan::Set()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_force_set"><b><code>Nan::ForceSet()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_get"><b><code>Nan::Get()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_get_property_attribute"><b><code>Nan::GetPropertyAttributes()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_has"><b><code>Nan::Has()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_delete"><b><code>Nan::Delete()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_get_property_names"><b><code>Nan::GetPropertyNames()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_get_own_property_names"><b><code>Nan::GetOwnPropertyNames()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_set_prototype"><b><code>Nan::SetPrototype()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_object_proto_to_string"><b><code>Nan::ObjectProtoToString()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_has_own_property"><b><code>Nan::HasOwnProperty()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_has_real_named_property"><b><code>Nan::HasRealNamedProperty()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_has_real_indexed_property"><b><code>Nan::HasRealIndexedProperty()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_has_real_named_callback_property"><b><code>Nan::HasRealNamedCallbackProperty()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_get_real_named_property_in_prototype_chain"><b><code>Nan::GetRealNamedPropertyInPrototypeChain()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_get_real_named_property"><b><code>Nan::GetRealNamedProperty()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_call_as_function"><b><code>Nan::CallAsFunction()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_call_as_constructor"><b><code>Nan::CallAsConstructor()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_get_source_line"><b><code>Nan::GetSourceLine()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_get_line_number"><b><code>Nan::GetLineNumber()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_get_start_column"><b><code>Nan::GetStartColumn()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_get_end_column"><b><code>Nan::GetEndColumn()</code></b></a>
|
||||
- <a href="doc/maybe_types.md#api_nan_clone_element_at"><b><code>Nan::CloneElementAt()</code></b></a>
|
||||
|
||||
### Script
|
||||
|
||||
NAN provides a `v8::Script` helpers as the API has changed over the supported versions of V8.
|
||||
|
||||
- <a href="doc/script.md#api_nan_compile_script"><b><code>Nan::CompileScript()</code></b></a>
|
||||
- <a href="doc/script.md#api_nan_run_script"><b><code>Nan::RunScript()</code></b></a>
|
||||
|
||||
|
||||
### Errors
|
||||
|
||||
NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted.
|
||||
|
||||
Note that an Error object is simply a specialized form of `v8::Value`.
|
||||
|
||||
Also consult the V8 Embedders Guide section on [Exceptions](https://developers.google.com/v8/embed#exceptions) for more information.
|
||||
|
||||
- <a href="doc/errors.md#api_nan_error"><b><code>Nan::Error()</code></b></a>
|
||||
- <a href="doc/errors.md#api_nan_range_error"><b><code>Nan::RangeError()</code></b></a>
|
||||
- <a href="doc/errors.md#api_nan_reference_error"><b><code>Nan::ReferenceError()</code></b></a>
|
||||
- <a href="doc/errors.md#api_nan_syntax_error"><b><code>Nan::SyntaxError()</code></b></a>
|
||||
- <a href="doc/errors.md#api_nan_type_error"><b><code>Nan::TypeError()</code></b></a>
|
||||
- <a href="doc/errors.md#api_nan_throw_error"><b><code>Nan::ThrowError()</code></b></a>
|
||||
- <a href="doc/errors.md#api_nan_throw_range_error"><b><code>Nan::ThrowRangeError()</code></b></a>
|
||||
- <a href="doc/errors.md#api_nan_throw_reference_error"><b><code>Nan::ThrowReferenceError()</code></b></a>
|
||||
- <a href="doc/errors.md#api_nan_throw_syntax_error"><b><code>Nan::ThrowSyntaxError()</code></b></a>
|
||||
- <a href="doc/errors.md#api_nan_throw_type_error"><b><code>Nan::ThrowTypeError()</code></b></a>
|
||||
- <a href="doc/errors.md#api_nan_fatal_exception"><b><code>Nan::FatalException()</code></b></a>
|
||||
- <a href="doc/errors.md#api_nan_errno_exception"><b><code>Nan::ErrnoException()</code></b></a>
|
||||
- <a href="doc/errors.md#api_nan_try_catch"><b><code>Nan::TryCatch</code></b></a>
|
||||
|
||||
|
||||
### Buffers
|
||||
|
||||
NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility.
|
||||
|
||||
- <a href="doc/buffers.md#api_nan_new_buffer"><b><code>Nan::NewBuffer()</code></b></a>
|
||||
- <a href="doc/buffers.md#api_nan_copy_buffer"><b><code>Nan::CopyBuffer()</code></b></a>
|
||||
- <a href="doc/buffers.md#api_nan_free_callback"><b><code>Nan::FreeCallback()</code></b></a>
|
||||
|
||||
### Nan::Callback
|
||||
|
||||
`Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution.
|
||||
|
||||
- <a href="doc/callback.md#api_nan_callback"><b><code>Nan::Callback</code></b></a>
|
||||
|
||||
### Asynchronous work helpers
|
||||
|
||||
`Nan::AsyncWorker` and `Nan::AsyncProgressWorker` are helper classes that make working with asynchronous code easier.
|
||||
|
||||
- <a href="doc/asyncworker.md#api_nan_async_worker"><b><code>Nan::AsyncWorker</code></b></a>
|
||||
- <a href="doc/asyncworker.md#api_nan_async_progress_worker"><b><code>Nan::AsyncProgressWorker</code></b></a>
|
||||
- <a href="doc/asyncworker.md#api_nan_async_queue_worker"><b><code>Nan::AsyncQueueWorker</code></b></a>
|
||||
|
||||
### Strings & Bytes
|
||||
|
||||
Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing.
|
||||
|
||||
- <a href="doc/string_bytes.md#api_nan_encoding"><b><code>Nan::Encoding</code></b></a>
|
||||
- <a href="doc/string_bytes.md#api_nan_encode"><b><code>Nan::Encode()</code></b></a>
|
||||
- <a href="doc/string_bytes.md#api_nan_decode_bytes"><b><code>Nan::DecodeBytes()</code></b></a>
|
||||
- <a href="doc/string_bytes.md#api_nan_decode_write"><b><code>Nan::DecodeWrite()</code></b></a>
|
||||
|
||||
|
||||
### V8 internals
|
||||
|
||||
The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods.
|
||||
|
||||
- <a href="doc/v8_internals.md#api_nan_gc_callback"><b><code>NAN_GC_CALLBACK()</code></b></a>
|
||||
- <a href="doc/v8_internals.md#api_nan_add_gc_epilogue_callback"><b><code>Nan::AddGCEpilogueCallback()</code></b></a>
|
||||
- <a href="doc/v8_internals.md#api_nan_remove_gc_epilogue_callback"><b><code>Nan::RemoveGCEpilogueCallback()</code></b></a>
|
||||
- <a href="doc/v8_internals.md#api_nan_add_gc_prologue_callback"><b><code>Nan::AddGCPrologueCallback()</code></b></a>
|
||||
- <a href="doc/v8_internals.md#api_nan_remove_gc_prologue_callback"><b><code>Nan::RemoveGCPrologueCallback()</code></b></a>
|
||||
- <a href="doc/v8_internals.md#api_nan_get_heap_statistics"><b><code>Nan::GetHeapStatistics()</code></b></a>
|
||||
- <a href="doc/v8_internals.md#api_nan_set_counter_function"><b><code>Nan::SetCounterFunction()</code></b></a>
|
||||
- <a href="doc/v8_internals.md#api_nan_set_create_histogram_function"><b><code>Nan::SetCreateHistogramFunction()</code></b></a>
|
||||
- <a href="doc/v8_internals.md#api_nan_set_add_histogram_sample_function"><b><code>Nan::SetAddHistogramSampleFunction()</code></b></a>
|
||||
- <a href="doc/v8_internals.md#api_nan_idle_notification"><b><code>Nan::IdleNotification()</code></b></a>
|
||||
- <a href="doc/v8_internals.md#api_nan_low_memory_notification"><b><code>Nan::LowMemoryNotification()</code></b></a>
|
||||
- <a href="doc/v8_internals.md#api_nan_context_disposed_notification"><b><code>Nan::ContextDisposedNotification()</code></b></a>
|
||||
- <a href="doc/v8_internals.md#api_nan_get_internal_field_pointer"><b><code>Nan::GetInternalFieldPointer()</code></b></a>
|
||||
- <a href="doc/v8_internals.md#api_nan_set_internal_field_pointer"><b><code>Nan::SetInternalFieldPointer()</code></b></a>
|
||||
- <a href="doc/v8_internals.md#api_nan_adjust_external_memory"><b><code>Nan::AdjustExternalMemory()</code></b></a>
|
||||
|
||||
|
||||
### Miscellaneous V8 Helpers
|
||||
|
||||
- <a href="doc/v8_misc.md#api_nan_utf8_string"><b><code>Nan::Utf8String</code></b></a>
|
||||
- <a href="doc/v8_misc.md#api_nan_get_current_context"><b><code>Nan::GetCurrentContext()</code></b></a>
|
||||
- <a href="doc/v8_misc.md#api_nan_set_isolate_data"><b><code>Nan::SetIsolateData()</code></b></a>
|
||||
- <a href="doc/v8_misc.md#api_nan_get_isolate_data"><b><code>Nan::GetIsolateData()</code></b></a>
|
||||
|
||||
|
||||
### Miscellaneous Node Helpers
|
||||
|
||||
- <a href="doc/node_misc.md#api_nan_make_callback"><b><code>Nan::MakeCallback()</code></b></a>
|
||||
- <a href="doc/node_misc.md#api_nan_object_wrap"><b><code>Nan::ObjectWrap</code></b></a>
|
||||
- <a href="doc/node_misc.md#api_nan_module_init"><b><code>NAN_MODULE_INIT()</code></b></a>
|
||||
- <a href="doc/node_misc.md#api_nan_export"><b><code>Nan::Export()</code></b></a>
|
||||
|
||||
<!-- END API -->
|
||||
|
||||
|
||||
<a name="tests"></a>
|
||||
### Tests
|
||||
|
||||
To run the NAN tests do:
|
||||
|
||||
``` sh
|
||||
npm install
|
||||
npm run-script rebuild-tests
|
||||
npm test
|
||||
```
|
||||
|
||||
Or just:
|
||||
|
||||
``` sh
|
||||
npm install
|
||||
make test
|
||||
```
|
||||
|
||||
<a name="governance"></a>
|
||||
## Governance & Contributing
|
||||
|
||||
NAN is governed by the [io.js](https://iojs.org/) Addon API Working Group
|
||||
|
||||
### Addon API Working Group (WG)
|
||||
|
||||
The NAN project is jointly governed by a Working Group which is responsible for high-level guidance of the project.
|
||||
|
||||
Members of the WG are also known as Collaborators, there is no distinction between the two, unlike other io.js projects.
|
||||
|
||||
The WG has final authority over this project including:
|
||||
|
||||
* Technical direction
|
||||
* Project governance and process (including this policy)
|
||||
* Contribution policy
|
||||
* GitHub repository hosting
|
||||
* Maintaining the list of additional Collaborators
|
||||
|
||||
For the current list of WG members, see the project [README.md](./README.md#collaborators).
|
||||
|
||||
Individuals making significant and valuable contributions are made members of the WG and given commit-access to the project. These individuals are identified by the WG and their addition to the WG is discussed via GitHub and requires unanimous consensus amongst those WG members participating in the discussion with a quorum of 50% of WG members required for acceptance of the vote.
|
||||
|
||||
_Note:_ If you make a significant contribution and are not considered for commit-access log an issue or contact a WG member directly.
|
||||
|
||||
For the current list of WG members / Collaborators, see the project [README.md](./README.md#collaborators).
|
||||
|
||||
### Consensus Seeking Process
|
||||
|
||||
The WG follows a [Consensus Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) decision making model.
|
||||
|
||||
Modifications of the contents of the NAN repository are made on a collaborative basis. Anybody with a GitHub account may propose a modification via pull request and it will be considered by the WG. All pull requests must be reviewed and accepted by a WG member with sufficient expertise who is able to take full responsibility for the change. In the case of pull requests proposed by an existing WG member, an additional WG member is required for sign-off. Consensus should be sought if additional WG members participate and there is disagreement around a particular modification.
|
||||
|
||||
If a change proposal cannot reach a consensus, a WG member can call for a vote amongst the members of the WG. Simple majority wins.
|
||||
|
||||
### Developer's Certificate of Origin 1.0
|
||||
|
||||
By making a contribution to this project, I certify that:
|
||||
|
||||
* (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or
|
||||
* (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or
|
||||
* (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it.
|
||||
|
||||
<a name="collaborators"></a>
|
||||
### WG Members / Collaborators
|
||||
|
||||
<table><tbody>
|
||||
<tr><th align="left">Rod Vagg</th><td><a href="https://github.com/rvagg">GitHub/rvagg</a></td><td><a href="http://twitter.com/rvagg">Twitter/@rvagg</a></td></tr>
|
||||
<tr><th align="left">Benjamin Byholm</th><td><a href="https://github.com/kkoopa/">GitHub/kkoopa</a></td><td>-</td></tr>
|
||||
<tr><th align="left">Trevor Norris</th><td><a href="https://github.com/trevnorris">GitHub/trevnorris</a></td><td><a href="http://twitter.com/trevnorris">Twitter/@trevnorris</a></td></tr>
|
||||
<tr><th align="left">Nathan Rajlich</th><td><a href="https://github.com/TooTallNate">GitHub/TooTallNate</a></td><td><a href="http://twitter.com/TooTallNate">Twitter/@TooTallNate</a></td></tr>
|
||||
<tr><th align="left">Brett Lawson</th><td><a href="https://github.com/brett19">GitHub/brett19</a></td><td><a href="http://twitter.com/brett19x">Twitter/@brett19x</a></td></tr>
|
||||
<tr><th align="left">Ben Noordhuis</th><td><a href="https://github.com/bnoordhuis">GitHub/bnoordhuis</a></td><td><a href="http://twitter.com/bnoordhuis">Twitter/@bnoordhuis</a></td></tr>
|
||||
<tr><th align="left">David Siegel</th><td><a href="https://github.com/agnat">GitHub/agnat</a></td><td>-</td></tr>
|
||||
</tbody></table>
|
||||
|
||||
## Licence & copyright
|
||||
|
||||
Copyright (c) 2015 NAN WG Members / Collaborators (listed above).
|
||||
|
||||
Native Abstractions for Node.js is licensed under an MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details.
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
# http://www.appveyor.com/docs/appveyor-yml
|
||||
|
||||
# Test against these versions of Io.js and Node.js.
|
||||
environment:
|
||||
matrix:
|
||||
# node.js
|
||||
- nodejs_version: "0.8"
|
||||
- nodejs_version: "0.10"
|
||||
- nodejs_version: "0.12"
|
||||
# io.js
|
||||
- nodejs_version: "1"
|
||||
- nodejs_version: "2"
|
||||
- nodejs_version: "3"
|
||||
|
||||
# Install scripts. (runs after repo cloning)
|
||||
install:
|
||||
# Get the latest stable version of Node 0.STABLE.latest
|
||||
- ps: if($env:nodejs_version -eq "0.8") {Install-Product node $env:nodejs_version}
|
||||
- ps: if($env:nodejs_version -ne "0.8") {Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version)}
|
||||
- IF %nodejs_version% LSS 1 npm -g install npm
|
||||
- IF %nodejs_version% LSS 1 set PATH=%APPDATA%\npm;%PATH%
|
||||
# Typical npm stuff.
|
||||
- npm install
|
||||
- IF %nodejs_version% EQU 0.8 (node node_modules\node-gyp\bin\node-gyp.js rebuild --msvs_version=2013 --directory test) ELSE (npm run rebuild-tests)
|
||||
|
||||
# Post-install test scripts.
|
||||
test_script:
|
||||
# Output useful info for debugging.
|
||||
- node --version
|
||||
- npm --version
|
||||
# run tests
|
||||
- IF %nodejs_version% LSS 1 (npm test) ELSE (iojs node_modules\tap\bin\tap.js --gc test/js/*-test.js)
|
||||
|
||||
# Don't actually build.
|
||||
build: off
|
||||
|
||||
# Set build version format here instead of in the admin panel.
|
||||
version: "{build}"
|
||||
Generated
Vendored
+38
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
files=" \
|
||||
methods.md \
|
||||
scopes.md \
|
||||
persistent.md \
|
||||
new.md \
|
||||
converters.md \
|
||||
maybe_types.md \
|
||||
script.md \
|
||||
errors.md \
|
||||
buffers.md \
|
||||
callback.md \
|
||||
asyncworker.md \
|
||||
string_bytes.md \
|
||||
v8_internals.md \
|
||||
v8_misc.md \
|
||||
node_misc.md \
|
||||
"
|
||||
|
||||
__dirname=$(dirname "${BASH_SOURCE[0]}")
|
||||
head=$(perl -e 'while (<>) { if (!$en){print;} if ($_=~/<!-- START/){$en=1} };' $__dirname/../README.md)
|
||||
tail=$(perl -e 'while (<>) { if ($_=~/<!-- END/){$st=1} if ($st){print;} };' $__dirname/../README.md)
|
||||
apidocs=$(for f in $files; do
|
||||
perl -pe '
|
||||
last if /^<a name/;
|
||||
$_ =~ s/^## /### /;
|
||||
$_ =~ s/<a href="#/<a href="doc\/'$f'#/;
|
||||
' $__dirname/$f;
|
||||
done)
|
||||
|
||||
cat > $__dirname/../README.md << EOF
|
||||
$head
|
||||
|
||||
$apidocs
|
||||
|
||||
$tail
|
||||
EOF
|
||||
Generated
Vendored
+97
@@ -0,0 +1,97 @@
|
||||
## Asynchronous work helpers
|
||||
|
||||
`Nan::AsyncWorker` and `Nan::AsyncProgressWorker` are helper classes that make working with asynchronous code easier.
|
||||
|
||||
- <a href="#api_nan_async_worker"><b><code>Nan::AsyncWorker</code></b></a>
|
||||
- <a href="#api_nan_async_progress_worker"><b><code>Nan::AsyncProgressWorker</code></b></a>
|
||||
- <a href="#api_nan_async_queue_worker"><b><code>Nan::AsyncQueueWorker</code></b></a>
|
||||
|
||||
<a name="api_nan_async_worker"></a>
|
||||
### Nan::AsyncWorker
|
||||
|
||||
`Nan::AsyncWorker` is an _abstract_ class that you can subclass to have much of the annoying asynchronous queuing and handling taken care of for you. It can even store arbitrary V8 objects for you and have them persist while the asynchronous work is in progress.
|
||||
|
||||
Definition:
|
||||
|
||||
```c++
|
||||
class AsyncWorker {
|
||||
public:
|
||||
explicit AsyncWorker(Callback *callback_);
|
||||
|
||||
virtual ~AsyncWorker();
|
||||
|
||||
virtual void WorkComplete();
|
||||
|
||||
void SaveToPersistent(const char *key, const v8::Local<v8::Value> &value);
|
||||
|
||||
void SaveToPersistent(const v8::Local<v8::String> &key,
|
||||
const v8::Local<v8::Value> &value);
|
||||
|
||||
void SaveToPersistent(uint32_t index,
|
||||
const v8::Local<v8::Value> &value);
|
||||
|
||||
v8::Local<v8::Value> GetFromPersistent(const char *key) const;
|
||||
|
||||
v8::Local<v8::Value> GetFromPersistent(const v8::Local<v8::String> &key) const;
|
||||
|
||||
v8::Local<v8::Value> GetFromPersistent(uint32_t index) const;
|
||||
|
||||
virtual void Execute() = 0;
|
||||
|
||||
uv_work_t request;
|
||||
|
||||
virtual void Destroy();
|
||||
|
||||
protected:
|
||||
Persistent<v8::Object> persistentHandle;
|
||||
|
||||
Callback *callback;
|
||||
|
||||
virtual void HandleOKCallback();
|
||||
|
||||
virtual void HandleErrorCallback();
|
||||
|
||||
void SetErrorMessage(const char *msg);
|
||||
|
||||
const char* ErrorMessage();
|
||||
};
|
||||
```
|
||||
|
||||
<a name="api_nan_async_progress_worker"></a>
|
||||
### Nan::AsyncProgressWorker
|
||||
|
||||
`Nan::AsyncProgressWorker` is an _abstract_ class that extends `Nan::AsyncWorker` and adds additional progress reporting callbacks that can be used during the asynchronous work execution to provide progress data back to JavaScript.
|
||||
|
||||
Definition:
|
||||
|
||||
```c++
|
||||
class AsyncProgressWorker : public AsyncWorker {
|
||||
public:
|
||||
explicit AsyncProgressWorker(Callback *callback_);
|
||||
|
||||
virtual ~AsyncProgressWorker();
|
||||
|
||||
void WorkProgress();
|
||||
|
||||
class ExecutionProgress {
|
||||
public:
|
||||
void Send(const char* data, size_t size) const;
|
||||
};
|
||||
|
||||
virtual void Execute(const ExecutionProgress& progress) = 0;
|
||||
|
||||
virtual void HandleProgressCallback(const char *data, size_t size) = 0;
|
||||
|
||||
virtual void Destroy();
|
||||
```
|
||||
|
||||
<a name="api_nan_async_queue_worker"></a>
|
||||
### Nan::AsyncQueueWorker
|
||||
|
||||
`Nan::AsyncQueueWorker` will run a `Nan::AsyncWorker` asynchronously via libuv. Both the `execute` and `after_work` steps are taken care of for you. Most of the logic for this is embedded in `Nan::AsyncWorker`.
|
||||
|
||||
Definition:
|
||||
|
||||
```c++
|
||||
void AsyncQueueWorker(AsyncWorker *);
|
||||
```
|
||||
Generated
Vendored
+54
@@ -0,0 +1,54 @@
|
||||
## Buffers
|
||||
|
||||
NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility.
|
||||
|
||||
- <a href="#api_nan_new_buffer"><b><code>Nan::NewBuffer()</code></b></a>
|
||||
- <a href="#api_nan_copy_buffer"><b><code>Nan::CopyBuffer()</code></b></a>
|
||||
- <a href="#api_nan_free_callback"><b><code>Nan::FreeCallback()</code></b></a>
|
||||
|
||||
<a name="api_nan_new_buffer"></a>
|
||||
### Nan::NewBuffer()
|
||||
|
||||
Allocate a new `node::Buffer` object with the specified size and optional data. Calls `node::Buffer::New()`.
|
||||
|
||||
Note that when creating a `Buffer` using `Nan::NewBuffer()` and an existing `char*`, it is assumed that the ownership of the pointer is being transferred to the new `Buffer` for management.
|
||||
When a `node::Buffer` instance is garbage collected and a `FreeCallback` has not been specified, `data` will be disposed of via a call to `free()`.
|
||||
You _must not_ free the memory space manually once you have created a `Buffer` in this way.
|
||||
|
||||
Signature:
|
||||
|
||||
```c++
|
||||
Nan::MaybeLocal<v8::Object> Nan::NewBuffer(uint32_t size)
|
||||
Nan::MaybeLocal<v8::Object> Nan::NewBuffer(char* data, uint32_t size)
|
||||
Nan::MaybeLocal<v8::Object> Nan::NewBuffer(char *data,
|
||||
size_t length,
|
||||
Nan::FreeCallback callback,
|
||||
void *hint)
|
||||
```
|
||||
|
||||
|
||||
<a name="api_nan_copy_buffer"></a>
|
||||
### Nan::CopyBuffer()
|
||||
|
||||
Similar to [`Nan::NewBuffer()`](#api_nan_new_buffer) except that an implicit memcpy will occur within Node. Calls `node::Buffer::Copy()`.
|
||||
|
||||
Management of the `char*` is left to the user, you should manually free the memory space if necessary as the new `Buffer` will have its own copy.
|
||||
|
||||
Signature:
|
||||
|
||||
```c++
|
||||
Nan::MaybeLocal<v8::Object> Nan::CopyBuffer(const char *data, uint32_t size)
|
||||
```
|
||||
|
||||
|
||||
<a name="api_nan_free_callback"></a>
|
||||
### Nan::FreeCallback()
|
||||
|
||||
A free callback that can be provided to [`Nan::NewBuffer()`](#api_nan_new_buffer).
|
||||
The supplied callback will be invoked when the `Buffer` undergoes garbage collection.
|
||||
|
||||
Signature:
|
||||
|
||||
```c++
|
||||
typedef void (*FreeCallback)(char *data, void *hint);
|
||||
```
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user