adding multiple hooks supports for events and loop

This commit is contained in:
Kbz-8
2024-12-17 02:33:04 +01:00
parent 8f4dc6e3b5
commit ffff4722b7
15 changed files with 77 additions and 59 deletions

View File

@@ -50,7 +50,3 @@ jobs:
# Build the mlx # Build the mlx
- name: Build MacroLibX - name: Build MacroLibX
run: xmake --yes run: xmake --yes
# Build the example
- name: Build Example
run: xmake build --yes Test

View File

@@ -33,17 +33,19 @@ INCLUDES = -I./includes -I./runtime/Includes -I./runtime/Sources -I./third_party
CXXPCHFLAGS = -xc++-header CXXPCHFLAGS = -xc++-header
PCH = runtime/Includes/PreCompiled.h PCH_SOURCE = runtime/Includes/PreCompiled.h
GCH = GCH = runtime/Includes/PreCompiled.h.gch
CCH = runtime/Includes/PreCompiled.h.pch
PCH =
NZRRC = nzslc NZRRC ?= nzslc
ifeq ($(TOOLCHAIN), gcc) ifeq ($(TOOLCHAIN), gcc)
CXX = g++ CXX = g++
GCH = runtime/Includes/PreCompiled.h.gch PCH = $(GCH)
CXXFLAGS += -Wno-error=cpp CXXFLAGS += -Wno-error=cpp
else else
GCH = runtime/Includes/PreCompiled.h.pch PCH = $(CCH)
CXXFLAGS += -Wno-error=#warning -include-pch $(GCH) CXXFLAGS += -Wno-error=#warning -include-pch $(GCH)
endif endif
@@ -115,7 +117,7 @@ ifeq ($(OBJS_TOTAL), 0) # To avoid division per 0
endif endif
CURR_OBJ = 0 CURR_OBJ = 0
$(OBJ_DIR)/%.o: %.cpp $(GCH) $(OBJ_DIR)/%.o: %.cpp $(PCH)
@mkdir -p $(dir $@) @mkdir -p $(dir $@)
@$(eval CURR_OBJ=$(shell echo $$(( $(CURR_OBJ) + 1 )))) @$(eval CURR_OBJ=$(shell echo $$(( $(CURR_OBJ) + 1 ))))
@$(eval PERCENT=$(shell echo $$(( $(CURR_OBJ) * 100 / $(OBJS_TOTAL) )))) @$(eval PERCENT=$(shell echo $$(( $(CURR_OBJ) * 100 / $(OBJS_TOTAL) ))))
@@ -139,9 +141,9 @@ CURR_SPV = 0
all: _printbuildinfos all: _printbuildinfos
@$(MAKE) $(NAME) @$(MAKE) $(NAME)
$(GCH): $(PCH):
@printf "$(COLOR)($(_BOLD)%3s%%$(_RESET)$(COLOR)) $(_RESET)Compiling $(_BOLD)PreCompiled header$(_RESET)\n" "0" @printf "$(COLOR)($(_BOLD)%3s%%$(_RESET)$(COLOR)) $(_RESET)Compiling $(_BOLD)PreCompiled header$(_RESET)\n" "0"
@$(CXX) $(CXXPCHFLAGS) $(INCLUDES) $(PCH) -o $(GCH) @$(CXX) $(CXXPCHFLAGS) $(INCLUDES) $(PCH_SOURCE) -o $(PCH)
$(NAME): $(OBJS) $(NAME): $(OBJS)
@printf "Linking $(_BOLD)$(NAME)$(_RESET)\n" @printf "Linking $(_BOLD)$(NAME)$(_RESET)\n"
@@ -163,7 +165,8 @@ clean:
@$(RM) $(OBJ_DIR) @$(RM) $(OBJ_DIR)
@printf "Cleaned $(_BOLD)$(OBJ_DIR)$(_RESET)\n" @printf "Cleaned $(_BOLD)$(OBJ_DIR)$(_RESET)\n"
@$(RM) $(GCH) @$(RM) $(GCH)
@printf "Cleaned $(_BOLD)$(GCH)$(_RESET)\n" @$(RM) $(CCH)
@printf "Cleaned pre compiled header\n"
fclean: clean fclean: clean
@$(RM) $(NAME) @$(RM) $(NAME)

