Commit for 2020.11.21.7z

This commit is contained in:
mrq 2020-11-21 00:00:00 -06:00
parent 71299d1284
commit 1b7203d4fd
53 changed files with 2074 additions and 952 deletions

View File

@ -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<bool>());
@ -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<std::string>() == "fullscreen" ) client::window.switchToFullscreen();
if ( client::config["window"]["mode"].as<std::string>() == "borderless" ) client::window.switchToFullscreen( true );

View File

@ -1,3 +1,5 @@
#include <uf/utils/type/type.h>
template<typename C>
typename pod::NamedTypes<C>::type_t pod::NamedTypes<C>::getType( const std::string& name ) {
for ( auto pair : names ) if ( pair.second == name ) return pair.first;

View File

@ -1,17 +0,0 @@
#pragma once
#include <uf/config.h>
#if defined(UF_USE_ASSIMP)
#include <string>
#include <uf/gl/mesh/mesh.h>
#include <uf/gl/mesh/skeletal/mesh.h>
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

View File

@ -1,11 +1,14 @@
#pragma once
#include "mesh.h"
#include <uf/engine/object/object.h>
#include <uf/utils/graphic/mesh.h>
namespace ext {
namespace gltf {
typedef uf::BaseMesh<pod::Vertex_3F2F3F1UI, uint32_t> mesh_t;
namespace gltf {
// typedef uf::BaseMesh<ext::gltf::mesh::ID, uint32_t> mesh_t;
typedef uf::BaseMesh<ext::gltf::mesh::Skinned, uint32_t> mesh_t;
typedef uf::BaseMesh<ext::gltf::mesh::Skinned, uint32_t> 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 );
}
}

View File

@ -0,0 +1,73 @@
#pragma once
#include <uf/utils/graphic/mesh.h>
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<ext::vulkan::VertexDescriptor> 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<ext::vulkan::VertexDescriptor> 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<ext::gltf::mesh::ID> {
size_t operator()(ext::gltf::mesh::ID const& vertex) const {
std::size_t seed = 3 + 2 + 3 + 1;
std::hash<float> 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<ext::gltf::mesh::Skinned> {
size_t operator()(ext::gltf::mesh::Skinned const& vertex) const {
std::size_t seed = 3 + 2 + 3 + 4 + 4 + 1;
std::hash<float> 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;
}
};
}

View File

@ -4,6 +4,7 @@
#include <uf/ext/vulkan/buffer.h>
#include <uf/utils/window/window.h>
#include <uf/utils/thread/thread.h>
#include <uf/utils/thread/perthread.h>
namespace ext {
namespace vulkan {
@ -14,9 +15,12 @@ namespace ext {
VkPhysicalDevice physicalDevice;
VkDevice logicalDevice;
struct {
std::unordered_map<std::thread::id, VkCommandPool> graphics;
std::unordered_map<std::thread::id, VkCommandPool> compute;
std::unordered_map<std::thread::id, VkCommandPool> transfer;
// std::unordered_map<std::thread::id, VkCommandPool> graphics;
// std::unordered_map<std::thread::id, VkCommandPool> compute;
// std::unordered_map<std::thread::id, VkCommandPool> transfer;
uf::ThreadUnique<VkCommandPool> graphics;
uf::ThreadUnique<VkCommandPool> compute;
uf::ThreadUnique<VkCommandPool> transfer;
} commandPool;
VkPhysicalDeviceProperties properties;
@ -43,10 +47,14 @@ namespace ext {
std::vector<VkQueueFamilyProperties> queueFamilyProperties;
struct {
std::unordered_map<std::thread::id,VkQueue> graphics;
std::unordered_map<std::thread::id,VkQueue> present;
std::unordered_map<std::thread::id,VkQueue> compute;
std::unordered_map<std::thread::id,VkQueue> transfer;
// std::unordered_map<std::thread::id,VkQueue> graphics;
// std::unordered_map<std::thread::id,VkQueue> present;
// std::unordered_map<std::thread::id,VkQueue> compute;
// std::unordered_map<std::thread::id,VkQueue> transfer;
uf::ThreadUnique<VkQueue> graphics;
uf::ThreadUnique<VkQueue> present;
uf::ThreadUnique<VkQueue> compute;
uf::ThreadUnique<VkQueue> transfer;
} queues;
uf::Window* window;

View File

@ -44,14 +44,13 @@ namespace ext {
VkSpecializationInfo specializationInfo;
std::vector<uf::Userdata> pushConstants;
// std::vector<uf::Userdata> specializationConstants;
// uf::Userdata specializationConstants;
std::vector<uint8_t> specializationConstants;
std::vector<uf::Userdata> uniforms;
// ~Shader();
void initialize( Device& device, const std::string&, VkShaderStageFlagBits );
void destroy();
bool validate();
};
struct UF_API Pipeline {
bool aliased = false;

View File

@ -20,7 +20,8 @@ namespace ext {
typedef std::vector<VkCommandBuffer> commands_container_t;
std::thread::id mostRecentCommandPoolId;
std::unordered_map<std::thread::id, commands_container_t> commands;
// std::unordered_map<std::thread::id, commands_container_t> commands;
uf::ThreadUnique<commands_container_t> commands;
virtual ~RenderMode();
// RAII

View File

@ -20,36 +20,35 @@ namespace spec {
typedef uf::String title_t;
typedef pod::Vector2i vector_t;
/*
struct Events {
template<typename Hook>
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<Event> events_t;
};
Type<uf::ReadableHook>::events_t readable;
Type<uf::OptimalHook>::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<spec::uni::Window::event_t> events_t;
protected:
spec::uni::Window::events_t m_events;
*/
// Window::Events m_events;
std::queue<Event> 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& );
};

View File

@ -48,11 +48,7 @@ T* uf::Component::getComponentPointer() {
pod::Component::id_t id = this->getType<T>();
pod::Component& component = this->m_container[id];
try {
pointer = &uf::userdata::get<T>(component.userdata);
} catch ( std::exception& e ) {
return NULL;
}
pointer = &uf::userdata::get<T>(component.userdata);
return pointer;
}
template<typename T>
@ -62,11 +58,7 @@ const T* uf::Component::getComponentPointer() const {
pod::Component::id_t id = this->getType<T>();
const pod::Component& component = this->m_container.at(id);
try {
pointer = &uf::userdata::get<T>(component.userdata);
} catch ( std::exception& e ) {
return NULL;
}
pointer = &uf::userdata::get<T>(component.userdata);
return pointer;
}
template<typename T>

View File

@ -0,0 +1,57 @@
/*
template<typename T>
struct function_traits;
template<typename R, typename ...Args>
struct function_traits<std::function<R(Args...)>> {
static const size_t nargs = sizeof...(Args);
typedef R result_type;
template <size_t i>
struct arg {
typedef typename std::tuple_element<i, std::tuple<Args...>>::type type;
};
};
*/
// For generic types that are functors, delegate to its 'operator()'
template <typename T>
struct function_traits : public function_traits<decltype(&T::operator())> {};
// for pointers to member function
template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType(ClassType::*)(Args...) const> {
//enum { arity = sizeof...(Args) };
static const size_t arguments = sizeof...(Args);
template <size_t i>
struct Arg {
typedef typename std::tuple_element<i, std::tuple<Args...>>::type type;
};
typedef ReturnType return_type;
typedef std::function<ReturnType (Args...)> type;
};
// for pointers to member function
template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType(ClassType::*)(Args...) > {
static const size_t arguments = sizeof...(Args);
template <size_t i>
struct Arg {
typedef typename std::tuple_element<i, std::tuple<Args...>>::type type;
};
typedef ReturnType return_type;
typedef std::function<ReturnType (Args...)> type;
};
// for function pointers
template <typename ReturnType, typename... Args>
struct function_traits<ReturnType (*)(Args...)> {
static const size_t arguments = sizeof...(Args);
template <size_t i>
struct Arg {
typedef typename std::tuple_element<i, std::tuple<Args...>>::type type;
};
typedef ReturnType return_type;
typedef std::function<ReturnType (Args...)> type;
};

View File

@ -9,6 +9,7 @@
#include <vector> // std::vector
#include <unordered_map> // std::unordered_map
#if 0
namespace pod {
template<typename Argument = std::string, typename Return = Argument>
struct UF_API Hook {
@ -112,4 +113,75 @@ namespace uf {
};
extern UF_API uf::HookHandler hooks;
}
}
#endif
#include <uf/utils/userdata/userdata.h>
#include <uf/utils/serialize/serializer.h>
#include <type_traits>
namespace pod {
struct UF_API Hook {
typedef std::function<uf::Userdata(const uf::Userdata&)> function_t;
size_t uid;
size_t type;
function_t callback;
};
}
namespace uf {
class UF_API Hooks {
public:
typedef std::vector<pod::Hook> hooks_t;
typedef std::unordered_map<std::string, hooks_t> container_t;
typedef std::string name_t;
typedef uf::Userdata argument_t;
typedef std::vector<uf::Userdata> 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<void()>& callback );
/*
size_t addHook( const name_t& name, const std::function<void(const std::string&)>& callback );
size_t addHook( const name_t& name, const std::function<std::string(const std::string&)>& callback );
*/
template<typename Arg>
size_t addHook( const uf::Hooks::name_t& name, const std::function<void(Arg)>& callback );
template<typename R, typename Arg>
size_t addHook( const uf::Hooks::name_t& name, const std::function<R(Arg)>& callback );
/*
template<typename R, typename ...Args>
size_t addHook( const uf::Hooks::name_t& name, const std::function<R(Args...)>& callback );
*/
template<typename Function>
size_t addHook( const uf::Hooks::name_t& name, const Function& lambda );
template<typename T>
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<std::string(const std::string&)> function_t;
}
}
}
#include "function_traits.inl"
#include "hook.inl"

View File

@ -0,0 +1,52 @@
template<typename Arg>
size_t uf::Hooks::addHook( const uf::Hooks::name_t& name, const std::function<void(Arg)>& callback ) {
typedef typename std::remove_reference<Arg>::type Argument;
return addHook(name, [=]( const uf::Userdata& userdata ){
uf::Userdata ret;
const Argument& payload = userdata.is<Argument>() ? userdata.get<Argument>() : Argument{};
callback( payload );
return ret;
}, typeid(callback).hash_code());
}
template<typename R, typename Arg>
size_t uf::Hooks::addHook( const uf::Hooks::name_t& name, const std::function<R(Arg)>& callback ) {
typedef typename std::remove_reference<Arg>::type Argument;
return addHook(name, [=]( const uf::Userdata& userdata ){
uf::Userdata ret;
const Argument& payload = userdata.is<Argument>() ? userdata.get<Argument>() : Argument{};
R res = callback( payload );
ret.create<R>(res);
return ret;
}, typeid(callback).hash_code());
}
/*
template<typename R, typename ...Args>
size_t uf::Hooks::addHook( const uf::Hooks::name_t& name, const std::function<R(Args...)>& callback ) {
typedef function_traits<decltype(callback)> Traits;
typedef typename std::remove_reference<typename Traits::template Arg<0>::type>::type Argument;
return addHook(name, [=]( const uf::Userdata& userdata ){
uf::Userdata ret;
const Argument& payload = userdata.is<Argument>() ? userdata.get<Argument>() : Argument{};
R res = callback( payload );
ret.create<R>(res);
return ret;
}, typeid(callback).hash_code());
}
*/
template<typename Function>
size_t uf::Hooks::addHook( const uf::Hooks::name_t& name, const Function& lambda ) {
typedef function_traits<Function> Traits;
typename Traits::type function = lambda;
return addHook(name, function);
}
template<typename T>
uf::Hooks::return_t uf::Hooks::call( const uf::Hooks::name_t& name, const T& p ) {
uf::Userdata payload;
payload.create<T>(p);
return call( name, payload );
}

View File

@ -2,6 +2,7 @@
#include <uf/utils/image/image.h>
#include <binpack2d/binpack2d.hpp>
#include <unordered_map>
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<hash_t, uf::Image> images_t;
struct Identifier {
hash_t hash;
};
typedef Identifier identifier_t;
typedef BinPack2D::CanvasArray<identifier_t> 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;
};
}

View File

@ -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&);
};
}

