diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index 0f6c9c5b..9d8f65f9 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -25,7 +25,7 @@ jobs: # - macos-latest compiler: [ { cc: "gcc", cxx: "g++"}, - { cc: "clang", cxx: "clang++"} + { cc: "clang-19", cxx: "clang++-19"} ] build: - Release @@ -44,17 +44,17 @@ jobs: with: submodules: 'recursive' - - name: Install Ninja + - name: Install Ninja & Clang-19 run: | sudo apt update sudo apt install ninja-build -y + sudo apt install clang-19 -y - name: Install Dependencies run: | sudo apt update sudo apt install \ - lua5.3 liblua5.3-dev \ libglfw3 libglfw3-dev \ libglew-dev \ libglm-dev \ diff --git a/.gitmodules b/.gitmodules index 4e14bb77..81aeff00 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,9 +1,6 @@ [submodule "vendor/quill"] path = vendor/quill url = https://github.com/odygrd/quill.git -[submodule "vendor/sol2"] - path = vendor/sol2 - url = https://github.com/ThePhD/sol2.git [submodule "vendor/imgui"] path = vendor/imgui/imgui url = https://github.com/ocornut/imgui @@ -19,3 +16,6 @@ [submodule "vendor/whereami"] path = vendor/whereami url = https://github.com/gpakosz/whereami.git +[submodule "vendor/angelscript"] + path = vendor/angelscript + url = https://github.com/anjo76/angelscript.git diff --git a/CMakeLists.txt b/CMakeLists.txt index 0fce8114..a9851725 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10,23 +10,39 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON) # set the project name project(FunGame VERSION 0.1.0) +# AngelScript +file(GLOB ANGELSCRIPT_SOURCE "vendor/angelscript/sdk/angelscript/source/*.c*") +file(GLOB ANGELSCRIPT_SOURCE_STRING "vendor/angelscript/sdk/add_on/scriptstdstring/*.c*") +file(GLOB ANGELSCRIPT_SOURCE_ARRAY "vendor/angelscript/sdk/add_on/scriptarray/*.c*") +add_library(angelscript OBJECT ${ANGELSCRIPT_SOURCE} ${ANGELSCRIPT_SOURCE_STRING} ${ANGELSCRIPT_SOURCE_ARRAY}) +target_compile_definitions(angelscript PRIVATE "AS_USE_NAMESPACE") +target_compile_definitions(angelscript PRIVATE "AS_USE_STLNAMES") +target_include_directories(angelscript PRIVATE "vendor/angelscript/sdk/angelscript/include") + +# where am I +file(GLOB WHEREAMI_SOURCE "vendor/whereami/src/**") +add_library(whereami OBJECT ${WHEREAMI_SOURCE}) +target_include_directories(whereami PRIVATE "vendor/whereami/src") + +# ImGUI +file(GLOB IMGUI_SOURCES1 "vendor/imgui/imgui/*.c*") +file(GLOB IMGUI_SOURCES2 "vendor/imgui/imgui/backends/imgui_impl_opengl3.cpp") +file(GLOB IMGUI_SOURCES3 "vendor/imgui/imgui/backends/imgui_impl_glfw.cpp") +add_library(dear_imgui OBJECT ${IMGUI_SOURCES1} ${IMGUI_SOURCES2} ${IMGUI_SOURCES3}) +target_include_directories(dear_imgui PRIVATE "vendor/imgui/imgui") + # add the executable file(GLOB_RECURSE SOURCES1 "src/*.cpp") - -# this is one json file and whereami -file(GLOB SOURCES4 "vendor/whereami/src/*.c*") -file(GLOB SOURCES6 "vendor/imgui/imgui/*.c*") -file(GLOB SOURCES7 "vendor/imgui/imgui/backends/imgui_impl_opengl3.cpp") -file(GLOB SOURCES8 "vendor/imgui/imgui/backends/imgui_impl_glfw.cpp") -add_executable(FunGame ${SOURCES1} ${SOURCES4} ${SOURCES6} ${SOURCES7} ${SOURCES8}) +add_executable(FunGame ${SOURCES1}) # Set standard version set_property(TARGET FunGame PROPERTY CXX_STANDARD 23) set_property(TARGET FunGame PROPERTY C_STANDARD 17) +target_compile_definitions(FunGame PRIVATE "AS_USE_NAMESPACE") target_compile_definitions(FunGame PUBLIC GLM_ENABLE_EXPERIMENTAL) -# compile quill and sol2 +# compile quill block() set(QUILL_BUILD_EXAMPLES OFF) set(QUILL_BUILD_TESTS OFF) @@ -36,8 +52,6 @@ block() add_subdirectory("vendor/quill") endblock() -add_subdirectory("vendor/sol2") - add_subdirectory("vendor/glaze") add_subdirectory("vendor/argh") @@ -69,17 +83,13 @@ else() target_link_libraries(FunGame PRIVATE glm::glm) endif() -# Lua 5.2 just uses the name "Lua" while 5.1, and 5.0 used "Lua51", and "Lua50" -# respectivly. -find_package(Lua REQUIRED) - -include_directories(${LUA_INCLUDE_DIR}) # add quill and sol2 -target_link_libraries_system(FunGame PRIVATE quill::quill) +target_link_libraries(FunGame PRIVATE quill::quill) -target_link_libraries_system(FunGame PRIVATE sol2::sol2) -target_link_libraries(FunGame PRIVATE ${LUA_LIBRARIES}) +target_link_libraries(FunGame PRIVATE whereami) +target_link_libraries(FunGame PRIVATE dear_imgui) +target_link_libraries(FunGame PRIVATE angelscript) # Add include dirs target_include_directories(FunGame PRIVATE "vendor/whereami/src") @@ -88,6 +98,8 @@ target_include_directories(FunGame PRIVATE "vendor/thread-pool/include") target_include_directories(FunGame PRIVATE "vendor/glaze/include") target_include_directories(FunGame PRIVATE "vendor/imgui") target_include_directories(FunGame PRIVATE "vendor/imgui/imgui") +target_include_directories(FunGame PRIVATE "vendor/angelscript/sdk/angelscript/include") +target_include_directories(FunGame PRIVATE "vendor/angelscript/sdk/add_on/scriptstdstring") target_include_directories(FunGame PRIVATE "src") target_include_directories(FunGame PRIVATE "${PROJECT_BINARY_DIR}") @@ -139,9 +151,8 @@ add_test(NAME Logging COMMAND FunGame Test Logging) add_test(NAME ChunkDataTest COMMAND FunGame Test ChunkDataTest) add_test(NAME LoadManifest COMMAND FunGame Test LoadManifest) add_test(NAME PathFinderTest COMMAND FunGame Test PathFinderTest) -add_test(NAME LuaMap COMMAND FunGame Test Lua Map) -add_test(NAME LuaLogging COMMAND FunGame Test Lua Logging) -add_test(NAME LuaLoadTime COMMAND FunGame Test Lua LoadTime) -add_test(NAME LuaLoadScript COMMAND FunGame Test Lua LoadScript) -add_test(NAME LuaTransferScript COMMAND FunGame Test Lua TransferScript) +add_test(NAME AngelScriptNap COMMAND FunGame Test AngelScript Map) +add_test(NAME AngelScriptLogging COMMAND FunGame Test AngelScript Logging) +add_test(NAME AngelScriptLoadTime COMMAND FunGame Test AngelScript LoadTime) +add_test(NAME AngelScriptLoadScript COMMAND FunGame Test AngelScript LoadScript) add_test(NAME EngineTest COMMAND FunGame Test EngineTest) diff --git a/README.md b/README.md index 28ac4335..d29f6265 100644 --- a/README.md +++ b/README.md @@ -15,8 +15,7 @@ pacman -Su \ mingw-w64-x86_64-ninja \ mingw-w64-x86_64-glew \ mingw-w64-x86_64-glfw \ - mingw-w64-x86_64-glm \ - mingw-w64-x86_64-lua # not 100% sure this is the right lua version + mingw-w64-x86_64-glm ``` ## Building diff --git a/TODO.txt b/TODO.txt index 323842eb..a2e8e818 100644 --- a/TODO.txt +++ b/TODO.txt @@ -18,3 +18,5 @@ GUI make trees function like entities # here same shader etc +Generally fix TODOs in the code +Want to get the correct module name for as code, and make sure modules can communicate with needed. diff --git a/data/Base/biome_data.json b/data/Base/biome_data.json index d21b9a3c..a096dab1 100644 --- a/data/Base/biome_data.json +++ b/data/Base/biome_data.json @@ -1,5 +1,5 @@ { - "map_generator_path": "./biome_map.lua", + "map_generator_path": "./biome_map.as", "image_path": "path/to/image", "description": "This is a test biome", "name": "Base", @@ -730,7 +730,7 @@ { "identification": "base/Flower_Test", "map_name": "Flower_1", - "map_generator_path": "biome_map.lua" + "map_generator_path": "biome_map.as" } ] } \ No newline at end of file diff --git a/data/Base/biome_map.as b/data/Base/biome_map.as new file mode 100644 index 00000000..60afe402 --- /dev/null +++ b/data/Base/biome_map.as @@ -0,0 +1,78 @@ +// Biome map files must define a function that returns a structure with a "map". +// The map function is called from c++ and reads the x and y lengths. Using this +// information the "map" key of the returned structure can be used as if it were +// a 2D array. + +// Anyway, do something like this and it should work as long as there are +// correctly defined tile types and tile macros. + +// Base = Base or {} +// Base.biome_map = Base.biome_map or {} + +// Base.biome_map.spacing = .8 + +namespace Base { + +namespace biomes { + +class biome_map { + + TerrainGeneration::FractalNoise noise; + TerrainGeneration::AlternativeWorleyNoise flower_noise; + float spacing; + + biome_map() { + noise = TerrainGeneration::FractalNoise(4, 0.6, 3); + flower_noise = TerrainGeneration::AlternativeWorleyNoise(32, 0.5, 32); + spacing = 0.8; + } + + int sample(int x, int y) { + // sample noise and set a value + float height = 12.0 * noise.sample(float(x) * spacing, float(y) * spacing) - 4.0; + // each value must be integers. math.floor changes doubles to ints + int height_map_value = int(height) ; + // This biome only defines tile types between 0, and 6 + if (height_map_value > 6) { + height_map_value = 6; + } + else if (height_map_value < 0) { + height_map_value = 0; + } + return height_map_value; + } + + // Maps for trees and bushes + // name should be used in json file + float sample_plants(string plant_id, int x, int y) { + if (plant_id == "Trees_1") { + int height = sample(x, y); + if (height == 1) { + return 0.1; + } + else { + return 0.0; + } + } + else if (plant_id == "Flower_1") { + int flower_height = int(flower_noise.sample(x * 4, y * 4)); + if (flower_height > 0) { + return 0.10; + } + else { + return 0.0; + } + } + else { + return 0.0; + } + } +} + +} + +} + +void do_something() { + Base::biomes::biome_map@ map = Base::biomes::biome_map(); +} diff --git a/data/Base/biomes/Test_Biome.json b/data/Base/biomes/Test_Biome.json index 0ec7d5f5..f1bc59ee 100644 --- a/data/Base/biomes/Test_Biome.json +++ b/data/Base/biomes/Test_Biome.json @@ -1,5 +1,5 @@ { - "map_generator_path": "../biome_map.lua", + "map_generator_path": "../biome_map.as", "image_path": "path/to/image", "description": "This is a test biome", "name": "Base", @@ -730,7 +730,7 @@ { "identification": "base/Flower_Test", "map_name": "Flower_1", - "map_generator_path": "../biome_map.lua" + "map_generator_path": "../biome_map.as" } ] } \ No newline at end of file diff --git a/data/Base/models/Test_Entity/Test.json b/data/Base/models/Test_Entity/Test.json index 79c5ac91..5295b6bd 100644 --- a/data/Base/models/Test_Entity/Test.json +++ b/data/Base/models/Test_Entity/Test.json @@ -17,5 +17,5 @@ } ], "listeners":"", - "ai":"ai.lua" + "ai":"ai.as" } diff --git a/data/Base/models/Test_Entity/ai.lua b/data/Base/models/Test_Entity/ai.lua index dab82bc4..c07d2ef8 100644 --- a/data/Base/models/Test_Entity/ai.lua +++ b/data/Base/models/Test_Entity/ai.lua @@ -1,3 +1,5 @@ +-- Leaving this one for now because I need it to chang to as + Base = Base or {} Base.entities = Base.entities or {} Base.entities.Test_Entity = Base.entities.Test_Entity or {} diff --git a/resources/as/test.as b/resources/as/test.as new file mode 100644 index 00000000..07784379 --- /dev/null +++ b/resources/as/test.as @@ -0,0 +1,34 @@ +void test1() { + int x = 5; + return; +} + +int test2() { + int x = 1 * 2 * 3 * 4 * 5 * 6; + if (x % 2 == 0) { + return 2; + } + return 1; +} + +int test3() { + LOGGING::LOG_BACKTRACE("Backtrace log 1"); + LOGGING::LOG_BACKTRACE("Backtrace log 2"); + + LOGGING::LOG_INFO("Welcome to AngelScript!"); + LOGGING::LOG_ERROR("An error message. error code 123"); + LOGGING::LOG_WARNING("A warning message."); + LOGGING::LOG_CRITICAL("A critical error."); + LOGGING::LOG_DEBUG("Debugging foo 1234"); + + return 0; +} + +bool is_prime(int N) { + for (int x = 2; x * x < N; x++) { + if (N % x == 0) { + return false; + } + } + return true; +} diff --git a/resources/lua/is_prime_test.lua b/resources/lua/is_prime_test.lua deleted file mode 100644 index 2d5e4f26..00000000 --- a/resources/lua/is_prime_test.lua +++ /dev/null @@ -1,14 +0,0 @@ -tests = tests or {} - -function tests.is_prime(N) - for x = 2, N^(1/2) do - if N % x == 0 then - return 0 - end - return 1 - end -end - -__ = {} -__.tests = tests -return __ diff --git a/resources/lua/logging.lua b/resources/lua/logging.lua deleted file mode 100644 index 9117312f..00000000 --- a/resources/lua/logging.lua +++ /dev/null @@ -1,58 +0,0 @@ -Logging = Logging or {} - -function Logging.LOG_BACKTRACE(message) - local info = debug.getinfo(2) - if info == nil then - lua_log_backtrace("Invoked from c++", -1, message) - else - local filename = info.source:match("^.+/(.+)$") - lua_log_backtrace(filename, info.currentline, message) - end -end - -function Logging.LOG_INFO(message) - local info = debug.getinfo(2) - if info == nil then - lua_log_info("Invoked from c++", -1, message) - else - local filename = info.source:match("^.+/(.+)$") - lua_log_info(filename, info.currentline, message) - end -end - -function Logging.LOG_DEBUG(message) - local info = debug.getinfo(2) - if info == nil then - lua_log_debug("Invoked from c++", -1, message) - else - local filename = info.source:match("^.+/(.+)$") - lua_log_debug(filename, info.currentline, message) - end -end - -function Logging.LOG_WARNING(message) - local info = debug.getinfo(2) - if info == nil then - lua_log_warning("Invoked from c++", -1, message) - else - local filename = info.source:match("^.+/(.+)$") - lua_log_warning(filename, info.currentline, message) - end -end - -function Logging.LOG_CRITICAL(message) - - local info = debug.getinfo(2) - if info == nil then - lua_log_critical("Invoked from c++", -1, message) - else - local filename = info.source:match("^.+/(.+)$") - lua_log_critical(filename, info.currentline, message) - end -end - -Logging.LOG_BACKTRACE("Finished lua logging initialization.") - -__ = {} -__.Logging = Logging -return __ \ No newline at end of file diff --git a/src/exceptions.hpp b/src/exceptions.hpp index 7e9993df..1d1e217e 100644 --- a/src/exceptions.hpp +++ b/src/exceptions.hpp @@ -18,8 +18,8 @@ class file_not_found_error : public std::runtime_error { file_not_found_error(const file_not_found_error& other) noexcept = default; - file_not_found_error& operator=(const file_not_found_error& other - ) noexcept = default; + file_not_found_error& + operator=(const file_not_found_error& other) noexcept = default; [[nodiscard]] virtual inline const std::filesystem::path path() const noexcept { @@ -35,8 +35,8 @@ class not_implemented_error : public std::logic_error { not_implemented_error(const not_implemented_error& other) noexcept = default; - not_implemented_error& operator=(const not_implemented_error& other - ) noexcept = default; + not_implemented_error& + operator=(const not_implemented_error& other) noexcept = default; }; } // namespace exc diff --git a/src/global_context.cpp b/src/global_context.cpp index 5d824e71..f23ec5b2 100644 --- a/src/global_context.cpp +++ b/src/global_context.cpp @@ -2,6 +2,34 @@ #include "local_context.hpp" #include "logging.hpp" +#include "scriptstdstring.h" +#include "util/angel_script/as_logging.hpp" +#include "util/angel_script/error_checks.hpp" +#include "util/files.hpp" +#include "world/terrain/generation/interface.hpp" + +// Implement a simple message callback function +void +MessageCallback(const AngelScript::asSMessageInfo* msg, void* param) { + if (msg->type == AngelScript::asMSGTYPE_ERROR) { + LOG_ERROR( + logging::script_logger, "[ {} :({}, {}) ] - {}", msg->section, msg->row, + msg->col, msg->message + ); + } else if (msg->type == AngelScript::asMSGTYPE_WARNING) { + LOG_WARNING( + logging::script_logger, "[ {} :({}, {}) ] - {}", msg->section, msg->row, + msg->col, msg->message + ); + } else if (msg->type == AngelScript::asMSGTYPE_INFORMATION) { + LOG_INFO( + logging::script_logger, "[ {} :({}, {}) ] - {}", msg->section, msg->row, + msg->col, msg->message + ); + } else { + LOG_ERROR(logging::script_logger, "Unknown message type."); + } +} void GlobalContext::run_opengl_queue() { @@ -26,80 +54,84 @@ GlobalContext::run_opengl_queue() { } GlobalContext::GlobalContext() : - thread_pool_([] { quill::detail::set_thread_name("BS Thread"); }) {} - -std::optional -GlobalContext::get_from_lua(const std::string& command) { - LOG_BACKTRACE(logging::lua_logger, "Attempting to index {}.", command); - - std::stringstream command_stream(command); - - std::string key; - - std::getline(command_stream, key, '\\'); - - auto raw_result = lua_.get>(key); - - if (!raw_result) { - LOG_BACKTRACE(logging::lua_logger, "{} not valid.", key); - return {}; + thread_pool_([] { quill::detail::set_thread_name("BS Thread"); }) { + AngelScript::asPrepareMultithread(); + engine_ = AngelScript::asCreateScriptEngine(); + int r = engine_->SetMessageCallback( + AngelScript::asFUNCTION(MessageCallback), 0, AngelScript::asCALL_CDECL + ); + if (r < 0) { + LOG_ERROR(logging::as_logger, "Could not set Message Callback."); } + RegisterStdString(engine_); + terrain::generation::init_as_interface(engine_); + util::scripting::init_as_interface(engine_); +} - sol::table result; - - while (std::getline(command_stream, key, '\\')) { - if (!raw_result->is()) { - LOG_BACKTRACE(logging::lua_logger, "{} not index of table.", key); - return {}; - } - result = raw_result.value(); - - if (!result.valid()) { - LOG_BACKTRACE(logging::lua_logger, "Could not find {}.", key); - return {}; - } +GlobalContext::~GlobalContext() { + engine_->ShutDownAndRelease(); +} - if (result == sol::lua_nil) { - LOG_BACKTRACE( - logging::lua_logger, "Attempting to index {}. nil value at {}.", - command, key - ); - return {}; - } +AngelScript::asERetCodes +GlobalContext::load_file(const std::string& mod_name, std::filesystem::path path) { + AngelScript::asIScriptModule* mod; + if (mod = engine_->GetModule(mod_name.c_str(), AngelScript::asGM_ONLY_IF_EXISTS)) { + LOG_BACKTRACE( + logging::as_logger, "Loading file from \"{}\" into module \"{}\".", + path.lexically_normal().string(), mod_name + ); + } else if (mod = engine_->GetModule( + mod_name.c_str(), AngelScript::asGM_CREATE_IF_NOT_EXISTS + )) { + LOG_BACKTRACE( + logging::as_logger, "Creating module \"{}\" from file \"{}\".", mod_name, + path.lexically_normal().string() + ); + } else { + LOG_ERROR( + logging::as_logger, "Could not find or create module \"{}\".", mod_name + ); + return AngelScript::asERetCodes::asERROR; + } - if (!result.is()) { - LOG_BACKTRACE( - logging::lua_logger, "Attempting to index {}. {} not index of table.", - command, key - ); - return {}; - } + std::ostringstream script; + auto file = files::open_file(path); + if (!file) { + LOG_ERROR(logging::as_logger, "Could not open file."); + return AngelScript::asERetCodes::asERROR; + } - raw_result = result.get>(key); + script << file.value().rdbuf(); + mod->AddScriptSection(path.filename().c_str(), script.str().c_str()); - if (!raw_result) { - LOG_BACKTRACE(logging::lua_logger, "{} not valid.", key); - return {}; - } + int result = mod->Build(); + if (util::scripting::check_ScriptModule_Build(result)) { + return static_cast(result); } - - // a sol object - return raw_result.value(); + return AngelScript::asERetCodes::asSUCCESS; } -void -GlobalContext::load_script_file(const std::filesystem::path& path) { - if (!std::filesystem::exists(path)) { - LOG_WARNING(logging::file_io_logger, "File {} does not exists.", path); - return; +AngelScript::asIScriptFunction* +GlobalContext::get_function( + const std::string& module, std::string function_signature +) const { + // check that the module exists. + AngelScript::asIScriptModule* mod; + if ((mod = engine_->GetModule(module.c_str())) == nullptr) { + return nullptr; } - // i think you also want this on the result valid but it might not matter - std::scoped_lock lock(global_lua_mutex_); - auto result = lua_.safe_script_file(path.lexically_normal().string()); + AngelScript::asIScriptFunction* function = + mod->GetFunctionByDecl(function_signature.c_str()); + return function; +} - if (!result.valid()) { - sol::error err = result; // who designed this? - std::string what = err.what(); - LOG_ERROR(logging::lua_logger, "{}", what); +AngelScript::asITypeInfo* +GlobalContext::get_type(const std::string& module, std::string type_signature) const { + // check that the module exists. + AngelScript::asIScriptModule* mod; + if ((mod = engine_->GetModule(module.c_str())) == nullptr) { + return nullptr; } + AngelScript::asITypeInfo* type = mod->GetTypeInfoByDecl(type_signature.c_str()); + return type; } diff --git a/src/global_context.hpp b/src/global_context.hpp index fdd9ba29..0afd2ae9 100644 --- a/src/global_context.hpp +++ b/src/global_context.hpp @@ -26,8 +26,8 @@ #include "logging.hpp" #define BS_THREAD_POOL_ENABLE_PRIORITY +#include #include -#include #include #include @@ -53,9 +53,9 @@ class GlobalContext { std::mutex opengl_queue_mutex; - sol::state lua_; + AngelScript::asIScriptEngine* engine_; - std::mutex global_lua_mutex_; + // std::mutex global_as_mutex_; #if DEBUG() @@ -74,6 +74,8 @@ class GlobalContext { void operator=(GlobalContext&&) = delete; void operator=(GlobalContext const&) = delete; + ~GlobalContext(); + inline void set_main_thread() { #if DEBUG() @@ -101,9 +103,15 @@ class GlobalContext { return obj; } - // this must be run before exit if lua has been initialized on thread local - // - inline void close_threads() { + /** + * @brief Close all threads in thread pool. + * + * @details This function will close the threads in the thread pool. This + * may be necessary if things allocated in thread local memory need to be + * deallocated before things on the main thread are deallocated. + */ + inline void + close_threads() { thread_pool_.reset(0); } @@ -133,7 +141,7 @@ class GlobalContext { * @param BS::priority_t priority = BS::pr::normal */ template >> - auto + [[nodiscard]] auto submit_task(F&& function, BS::priority_t priority = BS::pr::normal) { return thread_pool_.submit_task(function, priority); } @@ -148,14 +156,27 @@ class GlobalContext { } // Might want to expose these in the future. - auto + [[nodiscard]] auto wait_for_tasks() { return thread_pool_.wait(); } // oh boy time to start wrapping tread_pool - void load_script_file(const std::filesystem::path& path); + [[nodiscard]] auto + as_engine() { + return engine_; + } + + // load as script file + [[nodiscard]] AngelScript::asERetCodes + load_file(const std::string& module, std::filesystem::path path); + + // get function from module + [[nodiscard]] AngelScript::asIScriptFunction* + get_function(const std::string& module, std::string function) const; - std::optional get_from_lua(const std::string& command); + // get type from module + [[nodiscard]] AngelScript::asITypeInfo* + get_type(const std::string& module, std::string type_signature) const; }; diff --git a/src/gui/gui_logging.hpp b/src/gui/gui_logging.hpp index 265fe5d9..b2416bf1 100644 --- a/src/gui/gui_logging.hpp +++ b/src/gui/gui_logging.hpp @@ -28,9 +28,9 @@ #include #include +#include #include #include -#include namespace gui { diff --git a/src/gui/render/gpu_data/frame_buffer.cpp b/src/gui/render/gpu_data/frame_buffer.cpp index 0c8b2d39..0c80292d 100644 --- a/src/gui/render/gpu_data/frame_buffer.cpp +++ b/src/gui/render/gpu_data/frame_buffer.cpp @@ -11,9 +11,7 @@ namespace gpu_data { FrameBufferBase::FrameBufferBase( screen_size_t width, screen_size_t height, FrameBufferSettings settings -) : - width_(width), - height_(height), settings_(settings) { +) : width_(width), height_(height), settings_(settings) { // frame buffer (the container for the other two) // ----------------- glGenFramebuffers(1, &frame_buffer); @@ -22,15 +20,17 @@ FrameBufferBase::FrameBufferBase( FrameBuffer::FrameBuffer( screen_size_t width, screen_size_t height, FrameBufferSettings settings -) : - FrameBufferBase(width, height, settings) { - connect_depth_texture(std::make_shared( - width_, height_, - TextureSettings{ - .internal_format = GPUPixelStorageFormat::DEPTH, - .read_format = GPUPixelReadFormat::DEPTH_COMPONENT}, - false - )); +) : FrameBufferBase(width, height, settings) { + connect_depth_texture( + std::make_shared( + width_, height_, + TextureSettings{ + .internal_format = GPUPixelStorageFormat::DEPTH, + .read_format = GPUPixelReadFormat::DEPTH_COMPONENT + }, + false + ) + ); connect_render_texture( std::make_shared( width_, height_, diff --git a/src/gui/render/gpu_data/frame_buffer_multisample.cpp b/src/gui/render/gpu_data/frame_buffer_multisample.cpp index 52fcea94..3aeabfe4 100644 --- a/src/gui/render/gpu_data/frame_buffer_multisample.cpp +++ b/src/gui/render/gpu_data/frame_buffer_multisample.cpp @@ -11,22 +11,25 @@ namespace gpu_data { FrameBufferMultisample::FrameBufferMultisample( screen_size_t width, screen_size_t height, FrameBufferSettings settings -) : - FrameBufferBase(width, height, settings) { - connect_depth_texture(std::make_shared( - width_, height_, - RenderBufferSettings{ - .samples = settings_.samples, - .multisample = settings_.samples > 1, - .internal_format = GPUPixelStorageFormat::DEPTH} - )); +) : FrameBufferBase(width, height, settings) { + connect_depth_texture( + std::make_shared( + width_, height_, + RenderBufferSettings{ + .samples = settings_.samples, + .multisample = settings_.samples > 1, + .internal_format = GPUPixelStorageFormat::DEPTH + } + ) + ); connect_render_texture( std::make_shared( width_, height_, TextureSettings{ .samples = settings.samples, .multisample = (settings_.samples > 1), - .internal_format = GPUPixelStorageFormat::RGB8}, + .internal_format = GPUPixelStorageFormat::RGB8 + }, false ), 0 diff --git a/src/gui/render/gpu_data/render_buffer.hpp b/src/gui/render/gpu_data/render_buffer.hpp index e74f5c99..5519c155 100644 --- a/src/gui/render/gpu_data/render_buffer.hpp +++ b/src/gui/render/gpu_data/render_buffer.hpp @@ -28,8 +28,7 @@ class RenderBuffer : virtual public GPUDataRenderBuffer { inline RenderBuffer( screen_size_t width, screen_size_t height, RenderBufferSettings settings - ) : - RenderBuffer(settings) { + ) : RenderBuffer(settings) { bind(); if (settings_.multisample) { glRenderbufferStorageMultisample( diff --git a/src/gui/render/gpu_data/shadow_map.cpp b/src/gui/render/gpu_data/shadow_map.cpp index a46dca73..c79349b2 100644 --- a/src/gui/render/gpu_data/shadow_map.cpp +++ b/src/gui/render/gpu_data/shadow_map.cpp @@ -23,7 +23,8 @@ ShadowMap::ShadowMap(screen_size_t w, screen_size_t h, FrameBufferSettings setti .internal_format = GPUPixelStorageFormat::DEPTH_16, .read_format = GPUPixelReadFormat::DEPTH_COMPONENT, .type = GPUPixelType::HALF_FLOAT, - .min_filter = GL_LINEAR}; + .min_filter = GL_LINEAR + }; connect_depth_texture( std::make_shared(width_, height_, depth_texture_settings, false) diff --git a/src/gui/render/gpu_data/texture.cpp b/src/gui/render/gpu_data/texture.cpp index 21822536..c2323d9f 100644 --- a/src/gui/render/gpu_data/texture.cpp +++ b/src/gui/render/gpu_data/texture.cpp @@ -119,8 +119,7 @@ Texture2D::setup(std::shared_ptr image) { Texture2D::Texture2D( screen_size_t width, screen_size_t height, TextureSettings settings, bool differed -) : - width_(width), height_(height), settings_(settings) { +) : width_(width), height_(height), settings_(settings) { if (differed) { GlobalContext& context = GlobalContext::instance(); context.push_opengl_task([this]() { setup(nullptr); }); @@ -131,8 +130,7 @@ Texture2D::Texture2D( Texture2D::Texture2D( std::shared_ptr image, TextureSettings settings, bool differed -) : - settings_(settings) { +) : settings_(settings) { if (!image) { return; } diff --git a/src/gui/render/gpu_data/vertex_buffer_object.hpp b/src/gui/render/gpu_data/vertex_buffer_object.hpp index 1eca07f2..0d717316 100644 --- a/src/gui/render/gpu_data/vertex_buffer_object.hpp +++ b/src/gui/render/gpu_data/vertex_buffer_object.hpp @@ -69,9 +69,8 @@ struct GPUStructureType { uint8_t major_size_, uint8_t minor_size_, uint8_t type_size, bool is_int, GPUArayType draw_type ) : - major_size(major_size_), - minor_size(minor_size_), type_size(type_size), is_int(is_int), - draw_type(draw_type) {} + major_size(major_size_), minor_size(minor_size_), type_size(type_size), + is_int(is_int), draw_type(draw_type) {} template < uint8_t major_size_T, uint8_t minor_size_T, uint8_t type_size_T, bool is_int_T, diff --git a/src/gui/render/graphics_shaders/program_handler.cpp b/src/gui/render/graphics_shaders/program_handler.cpp index dcd4235b..e8fc137d 100644 --- a/src/gui/render/graphics_shaders/program_handler.cpp +++ b/src/gui/render/graphics_shaders/program_handler.cpp @@ -170,23 +170,28 @@ Program::get_status_string() const { "OK", "This program and its corresponding shaders have compiled successfully. If " "there is still some error check that Uniforms and Locations are set " - "correctly."}; + "correctly." + }; static std::pair linking_failed_string = { "Linking Failed", "There is an error when connecting different shader types together. Check that " - "the inputs and output between shaders align."}; + "the inputs and output between shaders align." + }; static std::pair invalid_shader_string = { "Shader Failed", "Error compiling constituent shader(s). Check the log file " - "for more information."}; + "for more information." + }; static std::pair empty_program_string = { - "No Program; Reload", "Program has not been loaded. Click the reload button."}; + "No Program; Reload", "Program has not been loaded. Click the reload button." + }; static std::pair other_string = { "This should not happen", - "This is a bug that should be reported to the developers."}; + "This is a bug that should be reported to the developers." + }; switch (status_) { case ProgramStatus::OK: diff --git a/src/gui/render/graphics_shaders/program_handler.hpp b/src/gui/render/graphics_shaders/program_handler.hpp index 5d379676..efb5bb6e 100644 --- a/src/gui/render/graphics_shaders/program_handler.hpp +++ b/src/gui/render/graphics_shaders/program_handler.hpp @@ -498,7 +498,7 @@ class ShaderHandler { /** * @brief construct a new ShaderHandler */ - inline ShaderHandler(){}; + inline ShaderHandler() {}; inline ~ShaderHandler() {} }; diff --git a/src/gui/render/graphics_shaders/shader_program.cpp b/src/gui/render/graphics_shaders/shader_program.cpp index 7ab7778b..41974494 100644 --- a/src/gui/render/graphics_shaders/shader_program.cpp +++ b/src/gui/render/graphics_shaders/shader_program.cpp @@ -259,7 +259,8 @@ ShaderProgram_MultiElements::render( GL_TRIANGLES, // mode mesh->get_num_vertices().data(), // count static_cast(element_type), // type - reinterpret_cast(mesh->get_elements_position().data() + reinterpret_cast( + mesh->get_elements_position().data() ), // indices mesh->get_num_objects(), // drawcount mesh->get_base_vertex().data() diff --git a/src/gui/render/graphics_shaders/shader_program.hpp b/src/gui/render/graphics_shaders/shader_program.hpp index ef5f8cde..cb7ae074 100644 --- a/src/gui/render/graphics_shaders/shader_program.hpp +++ b/src/gui/render/graphics_shaders/shader_program.hpp @@ -113,9 +113,7 @@ class Render_Base { public: inline Render_Base( shader::Program& shader_program, const std::function setup_commands - ) : - opengl_program_(shader_program), - setup_(setup_commands) { + ) : opengl_program_(shader_program), setup_(setup_commands) { LOG_DEBUG( logging::opengl_logger, "Program ID: {}, Name: {}", opengl_program_.get_program_ID(), opengl_program_.get_name() @@ -143,8 +141,7 @@ class ShaderProgram_Standard : inline ShaderProgram_Standard( shader::Program& shader_program, const std::function setup_commands - ) : - Render_Base(shader_program, setup_commands) {} + ) : Render_Base(shader_program, setup_commands) {} inline virtual ~ShaderProgram_Standard() {} @@ -165,8 +162,7 @@ class ShaderProgram_Elements : inline ShaderProgram_Elements( shader::Program& shader_program, const std::function setup_commands - ) : - Render_Base(shader_program, setup_commands) {} + ) : Render_Base(shader_program, setup_commands) {} inline virtual ~ShaderProgram_Elements() {} @@ -187,8 +183,7 @@ class ShaderProgram_Instanced : inline ShaderProgram_Instanced( shader::Program& shader_program, const std::function setup_commands - ) : - Render_Base(shader_program, setup_commands) {} + ) : Render_Base(shader_program, setup_commands) {} inline virtual ~ShaderProgram_Instanced() {} @@ -209,8 +204,7 @@ class ShaderProgram_ElementsInstanced : inline ShaderProgram_ElementsInstanced( shader::Program& shader_program, const std::function setup_commands - ) : - Render_Base(shader_program, setup_commands) {} + ) : Render_Base(shader_program, setup_commands) {} inline virtual ~ShaderProgram_ElementsInstanced() {} @@ -231,8 +225,7 @@ class ShaderProgram_MultiElements : inline ShaderProgram_MultiElements( shader::Program& shader_program, const std::function setup_commands - ) : - Render_Base(shader_program, setup_commands) {} + ) : Render_Base(shader_program, setup_commands) {} inline virtual ~ShaderProgram_MultiElements() {} diff --git a/src/gui/render/structures/floating_instanced_i_mesh.cpp b/src/gui/render/structures/floating_instanced_i_mesh.cpp index 168364e0..e5a4719d 100644 --- a/src/gui/render/structures/floating_instanced_i_mesh.cpp +++ b/src/gui/render/structures/floating_instanced_i_mesh.cpp @@ -15,9 +15,7 @@ namespace gpu_data { FloatingInstancedIMeshGPU::FloatingInstancedIMeshGPU( const util::Mesh& mesh, const std::vector& model_transforms -) : - IMeshGPU(mesh, false), - transforms_array_(model_transforms, 1) { +) : IMeshGPU(mesh, false), transforms_array_(model_transforms, 1) { // InstancedInt does not have a color texture. One must inherit from this // class and define a method that creates a color texture, and sets its id // as color_texture_. diff --git a/src/gui/render/structures/floating_instanced_i_mesh.hpp b/src/gui/render/structures/floating_instanced_i_mesh.hpp index 09a6f3a4..e6c87b0e 100644 --- a/src/gui/render/structures/floating_instanced_i_mesh.hpp +++ b/src/gui/render/structures/floating_instanced_i_mesh.hpp @@ -54,10 +54,10 @@ class FloatingInstancedIMeshGPU : inline FloatingInstancedIMeshGPU(const FloatingInstancedIMeshGPU& obj) = delete; inline FloatingInstancedIMeshGPU(FloatingInstancedIMeshGPU&& other) = default; // copy operator - inline FloatingInstancedIMeshGPU& operator=(const FloatingInstancedIMeshGPU& obj - ) = delete; - inline FloatingInstancedIMeshGPU& operator=(FloatingInstancedIMeshGPU&& other - ) = default; + inline FloatingInstancedIMeshGPU& + operator=(const FloatingInstancedIMeshGPU& obj) = delete; + inline FloatingInstancedIMeshGPU& + operator=(FloatingInstancedIMeshGPU&& other) = default; inline FloatingInstancedIMeshGPU(const util::Mesh& mesh) : FloatingInstancedIMeshGPU(mesh, {}) {} diff --git a/src/gui/render/structures/instanced_i_mesh.cpp b/src/gui/render/structures/instanced_i_mesh.cpp index 2bd435ce..52bdc1a0 100644 --- a/src/gui/render/structures/instanced_i_mesh.cpp +++ b/src/gui/render/structures/instanced_i_mesh.cpp @@ -16,8 +16,8 @@ namespace gpu_data { InstancedIMeshGPU::InstancedIMeshGPU( const util::Mesh& mesh, const std::vector& model_transforms ) : - IMeshGPU(mesh, false), - transforms_array_(model_transforms, 1), num_models_(model_transforms.size()) { + IMeshGPU(mesh, false), transforms_array_(model_transforms, 1), + num_models_(model_transforms.size()) { // InstancedInt does not have a color texture. One must inherit from this // class and define a method that creates a color texture, and sets its id // as color_texture_. diff --git a/src/gui/render/structures/model.hpp b/src/gui/render/structures/model.hpp index ecc8c466..517e34bf 100644 --- a/src/gui/render/structures/model.hpp +++ b/src/gui/render/structures/model.hpp @@ -95,7 +95,7 @@ class ModelController : virtual public gui::gpu_data::GPUDataElementsInstanced { model_mesh_(std::move(other.model_mesh_)), model_textures_(std::move(other.model_textures_)), texture_id_(std::move(other.texture_id_)), - placements_(std::move(other.placements_)), offset_(std::move(other.offset_)){}; + placements_(std::move(other.placements_)), offset_(std::move(other.offset_)) {}; // copy operator inline ModelController& operator=(const ModelController& obj) = delete; ModelController& operator=(ModelController&& other) = default; diff --git a/src/gui/render/structures/static_mesh.hpp b/src/gui/render/structures/static_mesh.hpp index ae50a62d..4d8a7ccf 100644 --- a/src/gui/render/structures/static_mesh.hpp +++ b/src/gui/render/structures/static_mesh.hpp @@ -44,8 +44,7 @@ class StaticMesh : public virtual InstancedIMeshGPU { inline StaticMesh( const util::Mesh& mesh, const std::vector& model_transforms - ) : - InstancedIMeshGPU(mesh, model_transforms) {} + ) : InstancedIMeshGPU(mesh, model_transforms) {} inline virtual ~StaticMesh() {} diff --git a/src/gui/render/structures/terrain_mesh.cpp b/src/gui/render/structures/terrain_mesh.cpp index 0555eca8..d1977664 100644 --- a/src/gui/render/structures/terrain_mesh.cpp +++ b/src/gui/render/structures/terrain_mesh.cpp @@ -6,7 +6,8 @@ namespace gpu_data { namespace detail { -coalesced_data::coalesced_data(const std::unordered_map mesh_map +coalesced_data::coalesced_data( + const std::unordered_map mesh_map ) { size_t total_size = 0; size_t total_elements_size = 0; diff --git a/src/gui/render/structures/terrain_mesh.hpp b/src/gui/render/structures/terrain_mesh.hpp index c16d1f98..b1134069 100644 --- a/src/gui/render/structures/terrain_mesh.hpp +++ b/src/gui/render/structures/terrain_mesh.hpp @@ -177,10 +177,10 @@ class TerrainMesh : public virtual IMeshMultiGPU { public: inline TerrainMesh() : - color_texture_(terrain::TerrainColorMapping::get_color_texture()){}; + color_texture_(terrain::TerrainColorMapping::get_color_texture()) {}; inline TerrainMesh(Texture1D& color_texture_id) : - color_texture_(color_texture_id){}; + color_texture_(color_texture_id) {}; inline TerrainMesh( const std::unordered_map mesh_map, diff --git a/src/gui/render/structures/uniform_types.hpp b/src/gui/render/structures/uniform_types.hpp index 7eb6dfc0..a1a006b0 100644 --- a/src/gui/render/structures/uniform_types.hpp +++ b/src/gui/render/structures/uniform_types.hpp @@ -18,7 +18,7 @@ namespace render { class LightEnvironment { private: public: - virtual ~LightEnvironment(){}; + virtual ~LightEnvironment() {}; virtual glm::vec3 get_light_direction() const = 0; virtual glm::vec3 get_diffuse_light() const = 0; @@ -27,7 +27,7 @@ class LightEnvironment { class StarRotation { public: - virtual ~StarRotation(){}; + virtual ~StarRotation() {}; virtual glm::mat4 get_sky_rotation() const = 0; }; @@ -39,7 +39,7 @@ class LightDirection : public shader::UniformExecutor { LightDirection(std::shared_ptr lighting) : UniformExecutor(gpu_data::GPUArayType::FLOAT_VEC3), lighting_(lighting) {} - virtual ~LightDirection(){}; + virtual ~LightDirection() {}; virtual void bind(GLint uniform_ID) const override { @@ -66,7 +66,7 @@ class DiffuseLight : public shader::UniformExecutor { DiffuseLight(std::shared_ptr lighting) : UniformExecutor(gpu_data::GPUArayType::FLOAT_VEC3), lighting_(lighting) {} - virtual ~DiffuseLight(){}; + virtual ~DiffuseLight() {}; virtual void bind(GLint uniform_ID) const override { @@ -93,7 +93,7 @@ class SpectralLight : public shader::UniformExecutor { SpectralLight(std::shared_ptr lighting) : UniformExecutor(gpu_data::GPUArayType::FLOAT_VEC3), lighting_(lighting) {} - virtual ~SpectralLight(){}; + virtual ~SpectralLight() {}; inline virtual void bind(GLint uniform_ID) const override { @@ -117,7 +117,7 @@ class MatrixViewProjection : public shader::UniformExecutor { MatrixViewProjection(std::shared_ptr controller) : UniformExecutor(gpu_data::GPUArayType::FLOAT_MAT4), controller_(controller) {} - virtual ~MatrixViewProjection(){}; + virtual ~MatrixViewProjection() {}; inline virtual void bind(GLint uniform_ID) const override { @@ -141,7 +141,7 @@ class ViewMatrix : public shader::UniformExecutor { ViewMatrix(std::shared_ptr controller) : UniformExecutor(gpu_data::GPUArayType::FLOAT_MAT4), controller_(controller) {} - virtual ~ViewMatrix(){}; + virtual ~ViewMatrix() {}; inline virtual void bind(GLint uniform_ID) const override { diff --git a/src/gui/scene/scene.hpp b/src/gui/scene/scene.hpp index 5a5fc16f..7700f90f 100644 --- a/src/gui/scene/scene.hpp +++ b/src/gui/scene/scene.hpp @@ -204,7 +204,8 @@ class Scene { * @param render object that can render to a framebuffer. */ inline void - add_background_ground_renderer(const std::shared_ptr render + add_background_ground_renderer( + const std::shared_ptr render ) { background_frame_buffer_.push_back(render); } diff --git a/src/gui/ui/imgui_gui.cpp b/src/gui/ui/imgui_gui.cpp index 5ce2dc92..f9690f97 100644 --- a/src/gui/ui/imgui_gui.cpp +++ b/src/gui/ui/imgui_gui.cpp @@ -83,8 +83,9 @@ imgui_entry(GLFWwindow* window, world::World& world, world::Climate& climate) { std::shared_ptr controller = std::make_shared(key_mapping); scene::InputHandler::set_window(window); - scene::InputHandler::forward_inputs_to(static_pointer_cast(controller - )); + scene::InputHandler::forward_inputs_to( + static_pointer_cast(controller) + ); // Setup Platform/Renderer backends ImGui_ImplGlfw_InitForOpenGL(window, true); @@ -146,7 +147,8 @@ imgui_entry(GLFWwindow* window, world::World& world, world::Climate& climate) { // 2. Show a simple window that we create ourselves. We use a Begin/End pair to // create a named window. { - ImGui::Begin("Hello, world!" + ImGui::Begin( + "Hello, world!" ); // Create a window called "Hello, world!" and append into it. if (scene::InputHandler::escape()) { @@ -156,7 +158,8 @@ imgui_entry(GLFWwindow* window, world::World& world, world::Climate& climate) { scene::InputHandler::clear_escape(); } - ImGui::Text("This is some useful text." + ImGui::Text( + "This is some useful text." ); // Display some text (you can use a format strings too) ImGui::Checkbox("Position Window", &show_position_window); ImGui::Checkbox("Show Light Controls", &show_light_controls); diff --git a/src/gui/ui/imgui_windows.cpp b/src/gui/ui/imgui_windows.cpp index a713db5e..198529bc 100644 --- a/src/gui/ui/imgui_windows.cpp +++ b/src/gui/ui/imgui_windows.cpp @@ -108,7 +108,8 @@ display_data(const manifest::ObjectHandler& object_handler, bool& show) { for (auto& [id, object] : object_handler) { // Display a data item - ImGui::PushID(std::hash{}(id) + ImGui::PushID( + std::hash{}(id) ); // maybe not grate to call hashes like this ImGui::TableNextRow(); ImGui::TableNextColumn(); diff --git a/src/gui/ui/scene_setup.cpp b/src/gui/ui/scene_setup.cpp index 13d50f15..80eb9f16 100644 --- a/src/gui/ui/scene_setup.cpp +++ b/src/gui/ui/scene_setup.cpp @@ -295,7 +295,8 @@ setup( star_pipeline->data.push_back(star_data); sun_pipeline->data.push_back(star_shape); - terrain_mesh->set_shadow_texture(scene.get_shadow_map().get_depth_buffer()->value() + terrain_mesh->set_shadow_texture( + scene.get_shadow_map().get_depth_buffer()->value() ); chunks_render_pipeline->data.push_back(terrain_mesh.get()); chunks_shadow_pipeline->data.push_back(terrain_mesh.get()); @@ -306,7 +307,8 @@ setup( render_programs_t object_render_programs{ .entity_render_program = entity_render_pipeline, - .tile_object_render_program = tile_entity_render_pipeline}; + .tile_object_render_program = tile_entity_render_pipeline + }; // attach the world objects to the render program for (auto& [id, object] : *world.get_object_handler()) { diff --git a/src/local_context.cpp b/src/local_context.cpp index 807c2abf..1bf7f5ae 100644 --- a/src/local_context.cpp +++ b/src/local_context.cpp @@ -1,18 +1,13 @@ #include "local_context.hpp" #include "global_context.hpp" -#include "util/lua/lua_logging.hpp" -#include "world/terrain/generation/lua_interface.hpp" -// #include +LocalContext::LocalContext() : + context_(GlobalContext::instance().as_engine()->CreateContext()) {} -LocalContext::LocalContext() { - lua_state.open_libraries(sol::lib::base); - lua_state.open_libraries(sol::lib::math); - lua_state.open_libraries(sol::lib::string); - lua_state.open_libraries(sol::lib::debug); - lua_logging::setup_lua_logging(lua_state); - terrain::generation::init_lua_interface(lua_state); +LocalContext::~LocalContext() { + context_->Release(); + AngelScript::asThreadCleanup(); } LocalContext& @@ -20,206 +15,3 @@ LocalContext::instance() { static thread_local LocalContext local_ctx; return local_ctx; } - -std::optional -LocalContext::get_from_this_lua_state(const std::string& command) { - LOG_BACKTRACE(logging::lua_logger, "Attempting to index {}.", command); - sol::state& lua = get_lua_state(); - - std::stringstream command_stream(command); - - std::string key; - - std::getline(command_stream, key, '\\'); - - auto raw_result = lua.get>(key); - - if (!raw_result) { - LOG_BACKTRACE(logging::lua_logger, "{} not valid.", key); - return {}; - } - - sol::table result; - - while (std::getline(command_stream, key, '\\')) { - if (!raw_result->is()) { - LOG_BACKTRACE(logging::lua_logger, "{} not index of table.", key); - return {}; - } - result = raw_result.value(); - - if (!result.valid()) { - LOG_BACKTRACE(logging::lua_logger, "Could not find {}.", key); - return {}; - } - - if (result == sol::lua_nil) { - LOG_BACKTRACE( - logging::lua_logger, "Attempting to index {}. nil value at {}.", - command, key - ); - return {}; - } - - if (!result.is()) { - LOG_BACKTRACE( - logging::lua_logger, "Attempting to index {}. {} not index of table.", - command, key - ); - return {}; - } - - raw_result = result.get>(key); - - if (!raw_result) { - LOG_BACKTRACE(logging::lua_logger, "{} not valid.", key); - return {}; - } - LOG_BACKTRACE(logging::lua_logger, "{} valid.", key); - } - - // a sol object - return raw_result.value(); -} - -void -LocalContext::set_to_this_lua_state( - const std::string& command, const sol::object& object -) { - if (command.length() == 0) { - LOG_WARNING(logging::lua_logger, "Cannot set table with no name."); - return; - } - LOG_BACKTRACE(logging::lua_logger, "Attempting to index {}.", command); - sol::state& lua = get_lua_state(); - - std::stringstream command_stream(command); - std::string key; - - sol::optional raw_result; - - while (std::getline(command_stream, key, '\\')) { - LOG_BACKTRACE(logging::lua_logger, "Locking up {}.", key); - // if last part of command - if (command_stream.tellg() == -1) { - if (raw_result) { - if (raw_result->is()) { - sol::table result = raw_result.value(); - result.set(key, object); - } else { - LOG_ERROR(logging::lua_logger, "Object at {} is not a table.", key); - } - - } else { - lua.set(key, object); - } - continue; - // will return here - } - if (raw_result) { - if (raw_result->is()) { - sol::table result = raw_result.value(); - raw_result = result.get>(key); - if (!raw_result) { - result.set(key, lua.create_table()); - raw_result = result.get>(key); - } - } else { - LOG_ERROR(logging::lua_logger, "Object at {} is not a table.", key); - } - } else { - raw_result = lua.get>(key); - if (!raw_result) { - lua.set(key, lua.create_table()); - raw_result = lua.get>(key); - } - } - if (!raw_result) { - LOG_ERROR(logging::lua_logger, "Could not find key {}", key); - return; - } - } -} - -bool -LocalContext::load_into_this_lua_state(const std::string& command) { - GlobalContext& context = GlobalContext::instance(); - std::optional object_result = context.get_from_lua(command); - - if (!object_result) { - LOG_WARNING(logging::lua_logger, "Command {} not found.", command); - return false; - } - - sol::object object_this_state = copy(lua_state, object_result.value()); - -#if DEBUG() - if (object_this_state.is()) { - sol::table table_copy = object_this_state; - - for (auto& [key, value] : table_copy) { - LOG_DEBUG(logging::lua_logger, "key: {}", key.as()); - } - } -#endif - - set_to_this_lua_state(command, object_this_state); - return true; -} - -sol::object -LocalContext::copy(sol::state& lua_state, const sol::object& object) { - sol::type type = object.get_type(); - switch (type) { - case sol::type::number: - { - double number = object.as(); - return sol::make_object(lua_state, number); - } - case sol::type::string: - { - std::string string = object.as(); - return sol::make_object(lua_state, string); - } - case sol::type::boolean: - { - bool b = object.as(); - return sol::make_object(lua_state, b); - } - case sol::type::table: - { - sol::table table = object.as(); - sol::table table_copy = lua_state.create_table(); - for (auto& [key, value] : table) { - table_copy.set(copy(lua_state, key), copy(lua_state, value)); - } - return table_copy; - } - case sol::type::function: - { - sol::protected_function funct = object.as(); - sol::bytecode target_bc = funct.dump(); - auto result = lua_state.load(target_bc.as_string_view()); - sol::protected_function loaded_function = result; - return loaded_function; - } - case sol::type::lua_nil: - case sol::type::none: - return {}; - default: - return {}; - } -} - -std::optional -LocalContext::get_from_lua(const std::string& command) { - std::optional in_this_state = get_from_this_lua_state(command); - if (in_this_state) { - return in_this_state; - } - bool load_secsess = load_into_this_lua_state(command); - if (!load_secsess) { - return {}; - } - return get_from_this_lua_state(command); -} diff --git a/src/local_context.hpp b/src/local_context.hpp index 292bb3ce..3518db5a 100644 --- a/src/local_context.hpp +++ b/src/local_context.hpp @@ -18,35 +18,269 @@ * * @brief Defines Local Context class * - * @details Creates a local Lua environment. Helpfull for multithreading. + * @details Creates a local environment. Helpfull for multithreading. * * @ingroup -- */ #pragma once -#include +#include +#include + +#include class LocalContext { private: LocalContext(); - sol::state lua_state; - sol::object copy(sol::state& lua, const sol::object& object); + AngelScript::asIScriptContext* context_; + + // Return values + // asSUCCESS Success + // asCONTEXT_NOT_PREPARED The context is not in prepared state. + // asINVALID_ARG The arg is larger than the number of arguments in the + // prepared function. asINVALID_TYPE The argument is not an object or + // handle. + inline AngelScript::asERetCodes + set_arg(size_t i, bool arg) { + return static_cast(context_->SetArgByte(i, arg)); + } + + inline AngelScript::asERetCodes + set_arg(size_t i, int8_t arg) { + return static_cast(context_->SetArgByte(i, arg)); + } + + inline AngelScript::asERetCodes + set_arg(size_t i, uint8_t arg) { + return static_cast(context_->SetArgByte(i, arg)); + } + + inline AngelScript::asERetCodes + set_arg(size_t i, int16_t arg) { + return static_cast(context_->SetArgWord(i, arg)); + } + + inline AngelScript::asERetCodes + set_arg(size_t i, uint16_t arg) { + return static_cast(context_->SetArgWord(i, arg)); + } + + inline AngelScript::asERetCodes + set_arg(size_t i, int32_t arg) { + return static_cast(context_->SetArgDWord(i, arg)); + } + + inline AngelScript::asERetCodes + set_arg(size_t i, uint32_t arg) { + return static_cast(context_->SetArgDWord(i, arg)); + } + + inline AngelScript::asERetCodes + set_arg(size_t i, int64_t arg) { + return static_cast(context_->SetArgQWord(i, arg)); + } + + inline AngelScript::asERetCodes + set_arg(size_t i, uint64_t arg) { + return static_cast(context_->SetArgQWord(i, arg)); + } + + inline AngelScript::asERetCodes + set_arg(size_t i, float arg) { + return static_cast(context_->SetArgFloat(i, arg)); + } + + inline AngelScript::asERetCodes + set_arg(size_t i, double arg) { + return static_cast(context_->SetArgDouble(i, arg)); + } + + inline AngelScript::asERetCodes + set_arg(size_t i, void* arg) { + return static_cast(context_->SetArgObject(i, arg)); + } + + inline AngelScript::asERetCodes + set_arg(size_t i, std::string& arg) { + return static_cast(context_->SetArgObject(i, &arg)); + } + + template + inline AngelScript::asERetCodes + set_all_args(const size_t i, const A&& a) { + AngelScript::asERetCodes result = set_arg(i, a); + if (result != AngelScript::asERetCodes::asSUCCESS) { + LOG_ERROR( + logging::main_logger, "An error occurred {} at parameter {}", + std::to_underlying(result), i + ); + } + return result; + } + + template + inline AngelScript::asERetCodes + set_all_args(const size_t i, const A&& a, const Args&&... args) { + AngelScript::asERetCodes result = set_arg(i, a); + if (result != AngelScript::asERetCodes::asSUCCESS) { + LOG_ERROR( + logging::main_logger, "An error occurred {} at parameter {}", + std::to_underlying(result), i + ); + return result; + } + return set_all_args(i + 1, std::forward(args)...); + } public: [[nodiscard]] static LocalContext& instance(); + ~LocalContext(); + + template + inline std::expected + run_function(AngelScript::asIScriptFunction* function, const Args&&... args) { + AngelScript::asEContextState result = + static_cast(context_->Prepare(function)); + if (result != AngelScript::asEContextState::asEXECUTION_FINISHED) { + return std::unexpected(result); + } + if constexpr (sizeof...(args) != 0) { + AngelScript::asERetCodes args_result = + set_all_args(0, std::forward(args)...); + if (args_result != AngelScript::asERetCodes::asSUCCESS) { + LOG_WARNING( + logging::as_logger, "Setting script arguments did not secseed." + ); + return std::unexpected(AngelScript::asEContextState::asEXECUTION_ERROR); + } + } + + result = static_cast(context_->Execute()); - [[nodiscard]] inline sol::state& - get_lua_state() { - return lua_state; + if (result != AngelScript::asEContextState::asEXECUTION_FINISHED) { + return std::unexpected(result); + } + + if constexpr (std::is_same::value) { + return nullptr; + } + + AngelScript::asEContextState error; + if constexpr (std::is_pointer::value) { + void* pointer = context_->GetReturnObject(); + if (pointer) { + T object = *static_cast(pointer); + return object; + } + error = AngelScript::asEContextState::asEXECUTION_ERROR; + } else { + T out; + error = get_return_value(out); + if (error == AngelScript::asEContextState::asEXECUTION_FINISHED) { + return out; + } + } + return std::unexpected(error); } - std::optional get_from_this_lua_state(const std::string& command); + // this might crash. should probably do some tests + AngelScript::asIScriptObject* + get_return_object() const { + auto out = context_->GetAddressOfReturnValue(); + if (out == nullptr) { + return nullptr; + } + return *(AngelScript::asIScriptObject**)out; + } - void set_to_this_lua_state(const std::string& command, const sol::object& object); + template + inline std::expected + run_method( + AngelScript::asIScriptObject* object, AngelScript::asIScriptFunction* function, + const Args&&... args + ) { + AngelScript::asEContextState result = + static_cast(context_->Prepare(function)); + if (result != AngelScript::asEContextState::asEXECUTION_FINISHED) { + return std::unexpected(result); + } + result = static_cast(context_->SetObject(object)); + if (result != AngelScript::asEContextState::asEXECUTION_FINISHED) { + return std::unexpected(result); + } + if constexpr (sizeof...(args) != 0) { + AngelScript::asERetCodes args_result = + set_all_args(0, std::forward(args)...); + if (args_result != AngelScript::asERetCodes::asSUCCESS) { + LOG_WARNING( + logging::as_logger, "Setting script arguments did not secseed." + ); + return std::unexpected(AngelScript::asEContextState::asEXECUTION_ERROR); + } + } - bool load_into_this_lua_state(const std::string& command); + result = static_cast(context_->Execute()); - std::optional get_from_lua(const std::string& command); + if (result != AngelScript::asEContextState::asEXECUTION_FINISHED) { + return std::unexpected(result); + } + + if constexpr (std::is_same::value) { + return nullptr; + } + + AngelScript::asEContextState error; + if constexpr (std::is_pointer::value) { + void* pointer = context_->GetReturnObject(); + if (pointer) { + T object_out = *static_cast(pointer); + return object_out; + } + error = AngelScript::asEContextState::asEXECUTION_ERROR; + } else { + T out; + error = get_return_value(out); + if (error == AngelScript::asEContextState::asEXECUTION_FINISHED) { + return out; + } + } + return std::unexpected(error); + } + + AngelScript::asEContextState + get_return_value(int& value) { + AngelScript::asEContextState state = context_->GetState(); + if (state != AngelScript::asEContextState::asEXECUTION_FINISHED) { + return state; + } + value = context_->GetReturnDWord(); + return AngelScript::asEContextState::asEXECUTION_FINISHED; + } + + AngelScript::asEContextState + get_return_value(bool& value) { + AngelScript::asEContextState state = context_->GetState(); + if (state != AngelScript::asEContextState::asEXECUTION_FINISHED) { + return state; + } + value = context_->GetReturnByte(); + return AngelScript::asEContextState::asEXECUTION_FINISHED; + } + + AngelScript::asEContextState + get_return_value(float& value) { + AngelScript::asEContextState state = context_->GetState(); + if (state != AngelScript::asEContextState::asEXECUTION_FINISHED) { + return state; + } + value = context_->GetReturnFloat(); + return AngelScript::asEContextState::asEXECUTION_FINISHED; + } + + inline int + get_line_number(int stack_level, int* column, const char** section_name) const { + return context_->GetLineNumber(stack_level, column, section_name); + } }; diff --git a/src/logging.cpp b/src/logging.cpp index 275a0c99..87c901db 100644 --- a/src/logging.cpp +++ b/src/logging.cpp @@ -29,11 +29,11 @@ static const std::string LOGLINE_FORMAT = #if defined(__CYGWIN__) || defined(__MINGW32__) || defined(__MINGW64__) \ || defined(QUILL_NO_THREAD_NAME_SUPPORT) -static const std::string LOGLINE_FORMAT_LUA = +static const std::string LOGLINE_FORMAT_SCRIPT = "%(time) [%(thread_id:>6)] %(log_level:<10) [%(logger:<10)] " "%(message)"; #else -static const std::string LOGLINE_FORMAT_LUA = +static const std::string LOGLINE_FORMAT_SCRIPT = "%(time) [%(thread_id:>6):%(thread_name:<16)] %(log_level:<10) " "[%(logger:<10)] %(message)"; @@ -46,14 +46,14 @@ using cc = quill::ConsoleColours; LogLevel _LOG_LEVEL; -quill::Logger* main_logger; // for everything else -quill::Logger* opengl_logger; // for glfw, glew etc -quill::Logger* terrain_logger; // for terrain, chunk, tile class -quill::Logger* game_map_logger; // for terrain generation -quill::Logger* voxel_logger; // for voxel logic like mesh creation -quill::Logger* file_io_logger; // for file io -quill::Logger* lua_logger; // for lua -quill::Logger* lua_script_logger; // for lua +quill::Logger* main_logger; // for everything else +quill::Logger* opengl_logger; // for glfw, glew etc +quill::Logger* terrain_logger; // for terrain, chunk, tile class +quill::Logger* game_map_logger; // for terrain generation +quill::Logger* voxel_logger; // for voxel logic like mesh creation +quill::Logger* file_io_logger; // for file io +quill::Logger* as_logger; // for AngelScript +quill::Logger* script_logger; // for scripts const static std::filesystem::path LOG_FILE = files::get_log_path() / "app.log"; @@ -115,6 +115,7 @@ init(bool console, quill::LogLevel log_level) { #endif // create all loggers + // clang-format off main_logger = quill::Frontend::create_or_get_logger("main", file_sink, LOGLINE_FORMAT); opengl_logger = @@ -127,10 +128,11 @@ init(bool console, quill::LogLevel log_level) { quill::Frontend::create_or_get_logger("voxel", file_sink, LOGLINE_FORMAT); file_io_logger = quill::Frontend::create_or_get_logger("file_io", file_sink, LOGLINE_FORMAT); - lua_logger = - quill::Frontend::create_or_get_logger("lua", file_sink, LOGLINE_FORMAT); - lua_script_logger = - quill::Frontend::create_or_get_logger("script", file_sink, LOGLINE_FORMAT_LUA); + as_logger = + quill::Frontend::create_or_get_logger("as", file_sink, LOGLINE_FORMAT); + script_logger = + quill::Frontend::create_or_get_logger("script", file_sink, LOGLINE_FORMAT_SCRIPT); + // clang-format on main_logger->set_log_level(_LOG_LEVEL); opengl_logger->set_log_level(_LOG_LEVEL); @@ -138,8 +140,8 @@ init(bool console, quill::LogLevel log_level) { game_map_logger->set_log_level(_LOG_LEVEL); voxel_logger->set_log_level(_LOG_LEVEL); file_io_logger->set_log_level(_LOG_LEVEL); - lua_logger->set_log_level(_LOG_LEVEL); - lua_script_logger->set_log_level(_LOG_LEVEL); + as_logger->set_log_level(_LOG_LEVEL); + script_logger->set_log_level(_LOG_LEVEL); // initialize backtrace on all loggers // is there a better way? @@ -149,8 +151,8 @@ init(bool console, quill::LogLevel log_level) { game_map_logger->init_backtrace(5, quill::LogLevel::Error); voxel_logger->init_backtrace(5, quill::LogLevel::Error); file_io_logger->init_backtrace(5, quill::LogLevel::Error); - lua_logger->init_backtrace(5, quill::LogLevel::Error); - lua_script_logger->init_backtrace(5, quill::LogLevel::Error); + as_logger->init_backtrace(5, quill::LogLevel::Error); + script_logger->init_backtrace(5, quill::LogLevel::Error); LOG_INFO(main_logger, "Logging initialized!"); } diff --git a/src/logging.hpp b/src/logging.hpp index eb2ee2f8..eb83bacd 100644 --- a/src/logging.hpp +++ b/src/logging.hpp @@ -24,14 +24,14 @@ static constexpr quill::LogLevel DEFAULT_LOG_LEVEL = quill::LogLevel::Info; extern quill::LogLevel _LOG_LEVEL; -extern quill::Logger* main_logger; // for general logging -extern quill::Logger* opengl_logger; // for glfw, glew etc -extern quill::Logger* terrain_logger; // for terrain, chunk, tile class -extern quill::Logger* game_map_logger; // for terrain generation -extern quill::Logger* voxel_logger; // for voxel logic like mesh creation -extern quill::Logger* file_io_logger; // for file io -extern quill::Logger* lua_logger; // for lua logging -extern quill::Logger* lua_script_logger; // for lua logging +extern quill::Logger* main_logger; // for general logging +extern quill::Logger* opengl_logger; // for glfw, glew etc +extern quill::Logger* terrain_logger; // for terrain, chunk, tile class +extern quill::Logger* game_map_logger; // for terrain generation +extern quill::Logger* voxel_logger; // for voxel logic like mesh creation +extern quill::Logger* file_io_logger; // for file io +extern quill::Logger* as_logger; // for as logging +extern quill::Logger* script_logger; // for script logging inline void set_thread_name(std::string name) { @@ -52,8 +52,8 @@ flush() { game_map_logger->flush_log(); voxel_logger->flush_log(); file_io_logger->flush_log(); - lua_logger->flush_log(); - lua_script_logger->flush_log(); + as_logger->flush_log(); + script_logger->flush_log(); } } // namespace logging diff --git a/src/main.cpp b/src/main.cpp index c030092c..6edfe72c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,21 +1,13 @@ #include "config.h" #include "graphics_main.hpp" -#include "gui/render/graphics_shaders/program_handler.hpp" -#include "gui/scene/controls.hpp" #include "gui/tests.hpp" -#include "gui/ui/gui_test.hpp" #include "gui/ui/imgui_gui.hpp" -#include "gui/ui/opengl_gui.hpp" -#include "local_context.hpp" #include "logging.hpp" #include "manifest/object_handler.hpp" +#include "util/angel_script/as_tests.hpp" #include "util/files.hpp" -#include "util/lua/lua_logging.hpp" -#include "util/lua/lua_tests.hpp" -#include "util/mesh.hpp" #include "util/png_image.hpp" #include "util/time.hpp" -#include "util/voxel_io.hpp" #include "world/biome.hpp" #include "world/terrain/generation/terrain_map.hpp" #include "world/terrain/terrain.hpp" @@ -39,7 +31,6 @@ #include #include -#include #include #include @@ -402,14 +393,14 @@ LogTest() { }); LOG_INFO( - logging::lua_script_logger, - "Using Lua logger. The lua logger should not log the cpp " - "file, but instead the lua file." + logging::script_logger, + "Using script logger. The script logger should not log the cpp " + "file, but instead the script file." ); LOG_INFO( - logging::lua_script_logger, - "[{}.lua:{}] - This is what a lua log should look like.", "example_file", 37 + logging::script_logger, + "[{}.as:{}] - This is what a script log should look like.", "example_file", 37 ); future.wait(); @@ -418,19 +409,23 @@ LogTest() { } int -lua_tests(const argh::parser& cmdl) { +as_tests(const argh::parser& cmdl) { + if (cmdl.size() < 3) { + return util::scripting::test(); + } + std::string run_function = cmdl(3).str(); if (run_function == "Map") { return MacroMap(cmdl); } else if (run_function == "Logging") { - return util::lua_tests::lua_log_test(); + return util::scripting::logging_test(); } else if (run_function == "LoadTime") { - return util::lua_tests::lua_loadtime_test(); + return util::scripting::as_loadtime_test(); + } else if (run_function == "Threading") { + return util::scripting::as_threading(); } else if (run_function == "LoadScript") { - return util::lua_tests::lua_load_tests(); - } else if (run_function == "TransferScript") { - return util::lua_tests::lua_transfertime_test(); + return util::scripting::as_load_tests(); } else { std::cout << "No known command" << std::endl; return 1; @@ -467,8 +462,8 @@ tests(const argh::parser& cmdl) { return object_handler.load_all_manifests(); } else if (run_function == "EngineTest") { return gui::opengl_tests(); - } else if (run_function == "Lua") { - return lua_tests(cmdl); + } else if (run_function == "AngelScript") { + return as_tests(cmdl); } else { std::cout << "No known command" << std::endl; return 1; @@ -486,7 +481,6 @@ main(int argc, char** argv) { "-c", "--console" // Enable console logging }); cmdl.add_param("biome-name"); - // cmdl.add_param("materials"); materials should be dictated by biome cmdl.add_params({"--imgui", "-g"}); // int seed for generation @@ -509,7 +503,7 @@ main(int argc, char** argv) { LOG_INFO(logger, "FunGame v{}.{}.{}", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH); LOG_INFO(logger, "Running from {}.", files::get_root_path().string()); - // main thread for opengl and lua loading + // main thread for opengl and script loading GlobalContext& context = GlobalContext::instance(); context.set_main_thread(); diff --git a/src/manifest/manifest.hpp b/src/manifest/manifest.hpp index c0458eda..07f50ec0 100644 --- a/src/manifest/manifest.hpp +++ b/src/manifest/manifest.hpp @@ -31,7 +31,8 @@ struct manifest_t { } // namespace manifest template <> -inline glz::detail::any_t::operator std::vector() const { +inline glz::detail::any_t:: +operator std::vector() const { assert(false && "Not Implemented"); return {}; } diff --git a/src/manifest/object_handler.cpp b/src/manifest/object_handler.cpp index 7e79953c..3ac5ded1 100644 --- a/src/manifest/object_handler.cpp +++ b/src/manifest/object_handler.cpp @@ -31,9 +31,10 @@ ObjectHandler::read_biome(const descriptor_t& biome_descriptor) { std::filesystem::path path_copy = biome_descriptor.path; - context.load_script_file( - files::get_data_path() / path_copy.remove_filename() - / biome_data->map_generator_path + // TODO just need to know what module to load this into + context.load_file( + "Base", files::get_data_path() / path_copy.remove_filename() + / biome_data->map_generator_path ); } diff --git a/src/manifest/object_handler.hpp b/src/manifest/object_handler.hpp index d59e29c0..9fedd01d 100644 --- a/src/manifest/object_handler.hpp +++ b/src/manifest/object_handler.hpp @@ -156,9 +156,9 @@ class ObjectHandler { for (const auto& directory_entry : std::filesystem::directory_iterator(manifest_folder)) { - auto manifest_opt = - files::read_json_from_file(directory_entry.path() - ); + auto manifest_opt = files::read_json_from_file( + directory_entry.path() + ); if (!manifest_opt) { if constexpr (opengl) { @@ -184,6 +184,7 @@ class ObjectHandler { // iterate through objects in manifest and queue them to be loaded for (const manifest::descriptor_t& entity_data : *manifest.entities) { auto future = context.submit_task([this, entity_data]() { + // manifest.name int result = read_object(entity_data); return result; }); diff --git a/src/util/angel_script/as_logging.cpp b/src/util/angel_script/as_logging.cpp new file mode 100644 index 00000000..2f771c01 --- /dev/null +++ b/src/util/angel_script/as_logging.cpp @@ -0,0 +1,197 @@ +#include "error_checks.hpp" +#include "local_context.hpp" +#include "logging.hpp" + +#include + +#include + +namespace util { +namespace scripting { + +namespace { + +struct script_location_t { + std::string file; + int line; + int column; +}; + +script_location_t +get_script_location() { + script_location_t location_data; + AngelScript::asIScriptContext* context = AngelScript::asGetActiveContext(); + if (context == nullptr) { + location_data.file = "Invoked from c++"; + location_data.line = -1; + } else { + char* section_name; + location_data.line = context->GetLineNumber( + 0, &location_data.column, const_cast(§ion_name) + ); + if (section_name == nullptr) { + location_data.file = "Unknown"; + } else { + location_data.file = std::string(section_name); + } + } + return location_data; +} + +/** + * @brief Backtrace Log API + * + * @param std::string message message to be logged + * + * @details Given a message this will log it to the log file. This function will + * determine the AngelScript line and file from the calling context. + */ +void +as_log_backtrace(std::string message) { + script_location_t location = get_script_location(); + LOG_BACKTRACE( + logging::script_logger, "[{:<18}] - {}", + fmtquill::format("{}:{}", location.file, location.line), message + ); +} + +/** + * @brief Info Log API + * + * @param std::string message message to be logged + * + * @details Given a message this will log it to the log file. This function will + * determine the AngelScript line and file from the calling context. + */ +void +as_log_info(std::string message) { + script_location_t location = get_script_location(); + LOG_INFO( + logging::script_logger, "[{:<18}] - {}", + fmtquill::format("{}:{}", location.file, location.line), message + ); +} + +/** + * @brief Debug Log API + * + * @param std::string message message to be logged + * + * @details Given a message this will log it to the log file. This function will + * determine the AngelScript line and file from the calling context. + */ +void +as_log_debug(std::string message) { + script_location_t location = get_script_location(); + LOG_DEBUG( + logging::script_logger, "[{:<18}] - {}", + fmtquill::format("{}:{}", location.file, location.line), message + ); +} + +/** + * @brief Warning Log API + * + * @param std::string message message to be logged + * + * @details Given a message this will log it to the log file. This function will + * determine the AngelScript line and file from the calling context. + */ +void +as_log_warning(std::string message) { + script_location_t location = get_script_location(); + LOG_WARNING( + logging::script_logger, "[{:<18}] - {}", + fmtquill::format("{}:{}", location.file, location.line), message + ); +} + +/** + * @brief Error Log API + * + * @param std::string message message to be logged + * + * @details Given a message this will log it to the log file. This function will + * determine the AngelScript line and file from the calling context. + */ +void +as_log_error(std::string message) { + script_location_t location = get_script_location(); + LOG_ERROR( + logging::script_logger, "[{:<18}] - {}", + fmtquill::format("{}:{}", location.file, location.line), message + ); +} + +/** + * @brief Critical Log API + * + * @param std::string message message to be logged + * + * @details Given a message this will log it to the log file. This function will + * determine the AngelScript line and file from the calling context. + */ +void +as_log_critical(std::string message) { + script_location_t location = get_script_location(); + LOG_CRITICAL( + logging::script_logger, "[{:<18}] - {}", + fmtquill::format("{}:{}", location.file, location.line), message + ); +} + +} // namespace + +void +init_as_interface(AngelScript::asIScriptEngine* engine) { + int r = engine->SetDefaultNamespace("LOGGING"); + if (util::scripting::check_SetDefaultNamespace(r)) { + return; + } + r = engine->RegisterGlobalFunction( + "void LOG_BACKTRACE(string)", AngelScript::asFUNCTION(as_log_backtrace), + AngelScript::asCALL_CDECL + ); + if (util::scripting::check_RegisterGlobalFunction(r)) { + return; + } + r = engine->RegisterGlobalFunction( + "void LOG_INFO(string)", AngelScript::asFUNCTION(as_log_info), + AngelScript::asCALL_CDECL + ); + if (util::scripting::check_RegisterGlobalFunction(r)) { + return; + } + r = engine->RegisterGlobalFunction( + "void LOG_DEBUG(string)", AngelScript::asFUNCTION(as_log_debug), + AngelScript::asCALL_CDECL + ); + if (util::scripting::check_RegisterGlobalFunction(r)) { + return; + } + r = engine->RegisterGlobalFunction( + "void LOG_WARNING(string)", AngelScript::asFUNCTION(as_log_warning), + AngelScript::asCALL_CDECL + ); + if (util::scripting::check_RegisterGlobalFunction(r)) { + return; + } + r = engine->RegisterGlobalFunction( + "void LOG_ERROR(string)", AngelScript::asFUNCTION(as_log_error), + AngelScript::asCALL_CDECL + ); + if (util::scripting::check_RegisterGlobalFunction(r)) { + return; + } + r = engine->RegisterGlobalFunction( + "void LOG_CRITICAL(string)", AngelScript::asFUNCTION(as_log_critical), + AngelScript::asCALL_CDECL + ); + if (util::scripting::check_RegisterGlobalFunction(r)) { + return; + } +} + +} // namespace scripting + +} // namespace util diff --git a/src/util/angel_script/as_logging.hpp b/src/util/angel_script/as_logging.hpp new file mode 100644 index 00000000..1bd0487f --- /dev/null +++ b/src/util/angel_script/as_logging.hpp @@ -0,0 +1,39 @@ +// -*- lsst-c++ -*- +/* + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +/** + * @file as_logging.hpp + * + * @author @AlemSnyder + * + * @brief Defines functions that initialize AngelScript logging + * + */ + +#pragma once + +#include + +namespace util { +namespace scripting { + +/** + * @brief Initialize Logging interface on given engine + * + * @param asIScriptEngine* engine the engine logging will be initialized on. + */ +void init_as_interface(AngelScript::asIScriptEngine* engine); + +} // namespace scripting + +} // namespace util diff --git a/src/util/angel_script/as_math.hpp b/src/util/angel_script/as_math.hpp new file mode 100644 index 00000000..b08f4ac6 --- /dev/null +++ b/src/util/angel_script/as_math.hpp @@ -0,0 +1,3 @@ +// TODO want to write math here +// There is some as math functions that need to be added, along with glm vectors +// Also want to add the array library. diff --git a/src/util/angel_script/as_tests.cpp b/src/util/angel_script/as_tests.cpp new file mode 100644 index 00000000..6a5dcbc6 --- /dev/null +++ b/src/util/angel_script/as_tests.cpp @@ -0,0 +1,278 @@ + +#include "as_logging.hpp" +#include "global_context.hpp" +#include "local_context.hpp" +#include "logging.hpp" +#include "scriptstdstring.h" // hm +#include "util/files.hpp" +#include "util/time.hpp" + +#include + +namespace util { +namespace scripting { + +int +as_loadtime_test() { + LOG_INFO(logging::main_logger, "Getting global and local context."); + GlobalContext& context = GlobalContext::instance(); + LocalContext& local_context = LocalContext::instance(); + + { + auto file_result = context.load_file( + "test_module", files::get_resources_path() / "as" / "test.as" + ); + if (file_result != AngelScript::asERetCodes::asSUCCESS) { + LOG_ERROR(logging::script_logger, "Could not open file."); + return 1; + } + + auto is_prime_function = + context.get_function("test_module", "bool is_prime(int)"); + + LOG_INFO(logging::main_logger, "Got as function, calling."); + + auto function_result = local_context.run_function(is_prime_function, 97); + + if (!function_result) { + return 1; + } + + bool is_prime_result; + local_context.get_return_value(is_prime_result); + + std::string log_value = is_prime_result ? "correct" : "incorrect"; + LOG_INFO( + logging::main_logger, "Got {} from as function. Is {} value.", + is_prime_result, log_value + ); + } + + { + std::vector load_times; + std::vector run_times; + + for (size_t y = 0; y < 100; y++) { + auto l_start = time_util::get_time_nanoseconds(); + + auto is_prime_function = + context.get_function("test_module", "bool is_prime(int)"); + auto l_end = time_util::get_time_nanoseconds(); + + auto r_start = time_util::get_time_nanoseconds(); + + auto function_result = local_context.run_function(is_prime_function, 97); + + if (!function_result) { + return 1; + } + + bool is_prime_result; + local_context.get_return_value(is_prime_result); + + auto r_end = time_util::get_time_nanoseconds(); + + load_times.push_back(l_end - l_start); + + run_times.push_back(r_end - r_start); + } + + std::chrono::nanoseconds r_mean(0); + for (size_t i = 1; i < run_times.size(); i++) { + std::chrono::nanoseconds duration = run_times[i]; + r_mean += duration; + } + r_mean /= (run_times.size() - 1); + + std::chrono::nanoseconds l_mean(0); + for (size_t i = 1; i < load_times.size(); i++) { + std::chrono::nanoseconds duration = load_times[i]; + l_mean += duration; + } + l_mean /= (load_times.size() - 1); + + LOG_INFO( + logging::main_logger, + "Mean load time of {} samples is {}ns. First load time is {}ns", + (load_times.size() - 1), int64_t(l_mean.count()), load_times[0].count() + ); + + LOG_INFO( + logging::main_logger, + "Mean execution time of {} samples is {}ns. First execution time is {}ns.", + (run_times.size() - 1), int64_t(r_mean.count()), run_times[0].count() + ); + } + + return 0; +} + +int +logging_test() { + GlobalContext& context = GlobalContext::instance(); + LocalContext& local_context = LocalContext::instance(); + + auto file_result = context.load_file( + "test_module", files::get_resources_path() / "as" / "test.as" + ); + if (file_result != AngelScript::asERetCodes::asSUCCESS) { + LOG_ERROR(logging::script_logger, "Could not open file."); + return 1; + } + AngelScript::asIScriptFunction* funct1 = + context.get_function("test_module", "int test3()"); + + if (funct1 == nullptr) { + return 1; + } + auto result_2 = local_context.run_function(funct1); + if (!result_2) { + return 1; + } + return 0; +} + +int +test() { + LOG_ERROR(logging::script_logger, ""); + + GlobalContext& context = GlobalContext::instance(); + LocalContext& local_context = LocalContext::instance(); + + auto result_1 = context.load_file( + "test_module", files::get_resources_path() / "as" / "test.as" + ); + + if (result_1 != AngelScript::asERetCodes::asSUCCESS) { + LOG_ERROR(logging::script_logger, "Could not open file."); + return 1; + } + + AngelScript::asIScriptFunction* funct1 = + context.get_function("test_module", "int test1()"); + + if (funct1 == nullptr) { + return 1; + } + auto result_2 = local_context.run_function(funct1); + if (!result_2) { + return 1; + } + AngelScript::asIScriptFunction* funct2 = + context.get_function("test_module", "int test1()"); + + if (funct2 == nullptr) { + return 1; + } + result_2 = local_context.run_function(funct2); + if (!result_2) { + return 1; + } + + return 0; +} + +int +as_threading() { + GlobalContext& context = GlobalContext::instance(); + auto file_result = context.load_file( + "test_module", files::get_resources_path() / "as" / "test.as" + ); + if (file_result != AngelScript::asERetCodes::asSUCCESS) { + LOG_ERROR(logging::script_logger, "Could not open file."); + return 1; + } + + std::future future = context.submit_task([]() { + GlobalContext& context = GlobalContext::instance(); + LocalContext& local_context = LocalContext::instance(); + + auto function = context.get_function("test_module", "int text3()"); + auto result = local_context.run_function(function); + if (!result) { + return 1; + } + return 0; + }); + + int result = future.get(); + + return result; +} + +int +as_load_tests() { + GlobalContext& context = GlobalContext::instance(); + LocalContext& local_context = LocalContext::instance(); + + auto file_result = + context.load_file("main", files::get_resources_path() / "as" / "test.as"); + if (file_result != AngelScript::asERetCodes::asSUCCESS) { + LOG_ERROR(logging::script_logger, "Could not open file."); + return 1; + } + file_result = + context.load_file("Base", files::get_data_path() / "Base" / "biome_map.as"); + if (file_result != AngelScript::asERetCodes::asSUCCESS) { + LOG_ERROR(logging::script_logger, "Could not open file."); + return 1; + } + + auto function = context.get_function("Base", "void do_something()"); + auto result = local_context.run_function(function); + if (!result) { + LOG_ERROR(logging::main_logger, "Failed AngelScript Test"); + return 1; + } + + auto type = context.get_type("Base", "Base::biomes::biome_map"); + int factory_count = type->GetFactoryCount(); + LOG_DEBUG(logging::main_logger, "Found {} factory functions", factory_count); + + auto factory_function = + type->GetFactoryByDecl("Base::biomes::biome_map@ biome_map()"); + auto factory_function_2 = type->GetFactoryByIndex(0); + + auto declaration = factory_function_2->GetDeclaration(true, true, true); + + auto factory_function_3 = type->GetFactoryByDecl(declaration); + + LOG_DEBUG( + logging::main_logger, "{}, {}, {}", factory_function != nullptr, + factory_function_2 != nullptr, factory_function_3 != nullptr + ); + + LOG_DEBUG(logging::main_logger, "{}", declaration); + + result = local_context.run_function(factory_function); + if (!result) { + LOG_ERROR(logging::main_logger, "Failed AngelScript getting biome map"); + return 1; + } + + AngelScript::asIScriptObject* biome_map = local_context.get_return_object(); + if (biome_map == nullptr) { + LOG_ERROR(logging::main_logger, "Failed to get object"); + return 1; + } + biome_map->AddRef(); + + AngelScript::asIScriptFunction* method = + type->GetMethodByDecl("int sample(int, int)"); + auto result_2 = local_context.run_method(biome_map, method, 5, 5); + if (!result) { + LOG_ERROR( + logging::main_logger, "Failed AngelScript run sample, with error {}.", + std::to_underlying(result_2.error()) + ); + return 1; + } + + LOG_DEBUG(logging::main_logger, "Got result {}.", result_2.value()); + biome_map->Release(); + return 0; +} + +} // namespace scripting + +} // namespace util diff --git a/src/util/angel_script/as_tests.hpp b/src/util/angel_script/as_tests.hpp new file mode 100644 index 00000000..b36db6c4 --- /dev/null +++ b/src/util/angel_script/as_tests.hpp @@ -0,0 +1,40 @@ +// -*- lsst-c++ -*- +/* + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +/** + * @file as_tests.hpp + * + * @author @AlemSnyder + * + * @brief Define AngelScript Tests + * + */ + +#pragma once + +namespace util { +namespace scripting { + +int test(); + +int as_loadtime_test(); + +int logging_test(); + +int as_threading(); + +int as_load_tests(); + +} // namespace scripting + +} // namespace util diff --git a/src/util/angel_script/error_checks.cpp b/src/util/angel_script/error_checks.cpp new file mode 100644 index 00000000..6f11b94e --- /dev/null +++ b/src/util/angel_script/error_checks.cpp @@ -0,0 +1,271 @@ +#include "error_checks.hpp" + +#include "angelscript.h" +#include "logging.hpp" + +namespace util { + +namespace scripting { + +bool +check_SetDefaultNamespace(int r) { + switch (r) { + case AngelScript::asERetCodes::asINVALID_ARG: + LOG_ERROR(logging::as_logger, "The namespace is invalid."); + return true; + case AngelScript::asERetCodes::asSUCCESS: + return false; + default: + if (r < 0) { + LOG_WARNING( + logging::as_logger, + "Error {} does not match function call. Are you using the correct " + "error handler?", + r + ); + return true; + } + return false; + } +} + +bool +check_RegisterGlobalFunction(int r) { + switch (r) { + case AngelScript::asERetCodes::asINVALID_ARG: + LOG_ERROR(logging::as_logger, "The namespace is null."); + return true; + case AngelScript::asERetCodes::asINVALID_DECLARATION: + LOG_ERROR(logging::as_logger, "The namespace is invalid."); + return true; + case AngelScript::asERetCodes::asSUCCESS: + return false; + default: + if (r < 0) { + LOG_WARNING( + logging::as_logger, + "Error {} does not match function call. Are you using the correct " + "error handler?", + r + ); + return true; + } + return false; + } +} + +bool +check_RegisterObjectType(int r) { + switch (r) { + case AngelScript::asERetCodes::asINVALID_ARG: + LOG_ERROR(logging::as_logger, "The flags are invalid."); + return true; + case AngelScript::asERetCodes::asINVALID_NAME: + LOG_ERROR(logging::as_logger, "The name is invalid."); + return true; + case AngelScript::asERetCodes::asALREADY_REGISTERED: + LOG_ERROR( + logging::as_logger, "Another type of the same name already exists." + ); + return true; + case AngelScript::asERetCodes::asNAME_TAKEN: + LOG_ERROR( + logging::as_logger, "The name conflicts with other symbol names." + ); + return true; + case AngelScript::asERetCodes::asLOWER_ARRAY_DIMENSION_NOT_REGISTERED: + LOG_ERROR( + logging::as_logger, "When registering an array type the array element " + "must be a primitive or a registered type." + ); + return true; + case AngelScript::asERetCodes::asINVALID_TYPE: + LOG_ERROR(logging::as_logger, "The array type was not properly formed."); + return true; + case AngelScript::asERetCodes::asNOT_SUPPORTED: + LOG_ERROR( + logging::as_logger, "The array type is not supported, or already in " + "use preventing it from being overloaded." + ); + return true; + case AngelScript::asERetCodes::asSUCCESS: + return false; + default: + if (r < 0) { + LOG_WARNING( + logging::as_logger, + "Error {} does not match function call. Are you using the correct " + "error handler?", + r + ); + return true; + } + return false; + } +} + +bool +check_RegisterObjectBehaviour(int r) { + switch (r) { + case AngelScript::asERetCodes::asWRONG_CONFIG_GROUP: + LOG_ERROR( + logging::as_logger, + "The object type was registered in a different configuration group." + ); + return true; + case AngelScript::asERetCodes::asINVALID_ARG: + LOG_ERROR( + logging::as_logger, + "obj is not set, or a global behaviour is given in behaviour, or the " + "objForThiscall pointer wasn't set according to calling convention." + ); + return true; + case AngelScript::asERetCodes::asWRONG_CALLING_CONV: + LOG_ERROR( + logging::as_logger, + "The function's calling convention isn't compatible with callConv." + ); + return true; + case AngelScript::asERetCodes::asNOT_SUPPORTED: + LOG_ERROR( + logging::as_logger, + "The calling convention or the behaviour signature is not supported." + ); + return true; + case AngelScript::asERetCodes::asINVALID_TYPE: + LOG_ERROR( + logging::as_logger, "The obj parameter is not a valid object name." + ); + return true; + case AngelScript::asERetCodes::asINVALID_DECLARATION: + LOG_ERROR(logging::as_logger, "The declaration is invalid."); + return true; + case AngelScript::asERetCodes::asILLEGAL_BEHAVIOUR_FOR_TYPE: + LOG_ERROR( + logging::as_logger, "The behaviour is not allowed for this type." + ); + return true; + case AngelScript::asERetCodes::asALREADY_REGISTERED: + LOG_ERROR( + logging::as_logger, + "The behaviour is already registered with the same signature." + ); + return true; + case AngelScript::asERetCodes::asSUCCESS: + return false; + default: + if (r < 0) { + LOG_WARNING( + logging::as_logger, + "Error {} does not match function call. Are you using the correct " + "error handler?", + r + ); + return true; + } + return false; + } +} + +bool +check_RegisterObjectMethod(int r) { + switch (r) { + case AngelScript::asERetCodes::asWRONG_CONFIG_GROUP: + LOG_ERROR( + logging::as_logger, + "The object type was registered in a different configuration group." + ); + return true; + case AngelScript::asERetCodes::asNOT_SUPPORTED: + LOG_ERROR(logging::as_logger, "The calling convention is not supported."); + return true; + case AngelScript::asERetCodes::asINVALID_TYPE: + LOG_ERROR( + logging::as_logger, "The obj parameter is not a valid object name." + ); + return true; + case AngelScript::asERetCodes::asINVALID_DECLARATION: + LOG_ERROR(logging::as_logger, "The declaration is invalid."); + return true; + case AngelScript::asERetCodes::asNAME_TAKEN: + LOG_ERROR(logging::as_logger, "The name conflicts with other members."); + return true; + case AngelScript::asERetCodes::asWRONG_CALLING_CONV: + LOG_ERROR( + logging::as_logger, + "The function's calling convention isn't compatible with callConv." + ); + return true; + case AngelScript::asERetCodes::asALREADY_REGISTERED: + LOG_ERROR( + logging::as_logger, + "The method has already been registered with the same parameter list." + ); + return true; + case AngelScript::asERetCodes::asINVALID_ARG: + LOG_ERROR( + logging::as_logger, + "The auxiliary pointer wasn't set according to calling convention." + ); + return true; + case AngelScript::asERetCodes::asSUCCESS: + return false; + default: + if (r < 0) { + LOG_WARNING( + logging::as_logger, + "Error {} does not match function call. Are you using the correct " + "error handler?", + r + ); + return true; + } + return false; + } +} + +bool +check_ScriptModule_Build(int r) { + switch (r) { + case AngelScript::asINVALID_CONFIGURATION: + LOG_ERROR(logging::as_logger, "The engine configuration is invalid."); + case AngelScript::asERROR: + LOG_ERROR(logging::as_logger, "The script failed to build."); + case AngelScript::asBUILD_IN_PROGRESS: + LOG_ERROR(logging::as_logger, "Another thread is currently building."); + case AngelScript::asINIT_GLOBAL_VARS_FAILED: + LOG_ERROR( + logging::as_logger, "It was not possible to initialize at least one of " + "the global variables." + ); + case AngelScript::asNOT_SUPPORTED: + LOG_ERROR( + logging::as_logger, "Compiler support is disabled in the engine." + ); + case AngelScript::asMODULE_IS_IN_USE: + LOG_ERROR( + logging::as_logger, + "The code in the module is still being used and and cannot be removed." + ); + case AngelScript::asERetCodes::asSUCCESS: + return false; + default: + if (r < 0) { + LOG_WARNING( + logging::as_logger, + "Error {} does not match function call. Are you using the correct " + "error handler?", + r + ); + return true; + } + return false; + } +} + +// AngelScript::asERetCodes check_RegisterObjectType(int r) { + +//} +} // namespace scripting + +} // namespace util diff --git a/src/util/angel_script/error_checks.hpp b/src/util/angel_script/error_checks.hpp new file mode 100644 index 00000000..9c2d517e --- /dev/null +++ b/src/util/angel_script/error_checks.hpp @@ -0,0 +1,24 @@ + + +#pragma once + +#include "angelscript.h" + +namespace util { +namespace scripting { + +bool check_SetDefaultNamespace(int); + +bool check_ScriptModule_Build(int); + +bool check_RegisterGlobalFunction(int); + +bool check_RegisterObjectBehaviour(int); + +bool check_RegisterObjectMethod(int); + +bool check_RegisterObjectType(int); + +} // namespace scripting + +} // namespace util \ No newline at end of file diff --git a/src/util/image.hpp b/src/util/image.hpp index 4fe4cbb4..fcf6d6a4 100644 --- a/src/util/image.hpp +++ b/src/util/image.hpp @@ -1,3 +1,25 @@ +// -*- lsst-c++ -*- +/* + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +/** + * @file image.hpp + * + * @author @AlemSnyder + * + * @brief Defines Image Templates and Classes + * + */ + #pragma once #include "types.hpp" @@ -70,9 +92,7 @@ class Image { inline Image( std::shared_ptr data, size_t width, size_t height, size_t data_size - ) : - width_(width), - height_(height), data_size_(data_size), data_(data){}; + ) : width_(width), height_(height), data_size_(data_size), data_(data) {}; virtual ~Image() {} }; @@ -107,8 +127,7 @@ class FloatMonochromeImage : public virtual MonochromeImage { FloatMonochromeImage( std::shared_ptr data, size_t width, size_t height, size_t data_size - ) : - Image(data, width, height, data_size) {} + ) : Image(data, width, height, data_size) {} inline virtual size_t get_width() const { @@ -131,8 +150,7 @@ class FloatPolychromeImage : public virtual PolychromeImage { FloatPolychromeImage( std::shared_ptr data, size_t width, size_t height, size_t data_size - ) : - Image(data, width, height, data_size) {} + ) : Image(data, width, height, data_size) {} inline virtual size_t get_width() const { @@ -162,8 +180,7 @@ class FloatPolychromeAlphaImage : public virtual PolychromeAlphaImage { FloatPolychromeAlphaImage( std::shared_ptr data, size_t width, size_t height, size_t data_size - ) : - Image(data, width, height, data_size) {} + ) : Image(data, width, height, data_size) {} FloatPolychromeAlphaImage(std::vector> data) : FloatPolychromeAlphaImage(pad_color_data(data)) {} diff --git a/src/util/lua/lua_logging.hpp b/src/util/lua/lua_logging.hpp deleted file mode 100644 index 07fb7529..00000000 --- a/src/util/lua/lua_logging.hpp +++ /dev/null @@ -1,79 +0,0 @@ -#pragma once - -#include "logging.hpp" -#include "util/files.hpp" - -#include -#include - -namespace lua_logging { - -inline void -lua_log_backtrace(std::string file, int line, std::string message) { - LOG_BACKTRACE( - logging::lua_script_logger, "[{:<18}] - {}", - fmtquill::format("{}:{}", file, line), message - ); -} - -inline void -lua_log_info(std::string file, int line, std::string message) { - LOG_INFO( - logging::lua_script_logger, "[{:<18}] - {}", - fmtquill::format("{}:{}", file, line), message - ); -} - -inline void -lua_log_debug(std::string file, int line, std::string message) { - LOG_DEBUG( - logging::lua_script_logger, "[{:<18}] - {}", - fmtquill::format("{}:{}", file, line), message - ); -} - -inline void -lua_log_warning(std::string file, int line, std::string message) { - LOG_WARNING( - logging::lua_script_logger, "[{:<18}] - {}", - fmtquill::format("{}:{}", file, line), message - ); -} - -inline void -lua_log_error(std::string file, int line, std::string message) { - LOG_ERROR( - logging::lua_script_logger, "[{:<18}] - {}", - fmtquill::format("{}:{}", file, line), message - ); -} - -inline void -lua_log_critical(std::string file, int line, std::string message) { - LOG_CRITICAL( - logging::lua_script_logger, "[{:<18}] - {}", - fmtquill::format("{}:{}", file, line), message - ); -} - -inline void -setup_lua_logging(sol::state& lua) { - lua.set_function("lua_log_backtrace", lua_log_backtrace); - lua.set_function("lua_log_info", lua_log_info); - lua.set_function("lua_log_debug", lua_log_debug); - lua.set_function("lua_log_warning", lua_log_warning); - lua.set_function("lua_log_error", lua_log_error); - lua.set_function("lua_log_critical", lua_log_critical); - - std::filesystem::path logging_file_path = - files::get_resources_path() / "lua" / "logging.lua"; - - sol::table logging_library = - lua.require_file("Logging", logging_file_path.string(), false); - - if (!logging_library.valid()) { - LOG_WARNING(logging::main_logger, "Logging library did not load correctly."); - } -} - -} // namespace lua_logging diff --git a/src/util/lua/lua_tests.cpp b/src/util/lua/lua_tests.cpp deleted file mode 100644 index 40570259..00000000 --- a/src/util/lua/lua_tests.cpp +++ /dev/null @@ -1,330 +0,0 @@ -#include "lua_tests.hpp" - -#include "global_context.hpp" -#include "local_context.hpp" -#include "logging.hpp" -#include "util/files.hpp" -#include "util/time.hpp" - -#include - -namespace util { - -namespace lua_tests { - -int -lua_loadtime_test() { - LOG_INFO(logging::main_logger, "Getting Local Lua State."); - LocalContext& local_context = LocalContext::instance(); - sol::state& lua = local_context.get_lua_state(); - LOG_INFO(logging::main_logger, "Got Local Lua State."); - LOG_INFO(logging::main_logger, "Loading Lua File."); - - std::filesystem::path lua_script_path = - files::get_resources_path() / "lua" / "is_prime_test.lua"; - - sol::table result = - lua.require_file("is_prime_test", lua_script_path.string(), false); - - if (!result.valid()) { - LOG_WARNING(logging::main_logger, "is prime test failed to import."); - return 1; - } - - for (const auto& key : result) { - if (key.first.is()) { - std::string string_key = key.first.as(); - LOG_INFO(logging::main_logger, "{}", string_key); - } - } - - { - sol::protected_function is_prime_function = result["tests"]["is_prime"]; - - LOG_INFO(logging::main_logger, "Got Lua function, calling."); - - auto function_result = is_prime_function.call(97); - - if (!function_result.valid()) { - sol::error err = function_result; - std::string what = err.what(); - LOG_DEBUG(logging::main_logger, "{}", what); - return 1; - } - - int is_prime_result = function_result; - - std::string log_value = is_prime_result == 1 ? "correct" : "incorrect"; - LOG_INFO( - logging::main_logger, "Got Lua {} from Lua function. Is {} value.", - is_prime_result, log_value - ); - } - - { - std::vector load_times; - std::vector run_times; - - for (size_t y = 0; y < 100; y++) { - auto l_start = time_util::get_time_nanoseconds(); - - std::filesystem::path prime_test_file_path = - files::get_resources_path() / "lua" / "is_prime_test.lua"; - - sol::table biome_library = - lua.require_file("is_prime_test", prime_test_file_path.string(), false); - - sol::protected_function is_prime_function = - biome_library["tests"]["is_prime"]; - - auto l_end = time_util::get_time_nanoseconds(); - load_times.push_back(l_end - l_start); - - auto r_start = time_util::get_time_nanoseconds(); - - auto function_result = is_prime_function.call(97); - - if (!function_result.valid()) { - sol::error err = function_result; - std::string what = err.what(); - LOG_DEBUG(logging::main_logger, "{}", what); - return 1; - } - - auto r_end = time_util::get_time_nanoseconds(); - - run_times.push_back(r_end - r_start); - } - - std::chrono::nanoseconds r_mean(0); - for (size_t i = 1; i < run_times.size(); i++) { - std::chrono::nanoseconds duration = run_times[i]; - r_mean += duration; - } - r_mean /= (run_times.size() - 1); - - std::chrono::nanoseconds l_mean(0); - for (size_t i = 1; i < load_times.size(); i++) { - std::chrono::nanoseconds duration = load_times[i]; - l_mean += duration; - } - l_mean /= (load_times.size() - 1); - - LOG_INFO( - logging::main_logger, - "Mean load time of {} samples is {}ns. First load time is {}ns", - (load_times.size() - 1), int64_t(l_mean.count()), load_times[0].count() - ); - - LOG_INFO( - logging::main_logger, - "Mean execution time of {} samples is {}ns. First execution time is {}ns.", - (run_times.size() - 1), int64_t(r_mean.count()), run_times[0].count() - ); - } - - return 0; -} - -int -lua_log_test() { - LocalContext& local_context = LocalContext::instance(); - sol::state& lua = local_context.get_lua_state(); - - sol::protected_function lua_log_critical = lua["Logging"]["LOG_CRITICAL"]; - - auto result = lua_log_critical.call("Critical message from cpp!!"); - - if (!result.valid()) { - sol::error err = result; // who designed this? - std::string what = err.what(); - LOG_DEBUG(logging::main_logger, "{}", what); - } - - return 0; -} - -int -lua_transfertime_test() { - LOG_INFO(logging::main_logger, "Loading Lua File."); - - std::filesystem::path lua_script_path = - files::get_resources_path() / "lua" / "is_prime_test.lua"; - - GlobalContext& context = GlobalContext::instance(); - context.load_script_file(lua_script_path); - - { - std::optional result = context.get_from_lua("tests\\is_prime"); - - if (!result) { - return 1; - } - if (!result->is()) { - return 1; - } - - sol::protected_function is_prime_function = - result->as(); - - auto function_result = is_prime_function.call(97); - - if (!function_result.valid()) { - sol::error err = function_result; - std::string what = err.what(); - LOG_DEBUG(logging::main_logger, "{}", what); - return 1; - } - - int is_prime_result = function_result; - - std::string log_value = is_prime_result == 1 ? "correct" : "incorrect"; - LOG_INFO( - logging::main_logger, "Got Lua {} from Lua function. Is {} value.", - is_prime_result, log_value - ); - } - - std::future future_result = context.submit_task([]() { - std::vector load_times; - std::vector run_times; - - for (size_t y = 0; y < 101; y++) { - auto l_start = time_util::get_time_nanoseconds(); - - LocalContext& local_context = LocalContext::instance(); - - std::optional result = - local_context.get_from_lua("tests\\is_prime"); - - if (!result) { - LOG_CRITICAL(logging::lua_logger, "Could not find is_prime."); - return 1; - } - if (!result->is()) { - return 1; - } - - sol::protected_function is_prime_function = - result->as(); - - auto l_end = time_util::get_time_nanoseconds(); - - load_times.push_back(l_end - l_start); - - auto r_start = time_util::get_time_nanoseconds(); - - auto function_result = is_prime_function.call(97); - - if (!function_result.valid()) { - sol::error err = function_result; - std::string what = err.what(); - LOG_DEBUG(logging::main_logger, "{}", what); - return 1; - } - - auto r_end = time_util::get_time_nanoseconds(); - - run_times.push_back(r_end - r_start); - } - - std::chrono::nanoseconds r_mean(0); - for (size_t i = 1; i < run_times.size(); i++) { - std::chrono::nanoseconds duration = run_times[i]; - r_mean += duration; - } - r_mean /= (run_times.size() - 1); - - std::chrono::nanoseconds l_mean(0); - for (size_t i = 1; i < load_times.size(); i++) { - std::chrono::nanoseconds duration = load_times[i]; - l_mean += duration; - } - l_mean /= (load_times.size() - 1); - - LOG_INFO( - logging::main_logger, - "Mean load time of {} samples is {}ns. First load time is {}ns", - (load_times.size() - 1), int64_t(l_mean.count()), load_times[0].count() - ); - - LOG_INFO( - logging::main_logger, - "Mean execution time of {} samples is {}ns. First execution time is {}ns.", - (run_times.size() - 1), int64_t(r_mean.count()), run_times[0].count() - ); - - return 0; - }); - - int subprocess_status = future_result.get(); - - return subprocess_status; -} - -int -lua_load_tests() { - // load is_prime_test.lua - LOG_INFO(logging::main_logger, "Loading Lua File."); - - std::filesystem::path lua_script_path = - files::get_resources_path() / "lua" / "is_prime_test.lua"; - - GlobalContext& context = GlobalContext::instance(); - context.load_script_file(lua_script_path); - - // this should work - std::future future_1 = context.submit_task([]() { - LocalContext& local_context = LocalContext::instance(); - bool return_status = local_context.load_into_this_lua_state("tests"); - // true when no erro -> 0 (!true) - return static_cast(!return_status); - }); - - int value_1 = future_1.get(); - if (value_1 != 0) { - LOG_ERROR(logging::lua_logger, "load_into_this_lua_state failed"); - return 1; - } - - // this should also work - std::future future_2 = context.submit_task([]() { - LocalContext& local_context = LocalContext::instance(); - bool return_status = local_context.load_into_this_lua_state("tests"); - if (!return_status) { - return 1; - } - std::optional tests_table = - local_context.get_from_this_lua_state("tests"); - if (tests_table) { - if (tests_table->is()) { - sol::table tests_table_table = tests_table.value(); - for (auto& [key, value] : tests_table_table) { - LOG_INFO(logging::lua_logger, "key: {}", key.as()); - } - } - } - - std::optional is_prime_function = - local_context.get_from_this_lua_state("tests\\is_prime"); - if (!is_prime_function) { - LOG_ERROR(logging::lua_logger, "Could not load tests table."); - return 1; - } - local_context.set_to_this_lua_state( - "tests\\is_not_not_prime", is_prime_function.value() - ); - return 0; - }); - - int value_2 = future_2.get(); - if (value_2 != 0) { - LOG_ERROR(logging::lua_logger, "get from and set to this lua state failed"); - return 1; - } - return 0; -} - -} // namespace lua_tests - -} // namespace util diff --git a/src/util/lua/lua_tests.hpp b/src/util/lua/lua_tests.hpp deleted file mode 100644 index 8db67af7..00000000 --- a/src/util/lua/lua_tests.hpp +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -namespace util { - -namespace lua_tests { - -int lua_loadtime_test(); - -int lua_load_tests(); - -int lua_transfertime_test(); - -int lua_log_test(); - -} // namespace lua_tests - -} // namespace util diff --git a/src/util/mesh.hpp b/src/util/mesh.hpp index 33c7e534..3a9182cf 100644 --- a/src/util/mesh.hpp +++ b/src/util/mesh.hpp @@ -15,8 +15,6 @@ * * @brief Defines Mesh Class * - * @ingroup ENTITY - * */ #pragma once @@ -49,10 +47,9 @@ class Mesh { const std::vector& indexed_normals, const std::vector& color_map, glm::ivec3 size, glm::ivec3 center ) : - size_(size), - center_(center), indices_(indices), indexed_vertices_(indexed_vertices), - indexed_color_ids_(indexed_color_ids), indexed_normals_(indexed_normals), - color_map_(color_map) {} + size_(size), center_(center), indices_(indices), + indexed_vertices_(indexed_vertices), indexed_color_ids_(indexed_color_ids), + indexed_normals_(indexed_normals), color_map_(color_map) {} Mesh() : size_({0, 0, 0}), center_({0, 0, 0}), indices_({}), indexed_vertices_({}), diff --git a/src/util/png_image.hpp b/src/util/png_image.hpp index 556dfc97..31c3c968 100644 --- a/src/util/png_image.hpp +++ b/src/util/png_image.hpp @@ -181,7 +181,7 @@ void log_result(write_result_t result, const std::filesystem::path& path); class ImageTest { public: - ImageTest(){}; + ImageTest() {}; size_t get_height() const { @@ -324,7 +324,7 @@ write_image(T image, const std::filesystem::path& path) { class ColorImageTest { public: - ColorImageTest(){}; + ColorImageTest() {}; size_t get_height() const { diff --git a/src/world/biome.cpp b/src/world/biome.cpp index 8e23448c..d6fd57d9 100644 --- a/src/world/biome.cpp +++ b/src/world/biome.cpp @@ -3,20 +3,14 @@ #include "global_context.hpp" #include "local_context.hpp" #include "logging.hpp" -#include "manifest/object_handler.hpp" -#include "terrain/generation/lua_interface.hpp" -#include "terrain/generation/noise.hpp" -#include "terrain/generation/worley_noise.hpp" +#include "util/files.hpp" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wmissing-braces" #include #pragma clang diagnostic pop -#include - #include -#include #include #include #include @@ -69,7 +63,7 @@ Biome::Biome(biome_json_data biome_data, size_t seed) : materials_(init_materials_(biome_data.materials_data)), generate_plants_(biome_data.biome_data.generate_plants), grass_data_(biome_data.materials_data.at("Dirt").gradient), - lua_map_generator_file_( + map_generator_file_( files::get_data_path() / biome_data.biome_name / biome_data.biome_data.map_generator_path ), @@ -82,97 +76,74 @@ Biome::Biome(biome_json_data biome_data, size_t seed) : read_add_to_top_data_(biome_data.biome_data.layer_effects); - if (!std::filesystem::exists(lua_map_generator_file_)) [[unlikely]] { + if (!std::filesystem::exists(map_generator_file_)) [[unlikely]] { LOG_ERROR( - logging::lua_logger, "File, {}, not found", lua_map_generator_file_.string() + logging::as_logger, "File, {}, not found", map_generator_file_.string() ); } } TerrainMacroMap Biome::get_map(MacroDim size) const { - std::vector out; + auto& global_context = GlobalContext::instance(); + auto& local_context = LocalContext::instance(); - LocalContext& local_context = LocalContext::instance(); - auto biome_map_query = local_context.get_from_lua(id_name_ + "\\biome_map"); - - if (!biome_map_query) { - LOG_ERROR(logging::lua_logger, "Could not copy biome map."); - return {}; - } - if (!biome_map_query->is()) { - LOG_ERROR(logging::lua_logger, "Could not copy biome map."); + auto type = global_context.get_type("Base", "Base::biomes::biome_map"); + if (type == nullptr) { return {}; } + auto factory_function = + type->GetFactoryByDecl("Base::biomes::biome_map@ biome_map()"); - sol::table biome_map = biome_map_query.value(); - - auto biome_map_function = - biome_map.get>("map"); - - if (!biome_map_function) { - LOG_ERROR(logging::lua_logger, "map does not exists"); + auto result = local_context.run_function(factory_function); + if (!result) { + LOG_ERROR(logging::main_logger, "Failed AngelScript getting biome map"); return {}; } - - sol::protected_function map_function = biome_map_function.value(); - - if (!map_function.valid()) [[unlikely]] { - LOG_ERROR(logging::lua_logger, "Function map not defined."); + AngelScript::asIScriptObject* biome_map = local_context.get_return_object(); + if (biome_map == nullptr) { + LOG_ERROR(logging::main_logger, "Failed to get object"); return {}; } + biome_map->AddRef(); - auto function_output = map_function(size); - - if (!function_output.valid()) { - LOG_ERROR(logging::lua_logger, "Function result not valid."); - sol::error err = function_output; - sol::call_status status = function_output.status(); - LOG_ERROR(logging::lua_logger, "{}: {}", sol::to_string(status), err.what()); + AngelScript::asIScriptFunction* method = + type->GetMethodByDecl("int sample(int, int)"); + if (method == nullptr) { + LOG_WARNING(logging::main_logger, "Could not find biome map function."); return {}; } + result = local_context.run_method(biome_map, method, 5, 5); - if (!(function_output.get_type() == sol::type::table)) { - LOG_ERROR(logging::lua_logger, "Function output must be a table."); - return {}; - } - - sol::table map = function_output; - - auto tile_map_map = map["map"]; - if (!(tile_map_map.get_type() == sol::type::table)) { - LOG_ERROR(logging::lua_logger, "Invalid map"); - return {}; - } - - auto table_x_value = map["x"]; - if (!(table_x_value.get_type() == sol::type::number)) { - LOG_ERROR(logging::lua_logger, "Invalid x value"); - return {}; - } - MacroDim x_map_tiles = table_x_value; + std::vector out; - auto table_y_value = map["y"]; - if (!(table_y_value.get_type() == sol::type::number)) { - LOG_ERROR(logging::lua_logger, "Invalid y value"); - return {}; - } - MacroDim y_map_tiles = table_y_value; + MacroDim x_map_tiles = size; + MacroDim y_map_tiles = size; - assert( - ((y_map_tiles == x_map_tiles) && (x_map_tiles == size)) - && "Map tile input and out put must all match" - ); out.reserve(x_map_tiles * y_map_tiles); for (MacroDim x = 0; x < x_map_tiles; x++) { for (MacroDim y = 0; y < y_map_tiles; y++) { - size_t map_index = x * y_map_tiles + y; - int tile_id = tile_map_map[map_index].get_or(0); + int x_copy = x; + int y_copy = y; + auto result_2 = local_context.run_method( + biome_map, method, std::move(x_copy), std::move(y_copy) + ); + if (!result_2) { + LOG_ERROR( + logging::main_logger, "Error code {}", + static_cast(result_2.error()) + ); + return {}; + } + + int tile_id = result_2.value(); const TileType& tile_type = macro_tile_types_[tile_id]; out.emplace_back(tile_type, seed, x, y); } } + biome_map->Release(); + return TerrainMacroMap(out, x_map_tiles, y_map_tiles); } @@ -180,109 +151,70 @@ const std::unordered_map Biome::get_plant_map(Dim length) const { std::unordered_map out; - LocalContext& local_context = LocalContext::instance(); - auto biome_map_query = local_context.get_from_lua(id_name_ + "\\biome_map"); - - if (!biome_map_query) { - LOG_ERROR(logging::lua_logger, "Could not copy biome map."); - return {}; - } - if (!biome_map_query->is()) { - LOG_ERROR(logging::lua_logger, "Could not copy biome map."); - return {}; - } - sol::table biome_map = biome_map_query.value(); + auto& global_context = GlobalContext::instance(); + auto& local_context = LocalContext::instance(); - auto biome_map_function = - biome_map.get>("map"); + // global_context.load_file("Base", files::get_data_path() / "Base" / + // "biome_map.as"); - if (!biome_map_function) { - LOG_ERROR(logging::lua_logger, "map does not exists"); - return {}; - } + auto type = global_context.get_type("Base", "Base::biomes::biome_map"); + auto factory_function = + type->GetFactoryByDecl("Base::biomes::biome_map@ biome_map()"); - sol::protected_function map_function = biome_map_function.value(); - - if (!map_function.valid()) [[unlikely]] { - LOG_ERROR(logging::lua_logger, "Function map not defined."); + auto result = local_context.run_function(factory_function); + if (!result) { + LOG_ERROR(logging::main_logger, "Failed AngelScript getting biome map"); return {}; } - - auto biome_plant_map_function = - biome_map.get>("plants_map"); - - if (!biome_plant_map_function) { - LOG_ERROR(logging::lua_logger, "map does not exists"); + AngelScript::asIScriptObject* biome_map = local_context.get_return_object(); + if (biome_map == nullptr) { + LOG_ERROR(logging::main_logger, "Failed to get object"); return {}; } + biome_map->AddRef(); - sol::protected_function plant_map = biome_plant_map_function.value(); - - if (!plant_map.valid()) { - LOG_ERROR(logging::lua_logger, "Error with plant_map in {}.", id_name_); - return {}; - } - - sol::protected_function_result macro_map = map_function(length); - - if (!macro_map.valid()) { - sol::error err = macro_map; - sol::call_status status = macro_map.status(); - LOG_ERROR(logging::lua_logger, "{}: {}", sol::to_string(status), err.what()); - return {}; - } else if (macro_map.get_type() != sol::type::table) { - LOG_WARNING(logging::lua_logger, "map function result is not a table."); + AngelScript::asIScriptFunction* script_method = + type->GetMethodByDecl("float sample_plants(string, int, int)"); + result = local_context.run_method(biome_map, script_method, 5, 5); + if (script_method == nullptr) { + LOG_WARNING(logging::main_logger, "Could not find biome map function."); return {}; } - sol::table macro_map_table = macro_map; + for (auto& plant : generate_plants_) { + std::string plant_map_name = plant.map_name; - sol::table map = plant_map(length, macro_map_table); + std::vector plant_data; - MacroDim x_map_tiles = map["x"]; - MacroDim y_map_tiles = map["y"]; + MacroDim x_map_tiles = length; + MacroDim y_map_tiles = length; - LOG_DEBUG( - logging::lua_logger, "Input length: {}, (x, y) = ({}, {})", length, x_map_tiles, - y_map_tiles - ); - - assert( - ((y_map_tiles == x_map_tiles) && (x_map_tiles == length)) - && "Map tile input and out put must all match" - ); - - auto maps = sol::table(map["map"]); - for (const auto& plant_sub_map : maps) { - std::vector type_map; - - sol::object flora_type = plant_sub_map.first; - - type_map.reserve(x_map_tiles * y_map_tiles); - - LOG_DEBUG(logging::lua_logger, "Key is {}", flora_type.as()); - - auto tile_map_map = maps[flora_type]; + out.reserve(x_map_tiles * y_map_tiles); for (MacroDim x = 0; x < x_map_tiles; x++) { for (MacroDim y = 0; y < y_map_tiles; y++) { - size_t map_index = x * y_map_tiles + y; - auto value = tile_map_map[map_index]; - - if (value.is()) { - type_map.emplace_back(value.get()); - } else { - LOG_ERROR(logging::lua_logger, "Value is not a float."); + int x_copy = x; + int y_copy = y; + auto result_2 = local_context.run_method( + biome_map, script_method, &plant_map_name, std::move(x_copy), + std::move(y_copy) + ); + if (!result) { + LOG_ERROR( + logging::script_logger, "Error code {}", + static_cast(result.error()) + ); + return {}; } + + float plant_probability = result_2.value(); + plant_data.push_back(plant_probability); } } - - std::string type_as_string = flora_type.as(); - - out.emplace(std::make_pair( - std::move(type_as_string), {type_map, x_map_tiles, y_map_tiles} - )); + out.emplace(plant_map_name, PlantMap(plant_data, length, length)); } + biome_map->Release(); + return out; } diff --git a/src/world/biome.hpp b/src/world/biome.hpp index 518295e0..c20305c6 100644 --- a/src/world/biome.hpp +++ b/src/world/biome.hpp @@ -24,9 +24,6 @@ #include "terrain/generation/land_generator.hpp" #include "terrain/generation/map_tile.hpp" #include "terrain/generation/terrain_map.hpp" -#include "util/files.hpp" - -#include #include #include @@ -123,7 +120,7 @@ class Biome { GrassData grass_data_; - const std::filesystem::path lua_map_generator_file_; + const std::filesystem::path map_generator_file_; // display name const std::string name_; @@ -287,9 +284,8 @@ class Biome { [[nodiscard]] std::unordered_map get_colors_inverse_map() const; - static TerrainMacroMap map_generation_test( - const std::filesystem::path& lua_map_generator_file, size_t size - ); + static TerrainMacroMap + map_generation_test(const std::filesystem::path& map_generator_file, size_t size); [[nodiscard]] static biome_json_data get_json_data(const std::filesystem::path& biome_file_folder); diff --git a/src/world/object/entity/entity.cpp b/src/world/object/entity/entity.cpp index f03c94e2..14f64c39 100644 --- a/src/world/object/entity/entity.cpp +++ b/src/world/object/entity/entity.cpp @@ -5,8 +5,6 @@ #include "logging.hpp" #include "util/files.hpp" -#include - namespace world { namespace object { @@ -14,9 +12,11 @@ namespace object { namespace entity { Entity::Entity(const util::Mesh& mesh) : - mesh_and_positions_(std::make_shared( - mesh, std::vector() - )) { + mesh_and_positions_( + std::make_shared( + mesh, std::vector() + ) + ) { LOG_WARNING( logging::main_logger, "Entity constructor Entity(const Mesh& mesh) is depreciated!" @@ -25,9 +25,7 @@ Entity::Entity(const util::Mesh& mesh) : Entity::Entity( const object_t& object_data, const manifest::descriptor_t& identification_data -) : - name_(object_data.name), - identification_(identification_data.identification) { +) : name_(object_data.name), identification_(identification_data.identification) { const auto& model_data = object_data.models[0]; // read mesh from path std::filesystem::path object_path_copy = identification_data.path; @@ -46,10 +44,9 @@ Entity::Entity( / object_path_copy.remove_filename() / object_data.ai.value(); - // load into All Lua - // need access control + // load into the angelscript engine GlobalContext& context = GlobalContext::instance(); - context.load_script_file(ai_path); + context.load_file("Base", ai_path); has_ai_ = true; } @@ -75,44 +72,16 @@ Entity::sync_data_to_gpu() { glm::vec3 Entity::decision(EntityInstance* entity_instance) { LocalContext& local_context = LocalContext::instance(); - std::optional update_function_query = - local_context.get_from_lua(identification_ + "\\update"); - if (!update_function_query) { - LOG_ERROR( - logging::lua_logger, "Could not find Update function for entity {}.", - identification_ - ); - return entity_instance->get_position(); - } else if (!update_function_query->is()) { - LOG_ERROR( - logging::lua_logger, "Update is not a function for entity {}.", - identification_ - ); - return entity_instance->get_position(); - } - sol::protected_function update_function = update_function_query.value(); - if (!update_function.valid()) { - LOG_ERROR( - logging::lua_logger, "Update function for entity {} not valid.", - identification_ - ); - return entity_instance->get_position(); - } - sol::protected_function_result result = update_function(entity_instance); + GlobalContext& global_context = GlobalContext::instance(); + // global_context.get_function(identification_, "vec3 update(Base::entity)"); + // TODO + // need to add glm vec3 to as + // and need to add the entity virtual class - if (!result.valid()) { - sol::error err = result; - sol::call_status status = result.status(); - LOG_ERROR(logging::lua_logger, "{}: {}", sol::to_string(status), err.what()); - return entity_instance->get_position(); - } + // Then call function and pass the entity instance object to it. - sol::table vector_table = result; - glm::vec3 position; - position.x = vector_table["x"]; - position.y = vector_table["y"]; - position.z = vector_table["z"]; + glm::vec3 position(0); return position; } diff --git a/src/world/object/entity/entity.hpp b/src/world/object/entity/entity.hpp index 453cd45e..e825d7d1 100644 --- a/src/world/object/entity/entity.hpp +++ b/src/world/object/entity/entity.hpp @@ -83,7 +83,7 @@ class Entity : public virtual Object, public virtual Cognition { Entity(const object_t& object_data, const manifest::descriptor_t& model_path); - virtual ~Entity(){}; + virtual ~Entity() {}; inline void reserve(size_t size) const { diff --git a/src/world/object/entity/implemented_entity.hpp b/src/world/object/entity/implemented_entity.hpp index dcd93bda..efad9069 100644 --- a/src/world/object/entity/implemented_entity.hpp +++ b/src/world/object/entity/implemented_entity.hpp @@ -12,8 +12,7 @@ class ImplementedEntity : public virtual Entity { public: ImplementedEntity( const object_t& object_data, const manifest::descriptor_t& model_path - ) : - Entity(object_data, model_path) {} + ) : Entity(object_data, model_path) {} [[nodiscard]] virtual glm::vec3 decision(EntityInstance* entity_instance) override; }; diff --git a/src/world/object/entity/object.hpp b/src/world/object/entity/object.hpp index c5a042ae..80229d99 100644 --- a/src/world/object/entity/object.hpp +++ b/src/world/object/entity/object.hpp @@ -110,8 +110,8 @@ struct glz::meta { }; template <> -inline glz::detail::any_t::operator std::vector( -) const { +inline glz::detail::any_t:: +operator std::vector() const { assert(false && "Not Implemented"); return {}; } diff --git a/src/world/object/entity/tile_object.cpp b/src/world/object/entity/tile_object.cpp index 0514f3e6..4a899e26 100644 --- a/src/world/object/entity/tile_object.cpp +++ b/src/world/object/entity/tile_object.cpp @@ -11,9 +11,7 @@ namespace entity { TileObjectInstance::TileObjectInstance( std::shared_ptr object_type, uint8_t model_id, gui::Placement placement -) : - placement_(placement), - model_id_(model_id), object_type_(object_type) { +) : placement_(placement), model_id_(model_id), object_type_(object_type) { object_type->get_model(model_id_).insert(placement_); } @@ -48,9 +46,7 @@ TileObject::num_models() const noexcept { TileObject::TileObject( const object_t& object_data, const manifest::descriptor_t& identification_data -) : - name_(object_data.name), - identification_(identification_data.identification) { +) : name_(object_data.name), identification_(identification_data.identification) { for (const model_t& model_data : object_data.models) { // each object may have multiple models std::filesystem::path object_path_copy = identification_data.path; diff --git a/src/world/object/entity_controller.cpp b/src/world/object/entity_controller.cpp index c0711a11..70a7f252 100644 --- a/src/world/object/entity_controller.cpp +++ b/src/world/object/entity_controller.cpp @@ -61,7 +61,8 @@ EntityController::spawn_entity(std::string identification, glm::vec3 position) { } void -EntityController::remove_entity(std::shared_ptr entity_instance +EntityController::remove_entity( + std::shared_ptr entity_instance ) { // get position ChunkPos chunk_position = @@ -107,9 +108,11 @@ EntityController::spawn_tile_object( // tile_object_instances_.at(position).insert(object); auto inserted = object_instances_.at(chunk_position) - .insert(std::make_shared( - tile_object_type, model_id, placement - )); + .insert( + std::make_shared( + tile_object_type, model_id, placement + ) + ); return *inserted.first; } diff --git a/src/world/object/entity_controller.hpp b/src/world/object/entity_controller.hpp index 21d2aa68..879ed392 100644 --- a/src/world/object/entity_controller.hpp +++ b/src/world/object/entity_controller.hpp @@ -25,7 +25,7 @@ class EntityController { public: EntityController(manifest::ObjectHandler* object_handler) : - object_handler_(object_handler){}; + object_handler_(object_handler) {}; void update_entities(glm::mat4 transforms_matrix); @@ -39,8 +39,8 @@ class EntityController { std::string identification, uint8_t model_id, gui::Placement placement ); - void remove_tile_object(std::shared_ptr entity_instance - ); + void + remove_tile_object(std::shared_ptr entity_instance); void load_to_gup(); diff --git a/src/world/plant.hpp b/src/world/plant.hpp index 7910c1c3..830e3610 100644 --- a/src/world/plant.hpp +++ b/src/world/plant.hpp @@ -25,11 +25,11 @@ struct plant_t { std::string identification; // The map that generates these plants eg Trees_1 std::string map_name; - // path to lua file that contains function map_name + // path to script file that contains function map_name std::optional map_generator_path; - [[nodiscard]] inline std::strong_ordering operator<=>(const plant_t& other - ) const = default; + [[nodiscard]] inline std::strong_ordering + operator<=>(const plant_t& other) const = default; }; } // namespace generation @@ -46,7 +46,8 @@ struct std::hash { }; template <> -inline glz::detail::any_t::operator std::filesystem::path() const { +inline glz::detail::any_t:: +operator std::filesystem::path() const { assert(false && "Not Implemented"); return {}; } diff --git a/src/world/terrain/chunk.cpp b/src/world/terrain/chunk.cpp index 9ac83160..7cb04f8f 100644 --- a/src/world/terrain/chunk.cpp +++ b/src/world/terrain/chunk.cpp @@ -55,7 +55,8 @@ Chunk::stamp_tile_region( void Chunk::init_nodegroups() { - std::unordered_map temporary_position_to_nodegroup_map({} + std::unordered_map temporary_position_to_nodegroup_map( + {} ); // for all tiles: @@ -171,7 +172,8 @@ Chunk::add_nodegroup_adjacent_mp() { continue; } std::scoped_lock lock{ - mut_, ter_->get_chunk(adjacent_chunk)->get_mutex()}; + mut_, ter_->get_chunk(adjacent_chunk)->get_mutex() + }; NG.add_adjacent(to_add, 31); } } @@ -207,7 +209,8 @@ Chunk::add_nodegroup_adjacent_all() { continue; } std::scoped_lock lock{ - mut_, ter_->get_chunk(adjacent_chunk)->get_mutex()}; + mut_, ter_->get_chunk(adjacent_chunk)->get_mutex() + }; NG.add_adjacent(to_add, 31); } } diff --git a/src/world/terrain/chunk.hpp b/src/world/terrain/chunk.hpp index 4c6d51a4..b856c106 100644 --- a/src/world/terrain/chunk.hpp +++ b/src/world/terrain/chunk.hpp @@ -65,7 +65,7 @@ class Chunk : public voxel_utility::VoxelBase { * @param bz chunk z position * @param ter the terrain this chunk is in */ - Chunk(Dim bx, Dim by, Dim bz, Terrain* ter) : Chunk({bx, by, bz}, ter){}; + Chunk(Dim bx, Dim by, Dim bz, Terrain* ter) : Chunk({bx, by, bz}, ter) {}; Chunk(TerrainDim3 chunk_position, Terrain* ter); @@ -238,7 +238,7 @@ class ChunkData : public voxel_utility::VoxelBase { inline ChunkData(const Chunk& chunk) : data_(get_mat_color_from_chunk(chunk)), offset_(chunk.get_offset()), - color_ids_(chunk.get_color_ids()){}; + color_ids_(chunk.get_color_ids()) {}; /** * @brief Used for getting mesh diff --git a/src/world/terrain/generation/interface.cpp b/src/world/terrain/generation/interface.cpp new file mode 100644 index 00000000..49829dbf --- /dev/null +++ b/src/world/terrain/generation/interface.cpp @@ -0,0 +1,147 @@ +#include "interface.hpp" + +#include "logging.hpp" +#include "noise.hpp" +#include "util/angel_script/error_checks.hpp" +#include "worley_noise.hpp" + +namespace terrain { +namespace generation { + +namespace { + +FractalNoise* +FractalNoise_factory(int x, double y, int z) { + // The class constructor is initializing the reference counter to 1 + return new FractalNoise(x, y, z); +} + +WorleyNoise* +WorleyNoise_factory(NoisePosition x, NoisePosition y) { + // The class constructor is initializing the reference counter to 1 + return new WorleyNoise(x, y); +} + +AlternativeWorleyNoise* +AlternativeWorleyNoise_factory(NoisePosition x, double y, NoisePosition z) { + // The class constructor is initializing the reference counter to 1 + return new AlternativeWorleyNoise(x, y, z); +} + +} // namespace + +void +init_as_interface(AngelScript::asIScriptEngine* engine) { + int r = engine->SetDefaultNamespace("TerrainGeneration"); + + if (util::scripting::check_SetDefaultNamespace(r)) { + return; + } + r = engine->RegisterObjectType("FractalNoise", 0, AngelScript::asOBJ_REF); + + if (util::scripting::check_RegisterObjectType(r)) { + return; + } + r = engine->RegisterObjectBehaviour( + "FractalNoise", AngelScript::asBEHAVE_FACTORY, + "FractalNoise@ f(int, double, int)", + AngelScript::asFUNCTION(FractalNoise_factory), AngelScript::asCALL_CDECL + ); + if (util::scripting::check_RegisterObjectBehaviour(r)) { + return; + } + r = engine->RegisterObjectBehaviour( + "FractalNoise", AngelScript::asBEHAVE_ADDREF, "void f()", + AngelScript::asMETHOD(FractalNoise, add_ref), AngelScript::asCALL_THISCALL + ); + if (util::scripting::check_RegisterObjectBehaviour(r)) { + return; + } + r = engine->RegisterObjectBehaviour( + "FractalNoise", AngelScript::asBEHAVE_RELEASE, "void f()", + AngelScript::asMETHOD(FractalNoise, release_ref), AngelScript::asCALL_THISCALL + ); + if (util::scripting::check_RegisterObjectBehaviour(r)) { + return; + } + r = engine->RegisterObjectMethod( + "FractalNoise", "double sample(double, double)", + AngelScript::asMETHOD(FractalNoise, get_noise), AngelScript::asCALL_THISCALL + ); + if (util::scripting::check_RegisterObjectMethod(r)) { + return; + } + r = engine->RegisterObjectType("WorleyNoise", 0, AngelScript::asOBJ_REF); + + if (util::scripting::check_RegisterObjectType(r)) { + return; + } + r = engine->RegisterObjectBehaviour( + "WorleyNoise", AngelScript::asBEHAVE_FACTORY, "WorleyNoise@ f(double, double)", + AngelScript::asFUNCTION(WorleyNoise_factory), AngelScript::asCALL_CDECL + ); + if (util::scripting::check_RegisterObjectBehaviour(r)) { + return; + } + r = engine->RegisterObjectBehaviour( + "WorleyNoise", AngelScript::asBEHAVE_ADDREF, "void f()", + AngelScript::asMETHOD(WorleyNoise, add_ref), AngelScript::asCALL_THISCALL + ); + if (util::scripting::check_RegisterObjectBehaviour(r)) { + return; + } + r = engine->RegisterObjectBehaviour( + "WorleyNoise", AngelScript::asBEHAVE_RELEASE, "void f()", + AngelScript::asMETHOD(WorleyNoise, release_ref), AngelScript::asCALL_THISCALL + ); + if (util::scripting::check_RegisterObjectBehaviour(r)) { + return; + } + r = engine->RegisterObjectMethod( + "WorleyNoise", "double sample(double, double)", + AngelScript::asMETHOD(WorleyNoise, get_noise), AngelScript::asCALL_THISCALL + ); + if (util::scripting::check_RegisterObjectMethod(r)) { + return; + } + r = engine->RegisterObjectType("AlternativeWorleyNoise", 0, AngelScript::asOBJ_REF); + if (util::scripting::check_RegisterObjectType(r)) { + return; + } + r = engine->RegisterObjectBehaviour( + "AlternativeWorleyNoise", AngelScript::asBEHAVE_FACTORY, + "AlternativeWorleyNoise@ f(double, double, double)", + AngelScript::asFUNCTION(AlternativeWorleyNoise_factory), + AngelScript::asCALL_CDECL + ); + if (util::scripting::check_RegisterObjectBehaviour(r)) { + return; + } + r = engine->RegisterObjectBehaviour( + "AlternativeWorleyNoise", AngelScript::asBEHAVE_ADDREF, "void f()", + AngelScript::asMETHOD(AlternativeWorleyNoise, add_ref), + AngelScript::asCALL_THISCALL + ); + if (util::scripting::check_RegisterObjectBehaviour(r)) { + return; + } + r = engine->RegisterObjectBehaviour( + "AlternativeWorleyNoise", AngelScript::asBEHAVE_RELEASE, "void f()", + AngelScript::asMETHOD(AlternativeWorleyNoise, release_ref), + AngelScript::asCALL_THISCALL + ); + if (util::scripting::check_RegisterObjectBehaviour(r)) { + return; + } + r = engine->RegisterObjectMethod( + "AlternativeWorleyNoise", "double sample(double, double)", + AngelScript::asMETHOD(AlternativeWorleyNoise, get_noise), + AngelScript::asCALL_THISCALL + ); + if (util::scripting::check_RegisterObjectMethod(r)) { + return; + } +} + +} // namespace generation +} // namespace terrain diff --git a/src/world/terrain/generation/lua_interface.hpp b/src/world/terrain/generation/interface.hpp similarity index 56% rename from src/world/terrain/generation/lua_interface.hpp rename to src/world/terrain/generation/interface.hpp index 5216ecdd..8f371ff6 100644 --- a/src/world/terrain/generation/lua_interface.hpp +++ b/src/world/terrain/generation/interface.hpp @@ -1,12 +1,12 @@ #pragma once -#include +#include namespace terrain { namespace generation { -void init_lua_interface(sol::state& lua); +void init_as_interface(AngelScript::asIScriptEngine* engine); } // namespace generation diff --git a/src/world/terrain/generation/land_generator.cpp b/src/world/terrain/generation/land_generator.cpp index ab2ad8c5..526342f2 100644 --- a/src/world/terrain/generation/land_generator.cpp +++ b/src/world/terrain/generation/land_generator.cpp @@ -67,8 +67,9 @@ LandGenerator::next() { namespace stamps { TileStamp -StampGenerator::get_volume(glm::imat2x2 center, std::default_random_engine& rand_engine) - const { +StampGenerator::get_volume( + glm::imat2x2 center, std::default_random_engine& rand_engine +) const { // center_x between center[1][0] and center[0][0] inclusive std::uniform_int_distribution center_x_dist( center[0][0], center[1][0] @@ -172,9 +173,7 @@ FromRadius::get_stamp( FromPosition::FromPosition( const generation_stamp_t& data, const stamp_generation_position_data_t& type_data -) : - StampGenerator(data), - center_variance_(data.center_range) { +) : StampGenerator(data), center_variance_(data.center_range) { points_.reserve(type_data.positions.size()); for (const auto& [x, y] : type_data.positions) { @@ -196,8 +195,9 @@ FromPosition::get_stamp( } TileStamp -FromGrid::get_stamp(size_t current_sub_region, std::default_random_engine& rand_engine) - const { +FromGrid::get_stamp( + size_t current_sub_region, std::default_random_engine& rand_engine +) const { TerrainOffset x_center = (1 + 2 * (current_sub_region % number_)) * (radius_ / number_) - radius_; TerrainOffset y_center = diff --git a/src/world/terrain/generation/land_generator.hpp b/src/world/terrain/generation/land_generator.hpp index 50aef3bb..6bdf3cee 100644 --- a/src/world/terrain/generation/land_generator.hpp +++ b/src/world/terrain/generation/land_generator.hpp @@ -175,8 +175,7 @@ class FromRadius : public StampGenerator { FromRadius( const generation_stamp_t& data, const stamp_generation_radius_data_t& type_data ) : - StampGenerator(data), - radius_(type_data.radius), number_(type_data.number), + StampGenerator(data), radius_(type_data.radius), number_(type_data.number), center_variance_(data.center_range) {} FromRadius(const generation_stamp_t& data) : @@ -202,8 +201,7 @@ class FromGrid : public StampGenerator { FromGrid( const generation_stamp_t& data, const stamp_generation_grid_data_t& type_data ) : - StampGenerator(data), - radius_(type_data.radius), number_(type_data.number), + StampGenerator(data), radius_(type_data.radius), number_(type_data.number), center_variance_(data.center_range) {} FromGrid(const generation_stamp_t& data) : FromGrid(data, data.grid.value()) {} diff --git a/src/world/terrain/generation/lua_interface.cpp b/src/world/terrain/generation/lua_interface.cpp deleted file mode 100644 index 3c3e3477..00000000 --- a/src/world/terrain/generation/lua_interface.cpp +++ /dev/null @@ -1,90 +0,0 @@ -#include "lua_interface.hpp" - -#include "noise.hpp" -#include "worley_noise.hpp" - -#include - -namespace terrain { -namespace generation { -void -init_lua_interface(sol::state& lua) { - lua.new_usertype( - "FractalNoise", sol::meta_function::construct, - sol::factories( - // FractalNoise.new(...) -- dot syntax, no "self" value - // passed in - [](int num_octaves, double persistence, int prime_index) { - return std::make_shared( - num_octaves, persistence, prime_index - ); - }, - // FractalNoise:new(...) -- colon syntax, passes in the - // "self" value as first argument implicitly - [](sol::object, int num_octaves, double persistence, int prime_index) { - return std::make_shared( - num_octaves, persistence, prime_index - ); - } - ), - // FractalNoise(...) syntax, only - sol::call_constructor, - sol::factories([](int num_octaves, double persistence, int prime_index) { - return std::make_shared( - num_octaves, persistence, prime_index - ); - }), - "sample", &FractalNoise::get_noise - ); - - lua.new_usertype( - "WorleyNoise", sol::meta_function::construct, - sol::factories( - // WorleyNoise.new(...) -- dot syntax, no "self" value - // passed in - [](int tile_size, double radius) { - return std::make_shared(tile_size, radius); - }, - // WorleyNoise:new(...) -- colon syntax, passes in the - // "self" value as first argument implicitly - [](sol::object, int tile_size, double radius) { - return std::make_shared(tile_size, radius); - } - ), - // WorleyNoise(...) syntax, only - sol::call_constructor, sol::factories([](int tile_size, double radius) { - return std::make_shared(tile_size, radius); - }), - "sample", &WorleyNoise::get_noise - ); - - lua.new_usertype( - "AlternativeWorleyNoise", sol::meta_function::construct, - sol::factories( - // AlternativeWorleyNoise.new(...) -- dot syntax, no "self" value - // passed in - [](int tile_size, double positive_chance, double radius) { - return std::make_shared( - tile_size, positive_chance, radius - ); - }, - // AlternativeWorleyNoise:new(...) -- colon syntax, passes in the - // "self" value as first argument implicitly - [](sol::object, int tile_size, double positive_chance, double radius) { - return std::make_shared( - tile_size, positive_chance, radius - ); - } - ), - // AlternativeWorleyNoise(...) syntax, only - sol::call_constructor, - sol::factories([](int tile_size, double positive_chance, double radius) { - return std::make_shared( - tile_size, positive_chance, radius - ); - }), - "sample", &AlternativeWorleyNoise::get_noise - ); -} -} // namespace generation -} // namespace terrain diff --git a/src/world/terrain/generation/map_tile.hpp b/src/world/terrain/generation/map_tile.hpp index 695b744b..b71b1164 100644 --- a/src/world/terrain/generation/map_tile.hpp +++ b/src/world/terrain/generation/map_tile.hpp @@ -123,7 +123,7 @@ class MapTile { rand_engine_( Noise::get_double((seed ^ tile_type.get_tile_type()) % RANDOM_NUMBER, x, y) * INT32_MAX - ){}; + ) {}; /** * @brief Get the x coordinate @@ -191,7 +191,7 @@ class PlantMap { * * @details Default constructor */ - inline PlantMap() : width_(0), height_(0){}; + inline PlantMap() : width_(0), height_(0) {}; /** * @brief Construct a new PlantMap object diff --git a/src/world/terrain/generation/mat_tile.cpp b/src/world/terrain/generation/mat_tile.cpp index 3949c1cf..4f971c20 100644 --- a/src/world/terrain/generation/mat_tile.cpp +++ b/src/world/terrain/generation/mat_tile.cpp @@ -9,9 +9,7 @@ TileType::TileType( const std::unordered_set land_generators, MapTile_t tile_type, const std::vector& layer_effect_generators, const std::unordered_map materials -) : - land_generators_(land_generators), - tile_type_(tile_type) { +) : land_generators_(land_generators), tile_type_(tile_type) { Dim max_height = 0; ColorId stamp_color_id = 0; diff --git a/src/world/terrain/generation/noise.cpp b/src/world/terrain/generation/noise.cpp index 60c7cc64..4ba8aa12 100644 --- a/src/world/terrain/generation/noise.cpp +++ b/src/world/terrain/generation/noise.cpp @@ -38,8 +38,9 @@ Noise::get_double(size_t i, NoiseTileIndex x, NoiseTileIndex y) { } double -generation::FractalNoise::smoothed_noise_(size_t i, NoiseTileIndex x, NoiseTileIndex y) - const { +generation::FractalNoise::smoothed_noise_( + size_t i, NoiseTileIndex x, NoiseTileIndex y +) const { // clang-format off double corners = (get_double(i, x - 1, y - 1) + get_double(i, x + 1, y - 1) diff --git a/src/world/terrain/generation/noise.hpp b/src/world/terrain/generation/noise.hpp index 72dd4eac..3fb749da 100644 --- a/src/world/terrain/generation/noise.hpp +++ b/src/world/terrain/generation/noise.hpp @@ -23,6 +23,9 @@ namespace terrain { namespace generation { class Noise { + private: + size_t ref_count = 1; + protected: // The length of Noise::primes static constexpr uint16_t NUM_PRIMES = 10; @@ -57,6 +60,20 @@ class Noise { } virtual ~Noise() {} + + // TODO what I want to do is create some sort of template that does this for me + // Also might want the reference counter to be mutable in the template; + inline void + add_ref() { + ref_count++; + } + + inline void + release_ref() { + if (--ref_count == 0) { + delete this; + } + } }; template @@ -66,14 +83,16 @@ concept NoiseGenerator = std::is_base_of::value; * @brief Generates two dimensional Perlin noise. * * @details FractalNoise generates two dimensional Perlin noise with cosine - * interpolation, and geometric persistance. The noise consists of different + * interpolation, and geometric persistence. The noise consists of different * layers. The first layer is between -1, and 1. Subsequent have twice the - * frequency, and amplitude of persistance times the previous amplitude. + * frequency, and amplitude of persistence times the previous amplitude. */ class FractalNoise : protected Noise { - int num_octaves_ = 7; - double persistence_ = 0.5; - int primeIndex_ = 0; + int num_octaves_; + double persistence_; + int primeIndex_; + + size_t ref_count = 1; public: /** @@ -96,6 +115,9 @@ class FractalNoise : protected Noise { */ virtual double get_noise(NoisePosition x, NoisePosition y) const override; + using Noise::add_ref; + using Noise::release_ref; + private: double smoothed_noise_(size_t i, NoiseTileIndex x, NoiseTileIndex y) const; // cosine interpolation diff --git a/src/world/terrain/generation/terrain_genreration_types.hpp b/src/world/terrain/generation/terrain_genreration_types.hpp index a24b4f13..ed2251f4 100644 --- a/src/world/terrain/generation/terrain_genreration_types.hpp +++ b/src/world/terrain/generation/terrain_genreration_types.hpp @@ -146,22 +146,22 @@ struct glz::meta { // error with glaze // when using optional glaze causes compiler errors and this suppresses those errors template <> -inline glz::detail::any_t::operator terrain::generation::stamp_generation_grid_data_t( -) const { +inline glz::detail::any_t:: +operator terrain::generation::stamp_generation_grid_data_t() const { assert(false && "Not Implemented"); return {}; } template <> -inline glz::detail::any_t::operator terrain::generation:: - stamp_generation_position_data_t() const { +inline glz::detail::any_t:: +operator terrain::generation::stamp_generation_position_data_t() const { assert(false && "Not Implemented"); return {}; } template <> -inline glz::detail::any_t::operator terrain::generation::stamp_generation_radius_data_t( -) const { +inline glz::detail::any_t:: +operator terrain::generation::stamp_generation_radius_data_t() const { assert(false && "Not Implemented"); return {}; } diff --git a/src/world/terrain/generation/terrain_map.hpp b/src/world/terrain/generation/terrain_map.hpp index a401a91c..4d98702a 100644 --- a/src/world/terrain/generation/terrain_map.hpp +++ b/src/world/terrain/generation/terrain_map.hpp @@ -23,7 +23,7 @@ class TerrainMacroMap { * * @details default constructor */ - inline TerrainMacroMap() : width_(0), height_(0){}; + inline TerrainMacroMap() : width_(0), height_(0) {}; /** * @brief Create a new TerrainMacroMap @@ -34,9 +34,7 @@ class TerrainMacroMap { */ inline TerrainMacroMap( std::vector terrain_map, size_t width, size_t height - ) : - width_(width), - height_(height), terrain_map_(terrain_map) { + ) : width_(width), height_(height), terrain_map_(terrain_map) { assert(terrain_map_.size() == width_ * height_); }; @@ -133,8 +131,8 @@ class TerrainMapRepresentation { const TerrainMacroMap& map, unsigned int tile_size = 4, unsigned int tile_border = 1 ) : - terrain_map_(map), - tile_size_in_pixels_(tile_size), tile_border_size_(tile_border) {} + terrain_map_(map), tile_size_in_pixels_(tile_size), + tile_border_size_(tile_border) {} [[nodiscard]] inline size_t get_height() const { diff --git a/src/world/terrain/generation/worley_noise.cpp b/src/world/terrain/generation/worley_noise.cpp index 6ec9081e..3688362b 100644 --- a/src/world/terrain/generation/worley_noise.cpp +++ b/src/world/terrain/generation/worley_noise.cpp @@ -33,8 +33,9 @@ WorleyNoise::get_noise(NoisePosition x, NoisePosition y) const { } std::set -WorleyNoise::get_points_(NoiseTileIndex xt, NoiseTileIndex yt, NoiseTileIndex range) - const { +WorleyNoise::get_points_( + NoiseTileIndex xt, NoiseTileIndex yt, NoiseTileIndex range +) const { // assert(range % 2 == 0 && "range must be even"); std::set out; // compute index of worley tile diff --git a/src/world/terrain/generation/worley_noise.hpp b/src/world/terrain/generation/worley_noise.hpp index b0afc454..992a5981 100644 --- a/src/world/terrain/generation/worley_noise.hpp +++ b/src/world/terrain/generation/worley_noise.hpp @@ -80,7 +80,7 @@ class WorleyNoise : protected Noise { * @details Default constructor sets tile_size to 1; */ inline WorleyNoise(NoisePosition tile_size, NoisePosition point_radius) : - tile_size_(tile_size), point_radius_(point_radius){}; + tile_size_(tile_size), point_radius_(point_radius) {}; /** * @brief Get the noise value at given position. @@ -88,6 +88,9 @@ class WorleyNoise : protected Noise { [[nodiscard]] virtual double get_noise(NoisePosition x, NoisePosition y) const override; + using Noise::add_ref; + using Noise::release_ref; + protected: [[nodiscard]] std::set get_points_(NoiseTileIndex x_t, NoiseTileIndex y_t, NoiseTileIndex range) const; @@ -112,14 +115,16 @@ class AlternativeWorleyNoise : public WorleyNoise { */ inline AlternativeWorleyNoise( NoisePosition tile_size, double positive_chance, NoisePosition radius - ) : - WorleyNoise(tile_size, radius) { + ) : WorleyNoise(tile_size, radius) { positive_chance_ = positive_chance; } [[nodiscard]] virtual double get_noise(NoisePosition x, NoisePosition y) const override; + using WorleyNoise::add_ref; + using WorleyNoise::release_ref; + private: [[nodiscard]] double modified_cos_(NoisePosition distance, NoisePosition effective_radius) const; diff --git a/src/world/terrain/material.cpp b/src/world/terrain/material.cpp index 3fa8cda9..dae86c6c 100644 --- a/src/world/terrain/material.cpp +++ b/src/world/terrain/material.cpp @@ -79,9 +79,9 @@ MaterialGroup::insert( return false; } -MaterialGroup::MaterialGroup(const std::vector& data -) : - contain_all_materials(false) { +MaterialGroup::MaterialGroup( + const std::vector& data +) : contain_all_materials(false) { // want to generated a group that represents the given data // There will be elements with no requirements on the color // materials_no_color_requirement_ diff --git a/src/world/terrain/material.hpp b/src/world/terrain/material.hpp index 2ebdb9e1..c1ae6f65 100644 --- a/src/world/terrain/material.hpp +++ b/src/world/terrain/material.hpp @@ -199,9 +199,9 @@ class MaterialGroup { * * @details Default constructor. Nothing will be in the group. */ - inline MaterialGroup() : contain_all_materials(false){}; + inline MaterialGroup() : contain_all_materials(false) {}; - inline MaterialGroup(bool all_materials) : contain_all_materials(all_materials){}; + inline MaterialGroup(bool all_materials) : contain_all_materials(all_materials) {}; /** * @brief Construct new MaterialGroup object. @@ -215,9 +215,8 @@ class MaterialGroup { std::unordered_set materials, std::unordered_map> materials_w_color ) : - contain_all_materials(false), - materials_no_color_requirement_(materials), - materials_with_color_requirement_(materials_w_color){}; + contain_all_materials(false), materials_no_color_requirement_(materials), + materials_with_color_requirement_(materials_w_color) {}; /** * @brief Read the materials and colors that this stamp can overwrite in @@ -342,7 +341,8 @@ struct glz::meta { }; template <> -inline glz::detail::any_t::operator terrain::grass_data_t() const { +inline glz::detail::any_t:: +operator terrain::grass_data_t() const { assert(false && "Not Implemented"); return {}; } diff --git a/src/world/terrain/path/node.hpp b/src/world/terrain/path/node.hpp index eb798d24..903ea9c6 100644 --- a/src/world/terrain/path/node.hpp +++ b/src/world/terrain/path/node.hpp @@ -59,12 +59,12 @@ class Node { // Used to find paths. */ Node(T* tile, float hc) : tile_(tile), parent_node_(nullptr), g_cost_(0), h_cost_(hc), - f_cost_(g_cost_ + h_cost_), explored_(false){}; + f_cost_(g_cost_ + h_cost_), explored_(false) {}; /** * @brief Construct a new Node object (default initializer) * @deprecated should not be used */ - Node() : Node(nullptr, 0){}; + Node() : Node(nullptr, 0) {}; /** * @brief Explore this node diff --git a/src/world/terrain/path/node_group.cpp b/src/world/terrain/path/node_group.cpp index 17051968..c448722e 100644 --- a/src/world/terrain/path/node_group.cpp +++ b/src/world/terrain/path/node_group.cpp @@ -9,8 +9,8 @@ namespace terrain { NodeGroup::NodeGroup( ChunkPos chunk_position, LocalPosition tile_position, UnitPath path_type ) : - chunk_position_(chunk_position), - path_type_(path_type), tile_positions_({tile_position}), center_x(tile_position.x), + chunk_position_(chunk_position), path_type_(path_type), + tile_positions_({tile_position}), center_x(tile_position.x), center_y(tile_position.y), center_z(tile_position.z) {} void diff --git a/src/world/terrain/path/node_wrappers.hpp b/src/world/terrain/path/node_wrappers.hpp index bc347f8f..4a39ac3a 100644 --- a/src/world/terrain/path/node_wrappers.hpp +++ b/src/world/terrain/path/node_wrappers.hpp @@ -8,7 +8,7 @@ class PositionWrapper { TerrainOffset3 position_; public: - inline PositionWrapper(){}; + inline PositionWrapper() {}; inline PositionWrapper(TerrainOffset3 position) : position_(position) {} diff --git a/src/world/terrain/path/tile_iterator.cpp b/src/world/terrain/path/tile_iterator.cpp index 4b06a075..a1bbd449 100644 --- a/src/world/terrain/path/tile_iterator.cpp +++ b/src/world/terrain/path/tile_iterator.cpp @@ -59,8 +59,8 @@ get_indexed_offsets(uint8_t index) { AdjacentIterator::AdjacentIterator( const Terrain& parent, TerrainOffset3 xyz, UnitPath path_type ) : - parent_(parent), - path_type_constraint_(path_type), pos_(xyz), path_type_(0), dpos_(0) { + parent_(parent), path_type_constraint_(path_type), pos_(xyz), path_type_(0), + dpos_(0) { update_path(); if (!path_type_.compatible(path_type_constraint_) || !is_valid_end_position()) { iterate_to_next_available(); diff --git a/src/world/terrain/terrain.cpp b/src/world/terrain/terrain.cpp index 198d784b..7447f23a 100644 --- a/src/world/terrain/terrain.cpp +++ b/src/world/terrain/terrain.cpp @@ -82,9 +82,8 @@ Terrain::Terrain( TerrainOffset z, const generation::Biome& biome, generation::TerrainMacroMap macro_map ) : - area_size_(area_size_), - biome_(biome), X_MAX(x_map_tiles * area_size_), Y_MAX(y_map_tiles * area_size_), - Z_MAX(z) { + area_size_(area_size_), biome_(biome), X_MAX(x_map_tiles * area_size_), + Y_MAX(y_map_tiles * area_size_), Z_MAX(z) { // srand(seed); LOG_INFO(logging::terrain_logger, "Start of land generator."); @@ -174,7 +173,8 @@ Terrain::qb_read( if (color == 0) { // if the qb voxel is transparent. mat_color = &materials_inverse.at(0); // set the materials to air - } else if (materials_inverse.count(color + } else if (materials_inverse.count( + color )) { // if the color is known mat_color = &materials_inverse.at(color); } else { // the color is unknown @@ -191,6 +191,7 @@ Terrain::qb_read( } }); } + // TODO instead of waiting should collect futures context.wait_for_tasks(); for (ColorInt color : unknown_colors) { @@ -545,11 +546,13 @@ Terrain::set_tile_material( } ColorId -Terrain::natural_color(TerrainOffset3 xyz, const material_t* mat, ColorId color_id) - const { +Terrain::natural_color( + TerrainOffset3 xyz, const material_t* mat, ColorId color_id +) const { auto mat_id = mat->material_id; if (mat_id == DIRT_ID) { // being set to dirt - // adds striations to the dirt. (This should be done by lua in the future) + // adds striations to the dirt. (This should be done by angelscript in the + // future) color_id = (xyz.z + (xyz.x / 16 + xyz.y / 16) % 2) / 3 % 2 + NUM_GRASS; } diff --git a/src/world/terrain/terrain.hpp b/src/world/terrain/terrain.hpp index 902deda5..2fb9aa9b 100644 --- a/src/world/terrain/terrain.hpp +++ b/src/world/terrain/terrain.hpp @@ -641,8 +641,8 @@ class Terrain : public voxel_utility::VoxelBase { * @return true can stand * @return false cannot stand */ - [[nodiscard]] bool can_stand_1(TerrainOffset3 xyz - ) const; // this might be faster, and used for looping + [[nodiscard]] bool + can_stand_1(TerrainOffset3 xyz) const; // this might be faster, and used for looping /** * @brief test if dxy x dyx x dz object can stand at given position diff --git a/src/world/terrain/terrain_helper-impls.cpp b/src/world/terrain/terrain_helper-impls.cpp index 8a1bf059..4727d895 100644 --- a/src/world/terrain/terrain_helper-impls.cpp +++ b/src/world/terrain/terrain_helper-impls.cpp @@ -36,12 +36,14 @@ namespace terrain { // implementations of start of iteration template void helper::grow_grass_recursive< - helper::edge_detector_low, helper::getter_low, - helper::setter_low>(Terrain&, std::unordered_set); + helper::edge_detector_low, helper::getter_low, helper::setter_low>( + Terrain&, std::unordered_set +); template void helper::grow_grass_recursive< - helper::edge_detector_high, helper::getter_high, - helper::setter_high>(Terrain&, std::unordered_set); + helper::edge_detector_high, helper::getter_high, helper::setter_high>( + Terrain&, std::unordered_set +); // implementations of inner recursive loop template void helper::grow_grass_inner( diff --git a/src/world/terrain/terrain_helper.cpp b/src/world/terrain/terrain_helper.cpp index 0ad8a073..d758f548 100644 --- a/src/world/terrain/terrain_helper.cpp +++ b/src/world/terrain/terrain_helper.cpp @@ -20,7 +20,7 @@ namespace helper { * given a set of grass tiles gets the adjacent grass tiles that have height * equal to given hight. Then next to those tiles set the grass height to * hight-1 if this is higher than the saved height. -*/ + */ template void grow_grass_inner( diff --git a/src/world/world.cpp b/src/world/world.cpp index a41c737c..e7f74f4d 100644 --- a/src/world/world.cpp +++ b/src/world/world.cpp @@ -22,19 +22,15 @@ #include "world.hpp" -#include "glm/gtx/transform.hpp" #include "global_context.hpp" #include "logging.hpp" #include "manifest/object_handler.hpp" -#include "object/entity/tile_object.hpp" #include "terrain/generation/map_tile.hpp" #include "terrain/material.hpp" #include "terrain/terrain.hpp" -#include "util/files.hpp" #include "util/mesh.hpp" #include -#include #include #include @@ -49,8 +45,8 @@ World::World( manifest::ObjectHandler* object_handler, const std::string& biome_name, const std::string& path, size_t seed ) : - biome_(biome_name, seed), - terrain_main_(path, biome_), controller_(object_handler) {} + biome_(biome_name, seed), terrain_main_(path, biome_), controller_(object_handler) { +} World::World( manifest::ObjectHandler* object_handler, const std::string& biome_name, @@ -58,8 +54,7 @@ World::World( ) : biome_(biome_name, seed), terrain_main_( - x_tiles, y_tiles, macro_tile_size, height, biome_, - std::move(biome_.get_map(x_tiles)) + x_tiles, y_tiles, macro_tile_size, height, biome_, biome_.get_map(x_tiles) ), controller_(object_handler) {} @@ -151,8 +146,9 @@ void World::update_marked_chunks_mesh() { for (auto chunk_pos : chunks_to_update_) { GlobalContext& context = GlobalContext::instance(); - context.submit_task([this, chunk_pos]() { this->update_single_mesh(chunk_pos); } - ); + context.submit_task([this, chunk_pos]() { + this->update_single_mesh(chunk_pos); + }); } chunks_to_update_.clear(); } @@ -231,8 +227,9 @@ World::remove_entity(std::shared_ptr entity) { } std::optional> -World::pathfind_to_object(TerrainOffset3 start_position, const std::string& object_id) - const { +World::pathfind_to_object( + TerrainOffset3 start_position, const std::string& object_id +) const { auto object = get_object_handler()->get_object(object_id); if (!object) { LOG_WARNING(logging::terrain_logger, "Object {} not found.", object_id); diff --git a/src/world/world.hpp b/src/world/world.hpp index e749c16f..45242de9 100644 --- a/src/world/world.hpp +++ b/src/world/world.hpp @@ -26,7 +26,6 @@ #include "gui/render/structures/terrain_mesh.hpp" #include "manifest/object_handler.hpp" #include "object/entity/entity.hpp" -#include "object/entity/tile_object.hpp" #include "object/entity_controller.hpp" #include "terrain/material.hpp" #include "terrain/terrain.hpp" @@ -99,7 +98,7 @@ class World { /** * @brief Get object handler */ - const auto + auto get_object_handler() const { return controller_.get_object_handler(); } diff --git a/vendor/angelscript b/vendor/angelscript new file mode 160000 index 00000000..629ed800 --- /dev/null +++ b/vendor/angelscript @@ -0,0 +1 @@ +Subproject commit 629ed8008f68d12c2b8205e4c6f1c18a4e850fbe diff --git a/vendor/sol2 b/vendor/sol2 deleted file mode 160000 index 9c882a28..00000000 --- a/vendor/sol2 +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 9c882a28fdb6f4ad79a53a4191b43ce48a661175