View File

@@ -18,7 +18,7 @@ typedef struct
static mlx_color pixels_circle[CIRCLE_DIAMETER * CIRCLE_DIAMETER] = { 0 }; static mlx_color pixels_circle[CIRCLE_DIAMETER * CIRCLE_DIAMETER] = { 0 };
int update(void* param) void update(void* param)
{ {
static int i = 0; static int i = 0;
mlx_t* mlx = (mlx_t*)param; mlx_t* mlx = (mlx_t*)param;
@@ -60,7 +60,6 @@ int update(void* param)
mlx_pixel_put_region(mlx->mlx, mlx->win, 200, 170, CIRCLE_DIAMETER, CIRCLE_DIAMETER, pixels_circle); mlx_pixel_put_region(mlx->mlx, mlx->win, 200, 170, CIRCLE_DIAMETER, CIRCLE_DIAMETER, pixels_circle);
i++; i++;
return 0;
} }
mlx_image create_image(mlx_t* mlx) mlx_image create_image(mlx_t* mlx)
@@ -87,7 +86,7 @@ mlx_image create_image(mlx_t* mlx)
return img; return img;
} }
int key_hook(int key, void* param) void key_hook(int key, void* param)
{ {
int x; int x;
int y; int y;
@@ -123,14 +122,12 @@ int key_hook(int key, void* param)
default : break; default : break;
} }
return 0;
} }
int window_hook(int event, void* param) void window_hook(int event, void* param)
{ {
if(event == 0) if(event == 0)
mlx_loop_end(((mlx_t*)param)->mlx); mlx_loop_end(((mlx_t*)param)->mlx);
return 0;
} }
int main(void) int main(void)
@@ -179,7 +176,7 @@ int main(void)
mlx_set_font_scale(mlx.mlx, "font.ttf", 16.f); mlx_set_font_scale(mlx.mlx, "font.ttf", 16.f);
mlx_string_put(mlx.mlx, mlx.win, 20, 20, (mlx_color){ .rgba = 0x0020FFFF }, "that text will disappear"); mlx_string_put(mlx.mlx, mlx.win, 20, 20, (mlx_color){ .rgba = 0x0020FFFF }, "that text will disappear");
mlx_loop_hook(mlx.mlx, update, &mlx); mlx_add_loop_hook(mlx.mlx, update, &mlx);
mlx_loop(mlx.mlx); mlx_loop(mlx.mlx);
mlx_destroy_image(mlx.mlx, mlx.logo_png); mlx_destroy_image(mlx.mlx, mlx.logo_png);

View File

@@ -6,7 +6,7 @@
/* By: maldavid <contact@kbz8.me> +#+ +:+ +#+ */ /* By: maldavid <contact@kbz8.me> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/04 16:56:35 by maldavid #+# #+# */ /* Created: 2022/10/04 16:56:35 by maldavid #+# #+# */
/* Updated: 2024/12/17 00:27:35 by maldavid ### ########.fr */ /* Updated: 2024/12/17 02:23:40 by maldavid ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
@@ -213,7 +213,7 @@ MLX_API void mlx_get_screen_size(mlx_context mlx, mlx_window win, int* w, int* h
* @param f The function * @param f The function
* @param param Param to give to the function passed * @param param Param to give to the function passed
*/ */
MLX_API void mlx_loop_hook(mlx_context mlx, int (*f)(void*), void* param); MLX_API void mlx_add_loop_hook(mlx_context mlx, void(*f)(void*), void* param);
/** /**
* @brief Starts the internal main loop * @brief Starts the internal main loop
@@ -289,7 +289,7 @@ typedef enum mlx_event_type
* @param f Function to be executed * @param f Function to be executed
* @param param Parameter given to the function * @param param Parameter given to the function
*/ */
MLX_API void mlx_on_event(mlx_context mlx, mlx_window win, mlx_event_type event, int (*f)(int, void*), void* param); MLX_API void mlx_on_event(mlx_context mlx, mlx_window win, mlx_event_type event, void(*f)(int, void*), void* param);