View File

@ -1,10 +1,13 @@
#include <uf/utils/type/type.h>
template<typename T>
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<typename T>
@ -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;

View File

@ -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;

View File

@ -0,0 +1,22 @@
#pragma once
#include <uf/config.h>
#include "thread.h"
namespace uf {
template<typename T>
class UF_API ThreadUnique {
public:
typedef T type_t;
typedef std::thread::id id_t;
typedef std::unordered_map<id_t, type_t> 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"

View File

@ -0,0 +1,12 @@
template<typename T>
bool uf::ThreadUnique<T>::has( id_t id ) const {
return m_container.count(id) > 0;
}
template<typename T>
T& uf::ThreadUnique<T>::get( id_t id ) {
return m_container[id];
}
template<typename T>
typename uf::ThreadUnique<T>::container_t& uf::ThreadUnique<T>::container() {
return m_container;
}

View File

@ -0,0 +1,44 @@
#pragma once
#include <uf/config.h>
#include <typeindex>
#include <unordered_map>
#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<pod::TypeInfo> {
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<index_t, pod::TypeInfo>* 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<typename T> const index_t getIndex();
template<typename T> void registerType( const std::string& = "" );
template<typename T> const pod::TypeInfo& getType();
}
}
#include "type.inl"

View File

@ -0,0 +1,12 @@
template<typename T>
const std::type_index uf::typeInfo::getIndex() {
return typeid(T);
}
template<typename T>
void uf::typeInfo::registerType( const std::string& pretty ) {
return registerType(getIndex<T>(), sizeof(T), pretty);
}
template<typename T>
const pod::TypeInfo& uf::typeInfo::getType() {
return getType(getIndex<T>());
}

