From 65b88356984ce549dc69179a17393c716790bc33 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Tue, 24 Dec 2024 15:53:26 +0300 Subject: [PATCH 01/12] update doc/*/block-properties.md (model-name) --- doc/en/block-properties.md | 10 ++++++++++ doc/ru/block-properties.md | 10 ++++++++++ 2 files changed, 20 insertions(+) diff --git a/doc/en/block-properties.md b/doc/en/block-properties.md index 6400c910..87df173b 100644 --- a/doc/en/block-properties.md +++ b/doc/en/block-properties.md @@ -35,6 +35,16 @@ Block model type from list: - "X" - grass model (two crossed sprites) - "aabb" - model based of block hitbox (complex hitbox will be combined into one). Examples: pipes, bulbs, panels. +### *model-name* + +In addition to built-in model types, you can use your own, loaded from file. + +The property specifies the model name without `entry_point:models/` nor extension. + +> [!WARNING] +> Textures (materials) used in the model must be in the `blocks` atlas and specified in the *atlas-texture* format: +> `blocks:texture_name` + ### *draw-group* Integer specifying number of block draw group (render order). Used for semi-transparent blocks. diff --git a/doc/ru/block-properties.md b/doc/ru/block-properties.md index 366cf0fb..2f958e88 100644 --- a/doc/ru/block-properties.md +++ b/doc/ru/block-properties.md @@ -35,6 +35,16 @@ - "X" - модель травы (крест из двух спрайтов) - "aabb" - модель, соответствующая хитбоксу блока (составной хитбокс будет объединен в один). Примеры: трубы, лампочки, панели. +### Имя модели - *model-name* + +Кроме встроенных типов моделей, можно использовать собственные, загружаемые из файлов. + +В свойстве указывается имя модели без `точка_входа:models/` и расширения. + +> [!WARNING] +> Текстуры (материалы), использующиеся в модели, должны находиться в атласе `blocks` и указываться в соответствующем формате: +> `blocks:имя_текстуры` + ### Группа отрисовки - *draw-group* Целое число определяющее номер группы отрисовки данного блока. From 560288b5c337f100781a2cb1d557e6200a8a50df Mon Sep 17 00:00:00 2001 From: MihailRis Date: Tue, 24 Dec 2024 20:00:49 +0300 Subject: [PATCH 02/12] update util::PseudoRandom.setSeed --- src/maths/util.hpp | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/maths/util.hpp b/src/maths/util.hpp index ec128917..df39cf41 100644 --- a/src/maths/util.hpp +++ b/src/maths/util.hpp @@ -9,6 +9,12 @@ #include namespace util { + inline uint64_t shuffle_bits_step(uint64_t x, uint64_t m, unsigned shift) { + uint64_t t = ((x >> shift) ^ x) & m; + x = (x ^ t) ^ (t << shift); + return x; + } + constexpr inline float EPSILON = 1e-6f; class PseudoRandom { @@ -57,17 +63,20 @@ namespace util { return randU64() / static_cast(UINT64_MAX); } - void setSeed(int number) { - seed = (static_cast(number * 23729) ^ - static_cast(number + 16786)); - rand(); - } void setSeed(int number1, int number2) { seed = ((static_cast(number1 * 23729) | static_cast(number2 % 16786)) ^ static_cast(number2 * number1)); rand(); } + + void setSeed(long number) { + number = shuffle_bits_step(number, 0x2222222222222222ull, 1); + number = shuffle_bits_step(number, 0x0c0c0c0c0c0c0c0cull, 2); + number = shuffle_bits_step(number, 0x00f000f000f000f0ull, 4); + seed = number; + rand(); + } }; template From ad6a6666da0857353083641320b44ee33391e230 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Wed, 25 Dec 2024 06:06:55 +0300 Subject: [PATCH 03/12] rename test library to app & rename app.name to app.script --- dev/tests/chunks.lua | 12 ++++---- dev/tests/world.lua | 12 ++++---- res/scripts/stdlib.lua | 30 +++++++++---------- src/logic/scripting/lua/libs/api_lua.hpp | 2 +- .../lua/libs/{libtest.cpp => libapp.cpp} | 2 +- src/logic/scripting/lua/lua_engine.cpp | 10 +++---- src/logic/scripting/lua/lua_engine.hpp | 2 +- 7 files changed, 35 insertions(+), 35 deletions(-) rename src/logic/scripting/lua/libs/{libtest.cpp => libapp.cpp} (60%) diff --git a/dev/tests/chunks.lua b/dev/tests/chunks.lua index dbc001ba..dfc2fced 100644 --- a/dev/tests/chunks.lua +++ b/dev/tests/chunks.lua @@ -1,8 +1,8 @@ -test.set_setting("chunks.load-distance", 3) -test.set_setting("chunks.load-speed", 1) +app.set_setting("chunks.load-distance", 3) +app.set_setting("chunks.load-speed", 1) -test.reconfig_packs({"base"}, {}) -test.new_world("demo", "2019", "core:default") +app.reconfig_packs({"base"}, {}) +app.new_world("demo", "2019", "core:default") local pid1 = player.create("Xerxes") assert(player.get_name(pid1) == "Xerxes") @@ -21,7 +21,7 @@ for i=1,25 do end player.set_pos(pid1, math.random() * 100 - 50, 100, math.random() * 100 - 50) player.set_pos(pid2, math.random() * 200 - 100, 100, math.random() * 200 - 100) - test.tick() + app.tick() end -test.close_world(true) +app.close_world(true) diff --git a/dev/tests/world.lua b/dev/tests/world.lua index 3e7353e3..32f56ad2 100644 --- a/dev/tests/world.lua +++ b/dev/tests/world.lua @@ -1,23 +1,23 @@ -- Create/close/open/close world -- Open -test.new_world("demo", "2019", "core:default") +app.new_world("demo", "2019", "core:default") assert(world.is_open()) assert(world.get_generator() == "core:default") -test.sleep(1) +app.sleep(1) assert(world.get_total_time() > 0.0) print(world.get_total_time()) -- Close -test.close_world(true) +app.close_world(true) assert(not world.is_open()) -- Reopen -test.open_world("demo") +app.open_world("demo") assert(world.is_open()) assert(world.get_total_time() > 0.0) assert(world.get_seed() == 2019) -test.tick() +app.tick() -- Close -test.close_world(true) +app.close_world(true) diff --git a/res/scripts/stdlib.lua b/res/scripts/stdlib.lua index 0a49ccd1..26f04582 100644 --- a/res/scripts/stdlib.lua +++ b/res/scripts/stdlib.lua @@ -22,21 +22,21 @@ function tb_frame_tostring(frame) return s end -if test then - test.sleep = sleep - test.name = __VC_TEST_NAME - test.new_world = core.new_world - test.open_world = core.open_world - test.close_world = core.close_world - test.reopen_world = core.reopen_world - test.delete_world = core.delete_world - test.reconfig_packs = core.reconfig_packs - test.set_setting = core.set_setting - test.tick = coroutine.yield +if app then + app.sleep = sleep + app.script = __VC_SCRIPT_NAME + app.new_world = core.new_world + app.open_world = core.open_world + app.close_world = core.close_world + app.reopen_world = core.reopen_world + app.delete_world = core.delete_world + app.reconfig_packs = core.reconfig_packs + app.set_setting = core.set_setting + app.tick = coroutine.yield - function test.quit() + function app.quit() local tb = debug.get_traceback(1) - local s = "test.quit() traceback:" + local s = "app.quit() traceback:" for i, frame in ipairs(tb) do s = s .. "\n\t"..tb_frame_tostring(frame) end @@ -45,11 +45,11 @@ if test then coroutine.yield() end - function test.sleep_until(predicate, max_ticks) + function app.sleep_until(predicate, max_ticks) max_ticks = max_ticks or 1e9 local ticks = 0 while ticks < max_ticks and not predicate() do - test.tick() + app.tick() end if ticks == max_ticks then error("max ticks exceed") diff --git a/src/logic/scripting/lua/libs/api_lua.hpp b/src/logic/scripting/lua/libs/api_lua.hpp index 23f3db66..48ea6da1 100644 --- a/src/logic/scripting/lua/libs/api_lua.hpp +++ b/src/logic/scripting/lua/libs/api_lua.hpp @@ -37,7 +37,7 @@ extern const luaL_Reg packlib[]; extern const luaL_Reg particleslib[]; // gfx.particles extern const luaL_Reg playerlib[]; extern const luaL_Reg quatlib[]; -extern const luaL_Reg testlib[]; +extern const luaL_Reg applib[]; extern const luaL_Reg text3dlib[]; // gfx.text3d extern const luaL_Reg timelib[]; extern const luaL_Reg tomllib[]; diff --git a/src/logic/scripting/lua/libs/libtest.cpp b/src/logic/scripting/lua/libs/libapp.cpp similarity index 60% rename from src/logic/scripting/lua/libs/libtest.cpp rename to src/logic/scripting/lua/libs/libapp.cpp index 034a72fb..fa3b0453 100644 --- a/src/logic/scripting/lua/libs/libtest.cpp +++ b/src/logic/scripting/lua/libs/libapp.cpp @@ -1,5 +1,5 @@ #include "api_lua.hpp" -const luaL_Reg testlib[] = { +const luaL_Reg applib[] = { {NULL, NULL} }; diff --git a/src/logic/scripting/lua/lua_engine.cpp b/src/logic/scripting/lua/lua_engine.cpp index b34b87a0..dca6ec69 100644 --- a/src/logic/scripting/lua/lua_engine.cpp +++ b/src/logic/scripting/lua/lua_engine.cpp @@ -58,10 +58,10 @@ static void create_libs(State* L, StateType stateType) { openlib(L, "vec3", vec3lib); openlib(L, "vec4", vec4lib); - if (stateType == StateType::TEST) { - openlib(L, "test", testlib); + if (stateType == StateType::SCRIPT) { + openlib(L, "app", applib); } - if (stateType == StateType::BASE || stateType == StateType::TEST) { + if (stateType == StateType::BASE || stateType == StateType::SCRIPT) { openlib(L, "gui", guilib); openlib(L, "input", inputlib); openlib(L, "inventory", inventorylib); @@ -119,10 +119,10 @@ void lua::initialize(const EnginePaths& paths, const CoreParameters& params) { logger.info() << LUAJIT_VERSION; main_thread = create_state( - paths, params.headless ? StateType::TEST : StateType::BASE + paths, params.headless ? StateType::SCRIPT : StateType::BASE ); lua::pushstring(main_thread, params.scriptFile.stem().u8string()); - lua::setglobal(main_thread, "__VC_TEST_NAME"); + lua::setglobal(main_thread, "__VC_SCRIPT_NAME"); } void lua::finalize() { diff --git a/src/logic/scripting/lua/lua_engine.hpp b/src/logic/scripting/lua/lua_engine.hpp index a70f5948..aee93035 100644 --- a/src/logic/scripting/lua/lua_engine.hpp +++ b/src/logic/scripting/lua/lua_engine.hpp @@ -13,7 +13,7 @@ struct CoreParameters; namespace lua { enum class StateType { BASE, - TEST, + SCRIPT, GENERATOR, }; From 686ace37f179e531b5509b56988f6d7a2fe92731 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Wed, 25 Dec 2024 06:10:38 +0300 Subject: [PATCH 04/12] fix: app.sleep_until max_ticks ignored --- res/scripts/stdlib.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/res/scripts/stdlib.lua b/res/scripts/stdlib.lua index 26f04582..f5d15201 100644 --- a/res/scripts/stdlib.lua +++ b/res/scripts/stdlib.lua @@ -50,6 +50,7 @@ if app then local ticks = 0 while ticks < max_ticks and not predicate() do app.tick() + ticks = ticks + 1 end if ticks == max_ticks then error("max ticks exceed") From be0945b4a5a0aeffae7aaddd93784affaca97cb1 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Wed, 25 Dec 2024 06:52:30 +0300 Subject: [PATCH 05/12] add app.get_version, app.get_setting_info --- res/scripts/stdlib.lua | 2 ++ 1 file changed, 2 insertions(+) diff --git a/res/scripts/stdlib.lua b/res/scripts/stdlib.lua index f5d15201..245e2962 100644 --- a/res/scripts/stdlib.lua +++ b/res/scripts/stdlib.lua @@ -33,6 +33,8 @@ if app then app.reconfig_packs = core.reconfig_packs app.set_setting = core.set_setting app.tick = coroutine.yield + app.get_version = core.get_version + app.get_setting_info = core.get_setting_info function app.quit() local tb = debug.get_traceback(1) From 8179b9c2497e02501d3156fe4818c1fa22bd3560 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Wed, 25 Dec 2024 07:01:26 +0300 Subject: [PATCH 06/12] add app.get_setting --- res/scripts/stdlib.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/res/scripts/stdlib.lua b/res/scripts/stdlib.lua index 245e2962..7900e1c8 100644 --- a/res/scripts/stdlib.lua +++ b/res/scripts/stdlib.lua @@ -31,6 +31,7 @@ if app then app.reopen_world = core.reopen_world app.delete_world = core.delete_world app.reconfig_packs = core.reconfig_packs + app.get_setting = core.get_setting app.set_setting = core.set_setting app.tick = coroutine.yield app.get_version = core.get_version From 36bfa215c1d6c8a7ebe319c192b870028a0c095b Mon Sep 17 00:00:00 2001 From: MihailRis Date: Wed, 25 Dec 2024 07:27:53 +0300 Subject: [PATCH 07/12] add app library docs --- doc/en/scripting/builtins/libapp.md | 130 +++++++++++++++++++++++++++ doc/ru/scripting/builtins/libapp.md | 131 ++++++++++++++++++++++++++++ 2 files changed, 261 insertions(+) create mode 100644 doc/en/scripting/builtins/libapp.md create mode 100644 doc/ru/scripting/builtins/libapp.md diff --git a/doc/en/scripting/builtins/libapp.md b/doc/en/scripting/builtins/libapp.md new file mode 100644 index 00000000..00b6ae9a --- /dev/null +++ b/doc/en/scripting/builtins/libapp.md @@ -0,0 +1,130 @@ +# *app* library + +A library for high-level engine control, available only in script/test mode. + +The script/test name without path and extension is available as `app.script`. The file path can be obtained as: +```lua +local filename = "script:"..app.script..".lua" +``` + +## Functions + +```lua +app.tick() +``` + +Executes one tick of the engine main loop. + +```lua +app.sleep(time: number) +``` + +Waits for the specified time in seconds, executing the engine main loop. + +```lua +app.sleep_until( + -- function that checks the wait finishing condition + predicate: function() -> bool, + -- maximum number of engine cycle ticks, after which + -- an exception "max ticks exceed" will be thrown + [optional] max_ticks = 1e9 +) +``` + +Waits for the condition checked by the function to be true, executing the engine main loop. + +```lua +app.quit() +``` + +Quits the engine, printing the call stack to track where the function was called. + +```lua +app.reconfig_packs( + -- packs to add + add_packs: table, + -- packs to remove + remove_packs: table +) +``` + +Updates the packs configuration, checking its correctness (dependencies and packs existence). + +To remove all packs from the configuration, you can use `pack.get_installed()`: + +```lua +app.reconfig_packs({}, pack.get_installed()) +``` + +In this case, `base` will also be removed from the configuration. + +```lua +app.new_world( + -- world name + name: str, + -- seed of generation + seed: str, + -- name of generator + generator: str +) +``` + +Creates a new world and opens it. + +```lua +app.open_world(name: str) +``` + +Opens a world by name. + +```lua +app.reopen_world() +``` + +Reopens the world. + +```lua +app.close_world( + -- save the world before closing + [optional] save_world: bool=false +) +``` + +Closes the world. + +```lua +app.delete_world(name: str) +``` + +Deletes a world by name. + +```lua +app.get_version() -> int, int +``` + +Returns the major and minor engine versions. + +```lua +app.get_setting(name: str) -> value +``` + +Returns the value of a setting. Throws an exception if the setting does not exist. + +```lua +app.set_setting(name: str, value: value) +``` + +Sets the value of a setting. Throws an exception if the setting does not exist. + +```lua +app.get_setting_info(name: str) -> { + -- default value + def: value + -- minimum value + [numeric settings only] min: number, + -- maximum value + [numeric settings only] max: number +} +``` + +Returns a table with information about the setting. Throws an exception if the setting does not exist. diff --git a/doc/ru/scripting/builtins/libapp.md b/doc/ru/scripting/builtins/libapp.md new file mode 100644 index 00000000..1cf067a2 --- /dev/null +++ b/doc/ru/scripting/builtins/libapp.md @@ -0,0 +1,131 @@ +# Библиотека *app* + +Библиотека для высокоуровневого управления работой движка, доступная только в режиме сценария или теста. + +Имя сценария/теста без пути и расширения доступен как `app.script`. Путь к файлу можно получить как: +```lua +local filename = "script:"..app.script..".lua" +``` + +## Функции + +```lua +app.tick() +``` + +Выполняет один такт основного цикла движка. + +```lua +app.sleep(time: number) +``` + +Ожидает указанное время в секундах, выполняя основной цикл движка. + +```lua +app.sleep_until( + -- функция, проверяющее условия завершения ожидания + predicate: function() -> bool, + -- максимальное количество тактов цикла движка, после истечения которых + -- будет брошено исключение "max ticks exceed" + [опционально] max_ticks = 1e9 +) +``` + +Ожидает истинности утверждения (условия), проверяемого функцией, выполнячя основной цикл движка. + +```lua +app.quit() +``` + +Завершает выполнение движка, выводя стек вызовов для ослеживания места вызова функции. + +```lua +app.reconfig_packs( + -- добавляемые паки + add_packs: table, + -- удаляемые паки + remove_packs: table +) +``` + +Обновляет конфигурацию паков, проверяя её корректность (зависимости и доступность паков). + +Для удаления всех паков из конфигурации можно использовать `pack.get_installed()`: + +```lua +app.reconfig_packs({}, pack.get_installed()) +``` + +В этом случае из конфигурации будет удалён и `base`. + +```lua +app.new_world( + -- название мира + name: str, + -- зерно генерации + seed: str, + -- название генератора + generator: str +) +``` + +Создаёт новый мир и открывает его. + +```lua +app.open_world(name: str) +``` + +Открывает мир по названию. + +```lua +app.reopen_world() +``` + +Переоткрывает мир. + +```lua +app.close_world( + -- сохранить мир перед закрытием + [опционально] save_world: bool=false +) +``` + +Закрывает мир. + +```lua +app.delete_world(name: str) +``` + +Удаляет мир по названию. + +```lua +app.get_version() -> int, int +``` + +Возвращает мажорную и минорную версии движка. + +```lua +app.get_setting(name: str) -> value +``` + +Возвращает значение настройки. Бросает исключение, если настройки не существует. + +```lua +app.set_setting(name: str, value: value) +``` + +Устанавливает значение настройки. Бросает исключение, если настройки не существует. + + +```lua +app.get_setting_info(name: str) -> { + -- значение по-умолчанию + def: value + -- минимальное значение + [только числовые настройки] min: number, + -- максимальное значение + [только числовые настройки] max: number +} +``` + +Возвращает таблицу с информацией о настройке. Бросает исключение, если настройки не существует. From bb038653d6eafb51b660bd50bfb91c4fae5a7f24 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Wed, 25 Dec 2024 10:28:31 +0300 Subject: [PATCH 08/12] fix UVFace.rotate --- src/maths/UVFace.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/maths/UVFace.hpp b/src/maths/UVFace.hpp index 538ae210..8a0815bb 100644 --- a/src/maths/UVFace.hpp +++ b/src/maths/UVFace.hpp @@ -16,7 +16,7 @@ struct UVFace { } template - inline void rotate(int times) { + inline void rotate() { int times = n % 4; if (times < 0) { times += 4; From e98132f4dad93985e39016a49b70cb11f69f6857 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Wed, 25 Dec 2024 10:42:45 +0300 Subject: [PATCH 09/12] update doc/en/scripting/builtins/libapp.md --- doc/en/scripting/builtins/libapp.md | 34 ++++++++++++++--------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/doc/en/scripting/builtins/libapp.md b/doc/en/scripting/builtins/libapp.md index 00b6ae9a..6b1d8e60 100644 --- a/doc/en/scripting/builtins/libapp.md +++ b/doc/en/scripting/builtins/libapp.md @@ -1,8 +1,8 @@ # *app* library -A library for high-level engine control, available only in script/test mode. +A library for high-level engine control, available only in script or test mode. -The script/test name without path and extension is available as `app.script`. The file path can be obtained as: +The script/test name without the path and extension is available as `app.script`. The file path can be obtained as: ```lua local filename = "script:"..app.script..".lua" ``` @@ -13,31 +13,31 @@ local filename = "script:"..app.script..".lua" app.tick() ``` -Executes one tick of the engine main loop. +Performs one tick of the main engine loop. ```lua app.sleep(time: number) ``` -Waits for the specified time in seconds, executing the engine main loop. +Waits for the specified time in seconds, performing the main engine loop. ```lua app.sleep_until( - -- function that checks the wait finishing condition + -- function that checks the condition for ending the wait predicate: function() -> bool, - -- maximum number of engine cycle ticks, after which - -- an exception "max ticks exceed" will be thrown + -- the maximum number of engine loop ticks after which + -- a "max ticks exceed" exception will be thrown [optional] max_ticks = 1e9 ) ``` -Waits for the condition checked by the function to be true, executing the engine main loop. +Waits for the condition checked by the function to be true, performing the main engine loop. ```lua app.quit() ``` -Quits the engine, printing the call stack to track where the function was called. +Terminates the engine, printing the call stack to trace the function call location. ```lua app.reconfig_packs( @@ -48,7 +48,7 @@ app.reconfig_packs( ) ``` -Updates the packs configuration, checking its correctness (dependencies and packs existence). +Updates the pack configuration, checking its correctness (dependencies and availability of packs). To remove all packs from the configuration, you can use `pack.get_installed()`: @@ -62,9 +62,9 @@ In this case, `base` will also be removed from the configuration. app.new_world( -- world name name: str, - -- seed of generation + -- generation seed seed: str, - -- name of generator + -- generator name generator: str ) ``` @@ -102,7 +102,7 @@ Deletes a world by name. app.get_version() -> int, int ``` -Returns the major and minor engine versions. +Returns the major and minor versions of the engine. ```lua app.get_setting(name: str) -> value @@ -119,12 +119,12 @@ Sets the value of a setting. Throws an exception if the setting does not exist. ```lua app.get_setting_info(name: str) -> { -- default value - def: value + def: value, -- minimum value - [numeric settings only] min: number, + [only for numeric settings] min: number, -- maximum value - [numeric settings only] max: number + [only for numeric settings] max: number } ``` -Returns a table with information about the setting. Throws an exception if the setting does not exist. +Returns a table with information about a setting. Throws an exception if the setting does not exist. From 357e4f860707d3d1e9e3c9841c416bcc25526413 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Wed, 25 Dec 2024 11:04:12 +0300 Subject: [PATCH 10/12] refactor: extract post-runnables to a separate class --- src/PostRunnables.hpp | 29 +++++++++++++++++++++++++++++ src/engine.cpp | 16 +--------------- src/engine.hpp | 11 +++++------ 3 files changed, 35 insertions(+), 21 deletions(-) create mode 100644 src/PostRunnables.hpp diff --git a/src/PostRunnables.hpp b/src/PostRunnables.hpp new file mode 100644 index 00000000..dc227c88 --- /dev/null +++ b/src/PostRunnables.hpp @@ -0,0 +1,29 @@ +#pragma once + +#include +#include +#include "delegates.hpp" + +class PostRunnables { + std::queue runnables; + std::recursive_mutex mutex; +public: + void postRunnable(runnable task) { + std::lock_guard lock(mutex); + runnables.push(std::move(task)); + } + + void run() { + std::queue tasksToRun; + { + std::lock_guard lock(mutex); + std::swap(tasksToRun, runnables); + } + + while (!tasksToRun.empty()) { + auto& task = tasksToRun.front(); + task(); + tasksToRun.pop(); + } + } +}; diff --git a/src/engine.cpp b/src/engine.cpp index a3c63035..da69e75e 100644 --- a/src/engine.cpp +++ b/src/engine.cpp @@ -184,7 +184,7 @@ void Engine::run() { void Engine::postUpdate() { network->update(); - processPostRunnables(); + postRunnables.run(); } void Engine::updateFrontend() { @@ -213,15 +213,6 @@ void Engine::renderFrame() { gui->draw(ctx, *assets); } -void Engine::processPostRunnables() { - std::lock_guard lock(postRunnablesMutex); - while (!postRunnables.empty()) { - postRunnables.front()(); - postRunnables.pop(); - } - scripting::process_post_runnables(); -} - void Engine::saveSettings() { logger.info() << "saving settings"; files::write_string(paths.getSettingsFile(), toml::stringify(settingsHandler)); @@ -517,11 +508,6 @@ std::shared_ptr Engine::getScreen() { return screen; } -void Engine::postRunnable(const runnable& callback) { - std::lock_guard lock(postRunnablesMutex); - postRunnables.push(callback); -} - SettingsHandler& Engine::getSettingsHandler() { return settingsHandler; } diff --git a/src/engine.hpp b/src/engine.hpp index f10fb3a0..56231928 100644 --- a/src/engine.hpp +++ b/src/engine.hpp @@ -11,15 +11,14 @@ #include "files/engine_paths.hpp" #include "files/settings_io.hpp" #include "util/ObjectsKeeper.hpp" +#include "PostRunnables.hpp" #include "Time.hpp" #include #include -#include #include #include #include -#include class Level; class Screen; @@ -65,13 +64,12 @@ class Engine : public util::ObjectsKeeper { std::vector contentPacks; std::unique_ptr content; std::unique_ptr resPaths; - std::queue postRunnables; - std::recursive_mutex postRunnablesMutex; std::unique_ptr controller; std::unique_ptr interpreter; std::unique_ptr network; std::vector basePacks; std::unique_ptr gui; + PostRunnables postRunnables; Time time; consumer> levelConsumer; bool quitSignal = false; @@ -80,7 +78,6 @@ class Engine : public util::ObjectsKeeper { void loadSettings(); void saveSettings(); void updateHotkeys(); - void processPostRunnables(); void loadAssets(); public: Engine(CoreParameters coreParameters); @@ -157,7 +154,9 @@ public: std::shared_ptr getScreen(); /// @brief Enqueue function call to the end of current frame in draw thread - void postRunnable(const runnable& callback); + void postRunnable(const runnable& callback) { + postRunnables.postRunnable(callback); + } void saveScreenshot(); From 5e76cdfadcd0b237326f7e64a5e4ab88b8dfab8a Mon Sep 17 00:00:00 2001 From: MihailRis Date: Wed, 25 Dec 2024 12:13:03 +0300 Subject: [PATCH 11/12] rename engine.hpp/cpp to Engine.hpp/cpp & move Engine, Time and mainloop classes to 'engine' folder --- src/{engine.cpp => engine/Engine.cpp} | 11 +++-------- src/{engine.hpp => engine/Engine.hpp} | 0 src/{ => engine}/Mainloop.cpp | 2 +- src/{ => engine}/Mainloop.hpp | 0 src/{ => engine}/PostRunnables.hpp | 0 src/{ => engine}/ServerMainloop.cpp | 2 +- src/{ => engine}/ServerMainloop.hpp | 0 src/{ => engine}/Time.hpp | 0 src/frontend/debug_panel.cpp | 2 +- src/frontend/hud.cpp | 2 +- src/frontend/menu.cpp | 2 +- src/frontend/screens/LevelScreen.cpp | 2 +- src/frontend/screens/MenuScreen.cpp | 2 +- src/frontend/screens/Screen.cpp | 2 +- src/graphics/render/Decorator.cpp | 2 +- src/graphics/render/WorldRenderer.cpp | 2 +- src/logic/EngineController.cpp | 2 +- src/logic/LevelController.cpp | 2 +- src/logic/scripting/lua/libs/libaudio.cpp | 2 +- src/logic/scripting/lua/libs/libconsole.cpp | 2 +- src/logic/scripting/lua/libs/libcore.cpp | 2 +- src/logic/scripting/lua/libs/libentity.cpp | 2 +- src/logic/scripting/lua/libs/libfile.cpp | 2 +- src/logic/scripting/lua/libs/libgeneration.cpp | 2 +- src/logic/scripting/lua/libs/libgui.cpp | 2 +- src/logic/scripting/lua/libs/libhud.cpp | 2 +- src/logic/scripting/lua/libs/libinput.cpp | 2 +- src/logic/scripting/lua/libs/libnetwork.cpp | 2 +- src/logic/scripting/lua/libs/libpack.cpp | 2 +- src/logic/scripting/lua/libs/libparticles.cpp | 2 +- src/logic/scripting/lua/libs/libtext3d.cpp | 2 +- src/logic/scripting/lua/libs/libtime.cpp | 2 +- src/logic/scripting/lua/libs/libworld.cpp | 2 +- src/logic/scripting/lua/lua_engine.cpp | 2 +- .../scripting/lua/usertypes/lua_type_heightmap.cpp | 2 +- src/logic/scripting/scripting.cpp | 2 +- src/logic/scripting/scripting_hud.cpp | 2 +- src/logic/scripting/scripting_world_generation.cpp | 2 +- src/main.cpp | 2 +- src/objects/Entities.cpp | 2 +- src/util/command_line.cpp | 2 +- 41 files changed, 38 insertions(+), 43 deletions(-) rename src/{engine.cpp => engine/Engine.cpp} (95%) rename src/{engine.hpp => engine/Engine.hpp} (100%) rename src/{ => engine}/Mainloop.cpp (98%) rename src/{ => engine}/Mainloop.hpp (100%) rename src/{ => engine}/PostRunnables.hpp (100%) rename src/{ => engine}/ServerMainloop.cpp (99%) rename src/{ => engine}/ServerMainloop.hpp (100%) rename src/{ => engine}/Time.hpp (100%) diff --git a/src/engine.cpp b/src/engine/Engine.cpp similarity index 95% rename from src/engine.cpp rename to src/engine/Engine.cpp index da69e75e..35caf40d 100644 --- a/src/engine.cpp +++ b/src/engine/Engine.cpp @@ -1,4 +1,4 @@ -#include "engine.hpp" +#include "Engine.hpp" #define GLEW_STATIC @@ -285,13 +285,8 @@ void Engine::loadAssets() { auto task = loader.startTask([=](){}); task->waitForEnd(); } else { - try { - while (loader.hasNext()) { - loader.loadNext(); - } - } catch (const assetload::error& err) { - new_assets.reset(); - throw; + while (loader.hasNext()) { + loader.loadNext(); } } assets = std::move(new_assets); diff --git a/src/engine.hpp b/src/engine/Engine.hpp similarity index 100% rename from src/engine.hpp rename to src/engine/Engine.hpp diff --git a/src/Mainloop.cpp b/src/engine/Mainloop.cpp similarity index 98% rename from src/Mainloop.cpp rename to src/engine/Mainloop.cpp index a12434ef..e0e64d10 100644 --- a/src/Mainloop.cpp +++ b/src/engine/Mainloop.cpp @@ -1,7 +1,7 @@ #include "Mainloop.hpp" +#include "Engine.hpp" #include "debug/Logger.hpp" -#include "engine.hpp" #include "frontend/screens/MenuScreen.hpp" #include "frontend/screens/LevelScreen.hpp" #include "window/Window.hpp" diff --git a/src/Mainloop.hpp b/src/engine/Mainloop.hpp similarity index 100% rename from src/Mainloop.hpp rename to src/engine/Mainloop.hpp diff --git a/src/PostRunnables.hpp b/src/engine/PostRunnables.hpp similarity index 100% rename from src/PostRunnables.hpp rename to src/engine/PostRunnables.hpp diff --git a/src/ServerMainloop.cpp b/src/engine/ServerMainloop.cpp similarity index 99% rename from src/ServerMainloop.cpp rename to src/engine/ServerMainloop.cpp index 2c88a06b..422172b4 100644 --- a/src/ServerMainloop.cpp +++ b/src/engine/ServerMainloop.cpp @@ -1,5 +1,6 @@ #include "ServerMainloop.hpp" +#include "Engine.hpp" #include "logic/scripting/scripting.hpp" #include "logic/LevelController.hpp" #include "interfaces/Process.hpp" @@ -7,7 +8,6 @@ #include "world/Level.hpp" #include "world/World.hpp" #include "util/platform.hpp" -#include "engine.hpp" #include diff --git a/src/ServerMainloop.hpp b/src/engine/ServerMainloop.hpp similarity index 100% rename from src/ServerMainloop.hpp rename to src/engine/ServerMainloop.hpp diff --git a/src/Time.hpp b/src/engine/Time.hpp similarity index 100% rename from src/Time.hpp rename to src/engine/Time.hpp diff --git a/src/frontend/debug_panel.cpp b/src/frontend/debug_panel.cpp index a5607803..00f0ee45 100644 --- a/src/frontend/debug_panel.cpp +++ b/src/frontend/debug_panel.cpp @@ -1,6 +1,6 @@ #include "audio/audio.hpp" #include "delegates.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" #include "settings.hpp" #include "hud.hpp" #include "content/Content.hpp" diff --git a/src/frontend/hud.cpp b/src/frontend/hud.cpp index f0535e14..a367227e 100644 --- a/src/frontend/hud.cpp +++ b/src/frontend/hud.cpp @@ -8,7 +8,7 @@ #include "content/Content.hpp" #include "core_defs.hpp" #include "delegates.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" #include "graphics/core/Atlas.hpp" #include "graphics/core/Batch2D.hpp" #include "graphics/core/Batch3D.hpp" diff --git a/src/frontend/menu.cpp b/src/frontend/menu.cpp index 8a71b8ba..64f8affb 100644 --- a/src/frontend/menu.cpp +++ b/src/frontend/menu.cpp @@ -5,7 +5,7 @@ #include "screens/MenuScreen.hpp" #include "delegates.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" #include "data/dv.hpp" #include "interfaces/Task.hpp" #include "files/engine_paths.hpp" diff --git a/src/frontend/screens/LevelScreen.cpp b/src/frontend/screens/LevelScreen.cpp index 5fc073b3..bb63e572 100644 --- a/src/frontend/screens/LevelScreen.cpp +++ b/src/frontend/screens/LevelScreen.cpp @@ -5,7 +5,7 @@ #include "content/Content.hpp" #include "core_defs.hpp" #include "debug/Logger.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" #include "files/files.hpp" #include "frontend/LevelFrontend.hpp" #include "frontend/hud.hpp" diff --git a/src/frontend/screens/MenuScreen.cpp b/src/frontend/screens/MenuScreen.cpp index ec75ac00..f16f73ee 100644 --- a/src/frontend/screens/MenuScreen.cpp +++ b/src/frontend/screens/MenuScreen.cpp @@ -8,7 +8,7 @@ #include "maths/UVRegion.hpp" #include "window/Window.hpp" #include "window/Camera.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" MenuScreen::MenuScreen(Engine& engine) : Screen(engine) { engine.resetContent(); diff --git a/src/frontend/screens/Screen.cpp b/src/frontend/screens/Screen.cpp index 16fde620..3fd64825 100644 --- a/src/frontend/screens/Screen.cpp +++ b/src/frontend/screens/Screen.cpp @@ -1,7 +1,7 @@ #include "Screen.hpp" #include "graphics/core/Batch2D.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" Screen::Screen(Engine& engine) : engine(engine), diff --git a/src/graphics/render/Decorator.cpp b/src/graphics/render/Decorator.cpp index c5d66ea8..c785098c 100644 --- a/src/graphics/render/Decorator.cpp +++ b/src/graphics/render/Decorator.cpp @@ -14,7 +14,7 @@ #include "objects/Players.hpp" #include "logic/LevelController.hpp" #include "util/stringutil.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" #include "files/files.hpp" namespace fs = std::filesystem; diff --git a/src/graphics/render/WorldRenderer.cpp b/src/graphics/render/WorldRenderer.cpp index 098cb8e8..e5456d90 100644 --- a/src/graphics/render/WorldRenderer.cpp +++ b/src/graphics/render/WorldRenderer.cpp @@ -11,7 +11,7 @@ #include "assets/Assets.hpp" #include "assets/assets_util.hpp" #include "content/Content.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" #include "frontend/LevelFrontend.hpp" #include "frontend/ContentGfxCache.hpp" #include "items/Inventory.hpp" diff --git a/src/logic/EngineController.cpp b/src/logic/EngineController.cpp index 94a76862..a21325fe 100644 --- a/src/logic/EngineController.cpp +++ b/src/logic/EngineController.cpp @@ -4,7 +4,7 @@ #include #include -#include "engine.hpp" +#include "engine/Engine.hpp" #include "coders/commons.hpp" #include "debug/Logger.hpp" #include "content/ContentReport.hpp" diff --git a/src/logic/LevelController.cpp b/src/logic/LevelController.cpp index 6e7fcca6..efe7ae0d 100644 --- a/src/logic/LevelController.cpp +++ b/src/logic/LevelController.cpp @@ -3,7 +3,7 @@ #include #include "debug/Logger.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" #include "files/WorldFiles.hpp" #include "maths/voxmaths.hpp" #include "objects/Entities.hpp" diff --git a/src/logic/scripting/lua/libs/libaudio.cpp b/src/logic/scripting/lua/libs/libaudio.cpp index ee311585..aa7b0f8f 100644 --- a/src/logic/scripting/lua/libs/libaudio.cpp +++ b/src/logic/scripting/lua/libs/libaudio.cpp @@ -1,5 +1,5 @@ #include "audio/audio.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" #include "api_lua.hpp" inline const char* DEFAULT_CHANNEL = "regular"; diff --git a/src/logic/scripting/lua/libs/libconsole.cpp b/src/logic/scripting/lua/libs/libconsole.cpp index 1e9168ef..295d264b 100644 --- a/src/logic/scripting/lua/libs/libconsole.cpp +++ b/src/logic/scripting/lua/libs/libconsole.cpp @@ -1,5 +1,5 @@ #include "coders/commons.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" #include "logic/CommandsInterpreter.hpp" #include "api_lua.hpp" diff --git a/src/logic/scripting/lua/libs/libcore.cpp b/src/logic/scripting/lua/libs/libcore.cpp index ac26bd47..af15df21 100644 --- a/src/logic/scripting/lua/libs/libcore.cpp +++ b/src/logic/scripting/lua/libs/libcore.cpp @@ -6,7 +6,7 @@ #include "constants.hpp" #include "content/Content.hpp" #include "debug/Logger.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" #include "files/engine_paths.hpp" #include "files/files.hpp" #include "files/settings_io.hpp" diff --git a/src/logic/scripting/lua/libs/libentity.cpp b/src/logic/scripting/lua/libs/libentity.cpp index ce394fb5..211bf5b1 100644 --- a/src/logic/scripting/lua/libs/libentity.cpp +++ b/src/logic/scripting/lua/libs/libentity.cpp @@ -1,7 +1,7 @@ #include "libentity.hpp" #include "content/Content.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" #include "objects/Entities.hpp" #include "objects/EntityDef.hpp" #include "objects/Player.hpp" diff --git a/src/logic/scripting/lua/libs/libfile.cpp b/src/logic/scripting/lua/libs/libfile.cpp index 6b35b11e..7fc70f46 100644 --- a/src/logic/scripting/lua/libs/libfile.cpp +++ b/src/logic/scripting/lua/libs/libfile.cpp @@ -3,7 +3,7 @@ #include #include "coders/gzip.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" #include "files/engine_paths.hpp" #include "files/files.hpp" #include "util/stringutil.hpp" diff --git a/src/logic/scripting/lua/libs/libgeneration.cpp b/src/logic/scripting/lua/libs/libgeneration.cpp index dddca12e..90b681c3 100644 --- a/src/logic/scripting/lua/libs/libgeneration.cpp +++ b/src/logic/scripting/lua/libs/libgeneration.cpp @@ -6,7 +6,7 @@ #include "world/Level.hpp" #include "world/generator/VoxelFragment.hpp" #include "content/ContentLoader.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" #include "../lua_custom_types.hpp" using namespace scripting; diff --git a/src/logic/scripting/lua/libs/libgui.cpp b/src/logic/scripting/lua/libs/libgui.cpp index 2a485be7..97b5a8cc 100644 --- a/src/logic/scripting/lua/libs/libgui.cpp +++ b/src/logic/scripting/lua/libs/libgui.cpp @@ -1,5 +1,5 @@ #include "assets/Assets.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" #include "frontend/UiDocument.hpp" #include "frontend/locale.hpp" #include "graphics/ui/elements/Button.hpp" diff --git a/src/logic/scripting/lua/libs/libhud.cpp b/src/logic/scripting/lua/libs/libhud.cpp index 90cb57d4..642121cf 100644 --- a/src/logic/scripting/lua/libs/libhud.cpp +++ b/src/logic/scripting/lua/libs/libhud.cpp @@ -3,7 +3,7 @@ #include "assets/Assets.hpp" #include "content/Content.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" #include "frontend/UiDocument.hpp" #include "frontend/hud.hpp" #include "graphics/ui/elements/InventoryView.hpp" diff --git a/src/logic/scripting/lua/libs/libinput.cpp b/src/logic/scripting/lua/libs/libinput.cpp index 2c79afaa..4aac2976 100644 --- a/src/logic/scripting/lua/libs/libinput.cpp +++ b/src/logic/scripting/lua/libs/libinput.cpp @@ -1,6 +1,6 @@ #include -#include "engine.hpp" +#include "engine/Engine.hpp" #include "files/files.hpp" #include "frontend/hud.hpp" #include "frontend/screens/Screen.hpp" diff --git a/src/logic/scripting/lua/libs/libnetwork.cpp b/src/logic/scripting/lua/libs/libnetwork.cpp index dc752710..0cf7e538 100644 --- a/src/logic/scripting/lua/libs/libnetwork.cpp +++ b/src/logic/scripting/lua/libs/libnetwork.cpp @@ -1,6 +1,6 @@ #include "api_lua.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" #include "network/Network.hpp" using namespace scripting; diff --git a/src/logic/scripting/lua/libs/libpack.cpp b/src/logic/scripting/lua/libs/libpack.cpp index fdd9ae8a..c436ec4e 100644 --- a/src/logic/scripting/lua/libs/libpack.cpp +++ b/src/logic/scripting/lua/libs/libpack.cpp @@ -5,7 +5,7 @@ #include "assets/AssetsLoader.hpp" #include "content/Content.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" #include "files/WorldFiles.hpp" #include "files/engine_paths.hpp" #include "world/Level.hpp" diff --git a/src/logic/scripting/lua/libs/libparticles.cpp b/src/logic/scripting/lua/libs/libparticles.cpp index ae2ed6d3..d3bccf76 100644 --- a/src/logic/scripting/lua/libs/libparticles.cpp +++ b/src/logic/scripting/lua/libs/libparticles.cpp @@ -5,7 +5,7 @@ #include "graphics/render/ParticlesRenderer.hpp" #include "graphics/render/Emitter.hpp" #include "assets/assets_util.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" using namespace scripting; diff --git a/src/logic/scripting/lua/libs/libtext3d.cpp b/src/logic/scripting/lua/libs/libtext3d.cpp index 433a959e..f334c85f 100644 --- a/src/logic/scripting/lua/libs/libtext3d.cpp +++ b/src/logic/scripting/lua/libs/libtext3d.cpp @@ -4,7 +4,7 @@ #include "graphics/render/WorldRenderer.hpp" #include "graphics/render/TextsRenderer.hpp" #include "graphics/render/TextNote.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" using namespace scripting; diff --git a/src/logic/scripting/lua/libs/libtime.cpp b/src/logic/scripting/lua/libs/libtime.cpp index 78952ede..988e403a 100644 --- a/src/logic/scripting/lua/libs/libtime.cpp +++ b/src/logic/scripting/lua/libs/libtime.cpp @@ -1,4 +1,4 @@ -#include "engine.hpp" +#include "engine/Engine.hpp" #include "api_lua.hpp" using namespace scripting; diff --git a/src/logic/scripting/lua/libs/libworld.cpp b/src/logic/scripting/lua/libs/libworld.cpp index fbb7763b..1acc1ad7 100644 --- a/src/logic/scripting/lua/libs/libworld.cpp +++ b/src/logic/scripting/lua/libs/libworld.cpp @@ -7,7 +7,7 @@ #include "coders/compression.hpp" #include "coders/gzip.hpp" #include "coders/json.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" #include "files/engine_paths.hpp" #include "files/files.hpp" #include "lighting/Lighting.hpp" diff --git a/src/logic/scripting/lua/lua_engine.cpp b/src/logic/scripting/lua/lua_engine.cpp index dca6ec69..e9b28ff6 100644 --- a/src/logic/scripting/lua/lua_engine.cpp +++ b/src/logic/scripting/lua/lua_engine.cpp @@ -9,7 +9,7 @@ #include "util/stringutil.hpp" #include "libs/api_lua.hpp" #include "lua_custom_types.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" static debug::Logger logger("lua-state"); static lua::State* main_thread = nullptr; diff --git a/src/logic/scripting/lua/usertypes/lua_type_heightmap.cpp b/src/logic/scripting/lua/usertypes/lua_type_heightmap.cpp index 67c32308..0db89634 100644 --- a/src/logic/scripting/lua/usertypes/lua_type_heightmap.cpp +++ b/src/logic/scripting/lua/usertypes/lua_type_heightmap.cpp @@ -12,7 +12,7 @@ #include "files/util.hpp" #include "graphics/core/ImageData.hpp" #include "maths/Heightmap.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" #include "../lua_util.hpp" using namespace lua; diff --git a/src/logic/scripting/scripting.cpp b/src/logic/scripting/scripting.cpp index 96e9f06e..9a6cc115 100644 --- a/src/logic/scripting/scripting.cpp +++ b/src/logic/scripting/scripting.cpp @@ -7,7 +7,7 @@ #include "content/Content.hpp" #include "content/ContentPack.hpp" #include "debug/Logger.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" #include "files/engine_paths.hpp" #include "files/files.hpp" #include "frontend/UiDocument.hpp" diff --git a/src/logic/scripting/scripting_hud.cpp b/src/logic/scripting/scripting_hud.cpp index 0ab5438d..75c063a4 100644 --- a/src/logic/scripting/scripting_hud.cpp +++ b/src/logic/scripting/scripting_hud.cpp @@ -1,7 +1,7 @@ #include "scripting_hud.hpp" #include "debug/Logger.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" #include "files/files.hpp" #include "frontend/hud.hpp" #include "graphics/render/WorldRenderer.hpp" diff --git a/src/logic/scripting/scripting_world_generation.cpp b/src/logic/scripting/scripting_world_generation.cpp index d24eec66..1169b64f 100644 --- a/src/logic/scripting/scripting_world_generation.cpp +++ b/src/logic/scripting/scripting_world_generation.cpp @@ -14,7 +14,7 @@ #include "world/generator/GeneratorDef.hpp" #include "util/timeutil.hpp" #include "files/files.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" #include "debug/Logger.hpp" using namespace lua; diff --git a/src/main.cpp b/src/main.cpp index b0d03412..c9732ca1 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,4 +1,4 @@ -#include "engine.hpp" +#include "engine/Engine.hpp" #include "util/platform.hpp" #include "util/command_line.hpp" #include "debug/Logger.hpp" diff --git a/src/objects/Entities.cpp b/src/objects/Entities.cpp index e047fdd4..441d340c 100644 --- a/src/objects/Entities.cpp +++ b/src/objects/Entities.cpp @@ -7,7 +7,7 @@ #include "content/Content.hpp" #include "data/dv_util.hpp" #include "debug/Logger.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" #include "graphics/core/DrawContext.hpp" #include "graphics/core/LineBatch.hpp" #include "graphics/commons/Model.hpp" diff --git a/src/util/command_line.cpp b/src/util/command_line.cpp index 25d7b554..483b0f8b 100644 --- a/src/util/command_line.cpp +++ b/src/util/command_line.cpp @@ -5,7 +5,7 @@ #include "files/engine_paths.hpp" #include "util/ArgsReader.hpp" -#include "engine.hpp" +#include "engine/Engine.hpp" namespace fs = std::filesystem; From 96577ee041789628caad458f7ab144c3c238da80 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Wed, 25 Dec 2024 14:08:22 +0300 Subject: [PATCH 12/12] add input.add_callback("key:...") support --- src/logic/scripting/lua/libs/libinput.cpp | 16 +++++++++++++++- src/util/RunnablesList.hpp | 17 +++++++++++++++++ src/window/Events.cpp | 12 +++++++++++- src/window/Events.hpp | 3 +++ 4 files changed, 46 insertions(+), 2 deletions(-) diff --git a/src/logic/scripting/lua/libs/libinput.cpp b/src/logic/scripting/lua/libs/libinput.cpp index 4aac2976..47233a49 100644 --- a/src/logic/scripting/lua/libs/libinput.cpp +++ b/src/logic/scripting/lua/libs/libinput.cpp @@ -30,7 +30,21 @@ static int l_mousecode(lua::State* L) { } static int l_add_callback(lua::State* L) { - auto bindname = lua::require_string(L, 1); + std::string bindname = lua::require_string(L, 1); + size_t pos = bindname.find(':'); + if (pos != std::string::npos) { + std::string prefix = bindname.substr(0, pos); + if (prefix == "key") { + if (hud == nullptr) { + throw std::runtime_error("on_hud_open is not called yet"); + } + auto key = input_util::keycode_from(bindname.substr(pos + 1)); + auto callback = lua::create_runnable(L); + hud->keepAlive(Events::keyCallbacks[key].add(callback)); + return 0; + } + } + const auto& bind = Events::bindings.find(bindname); if (bind == Events::bindings.end()) { throw std::runtime_error("unknown binding " + util::quote(bindname)); diff --git a/src/util/RunnablesList.hpp b/src/util/RunnablesList.hpp index e655b42c..c9771de3 100644 --- a/src/util/RunnablesList.hpp +++ b/src/util/RunnablesList.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -11,17 +12,33 @@ namespace util { class RunnablesList { int nextid = 1; std::unordered_map runnables; + std::mutex mutex; public: + RunnablesList() = default; + + RunnablesList(RunnablesList&& o) { + runnables = std::move(o.runnables); + nextid = o.nextid; + } + + void operator=(RunnablesList&& o) { + runnables = std::move(o.runnables); + nextid = o.nextid; + } + observer_handler add(runnable callback) { + std::lock_guard lock(mutex); int id = nextid++; runnables[id] = std::move(callback); return observer_handler(new int(id), [this](int* id) { //-V508 + std::lock_guard lock(mutex); runnables.erase(*id); delete id; }); } void notify() { + std::lock_guard lock(mutex); for (auto& entry : runnables) { entry.second(); } diff --git a/src/window/Events.cpp b/src/window/Events.cpp index f63431cf..1465b77b 100644 --- a/src/window/Events.cpp +++ b/src/window/Events.cpp @@ -23,6 +23,7 @@ bool Events::_cursor_locked = false; std::vector Events::codepoints; std::vector Events::pressedKeys; std::unordered_map Events::bindings; +std::unordered_map Events::keyCallbacks; bool Events::pressed(keycode keycode) { return pressed(static_cast(keycode)); @@ -156,6 +157,12 @@ bool Events::jactive(const std::string& name) { void Events::setKey(int key, bool b) { Events::keys[key] = b; Events::frames[key] = currentFrame; + if (b) { + const auto& callbacks = keyCallbacks.find(static_cast(key)); + if (callbacks != keyCallbacks.end()) { + callbacks->second.notify(); + } + } } void Events::setButton(int button, bool b) { @@ -173,6 +180,10 @@ void Events::setPosition(float xpos, float ypos) { Events::cursor.y = ypos; } +observer_handler Events::addKeyCallback(keycode key, runnable callback) { + return keyCallbacks[key].add(std::move(callback)); +} + #include "coders/json.hpp" #include "coders/toml.hpp" @@ -228,7 +239,6 @@ void Events::loadBindings( } else if (bindType == BindType::REBIND) { Events::rebind(key, type, code); } - } } } diff --git a/src/window/Events.hpp b/src/window/Events.hpp index 8155bb2b..e231462a 100644 --- a/src/window/Events.hpp +++ b/src/window/Events.hpp @@ -27,6 +27,7 @@ public: static std::vector codepoints; static std::vector pressedKeys; static std::unordered_map bindings; + static std::unordered_map keyCallbacks; static void pollEvents(); @@ -50,6 +51,8 @@ public: static bool active(const std::string& name); static bool jactive(const std::string& name); + static observer_handler addKeyCallback(keycode key, runnable callback); + static void setKey(int key, bool b); static void setButton(int button, bool b);