View File

@@ -21,7 +21,7 @@ namespace mlx
inline void GetScreenSize(mlx_window win, int* w, int* h) noexcept; inline void GetScreenSize(mlx_window win, int* w, int* h) noexcept;
inline void SetFPSCap(std::uint32_t fps) noexcept; inline void SetFPSCap(std::uint32_t fps) noexcept;
inline void OnEvent(mlx_window win, int event, int (*funct_ptr)(int, void*), void* param) noexcept; inline void OnEvent(mlx_window win, int event, void(*f)(int, void*), void* param) noexcept;
inline mlx_window NewGraphicsSuport(const mlx_window_create_info* info); inline mlx_window NewGraphicsSuport(const mlx_window_create_info* info);
inline NonOwningPtr<GraphicsSupport> GetGraphicsSupport(mlx_window win); inline NonOwningPtr<GraphicsSupport> GetGraphicsSupport(mlx_window win);
@@ -32,7 +32,7 @@ namespace mlx
inline NonOwningPtr<Texture> GetTexture(mlx_image image); inline NonOwningPtr<Texture> GetTexture(mlx_image image);
void DestroyTexture(mlx_image img); void DestroyTexture(mlx_image img);
inline void LoopHook(int (*f)(void*), void* param); inline void AddLoopHook(void(*f)(void*), void* param);
inline void LoopEnd() noexcept; inline void LoopEnd() noexcept;
inline void LoadFont(const std::filesystem::path& filepath, float scale); inline void LoadFont(const std::filesystem::path& filepath, float scale);
@@ -41,6 +41,15 @@ namespace mlx
~Application(); ~Application();
private:
struct Hook
{
func::function<void(void*)> fn;
void* param;
Hook(func::function<void(void*)> fn, void* param) : fn(fn), param(param) {}
};
private: private:
std::unique_ptr<MemManager> p_mem_manager; // Putting ptr here to initialise them before inputs, even if it f*cks the padding std::unique_ptr<MemManager> p_mem_manager; // Putting ptr here to initialise them before inputs, even if it f*cks the padding
std::unique_ptr<SDLManager> p_sdl_manager; std::unique_ptr<SDLManager> p_sdl_manager;
@@ -50,13 +59,12 @@ namespace mlx
ImageRegistry m_image_registry; ImageRegistry m_image_registry;
MeshRegistry m_mesh_registry; MeshRegistry m_mesh_registry;
std::vector<std::unique_ptr<GraphicsSupport>> m_graphics; std::vector<std::unique_ptr<GraphicsSupport>> m_graphics;
std::vector<Hook> m_hooks;
std::shared_ptr<Font> p_last_font_bound; std::shared_ptr<Font> p_last_font_bound;
std::function<int(Handle)> f_loop_hook;
std::unique_ptr<RenderCore> p_render_core; std::unique_ptr<RenderCore> p_render_core;
#ifdef PROFILER #ifdef PROFILER
std::unique_ptr<Profiler> p_profiler; std::unique_ptr<Profiler> p_profiler;
#endif #endif
Handle p_param = nullptr;
}; };
} }

View File