View File

@ -8,13 +8,18 @@
#include <cstddef>
#include <string>
#include <algorithm>
#include <typeindex>
#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<typename T> pod::Userdata* create( const T& data = T() );
template<typename T> T& get( pod::Userdata* userdata, bool validate = true);
template<typename T> const T& get(const pod::Userdata* userdata);
template<typename T> const T& get(const pod::Userdata* userdata, bool validate = true );
template<typename T> 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<typename T> 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<typename T> pod::Userdata* create( const T& data = T() );
template<typename T> T& get();
template<typename T> const T& get() const;
template<typename T> bool is() const;
template<typename T> inline T& as() { return get<T>(); }
template<typename T> inline T& as() const { return get<T>(); }
// Overloaded ops
operator void*();
operator void*() const;
operator bool() const;
Userdata& operator=( pod::Userdata* pointer );
Userdata& operator=( Userdata&& move );
Userdata& operator=( const Userdata& copy );

View File

@ -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 <stdexcept>
template<typename T>
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<T>( 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<typename T>
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<T>( 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<typename T>
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<typename T>
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<T>( this->m_pod );
}
// Easy way to get the userdata as a const-reference
template<typename T>
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<T>( this->m_pod );
}
template<typename T>
bool uf::Userdata::is() const {
return this->m_pod && uf::userdata::is<T>( this->m_pod );
}

