From 1b7203d4fd38de4de44ecc254688ed170c9df447 Mon Sep 17 00:00:00 2001 From: mrq Date: Sat, 21 Nov 2020 00:00:00 -0600 Subject: [PATCH] Commit for 2020.11.21.7z --- client/client/ext.cpp | 13 +- .../uf/engine/instantiator/instantiator.inl | 2 + engine/inc/uf/ext/assimp/assimp.h | 17 - engine/inc/uf/ext/gltf/gltf.h | 14 +- engine/inc/uf/ext/gltf/mesh.h | 73 ++ engine/inc/uf/ext/vulkan/device.h | 22 +- engine/inc/uf/ext/vulkan/graphic.h | 3 +- engine/inc/uf/ext/vulkan/rendermode.h | 3 +- engine/inc/uf/spec/window/universal.h | 22 +- engine/inc/uf/utils/component/component.inl | 12 +- engine/inc/uf/utils/hook/function_traits.inl | 57 + engine/inc/uf/utils/hook/hook.h | 74 +- engine/inc/uf/utils/hook/hook.inl | 52 + engine/inc/uf/utils/image/atlas.h | 34 +- engine/inc/uf/utils/image/image.h | 3 + engine/inc/uf/utils/mempool/mempool.inl | 7 +- engine/inc/uf/utils/serialize/serializer.h | 1 + engine/inc/uf/utils/thread/perthread.h | 22 + engine/inc/uf/utils/thread/perthread.inl | 12 + engine/inc/uf/utils/type/type.h | 44 + engine/inc/uf/utils/type/type.inl | 12 + engine/inc/uf/utils/userdata/userdata.h | 22 +- engine/inc/uf/utils/userdata/userdata.inl | 39 +- engine/src/engine/asset/asset.cpp | 3 +- engine/src/engine/behavior/behavior.cpp | 27 +- .../src/engine/instantiator/instantiator.cpp | 3 +- engine/src/engine/object/behavior.cpp | 9 + engine/src/engine/object/behaviors/gltf.cpp | 5 +- engine/src/engine/object/object.cpp | 30 +- engine/src/ext/assimp/assimp.cpp | 296 ----- engine/src/ext/gltf/gltf.cpp | 1091 ++++++++++++----- engine/src/ext/gltf/mesh.cpp | 46 + engine/src/ext/lua/lua.cpp | 4 +- engine/src/ext/vulkan/buffer.cpp | 2 +- engine/src/ext/vulkan/device.cpp | 48 +- engine/src/ext/vulkan/graphic.cpp | 21 + engine/src/ext/vulkan/rendermode.cpp | 6 +- engine/src/spec/window/universal.cpp | 33 +- engine/src/spec/window/windows.cpp | 62 +- engine/src/utils/hook/hook.cpp | 83 +- engine/src/utils/image/atlas.cpp | 225 +++- engine/src/utils/image/image.cpp | 14 + engine/src/utils/mempool/mempool.cpp | 30 +- engine/src/utils/serialize/serializer.cpp | 16 + engine/src/utils/type/type.cpp | 50 + engine/src/utils/userdata/userdata.cpp | 151 +-- engine/src/utils/window/window.cpp | 11 +- ext/behaviors/player/behavior.cpp | 1 + ext/behaviors/scene/behavior.cpp | 8 +- ext/gui/behavior.cpp | 170 +-- ext/gui/manager/behavior.cpp | 8 +- ext/main.cpp | 11 +- ext/scenes/worldscape/gui/dialogue.cpp | 2 +- 53 files changed, 2074 insertions(+), 952 deletions(-) delete mode 100644 engine/inc/uf/ext/assimp/assimp.h create mode 100644 engine/inc/uf/ext/gltf/mesh.h create mode 100644 engine/inc/uf/utils/hook/function_traits.inl create mode 100644 engine/inc/uf/utils/hook/hook.inl create mode 100644 engine/inc/uf/utils/thread/perthread.h create mode 100644 engine/inc/uf/utils/thread/perthread.inl create mode 100644 engine/inc/uf/utils/type/type.h create mode 100644 engine/inc/uf/utils/type/type.inl delete mode 100644 engine/src/ext/assimp/assimp.cpp create mode 100644 engine/src/ext/gltf/mesh.cpp create mode 100644 engine/src/utils/type/type.cpp diff --git a/client/client/ext.cpp b/client/client/ext.cpp index 661fccc9..9e048078 100644 --- a/client/client/ext.cpp +++ b/client/client/ext.cpp @@ -84,8 +84,12 @@ void client::initialize() { json["window"]["title"] = std::string(title); uf::hooks.call( hook, json ); } + /* uf::hooks.shouldPreferReadable(); - if ( client::config["engine"]["hook"]["mode"] == "Readable" ) {} + if ( client::config["engine"]["hook"]["mode"] == "Readable" ) { + + } + */ } /* Initialize OpenAL */ { @@ -97,7 +101,7 @@ void client::initialize() { } /* Initialize hooks */ { - if ( client::config["engine"]["hook"]["mode"] == "Both" || client::config["engine"]["hook"]["mode"] == "Readable" ) { + // if ( client::config["engine"]["hook"]["mode"] == "Both" || client::config["engine"]["hook"]["mode"] == "Readable" ) { uf::hooks.addHook( "window:Mouse.CursorVisibility", [&](const std::string& event)->std::string{ uf::Serializer json = event; client::window.setCursorVisible(json["state"].as()); @@ -146,7 +150,9 @@ void client::initialize() { uf::renderer::states::resized = true; return "true"; } ); - } else if ( client::config["engine"]["hook"]["mode"] == "Both" || client::config["engine"]["hook"]["mode"] == "Optimal" ) { + /* + } + else if ( client::config["engine"]["hook"]["mode"] == "Both" || client::config["engine"]["hook"]["mode"] == "Optimal" ) { uf::hooks.addHook( "window:Closed", [&](const uf::OptimalHook::argument_t& userdata)->uf::OptimalHook::return_t{ client::ready = false; std::exit(EXIT_SUCCESS); @@ -187,6 +193,7 @@ void client::initialize() { return NULL; } ); } + */ } if ( client::config["window"]["mode"].as() == "fullscreen" ) client::window.switchToFullscreen(); if ( client::config["window"]["mode"].as() == "borderless" ) client::window.switchToFullscreen( true ); diff --git a/engine/inc/uf/engine/instantiator/instantiator.inl b/engine/inc/uf/engine/instantiator/instantiator.inl index 539d7f29..7b7dcbbf 100644 --- a/engine/inc/uf/engine/instantiator/instantiator.inl +++ b/engine/inc/uf/engine/instantiator/instantiator.inl @@ -1,3 +1,5 @@ +#include + template typename pod::NamedTypes::type_t pod::NamedTypes::getType( const std::string& name ) { for ( auto pair : names ) if ( pair.second == name ) return pair.first; diff --git a/engine/inc/uf/ext/assimp/assimp.h b/engine/inc/uf/ext/assimp/assimp.h deleted file mode 100644 index d91a1699..00000000 --- a/engine/inc/uf/ext/assimp/assimp.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#include -#if defined(UF_USE_ASSIMP) - -#include -#include -#include - -namespace ext { - namespace assimp { - UF_API bool load( const std::string&, uf::Mesh&, bool = false ); - UF_API bool load( const std::string&, uf::SkeletalMesh&, bool = false ); - } -} - -#endif \ No newline at end of file diff --git a/engine/inc/uf/ext/gltf/gltf.h b/engine/inc/uf/ext/gltf/gltf.h index 60453579..c4a35ca4 100644 --- a/engine/inc/uf/ext/gltf/gltf.h +++ b/engine/inc/uf/ext/gltf/gltf.h @@ -1,11 +1,14 @@ #pragma once +#include "mesh.h" #include -#include namespace ext { - namespace gltf { - typedef uf::BaseMesh mesh_t; + namespace gltf { + // typedef uf::BaseMesh mesh_t; + typedef uf::BaseMesh mesh_t; + typedef uf::BaseMesh skinned_mesh_t; + enum LoadMode { GENERATE_NORMALS = 0x1 << 0, APPLY_TRANSFORMS = 0x1 << 1, @@ -15,7 +18,10 @@ namespace ext { AABB = 0x1 << 5, DEFER_INIT = 0x1 << 6, USE_ATLAS = 0x1 << 7, + SKINNED = 0x1 << 8, }; - bool UF_API load( uf::Object&, const std::string&, uint8_t = LoadMode::GENERATE_NORMALS | LoadMode::RENDER ); + typedef uint16_t load_mode_t; + + bool UF_API load( uf::Object&, const std::string&, ext::gltf::load_mode_t = LoadMode::GENERATE_NORMALS | LoadMode::RENDER ); } } \ No newline at end of file diff --git a/engine/inc/uf/ext/gltf/mesh.h b/engine/inc/uf/ext/gltf/mesh.h new file mode 100644 index 00000000..5c1e10b7 --- /dev/null +++ b/engine/inc/uf/ext/gltf/mesh.h @@ -0,0 +1,73 @@ +#pragma once + +#include + +namespace ext { + namespace gltf { + namespace mesh { + struct ID { + alignas(16) pod::Vector3f position; + alignas(8) pod::Vector2f uv; + alignas(16) pod::Vector3f normal; + alignas(4) uint32_t id; + + static UF_API std::vector descriptor; + + bool operator==( const ID& that ) const { + return this->position == that.position && + this->normal == that.normal && + this->uv == that.uv && + this->id == that.id; + } + bool operator!=( const ID& that ) const { return !(*this == that); } + }; + struct Skinned { + alignas(16) pod::Vector3f position; + alignas(8) pod::Vector2f uv; + alignas(16) pod::Vector3f normal; + alignas(4) uint32_t id; + alignas(16) pod::Vector4ui joints; + alignas(16) pod::Vector4f weights; + + static UF_API std::vector descriptor; + + bool operator==( const Skinned& that ) const { + return this->position == that.position && + this->normal == that.normal && + this->uv == that.uv && + this->joints == that.joints && + this->weights == that.weights && + this->id == that.id; + } + bool operator!=( const Skinned& that ) const { return !(*this == that); } + }; + } + } +} + +namespace std { + template<> struct hash { + size_t operator()(ext::gltf::mesh::ID const& vertex) const { + std::size_t seed = 3 + 2 + 3 + 1; + std::hash hasher; + for ( size_t i = 0; i < 3; ++i ) seed ^= hasher( vertex.position[i] ) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + for ( size_t i = 0; i < 3; ++i ) seed ^= hasher( vertex.normal[i] ) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + for ( size_t i = 0; i < 2; ++i ) seed ^= hasher( vertex.uv[i] ) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + seed ^= hasher( (float) vertex.id ) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + return seed; + } + }; + template<> struct hash { + size_t operator()(ext::gltf::mesh::Skinned const& vertex) const { + std::size_t seed = 3 + 2 + 3 + 4 + 4 + 1; + std::hash hasher; + for ( size_t i = 0; i < 3; ++i ) seed ^= hasher( vertex.position[i] ) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + for ( size_t i = 0; i < 3; ++i ) seed ^= hasher( vertex.normal[i] ) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + for ( size_t i = 0; i < 2; ++i ) seed ^= hasher( vertex.uv[i] ) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + for ( size_t i = 0; i < 4; ++i ) seed ^= hasher( (float) vertex.joints[i] ) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + for ( size_t i = 0; i < 4; ++i ) seed ^= hasher( vertex.weights[i] ) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + seed ^= hasher( (float) vertex.id ) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + return seed; + } + }; +} \ No newline at end of file diff --git a/engine/inc/uf/ext/vulkan/device.h b/engine/inc/uf/ext/vulkan/device.h index 8f421abe..14691e30 100644 --- a/engine/inc/uf/ext/vulkan/device.h +++ b/engine/inc/uf/ext/vulkan/device.h @@ -4,6 +4,7 @@ #include #include #include +#include namespace ext { namespace vulkan { @@ -14,9 +15,12 @@ namespace ext { VkPhysicalDevice physicalDevice; VkDevice logicalDevice; struct { - std::unordered_map graphics; - std::unordered_map compute; - std::unordered_map transfer; + // std::unordered_map graphics; + // std::unordered_map compute; + // std::unordered_map transfer; + uf::ThreadUnique graphics; + uf::ThreadUnique compute; + uf::ThreadUnique transfer; } commandPool; VkPhysicalDeviceProperties properties; @@ -43,10 +47,14 @@ namespace ext { std::vector queueFamilyProperties; struct { - std::unordered_map graphics; - std::unordered_map present; - std::unordered_map compute; - std::unordered_map transfer; + // std::unordered_map graphics; + // std::unordered_map present; + // std::unordered_map compute; + // std::unordered_map transfer; + uf::ThreadUnique graphics; + uf::ThreadUnique present; + uf::ThreadUnique compute; + uf::ThreadUnique transfer; } queues; uf::Window* window; diff --git a/engine/inc/uf/ext/vulkan/graphic.h b/engine/inc/uf/ext/vulkan/graphic.h index a0d94a36..d746b564 100644 --- a/engine/inc/uf/ext/vulkan/graphic.h +++ b/engine/inc/uf/ext/vulkan/graphic.h @@ -44,14 +44,13 @@ namespace ext { VkSpecializationInfo specializationInfo; std::vector pushConstants; - // std::vector specializationConstants; - // uf::Userdata specializationConstants; std::vector specializationConstants; std::vector uniforms; // ~Shader(); void initialize( Device& device, const std::string&, VkShaderStageFlagBits ); void destroy(); + bool validate(); }; struct UF_API Pipeline { bool aliased = false; diff --git a/engine/inc/uf/ext/vulkan/rendermode.h b/engine/inc/uf/ext/vulkan/rendermode.h index d6e1f016..2e4e9ac9 100644 --- a/engine/inc/uf/ext/vulkan/rendermode.h +++ b/engine/inc/uf/ext/vulkan/rendermode.h @@ -20,7 +20,8 @@ namespace ext { typedef std::vector commands_container_t; std::thread::id mostRecentCommandPoolId; - std::unordered_map commands; + // std::unordered_map commands; + uf::ThreadUnique commands; virtual ~RenderMode(); // RAII diff --git a/engine/inc/uf/spec/window/universal.h b/engine/inc/uf/spec/window/universal.h index 44668825..4591809d 100644 --- a/engine/inc/uf/spec/window/universal.h +++ b/engine/inc/uf/spec/window/universal.h @@ -20,36 +20,35 @@ namespace spec { typedef uf::String title_t; typedef pod::Vector2i vector_t; + /* struct Events { template struct Type { typedef typename Hook::argument_t Argument; typedef typename Hook::return_t Return; typedef typename Hook::name_t Name; + typedef Argument argument_t; typedef Return return_t; typedef Name name_t; + struct Event { Name name; Argument argument; }; - typedef std::queue events_t; }; Type::events_t readable; Type::events_t optimal; }; - protected: - Window::Events m_events; - /* + */ struct Event { - std::string name, argument; + std::string name; + uf::Userdata payload; }; - typedef Event event_t; - typedef std::queue events_t; protected: - spec::uni::Window::events_t m_events; - */ + // Window::Events m_events; + std::queue m_events; public: // C-tors /*virtual*/ void UF_API_CALL create( const spec::uni::Window::vector_t& size, const spec::uni::Window::title_t& title = L"Window" ) {} ;// = 0; @@ -75,10 +74,15 @@ namespace spec { /*virtual*/ bool UF_API_CALL hasFocus() const;/* = 0;*/ // Update /*virtual*/ void UF_API_CALL processEvents();/* = 0;*/ + /* void UF_API_CALL pushEvent( const uf::ReadableHook::name_t& name, const uf::ReadableHook::argument_t& argument ); void UF_API_CALL pushEvent( const uf::OptimalHook::name_t& name, const uf::OptimalHook::argument_t& argument ); void UF_API_CALL pushEvent( const uf::ReadableHook::argument_t& serialized ); void UF_API_CALL pushEvent( const uf::OptimalHook::argument_t& userdata ); + */ + void UF_API_CALL pushEvent( const uf::Hooks::name_t& name, const std::string& payload ); + void UF_API_CALL pushEvent( const uf::Hooks::name_t& name, const uf::Hooks::argument_t& payload ); + void UF_API_CALL pushEvent( const uf::Hooks::argument_t& payload ); bool UF_API_CALL pollEvents( bool block = false ); static bool UF_API_CALL isKeyPressed( const std::string& ); }; diff --git a/engine/inc/uf/utils/component/component.inl b/engine/inc/uf/utils/component/component.inl index 41a13d3f..a9a4d4dc 100644 --- a/engine/inc/uf/utils/component/component.inl +++ b/engine/inc/uf/utils/component/component.inl @@ -48,11 +48,7 @@ T* uf::Component::getComponentPointer() { pod::Component::id_t id = this->getType(); pod::Component& component = this->m_container[id]; - try { - pointer = &uf::userdata::get(component.userdata); - } catch ( std::exception& e ) { - return NULL; - } + pointer = &uf::userdata::get(component.userdata); return pointer; } template @@ -62,11 +58,7 @@ const T* uf::Component::getComponentPointer() const { pod::Component::id_t id = this->getType(); const pod::Component& component = this->m_container.at(id); - try { - pointer = &uf::userdata::get(component.userdata); - } catch ( std::exception& e ) { - return NULL; - } + pointer = &uf::userdata::get(component.userdata); return pointer; } template diff --git a/engine/inc/uf/utils/hook/function_traits.inl b/engine/inc/uf/utils/hook/function_traits.inl new file mode 100644 index 00000000..00c838b3 --- /dev/null +++ b/engine/inc/uf/utils/hook/function_traits.inl @@ -0,0 +1,57 @@ +/* +template +struct function_traits; + +template +struct function_traits> { + static const size_t nargs = sizeof...(Args); + + typedef R result_type; + + template + struct arg { + typedef typename std::tuple_element>::type type; + }; +}; +*/ + +// For generic types that are functors, delegate to its 'operator()' +template +struct function_traits : public function_traits {}; + +// for pointers to member function +template +struct function_traits { + //enum { arity = sizeof...(Args) }; + static const size_t arguments = sizeof...(Args); + template + struct Arg { + typedef typename std::tuple_element>::type type; + }; + typedef ReturnType return_type; + typedef std::function type; +}; + +// for pointers to member function +template +struct function_traits { + static const size_t arguments = sizeof...(Args); + template + struct Arg { + typedef typename std::tuple_element>::type type; + }; + typedef ReturnType return_type; + typedef std::function type; +}; + +// for function pointers +template +struct function_traits { + static const size_t arguments = sizeof...(Args); + template + struct Arg { + typedef typename std::tuple_element>::type type; + }; + typedef ReturnType return_type; + typedef std::function type; +}; \ No newline at end of file diff --git a/engine/inc/uf/utils/hook/hook.h b/engine/inc/uf/utils/hook/hook.h index 324107a5..c8ed6e60 100644 --- a/engine/inc/uf/utils/hook/hook.h +++ b/engine/inc/uf/utils/hook/hook.h @@ -9,6 +9,7 @@ #include // std::vector #include // std::unordered_map +#if 0 namespace pod { template struct UF_API Hook { @@ -112,4 +113,75 @@ namespace uf { }; extern UF_API uf::HookHandler hooks; -} \ No newline at end of file +} +#endif + + +#include +#include +#include + +namespace pod { + struct UF_API Hook { + typedef std::function function_t; + + size_t uid; + size_t type; + function_t callback; + }; +} + +namespace uf { + class UF_API Hooks { + public: + typedef std::vector hooks_t; + typedef std::unordered_map container_t; + + typedef std::string name_t; + typedef uf::Userdata argument_t; + typedef std::vector return_t; + protected: + static size_t uids; + uf::Hooks::container_t m_container; + public: + bool exists( const name_t& name ); + size_t addHook( const name_t& name, const pod::Hook::function_t& callback, size_t type = 0 ); + void removeHook( const name_t& name, size_t uid ); + return_t call( const name_t& name, const argument_t& payload ); + + return_t call( const name_t& name, const std::string& = "" ); + return_t call( const name_t& name, const uf::Serializer& ); + + size_t addHook( const name_t& name, const std::function& callback ); + /* + size_t addHook( const name_t& name, const std::function& callback ); + size_t addHook( const name_t& name, const std::function& callback ); + */ + template + size_t addHook( const uf::Hooks::name_t& name, const std::function& callback ); + template + size_t addHook( const uf::Hooks::name_t& name, const std::function& callback ); + /* + template + size_t addHook( const uf::Hooks::name_t& name, const std::function& callback ); + */ + template + size_t addHook( const uf::Hooks::name_t& name, const Function& lambda ); + + template + return_t call( const name_t& name, const T& payload ); + }; + + extern UF_API uf::Hooks hooks; +} + +namespace uf { + namespace HookHandler { + namespace Readable { + typedef std::function function_t; + } + } +} + +#include "function_traits.inl" +#include "hook.inl" \ No newline at end of file diff --git a/engine/inc/uf/utils/hook/hook.inl b/engine/inc/uf/utils/hook/hook.inl new file mode 100644 index 00000000..a638c75a --- /dev/null +++ b/engine/inc/uf/utils/hook/hook.inl @@ -0,0 +1,52 @@ +template +size_t uf::Hooks::addHook( const uf::Hooks::name_t& name, const std::function& callback ) { + typedef typename std::remove_reference::type Argument; + return addHook(name, [=]( const uf::Userdata& userdata ){ + uf::Userdata ret; + + const Argument& payload = userdata.is() ? userdata.get() : Argument{}; + callback( payload ); + + return ret; + }, typeid(callback).hash_code()); +} +template +size_t uf::Hooks::addHook( const uf::Hooks::name_t& name, const std::function& callback ) { + typedef typename std::remove_reference::type Argument; + return addHook(name, [=]( const uf::Userdata& userdata ){ + uf::Userdata ret; + const Argument& payload = userdata.is() ? userdata.get() : Argument{}; + + R res = callback( payload ); + ret.create(res); + return ret; + }, typeid(callback).hash_code()); +} +/* +template +size_t uf::Hooks::addHook( const uf::Hooks::name_t& name, const std::function& callback ) { + typedef function_traits Traits; + typedef typename std::remove_reference::type>::type Argument; + return addHook(name, [=]( const uf::Userdata& userdata ){ + uf::Userdata ret; + const Argument& payload = userdata.is() ? userdata.get() : Argument{}; + + R res = callback( payload ); + ret.create(res); + + return ret; + }, typeid(callback).hash_code()); +} +*/ +template +size_t uf::Hooks::addHook( const uf::Hooks::name_t& name, const Function& lambda ) { + typedef function_traits Traits; + typename Traits::type function = lambda; + return addHook(name, function); +} +template +uf::Hooks::return_t uf::Hooks::call( const uf::Hooks::name_t& name, const T& p ) { + uf::Userdata payload; + payload.create(p); + return call( name, payload ); +} \ No newline at end of file diff --git a/engine/inc/uf/utils/image/atlas.h b/engine/inc/uf/utils/image/atlas.h index 9a482e84..6e2b5f19 100644 --- a/engine/inc/uf/utils/image/atlas.h +++ b/engine/inc/uf/utils/image/atlas.h @@ -2,6 +2,7 @@ #include #include +#include namespace uf { class UF_API Atlas { @@ -21,7 +22,7 @@ namespace uf { void addImage( uf::Image&&, bool = false ); void addImage( const uint8_t*, const pod::Vector2ui&, std::size_t, std::size_t, bool = false, bool = false ); - void generate(); + void generate(float padding = 1); void clear(); pod::Vector2f mapUv( const pod::Vector2f&, size_t ); @@ -31,4 +32,35 @@ namespace uf { images_t& getImages(); const images_t& getImages() const; }; + + class UF_API HashAtlas { + public: + typedef std::string hash_t; + typedef std::unordered_map images_t; + + struct Identifier { + hash_t hash; + }; + typedef Identifier identifier_t; + typedef BinPack2D::CanvasArray atlas_t; + protected: + uf::Image m_image; + images_t m_images; + atlas_t m_atlas; + public: + hash_t addImage( const uf::Image&, bool = false ); + hash_t addImage( uf::Image&&, bool = false ); + hash_t addImage( const uint8_t*, const pod::Vector2ui&, std::size_t, std::size_t, bool = false, bool = false ); + + void generate(float padding = 1); + void clear(); + bool has( const uf::Image& ) const; + bool has( const std::string& ) const; + + pod::Vector2f mapUv( const pod::Vector2f&, const hash_t& ); + + uf::Image& getAtlas(); + images_t& getImages(); + const images_t& getImages() const; + }; } \ No newline at end of file diff --git a/engine/inc/uf/utils/image/image.h b/engine/inc/uf/utils/image/image.h index 78070e4d..11005aab 100644 --- a/engine/inc/uf/utils/image/image.h +++ b/engine/inc/uf/utils/image/image.h @@ -48,6 +48,7 @@ namespace uf { std::size_t getBpp() const; std::size_t& getChannels(); std::size_t getChannels() const; + std::string getHash() const; Image::pixel_t at( const Image::vec2_t& at ); // Modifiers void flip(); @@ -57,5 +58,7 @@ namespace uf { Image overlay(const Image& top, const Image::vec2_t& corner = {} ) const; // Merges one image on top of another Image replace(const Image::pixel_t& from, const Image::pixel_t& to ) const; // Changes all pixel from one color (from), to another (to) Image subImage( const Image::vec2_t& start, const Image::vec2_t& end) const; // Crops an image + // Operators + uf::Image& operator=(const uf::Image&); }; } \ No newline at end of file diff --git a/engine/inc/uf/utils/mempool/mempool.inl b/engine/inc/uf/utils/mempool/mempool.inl index 38cc2428..d6b92808 100644 --- a/engine/inc/uf/utils/mempool/mempool.inl +++ b/engine/inc/uf/utils/mempool/mempool.inl @@ -1,10 +1,13 @@ +#include + template T& uf::MemoryPool::alloc( const T& data ) { auto allocation = this->allocate( data ); union { uint8_t* from; T* to; - } static kludge; + } kludge; + kludge.from = (uint8_t*) allocation.pointer; return *kludge.to; } template @@ -14,7 +17,7 @@ pod::Allocation uf::MemoryPool::allocate( const T& data ) { union { uint8_t* from; T* to; - } static kludge; + } kludge; kludge.from = (uint8_t*) allocation.pointer; ::new (kludge.to) T(data); return allocation; diff --git a/engine/inc/uf/utils/serialize/serializer.h b/engine/inc/uf/utils/serialize/serializer.h index 07c5ba84..e017d9f8 100644 --- a/engine/inc/uf/utils/serialize/serializer.h +++ b/engine/inc/uf/utils/serialize/serializer.h @@ -61,6 +61,7 @@ namespace uf { bool writeToFile( const std::string& to ) const; void merge( const uf::Serializer& other, bool priority = true ); + void import( const uf::Serializer& other ); operator Serializer::output_t(); operator Serializer::output_t() const; diff --git a/engine/inc/uf/utils/thread/perthread.h b/engine/inc/uf/utils/thread/perthread.h new file mode 100644 index 00000000..63e9705c --- /dev/null +++ b/engine/inc/uf/utils/thread/perthread.h @@ -0,0 +1,22 @@ +#pragma once + +#include +#include "thread.h" + +namespace uf { + template + class UF_API ThreadUnique { + public: + typedef T type_t; + typedef std::thread::id id_t; + typedef std::unordered_map container_t; + protected: + container_t m_container; + public: + bool has( id_t id = std::this_thread::get_id() ) const; + T& get( id_t id = std::this_thread::get_id() ); + container_t& container(); + }; +} + +#include "perthread.inl" \ No newline at end of file diff --git a/engine/inc/uf/utils/thread/perthread.inl b/engine/inc/uf/utils/thread/perthread.inl new file mode 100644 index 00000000..9fea5b60 --- /dev/null +++ b/engine/inc/uf/utils/thread/perthread.inl @@ -0,0 +1,12 @@ +template +bool uf::ThreadUnique::has( id_t id ) const { + return m_container.count(id) > 0; +} +template +T& uf::ThreadUnique::get( id_t id ) { + return m_container[id]; +} +template +typename uf::ThreadUnique::container_t& uf::ThreadUnique::container() { + return m_container; +} \ No newline at end of file diff --git a/engine/inc/uf/utils/type/type.h b/engine/inc/uf/utils/type/type.h new file mode 100644 index 00000000..795ae656 --- /dev/null +++ b/engine/inc/uf/utils/type/type.h @@ -0,0 +1,44 @@ +#pragma once + +#include +#include +#include + +#define UF_TYPE_REGISTER 1 + +namespace pod { + struct UF_API TypeInfo { + size_t hash; + size_t size; + struct { + std::string pretty; + std::string compiler; + } name; + }; +} +namespace std { + template<> struct hash { + size_t operator()(const pod::TypeInfo& type) const { + return type.hash; + } + }; +} + +namespace uf { + namespace typeInfo { + typedef std::type_index index_t; + typedef pod::TypeInfo type_t; + + extern UF_API std::unordered_map* types; + + void UF_API registerType( const index_t&, size_t = 0, const std::string& = "" ); + const pod::TypeInfo& UF_API getType( size_t ); + const pod::TypeInfo& UF_API getType( const index_t& ); + + template const index_t getIndex(); + template void registerType( const std::string& = "" ); + template const pod::TypeInfo& getType(); + } +} + +#include "type.inl" \ No newline at end of file diff --git a/engine/inc/uf/utils/type/type.inl b/engine/inc/uf/utils/type/type.inl new file mode 100644 index 00000000..e127fc29 --- /dev/null +++ b/engine/inc/uf/utils/type/type.inl @@ -0,0 +1,12 @@ +template +const std::type_index uf::typeInfo::getIndex() { + return typeid(T); +} +template +void uf::typeInfo::registerType( const std::string& pretty ) { + return registerType(getIndex(), sizeof(T), pretty); +} +template +const pod::TypeInfo& uf::typeInfo::getType() { + return getType(getIndex()); +} \ No newline at end of file diff --git a/engine/inc/uf/utils/userdata/userdata.h b/engine/inc/uf/utils/userdata/userdata.h index 05d3fdfc..9ef323f6 100644 --- a/engine/inc/uf/utils/userdata/userdata.h +++ b/engine/inc/uf/utils/userdata/userdata.h @@ -8,13 +8,18 @@ #include #include #include +#include #define UF_USERDATA_POOLED 0 #define UF_USERDATA_KLUDGE 0 +#define UF_USERDATA_RTTI 1 namespace pod { struct UF_API Userdata { std::size_t len = 0; + #if UF_USERDATA_RTTI + std::size_t type; + #endif uint8_t data[1]; }; } @@ -25,10 +30,12 @@ namespace uf { pod::Userdata* UF_API create( std::size_t len, void* data = NULL ); void UF_API destroy( pod::Userdata* userdata ); + pod::Userdata* UF_API copy( const pod::Userdata* userdata ); template pod::Userdata* create( const T& data = T() ); template T& get( pod::Userdata* userdata, bool validate = true); - template const T& get(const pod::Userdata* userdata); + template const T& get(const pod::Userdata* userdata, bool validate = true ); + template bool is(const pod::Userdata* userdata); std::string UF_API toBase64( pod::Userdata* userdata ); pod::Userdata* UF_API fromBase64( const std::string& base64 ); @@ -40,6 +47,7 @@ namespace uf { pod::Userdata* UF_API create( uf::MemoryPool&, std::size_t len, void* data = NULL ); template pod::Userdata* create( uf::MemoryPool&, const T& data = T() ); void UF_API destroy( uf::MemoryPool&, pod::Userdata* userdata ); + pod::Userdata* UF_API copy( uf::MemoryPool&, const pod::Userdata* userdata ); size_t UF_API size( size_t size, size_t padding = 0 ); } @@ -57,12 +65,13 @@ namespace uf { public: // C-tor - Userdata(std::size_t len = 0, void* data = NULL); // initializes POD to 'def' + Userdata(std::size_t len = 0, void* data = NULL); // initializes POD to default + Userdata( pod::Userdata* ); // initializes from POD Userdata( Userdata&& move ); // Move c-tor Userdata( const Userdata& copy ); // Copy c-tor - pod::Userdata* create( std::size_t len ); - pod::Userdata* create( std::size_t len, void* data ); + pod::Userdata* create( std::size_t len, void* data = NULL ); + void move( Userdata& move ); void move( Userdata&& move ); void copy( const Userdata& copy ); // D-tor @@ -77,12 +86,17 @@ namespace uf { template pod::Userdata* create( const T& data = T() ); template T& get(); template const T& get() const; + + template bool is() const; + template inline T& as() { return get(); } + template inline T& as() const { return get(); } // Overloaded ops operator void*(); operator void*() const; operator bool() const; + Userdata& operator=( pod::Userdata* pointer ); Userdata& operator=( Userdata&& move ); Userdata& operator=( const Userdata& copy ); diff --git a/engine/inc/uf/utils/userdata/userdata.inl b/engine/inc/uf/utils/userdata/userdata.inl index b90c4dbf..aa02f854 100644 --- a/engine/inc/uf/utils/userdata/userdata.inl +++ b/engine/inc/uf/utils/userdata/userdata.inl @@ -24,10 +24,13 @@ pod::Userdata* uf::userdata::create( uf::MemoryPool& requestedMemoryPool, const userdata = (pod::Userdata*) operator new( requestedLen ); // allocate data for the userdata struct, and then some } #endif userdata->len = len; +#if UF_USERDATA_RTTI + userdata->type = typeid(T).hash_code(); +#endif union { uint8_t* from; T* to; - } static kludge; + } kludge; kludge.from = userdata->data; ::new (kludge.to) T(data); return userdata; @@ -36,9 +39,7 @@ pod::Userdata* uf::userdata::create( uf::MemoryPool& requestedMemoryPool, const #include template T& uf::userdata::get( pod::Userdata* userdata, bool validate ) { - if ( validate && userdata->len != sizeof(T) ) { - throw std::logic_error("Userdata size mismatch"); - } + if ( validate && !uf::userdata::is( userdata ) ) throw std::logic_error("Userdata size|type mismatch"); union { uint8_t* original; T* casted; @@ -47,14 +48,25 @@ T& uf::userdata::get( pod::Userdata* userdata, bool validate ) { return *cast.casted; } template -const T& uf::userdata::get( const pod::Userdata* userdata ) { +const T& uf::userdata::get( const pod::Userdata* userdata, bool validate ) { + if ( validate && !uf::userdata::is( userdata ) ) throw std::logic_error("Userdata size|type mismatch"); union { - uint8_t* original; + const uint8_t* original; const T* casted; - } static cast; + } cast; cast.original = userdata->data; return *cast.casted; } + +template +bool uf::userdata::is( const pod::Userdata* userdata ) { +#if UF_USERDATA_RTTI + return userdata && userdata->type == typeid(T).hash_code(); +#else + return userdata && userdata->len == sizeof(T); +#endif +} + // No need to cast data to a pointer AND get the data's size! template pod::Userdata* uf::Userdata::create( const T& data ) { @@ -67,17 +79,24 @@ T& uf::Userdata::get() { union { uint8_t* original; T* casted; - } static cast; + } cast; cast.original = this->m_pod->data; return *cast.casted; +// return uf::userdata::get( this->m_pod ); } // Easy way to get the userdata as a const-reference template const T& uf::Userdata::get() const { union { - uint8_t* original; + const uint8_t* original; const T* casted; - } static cast; + } cast; cast.original = this->m_pod->data; return *cast.casted; +// return uf::userdata::get( this->m_pod ); +} + +template +bool uf::Userdata::is() const { + return this->m_pod && uf::userdata::is( this->m_pod ); } \ No newline at end of file diff --git a/engine/src/engine/asset/asset.cpp b/engine/src/engine/asset/asset.cpp index edf1aa86..d4472259 100644 --- a/engine/src/engine/asset/asset.cpp +++ b/engine/src/engine/asset/asset.cpp @@ -140,7 +140,7 @@ std::string uf::Asset::load( const std::string& uri ) { asset = ext::lua::script( filename ); } else if ( extension == "gltf" || extension == "glb" ) { UF_ASSET_REGISTER(uf::Object*) - uint8_t LOAD_FLAGS = 0; + ext::gltf::load_mode_t LOAD_FLAGS = 0; asset = &uf::instantiator::instantiate(); @@ -158,6 +158,7 @@ std::string uf::Asset::load( const std::string& uri ) { LOAD_FLAG(AABB); // 0x1 << 5; LOAD_FLAG(DEFER_INIT); // 0x1 << 6; LOAD_FLAG(USE_ATLAS); // 0x1 << 7; + LOAD_FLAG(SKINNED); // 0x1 << 8; ext::gltf::load( *asset, filename, LOAD_FLAGS ); } else { diff --git a/engine/src/engine/behavior/behavior.cpp b/engine/src/engine/behavior/behavior.cpp index 8a9b741f..1464e098 100644 --- a/engine/src/engine/behavior/behavior.cpp +++ b/engine/src/engine/behavior/behavior.cpp @@ -26,7 +26,9 @@ void uf::Behaviors::removeBehavior( const pod::Behavior& behavior ) { #define FUNCTION_AS_VARIABLE(x) x -#define UF_BEHAVIOR_POLYFILL(f)\ +#define UF_BEHAVIOR_POLYFILL UF_BEHAVIOR_POLYFILL_SAFE + +#define UF_BEHAVIOR_POLYFILL_SAFE(f)\ uf::Object& self = *((uf::Object*) this);\ bool headLoopChildren = true;\ bool forwardIteration = true;\ @@ -75,6 +77,8 @@ void uf::Behaviors::removeBehavior( const pod::Behavior& behavior ) { bool headLoopChildren = true;\ bool forwardIteration = true;\ bool multithreading = false;\ + bool useWorkers = false;\ + std::vector> jobs;\ if ( this->hasComponent() ) {\ auto& metadata = this->getComponent();\ if ( !ext::json::isNull( metadata["system"]["behavior"][#f]["head loop children"] ) )\ @@ -83,6 +87,8 @@ void uf::Behaviors::removeBehavior( const pod::Behavior& behavior ) { forwardIteration = metadata["system"]["behavior"][#f]["forward iteration"].as();\ if ( !ext::json::isNull( metadata["system"]["behavior"][#f]["multithreading"] ) )\ multithreading = metadata["system"]["behavior"][#f]["multithreading"].as();\ + if ( !ext::json::isNull( metadata["system"]["behavior"][#f]["use workers"] ) )\ + useWorkers = metadata["system"]["behavior"][#f]["use workers"].as();\ }\ if ( headLoopChildren ) {\ if ( forwardIteration ) {\ @@ -95,7 +101,9 @@ void uf::Behaviors::removeBehavior( const pod::Behavior& behavior ) { it->f(self);\ return 0;\ };\ - if ( multithreading ) uf::thread::add( uf::thread::fetchWorker(), function, true ); else function();\ + if ( multithreading && useWorkers ) jobs.emplace_back(function);\ + else if ( multithreading ) uf::thread::add( uf::thread::fetchWorker(), function, true );\ + else function();\ }\ } else {\ auto it = this->m_behaviors.rbegin();\ @@ -107,7 +115,9 @@ void uf::Behaviors::removeBehavior( const pod::Behavior& behavior ) { it->f(self);\ return 0;\ };\ - if ( multithreading ) uf::thread::add( uf::thread::fetchWorker(), function, true ); else function();\ + if ( multithreading && useWorkers ) jobs.emplace_back(function);\ + else if ( multithreading ) uf::thread::add( uf::thread::fetchWorker(), function, true );\ + else function();\ }\ }\ } else {\ @@ -118,7 +128,9 @@ void uf::Behaviors::removeBehavior( const pod::Behavior& behavior ) { it->f(self);\ return 0;\ };\ - if ( multithreading ) uf::thread::add( uf::thread::fetchWorker(), function, true ); else function();\ + if ( multithreading && useWorkers ) jobs.emplace_back(function);\ + else if ( multithreading ) uf::thread::add( uf::thread::fetchWorker(), function, true );\ + else function();\ }\ if ( (it = this->m_behaviors.begin()) != this->m_behaviors.end() ) {\ it->f(self);\ @@ -130,13 +142,16 @@ void uf::Behaviors::removeBehavior( const pod::Behavior& behavior ) { it->f(self);\ return 0;\ };\ - if ( multithreading ) uf::thread::add( uf::thread::fetchWorker(), function, true ); else function();\ + if ( multithreading && useWorkers ) jobs.emplace_back(function);\ + else if ( multithreading ) uf::thread::add( uf::thread::fetchWorker(), function, true );\ + else function();\ }\ if ( (it = this->m_behaviors.rbegin()) != this->m_behaviors.rend() ) {\ it->f(self);\ }\ }\ - } + }\ + if ( !jobs.empty() ) uf::thread::batchWorkers( jobs ); void uf::Behaviors::initialize() { diff --git a/engine/src/engine/instantiator/instantiator.cpp b/engine/src/engine/instantiator/instantiator.cpp index 2d3b8c22..edceff20 100644 --- a/engine/src/engine/instantiator/instantiator.cpp +++ b/engine/src/engine/instantiator/instantiator.cpp @@ -63,7 +63,8 @@ uf::Entity* uf::instantiator::alloc( size_t size ) { } void uf::instantiator::free( uf::Entity* pointer ) { if ( !pointer ) return; - if ( pointer->getUid() > 0 ) pointer->destroy(); + if ( pointer->getUid() > 0 ) + pointer->destroy(); #if UF_MEMORYPOOL_INVALID_FREE uf::MemoryPool& memoryPool = uf::Entity::memoryPool.size() > 0 ? uf::Entity::memoryPool : uf::MemoryPool::global; diff --git a/engine/src/engine/object/behavior.cpp b/engine/src/engine/object/behavior.cpp index 3af328fb..5bd9e519 100644 --- a/engine/src/engine/object/behavior.cpp +++ b/engine/src/engine/object/behavior.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include #include #include @@ -121,6 +122,14 @@ void uf::ObjectBehavior::destroy( uf::Object& self ) { } } + if ( this->hasComponent() ) { + auto& audio = this->getComponent(); + audio.destroy(); + } + if ( this->hasComponent() ) { + auto& audio = this->getComponent(); + audio.cleanup(true); + } if ( this->hasComponent() ) { auto& graphic = this->getComponent(); graphic.destroy(); diff --git a/engine/src/engine/object/behaviors/gltf.cpp b/engine/src/engine/object/behaviors/gltf.cpp index fe76ef93..cbb00186 100644 --- a/engine/src/engine/object/behaviors/gltf.cpp +++ b/engine/src/engine/object/behaviors/gltf.cpp @@ -42,9 +42,10 @@ void uf::GltfBehavior::initialize( uf::Object& self ) { if ( !entity->hasComponent() || !entity->hasComponent() ) return; auto& graphic = entity->getComponent(); auto& mesh = entity->getComponent(); + /* graphic.initialize(); graphic.initializeGeometry( mesh ); - + */ { std::string filename = "/gltf.stereo.vert.spv"; if ( metadata["system"]["renderer"]["shaders"]["vertex"].is() ) @@ -107,6 +108,8 @@ void uf::GltfBehavior::tick( uf::Object& self ) { if ( !graphic.initialized ) return; auto& shader = graphic.material.shaders.back(); if ( shader.uniforms.empty() ) return; + shader.validate(); + auto& userdata = shader.uniforms.front(); struct UniformDescriptor { // alignas(4) uint32_t mappings; diff --git a/engine/src/engine/object/object.cpp b/engine/src/engine/object/object.cpp index c1188c68..7b008c5a 100644 --- a/engine/src/engine/object/object.cpp +++ b/engine/src/engine/object/object.cpp @@ -60,7 +60,14 @@ std::string uf::Object::formatHookName( const std::string& n ) { return name; } std::vector uf::Object::callHook( const std::string& name, const std::string& payload ) { - return uf::hooks.call( this->formatHookName( name ), payload ); + std::vector strings; + auto results = uf::hooks.call( this->formatHookName( name ), payload ); + for ( auto& result : results ) { + if ( result.is() ) { + strings.emplace_back( result.as() ); + } + } + return strings; } std::size_t uf::Object::addHook( const std::string& name, const uf::HookHandler::Readable::function_t& callback ) { std::string parsed = this->formatHookName( name ); @@ -116,6 +123,27 @@ bool uf::Object::reload( bool hard ) { bool uf::Object::load( const uf::Serializer& _json ) { uf::Serializer& metadata = this->getComponent(); uf::Serializer json = _json; + // import + if ( _json["import"].is() || _json["include"].is() ) { + uf::Serializer chain = _json; + std::string root = json["root"].as(); + do { + std::string filename = chain["import"].is() ? chain["import"].as() : chain["include"].as(); + filename = grabURI( filename, root ); + chain.readFromFile( filename ); + // set new root + root = uf::io::directory( filename ); + // merge table + json.import( chain ); + /* + json["import"] = Json::nullValue; + json["include"] = Json::nullValue; + chain.merge( json, true ); + json = chain; + */ + } while ( chain["import"].is() || chain["include"].is() ); + if ( !ext::json::isArray(_json["assets"]) || _json["assets"].size() == 0 ) json["root"] = root; + } // copy system table to base for ( auto it = json["system"].begin(); it != json["system"].end(); ++it ) { std::string key = it.key().as(); diff --git a/engine/src/ext/assimp/assimp.cpp b/engine/src/ext/assimp/assimp.cpp deleted file mode 100644 index a194971f..00000000 --- a/engine/src/ext/assimp/assimp.cpp +++ /dev/null @@ -1,296 +0,0 @@ - -#include -#if defined(UF_USE_ASSIMP) - -#include -#include -#include -#include - -#include -#include - -UF_API bool ext::assimp::load( const std::string& filename, uf::Mesh& mesh, bool flip ) { - Assimp::Importer importer; - const aiScene* scene = importer.ReadFile( filename, aiProcess_Triangulate ); - - if( !scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode ) { - uf::iostream << "Failed to load model @ `" << filename << "`" << "\n"; - return false; - } - - struct { - std::vector points; - std::vector normals; - std::vector uvs; - } model; - - std::function readNodes = [&]( const aiNode* node ) { - for ( uint m = 0; m < node->mNumMeshes; ++m ) { - const aiMesh* assMesh = scene->mMeshes[node->mMeshes[m]]; - for ( uint i = 0; i < assMesh->mNumVertices; i++ ) { - if ( assMesh->HasPositions() ) { - const aiVector3D* vp = &(assMesh->mVertices[i]); - model.points.push_back((float) vp->x); - model.points.push_back((float) vp->y); - model.points.push_back((float) vp->z); - - if ( flip ) { - uint offset = model.points.size(); - std::swap( model.points[offset-1], model.points[offset-2] ); - model.points[offset-1] *= -1; - } - - if ( assMesh->HasNormals() ) { - const aiVector3D* vn = &(assMesh->mNormals[i]); - model.normals.push_back((float) vn->x); - model.normals.push_back((float) vn->y); - model.normals.push_back((float) vn->z); - if ( flip ) { - uint offset = model.normals.size(); - std::swap( model.normals[offset-1], model.normals[offset-2] ); - model.normals[offset-1] *= -1; - } - } else { - model.normals.push_back(0); model.normals.push_back(0); model.normals.push_back(0); - } - if ( assMesh->HasTextureCoords(0) ) { - const aiVector3D* vt = &(assMesh->mTextureCoords[0][i]); - model.uvs.push_back((float) vt->x); - model.uvs.push_back((float) vt->y); - } else { - model.uvs.push_back(0); model.uvs.push_back(0); - } - } - } - } - for ( uint i = 0; i < node->mNumChildren; ++i ) readNodes(node->mChildren[i]); - }; readNodes(scene->mRootNode); - - /* Load */ { - if ( !model.points.empty() ) mesh.getPositions().add( &model.points[0], model.points.size() ); - if ( !model.normals.empty() ) mesh.getNormals().add( &model.normals[0], model.normals.size() ); - if ( !model.uvs.empty() ) mesh.getUvs().add( &model.uvs[0], model.uvs.size() ); - } - - return true; -} -#include -UF_API bool ext::assimp::load( const std::string& filename, uf::SkeletalMesh& mesh, bool flip ) { - Assimp::Importer& importer = mesh.getImporter(); - mesh.setScene( importer.ReadFile( filename, aiProcess_Triangulate | aiProcess_GenSmoothNormals )); - const aiScene* scene = mesh.getScene(); - - if( !scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode ) { - uf::iostream << "Failed to load model @ `" << filename << "`" << "\n"; - return false; - } - - std::function convertMatrix = [&]( const aiMatrix4x4& m, bool t = false) { - return t ? uf::matrix::initialize({ - m.a1, m.b1, m.c1, m.d1, - m.a2, m.b2, m.c2, m.d2, - m.a3, m.b3, m.c3, m.d3, - m.a4, m.b4, m.c4, m.d4 - }) : uf::matrix::initialize({ - 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - m.a4, m.b4, m.c4, m.d4 - }); - }; - - uf::Skeleton& skel = mesh.getSkeleton(); - uf::Skeleton::container_t& skeleton = skel.getBones(); - - struct { - std::vector points; - std::vector normals; - std::vector uvs; - std::vector bones_id; - std::vector bones_weight; - } model; - /* */ { - std::function readNodes = [&]( const aiNode* node ) { - int startIndex = model.points.size() / 3; - for ( uint m = 0; m < node->mNumMeshes; ++m ) { - const aiMesh* assMesh = scene->mMeshes[node->mMeshes[m]]; - if ( false && assMesh->HasBones()) { - const int WEIGHTS_PER_VERTEX = 4; - int size = assMesh->mNumVertices * WEIGHTS_PER_VERTEX; - std::vector boneIDs; boneIDs.resize(size, 0); - std::vector boneWeights; boneWeights.resize(size, 0); - for ( uint i = 0; i < assMesh->mNumBones; ++i ) { - const aiBone* bone = assMesh->mBones[i]; - const aiMatrix4x4& m = bone->mOffsetMatrix; - - uint index = i; - std::string name = bone->mName.data; - pod::Matrix4 matrix = convertMatrix(m, true); - if ( !skel.hasBone( name ) ) { - index = skeleton.size(); - uf::Skeleton::Bone b; - b.index = index; - b.name = name; - b.matrix = uf::matrix::identity(); - b.animation = uf::matrix::identity(); - b.offset = matrix; - b.inverse = matrix; b.inverse = uf::matrix::inverse( b.inverse ); - b.parent = 0; - skeleton.push_back(b); - } else { - index = skel.getBone( name ).index; - } - for ( uint j = 0; j < bone->mNumWeights; ++j) { - aiVertexWeight weight = bone->mWeights[j]; - int start = weight.mVertexId * WEIGHTS_PER_VERTEX; - int lowest = -1; - for ( int k = 0; k < WEIGHTS_PER_VERTEX; ++k ) { int offset = start + k; - if ( boneWeights.at(offset) == 0.0 ) { - boneWeights.at(offset) = weight.mWeight; - boneIDs.at(offset) = index; - break; - } - // if ( boneWeights.at(offset) < weight.mWeight ) lowest = k; - } - if ( lowest >= 0 ) { - boneWeights.at(start + lowest) = weight.mWeight; - boneIDs.at(start + lowest) = index; - } - } - } - for ( auto id : boneIDs ) model.bones_id.push_back(id); - for ( auto weight : boneWeights ) model.bones_weight.push_back(weight); - } - for ( uint i = 0; i < assMesh->mNumVertices; i++ ) { - if ( assMesh->HasPositions() ) { - const aiVector3D* vp = &(assMesh->mVertices[i]); - model.points.push_back((float) vp->x); - model.points.push_back((float) vp->y); - model.points.push_back((float) vp->z); - - if ( flip ) { - uint offset = model.points.size(); - std::swap( model.points[offset-1], model.points[offset-2] ); - model.points[offset-1] *= -1; - } - - if ( assMesh->HasNormals() ) { - const aiVector3D* vn = &(assMesh->mNormals[i]); - model.normals.push_back((float) vn->x); - model.normals.push_back((float) vn->y); - model.normals.push_back((float) vn->z); - if ( flip ) { - uint offset = model.normals.size(); - std::swap( model.normals[offset-1], model.normals[offset-2] ); - model.normals[offset-1] *= -1; - } - } else { - model.normals.push_back(0); model.normals.push_back(0); model.normals.push_back(0); - } - if ( assMesh->HasTextureCoords(0) ) { - const aiVector3D* vt = &(assMesh->mTextureCoords[0][i]); - model.uvs.push_back((float) vt->x); - model.uvs.push_back((float) vt->y); - } else { - model.uvs.push_back(0); model.uvs.push_back(0); - } - } - } - if ( true && assMesh->HasBones()) { - const int WEIGHTS_PER_VERTEX = 4; - int size = assMesh->mNumVertices * WEIGHTS_PER_VERTEX; - model.bones_id.resize( model.bones_id.size() + size, 0 ); - model.bones_weight.resize( model.bones_weight.size() + size, 0 ); - for ( uint i = 0; i < assMesh->mNumBones; ++i ) { - const aiBone* bone = assMesh->mBones[i]; - const aiMatrix4x4& m = bone->mOffsetMatrix; - - uint index = i; - std::string name = bone->mName.data; - pod::Matrix4 matrix = convertMatrix(m, true); - if ( !skel.hasBone( name ) ) { - index = skeleton.size(); - uf::Skeleton::Bone b; - b.index = index; - b.name = name; - b.matrix = uf::matrix::identity(); - b.animation = uf::matrix::identity(); - b.offset = matrix; - b.inverse = matrix; b.inverse = uf::matrix::inverse( b.inverse ); - b.parent = 0; - skeleton.push_back(b); - } else { - index = skel.getBone( name ).index; - } - for ( uint j = 0; j < bone->mNumWeights; ++j) { - aiVertexWeight weight = bone->mWeights[j]; - int lowest = -1; - int start = startIndex + weight.mVertexId * WEIGHTS_PER_VERTEX; - for ( int k = 0; k < WEIGHTS_PER_VERTEX; ++k ) { int offset = start + k; - if ( model.bones_weight.at(offset) == 0 ) { - model.bones_weight.at(offset) = weight.mWeight; - model.bones_id.at(offset) = index; - break; - } - // if ( model.bones_weight.at(offset) < weight.mWeight ) lowest = k; - } - if ( lowest >= 0 ) { - model.bones_weight.at(start + lowest) = weight.mWeight; - model.bones_id.at(start + lowest) = index; - } - } - } - } - } - for ( uint i = 0; i < node->mNumChildren; ++i ) if (!readNodes(node->mChildren[i])) return false; - return true; - }; if ( !readNodes(scene->mRootNode) ) return false; - } - - /* Load */ { - if ( !model.points.empty() ) mesh.getPositions().add( &model.points[0], model.points.size() ); - if ( !model.normals.empty() ) mesh.getNormals().add( &model.normals[0], model.normals.size() ); - if ( !model.uvs.empty() ) mesh.getUvs().add( &model.uvs[0], model.uvs.size() ); - if ( !model.bones_id.empty() ) { - mesh.getBonesId().add( &model.bones_id[0], model.bones_id.size() ); - mesh.getBonesWeight().add( &model.bones_weight[0], model.bones_weight.size() ); - mesh.getSkeleton().getBones() = skeleton; if ( true ) { - std::vector nodes; { - std::function fillNodes = [&]( const aiNode* node ) { - nodes.push_back(node); for ( uint i = 0; i < node->mNumChildren; ++i ) fillNodes(node->mChildren[i]); - }; fillNodes(scene->mRootNode); - } - std::function nameToBoneNode = [&]( const std::string& name ) { - for ( const aiNode* node : nodes ) if ( node->mName.data == name ) return node; - return (const aiNode*) NULL; - }; - - auto& skeleton = mesh.getSkeleton(); - for ( auto& bone : skeleton.getBones() ) { - const aiNode* node = nameToBoneNode(bone.name); - if ( node && node->mParent && skeleton.hasBone( node->mParent->mName.data ) ) { - bone.parent = skeleton.getBone(node->mParent->mName.data).index; - skeleton.getBone(node->mParent->mName.data).children.push_back(bone.index); - } else bone.parent = bone.index; - } - if ( false ) { std::cout << "Map of " << filename << std::endl; - std::function recurseChild = [&]( const uf::Skeleton::Bone& bone, int indent ) { - for ( int i = 0; i < indent; ++i ) std::cout << "\t"; - std::cout << bone.name << "\n"; - for ( auto child : bone.children ) recurseChild( skeleton.getBone(child), indent+1 ); - }; - for ( auto& bone : skeleton.getBones() ) { - if ( bone.index != bone.parent ) continue; - recurseChild( bone, 0 ); - } - std::cout << std::endl; - } - } - } - } - - return true; -} - -#endif \ No newline at end of file diff --git a/engine/src/ext/gltf/gltf.cpp b/engine/src/ext/gltf/gltf.cpp index e0b6350d..0db30dc8 100644 --- a/engine/src/ext/gltf/gltf.cpp +++ b/engine/src/ext/gltf/gltf.cpp @@ -15,247 +15,279 @@ #include namespace { + VkSamplerAddressMode getVkWrapMode(int32_t wrapMode) { + switch (wrapMode) { + case 10497: return VK_SAMPLER_ADDRESS_MODE_REPEAT; + case 33071: return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + case 33648: return VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT; + default: return VK_SAMPLER_ADDRESS_MODE_REPEAT; + } + } -VkSamplerAddressMode getVkWrapMode(int32_t wrapMode) { - switch (wrapMode) { - case 10497: return VK_SAMPLER_ADDRESS_MODE_REPEAT; - case 33071: return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - case 33648: return VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT; - default: return VK_SAMPLER_ADDRESS_MODE_REPEAT; + VkFilter getVkFilterMode(int32_t filterMode) { + switch (filterMode) { + case 9728: return VK_FILTER_NEAREST; + case 9729: return VK_FILTER_LINEAR; + case 9984: return VK_FILTER_NEAREST; + case 9985: return VK_FILTER_NEAREST; + case 9986: return VK_FILTER_LINEAR; + case 9987: return VK_FILTER_LINEAR; + default: return VK_FILTER_LINEAR; + } } } -VkFilter getVkFilterMode(int32_t filterMode) { - switch (filterMode) { - case 9728: return VK_FILTER_NEAREST; - case 9729: return VK_FILTER_LINEAR; - case 9984: return VK_FILTER_NEAREST; - case 9985: return VK_FILTER_NEAREST; - case 9986: return VK_FILTER_LINEAR; - case 9987: return VK_FILTER_LINEAR; - default: return VK_FILTER_LINEAR; - } -} +namespace legacy { + void loadNode( uf::Object& entity, const tinygltf::Model& model, const tinygltf::Node& node, ext::gltf::load_mode_t mode ) { + auto& transform = entity.getComponent>(); + auto& atlas = entity.getComponent(); -void loadNode( uf::Object& entity, const tinygltf::Model& model, const tinygltf::Node& node, uint8_t mode ) { - auto& transform = entity.getComponent>(); - auto& atlas = entity.getComponent(); - - if ( node.translation.size() == 3 ) { - transform.position.x = node.translation[0]; - transform.position.y = node.translation[1]; - transform.position.z = node.translation[2]; - } - if ( node.rotation.size() == 4 ) { - transform.orientation.x = node.rotation[0]; - transform.orientation.y = node.rotation[1]; - transform.orientation.z = node.rotation[2]; - transform.orientation.w = node.rotation[3]; - } - if ( node.scale.size() == 3 ) { - transform.scale.x = node.scale[0]; - transform.scale.y = node.scale[1]; - transform.scale.z = node.scale[2]; - } -// if ( node.matrix.size() == 16 ) {} - - auto fillMesh = [&]( ext::gltf::mesh_t& mesh, const tinygltf::Primitive& primitive, uf::Collider& collider, size_t num ) { - size_t verticesStart = mesh.vertices.size(); - size_t indicesStart = mesh.indices.size(); - - size_t vertices = 0; - struct Attribute { - std::string name = ""; - size_t components = 1; - std::vector buffer; - }; - std::unordered_map attributes = { - {"POSITION", {}}, - {"TEXCOORD_0", {}}, - {"NORMAL", {}}, - }; - - for ( auto& kv : attributes ) { - auto& attribute = kv.second; - attribute.name = kv.first; - auto it = primitive.attributes.find(attribute.name); - if ( it == primitive.attributes.end() ) continue; - - auto& accessor = model.accessors[it->second]; - auto& view = model.bufferViews[accessor.bufferView]; - auto* buffer = reinterpret_cast(&(model.buffers[view.buffer].data[accessor.byteOffset + view.byteOffset])); - - if ( attribute.name == "POSITION" ) { - vertices = accessor.count; - pod::Vector3f minCorner = { accessor.minValues[0], accessor.minValues[1], accessor.minValues[2] }; - pod::Vector3f maxCorner = { accessor.maxValues[0], accessor.maxValues[1], accessor.maxValues[2] }; - - pod::Vector3f origin = (maxCorner + minCorner) * 0.5f; - pod::Vector3f size = (maxCorner - minCorner) * 0.5f; - - if ( (mode & ext::gltf::LoadMode::COLLISION) && (mode & ext::gltf::LoadMode::AABB) ) { - auto* box = new uf::BoundingBox( origin, size ); - collider.add(box); - } - } - attribute.components = accessor.ByteStride(view) / sizeof(float); - size_t len = accessor.count * attribute.components; - attribute.buffer.reserve( len ); - attribute.buffer.insert( attribute.buffer.end(), &buffer[0], &buffer[len] ); + if ( node.translation.size() == 3 ) { + transform.position.x = node.translation[0]; + transform.position.y = node.translation[1]; + transform.position.z = node.translation[2]; } - - mesh.vertices.reserve( vertices + verticesStart ); - for ( size_t i = 0; i < vertices; ++i ) { - #define ITERATE_ATTRIBUTE( name, member )\ - if ( !attributes[name].buffer.empty() ) { \ - for ( size_t j = 0; j < attributes[name].components; ++j )\ - vertex.member[j] = attributes[name].buffer[i * attributes[name].components + j];\ - } - - auto& vertex = mesh.vertices.emplace_back(); - ITERATE_ATTRIBUTE("POSITION", position); - ITERATE_ATTRIBUTE("TEXCOORD_0", uv); - ITERATE_ATTRIBUTE("NORMAL", normal); - - #undef ITERATE_ATTRIBUTE - if ( !(mode & ext::gltf::LoadMode::SEPARATE_MESHES) && (mode & ext::gltf::LoadMode::USE_ATLAS) ) { - vertex.uv = atlas.mapUv( vertex.uv, num ); - } - vertex.id = num; + if ( node.rotation.size() == 4 ) { + transform.orientation.x = node.rotation[0]; + transform.orientation.y = node.rotation[1]; + transform.orientation.z = node.rotation[2]; + transform.orientation.w = node.rotation[3]; } + if ( node.scale.size() == 3 ) { + transform.scale.x = node.scale[0]; + transform.scale.y = node.scale[1]; + transform.scale.z = node.scale[2]; + } + // if ( node.matrix.size() == 16 ) {} + if ( node.mesh > -1 ) { + auto& m = model.meshes[node.mesh]; + std::vector samplers; + std::vector _images; + bool useAtlas = (mode & ext::gltf::LoadMode::USE_ATLAS) && (mode & ext::gltf::LoadMode::SEPARATE_MESHES); + auto& images = useAtlas ? atlas.getImages() : _images; - if ( primitive.indices > -1 ) { - auto& accessor = model.accessors[primitive.indices]; - auto& view = model.bufferViews[accessor.bufferView]; - auto& buffer = model.buffers[view.buffer]; - - auto indices = static_cast(accessor.count); - mesh.indices.reserve( indices + indicesStart ); - const void* pointer = &(buffer.data[accessor.byteOffset + view.byteOffset]); - - #define COPY_INDICES()\ - for (size_t index = 0; index < indices; index++)\ - mesh.indices.emplace_back(buf[index] + verticesStart); - - switch (accessor.componentType) { - case TINYGLTF_PARAMETER_TYPE_UNSIGNED_INT: { - auto* buf = static_cast( pointer ); - COPY_INDICES() - break; - } - case TINYGLTF_PARAMETER_TYPE_UNSIGNED_SHORT: { - auto* buf = static_cast( pointer ); - COPY_INDICES() - break; - } - case TINYGLTF_PARAMETER_TYPE_UNSIGNED_BYTE: { - auto* buf = static_cast( pointer ); - COPY_INDICES() - break; - } + for ( auto& s : model.samplers ) { + auto& sampler = samplers.emplace_back(); + sampler.descriptor.filter.min = getVkFilterMode( s.minFilter ); + sampler.descriptor.filter.mag = getVkFilterMode( s.magFilter ); + sampler.descriptor.addressMode.u = getVkWrapMode( s.wrapS ); + sampler.descriptor.addressMode.v = getVkWrapMode( s.wrapT ); + sampler.descriptor.addressMode.w = sampler.descriptor.addressMode.v; } - #undef COPY_INDICES + for ( auto& t : model.textures ) { + auto& im = model.images[t.source]; + uf::Image& image = images.emplace_back(); + image.loadFromBuffer( &im.image[0], {im.width, im.height}, 8, im.component, true ); + } + auto fillMesh = [&]( ext::gltf::mesh_t& mesh, const tinygltf::Primitive& primitive, uf::Collider& collider, size_t id ) { + size_t verticesStart = mesh.vertices.size(); + size_t indicesStart = mesh.indices.size(); - if ( mode & ext::gltf::LoadMode::GENERATE_NORMALS ) { - for ( size_t i = 0; i < mesh.indices.size(); i+=3 ) { - auto& A = mesh.vertices[mesh.indices[i+0]]; - auto& B = mesh.vertices[mesh.indices[i+1]]; - auto& C = mesh.vertices[mesh.indices[i+2]]; + size_t vertices = 0; + struct Attribute { + std::string name = ""; + size_t components = 1; + std::vector buffer; + }; + std::unordered_map attributes = { + {"POSITION", {}}, + {"TEXCOORD_0", {}}, + {"NORMAL", {}}, + }; - auto& a = A.position; - auto& b = B.position; - auto& c = C.position; + for ( auto& kv : attributes ) { + auto& attribute = kv.second; + attribute.name = kv.first; + auto it = primitive.attributes.find(attribute.name); + if ( it == primitive.attributes.end() ) continue; - pod::Vector3f normal = uf::vector::normalize( uf::vector::cross( b - a, c - a ) ); + auto& accessor = model.accessors[it->second]; + auto& view = model.bufferViews[accessor.bufferView]; - A.normal = normal; - B.normal = normal; - C.normal = normal; + if ( attribute.name == "POSITION" ) { + vertices = accessor.count; + pod::Vector3f minCorner = { accessor.minValues[0], accessor.minValues[1], accessor.minValues[2] }; + pod::Vector3f maxCorner = { accessor.maxValues[0], accessor.maxValues[1], accessor.maxValues[2] }; + + pod::Vector3f origin = (maxCorner + minCorner) * 0.5f; + pod::Vector3f size = (maxCorner - minCorner) * 0.5f; + + if ( (mode & ext::gltf::LoadMode::COLLISION) && (mode & ext::gltf::LoadMode::AABB) ) { + auto* box = new uf::BoundingBox( origin, size ); + collider.add(box); + } + } + { + auto* buffer = reinterpret_cast(&(model.buffers[view.buffer].data[accessor.byteOffset + view.byteOffset])); + attribute.components = accessor.ByteStride(view) / sizeof(float); + size_t len = accessor.count * attribute.components; + attribute.buffer.reserve( len ); + attribute.buffer.insert( attribute.buffer.end(), &buffer[0], &buffer[len] ); + } } - } - // validate incides - size_t maxIndex = mesh.vertices.size(); - for ( size_t i = 0; i < mesh.indices.size(); ++i ) { - size_t index = mesh.indices[i]; - if ( index >= maxIndex ) { - std::cout << "mesh.indices["<< i <<"] = " << index << " >= " << maxIndex << std::endl; + mesh.vertices.reserve( vertices + verticesStart ); + for ( size_t i = 0; i < vertices; ++i ) { + #define ITERATE_ATTRIBUTE( name, member )\ + if ( !attributes[name].buffer.empty() ) { \ + for ( size_t j = 0; j < attributes[name].components; ++j )\ + vertex.member[j] = attributes[name].buffer[i * attributes[name].components + j];\ + } + + auto& vertex = mesh.vertices.emplace_back(); + ITERATE_ATTRIBUTE("POSITION", position); + ITERATE_ATTRIBUTE("TEXCOORD_0", uv); + ITERATE_ATTRIBUTE("NORMAL", normal); + + #undef ITERATE_ATTRIBUTE + if ( !(mode & ext::gltf::LoadMode::SEPARATE_MESHES) && (mode & ext::gltf::LoadMode::USE_ATLAS) ) { + vertex.uv = atlas.mapUv( vertex.uv, id ); + } + vertex.id = id; } - } - } else { - // recalc normals - if ( mode & ext::gltf::LoadMode::GENERATE_NORMALS ) { - // bool invert = false; - for ( size_t i = 0; i < mesh.vertices.size(); i+=3 ) { - auto& a = mesh.vertices[i+0].position; - auto& b = mesh.vertices[i+1].position; - auto& c = mesh.vertices[i+2].position; - pod::Vector3f normal = uf::vector::normalize( uf::vector::cross( b - a, c - a ) ); - mesh.vertices[i+0].normal = normal; - mesh.vertices[i+1].normal = normal; - mesh.vertices[i+2].normal = normal; + if ( primitive.indices > -1 ) { + auto& accessor = model.accessors[primitive.indices]; + auto& view = model.bufferViews[accessor.bufferView]; + auto& buffer = model.buffers[view.buffer]; + + auto indices = static_cast(accessor.count); + mesh.indices.reserve( indices + indicesStart ); + const void* pointer = &(buffer.data[accessor.byteOffset + view.byteOffset]); + + #define COPY_INDICES()\ + for (size_t index = 0; index < indices; index++)\ + mesh.indices.emplace_back(buf[index] + verticesStart); + + switch (accessor.componentType) { + case TINYGLTF_PARAMETER_TYPE_UNSIGNED_INT: { + auto* buf = static_cast( pointer ); + COPY_INDICES() + break; + } + case TINYGLTF_PARAMETER_TYPE_UNSIGNED_SHORT: { + auto* buf = static_cast( pointer ); + COPY_INDICES() + break; + } + case TINYGLTF_PARAMETER_TYPE_UNSIGNED_BYTE: { + auto* buf = static_cast( pointer ); + COPY_INDICES() + break; + } + } + #undef COPY_INDICES } - } - } - if ( mode & ext::gltf::LoadMode::APPLY_TRANSFORMS ) { - pod::Matrix4f model = uf::transform::model( transform ); - for ( auto& vertex : mesh.vertices ) { - vertex.position = uf::matrix::multiply( model, vertex.position ); - } - } - }; + // recalc normals + if ( mode & ext::gltf::LoadMode::GENERATE_NORMALS ) { + // bool invert = false; + if ( !mesh.indices.empty() ) { + for ( size_t i = 0; i < mesh.vertices.size(); i+=3 ) { + auto& a = mesh.vertices[i+0].position; + auto& b = mesh.vertices[i+1].position; + auto& c = mesh.vertices[i+2].position; - if ( node.mesh > -1 ) { - auto& m = model.meshes[node.mesh]; - std::vector samplers; - std::vector _images; - bool useAtlas = (mode & ext::gltf::LoadMode::USE_ATLAS) && (mode & ext::gltf::LoadMode::SEPARATE_MESHES); - auto& images = useAtlas ? atlas.getImages() : _images; + pod::Vector3f normal = uf::vector::normalize( uf::vector::cross( b - a, c - a ) ); + mesh.vertices[i+0].normal = normal; + mesh.vertices[i+1].normal = normal; + mesh.vertices[i+2].normal = normal; + } + } else { + for ( size_t i = 0; i < mesh.indices.size(); i+=3 ) { + auto& A = mesh.vertices[mesh.indices[i+0]]; + auto& B = mesh.vertices[mesh.indices[i+1]]; + auto& C = mesh.vertices[mesh.indices[i+2]]; - for ( auto& s : model.samplers ) { - auto& sampler = samplers.emplace_back(); - sampler.descriptor.filter.min = getVkFilterMode( s.minFilter ); - sampler.descriptor.filter.mag = getVkFilterMode( s.magFilter ); - sampler.descriptor.addressMode.u = getVkWrapMode( s.wrapS ); - sampler.descriptor.addressMode.v = getVkWrapMode( s.wrapT ); - sampler.descriptor.addressMode.w = sampler.descriptor.addressMode.v; - } - for ( auto& t : model.textures ) { - auto& im = model.images[t.source]; - uf::Image& image = images.emplace_back(); - image.loadFromBuffer( &im.image[0], {im.width, im.height}, 8, im.component, true ); - /* - { - static int i = 0; - auto& pixels = image.getPixels(); - std::string hash = uf::string::sha256( pixels ); - image.save("./textures/" + std::to_string(i++) + "."+hash+".png"); - } - */ - } - if ( mode & ext::gltf::LoadMode::SEPARATE_MESHES ) { - auto sampler = samplers.begin(); - auto image = images.begin(); - size_t num = 0; - for ( auto& primitive : m.primitives ) { - uf::Object* child = new uf::Object; - - //ext::gltf::mesh_t mesh; - auto& mesh = child->getComponent(); - auto& cTransform = child->getComponent>(); - cTransform = transform; + auto& a = A.position; + auto& b = B.position; + auto& c = C.position; - auto& collider = child->getComponent(); - fillMesh( mesh, primitive, collider, num++ ); + pod::Vector3f normal = uf::vector::normalize( uf::vector::cross( b - a, c - a ) ); + + A.normal = normal; + B.normal = normal; + C.normal = normal; + } + } + } + if ( mode & ext::gltf::LoadMode::APPLY_TRANSFORMS ) { + pod::Matrix4f model = uf::transform::model( transform ); + for ( auto& vertex : mesh.vertices ) { + vertex.position = uf::matrix::multiply( model, vertex.position ); + } + } + }; + if ( mode & ext::gltf::LoadMode::SEPARATE_MESHES ) { + auto sampler = samplers.begin(); + auto image = images.begin(); + size_t id = 0; + for ( auto& primitive : m.primitives ) { + uf::Object* child = new uf::Object; + + //ext::gltf::mesh_t mesh; + auto& mesh = child->getComponent(); + auto& cTransform = child->getComponent>(); + cTransform = transform; + auto& collider = child->getComponent(); + fillMesh( mesh, primitive, collider, id++ ); + + if ( (mode & ext::gltf::LoadMode::COLLISION) && !(mode & ext::gltf::LoadMode::AABB) ) { + auto* box = new uf::MeshCollider( cTransform ); + box->setPositions( mesh ); + collider.add(box); + } + if ( mode & ext::gltf::LoadMode::RENDER ) { + auto& graphic = child->getComponent(); + if ( mode & ext::gltf::LoadMode::DEFER_INIT ) { + graphic.process = false; + } else { + graphic.initialize(); + graphic.initializeGeometry( mesh ); + + graphic.material.attachShader("./data/shaders/gltf.stereo.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); + graphic.material.attachShader("./data/shaders/gltf.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); + + auto& shader = graphic.material.shaders.back(); + struct SpecializationConstant { + uint32_t textures = 1; + }; + auto* specializationConstants = (SpecializationConstant*) &shader.specializationConstants[0]; + specializationConstants->textures = graphic.material.textures.size(); + for ( auto& binding : shader.descriptorSetLayoutBindings ) { + if ( binding.descriptorCount > 1 ) + binding.descriptorCount = specializationConstants->textures; + } + } + + if ( image != images.end() ) graphic.material.textures.emplace_back().loadFromImage( *(image++) ); + if ( sampler != samplers.end() ) graphic.material.samplers.push_back( *(sampler++) ); + } + for ( auto* collider : collider.getContainer() ) collider->getTransform().reference = &cTransform; + + entity.addChild( *child ); + child->initialize(); + + if ( mode & ext::gltf::LoadMode::APPLY_TRANSFORMS ) cTransform = {}; + } + } else { + auto& mesh = entity.getComponent(); + auto& collider = entity.getComponent(); + size_t id = 0; + for ( auto& primitive : m.primitives ) { + fillMesh( mesh, primitive, collider, id++ ); + } + if ( (mode & ext::gltf::LoadMode::COLLISION) && !(mode & ext::gltf::LoadMode::AABB) ) { - auto* box = new uf::MeshCollider( cTransform ); - box->setPositions( mesh ); - collider.add(box); + auto* c = new uf::MeshCollider( transform ); + c->setPositions( mesh ); + collider.add(c); } + + for ( auto* collider : collider.getContainer() ) collider->getTransform().reference = &transform; + if ( mode & ext::gltf::LoadMode::RENDER ) { - auto& graphic = child->getComponent(); + auto& graphic = entity.getComponent(); if ( mode & ext::gltf::LoadMode::DEFER_INIT ) { graphic.process = false; } else { @@ -276,79 +308,578 @@ void loadNode( uf::Object& entity, const tinygltf::Model& model, const tinygltf: binding.descriptorCount = specializationConstants->textures; } } - - if ( image != images.end() ) graphic.material.textures.emplace_back().loadFromImage( *(image++) ); - if ( sampler != samplers.end() ) graphic.material.samplers.push_back( *(sampler++) ); + if ( useAtlas ) { + atlas.generate(); + graphic.material.textures.emplace_back().loadFromImage( atlas.getAtlas() ); + } else { + for ( auto& image : images ) graphic.material.textures.emplace_back().loadFromImage( image ); + } + for ( auto& sampler : samplers ) graphic.material.samplers.push_back(sampler); } - for ( auto* collider : collider.getContainer() ) collider->getTransform().reference = &cTransform; - - entity.addChild( *child ); - child->initialize(); - - if ( mode & ext::gltf::LoadMode::APPLY_TRANSFORMS ) cTransform = {}; + if ( mode & ext::gltf::LoadMode::APPLY_TRANSFORMS ) transform = {}; } - } else { - auto& mesh = entity.getComponent(); - auto& collider = entity.getComponent(); + } - size_t num = 0; - for ( auto& primitive : m.primitives ) { - fillMesh( mesh, primitive, collider, num++ ); + for ( auto i : node.children ) { + uf::Object* child = new uf::Object; + entity.addChild( *child ); + legacy::loadNode( *child, model, model.nodes[i], mode ); + child->initialize(); + } + } + + void process( uf::Object& entity, const tinygltf::Model& model, ext::gltf::load_mode_t mode ) { + const auto& scene = model.scenes[model.defaultScene > -1 ? model.defaultScene : 0]; + for ( auto i : scene.nodes ) legacy::loadNode( entity, model, model.nodes[i], mode ); + + auto& transform = entity.getComponent>(); + std::function filter = [&]( uf::Entity* child ) { + // add default render behavior + if ( child->hasComponent() ) uf::instantiator::bind("RenderBehavior", *child); + + // parent transform + if ( child == &entity ) return; + if ( !child->hasComponent>() ) return; + child->getComponent>().reference = &transform; + }; + entity.process(filter); + } +} + +namespace { + struct Node { + typedef ext::gltf::skinned_mesh_t Mesh; + + uint32_t index = -1; + + Node* parent = NULL; + std::vector children; + + int32_t skin = -1; + Mesh mesh; + uf::Collider collider; + + pod::Transform<> transform; + pod::Matrix4f local() { + return + uf::matrix::translate( uf::matrix::identity(), transform.position ) * + uf::quaternion::matrix(transform.orientation) * + uf::matrix::scale( uf::matrix::identity(), transform.scale ) * + transform.model; + } + Node* find( int32_t index ) { + if ( parent && parent->index == index ) return parent; + if ( this->index == index ) return this; + + Node* node = NULL; + for ( auto& child : children ) + if ( (node = child->find(index)) ) break; + return node; + } + }; + Node& node() { + Node* pointer = NULL; + if ( uf::MemoryPool::global.size() > 0 ) + pointer = &uf::MemoryPool::global.alloc(); + else + pointer = new Node; + return *pointer; + } + + struct Skin { + std::string name; + Node* root = NULL; + std::vector joints; + std::vector inverseBindMatrices; + }; + struct Animation { + struct Sampler { + std::string interpolator; + std::vector inputs; + std::vector outputs; + }; + struct Channel { + std::string path; + Node* node; + uint32_t sampler; + }; + + std::string name; + std::vector samplers; + std::vector channels; + float start = std::numeric_limits::max(); + float end = std::numeric_limits::min(); + float cur = 0; + }; +} +namespace ext { + namespace gltf { + struct Graph { + Node* node; + uf::Atlas atlas; + std::vector samplers; + std::vector skins; + std::vector animations; + }; + } +} +namespace { + Node& loadNode( ext::gltf::Graph& graph, const tinygltf::Model& model, int32_t nodeIndex, Node& parentNode, ext::gltf::load_mode_t mode ); + Node& loadNodes( ext::gltf::Graph& graph, const tinygltf::Model& model, const std::vector& nodes, Node& node, ext::gltf::load_mode_t mode ); + + Node& loadNode( ext::gltf::Graph& graph, const tinygltf::Model& model, int32_t nodeIndex, Node& parentNode, ext::gltf::load_mode_t mode ) { + auto& newNode = ::node(); + if ( nodeIndex < 0 ) return newNode; + auto& node = model.nodes[nodeIndex]; + newNode.parent = &parentNode; + newNode.index = nodeIndex; + newNode.skin = node.skin; + + auto& transform = newNode.transform; + if ( node.translation.size() == 3 ) { + transform.position.x = node.translation[0]; + transform.position.y = node.translation[1]; + transform.position.z = node.translation[2]; + } + if ( node.rotation.size() == 4 ) { + transform.orientation.x = node.rotation[0]; + transform.orientation.y = node.rotation[1]; + transform.orientation.z = node.rotation[2]; + transform.orientation.w = node.rotation[3]; + } + if ( node.scale.size() == 3 ) { + transform.scale.x = node.scale[0]; + transform.scale.y = node.scale[1]; + transform.scale.z = node.scale[2]; + } + if ( node.matrix.size() == 16 ) { + memcpy( &transform.model[0], node.matrix.data(), node.matrix.size() * sizeof(float) ); + } + + if ( node.children.size() > 0 ) { + loadNodes( graph, model, node.children, newNode, mode ); + } + + auto& mesh = newNode.mesh; + auto& collider = newNode.collider; + if ( node.mesh > -1 ) { + size_t id = 0; + for ( auto& primitive : model.meshes[node.mesh].primitives ) { + size_t verticesStart = mesh.vertices.size(); + size_t indicesStart = mesh.indices.size(); + + size_t vertices = 0; + struct Attribute { + std::string name = ""; + size_t components = 1; + std::vector buffer; + std::vector indices; + }; + std::unordered_map attributes = { + {"POSITION", {}}, + {"TEXCOORD_0", {}}, + {"NORMAL", {}}, + {"JOINTS_0", {}}, + {"WEIGHTS_0", {}}, + }; + + for ( auto& kv : attributes ) { + auto& attribute = kv.second; + attribute.name = kv.first; + auto it = primitive.attributes.find(attribute.name); + if ( it == primitive.attributes.end() ) continue; + + auto& accessor = model.accessors[it->second]; + auto& view = model.bufferViews[accessor.bufferView]; + + if ( attribute.name == "POSITION" ) { + vertices = accessor.count; + pod::Vector3f minCorner = { accessor.minValues[0], accessor.minValues[1], accessor.minValues[2] }; + pod::Vector3f maxCorner = { accessor.maxValues[0], accessor.maxValues[1], accessor.maxValues[2] }; + + pod::Vector3f origin = (maxCorner + minCorner) * 0.5f; + pod::Vector3f size = (maxCorner - minCorner) * 0.5f; + + if ( (mode & ext::gltf::LoadMode::COLLISION) && (mode & ext::gltf::LoadMode::AABB) ) { + auto* box = new uf::BoundingBox( origin, size ); + collider.add(box); + } + } + if ( attribute.name == "JOINTS_0" ) { + auto* buffer = reinterpret_cast(&(model.buffers[view.buffer].data[accessor.byteOffset + view.byteOffset])); + attribute.components = accessor.ByteStride(view) / sizeof(uint16_t); + size_t len = accessor.count * attribute.components; + attribute.indices.reserve( len ); + attribute.indices.insert( attribute.indices.end(), &buffer[0], &buffer[len] ); + } else { + auto* buffer = reinterpret_cast(&(model.buffers[view.buffer].data[accessor.byteOffset + view.byteOffset])); + attribute.components = accessor.ByteStride(view) / sizeof(float); + size_t len = accessor.count * attribute.components; + attribute.buffer.reserve( len ); + attribute.buffer.insert( attribute.buffer.end(), &buffer[0], &buffer[len] ); + } + } + + mesh.vertices.reserve( vertices + verticesStart ); + for ( size_t i = 0; i < vertices; ++i ) { + #define ITERATE_ATTRIBUTE( name, member )\ + if ( !attributes[name].indices.empty() ) { \ + for ( size_t j = 0; j < attributes[name].components; ++j )\ + vertex.member[j] = attributes[name].indices[i * attributes[name].components + j];\ + } else if ( !attributes[name].buffer.empty() ) { \ + for ( size_t j = 0; j < attributes[name].components; ++j )\ + vertex.member[j] = attributes[name].buffer[i * attributes[name].components + j];\ + } + + auto& vertex = mesh.vertices.emplace_back(); + ITERATE_ATTRIBUTE("POSITION", position); + ITERATE_ATTRIBUTE("TEXCOORD_0", uv); + ITERATE_ATTRIBUTE("NORMAL", normal); + ITERATE_ATTRIBUTE("JOINTS_0", joints); + ITERATE_ATTRIBUTE("WEIGHTS_0", weights); + + #undef ITERATE_ATTRIBUTE + if ( !(mode & ext::gltf::LoadMode::SEPARATE_MESHES) && (mode & ext::gltf::LoadMode::USE_ATLAS) ) { + vertex.uv = graph.atlas.mapUv( vertex.uv, id ); + } + vertex.id = id; + } + + if ( primitive.indices > -1 ) { + auto& accessor = model.accessors[primitive.indices]; + auto& view = model.bufferViews[accessor.bufferView]; + auto& buffer = model.buffers[view.buffer]; + + auto indices = static_cast(accessor.count); + mesh.indices.reserve( indices + indicesStart ); + const void* pointer = &(buffer.data[accessor.byteOffset + view.byteOffset]); + + #define COPY_INDICES()\ + for (size_t index = 0; index < indices; index++)\ + mesh.indices.emplace_back(buf[index] + verticesStart); + + switch (accessor.componentType) { + case TINYGLTF_PARAMETER_TYPE_UNSIGNED_INT: { + auto* buf = static_cast( pointer ); + COPY_INDICES() + break; + } + case TINYGLTF_PARAMETER_TYPE_UNSIGNED_SHORT: { + auto* buf = static_cast( pointer ); + COPY_INDICES() + break; + } + case TINYGLTF_PARAMETER_TYPE_UNSIGNED_BYTE: { + auto* buf = static_cast( pointer ); + COPY_INDICES() + break; + } + } + #undef COPY_INDICES + } + // recalc normals + if ( mode & ext::gltf::LoadMode::GENERATE_NORMALS ) { + // bool invert = false; + if ( !mesh.indices.empty() ) { + for ( size_t i = 0; i < mesh.vertices.size(); i+=3 ) { + auto& a = mesh.vertices[i+0].position; + auto& b = mesh.vertices[i+1].position; + auto& c = mesh.vertices[i+2].position; + + pod::Vector3f normal = uf::vector::normalize( uf::vector::cross( b - a, c - a ) ); + mesh.vertices[i+0].normal = normal; + mesh.vertices[i+1].normal = normal; + mesh.vertices[i+2].normal = normal; + } + } else { + for ( size_t i = 0; i < mesh.indices.size(); i+=3 ) { + auto& A = mesh.vertices[mesh.indices[i+0]]; + auto& B = mesh.vertices[mesh.indices[i+1]]; + auto& C = mesh.vertices[mesh.indices[i+2]]; + + auto& a = A.position; + auto& b = B.position; + auto& c = C.position; + + pod::Vector3f normal = uf::vector::normalize( uf::vector::cross( b - a, c - a ) ); + + A.normal = normal; + B.normal = normal; + C.normal = normal; + } + } + } + if ( mode & ext::gltf::LoadMode::APPLY_TRANSFORMS ) { + pod::Matrix4f model = uf::transform::model( transform ); + for ( auto& vertex : mesh.vertices ) { + vertex.position = uf::matrix::multiply( model, vertex.position ); + } + } + ++id; } - + // setup collision if ( (mode & ext::gltf::LoadMode::COLLISION) && !(mode & ext::gltf::LoadMode::AABB) ) { auto* c = new uf::MeshCollider( transform ); c->setPositions( mesh ); collider.add(c); } + } + return newNode; + } + Node& loadNodes( ext::gltf::Graph& graph, const tinygltf::Model& model, const std::vector& nodes, Node& node, ext::gltf::load_mode_t mode ) { + for ( auto i : nodes ) { + node.children.emplace_back(&loadNode( graph, model, i, node, mode )); + } + return node; + } - for ( auto* collider : collider.getContainer() ) collider->getTransform().reference = &transform; + void postProcessEntity( uf::Object& entity, ext::gltf::Graph& graph, ext::gltf::load_mode_t mode ) { + auto& mesh = entity.getComponent(); + auto& transform = entity.getComponent>(); + auto& collider = entity.getComponent(); + + // setup graphic + if ( !(mode & ext::gltf::LoadMode::RENDER) ) return; - if ( mode & ext::gltf::LoadMode::RENDER ) { - auto& graphic = entity.getComponent(); - if ( mode & ext::gltf::LoadMode::DEFER_INIT ) { - graphic.process = false; - } else { - graphic.initialize(); - graphic.initializeGeometry( mesh ); + auto& graphic = entity.getComponent(); - graphic.material.attachShader("./data/shaders/gltf.stereo.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); - graphic.material.attachShader("./data/shaders/gltf.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); - - auto& shader = graphic.material.shaders.back(); - struct SpecializationConstant { - uint32_t textures = 1; - }; - auto* specializationConstants = (SpecializationConstant*) &shader.specializationConstants[0]; - specializationConstants->textures = graphic.material.textures.size(); - for ( auto& binding : shader.descriptorSetLayoutBindings ) { - if ( binding.descriptorCount > 1 ) - binding.descriptorCount = specializationConstants->textures; - } - } - if ( useAtlas ) { - atlas.generate(); - graphic.material.textures.emplace_back().loadFromImage( atlas.getAtlas() ); - } else { - for ( auto& image : images ) graphic.material.textures.emplace_back().loadFromImage( image ); - } - for ( auto& sampler : samplers ) graphic.material.samplers.push_back(sampler); + if ( !(mode & ext::gltf::LoadMode::SEPARATE_MESHES) ) { + for ( auto& image : graph.atlas.getImages() ) { + auto& texture = graphic.material.textures.emplace_back(); + texture.loadFromImage( image ); + } + + for ( auto& sampler : graph.samplers ) + graphic.material.samplers.emplace_back( sampler ); + } + + graphic.initialize(); + graphic.initializeGeometry( mesh ); + if ( mode & ext::gltf::LoadMode::DEFER_INIT ) { + graphic.process = false; + } else { + graphic.material.attachShader("./data/shaders/gltf.stereo.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); + graphic.material.attachShader("./data/shaders/gltf.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); + + auto& shader = graphic.material.shaders.back(); + struct SpecializationConstant { + uint32_t textures = 1; + }; + auto* specializationConstants = (SpecializationConstant*) &shader.specializationConstants[0]; + specializationConstants->textures = graphic.material.textures.size(); + for ( auto& binding : shader.descriptorSetLayoutBindings ) { + if ( binding.descriptorCount > 1 ) + binding.descriptorCount = specializationConstants->textures; } - if ( mode & ext::gltf::LoadMode::APPLY_TRANSFORMS ) transform = {}; } } + void processNode( uf::Object& parent, ext::gltf::Graph& graph, Node& node, ext::gltf::load_mode_t mode, size_t id = 0 ) { + // create child if requested - for ( auto i : node.children ) { - uf::Object* child = new uf::Object; - entity.addChild( *child ); - loadNode( *child, model, model.nodes[i], mode ); - child->initialize(); + uf::Object* pointer = &parent; + if ( mode & ext::gltf::LoadMode::SEPARATE_MESHES ) { + pointer = new uf::Object; + parent.addChild(*pointer); + } + uf::Object& entity = *pointer; + + // copy transform + auto& transform = entity.getComponent>(); + transform = node.transform; + // move colliders + auto& collider = entity.getComponent(); + collider.getContainer().insert( collider.getContainer().end(), node.collider.getContainer().begin(), node.collider.getContainer().end() ); + node.collider.getContainer().clear(); + // copy mesh + auto& mesh = entity.getComponent(); + struct { + size_t vertices = 0; + size_t indices = 0; + } start = { + mesh.vertices.size(), + mesh.indices.size(), + }; + mesh.vertices.reserve( node.mesh.vertices.size() + start.vertices ); + mesh.indices.reserve( node.mesh.indices.size() + start.indices ); + for ( auto& v : node.mesh.vertices ) { + auto& vertex = mesh.vertices.emplace_back( v ); + } + for ( auto& i : node.mesh.indices ) mesh.indices.emplace_back( i + start.indices ); + // copy image + sampler + if ( mode & ext::gltf::LoadMode::RENDER ) { + auto& graphic = entity.getComponent(); + if ( mode & ext::gltf::LoadMode::SEPARATE_MESHES ) { + auto& images = graph.atlas.getImages(); + auto& image = images.front(); + auto& texture = graphic.material.textures.emplace_back(); + texture.loadFromImage( image ); + images.erase( images.begin() ); + + auto& sampler = graph.samplers.front(); + graphic.material.samplers.emplace_back( sampler ); + graph.samplers.erase( graph.samplers.begin() ); + + postProcessEntity( entity, graph, mode ); + } + } + + // go through child nodes + for ( auto* child : node.children ) processNode( entity, graph, *child, mode, ++id ); + } + void processEntity( uf::Object& entity, ext::gltf::load_mode_t mode ) { + auto& graph = entity.getComponent(); + // load vertices into entity for each node + // if separate meshes is requested, each node will have a corresponding entity + processNode( entity, graph, *graph.node, mode ); + // initialize graphic + postProcessEntity( entity, graph, mode ); + /* + // print node tree + std::function print = [&]( Node& node, size_t indent ){ + for ( size_t i = 0; i < indent; ++i ) uf::iostream << "\t"; + uf::iostream << "Node: " << node.index << ":\n"; + for ( auto* child : node.children ) + print( *child, indent + 1 ); + }; + print( *graph.node, 0 ); + uf::iostream << "\n"; + uf::iostream << "Textures: " << graph.atlas.getImages().size() << "\n"; + */ + } + + void process( uf::Object& entity, const tinygltf::Model& model, ext::gltf::load_mode_t mode ) { + auto& graph = entity.getComponent(); + + // load images + { + for ( auto& s : model.samplers ) { + auto& sampler = graph.samplers.emplace_back(); + sampler.descriptor.filter.min = getVkFilterMode( s.minFilter ); + sampler.descriptor.filter.mag = getVkFilterMode( s.magFilter ); + sampler.descriptor.addressMode.u = getVkWrapMode( s.wrapS ); + sampler.descriptor.addressMode.v = getVkWrapMode( s.wrapT ); + sampler.descriptor.addressMode.w = sampler.descriptor.addressMode.v; + } + // auto& images = graph.images; + auto& images = graph.atlas.getImages(); + for ( auto& t : model.textures ) { + auto& im = model.images[t.source]; + // auto& image = graph.images.emplace_back(); + auto& image = images.emplace_back(); + image.loadFromBuffer( &im.image[0], {im.width, im.height}, 8, im.component, true ); + } + graph.atlas.generate(); + } + // load node information/meshes + { + const auto& scene = model.scenes[model.defaultScene > -1 ? model.defaultScene : 0]; + auto& node = ::node(); + graph.node = &loadNodes( graph, model, scene.nodes, node, mode ); + } + // load skins + { + graph.skins.reserve( model.skins.size() ); + for ( auto& s : model.skins ) { + auto& skin = graph.skins.emplace_back(); + skin.name = s.name; + skin.root = graph.node->find(s.skeleton); + + if ( s.inverseBindMatrices > -1 ) { + const tinygltf::Accessor& accessor = model.accessors[s.inverseBindMatrices]; + const tinygltf::BufferView& view = model.bufferViews[accessor.bufferView]; + const tinygltf::Buffer& buffer = model.buffers[view.buffer]; + skin.inverseBindMatrices.resize(accessor.count); + memcpy(skin.inverseBindMatrices.data(), &buffer.data[accessor.byteOffset + view.byteOffset], accessor.count * sizeof(pod::Matrix4f)); + } + + for ( auto& joint : s.joints ) { + auto* node = graph.node->find( joint ); + if ( node ) skin.joints.emplace_back( node ); + } + } + } + // load animations + { + graph.animations.reserve( model.animations.size() ); + for ( auto& a : model.animations ) { + auto& animation = graph.animations.emplace_back(); + animation.name = a.name; + + // load samplers + animation.samplers.reserve( a.samplers.size() ); + for ( auto& s : a.samplers ) { + auto& sampler = animation.samplers.emplace_back(); + sampler.interpolator = s.interpolation; + { + const tinygltf::Accessor& accessor = model.accessors[s.input]; + const tinygltf::BufferView& view = model.bufferViews[accessor.bufferView]; + const tinygltf::Buffer& buffer = model.buffers[view.buffer]; + const void* dataPtr = &buffer.data[accessor.byteOffset + view.byteOffset]; + const float* buf = static_cast(dataPtr); + + for ( size_t i = 0; i < accessor.count; ++i ) + sampler.inputs.push_back( buf[i] ); + + for ( auto& input : sampler.inputs ) { + if ( input < animation.start ) animation.start = input; + else if ( input > animation.end ) animation.end = input; + } + } + { + const tinygltf::Accessor& accessor = model.accessors[s.output]; + const tinygltf::BufferView& view = model.bufferViews[accessor.bufferView]; + const tinygltf::Buffer& buffer = model.buffers[view.buffer]; + const void* dataPtr = &buffer.data[accessor.byteOffset + view.byteOffset]; + switch ( accessor.type ) { + case TINYGLTF_TYPE_VEC3: { + const pod::Vector3f* buf = static_cast(dataPtr); + for ( size_t i = 0; i < accessor.count; ++i ) { + sampler.outputs.emplace_back(pod::Vector4f{ + buf[i].x, + buf[i].y, + buf[i].z, + 0 + }); + } + } break; + case TINYGLTF_TYPE_VEC4: { + const pod::Vector4f* buf = static_cast(dataPtr); + for ( size_t i = 0; i < accessor.count; ++i ) { + sampler.outputs.emplace_back( buf[i] ); + } + } break; + } + } + } + + // load channels + animation.channels.reserve( a.channels.size() ); + for ( auto& c : a.channels ) { + auto& channel = animation.channels.emplace_back(); + channel.path = c.target_path; + channel.sampler = c.sampler; + channel.node = graph.node->find(c.target_node); + } + } + } + + processEntity( entity, mode ); + + auto& transform = entity.getComponent>(); + std::function filter = [&]( uf::Entity* child ) { + // add default render behavior + if ( child->hasComponent() ) uf::instantiator::bind("RenderBehavior", *child); + + // parent transform + if ( child == &entity ) return; + if ( !child->hasComponent>() ) return; + child->getComponent>().reference = &transform; + }; + entity.process(filter); } } -} - -bool ext::gltf::load( uf::Object& entity, const std::string& filename, uint8_t mode ) { +bool ext::gltf::load( uf::Object& entity, const std::string& filename, ext::gltf::load_mode_t mode ) { tinygltf::Model model; tinygltf::TinyGLTF loader; @@ -366,22 +897,8 @@ bool ext::gltf::load( uf::Object& entity, const std::string& filename, uint8_t m return false; } - auto& metadata = entity.getComponent(); - const auto& scene = model.scenes[model.defaultScene > -1 ? model.defaultScene : 0]; - for ( auto i : scene.nodes ) { - loadNode( entity, model, model.nodes[i], mode ); - } - - auto& transform = entity.getComponent>(); - std::function filter = [&]( uf::Entity* child ) { - // add default render behavior - if ( child->hasComponent() ) uf::instantiator::bind("RenderBehavior", *child); - - // parent transform - if ( child == &entity ) return; - if ( !child->hasComponent>() ) return; - child->getComponent>().reference = &transform; - }; - entity.process(filter); +// legacy:: + process( entity, model, mode ); + return true; } \ No newline at end of file diff --git a/engine/src/ext/gltf/mesh.cpp b/engine/src/ext/gltf/mesh.cpp new file mode 100644 index 00000000..fcc47d42 --- /dev/null +++ b/engine/src/ext/gltf/mesh.cpp @@ -0,0 +1,46 @@ +#include + +std::vector ext::gltf::mesh::ID::descriptor = { + { + VK_FORMAT_R32G32B32_SFLOAT, + offsetof(ext::gltf::mesh::ID, position) + }, + { + VK_FORMAT_R32G32_SFLOAT, + offsetof(ext::gltf::mesh::ID, uv) + }, + { + VK_FORMAT_R32G32B32_SFLOAT, + offsetof(ext::gltf::mesh::ID, normal) + }, + { + VK_FORMAT_R32_UINT, + offsetof(ext::gltf::mesh::ID, id) + } +}; +std::vector ext::gltf::mesh::Skinned::descriptor = { + { + VK_FORMAT_R32G32B32_SFLOAT, + offsetof(ext::gltf::mesh::Skinned, position) + }, + { + VK_FORMAT_R32G32_SFLOAT, + offsetof(ext::gltf::mesh::Skinned, uv) + }, + { + VK_FORMAT_R32G32B32_SFLOAT, + offsetof(ext::gltf::mesh::Skinned, normal) + }, + { + VK_FORMAT_R32_UINT, + offsetof(ext::gltf::mesh::Skinned, id) + }, + { + VK_FORMAT_R32G32B32A32_UINT, + offsetof(ext::gltf::mesh::Skinned, joints) + }, + { + VK_FORMAT_R32G32B32A32_SFLOAT, + offsetof(ext::gltf::mesh::Skinned, weights) + }, +}; \ No newline at end of file diff --git a/engine/src/ext/lua/lua.cpp b/engine/src/ext/lua/lua.cpp index 26b85bf7..6c80a0e6 100644 --- a/engine/src/ext/lua/lua.cpp +++ b/engine/src/ext/lua/lua.cpp @@ -80,15 +80,13 @@ void ext::lua::initialize() { auto hooks = state["hooks"].get_or_create(); hooks["add"] = []( const std::string& name, const sol::function& function ) { - uf::hooks.addHook( name, [function]( const std::string& payload )->std::string{ + uf::hooks.addHook( name, [function]( const std::string& payload ) { sol::table table = ext::lua::state["json"]["decode"]( payload ); auto result = function( table ); if ( !result.valid() ) { sol::error err = result; uf::iostream << err.what() << "\n"; - return "false"; } - return "true"; }); }; hooks["call"] = []( const std::string& name, sol::table table = createTable() ) { diff --git a/engine/src/ext/vulkan/buffer.cpp b/engine/src/ext/vulkan/buffer.cpp index b1b3b23e..9f5493ff 100644 --- a/engine/src/ext/vulkan/buffer.cpp +++ b/engine/src/ext/vulkan/buffer.cpp @@ -214,7 +214,7 @@ void ext::vulkan::Buffers::updateBuffer( void* data, VkDeviceSize length, Buffer if ( buffer.allocationInfo.size != length ) { if ( true ) { - VK_VALIDATION_MESSAGE("Mismatch buffer update: Requesting " << buffer.allocationInfo.size << ", got " << length); + VK_VALIDATION_MESSAGE("Mismatch buffer update: Requesting " << buffer.allocationInfo.size << ", got " << length << "; Userdata might've been corrupted, please try validating with shader.validate() before updating buffer"); } else { length = buffer.allocationInfo.size; VK_VALIDATION_MESSAGE("Mismatch buffer update: Requesting " << buffer.allocationInfo.size << ", got " << length << ", resetting for safety"); diff --git a/engine/src/ext/vulkan/device.cpp b/engine/src/ext/vulkan/device.cpp index f8e7d929..4a09f910 100644 --- a/engine/src/ext/vulkan/device.cpp +++ b/engine/src/ext/vulkan/device.cpp @@ -448,18 +448,24 @@ VkCommandPool& ext::vulkan::Device::getCommandPool( ext::vulkan::Device::QueueEn switch ( queueEnum ) { case QueueEnum::GRAPHICS: index = device.queueFamilyIndices.graphics; - if ( commandPool.graphics.count(id) > 0 ) exists = true; - pool = &commandPool.graphics[id]; + // if ( commandPool.graphics.count(id) > 0 ) exists = true; + // pool = &commandPool.graphics[id]; + exists = commandPool.graphics.has(id); + pool = &commandPool.graphics.get(id); break; case QueueEnum::COMPUTE: index = device.queueFamilyIndices.compute; - if ( commandPool.compute.count(id) > 0 ) exists = true; - pool = &commandPool.compute[id]; + // if ( commandPool.compute.count(id) > 0 ) exists = true; + // pool = &commandPool.compute[id]; + exists = commandPool.compute.has(id); + pool = &commandPool.compute.get(id); break; case QueueEnum::TRANSFER: index = device.queueFamilyIndices.transfer; - if ( commandPool.transfer.count(id) > 0 ) exists = true; - pool = &commandPool.transfer[id]; + // if ( commandPool.transfer.count(id) > 0 ) exists = true; + // pool = &commandPool.transfer[id]; + exists = commandPool.transfer.has(id); + pool = &commandPool.transfer.get(id); break; } if ( !exists ) { @@ -480,23 +486,31 @@ VkQueue& ext::vulkan::Device::getQueue( ext::vulkan::Device::QueueEnum queueEnum switch ( queueEnum ) { case QueueEnum::GRAPHICS: index = device.queueFamilyIndices.graphics; - if ( queues.graphics.count(id) > 0 ) exists = true; - queue = &queues.graphics[id]; + exists = queues.graphics.has(id); + queue = &queues.graphics.get(id); + // if ( queues.graphics.count(id) > 0 ) exists = true; + // queue = &queues.graphics[id]; break; case QueueEnum::PRESENT: index = device.queueFamilyIndices.present; - if ( queues.present.count(id) > 0 ) exists = true; - queue = &queues.present[id]; + exists = queues.present.has(id); + queue = &queues.present.get(id); + // if ( queues.present.count(id) > 0 ) exists = true; + // queue = &queues.present[id]; break; case QueueEnum::COMPUTE: index = device.queueFamilyIndices.compute; - if ( queues.compute.count(id) > 0 ) exists = true; - queue = &queues.compute[id]; + exists = queues.compute.has(id); + queue = &queues.compute.get(id); + // if ( queues.compute.count(id) > 0 ) exists = true; + // queue = &queues.compute[id]; break; case QueueEnum::TRANSFER: index = device.queueFamilyIndices.transfer; - if ( queues.transfer.count(id) > 0 ) exists = true; - queue = &queues.transfer[id]; + exists = queues.transfer.has(id); + queue = &queues.transfer.get(id); + // if ( queues.transfer.count(id) > 0 ) exists = true; + // queue = &queues.transfer[id]; break; } if ( !exists ) { @@ -870,15 +884,15 @@ void ext::vulkan::Device::destroy() { vkDestroyPipelineCache( this->logicalDevice, this->pipelineCache, nullptr ); this->pipelineCache = nullptr; } - for ( auto& pair : this->commandPool.graphics ) { + for ( auto& pair : this->commandPool.graphics.container() ) { vkDestroyCommandPool( this->logicalDevice, pair.second, nullptr ); pair.second = VK_NULL_HANDLE; } - for ( auto& pair : this->commandPool.compute ) { + for ( auto& pair : this->commandPool.compute.container() ) { vkDestroyCommandPool( this->logicalDevice, pair.second, nullptr ); pair.second = VK_NULL_HANDLE; } - for ( auto& pair : this->commandPool.transfer ) { + for ( auto& pair : this->commandPool.transfer.container() ) { vkDestroyCommandPool( this->logicalDevice, pair.second, nullptr ); pair.second = VK_NULL_HANDLE; } diff --git a/engine/src/ext/vulkan/graphic.cpp b/engine/src/ext/vulkan/graphic.cpp index c025be3d..0625ef67 100644 --- a/engine/src/ext/vulkan/graphic.cpp +++ b/engine/src/ext/vulkan/graphic.cpp @@ -223,6 +223,27 @@ void ext::vulkan::Shader::destroy() { module = VK_NULL_HANDLE; descriptor = {}; } + for ( auto& userdata : uniforms ) userdata.destroy(); + for ( auto& userdata : pushConstants ) userdata.destroy(); + uniforms.clear(); + pushConstants.clear(); +} + +bool ext::vulkan::Shader::validate() { + // check if uniforms match buffer size + { + auto it = uniforms.begin(); + for ( auto& buffer : buffers ) { + if ( !(buffer.usageFlags & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT) ) continue; + if ( it == uniforms.end() ) break; + auto& uniform = *(it++); + if ( uniform.data().len != buffer.allocationInfo.size ) { + VK_VALIDATION_MESSAGE("Uniform size mismatch: Expected " << buffer.allocationInfo.size << ", got " << uniform.data().len << "; fixing..."); + uniform.destroy(); + uniform.create(buffer.allocationInfo.size); + } + } + } } void ext::vulkan::Pipeline::initialize( Graphic& graphic ) { diff --git a/engine/src/ext/vulkan/rendermode.cpp b/engine/src/ext/vulkan/rendermode.cpp index 88cf7afe..fdbb3878 100644 --- a/engine/src/ext/vulkan/rendermode.cpp +++ b/engine/src/ext/vulkan/rendermode.cpp @@ -50,8 +50,8 @@ ext::vulkan::RenderMode::commands_container_t& ext::vulkan::RenderMode::getComma return getCommands( std::this_thread::get_id() ); } ext::vulkan::RenderMode::commands_container_t& ext::vulkan::RenderMode::getCommands( std::thread::id id ) { - bool exists = this->commands.count(id) > 0; - auto& commands = this->commands[id]; + bool exists = this->commands.has(id); //this->commands.count(id) > 0; + auto& commands = this->commands.get(id); //this->commands[id]; if ( !exists ) { commands.resize( swapchain.buffers ); @@ -195,7 +195,7 @@ void ext::vulkan::RenderMode::destroy() { } commands.clear(); */ - for ( auto& pair : this->commands ) { + for ( auto& pair : this->commands.container() ) { vkFreeCommandBuffers( *device, device->getCommandPool(this->getType() == "Compute" ? Device::QueueEnum::COMPUTE : Device::QueueEnum::GRAPHICS, pair.first), static_cast(pair.second.size()), pair.second.data()); pair.second.clear(); } diff --git a/engine/src/spec/window/universal.cpp b/engine/src/spec/window/universal.cpp index 2b6d0814..15a45576 100644 --- a/engine/src/spec/window/universal.cpp +++ b/engine/src/spec/window/universal.cpp @@ -4,7 +4,7 @@ #include #include - +/* void UF_API_CALL spec::uni::Window::pushEvent( const uf::ReadableHook::name_t& name, const uf::ReadableHook::argument_t& argument ) { if ( !uf::hooks.prefersReadable() ) return; if ( !uf::hooks.exists(name) ) return; @@ -43,12 +43,42 @@ void UF_API_CALL spec::uni::Window::pushEvent( const uf::OptimalHook::argument_t } this->m_events.optimal.back().argument = userdata; } +*/ +void UF_API_CALL spec::uni::Window::pushEvent( const uf::Hooks::name_t& name, const std::string& payload ) { + uf::Userdata userdata; + userdata.create( payload ); + this->m_events.push({ name, std::move(userdata) }); +} +void UF_API_CALL spec::uni::Window::pushEvent( const uf::Hooks::name_t& name, const uf::Hooks::argument_t& payload ) { + this->m_events.push({ name, std::move(payload) }); +} +void UF_API_CALL spec::uni::Window::pushEvent( const uf::Hooks::argument_t& payload ) { + struct Header { + std::string type; + }; + const Header& header = payload.get
(); + if ( !uf::hooks.exists(header.type) ) return; + this->m_events.push({ header.type, std::move(payload) }); +} void UF_API_CALL spec::uni::Window::processEvents() { } bool UF_API_CALL spec::uni::Window::isKeyPressed(const std::string& key) { return false; } bool UF_API_CALL spec::uni::Window::pollEvents( bool block ) { + if ( this->m_events.empty() ) { + do { + this->processEvents(); + } while ( block && this->m_events.empty() ); + } + + while ( !this->m_events.empty() ) { + auto& event = this->m_events.front(); + uf::hooks.call( event.name, event.payload ); + this->m_events.pop(); + } + return true; +#if 0 /* Empty; look for something! */ if ( this->m_events.readable.empty() && this->m_events.optimal.empty() ) { do { this->processEvents(); @@ -88,4 +118,5 @@ bool UF_API_CALL spec::uni::Window::pollEvents( bool block ) { // this->m_events.readable.clear(); // flush queue in case } return true; +#endif } \ No newline at end of file diff --git a/engine/src/spec/window/windows.cpp b/engine/src/spec/window/windows.cpp index 2563f287..e17fb365 100644 --- a/engine/src/spec/window/windows.cpp +++ b/engine/src/spec/window/windows.cpp @@ -2,6 +2,8 @@ #include #include +#define USE_OPTIMAL 0 + #if defined(UF_ENV_WINDOWS) && (!defined(UF_USE_SFML) || (defined(UF_USE_SFML) && UF_USE_SFML == 0)) namespace { int windowCount = 0; @@ -468,7 +470,7 @@ void UF_API_CALL spec::win32::Window::processEvents() { auto code = this->getKey(key, 0); event.key.code = code; event.key.raw = key; - this->pushEvent(event.type + "." + code, uf::userdata::create(event)); + if ( USE_OPTIMAL ) this->pushEvent(event.type + "." + code, uf::Userdata(uf::userdata::create(event))); json["key"]["code"] = code; json["key"]["raw"] = key; @@ -479,6 +481,37 @@ void UF_API_CALL spec::win32::Window::processEvents() { } } bool UF_API_CALL spec::win32::Window::pollEvents( bool block ) { + if ( this->m_events.empty() ) { + do { + this->processEvents(); + } while ( block && this->m_events.empty() ); + } + + while ( !this->m_events.empty() ) { + auto& event = this->m_events.front(); + if ( event.payload.is() ) { + std::string payload = event.payload.as(); + uf::hooks.call( "window:Event", payload ); + uf::hooks.call( event.name, payload ); + } else { + uf::Userdata payload; + payload.copy(event.payload); + + uf::hooks.call( "window:Event", payload ); + uf::hooks.call( event.name, payload ); + } + /* + try { + uf::hooks.call( "window:Event", payload ); + uf::hooks.call( event.name, payload ); + } catch ( ... ) { + // Let the hook handler handle the exceptions + } + */ + this->m_events.pop(); + } + return true; +#if 0 /* Empty; look for something! */ if ( this->m_events.readable.empty() && this->m_events.optimal.empty() ) { do { this->processEvents(); @@ -490,7 +523,7 @@ bool UF_API_CALL spec::win32::Window::pollEvents( bool block ) { // process things while ( !this->m_events.readable.empty() ) { auto& event = this->m_events.readable.front(); - uf::hooks.call( event.name, event.argument ); + uf::hooks.call( event.name, event.argument ); /* try { uf::hooks.call( "window:Event", event.argument ); @@ -508,7 +541,7 @@ bool UF_API_CALL spec::win32::Window::pollEvents( bool block ) { // process things while ( !this->m_events.optimal.empty() ) { auto& event = this->m_events.optimal.front(); - uf::hooks.call( event.name, event.argument ); + uf::hooks.call( event.name, event.argument ); /* try { uf::hooks.call( "window:Event", event.argument ); @@ -524,6 +557,7 @@ bool UF_API_CALL spec::win32::Window::pollEvents( bool block ) { // this->m_events.readable.clear(); // flush queue in case } return true; +#endif } void UF_API_CALL spec::win32::Window::registerWindowClass() { @@ -565,7 +599,7 @@ void UF_API_CALL spec::win32::Window::processEvent(UINT message, WPARAM wParam, event.type = "window:Closed"; event.invoker = "os"; }; - this->pushEvent(event.type, uf::userdata::create(event)); { + if ( USE_OPTIMAL ) this->pushEvent(event.type, uf::Userdata(uf::userdata::create(event))); { json["type"] = event.type; json["invoker"] = event.invoker; this->pushEvent(event.type, json); @@ -588,7 +622,7 @@ void UF_API_CALL spec::win32::Window::processEvent(UINT message, WPARAM wParam, event.invoker = "os"; event.window.size = this->m_lastSize; }; - this->pushEvent(event.type, uf::userdata::create(event)); { + if ( USE_OPTIMAL ) this->pushEvent(event.type, uf::Userdata(uf::userdata::create(event))); { json["type"] = event.type; json["invoker"] = event.invoker; json["window"]["size"]["x"] = event.window.size.x; @@ -621,7 +655,7 @@ void UF_API_CALL spec::win32::Window::processEvent(UINT message, WPARAM wParam, event.invoker = "os"; event.window.size = this->m_lastSize; }; - this->pushEvent(event.type, uf::userdata::create(event)); { + if ( USE_OPTIMAL ) this->pushEvent(event.type, uf::Userdata(uf::userdata::create(event))); { json["type"] = event.type; json["invoker"] = event.invoker; json["window"]["size"]["x"] = event.window.size.x; @@ -637,7 +671,7 @@ void UF_API_CALL spec::win32::Window::processEvent(UINT message, WPARAM wParam, event.type = "window:Moved"; event.invoker = "os"; }; - this->pushEvent(event.type, uf::userdata::create(event)); { + if ( USE_OPTIMAL ) this->pushEvent(event.type, uf::Userdata(uf::userdata::create(event))); { json["type"] = event.type; json["invoker"] = event.invoker; this->pushEvent(event.type, json); @@ -677,7 +711,7 @@ void UF_API_CALL spec::win32::Window::processEvent(UINT message, WPARAM wParam, case WM_KILLFOCUS: event.window.state = -1; break; } }; - this->pushEvent(event.type, uf::userdata::create(event)); { + if ( USE_OPTIMAL ) this->pushEvent(event.type, uf::Userdata(uf::userdata::create(event))); { json["type"] = event.type; json["invoker"] = event.invoker; switch ( message ) { @@ -729,7 +763,7 @@ void UF_API_CALL spec::win32::Window::processEvent(UINT message, WPARAM wParam, event.text.unicode = std::string(utf8.begin(), utf8.end()); }; if ( this->m_syncParse ) { - this->pushEvent(event.type, uf::userdata::create(event)); + if ( USE_OPTIMAL ) this->pushEvent(event.type, uf::Userdata(uf::userdata::create(event))); json["type"] = event.type; json["invoker"] = event.invoker; @@ -784,7 +818,7 @@ void UF_API_CALL spec::win32::Window::processEvent(UINT message, WPARAM wParam, } } if ( this->m_syncParse ) { - this->pushEvent(event.type + "." + event.key.code, uf::userdata::create(event)); + if ( USE_OPTIMAL ) this->pushEvent(event.type + "." + event.key.code, uf::Userdata(uf::userdata::create(event))); json["type"] = event.type + "." + ((event.key.state == -1)?"Pressed":"Released"); json["invoker"] = event.invoker; json["key"]["state"] = (event.key.state == -1) ? "Down" : "Up"; @@ -825,7 +859,7 @@ void UF_API_CALL spec::win32::Window::processEvent(UINT message, WPARAM wParam, event.mouse.position.y = position.y; event.mouse.delta = delta / 120; }; - this->pushEvent(event.type, uf::userdata::create(event)); { + if ( USE_OPTIMAL ) this->pushEvent(event.type, uf::Userdata(uf::userdata::create(event))); { json["type"] = event.type; json["invoker"] = event.invoker; @@ -893,7 +927,7 @@ void UF_API_CALL spec::win32::Window::processEvent(UINT message, WPARAM wParam, } }; if ( true || this->m_syncParse ){ - this->pushEvent(event.type, uf::userdata::create(event)); + if ( USE_OPTIMAL ) this->pushEvent(event.type, uf::Userdata(uf::userdata::create(event))); json["type"] = event.type; json["invoker"] = event.invoker; @@ -936,7 +970,7 @@ void UF_API_CALL spec::win32::Window::processEvent(UINT message, WPARAM wParam, event.mouse.state = -1; }; - this->pushEvent(event.type, uf::userdata::create(event)); { + if ( USE_OPTIMAL ) this->pushEvent(event.type, uf::Userdata(uf::userdata::create(event))); { json["type"] = event.type; json["invoker"] = event.invoker; @@ -1003,7 +1037,7 @@ void UF_API_CALL spec::win32::Window::processEvent(UINT message, WPARAM wParam, event.mouse.size = {area.right, area.bottom}; event.mouse.delta = event.mouse.position - lastPosition; } - this->pushEvent(event.type, uf::userdata::create(event)); { + if ( USE_OPTIMAL ) this->pushEvent(event.type, uf::Userdata(uf::userdata::create(event))); { json["type"] = event.type; json["invoker"] = event.invoker; diff --git a/engine/src/utils/hook/hook.cpp b/engine/src/utils/hook/hook.cpp index efa70aaa..fc84c0bf 100644 --- a/engine/src/utils/hook/hook.cpp +++ b/engine/src/utils/hook/hook.cpp @@ -1,7 +1,85 @@ #include #include // uf::iostream -uf::HookHandler uf::hooks; +size_t uf::Hooks::uids = 0; +uf::Hooks uf::hooks; + +size_t uf::Hooks::addHook( const uf::Hooks::name_t& name, const pod::Hook::function_t& callback, size_t type ) { + auto& hook = this->m_container[name].emplace_back(); + hook.uid = ++uids; + hook.type = type; + hook.callback = callback; + + return hook.uid; +} +void uf::Hooks::removeHook( const uf::Hooks::name_t& name, size_t uid ) { + auto& container = this->m_container[name]; + for ( auto it = container.begin(); it != container.end(); ++it ) { + if ( it->uid == uid ) { + this->m_container[name].erase(it); + break; + } + } +} +uf::Hooks::return_t uf::Hooks::call( const uf::Hooks::name_t& name, const uf::Userdata& payload ) { + auto& container = this->m_container[name]; + std::vector results; + results.reserve( container.size() ); + for ( auto& hook : container ) { + uf::Userdata hookResult = hook.callback(payload); + auto& returnResult = results.emplace_back(); + returnResult.move( hookResult ); + + // results.emplace_back(std::move()); + } + return results; +} +uf::Hooks::return_t uf::Hooks::call( const uf::Hooks::name_t& name, const std::string& s ) { + uf::Userdata payload; + payload.create( s ); + return call(name, payload); +} +uf::Hooks::return_t uf::Hooks::call( const uf::Hooks::name_t& name, const uf::Serializer& s ) { + uf::Userdata payload; + payload.create( s.serialize() ); + return call(name, payload); +} +// specialization: void function +size_t uf::Hooks::addHook( const uf::Hooks::name_t& name, const std::function& callback ) { + return addHook( name, [=]( const uf::Userdata& userdata ){ + callback(); + uf::Userdata ret; + return ret; + }); +} +/* +// specialization: serialized JSON handling +size_t uf::Hooks::addHook( const uf::Hooks::name_t& name, const std::function& callback ) { + return addHook( name, [=]( const uf::Userdata& userdata ){ + std::string payload = userdata.is() ? userdata.get() : ""; + callback( payload ); + uf::Userdata ret; + return ret; + }); +} +// specialization: legacy callback handling +size_t uf::Hooks::addHook( const uf::Hooks::name_t& name, const std::function& callback ) { + return addHook( name, [=]( const uf::Userdata& userdata ){ + std::string payload = userdata.is() ? userdata.get() : ""; + std::string res = callback( payload ); + + uf::Userdata ret; + ret.create(res); + return ret; + }); +} +*/ +bool uf::Hooks::exists( const uf::Hooks::name_t& name ) { + return this->m_container.count(name) > 0; +} + +#if 0 +uf::HookHandler uf::hooks; namespace { std::size_t hooks = 0; } @@ -287,4 +365,5 @@ uf::HookHandler::return_vector_t UF_API_CALL uf::HookHandler::call( const uf::Ho return returns; } -*/ \ No newline at end of file +*/ +#endif \ No newline at end of file diff --git a/engine/src/utils/image/atlas.cpp b/engine/src/utils/image/atlas.cpp index 93a9e7b6..92c9188b 100644 --- a/engine/src/utils/image/atlas.cpp +++ b/engine/src/utils/image/atlas.cpp @@ -15,46 +15,58 @@ void uf::Atlas::addImage( const uint8_t* pointer, const pod::Vector2ui& size, st if ( regenerate ) this->generate(); } -void uf::Atlas::generate() { +void uf::Atlas::generate( float padding ) { if ( this->m_images.empty() ) return; // destroy atlas this->m_image.clear(); BinPack2D::ContentAccumulator queue; pod::Vector2ui size = {0,0}; + pod::Vector3ui largest = {0,0,0}; size_t index = 0; size_t area = 0; for ( auto& image : this->m_images ) { auto& dim = image.getDimensions(); + queue += BinPack2D::Content({index++}, BinPack2D::Coord(), BinPack2D::Size(dim.x, dim.y), false ); size += dim; area += dim.x * dim.y; - queue += BinPack2D::Content({index++}, BinPack2D::Coord(), BinPack2D::Size(dim.x, dim.y), false ); - } - { - size_t side = std::sqrt( area ); - size = { side, side }; - { - size.x--; - size.x |= size.x >> 1; - size.x |= size.x >> 2; - size.x |= size.x >> 4; - size.x |= size.x >> 8; - size.x |= size.x >> 16; - size.x++; - size.y--; - size.y |= size.y >> 1; - size.y |= size.y >> 2; - size.y |= size.y >> 4; - size.y |= size.y >> 8; - size.y |= size.y >> 16; - size.y++; + if ( area >= largest.z ) { + largest.x = dim.x; + largest.y = dim.y; } - this->m_image.loadFromBuffer( NULL, size, 8, 4 ); } - queue.Sort(); - this->m_atlas = BinPack2D::UniformCanvasArrayBuilder(size.x, size.y ,1).Build(); + size_t tries = 16; BinPack2D::ContentAccumulator stored, remainder; - bool success = this->m_atlas.Place( queue, remainder ); + do { + { + // size_t area = largest.x * largest.y * this->m_images.size(); + size_t side = std::sqrt( area ) * padding; + size = { side, side }; + { + size.x--; + size.x |= size.x >> 1; + size.x |= size.x >> 2; + size.x |= size.x >> 4; + size.x |= size.x >> 8; + size.x |= size.x >> 16; + size.x++; + size.y--; + size.y |= size.y >> 1; + size.y |= size.y >> 2; + size.y |= size.y >> 4; + size.y |= size.y >> 8; + size.y |= size.y >> 16; + size.y++; + } + } + queue.Sort(); + this->m_atlas = BinPack2D::UniformCanvasArrayBuilder(size.x, size.y, 1).Build(); + bool success = this->m_atlas.Place( queue, remainder ); + if ( success && remainder.Get().empty() ) break; + // increase padding + padding += 0.10f; + } while ( --tries ); + this->m_image.loadFromBuffer( NULL, size, 8, 4 ); this->m_atlas.CollectContent( stored ); auto& dstBuffer = this->m_image.getPixels(); @@ -122,4 +134,167 @@ uf::Atlas::images_t& uf::Atlas::getImages() { } const uf::Atlas::images_t& uf::Atlas::getImages() const { return this->m_images; +} + + + + + + + + + +#include +#include + +uf::HashAtlas::hash_t uf::HashAtlas::addImage( const uf::Image& _image, bool regenerate ) { + auto hash = _image.getHash(); + if ( this->has( hash ) ) return hash; + + auto& image = *(this->m_images.emplace(hash, _image)).first; + if ( regenerate ) this->generate(); + + return hash; +} +uf::HashAtlas::hash_t uf::HashAtlas::addImage( uf::Image&& _image, bool regenerate ) { + auto hash = _image.getHash(); + if ( this->has( hash ) ) return hash; + + auto& image = *(this->m_images.emplace(hash, _image)).first; + if ( regenerate ) this->generate(); + + return hash; +} +uf::HashAtlas::hash_t uf::HashAtlas::addImage( const uint8_t* pointer, const pod::Vector2ui& size, std::size_t bpp, std::size_t channels, bool flip, bool regenerate ) { + uf::Image image; + image.loadFromBuffer( pointer, size, bpp, channels, flip ); + std::string hash = image.getHash(); + if ( this->has( hash ) ) return hash; + this->m_images.emplace( hash, std::move(image) ); + if ( regenerate ) this->generate(); + return hash; + +} +bool uf::HashAtlas::has( const uf::Image& image ) const { + return this->has( image.getHash() ); +} +bool uf::HashAtlas::has( const std::string& hash ) const { + return this->m_images.count(hash) > 0; +} +void uf::HashAtlas::generate( float padding ) { + if ( this->m_images.empty() ) return; + // destroy atlas + this->m_image.clear(); + + BinPack2D::ContentAccumulator queue; + pod::Vector2ui size = {0,0}; + pod::Vector3ui largest = {0,0,0}; + size_t index = 0; + size_t area = 0; + for ( auto& pair : this->m_images ) { + auto hash = pair.first; + auto& dim = pair.second.getDimensions(); + queue += BinPack2D::Content({hash}, BinPack2D::Coord(), BinPack2D::Size(dim.x, dim.y), false ); + size += dim; + area += dim.x * dim.y; + if ( area >= largest.z ) { + largest.x = dim.x; + largest.y = dim.y; + } + } + size_t tries = 16; + BinPack2D::ContentAccumulator stored, remainder; + do { + { + // size_t area = largest.x * largest.y * this->m_images.size(); + size_t side = std::sqrt( area ) * padding; + size = { side, side }; + { + size.x--; + size.x |= size.x >> 1; + size.x |= size.x >> 2; + size.x |= size.x >> 4; + size.x |= size.x >> 8; + size.x |= size.x >> 16; + size.x++; + size.y--; + size.y |= size.y >> 1; + size.y |= size.y >> 2; + size.y |= size.y >> 4; + size.y |= size.y >> 8; + size.y |= size.y >> 16; + size.y++; + } + } + queue.Sort(); + this->m_atlas = BinPack2D::UniformCanvasArrayBuilder(size.x, size.y ,1).Build(); + bool success = this->m_atlas.Place( queue, remainder ); + if ( success && remainder.Get().empty() ) break; + // increase padding + padding += 0.10f; + } while ( --tries ); + this->m_image.loadFromBuffer( NULL, size, 8, 4 ); + this->m_atlas.CollectContent( stored ); + + auto& dstBuffer = this->m_image.getPixels(); + + for ( size_t i = 0; i < size.x * size.y * 4; i+=4 ) { + dstBuffer[i+0] = 0; + dstBuffer[i+1] = 0; + dstBuffer[i+2] = 0; + dstBuffer[i+3] = 0; + } + + for ( auto& it : stored.Get() ) { + auto& hash = it.content.hash; + auto& image = this->m_images[hash]; + auto& dim = image.getDimensions(); + auto channels = image.getChannels(); + auto& srcBuffer = image.getPixels(); + + for ( size_t y = 0; y < dim.y; ++y ) { + for ( size_t x = 0; x < dim.x; ++x ) { + size_t src = (y * dim.x * channels) + (x * channels); + size_t dst = ((y + it.coord.y) * size.x * 4) + ((x + it.coord.x) * 4); + for ( size_t i = 0; i < channels; ++i ) { + dstBuffer[dst+i] = srcBuffer[src+i]; + } + } + } + } +} +void uf::HashAtlas::clear() { + this->m_images.clear(); + this->m_image.clear(); + this->m_atlas = uf::HashAtlas::atlas_t{}; +} +pod::Vector2f uf::HashAtlas::mapUv( const pod::Vector2f& uv, const uf::HashAtlas::hash_t& hash ) { + BinPack2D::ContentAccumulator stored; + this->m_atlas.CollectContent( stored ); + auto& size = this->m_image.getDimensions(); + for ( auto& it : stored.Get() ) { + if ( it.content.hash != hash ) continue; + auto& image = this->m_images[hash]; + auto& dim = image.getDimensions(); + pod::Vector2f nuv = uv; + if ( nuv.x > 1.0f ) nuv.x = std::fmod( nuv.x, 1.0f ); + if ( nuv.y > 1.0f ) nuv.y = std::fmod( nuv.y, 1.0f ); + // while ( nuv.x > 1.0f ) nuv.x -= 1.0f; + // while ( nuv.y > 1.0f ) nuv.y -= 1.0f; + + pod::Vector2ui coord = { uv.x * dim.x + it.coord.x, uv.y * dim.y + it.coord.y }; + nuv = { (float) coord.x / (float) size.x, (float) coord.y / (float) size.y }; + nuv.y = 1.0f - nuv.y; + return nuv; + } + return uv; +} +uf::Image& uf::HashAtlas::getAtlas() { + return this->m_image; +} +uf::HashAtlas::images_t& uf::HashAtlas::getImages() { + return this->m_images; +} +const uf::HashAtlas::images_t& uf::HashAtlas::getImages() const { + return this->m_images; } \ No newline at end of file diff --git a/engine/src/utils/image/image.cpp b/engine/src/utils/image/image.cpp index 7be51a37..7d4e96f9 100644 --- a/engine/src/utils/image/image.cpp +++ b/engine/src/utils/image/image.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include // std::fstream #include // std::fstream @@ -290,6 +291,7 @@ void uf::Image::copy( const Image::container_t& copy, const Image::vec2_t& size } // D-tor uf::Image::~Image() { + this->clear(); } // empties pixel container void uf::Image::clear() { @@ -327,6 +329,9 @@ std::size_t& uf::Image::getChannels() { std::size_t uf::Image::getChannels() const { return this->m_channels; } +std::string uf::Image::getHash() const { + return uf::string::sha256( this->m_pixels ); +} uf::Image::pixel_t uf::Image::at( const uf::Image::vec2_t& at ) { std::size_t i = at.x * this->m_channels + this->m_dimensions.x*this->m_channels*at.y; uf::Image::pixel_t pixel; @@ -456,4 +461,13 @@ uf::Image uf::Image::subImage( const Image::vec2_t& start, const Image::vec2_t& image.format = this->format; return image; */ +} + +uf::Image& uf::Image::operator=( const uf::Image& copy ) { + this->m_pixels = copy.m_pixels; + this->m_dimensions = copy.m_dimensions; + this->m_bpp = copy.m_bpp; + this->m_channels = copy.m_channels; + this->m_filename = copy.m_filename; + return *this; } \ No newline at end of file diff --git a/engine/src/utils/mempool/mempool.cpp b/engine/src/utils/mempool/mempool.cpp index 9d7e4604..be4ac1f6 100644 --- a/engine/src/utils/mempool/mempool.cpp +++ b/engine/src/utils/mempool/mempool.cpp @@ -5,9 +5,11 @@ #include #include #include +#include +#include namespace { - bool IGNORE_GLOBAL_MEMORYPOOL = false; + uf::ThreadUnique globalOverrides; } #define DEBUG_PRINT 0 @@ -79,7 +81,7 @@ pod::Allocation uf::MemoryPool::allocate( void* data, size_t size ) { pod::Allocation allocation; // pool not initialized if ( len <= 0 ) { - if ( DEBUG_PRINT ) std::cout << "CANNOT MALLOC: " << size << ", POOL NOT INITIALIZED" << std::endl; + if ( DEBUG_PRINT ) uf::iostream << "CANNOT MALLOC: " << size << ", POOL NOT INITIALIZED" << "\n"; goto MANUAL_MALLOC; } @@ -116,10 +118,10 @@ pod::Allocation uf::MemoryPool::allocate( void* data, size_t size ) { else memset( allocation.pointer, 0, size ); // overrides if we're overloading global new/delete - IGNORE_GLOBAL_MEMORYPOOL = true; + globalOverrides.get() = true; // register as allocated this->m_allocations.insert(next, allocation); - IGNORE_GLOBAL_MEMORYPOOL = false; + globalOverrides.get() = false; goto RETURN; } @@ -139,7 +141,9 @@ pod::Allocation uf::MemoryPool::allocate( void* data, size_t size ) { } // no allocation found, OOM if ( index + size > len ) { - std::cout << "MemoryPool: " << this << ": Out of Memory!" << std::endl; + uf::iostream << "MemoryPool: " << this << ": Out of Memory!\n"; + uf::iostream << "Trying to request " << size << " bytes of memory\n"; + uf::iostream << "Stats: " << this->stats() << "\n"; goto MANUAL_MALLOC; } @@ -153,10 +157,10 @@ pod::Allocation uf::MemoryPool::allocate( void* data, size_t size ) { else memset( allocation.pointer, 0, size ); // overrides if we're overloading global new/delete - IGNORE_GLOBAL_MEMORYPOOL = true; + globalOverrides.get() = true; // register as allocated this->m_allocations.insert(next, allocation); - IGNORE_GLOBAL_MEMORYPOOL = false; + globalOverrides.get() = false; } goto RETURN; MANUAL_MALLOC: @@ -169,7 +173,7 @@ MANUAL_MALLOC: } RETURN: if ( UF_MEMORYPOOL_MUTEX ) this->m_mutex.unlock(); - if ( DEBUG_PRINT ) std::cout << "MALLOC'd: " << allocation.pointer << ", " << allocation.size << ", " << allocation.index << std::endl; + if ( DEBUG_PRINT ) uf::iostream << "MALLOC'd: " << allocation.pointer << ", " << allocation.size << ", " << allocation.index << "\n"; return allocation; } void* uf::MemoryPool::alloc( void* data, size_t size ) { @@ -201,7 +205,7 @@ bool uf::MemoryPool::free( void* pointer, size_t size ) { if ( UF_MEMORYPOOL_MUTEX ) this->m_mutex.lock(); // fail if uninitialized or pointer is outside of our pool if ( this->m_size <= 0 || pointer < &this->m_pool[0] || pointer >= &this->m_pool[0] + this->m_size ) { - if ( DEBUG_PRINT ) std::cout << "CANNOT FREE: " << pointer << ", ERROR: " << (this->m_size <= 0) << " " << (pointer < &this->m_pool[0]) << " " << (pointer >= &this->m_pool[0] + this->m_size) << std::endl; + if ( DEBUG_PRINT ) uf::iostream << "CANNOT FREE: " << pointer << ", ERROR: " << (this->m_size <= 0) << " " << (pointer < &this->m_pool[0]) << " " << (pointer >= &this->m_pool[0] + this->m_size) << "\n"; goto MANUAL_FREE; } { @@ -218,15 +222,15 @@ bool uf::MemoryPool::free( void* pointer, size_t size ) { } // pointer isn't actually allocated if ( allocation.index != index ) { - if ( DEBUG_PRINT ) std::cout << "CANNOT FREE: " << pointer << ", NOT FOUND" << std::endl; + if ( DEBUG_PRINT ) uf::iostream << "CANNOT FREE: " << pointer << ", NOT FOUND" << "\n"; goto MANUAL_FREE; } // size validation mismatch, do not free if (size > 0 && allocation.size != size) { - if ( DEBUG_PRINT ) std::cout << "CANNOT FREE: " << pointer << ", MISMATCHED SIZES (" << size << " != " << allocation.size << ")" << std::endl; + if ( DEBUG_PRINT ) uf::iostream << "CANNOT FREE: " << pointer << ", MISMATCHED SIZES (" << size << " != " << allocation.size << ")" << "\n"; goto MANUAL_FREE; } - if ( DEBUG_PRINT ) std::cout << "FREE'D ALLOCATION: " << pointer << ", " << size << "\t" << allocation.pointer << ", " << allocation.size << ", " << allocation.index << std::endl; + if ( DEBUG_PRINT ) uf::iostream << "FREE'D ALLOCATION: " << pointer << ", " << size << "\t" << allocation.pointer << ", " << allocation.size << ", " << allocation.index << "\n"; // remove from our allocation table... this->m_allocations.erase(it); // ...but add it to our free'd allocation cache @@ -247,7 +251,7 @@ const uf::MemoryPool::allocations_t& uf::MemoryPool::allocations() const { } #if UF_MEMORYPOOL_OVERRIDE_NEW_DELETE void* operator new( size_t size ) { - if ( !uf::MemoryPool::globalOverride || IGNORE_GLOBAL_MEMORYPOOL || uf::MemoryPool::global.size() <= 0 ) + if ( !uf::MemoryPool::globalOverride || globalOverrides.get() || uf::MemoryPool::global.size() <= 0 ) return malloc(size); return uf::MemoryPool::global.alloc( (void*) NULL, size ); } diff --git a/engine/src/utils/serialize/serializer.cpp b/engine/src/utils/serialize/serializer.cpp index d2f01d4d..d6af18ac 100644 --- a/engine/src/utils/serialize/serializer.cpp +++ b/engine/src/utils/serialize/serializer.cpp @@ -112,6 +112,22 @@ void uf::Serializer::merge( const uf::Serializer& other, bool priority ) { update(*this, other); } +void uf::Serializer::import( const uf::Serializer& other ) { + if ( !ext::json::isObject( *this ) || !ext::json::isObject( other ) ) return; + + std::function update = [&]( Json::Value& a, const Json::Value& b ) { + // doesn't exist, just copy it + if ( ext::json::isNull( a ) && !ext::json::isNull( b ) ) { + a = b; + // exists, iterate through children + } else if ( ext::json::isObject( a ) && ext::json::isObject( b ) ) { + for ( const auto& key : b.getMemberNames() ) + update(a[key], b[key]); + } + }; + + update(*this, other); +} uf::Serializer::operator Serializer::output_t() { return this->serialize(); diff --git a/engine/src/utils/type/type.cpp b/engine/src/utils/type/type.cpp new file mode 100644 index 00000000..daced6a0 --- /dev/null +++ b/engine/src/utils/type/type.cpp @@ -0,0 +1,50 @@ +#include +#include + +#include +#include +namespace { + std::string demangle( const std::string& mangled ) { + + int status = -4; + std::unique_ptr demangled{ + abi::__cxa_demangle(mangled.c_str(), NULL, NULL, &status), + std::free + }; + return ( status == 0 ) ? demangled.get() : mangled; + /* + int status; + char* pointer = abi::__cxa_demangle(mangled.c_str(), 0, 0, &status); + std::string demangled; + demangled.copy( pointer, strlen(pointer) ); + free(pointer); + return demangled; + */ + } +} + +std::unordered_map* uf::typeInfo::types = NULL; +void uf::typeInfo::registerType( const index_t& index, size_t size, const std::string& pretty ) { + if ( !uf::typeInfo::types ) uf::typeInfo::types = new std::unordered_map; + bool exists = uf::typeInfo::types->count(index) > 0; + auto& type = (*uf::typeInfo::types)[index]; + if ( !exists || type.size < size ) type.size = size; + if ( !exists ) type.hash = index.hash_code(); + if ( !exists ) type.name.compiler = index.name(); + if ( !exists || pretty != "" ) type.name.pretty = pretty != "" ? pretty : demangle( type.name.compiler ); + + // if ( !exists ) uf::iostream << "Registered type " << type.name.pretty << " (Mangled: " << type.name.compiler << ") of size " << size << "\n"; +} +const pod::TypeInfo& UF_API uf::typeInfo::getType( size_t hash ) { + if ( !uf::typeInfo::types ) uf::typeInfo::types = new std::unordered_map; + auto& types = *uf::typeInfo::types; + for ( auto& pair : types ) { + if ( pair.second.hash == hash ) return pair.second; + } + static pod::TypeInfo null; + return null; +} +const pod::TypeInfo& uf::typeInfo::getType( const index_t& index ) { + if ( !uf::typeInfo::types ) uf::typeInfo::types = new std::unordered_map; + return (*uf::typeInfo::types)[index]; +} \ No newline at end of file diff --git a/engine/src/utils/userdata/userdata.cpp b/engine/src/utils/userdata/userdata.cpp index d0fd7eb7..fa8181af 100644 --- a/engine/src/utils/userdata/userdata.cpp +++ b/engine/src/utils/userdata/userdata.cpp @@ -4,64 +4,28 @@ #include // memcpy #include -// Description: Allows abstract creation of anything -// Use: hook subsystem for passing hook data -/* Todo: - * [?] create a singleton class to destroy any remaining userdata - */ - uf::MemoryPool uf::userdata::memoryPool; // Constructs a pod::Userdata struct pod::Userdata* UF_API uf::userdata::create( std::size_t len, void* data ) { return uf::userdata::create( uf::userdata::memoryPool, len, data ); -/* - if ( uf::userdata::memoryPool.size() > 0 ) return uf::userdata::create( uf::userdata::memoryPool, len, data ); -#if UF_USERDATA_KLUDGE - void* pointer = operator new( sizeof(pod::Userdata) + len ); // allocate data for the userdata struct, and then some -// void* pointer = malloc( sizeof(pod::Userdata) + sizeof(uint8_t) * len ); // allocate data for the userdata struct, and then some - pod::Userdata& userdata = *(pod::Userdata*) pointer; // cast to reference - if ( data ) memcpy( userdata.data, data, len ); // copy contents from data to Userdata's data - else memset( userdata.data, 0, len ); - userdata.len = len; // don't forget to store its data's length! - userdata.pointer = NULL; //&userdata.data[0]; - return &userdata; // return address of userdata -#else - pod::Userdata* userdata = new pod::Userdata; - userdata->len = len; - userdata->data = (uint8_t*) operator new(len); - if ( data ) memcpy( userdata->data, data, len ); - else memset( userdata->data, 0, len ); - return userdata; -#endif -*/ } void UF_API uf::userdata::destroy( pod::Userdata* userdata ) { return uf::userdata::destroy( uf::userdata::memoryPool, userdata ); -/* - if ( uf::userdata::memoryPool.size() > 0 ) return uf::userdata::destroy( uf::userdata::memoryPool, userdata ); -#if UF_USERDATA_KLUDGE - if ( userdata->pointer ) return; // allocated with a pool, do not free - delete[] userdata; -#else - delete[] userdata->data; - userdata->len = 0; - userdata->data = NULL; - delete userdata; -#endif -*/ +} +pod::Userdata* UF_API uf::userdata::copy( const pod::Userdata* userdata ) { + return uf::userdata::copy( uf::userdata::memoryPool, userdata ); } size_t uf::userdata::size( size_t len, size_t padding ) { - padding = 0; - // return sizeof(pod::Userdata) + len + ( sizeof(uint8_t) * padding ); - return sizeof(size_t) + len + ( sizeof(uint8_t) * padding ); + // padding = 0; + // return sizeof(size_t) + len + ( sizeof(uint8_t) * padding ); + return sizeof(pod::Userdata) - sizeof(uint8_t) + len; } // pod::Userdata* UF_API uf::userdata::create( uf::MemoryPool& requestedMemoryPool, std::size_t len, void* data ) { if ( len <= 0 ) return NULL; size_t requestedLen = size( len ); -// uf::MemoryPool& memoryPool = uf::MemoryPool::global.size() > 0 ? uf::MemoryPool::global : requestedMemoryPool; #if UF_MEMORYPOOL_INVALID_MALLOC uf::MemoryPool& memoryPool = requestedMemoryPool.size() > 0 ? requestedMemoryPool : uf::MemoryPool::global; pod::Userdata* userdata = (pod::Userdata*) memoryPool.alloc( data, requestedLen ); @@ -79,65 +43,32 @@ pod::Userdata* UF_API uf::userdata::create( uf::MemoryPool& requestedMemoryPool, } #endif userdata->len = len; + userdata->type = typeid(NULL).hash_code(); return userdata; -/* - if ( uf::userdata::memoryPool.size() > 0 ) { - auto allocation = uf::userdata::memoryPool.allocate( NULL, requestedLen ); - pod::Userdata* userdata = (pod::Userdata*) allocation.pointer; - if ( data ) memcpy( userdata->data, data, len ); - else memset( userdata->data, 0, len ); - userdata->len = len; - #if UF_USERDATA_KLUDGE - userdata->pointer = NULL; - #endif - return userdata; - } else { - if ( memoryPool.size() <= 0 ) return uf::userdata::create( len, data ); - pod::Userdata* userdata = new pod::Userdata; - auto allocation = memoryPool.allocate( data, len ); - userdata->len = allocation.size; - #if UF_USERDATA_KLUDGE - userdata->pointer = (uint8_t*) allocation.pointer; - #else - userdata->data = (uint8_t*) allocation.pointer; - #endif - return userdata; - } -*/ } -#include void UF_API uf::userdata::destroy( uf::MemoryPool& requestedMemoryPool, pod::Userdata* userdata ) { -// uf::MemoryPool& memoryPool = uf::MemoryPool::global.size() > 0 ? uf::MemoryPool::global : requestedMemoryPool; - #if UF_MEMORYPOOL_INVALID_FREE uf::MemoryPool& memoryPool = requestedMemoryPool.size() > 0 ? requestedMemoryPool : uf::MemoryPool::global; - memoryPool.free( userdata, sizeof(pod::Userdata) + userdata->len ); + memoryPool.free( userdata, size(userdata->len) ); #else uf::MemoryPool* memoryPool = NULL; if ( requestedMemoryPool.size() > 0 ) memoryPool = &requestedMemoryPool; else if ( uf::MemoryPool::global.size() > 0 ) memoryPool = &uf::MemoryPool::global; - if ( memoryPool ) memoryPool->free( userdata, sizeof(pod::Userdata) + userdata->len ); + if ( memoryPool ) memoryPool->free( userdata, size(userdata->len) ); else { // free(userdata); delete[] userdata; } #endif -/* - if ( uf::userdata::memoryPool.size() > 0 ) { - memoryPool.free( userdata, sizeof(pod::Userdata) + userdata->len ); - userdata->len = 0; - } else { - #if UF_USERDATA_KLUDGE - if ( !userdata->pointer ) { - uf::userdata::destroy( userdata ); - return; - } - #endif - memoryPool.free( userdata->data, userdata->len ); - delete userdata; - } -*/ +} +pod::Userdata* UF_API uf::userdata::copy( uf::MemoryPool& requestedMemoryPool, const pod::Userdata* userdata ) { + if ( !userdata || userdata->len <= 0 ) return NULL; + auto* copied = uf::userdata::create( userdata->len, const_cast(userdata->data) ); +#if UF_USERDATA_RTTI +// copied->type = userdata->type; +#endif + return copied; } std::string UF_API uf::userdata::toBase64( pod::Userdata* userdata ) { @@ -154,6 +85,11 @@ uf::Userdata::Userdata(std::size_t len, void* data) : m_pod(NULL) { if ( len && data ) this->create(len, data); } +// Initializes from POD +uf::Userdata::Userdata( pod::Userdata* pointer ) : m_pod(pointer) { + +} + // Move c-tor uf::Userdata::Userdata( Userdata&& move ) : m_pod(std::move(move.m_pod)) @@ -161,31 +97,42 @@ uf::Userdata::Userdata( Userdata&& move ) : } // Copy c-tor -uf::Userdata::Userdata( const Userdata& copy ) { - if ( copy.m_pod && copy.m_pod->len ) this->create( copy.m_pod->len, copy.m_pod->data ); +uf::Userdata::Userdata( const Userdata& userdata ) { + this->copy( userdata ); } // Creates the POD -pod::Userdata* uf::Userdata::create( std::size_t len ) { - if ( len <= 0 ) return NULL; - this->destroy(); - return this->m_pod = uf::userdata::create( len, NULL ); -} pod::Userdata* uf::Userdata::create( std::size_t len, void* data ) { if ( len <= 0 ) return NULL; this->destroy(); return this->m_pod = uf::userdata::create( len, data ); } -void uf::Userdata::move( Userdata&& move ) { +void uf::Userdata::move( Userdata& moved ) { // if ( this->m_pod && move.m_pod ) uf::userdata::move( *this->m_pod, *move.m_pod ); - std::cout << "MOVE: " << this << " <- " << &move << ", " << this->m_pod << " <- " << move.m_pod << std::endl; - this->m_pod = move.m_pod; - move.m_pod = NULL; + this->destroy(); + this->m_pod = moved.m_pod; + moved.m_pod = NULL; } -void uf::Userdata::copy( const Userdata& copy ) { +void uf::Userdata::move( Userdata&& moved ) { +// if ( this->m_pod && move.m_pod ) uf::userdata::move( *this->m_pod, *move.m_pod ); + this->destroy(); + this->m_pod = moved.m_pod; + moved.m_pod = NULL; +} +void uf::Userdata::copy( const Userdata& userdata ) { + if ( !userdata.m_pod || !userdata.m_pod->len ) return; + this->destroy(); +// this->m_pod = uf::userdata::copy( userdata.m_pod ); + this->create( userdata.m_pod->len, userdata.m_pod->data ); +#if UF_USERDATA_RTTI +// this->m_pod->type = userdata.m_pod->type; +#endif +/* // if ( this->m_pod && copy.m_pod ) uf::userdata::copy( *this->m_pod, *copy.m_pod ); - std::cout << "COPY: " << this << " <- " << © << ", " << this->m_pod << " <- " << copy.m_pod << std::endl; - if ( copy.m_pod ) this->create( copy.m_pod->len, copy.m_pod->data ); + if ( !userdata ) return; + this->destroy(); +// this->m_pod = uf::userdata::copy( userdata.m_pod ); +*/ } // D-tor uf::Userdata::~Userdata() { @@ -226,6 +173,10 @@ uf::Userdata::operator bool() const { return this->initialized(); } +uf::Userdata& uf::Userdata::operator=( pod::Userdata* pointer ) { + this->m_pod = pointer; + return *this; +} uf::Userdata& uf::Userdata::operator=( Userdata&& move ) { if ( this->m_pod && move.m_pod ) this->m_pod = move.m_pod, move.m_pod = NULL; return *this; diff --git a/engine/src/utils/window/window.cpp b/engine/src/utils/window/window.cpp index 7646d7fa..6602f599 100644 --- a/engine/src/utils/window/window.cpp +++ b/engine/src/utils/window/window.cpp @@ -135,7 +135,7 @@ void UF_API_CALL uf::Window::display() { // Display the backbuffer on screen if (this->m_context && this->setActive()) this->m_context->display(); - /* FPS */ { + /* FPS */ if ( false ) { static double limit = 1.0 / 60; static uf::Timer timer(false); if ( !timer.running() ) timer.start(); @@ -145,15 +145,6 @@ void UF_API_CALL uf::Window::display() { timer.reset(); } } - -/* - // Limit the framerate if needed - if (m_frameTimeLimit != Time::Zero) - { - sleep(m_frameTimeLimit - m_clock.getElapsedTime()); - m_clock.restart(); - } -*/ } #endif \ No newline at end of file diff --git a/ext/behaviors/player/behavior.cpp b/ext/behaviors/player/behavior.cpp index bea1ea9b..b4f90a57 100644 --- a/ext/behaviors/player/behavior.cpp +++ b/ext/behaviors/player/behavior.cpp @@ -131,6 +131,7 @@ void ext::PlayerBehavior::initialize( uf::Object& self ) { uf::Serializer json = event; // discard events sent by os, only trust client now + if ( !ext::json::isObject(json) ) return "true"; if ( json["invoker"] != "client" ) return "true"; pod::Vector2i delta = { json["mouse"]["delta"]["x"].as(), json["mouse"]["delta"]["y"].as() }; diff --git a/ext/behaviors/scene/behavior.cpp b/ext/behaviors/scene/behavior.cpp index 42c5c8d8..fe264747 100644 --- a/ext/behaviors/scene/behavior.cpp +++ b/ext/behaviors/scene/behavior.cpp @@ -118,10 +118,10 @@ void ext::ExtSceneBehavior::initialize( uf::Object& self ) { return "true"; }); /* store viewport size */ { - metadata["system"]["window"]["size"]["x"] = uf::renderer::settings::width; - metadata["system"]["window"]["size"]["y"] = uf::renderer::settings::height; - ext::gui::size.current.x = uf::renderer::settings::width; - ext::gui::size.current.y = uf::renderer::settings::height; +// metadata["system"]["window"]["size"]["x"] = uf::renderer::settings::width; +// metadata["system"]["window"]["size"]["y"] = uf::renderer::settings::height; +// ext::gui::size.current.x = uf::renderer::settings::width; +// ext::gui::size.current.y = uf::renderer::settings::height; this->addHook( "window:Resized", [&](const std::string& event)->std::string{ uf::Serializer json = event; diff --git a/ext/gui/behavior.cpp b/ext/gui/behavior.cpp index 90a79ae2..d591c453 100644 --- a/ext/gui/behavior.cpp +++ b/ext/gui/behavior.cpp @@ -659,13 +659,13 @@ void ext::GuiBehavior::initialize( uf::Object& self ) { } return; } - { - float delay = 0.0f; - float scale = metadata["text settings"]["scale"].as(); - auto& transform = this->getComponent>(); - transform.scale.x = scale; - transform.scale.y = scale; + if ( false ) { + uf::Serializer payload; + payload["first"] = true; + payload["string"] = metadata["text settings"]["string"]; + this->callHook("gui:UpdateString.%UID%", payload); + } else { std::vector glyphs = this->as().generateGlyphs(); std::string font = "./data/fonts/" + metadata["text settings"]["font"].as(); @@ -678,46 +678,51 @@ void ext::GuiBehavior::initialize( uf::Object& self ) { key += metadata["text settings"]["sdf"].as(); } auto& scene = uf::scene::getCurrentScene(); - auto& atlas = this->getComponent(); + auto& atlas = this->getComponent(); auto& images = atlas.getImages(); auto& mesh = this->getComponent(); - auto& graphic = this->getComponent(); mesh.vertices.reserve( glyphs.size() * 6 ); + + std::unordered_map glyphHashMap; for ( auto& g : glyphs ) { - auto& glyph = ::glyphs.cache[font][std::to_string((uint64_t) g.code) + ";"+key]; - // add bitmap to atlas - uf::Image& image = images.emplace_back(); - const uint8_t* buffer = glyph.getBuffer(); - uf::Image::container_t pixels; - std::size_t len = glyph.getSize().x * glyph.getSize().y; - pixels.insert( pixels.end(), buffer, buffer + len ); - image.loadFromBuffer( pixels, glyph.getSize(), 8, 1, true ); - // add vertices - mesh.vertices.push_back({pod::Vector3f{ g.box.x, g.box.y + g.box.h, 0 }, pod::Vector2f{ 0.0f, 0.0f }, g.color}); - mesh.vertices.push_back({pod::Vector3f{ g.box.x, g.box.y , 0 }, pod::Vector2f{ 0.0f, 1.0f }, g.color}); - mesh.vertices.push_back({pod::Vector3f{ g.box.x + g.box.w, g.box.y , 0 }, pod::Vector2f{ 1.0f, 1.0f }, g.color}); - mesh.vertices.push_back({pod::Vector3f{ g.box.x, g.box.y + g.box.h, 0 }, pod::Vector2f{ 0.0f, 0.0f }, g.color}); - mesh.vertices.push_back({pod::Vector3f{ g.box.x + g.box.w, g.box.y , 0 }, pod::Vector2f{ 1.0f, 1.0f }, g.color}); - mesh.vertices.push_back({pod::Vector3f{ g.box.x + g.box.w, g.box.y + g.box.h, 0 }, pod::Vector2f{ 1.0f, 0.0f }, g.color}); + auto glyphKey = std::to_string((uint64_t) g.code) + ";"+key; + auto& glyph = ::glyphs.cache[font][glyphKey]; + + glyphHashMap[glyphKey] = atlas.addImage( glyph.getBuffer(), glyph.getSize(), 8, 1, true ); } atlas.generate(); - - for ( size_t i = 0, k = 0; i < mesh.vertices.size(); ++k, i += 6 ) { + + float scale = metadata["text settings"]["scale"].as(); + auto& transform = this->getComponent>(); + transform.scale.x = scale; + transform.scale.y = scale; + + for ( auto& g : glyphs ) { + auto glyphKey = std::to_string((uint64_t) g.code) + ";"+key; + auto& glyph = ::glyphs.cache[font][glyphKey]; + auto hash = glyphHashMap[glyphKey]; + // add vertices + mesh.vertices.push_back({pod::Vector3f{ g.box.x, g.box.y + g.box.h, 0 }, atlas.mapUv( pod::Vector2f{ 0.0f, 0.0f }, hash ), g.color}); + mesh.vertices.push_back({pod::Vector3f{ g.box.x, g.box.y , 0 }, atlas.mapUv( pod::Vector2f{ 0.0f, 1.0f }, hash ), g.color}); + mesh.vertices.push_back({pod::Vector3f{ g.box.x + g.box.w, g.box.y , 0 }, atlas.mapUv( pod::Vector2f{ 1.0f, 1.0f }, hash ), g.color}); + mesh.vertices.push_back({pod::Vector3f{ g.box.x, g.box.y + g.box.h, 0 }, atlas.mapUv( pod::Vector2f{ 0.0f, 0.0f }, hash ), g.color}); + mesh.vertices.push_back({pod::Vector3f{ g.box.x + g.box.w, g.box.y , 0 }, atlas.mapUv( pod::Vector2f{ 1.0f, 1.0f }, hash ), g.color}); + mesh.vertices.push_back({pod::Vector3f{ g.box.x + g.box.w, g.box.y + g.box.h, 0 }, atlas.mapUv( pod::Vector2f{ 1.0f, 0.0f }, hash ), g.color}); + } + for ( size_t i = 0; i < mesh.vertices.size(); i += 6 ) { for ( size_t j = 0; j < 6; ++j ) { auto& vertex = mesh.vertices[i+j]; vertex.position.x /= ext::gui::size.reference.x; vertex.position.y /= ext::gui::size.reference.y; - vertex.uv = atlas.mapUv( vertex.uv, k ); vertex.uv.y = 1 - vertex.uv.y; } } auto& texture = graphic.material.textures.emplace_back(); texture.loadFromImage( atlas.getAtlas() ); - graphic.initialize( "Gui" ); graphic.initializeGeometry( mesh ); @@ -759,8 +764,6 @@ void ext::GuiBehavior::initialize( uf::Object& self ) { } std::string string = metadata["text settings"]["string"].as(); - float delay = 0.0f; - float scale = metadata["text settings"]["scale"].as(); std::vector glyphs = this->as().generateGlyphs( string ); std::string font = "./data/fonts/" + metadata["text settings"]["font"].as(); @@ -772,88 +775,85 @@ void ext::GuiBehavior::initialize( uf::Object& self ) { key += metadata["text settings"]["font"].as() + ";"; key += metadata["text settings"]["sdf"].as(); } - auto& transform = this->getComponent>(); auto& scene = uf::scene::getCurrentScene(); - auto& atlas = this->getComponent(); + auto& atlas = this->getComponent(); auto& images = atlas.getImages(); auto& mesh = this->getComponent(); - auto& graphic = this->getComponent(); - - atlas.clear(); - mesh.vertices.clear(); - mesh.indices.clear(); + if ( !json["first"].as() ) { + atlas.clear(); + mesh.vertices.clear(); + mesh.indices.clear(); + + for ( auto& texture : graphic.material.textures ) texture.destroy(); + graphic.material.textures.clear(); + } mesh.vertices.reserve( glyphs.size() * 6 ); + + std::unordered_map glyphHashMap; for ( auto& g : glyphs ) { - auto& glyph = ::glyphs.cache[font][std::to_string((uint64_t) g.code) + ";"+key]; - // add bitmap to atlas - uf::Image& image = images.emplace_back(); - const uint8_t* buffer = glyph.getBuffer(); - uf::Image::container_t pixels; - std::size_t len = glyph.getSize().x * glyph.getSize().y; - pixels.insert( pixels.end(), buffer, buffer + len ); - image.loadFromBuffer( pixels, glyph.getSize(), 8, 1, true ); - // add vertices - mesh.vertices.push_back({pod::Vector3f{ g.box.x, g.box.y + g.box.h, 0 }, pod::Vector2f{ 0.0f, 0.0f }, g.color}); - mesh.vertices.push_back({pod::Vector3f{ g.box.x, g.box.y , 0 }, pod::Vector2f{ 0.0f, 1.0f }, g.color}); - mesh.vertices.push_back({pod::Vector3f{ g.box.x + g.box.w, g.box.y , 0 }, pod::Vector2f{ 1.0f, 1.0f }, g.color}); - mesh.vertices.push_back({pod::Vector3f{ g.box.x, g.box.y + g.box.h, 0 }, pod::Vector2f{ 0.0f, 0.0f }, g.color}); - mesh.vertices.push_back({pod::Vector3f{ g.box.x + g.box.w, g.box.y , 0 }, pod::Vector2f{ 1.0f, 1.0f }, g.color}); - mesh.vertices.push_back({pod::Vector3f{ g.box.x + g.box.w, g.box.y + g.box.h, 0 }, pod::Vector2f{ 1.0f, 0.0f }, g.color}); + auto glyphKey = std::to_string((uint64_t) g.code) + ";"+key; + auto& glyph = ::glyphs.cache[font][glyphKey]; + + glyphHashMap[glyphKey] = atlas.addImage( glyph.getBuffer(), glyph.getSize(), 8, 1, true ); } atlas.generate(); + float scale = metadata["text settings"]["scale"].as(); + auto& transform = this->getComponent>(); transform.scale.x = scale; transform.scale.y = scale; - for ( size_t i = 0, k = 0; i < mesh.vertices.size(); ++k, i += 6 ) { + + for ( auto& g : glyphs ) { + auto glyphKey = std::to_string((uint64_t) g.code) + ";"+key; + auto& glyph = ::glyphs.cache[font][glyphKey]; + auto hash = glyphHashMap[glyphKey]; + // add vertices + mesh.vertices.push_back({pod::Vector3f{ g.box.x, g.box.y + g.box.h, 0 }, atlas.mapUv( pod::Vector2f{ 0.0f, 0.0f }, hash ), g.color}); + mesh.vertices.push_back({pod::Vector3f{ g.box.x, g.box.y , 0 }, atlas.mapUv( pod::Vector2f{ 0.0f, 1.0f }, hash ), g.color}); + mesh.vertices.push_back({pod::Vector3f{ g.box.x + g.box.w, g.box.y , 0 }, atlas.mapUv( pod::Vector2f{ 1.0f, 1.0f }, hash ), g.color}); + mesh.vertices.push_back({pod::Vector3f{ g.box.x, g.box.y + g.box.h, 0 }, atlas.mapUv( pod::Vector2f{ 0.0f, 0.0f }, hash ), g.color}); + mesh.vertices.push_back({pod::Vector3f{ g.box.x + g.box.w, g.box.y , 0 }, atlas.mapUv( pod::Vector2f{ 1.0f, 1.0f }, hash ), g.color}); + mesh.vertices.push_back({pod::Vector3f{ g.box.x + g.box.w, g.box.y + g.box.h, 0 }, atlas.mapUv( pod::Vector2f{ 1.0f, 0.0f }, hash ), g.color}); + } + for ( size_t i = 0; i < mesh.vertices.size(); i += 6 ) { for ( size_t j = 0; j < 6; ++j ) { auto& vertex = mesh.vertices[i+j]; vertex.position.x /= ext::gui::size.reference.x; vertex.position.y /= ext::gui::size.reference.y; - vertex.uv = atlas.mapUv( vertex.uv, k ); vertex.uv.y = 1 - vertex.uv.y; } } - for ( auto& texture : graphic.material.textures ) texture.destroy(); - graphic.material.textures.clear(); - - auto& texture = graphic.material.textures.emplace_back(); - texture.loadFromImage( atlas.getAtlas() ); - // graphic.descriptor.indices = 0; - graphic.initializeGeometry( mesh ); - graphic.getPipeline().update( graphic ); - // graphic.updatePipelines(); - // uf::renderer::rebuild = true; - - /* - graphic.destroy(); - auto& texture = graphic.material.textures.emplace_back(); texture.loadFromImage( atlas.getAtlas() ); - graphic.initialize( "Gui" ); - graphic.initializeGeometry( mesh ); + if ( json["first"].as() ) { + graphic.initialize( "Gui" ); + graphic.initializeGeometry( mesh ); - std::string suffix = ""; { - std::string _ = scene.getComponent()["shaders"]["gui"]["suffix"].as(); - if ( _ != "" ) suffix = _ + "."; + std::string suffix = ""; { + std::string _ = scene.getComponent()["shaders"]["gui"]["suffix"].as(); + if ( _ != "" ) suffix = _ + "."; + } + struct { + std::string vertex = "./data/shaders/gui.text.vert.spv"; + std::string fragment = "./data/shaders/gui.text.frag.spv"; + } filenames; + if ( metadata["shaders"]["vertex"].is() ) filenames.vertex = metadata["shaders"]["vertex"].as(); + if ( metadata["shaders"]["fragment"].is() ) filenames.fragment = metadata["shaders"]["fragment"].as(); + else if ( suffix != "" ) filenames.fragment = "./data/shaders/gui.text."+suffix+"frag.spv"; + + graphic.material.initializeShaders({ + {filenames.vertex, VK_SHADER_STAGE_VERTEX_BIT}, + {filenames.fragment, VK_SHADER_STAGE_FRAGMENT_BIT}, + }); + } else { + graphic.initializeGeometry( mesh ); + graphic.getPipeline().update( graphic ); } - struct { - std::string vertex = "./data/shaders/gui.text.vert.spv"; - std::string fragment = "./data/shaders/gui.text.frag.spv"; - } filenames; - if ( metadata["shaders"]["vertex"].is() ) filenames.vertex = metadata["shaders"]["vertex"].as(); - if ( metadata["shaders"]["fragment"].is() ) filenames.fragment = metadata["shaders"]["fragment"].as(); - else if ( suffix != "" ) filenames.fragment = "./data/shaders/gui.text."+suffix+"frag.spv"; - - graphic.material.initializeShaders({ - {filenames.vertex, VK_SHADER_STAGE_VERTEX_BIT}, - {filenames.fragment, VK_SHADER_STAGE_FRAGMENT_BIT}, - }); - */ return "true"; }); diff --git a/ext/gui/manager/behavior.cpp b/ext/gui/manager/behavior.cpp index d1e6ad81..2766200b 100644 --- a/ext/gui/manager/behavior.cpp +++ b/ext/gui/manager/behavior.cpp @@ -32,8 +32,8 @@ ext::gui::Size ext::gui::size = { .current = { - uf::renderer::settings::width, - uf::renderer::settings::height, + 0, + 0, }, .reference = { 1920, @@ -47,8 +47,8 @@ UF_BEHAVIOR_REGISTER_AS_OBJECT(ext::GuiManagerBehavior, ext::GuiManager) #define this (&self) void ext::GuiManagerBehavior::initialize( uf::Object& self ) { { - ext::gui::size.current.x = uf::renderer::settings::width; - ext::gui::size.current.y = uf::renderer::settings::height; + // ext::gui::size.current.x = uf::renderer::settings::width; + // ext::gui::size.current.y = uf::renderer::settings::height; } // add gui render mode if ( !uf::renderer::hasRenderMode( "Gui", true ) ) { diff --git a/ext/main.cpp b/ext/main.cpp index 6b7a2a5b..67bdd2ca 100644 --- a/ext/main.cpp +++ b/ext/main.cpp @@ -3,7 +3,6 @@ #include #include #include -#include #include @@ -515,10 +514,12 @@ void EXT_API ext::tick() { if ( !timer.running() ) timer.start(); if ( uf::Window::isKeyPressed("P") && timer.elapsed().asDouble() >= 1 ) { timer.reset(); // uf::iostream << uf::renderer::allocatorStats() << "\n"; - if ( uf::MemoryPool::global.size() > 0 ) uf::iostream << "Global Memory Pool:\n" << uf::MemoryPool::global.stats() << "\n"; - if ( uf::Entity::memoryPool.size() > 0 ) uf::iostream << "Entity Memory Pool:\n" << uf::Entity::memoryPool.stats() << "\n"; - if ( uf::component::memoryPool.size() > 0 ) uf::iostream << "Components Memory Pool:\n" << uf::component::memoryPool.stats() << "\n"; - if ( uf::userdata::memoryPool.size() > 0 ) uf::iostream << "Userdata Memory Pool:\n" << uf::userdata::memoryPool.stats() << "\n"; + uf::iostream << "==== Memory Pool Information ===="; + if ( uf::MemoryPool::global.size() > 0 ) uf::iostream << "\nGlobal Memory Pool: " << uf::MemoryPool::global.stats(); + if ( uf::Entity::memoryPool.size() > 0 ) uf::iostream << "\nEntity Memory Pool: " << uf::Entity::memoryPool.stats(); + if ( uf::component::memoryPool.size() > 0 ) uf::iostream << "\nComponents Memory Pool: " << uf::component::memoryPool.stats(); + if ( uf::userdata::memoryPool.size() > 0 ) uf::iostream << "\nUserdata Memory Pool: " << uf::userdata::memoryPool.stats(); + uf::iostream << "\n"; } } /* Attempt to reset VR position */ { diff --git a/ext/scenes/worldscape/gui/dialogue.cpp b/ext/scenes/worldscape/gui/dialogue.cpp index 1e8e4360..d5ce5ab8 100644 --- a/ext/scenes/worldscape/gui/dialogue.cpp +++ b/ext/scenes/worldscape/gui/dialogue.cpp @@ -265,7 +265,7 @@ void ext::GuiDialogue::tick() { uf::Serializer payload; payload["action"] = "dialogue-select"; payload["index"] = stats.actions.index; - uf::Serializer result = uf::hooks.call("menu:Dialogue.Action." + std::to_string(dialogueManager->getUid()), payload)[0]; + uf::Serializer result = dialogueManager->callHook("menu:Dialogue.Action.%UID%", payload)[0]; postParseResult(result); // renderDialogueOptions(std::string(""));