@@ -40,12 +40,12 @@ namespace mlx
*y = m_in.GetY(); *y = m_in.GetY();
} }
void Application::OnEvent(mlx_window win, int event, int (*funct_ptr)(int, void*), void* param) noexcept void Application::OnEvent(mlx_window win, int event, void(*f)(int, void*), void* param) noexcept
{ {
CHECK_WINDOW_PTR(win, ); CHECK_WINDOW_PTR(win, );
if(!m_graphics[win->id]->HasWindow()) if(!m_graphics[win->id]->HasWindow())
return; return;
m_in.OnEvent(m_graphics[win->id]->GetWindow()->GetID(), event, funct_ptr, param); m_in.OnEvent(m_graphics[win->id]->GetWindow()->GetID(), event, f, param);
} }
void Application::SetFPSCap(std::uint32_t fps) noexcept void Application::SetFPSCap(std::uint32_t fps) noexcept
@@ -122,10 +122,9 @@ namespace mlx
return texture; return texture;
} }
void Application::LoopHook(int (*f)(void*), void* param) void Application::AddLoopHook(void(*f)(void*), void* param)
{ {
f_loop_hook = f; m_hooks.emplace_back(f, param);
p_param = param;
} }
void Application::LoopEnd() noexcept void Application::LoopEnd() noexcept

View File

@@ -93,7 +93,7 @@ namespace mlx
try try
{ {
std::stringstream ss; std::stringstream ss;
ss << Format("Verification failed : %", message, args...); ss << Format("Verification failed: %", message, args...);
Logs::Report(LogType::FatalError, line, file, function, ss.str()); Logs::Report(LogType::FatalError, line, file, function, ss.str());
} }
catch(const std::exception& e) catch(const std::exception& e)
@@ -112,7 +112,7 @@ namespace mlx
try try
{ {
std::stringstream ss; std::stringstream ss;
ss << Format("Assertion failed : %", message, args...); ss << Format("Assertion failed: %", message, args...);
Logs::Report(LogType::FatalError, line, file, function, ss.str()); Logs::Report(LogType::FatalError, line, file, function, ss.str());
} }
catch(const std::exception& e) catch(const std::exception& e)

View File

@@ -12,8 +12,10 @@ namespace mlx
public: public:
struct Hook struct Hook
{ {
func::function<int(int, void*)> hook; func::function<void(int, void*)> fn;
void* param = nullptr; void* param = nullptr;
Hook(func::function<void(int, void*)> fn, void* param) : fn(fn), param(param) {}
}; };
public: public:
@@ -33,17 +35,16 @@ namespace mlx
MLX_FORCEINLINE constexpr void Finish() noexcept { m_run = false; } MLX_FORCEINLINE constexpr void Finish() noexcept { m_run = false; }
MLX_FORCEINLINE constexpr void Run() noexcept { m_run = true; } MLX_FORCEINLINE constexpr void Run() noexcept { m_run = true; }
inline void OnEvent(std::uint32_t id, int event, int (*funct_ptr)(int, void*), void* param) noexcept inline void OnEvent(std::uint32_t id, int event, void(*f)(int, void*), void* param) noexcept
{ {
m_events_hooks[id][event].hook = funct_ptr; m_events_hooks[id][event].emplace_back(f, param);
m_events_hooks[id][event].param = param;
} }
~Inputs() = default; ~Inputs() = default;
private: private:
std::unordered_map<std::uint32_t, std::shared_ptr<Window>> m_windows; std::unordered_map<std::uint32_t, std::shared_ptr<Window>> m_windows;
std::unordered_map<std::uint32_t, std::array<Hook, 6>> m_events_hooks; std::unordered_map<std::uint32_t, std::array<std::vector<Hook>, 6>> m_events_hooks;
bool m_run = false; bool m_run = false;
}; };
} }

View File