View File

@ -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<uf::Object>();
@ -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 {

View File

@ -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<std::function<int()>> jobs;\
if ( this->hasComponent<uf::Serializer>() ) {\
auto& metadata = this->getComponent<uf::Serializer>();\
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<bool>();\
if ( !ext::json::isNull( metadata["system"]["behavior"][#f]["multithreading"] ) )\
multithreading = metadata["system"]["behavior"][#f]["multithreading"].as<bool>();\
if ( !ext::json::isNull( metadata["system"]["behavior"][#f]["use workers"] ) )\
useWorkers = metadata["system"]["behavior"][#f]["use workers"].as<bool>();\
}\
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() {

View File

@ -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;

View File

@ -2,6 +2,7 @@
#include <uf/engine/asset/asset.h>
#include <uf/engine/scene/scene.h>
#include <uf/utils/time/time.h>
#include <uf/utils/audio/audio.h>
#include <uf/utils/math/transform.h>
#include <uf/utils/math/physics.h>
#include <uf/utils/graphic/graphic.h>
@ -121,6 +122,14 @@ void uf::ObjectBehavior::destroy( uf::Object& self ) {
}
}
if ( this->hasComponent<uf::Audio>() ) {
auto& audio = this->getComponent<uf::Audio>();
audio.destroy();
}
if ( this->hasComponent<uf::SoundEmitter>() ) {
auto& audio = this->getComponent<uf::SoundEmitter>();
audio.cleanup(true);
}
if ( this->hasComponent<uf::Graphic>() ) {
auto& graphic = this->getComponent<uf::Graphic>();
graphic.destroy();

View File

@ -42,9 +42,10 @@ void uf::GltfBehavior::initialize( uf::Object& self ) {
if ( !entity->hasComponent<uf::Graphic>() || !entity->hasComponent<ext::gltf::mesh_t>() ) return;
auto& graphic = entity->getComponent<uf::Graphic>();
auto& mesh = entity->getComponent<ext::gltf::mesh_t>();
/*
graphic.initialize();
graphic.initializeGeometry( mesh );
*/
{
std::string filename = "/gltf.stereo.vert.spv";
if ( metadata["system"]["renderer"]["shaders"]["vertex"].is<std::string>() )
@ -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;

View File

@ -60,7 +60,14 @@ std::string uf::Object::formatHookName( const std::string& n ) {
return name;
}
std::vector<std::string> uf::Object::callHook( const std::string& name, const std::string& payload ) {
return uf::hooks.call( this->formatHookName( name ), payload );
std::vector<std::string> strings;
auto results = uf::hooks.call( this->formatHookName( name ), payload );
for ( auto& result : results ) {
if ( result.is<std::string>() ) {
strings.emplace_back( result.as<std::string>() );
}
}
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>();
uf::Serializer json = _json;
// import
if ( _json["import"].is<std::string>() || _json["include"].is<std::string>() ) {
uf::Serializer chain = _json;
std::string root = json["root"].as<std::string>();
do {
std::string filename = chain["import"].is<std::string>() ? chain["import"].as<std::string>() : chain["include"].as<std::string>();
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<std::string>() || chain["include"].is<std::string>() );
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<std::string>();

View File

@ -1,296 +0,0 @@
#include <uf/config.h>
#if defined(UF_USE_ASSIMP)
#include <uf/ext/assimp/assimp.h>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <uf/utils/io/iostream.h>
#include <uf/utils/math/matrix.h>
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<float> points;
std::vector<float> normals;
std::vector<float> uvs;
} model;
std::function<void(const aiNode*)> 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 <iomanip>
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<pod::Matrix4(const aiMatrix4x4&, bool)> 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<float> points;
std::vector<float> normals;
std::vector<float> uvs;
std::vector<int> bones_id;
std::vector<float> bones_weight;
} model;
/* */ {
std::function<bool(const aiNode*)> 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<int> boneIDs; boneIDs.resize(size, 0);
std::vector<float> 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<const aiNode*> nodes; {
std::function<void(const aiNode*)> 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<const aiNode*(const std::string&)> 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<void(const uf::Skeleton::Bone&, int)> 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

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,46 @@
#include <uf/ext/gltf/mesh.h>
std::vector<ext::vulkan::VertexDescriptor> 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::vulkan::VertexDescriptor> 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)
},
};

View File

@ -80,15 +80,13 @@ void ext::lua::initialize() {
auto hooks = state["hooks"].get_or_create<sol::table>();
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() ) {

View File

@ -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");

View File

@ -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;
}

View File

@ -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 ) {

View File

@ -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<uint32_t>(pair.second.size()), pair.second.data());
pair.second.clear();
}

View File

@ -4,7 +4,7 @@
#include <uf/utils/serialize/serializer.h>
#include <sstream>
/*
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<std::string>( 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<Header>();
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
}

View File

@ -2,6 +2,8 @@
#include <uf/utils/io/iostream.h>
#include <uf/utils/string/utf.h>
#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>() ) {
std::string payload = event.payload.as<std::string>();
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;

View File

@ -1,7 +1,85 @@
#include <uf/utils/hook/hook.h>
#include <uf/utils/io/iostream.h> // 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<uf::Userdata> 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<std::string>( 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<std::string>( s.serialize() );
return call(name, payload);
}
// specialization: void function
size_t uf::Hooks::addHook( const uf::Hooks::name_t& name, const std::function<void()>& 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<void(const std::string&)>& callback ) {
return addHook( name, [=]( const uf::Userdata& userdata ){
std::string payload = userdata.is<std::string>() ? userdata.get<std::string>() : "";
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<std::string(const std::string&)>& callback ) {
return addHook( name, [=]( const uf::Userdata& userdata ){
std::string payload = userdata.is<std::string>() ? userdata.get<std::string>() : "";
std::string res = callback( payload );
uf::Userdata ret;
ret.create<std::string>(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;
}
*/
*/
#endif

View File

@ -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<uf::Atlas::identifier_t> 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<uf::Atlas::identifier_t>({index++}, BinPack2D::Coord(), BinPack2D::Size(dim.x, dim.y), false );
size += dim;
area += dim.x * dim.y;
queue += BinPack2D::Content<uf::Atlas::identifier_t>({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<uf::Atlas::identifier_t>(size.x, size.y ,1).Build();
size_t tries = 16;
BinPack2D::ContentAccumulator<uf::Atlas::identifier_t> 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<uf::Atlas::identifier_t>(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 <uf/utils/image/atlas.h>
#include <iostream>
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<uf::HashAtlas::identifier_t> 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<uf::HashAtlas::identifier_t>({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<uf::HashAtlas::identifier_t> 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<uf::HashAtlas::identifier_t>(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<uf::HashAtlas::identifier_t> 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;
}

View File

@ -1,5 +1,6 @@
#include <uf/utils/image/image.h>
#include <uf/utils/string/ext.h>
#include <uf/utils/string/hash.h>
#include <uf/utils/io/iostream.h>
#include <fstream> // std::fstream
#include <iostream> // 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;
}

View File

@ -5,9 +5,11 @@
#include <iostream>
#include <sstream>
#include <uf/utils/serialize/serializer.h>
#include <uf/utils/thread/perthread.h>
#include <uf/utils/io/iostream.h>
namespace {
bool IGNORE_GLOBAL_MEMORYPOOL = false;
uf::ThreadUnique<bool> 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 );
}

View File

@ -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<void(Json::Value&, const Json::Value&)> 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();

View File

@ -0,0 +1,50 @@
#include <uf/utils/type/type.h>
#include <uf/utils/io/iostream.h>
#include <cxxabi.h>
#include <memory>
namespace {
std::string demangle( const std::string& mangled ) {
int status = -4;
std::unique_ptr<char, void(*)(void*)> 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::index_t, pod::TypeInfo>* 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<uf::typeInfo::index_t, pod::TypeInfo>;
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<uf::typeInfo::index_t, pod::TypeInfo>;
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<uf::typeInfo::index_t, pod::TypeInfo>;
return (*uf::typeInfo::types)[index];
}

View File

@ -4,64 +4,28 @@
#include <cstring> // memcpy
#include <iostream>
// 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 <iostream>
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<uint8_t*>(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 << " <- " << &copy << ", " << 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;

View File

@ -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<long long> 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

View File

@ -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<int>(), json["mouse"]["delta"]["y"].as<int>() };

View File

@ -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;

View File

@ -659,13 +659,13 @@ void ext::GuiBehavior::initialize( uf::Object& self ) {
}
return;
}
{
float delay = 0.0f;
float scale = metadata["text settings"]["scale"].as<float>();
auto& transform = this->getComponent<pod::Transform<>>();
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<pod::GlyphBox> glyphs = this->as<ext::Gui>().generateGlyphs();
std::string font = "./data/fonts/" + metadata["text settings"]["font"].as<std::string>();
@ -678,46 +678,51 @@ void ext::GuiBehavior::initialize( uf::Object& self ) {
key += metadata["text settings"]["sdf"].as<std::string>();
}
auto& scene = uf::scene::getCurrentScene();
auto& atlas = this->getComponent<uf::Atlas>();
auto& atlas = this->getComponent<uf::HashAtlas>();
auto& images = atlas.getImages();
auto& mesh = this->getComponent<ext::Gui::glyph_mesh_t>();
auto& graphic = this->getComponent<uf::Graphic>();
mesh.vertices.reserve( glyphs.size() * 6 );
std::unordered_map<std::string, std::string> 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<float>();
auto& transform = this->getComponent<pod::Transform<>>();
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<std::string>();
float delay = 0.0f;
float scale = metadata["text settings"]["scale"].as<float>();
std::vector<pod::GlyphBox> glyphs = this->as<ext::Gui>().generateGlyphs( string );
std::string font = "./data/fonts/" + metadata["text settings"]["font"].as<std::string>();
@ -772,88 +775,85 @@ void ext::GuiBehavior::initialize( uf::Object& self ) {
key += metadata["text settings"]["font"].as<std::string>() + ";";
key += metadata["text settings"]["sdf"].as<std::string>();
}
auto& transform = this->getComponent<pod::Transform<>>();
auto& scene = uf::scene::getCurrentScene();
auto& atlas = this->getComponent<uf::Atlas>();
auto& atlas = this->getComponent<uf::HashAtlas>();
auto& images = atlas.getImages();
auto& mesh = this->getComponent<ext::Gui::glyph_mesh_t>();
auto& graphic = this->getComponent<uf::Graphic>();
atlas.clear();
mesh.vertices.clear();
mesh.indices.clear();
if ( !json["first"].as<bool>() ) {
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<std::string, std::string> 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<float>();
auto& transform = this->getComponent<pod::Transform<>>();
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<bool>() ) {
graphic.initialize( "Gui" );
graphic.initializeGeometry( mesh );
std::string suffix = ""; {
std::string _ = scene.getComponent<uf::Serializer>()["shaders"]["gui"]["suffix"].as<std::string>();
if ( _ != "" ) suffix = _ + ".";
std::string suffix = ""; {
std::string _ = scene.getComponent<uf::Serializer>()["shaders"]["gui"]["suffix"].as<std::string>();
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<std::string>() ) filenames.vertex = metadata["shaders"]["vertex"].as<std::string>();
if ( metadata["shaders"]["fragment"].is<std::string>() ) filenames.fragment = metadata["shaders"]["fragment"].as<std::string>();
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<std::string>() ) filenames.vertex = metadata["shaders"]["vertex"].as<std::string>();
if ( metadata["shaders"]["fragment"].is<std::string>() ) filenames.fragment = metadata["shaders"]["fragment"].as<std::string>();
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";
});

View File

@ -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 ) ) {

View File

@ -3,7 +3,6 @@
#include <uf/ext/ext.h>
#include <uf/ext/vulkan/vulkan.h>
#include <uf/ext/oal/oal.h>
#include <uf/ext/assimp/assimp.h>
#include <uf/spec/terminal/terminal.h>
@ -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 */ {

View File

@ -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(""));