@@ -38,8 +38,11 @@ namespace mlx
m_in.FetchInputs(); m_in.FetchInputs();
if(f_loop_hook) for(const auto& hook : m_hooks)
f_loop_hook(p_param); {
if(hook.fn)
hook.fn(hook.param);
}
for(auto& gs : m_graphics) for(auto& gs : m_graphics)
{ {

View File

@@ -31,12 +31,13 @@ extern "C"
mlx::MemManager::Get(); // just to initialize the C garbage collector mlx::MemManager::Get(); // just to initialize the C garbage collector
try { __internal_application_ptr = new mlx::Application; } __internal_application_ptr = new mlx::Application;
catch(...) { mlx::FatalError("internal application memory allocation failed"); } if(__internal_application_ptr == nullptr)
mlx::FatalError("internal application memory allocation failed");
mlx_context_handler* context; mlx_context_handler* context = new mlx_context_handler;
try { context = new mlx_context_handler; } if(context == nullptr)
catch(...) { mlx::FatalError("mlx_context memory allocation failed"); } mlx::FatalError("mlx_context memory allocation failed");
context->app = __internal_application_ptr; context->app = __internal_application_ptr;
return context; return context;
} }
@@ -150,10 +151,10 @@ extern "C"
gs->GetWindow()->GetScreenSizeWindowIsOn(w, h); gs->GetWindow()->GetScreenSizeWindowIsOn(w, h);
} }
void mlx_loop_hook(mlx_context mlx, int (*f)(void*), void* param) void mlx_add_loop_hook(mlx_context mlx, void(*f)(void*), void* param)
{ {
MLX_CHECK_APPLICATION_POINTER(mlx); MLX_CHECK_APPLICATION_POINTER(mlx);
mlx->app->LoopHook(f, param); mlx->app->AddLoopHook(f, param);
} }
void mlx_loop(mlx_context mlx) void mlx_loop(mlx_context mlx)
@@ -195,10 +196,10 @@ extern "C"
mlx->app->GetMousePos(x, y); mlx->app->GetMousePos(x, y);
} }
void mlx_on_event(mlx_context mlx, mlx_window win, mlx_event_type event, int (*funct_ptr)(int, void*), void* param) void mlx_on_event(mlx_context mlx, mlx_window win, mlx_event_type event, void(*f)(int, void*), void* param)
{ {
MLX_CHECK_APPLICATION_POINTER(mlx); MLX_CHECK_APPLICATION_POINTER(mlx);
mlx->app->OnEvent(win, static_cast<int>(event), funct_ptr, param); mlx->app->OnEvent(win, static_cast<int>(event), f, param);
} }
void mlx_pixel_put(mlx_context mlx, mlx_window win, int x, int y, mlx_color color) void mlx_pixel_put(mlx_context mlx, mlx_window win, int x, int y, mlx_color color)

View File

@@ -54,13 +54,14 @@ namespace mlx
if(m_current_texture_index >= m_textures.size()) if(m_current_texture_index >= m_textures.size())
{ {
VkExtent2D extent; VkExtent2D extent{ .width = 0, .height = 0 };
if(p_renderer->GetWindow()) if(p_renderer->GetWindow())
extent = kvfGetSwapchainImagesSize(p_renderer->GetSwapchain().Get()); extent = kvfGetSwapchainImagesSize(p_renderer->GetSwapchain().Get());
else if(p_renderer->GetRenderTarget()) else if(p_renderer->GetRenderTarget())
extent = VkExtent2D{ .width = p_renderer->GetRenderTarget()->GetWidth(), .height = p_renderer->GetRenderTarget()->GetHeight() }; extent = VkExtent2D{ .width = p_renderer->GetRenderTarget()->GetWidth(), .height = p_renderer->GetRenderTarget()->GetHeight() };
else else
FatalError("a renderer was created without window nor render target attached (wtf)"); FatalError("a renderer was created without window nor render target attached (wtf)");
#ifdef DEBUG #ifdef DEBUG
m_textures.push_back(std::make_unique<Texture>(CPUBuffer{}, extent.width, extent.height, VK_FORMAT_R8G8B8A8_SRGB, false, "mlx_put_pixel_layer_" + std::to_string(m_current_texture_index))); m_textures.push_back(std::make_unique<Texture>(CPUBuffer{}, extent.width, extent.height, VK_FORMAT_R8G8B8A8_SRGB, false, "mlx_put_pixel_layer_" + std::to_string(m_current_texture_index)));
#else #else

View File

@@ -12,9 +12,13 @@ namespace mlx
{ {
if(!m_windows.contains(window_id)) if(!m_windows.contains(window_id))
return; return;
if(!m_events_hooks.contains(window_id) || !m_events_hooks[window_id][event].hook) if(!m_events_hooks.contains(window_id) || m_events_hooks[window_id][event].empty())
return; return;
m_events_hooks[window_id][event].hook(code, m_events_hooks[window_id][event].param); for(const auto& hook : m_events_hooks[window_id][event])
{
if(hook.fn)
hook.fn(code, hook.param);
}
}); });
} }

View File

@@ -80,7 +80,7 @@ namespace mlx
case ShaderType::Vertex: vulkan_shader_stage = VK_SHADER_STAGE_VERTEX_BIT; break; case ShaderType::Vertex: vulkan_shader_stage = VK_SHADER_STAGE_VERTEX_BIT; break;
case ShaderType::Fragment: vulkan_shader_stage = VK_SHADER_STAGE_FRAGMENT_BIT; break; case ShaderType::Fragment: vulkan_shader_stage = VK_SHADER_STAGE_FRAGMENT_BIT; break;
default : FatalError("wtf"); break; default: FatalError("wtf"); vulkan_shader_stage = VK_SHADER_STAGE_VERTEX_BIT; /* Just to shut up warnings */ break;
} }
std::vector<VkDescriptorSetLayoutBinding> bindings(layout.binds.size()); std::vector<VkDescriptorSetLayoutBinding> bindings(layout.binds.size());

View File

@@ -43,6 +43,8 @@ namespace mlx
void Image::Init(ImageType type, std::uint32_t width, std::uint32_t height, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, bool is_multisampled, [[maybe_unused]] std::string_view debug_name) void Image::Init(ImageType type, std::uint32_t width, std::uint32_t height, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, bool is_multisampled, [[maybe_unused]] std::string_view debug_name)
{ {
MLX_PROFILE_FUNCTION(); MLX_PROFILE_FUNCTION();
Verify(width > 0 && height > 0, "width or height cannot be null");
m_type = type; m_type = type;
m_width = width; m_width = width;
m_height = height; m_height = height;
@@ -387,6 +389,11 @@ namespace mlx
int channels; int channels;
std::uint8_t* data = stbi_load(filename.c_str(), &size.x, &size.y, &channels, 4); std::uint8_t* data = stbi_load(filename.c_str(), &size.x, &size.y, &channels, 4);
if(data == nullptr)
{
Error("Image loader: could not load % due to %", file, stbi_failure_reason());
return nullptr;
}
CallOnExit defer([&]() { stbi_image_free(data); }); CallOnExit defer([&]() { stbi_image_free(data); });
CPUBuffer buffer(size.x * size.y * 4); CPUBuffer buffer(size.x * size.y * 4);
@@ -396,10 +403,6 @@ namespace mlx
*w = size.x; *w = size.x;
if(h != nullptr) if(h != nullptr)
*h = size.y; *h = size.y;
return new Texture(std::move(buffer), size.x, size.y, VK_FORMAT_R8G8B8A8_SRGB, false, std::move(filename));
Texture* texture;
try { texture = new Texture(std::move(buffer), size.x, size.y, VK_FORMAT_R8G8B8A8_SRGB, false, std::move(filename)); }
catch(...) { return nullptr; }
return texture;
} }
} }

View File

@@ -85,6 +85,7 @@ target("mlx")
end) end)
target_end() target_end()
--[[
target("Test") target("Test")
set_default(false) set_default(false)
set_kind("binary") set_kind("binary")
@@ -100,3 +101,4 @@ target("Test")
add_packages("libsdl") add_packages("libsdl")
target_end() target_end()
]]--