diff --git a/src/assets/Assets.hpp b/src/assets/Assets.hpp index d30f8187..9a678462 100644 --- a/src/assets/Assets.hpp +++ b/src/assets/Assets.hpp @@ -1,29 +1,21 @@ #ifndef ASSETS_ASSETS_HPP_ #define ASSETS_ASSETS_HPP_ -#include "../graphics/core/TextureAnimation.hpp" - -#include -#include -#include -#include #include -#include +#include +#include +#include +#include #include #include +#include #include +#include "../graphics/core/TextureAnimation.hpp" + class Assets; -enum class AssetType { - TEXTURE, - SHADER, - FONT, - ATLAS, - LAYOUT, - SOUND, - MODEL -}; +enum class AssetType { TEXTURE, SHADER, FONT, ATLAS, LAYOUT, SOUND, MODEL }; namespace assetload { /// @brief final work to do in the main thread @@ -31,7 +23,7 @@ namespace assetload { using setupfunc = std::function; - template + template void assets_setup(const Assets*); class error : public std::runtime_error { @@ -39,12 +31,11 @@ namespace assetload { std::string filename; std::string reason; public: - error( - AssetType type, std::string filename, std::string reason - ) : std::runtime_error(filename + ": " + reason), - type(type), - filename(std::move(filename)), - reason(std::move(reason)) { + error(AssetType type, std::string filename, std::string reason) + : std::runtime_error(filename + ": " + reason), + type(type), + filename(std::move(filename)), + reason(std::move(reason)) { } AssetType getAssetType() const { @@ -75,12 +66,12 @@ public: const std::vector& getAnimations(); void store(const TextureAnimation& animation); - template + template void store(std::unique_ptr asset, const std::string& name) { assets[typeid(T)][name].reset(asset.release()); } - template + template T* get(const std::string& name) const { const auto& mapIter = assets.find(typeid(T)); if (mapIter == assets.end()) { @@ -94,7 +85,7 @@ public: return static_cast(found->second.get()); } - template + template std::optional getMap() const { const auto& mapIter = assets.find(typeid(T)); if (mapIter == assets.end()) { @@ -114,7 +105,7 @@ public: } }; -template +template void assetload::assets_setup(const Assets* assets) { if (auto mapPtr = assets->getMap()) { for (const auto& entry : **mapPtr) { @@ -123,4 +114,4 @@ void assetload::assets_setup(const Assets* assets) { } } -#endif // ASSETS_ASSETS_HPP_ +#endif // ASSETS_ASSETS_HPP_ diff --git a/src/assets/AssetsLoader.cpp b/src/assets/AssetsLoader.cpp index 87ef0454..84ed2894 100644 --- a/src/assets/AssetsLoader.cpp +++ b/src/assets/AssetsLoader.cpp @@ -1,30 +1,29 @@ #include "AssetsLoader.hpp" -#include "Assets.hpp" -#include "assetload_funcs.hpp" -#include "../util/ThreadPool.hpp" -#include "../constants.hpp" -#include "../data/dynamic.hpp" -#include "../debug/Logger.hpp" -#include "../coders/imageio.hpp" -#include "../files/files.hpp" -#include "../files/engine_paths.hpp" -#include "../content/Content.hpp" -#include "../content/ContentPack.hpp" -#include "../voxels/Block.hpp" -#include "../objects/rigging.hpp" -#include "../graphics/core/Texture.hpp" -#include "../logic/scripting/scripting.hpp" - #include #include #include +#include "../coders/imageio.hpp" +#include "../constants.hpp" +#include "../content/Content.hpp" +#include "../content/ContentPack.hpp" +#include "../data/dynamic.hpp" +#include "../debug/Logger.hpp" +#include "../files/engine_paths.hpp" +#include "../files/files.hpp" +#include "../graphics/core/Texture.hpp" +#include "../logic/scripting/scripting.hpp" +#include "../objects/rigging.hpp" +#include "../util/ThreadPool.hpp" +#include "../voxels/Block.hpp" +#include "Assets.hpp" +#include "assetload_funcs.hpp" + static debug::Logger logger("assets-loader"); -AssetsLoader::AssetsLoader(Assets* assets, const ResPaths* paths) - : assets(assets), paths(paths) -{ +AssetsLoader::AssetsLoader(Assets* assets, const ResPaths* paths) + : assets(assets), paths(paths) { addLoader(AssetType::SHADER, assetload::shader); addLoader(AssetType::TEXTURE, assetload::texture); addLoader(AssetType::FONT, assetload::font); @@ -38,8 +37,13 @@ void AssetsLoader::addLoader(AssetType tag, aloader_func func) { loaders[tag] = std::move(func); } -void AssetsLoader::add(AssetType tag, const std::string& filename, const std::string& alias, std::shared_ptr settings) { - entries.push(aloader_entry{tag, filename, alias, std::move(settings)}); +void AssetsLoader::add( + AssetType tag, + const std::string& filename, + const std::string& alias, + std::shared_ptr settings +) { + entries.push(aloader_entry {tag, filename, alias, std::move(settings)}); } bool AssetsLoader::hasNext() const { @@ -50,7 +54,7 @@ aloader_func AssetsLoader::getLoader(AssetType tag) { auto found = loaders.find(tag); if (found == loaders.end()) { throw std::runtime_error( - "unknown asset tag "+std::to_string(static_cast(tag)) + "unknown asset tag " + std::to_string(static_cast(tag)) ); } return found->second; @@ -61,7 +65,8 @@ void AssetsLoader::loadNext() { logger.info() << "loading " << entry.filename << " as " << entry.alias; try { aloader_func loader = getLoader(entry.tag); - auto postfunc = loader(this, paths, entry.filename, entry.alias, entry.config); + auto postfunc = + loader(this, paths, entry.filename, entry.alias, entry.config); postfunc(assets); entries.pop(); } catch (std::runtime_error& err) { @@ -74,16 +79,25 @@ void AssetsLoader::loadNext() { } } -void addLayouts(const scriptenv& env, const std::string& prefix, const fs::path& folder, AssetsLoader& loader) { +void addLayouts( + const scriptenv& env, + const std::string& prefix, + const fs::path& folder, + AssetsLoader& loader +) { if (!fs::is_directory(folder)) { return; } for (auto& entry : fs::directory_iterator(folder)) { const fs::path& file = entry.path(); - if (file.extension().u8string() != ".xml") - continue; - std::string name = prefix+":"+file.stem().u8string(); - loader.add(AssetType::LAYOUT, file.u8string(), name, std::make_shared(env)); + if (file.extension().u8string() != ".xml") continue; + std::string name = prefix + ":" + file.stem().u8string(); + loader.add( + AssetType::LAYOUT, + file.u8string(), + name, + std::make_shared(env) + ); } } @@ -91,30 +105,35 @@ void AssetsLoader::tryAddSound(const std::string& name) { if (name.empty()) { return; } - std::string file = SOUNDS_FOLDER+"/"+name; + std::string file = SOUNDS_FOLDER + "/" + name; add(AssetType::SOUND, file, name); } static std::string assets_def_folder(AssetType tag) { switch (tag) { - case AssetType::FONT: return FONTS_FOLDER; - case AssetType::SHADER: return SHADERS_FOLDER; - case AssetType::TEXTURE: return TEXTURES_FOLDER; - case AssetType::ATLAS: return TEXTURES_FOLDER; - case AssetType::LAYOUT: return LAYOUTS_FOLDER; - case AssetType::SOUND: return SOUNDS_FOLDER; - case AssetType::MODEL: return MODELS_FOLDER; + case AssetType::FONT: + return FONTS_FOLDER; + case AssetType::SHADER: + return SHADERS_FOLDER; + case AssetType::TEXTURE: + return TEXTURES_FOLDER; + case AssetType::ATLAS: + return TEXTURES_FOLDER; + case AssetType::LAYOUT: + return LAYOUTS_FOLDER; + case AssetType::SOUND: + return SOUNDS_FOLDER; + case AssetType::MODEL: + return MODELS_FOLDER; } return ""; } void AssetsLoader::processPreload( - AssetType tag, - const std::string& name, - dynamic::Map* map + AssetType tag, const std::string& name, dynamic::Map* map ) { std::string defFolder = assets_def_folder(tag); - std::string path = defFolder+"/"+name; + std::string path = defFolder + "/" + name; if (map == nullptr) { add(tag, path, name); return; @@ -122,9 +141,10 @@ void AssetsLoader::processPreload( map->str("path", path); switch (tag) { case AssetType::SOUND: - add(tag, path, name, std::make_shared( - map->get("keep-pcm", false) - )); + add(tag, + path, + name, + std::make_shared(map->get("keep-pcm", false))); break; default: add(tag, path, name); @@ -166,7 +186,7 @@ void AssetsLoader::processPreloadConfig(const fs::path& file) { } void AssetsLoader::processPreloadConfigs(const Content* content) { - auto preloadFile = paths->getMainRoot()/fs::path("preload.json"); + auto preloadFile = paths->getMainRoot() / fs::path("preload.json"); if (fs::exists(preloadFile)) { processPreloadConfig(preloadFile); } @@ -192,7 +212,12 @@ void AssetsLoader::addDefaults(AssetsLoader& loader, const Content* content) { loader.tryAddSound(material.breakSound); } - addLayouts(0, "core", loader.getPaths()->getMainRoot()/fs::path("layouts"), loader); + addLayouts( + 0, + "core", + loader.getPaths()->getMainRoot() / fs::path("layouts"), + loader + ); for (auto& entry : content->getPacks()) { auto pack = entry.second.get(); auto& info = pack->getInfo(); @@ -205,7 +230,9 @@ void AssetsLoader::addDefaults(AssetsLoader& loader, const Content* content) { for (auto& bone : skeleton.getBones()) { auto& model = bone->model.name; if (!model.empty()) { - loader.add(AssetType::MODEL, MODELS_FOLDER+"/"+model, model); + loader.add( + AssetType::MODEL, MODELS_FOLDER + "/" + model, model + ); } } } @@ -227,8 +254,8 @@ bool AssetsLoader::loadExternalTexture( assets->store(Texture::from(image.get()), name); return true; } catch (const std::exception& err) { - logger.error() << "error while loading external " - << path.u8string() << ": " << err.what(); + logger.error() << "error while loading external " + << path.u8string() << ": " << err.what(); } } } @@ -245,22 +272,26 @@ public: LoaderWorker(AssetsLoader* loader) : loader(loader) { } - assetload::postfunc operator()(const std::shared_ptr& entry) override { + assetload::postfunc operator()(const std::shared_ptr& entry + ) override { aloader_func loadfunc = loader->getLoader(entry->tag); - return loadfunc(loader, loader->getPaths(), entry->filename, entry->alias, entry->config); + return loadfunc( + loader, + loader->getPaths(), + entry->filename, + entry->alias, + entry->config + ); } }; std::shared_ptr AssetsLoader::startTask(runnable onDone) { - auto pool = std::make_shared< - util::ThreadPool - >( - "assets-loader-pool", - [=](){return std::make_shared(this);}, - [=](assetload::postfunc& func) { - func(assets); - } - ); + auto pool = + std::make_shared>( + "assets-loader-pool", + [=]() { return std::make_shared(this); }, + [=](assetload::postfunc& func) { func(assets); } + ); pool->setOnComplete(std::move(onDone)); while (!entries.empty()) { const aloader_entry& entry = entries.front(); diff --git a/src/assets/AssetsLoader.hpp b/src/assets/AssetsLoader.hpp index 65ab30fe..09dd4b7f 100644 --- a/src/assets/AssetsLoader.hpp +++ b/src/assets/AssetsLoader.hpp @@ -1,19 +1,19 @@ #ifndef ASSETS_ASSETS_LOADER_HPP_ #define ASSETS_ASSETS_LOADER_HPP_ -#include "Assets.hpp" -#include "../interfaces/Task.hpp" -#include "../typedefs.hpp" -#include "../delegates.hpp" - -#include -#include #include #include #include +#include #include +#include #include +#include "../delegates.hpp" +#include "../interfaces/Task.hpp" +#include "../typedefs.hpp" +#include "Assets.hpp" + namespace dynamic { class Map; class List; @@ -24,28 +24,27 @@ class AssetsLoader; class Content; struct AssetCfg { - virtual ~AssetCfg() {} + virtual ~AssetCfg() { + } }; struct LayoutCfg : AssetCfg { scriptenv env; - LayoutCfg(scriptenv env) : env(std::move(env)) {} + LayoutCfg(scriptenv env) : env(std::move(env)) { + } }; struct SoundCfg : AssetCfg { bool keepPCM; - - SoundCfg(bool keepPCM) : keepPCM(keepPCM) {} + + SoundCfg(bool keepPCM) : keepPCM(keepPCM) { + } }; -using aloader_func = std::function) ->; +using aloader_func = std::function< + assetload:: + postfunc(AssetsLoader*, const ResPaths*, const std::string&, const std::string&, std::shared_ptr)>; struct aloader_entry { AssetType tag; @@ -62,7 +61,9 @@ class AssetsLoader { void tryAddSound(const std::string& name); - void processPreload(AssetType tag, const std::string& name, dynamic::Map* map); + void processPreload( + AssetType tag, const std::string& name, dynamic::Map* map + ); void processPreloadList(AssetType tag, dynamic::List* list); void processPreloadConfig(const std::filesystem::path& file); void processPreloadConfigs(const Content* content); @@ -76,12 +77,12 @@ public: /// @param alias internal asset name /// @param settings asset loading settings (based on asset type) void add( - AssetType tag, + AssetType tag, const std::string& filename, const std::string& alias, - std::shared_ptr settings=nullptr + std::shared_ptr settings = nullptr ); - + bool hasNext() const; /// @throws assetload::error @@ -104,4 +105,4 @@ public: ); }; -#endif // ASSETS_ASSETS_LOADER_HPP_ +#endif // ASSETS_ASSETS_LOADER_HPP_ diff --git a/src/assets/assetload_funcs.cpp b/src/assets/assetload_funcs.cpp index ccbe3e80..a2ed0d9d 100644 --- a/src/assets/assetload_funcs.cpp +++ b/src/assets/assetload_funcs.cpp @@ -1,30 +1,30 @@ #include "assetload_funcs.hpp" -#include "Assets.hpp" -#include "AssetsLoader.hpp" -#include "../data/dynamic.hpp" +#include +#include +#include + #include "../audio/audio.hpp" -#include "../files/files.hpp" -#include "../files/engine_paths.hpp" +#include "../coders/GLSLExtension.hpp" #include "../coders/commons.hpp" #include "../coders/imageio.hpp" #include "../coders/json.hpp" #include "../coders/obj.hpp" -#include "../coders/GLSLExtension.hpp" -#include "../graphics/core/Shader.hpp" -#include "../graphics/core/Texture.hpp" -#include "../graphics/core/ImageData.hpp" +#include "../constants.hpp" +#include "../data/dynamic.hpp" +#include "../files/engine_paths.hpp" +#include "../files/files.hpp" +#include "../frontend/UiDocument.hpp" #include "../graphics/core/Atlas.hpp" #include "../graphics/core/Font.hpp" +#include "../graphics/core/ImageData.hpp" #include "../graphics/core/Model.hpp" +#include "../graphics/core/Shader.hpp" +#include "../graphics/core/Texture.hpp" #include "../graphics/core/TextureAnimation.hpp" #include "../objects/rigging.hpp" -#include "../frontend/UiDocument.hpp" -#include "../constants.hpp" - -#include -#include -#include +#include "Assets.hpp" +#include "AssetsLoader.hpp" namespace fs = std::filesystem; @@ -37,43 +37,38 @@ static bool animation( Atlas* dstAtlas ); -assetload::postfunc assetload::texture( - AssetsLoader*, - const ResPaths* paths, - const std::string& filename, - const std::string& name, - const std::shared_ptr& -) { - std::shared_ptr image ( - imageio::read(paths->find(filename+".png").u8string()).release() +assetload::postfunc assetload:: + texture(AssetsLoader*, const ResPaths* paths, const std::string& filename, const std::string& name, const std::shared_ptr&) { + std::shared_ptr image( + imageio::read(paths->find(filename + ".png").u8string()).release() ); return [name, image](auto assets) { assets->store(Texture::from(image.get()), name); }; } -assetload::postfunc assetload::shader( - AssetsLoader*, - const ResPaths* paths, - const std::string& filename, - const std::string& name, - const std::shared_ptr& -) { - fs::path vertexFile = paths->find(filename+".glslv"); - fs::path fragmentFile = paths->find(filename+".glslf"); +assetload::postfunc assetload:: + shader(AssetsLoader*, const ResPaths* paths, const std::string& filename, const std::string& name, const std::shared_ptr&) { + fs::path vertexFile = paths->find(filename + ".glslv"); + fs::path fragmentFile = paths->find(filename + ".glslf"); std::string vertexSource = files::read_string(vertexFile); std::string fragmentSource = files::read_string(fragmentFile); vertexSource = Shader::preprocessor->process(vertexFile, vertexSource); - fragmentSource = Shader::preprocessor->process(fragmentFile, fragmentSource); + fragmentSource = + Shader::preprocessor->process(fragmentFile, fragmentSource); return [=](auto assets) { - assets->store(Shader::create( - vertexFile.u8string(), - fragmentFile.u8string(), - vertexSource, fragmentSource - ), name); + assets->store( + Shader::create( + vertexFile.u8string(), + fragmentFile.u8string(), + vertexSource, + fragmentSource + ), + name + ); }; } @@ -89,19 +84,12 @@ static bool append_atlas(AtlasBuilder& atlas, const fs::path& file) { return true; } -assetload::postfunc assetload::atlas( - AssetsLoader*, - const ResPaths* paths, - const std::string& directory, - const std::string& name, - const std::shared_ptr& -) { +assetload::postfunc assetload:: + atlas(AssetsLoader*, const ResPaths* paths, const std::string& directory, const std::string& name, const std::shared_ptr&) { AtlasBuilder builder; for (const auto& file : paths->listdir(directory)) { - if (!imageio::is_read_supported(file.extension().u8string())) - continue; - if (!append_atlas(builder, file)) - continue; + if (!imageio::is_read_supported(file.extension().u8string())) continue; + if (!append_atlas(builder, file)) continue; } std::set names = builder.getNames(); Atlas* atlas = builder.build(2, false).release(); @@ -114,16 +102,11 @@ assetload::postfunc assetload::atlas( }; } -assetload::postfunc assetload::font( - AssetsLoader*, - const ResPaths* paths, - const std::string& filename, - const std::string& name, - const std::shared_ptr& -) { +assetload::postfunc assetload:: + font(AssetsLoader*, const ResPaths* paths, const std::string& filename, const std::string& name, const std::shared_ptr&) { auto pages = std::make_shared>>(); for (size_t i = 0; i <= 4; i++) { - std::string pagefile = filename + "_" + std::to_string(i) + ".png"; + std::string pagefile = filename + "_" + std::to_string(i) + ".png"; pagefile = paths->find(pagefile).string(); pages->push_back(imageio::read(pagefile)); } @@ -133,7 +116,9 @@ assetload::postfunc assetload::font( for (auto& page : *pages) { textures.emplace_back(Texture::from(page.get())); } - assets->store(std::make_unique(std::move(textures), res, 4), name); + assets->store( + std::make_unique(std::move(textures), res, 4), name + ); }; } @@ -150,7 +135,7 @@ assetload::postfunc assetload::layout( assets->store(UiDocument::read(cfg->env, name, file), name); } catch (const parsing_error& err) { throw std::runtime_error( - "failed to parse layout XML '"+file+"':\n"+err.errorLog() + "failed to parse layout XML '" + file + "':\n" + err.errorLog() ); } }; @@ -171,13 +156,13 @@ assetload::postfunc assetload::sound( for (size_t i = 0; i < extensions.size(); i++) { extension = extensions[i]; // looking for 'sound_name' as base sound - auto soundFile = paths->find(file+extension); + auto soundFile = paths->find(file + extension); if (fs::exists(soundFile)) { baseSound = audio::load_sound(soundFile, keepPCM); break; } // looking for 'sound_name_0' as base sound - auto variantFile = paths->find(file+"_0"+extension); + auto variantFile = paths->find(file + "_0" + extension); if (fs::exists(variantFile)) { baseSound = audio::load_sound(variantFile, keepPCM); break; @@ -188,12 +173,14 @@ assetload::postfunc assetload::sound( } // loading sound variants - for (uint i = 1; ; i++) { - auto variantFile = paths->find(file+"_"+std::to_string(i)+extension); + for (uint i = 1;; i++) { + auto variantFile = + paths->find(file + "_" + std::to_string(i) + extension); if (!fs::exists(variantFile)) { break; } - baseSound->variants.emplace_back(audio::load_sound(variantFile, keepPCM)); + baseSound->variants.emplace_back(audio::load_sound(variantFile, keepPCM) + ); } auto sound = baseSound.release(); @@ -202,22 +189,19 @@ assetload::postfunc assetload::sound( }; } -assetload::postfunc assetload::model( - AssetsLoader* loader, - const ResPaths* paths, - const std::string& file, - const std::string& name, - const std::shared_ptr& -) { - auto path = paths->find(file+".obj"); +assetload::postfunc assetload:: + model(AssetsLoader* loader, const ResPaths* paths, const std::string& file, const std::string& name, const std::shared_ptr&) { + auto path = paths->find(file + ".obj"); auto text = files::read_string(path); try { auto model = obj::parse(path.u8string(), text).release(); return [=](Assets* assets) { for (auto& mesh : model->meshes) { if (mesh.texture.find('$') == std::string::npos) { - auto filename = TEXTURES_FOLDER+"/"+mesh.texture; - loader->add(AssetType::TEXTURE, filename, mesh.texture, nullptr); + auto filename = TEXTURES_FOLDER + "/" + mesh.texture; + loader->add( + AssetType::TEXTURE, filename, mesh.texture, nullptr + ); } } assets->store(std::unique_ptr(model), name); @@ -272,8 +256,10 @@ static TextureAnimation create_animation( const int extension = 2; - frame.dstPos = glm::ivec2(region.u1 * dstWidth, region.v1 * dstHeight) - extension; - frame.size = glm::ivec2(region.u2 * dstWidth, region.v2 * dstHeight) - frame.dstPos + extension; + frame.dstPos = + glm::ivec2(region.u1 * dstWidth, region.v1 * dstHeight) - extension; + frame.size = glm::ivec2(region.u2 * dstWidth, region.v2 * dstHeight) - + frame.dstPos + extension; for (const auto& elem : frameList) { if (!srcAtlas->has(elem.first)) { @@ -284,7 +270,11 @@ static TextureAnimation create_animation( if (elem.second > 0) { frame.duration = static_cast(elem.second) / 1000.0f; } - frame.srcPos = glm::ivec2(region.u1 * srcWidth, srcHeight - region.v2 * srcHeight) - extension; + frame.srcPos = + glm::ivec2( + region.u1 * srcWidth, srcHeight - region.v2 * srcHeight + ) - + extension; animation.addFrame(frame); } return animation; @@ -303,10 +293,10 @@ inline bool contains( } static bool animation( - Assets* assets, + Assets* assets, const ResPaths* paths, - const std::string& atlasName, - const std::string& directory, + const std::string& atlasName, + const std::string& directory, const std::string& name, Atlas* dstAtlas ) { @@ -316,7 +306,7 @@ static bool animation( if (!fs::is_directory(folder)) continue; if (folder.filename().u8string() != name) continue; if (fs::is_empty(folder)) continue; - + AtlasBuilder builder; append_atlas(builder, paths->find(directory + "/" + name + ".png")); @@ -326,11 +316,11 @@ static bool animation( read_anim_file(animFile, frameList); } for (const auto& file : paths->listdir(animsDir + "/" + name)) { - if (!frameList.empty() && !contains(frameList, file.stem().u8string())) { + if (!frameList.empty() && + !contains(frameList, file.stem().u8string())) { continue; } - if (!append_atlas(builder, file)) - continue; + if (!append_atlas(builder, file)) continue; } auto srcAtlas = builder.build(2, true); if (frameList.empty()) { @@ -341,7 +331,9 @@ static bool animation( auto animation = create_animation( srcAtlas.get(), dstAtlas, name, builder.getNames(), frameList ); - assets->store(std::move(srcAtlas), atlasName + "/" + name + "_animation"); + assets->store( + std::move(srcAtlas), atlasName + "/" + name + "_animation" + ); assets->store(animation); return true; } diff --git a/src/assets/assetload_funcs.hpp b/src/assets/assetload_funcs.hpp index 6251ff88..6a88eabc 100644 --- a/src/assets/assetload_funcs.hpp +++ b/src/assets/assetload_funcs.hpp @@ -1,10 +1,10 @@ #ifndef ASSETS_ASSET_LOADERS_HPP_ #define ASSETS_ASSET_LOADERS_HPP_ -#include "Assets.hpp" - -#include #include +#include + +#include "Assets.hpp" class ResPaths; class Assets; @@ -30,7 +30,7 @@ namespace assetload { ); postfunc atlas( AssetsLoader*, - const ResPaths* paths, + const ResPaths* paths, const std::string& directory, const std::string& name, const std::shared_ptr& settings @@ -65,4 +65,4 @@ namespace assetload { ); } -#endif // ASSETS_ASSET_LOADERS_HPP_ +#endif // ASSETS_ASSET_LOADERS_HPP_ diff --git a/src/audio/AL/ALAudio.cpp b/src/audio/AL/ALAudio.cpp index 05cd4c56..4c24c75b 100644 --- a/src/audio/AL/ALAudio.cpp +++ b/src/audio/AL/ALAudio.cpp @@ -1,18 +1,19 @@ #include "ALAudio.hpp" -#include "alutil.hpp" -#include "../../debug/Logger.hpp" - #include #include +#include "../../debug/Logger.hpp" +#include "alutil.hpp" + static debug::Logger logger("al-audio"); using namespace audio; -ALSound::ALSound(ALAudio* al, uint buffer, const std::shared_ptr& pcm, bool keepPCM) -: al(al), buffer(buffer) -{ +ALSound::ALSound( + ALAudio* al, uint buffer, const std::shared_ptr& pcm, bool keepPCM +) + : al(al), buffer(buffer) { duration = pcm->getDuration(); if (keepPCM) { this->pcm = pcm; @@ -36,8 +37,10 @@ std::unique_ptr ALSound::newInstance(int priority, int channel) const { return speaker; } -ALStream::ALStream(ALAudio* al, std::shared_ptr source, bool keepSource) -: al(al), source(std::move(source)), keepSource(keepSource) { +ALStream::ALStream( + ALAudio* al, std::shared_ptr source, bool keepSource +) + : al(al), source(std::move(source)), keepSource(keepSource) { } ALStream::~ALStream() { @@ -60,10 +63,12 @@ std::shared_ptr ALStream::getSource() const { bool ALStream::preloadBuffer(uint buffer, bool loop) { size_t read = source->readFully(this->buffer, BUFFER_SIZE, loop); - if (!read) - return false; - ALenum format = AL::to_al_format(source->getChannels(), source->getBitsPerSample()); - AL_CHECK(alBufferData(buffer, format, this->buffer, read, source->getSampleRate())); + if (!read) return false; + ALenum format = + AL::to_al_format(source->getChannels(), source->getBitsPerSample()); + AL_CHECK(alBufferData( + buffer, format, this->buffer, read, source->getSampleRate() + )); return true; } @@ -83,7 +88,6 @@ std::unique_ptr ALStream::createSpeaker(bool loop, int channel) { return std::make_unique(al, source, PRIORITY_HIGH, channel); } - void ALStream::bindSpeaker(speakerid_t speaker) { auto sp = audio::get_speaker(this->speaker); if (sp) { @@ -110,7 +114,7 @@ void ALStream::unqueueBuffers(uint alsource) { AL_CHECK(alSourceUnqueueBuffers(alsource, 1, &buffer)); unusedBuffers.push(buffer); - uint bps = source->getBitsPerSample()/8; + uint bps = source->getBitsPerSample() / 8; uint channels = source->getChannels(); ALint bufferSize; @@ -151,10 +155,10 @@ void ALStream::update(double delta) { } uint alsource = alspeaker->source; - + unqueueBuffers(alsource); uint preloaded = enqueueBuffers(alsource); - + if (speaker->isStopped() && !alspeaker->stopped) { if (preloaded) { speaker->play(); @@ -166,10 +170,12 @@ void ALStream::update(double delta) { duration_t ALStream::getTime() const { uint total = totalPlayedSamples; - auto alspeaker = dynamic_cast(audio::get_speaker(this->speaker)); + auto alspeaker = + dynamic_cast(audio::get_speaker(this->speaker)); if (alspeaker) { uint alsource = alspeaker->source; - total += static_cast(AL::getSourcef(alsource, AL_SAMPLE_OFFSET)); + total += + static_cast(AL::getSourcef(alsource, AL_SAMPLE_OFFSET)); if (source->isSeekable()) { total %= source->getTotalSamples(); } @@ -178,11 +184,11 @@ duration_t ALStream::getTime() const { } void ALStream::setTime(duration_t time) { - if (!source->isSeekable()) - return; + if (!source->isSeekable()) return; uint sample = time * source->getSampleRate(); source->seek(sample); - auto alspeaker = dynamic_cast(audio::get_speaker(this->speaker)); + auto alspeaker = + dynamic_cast(audio::get_speaker(this->speaker)); if (alspeaker) { bool paused = alspeaker->isPaused(); AL_CHECK(alSourceStop(alspeaker->source)); @@ -198,8 +204,8 @@ void ALStream::setTime(duration_t time) { } } -ALSpeaker::ALSpeaker(ALAudio* al, uint source, int priority, int channel) -: al(al), priority(priority), channel(channel), source(source) { +ALSpeaker::ALSpeaker(ALAudio* al, uint source, int priority, int channel) + : al(al), priority(priority), channel(channel), source(source) { } ALSpeaker::~ALSpeaker() { @@ -209,11 +215,10 @@ ALSpeaker::~ALSpeaker() { } void ALSpeaker::update(const Channel* channel) { - if (source == 0) - return; + if (source == 0) return; float gain = this->volume * channel->getVolume(); AL_CHECK(alSourcef(source, AL_GAIN, gain)); - + if (!paused) { if (isPaused() && !channel->isPaused()) { play(); @@ -230,9 +235,12 @@ int ALSpeaker::getChannel() const { State ALSpeaker::getState() const { int state = AL::getSourcei(source, AL_SOURCE_STATE, AL_STOPPED); switch (state) { - case AL_PLAYING: return State::playing; - case AL_PAUSED: return State::paused; - default: return State::stopped; + case AL_PLAYING: + return State::playing; + case AL_PAUSED: + return State::paused; + default: + return State::stopped; } } @@ -264,7 +272,11 @@ void ALSpeaker::play() { paused = false; stopped = false; auto channel = get_channel(this->channel); - AL_CHECK(alSourcef(source, AL_GAIN, volume * channel->getVolume() * get_channel(0)->getVolume())); + AL_CHECK(alSourcef( + source, + AL_GAIN, + volume * channel->getVolume() * get_channel(0)->getVolume() + )); AL_CHECK(alSourcePlay(source)); } @@ -325,7 +337,9 @@ glm::vec3 ALSpeaker::getVelocity() const { } void ALSpeaker::setRelative(bool relative) { - AL_CHECK(alSourcei(source, AL_SOURCE_RELATIVE, relative ? AL_TRUE : AL_FALSE)); + AL_CHECK( + alSourcei(source, AL_SOURCE_RELATIVE, relative ? AL_TRUE : AL_FALSE) + ); } bool ALSpeaker::isRelative() const { @@ -336,19 +350,17 @@ int ALSpeaker::getPriority() const { return priority; } - ALAudio::ALAudio(ALCdevice* device, ALCcontext* context) -: device(device), context(context) -{ + : device(device), context(context) { ALCint size; alcGetIntegerv(device, ALC_ATTRIBUTES_SIZE, 1, &size); std::vector attrs(size); alcGetIntegerv(device, ALC_ALL_ATTRIBUTES, size, &attrs[0]); - for (size_t i = 0; i < attrs.size(); ++i){ - if (attrs[i] == ALC_MONO_SOURCES) { - logger.info() << "max mono sources: " << attrs[i+1]; - maxSources = attrs[i+1]; - } + for (size_t i = 0; i < attrs.size(); ++i) { + if (attrs[i] == ALC_MONO_SOURCES) { + logger.info() << "max mono sources: " << attrs[i + 1]; + maxSources = attrs[i + 1]; + } } auto devices = getAvailableDevices(); logger.info() << "devices:"; @@ -366,7 +378,7 @@ ALAudio::~ALAudio() { AL_CHECK(alDeleteSources(1, &source)); } - for (uint buffer : allbuffers){ + for (uint buffer : allbuffers) { AL_CHECK(alDeleteBuffers(1, &buffer)); } @@ -379,23 +391,28 @@ ALAudio::~ALAudio() { context = nullptr; } -std::unique_ptr ALAudio::createSound(std::shared_ptr pcm, bool keepPCM) { +std::unique_ptr ALAudio::createSound( + std::shared_ptr pcm, bool keepPCM +) { auto format = AL::to_al_format(pcm->channels, pcm->bitsPerSample); uint buffer = getFreeBuffer(); - AL_CHECK(alBufferData(buffer, format, pcm->data.data(), pcm->data.size(), pcm->sampleRate)); + AL_CHECK(alBufferData( + buffer, format, pcm->data.data(), pcm->data.size(), pcm->sampleRate + )); return std::make_unique(this, buffer, pcm, keepPCM); } -std::unique_ptr ALAudio::openStream(std::shared_ptr stream, bool keepSource) { +std::unique_ptr ALAudio::openStream( + std::shared_ptr stream, bool keepSource +) { return std::make_unique(this, stream, keepSource); } std::unique_ptr ALAudio::create() { ALCdevice* device = alcOpenDevice(nullptr); - if (device == nullptr) - return nullptr; + if (device == nullptr) return nullptr; ALCcontext* context = alcCreateContext(device, nullptr); - if (!alcMakeContextCurrent(context)){ + if (!alcMakeContextCurrent(context)) { alcCloseDevice(device); return nullptr; } @@ -404,14 +421,15 @@ std::unique_ptr ALAudio::create() { return std::make_unique(device, context); } -uint ALAudio::getFreeSource(){ - if (!freesources.empty()){ +uint ALAudio::getFreeSource() { + if (!freesources.empty()) { uint source = freesources.back(); freesources.pop_back(); return source; } - if (allsources.size() == maxSources){ - logger.error() << "attempted to create new source, but limit is " << maxSources; + if (allsources.size() == maxSources) { + logger.error() << "attempted to create new source, but limit is " + << maxSources; return 0; } ALuint id; @@ -423,8 +441,8 @@ uint ALAudio::getFreeSource(){ return id; } -uint ALAudio::getFreeBuffer(){ - if (!freebuffers.empty()){ +uint ALAudio::getFreeBuffer() { + if (!freebuffers.empty()) { uint buffer = freebuffers.back(); freebuffers.pop_back(); return buffer; @@ -439,11 +457,11 @@ uint ALAudio::getFreeBuffer(){ return id; } -void ALAudio::freeSource(uint source){ +void ALAudio::freeSource(uint source) { freesources.push_back(source); } -void ALAudio::freeBuffer(uint buffer){ +void ALAudio::freeBuffer(uint buffer) { freebuffers.push_back(buffer); } @@ -460,14 +478,15 @@ std::vector ALAudio::getAvailableDevices() const { do { devicesVec.emplace_back(ptr); ptr += devicesVec.back().size() + 1; - } - while (ptr[0]); + } while (ptr[0]); return devicesVec; } -void ALAudio::setListener(glm::vec3 position, glm::vec3 velocity, glm::vec3 at, glm::vec3 up){ - ALfloat listenerOri[] = { at.x, at.y, at.z, up.x, up.y, up.z }; +void ALAudio::setListener( + glm::vec3 position, glm::vec3 velocity, glm::vec3 at, glm::vec3 up +) { + ALfloat listenerOri[] = {at.x, at.y, at.z, up.x, up.y, up.z}; AL_CHECK(alListener3f(AL_POSITION, position.x, position.y, position.z)); AL_CHECK(alListener3f(AL_VELOCITY, velocity.x, velocity.y, velocity.z)); diff --git a/src/audio/AL/ALAudio.hpp b/src/audio/AL/ALAudio.hpp index 69d84a0c..63087dd4 100644 --- a/src/audio/AL/ALAudio.hpp +++ b/src/audio/AL/ALAudio.hpp @@ -1,14 +1,14 @@ #ifndef SRC_AUDIO_AUDIO_HPP_ #define SRC_AUDIO_AUDIO_HPP_ -#include "../audio.hpp" -#include "../../typedefs.hpp" - -#include -#include -#include #include +#include +#include #include +#include + +#include "../../typedefs.hpp" +#include "../audio.hpp" #ifdef __APPLE__ #include @@ -29,7 +29,12 @@ namespace audio { std::shared_ptr pcm; duration_t duration; public: - ALSound(ALAudio* al, uint buffer, const std::shared_ptr& pcm, bool keepPCM); + ALSound( + ALAudio* al, + uint buffer, + const std::shared_ptr& pcm, + bool keepPCM + ); ~ALSound(); duration_t getDuration() const override { @@ -40,12 +45,13 @@ namespace audio { return pcm; } - std::unique_ptr newInstance(int priority, int channel) const override; + std::unique_ptr newInstance(int priority, int channel) + const override; }; class ALStream : public Stream { static inline constexpr size_t BUFFER_SIZE = 44100; - + ALAudio* al; std::shared_ptr source; std::queue unusedBuffers; @@ -60,7 +66,9 @@ namespace audio { public: size_t totalPlayedSamples = 0; - ALStream(ALAudio* al, std::shared_ptr source, bool keepSource); + ALStream( + ALAudio* al, std::shared_ptr source, bool keepSource + ); ~ALStream(); std::shared_ptr getSource() const override; @@ -68,11 +76,11 @@ namespace audio { std::unique_ptr createSpeaker(bool loop, int channel) override; speakerid_t getSpeaker() const override; void update(double delta) override; - - duration_t getTime() const override; - void setTime(duration_t time) override; - static inline constexpr uint STREAM_BUFFERS = 3; + duration_t getTime() const override; + void setTime(duration_t time) override; + + static inline constexpr uint STREAM_BUFFERS = 3; }; /// @brief AL source adapter @@ -147,8 +155,12 @@ namespace audio { std::vector getAvailableDevices() const; - std::unique_ptr createSound(std::shared_ptr pcm, bool keepPCM) override; - std::unique_ptr openStream(std::shared_ptr stream, bool keepSource) override; + std::unique_ptr createSound( + std::shared_ptr pcm, bool keepPCM + ) override; + std::unique_ptr openStream( + std::shared_ptr stream, bool keepSource + ) override; void setListener( glm::vec3 position, @@ -158,7 +170,7 @@ namespace audio { ) override; void update(double delta) override; - + bool isDummy() const override { return false; } @@ -167,4 +179,4 @@ namespace audio { }; } -#endif // SRC_AUDIO_AUDIO_HPP_ +#endif // SRC_AUDIO_AUDIO_HPP_ diff --git a/src/audio/AL/alutil.cpp b/src/audio/AL/alutil.cpp index 420aa030..5fca2244 100644 --- a/src/audio/AL/alutil.cpp +++ b/src/audio/AL/alutil.cpp @@ -1,12 +1,12 @@ #include "alutil.hpp" -#include "../../debug/Logger.hpp" - -#include #include +#include #include #include +#include "../../debug/Logger.hpp" + #ifdef __APPLE__ #include #include @@ -17,28 +17,34 @@ static debug::Logger logger("open-al"); -bool AL::check_errors(const std::string& filename, const std::uint_fast32_t line){ +bool AL::check_errors( + const std::string& filename, const std::uint_fast32_t line +) { ALenum error = alGetError(); - if(error != AL_NO_ERROR){ + if (error != AL_NO_ERROR) { logger.error() << filename << ": " << line; - switch(error){ - case AL_INVALID_NAME: - logger.error() << "a bad name (ID) was passed to an OpenAL function"; - break; - case AL_INVALID_ENUM: - logger.error() << "an invalid enum value was passed to an OpenAL function"; - break; - case AL_INVALID_VALUE: - logger.error() << "an invalid value was passed to an OpenAL function"; - break; - case AL_INVALID_OPERATION: - logger.error() << "the requested operation is not valid"; - break; - case AL_OUT_OF_MEMORY: - logger.error() << "the requested operation resulted in OpenAL running out of memory"; - break; - default: - logger.error() << "UNKNOWN AL ERROR: " << error; + switch (error) { + case AL_INVALID_NAME: + logger.error() + << "a bad name (ID) was passed to an OpenAL function"; + break; + case AL_INVALID_ENUM: + logger.error() + << "an invalid enum value was passed to an OpenAL function"; + break; + case AL_INVALID_VALUE: + logger.error() + << "an invalid value was passed to an OpenAL function"; + break; + case AL_INVALID_OPERATION: + logger.error() << "the requested operation is not valid"; + break; + case AL_OUT_OF_MEMORY: + logger.error() << "the requested operation resulted in OpenAL " + "running out of memory"; + break; + default: + logger.error() << "UNKNOWN AL ERROR: " << error; } return false; } diff --git a/src/audio/AL/alutil.hpp b/src/audio/AL/alutil.hpp index 6ceccda4..f5b5a07d 100644 --- a/src/audio/AL/alutil.hpp +++ b/src/audio/AL/alutil.hpp @@ -1,11 +1,11 @@ #ifndef AUDIO_AUDIOUTIL_HPP_ #define AUDIO_AUDIOUTIL_HPP_ -#include "../../typedefs.hpp" - +#include #include #include -#include + +#include "../../typedefs.hpp" #ifdef __APPLE__ #include @@ -15,22 +15,25 @@ #include -#define AL_CHECK(STATEMENT) STATEMENT; AL::check_errors(__FILE__, __LINE__) +#define AL_CHECK(STATEMENT) \ + STATEMENT; \ + AL::check_errors(__FILE__, __LINE__) #define AL_GET_ERROR() AL::check_errors(__FILE__, __LINE__) -namespace AL { - /// @return true if no errors - bool check_errors(const std::string& filename, const std::uint_fast32_t line); +namespace AL { + /// @return true if no errors + bool check_errors( + const std::string& filename, const std::uint_fast32_t line + ); /// @brief alGetSourcef wrapper /// @param source target source /// @param field enum value /// @param def default value will be returned in case of error /// @return field value or default - inline float getSourcef(uint source, ALenum field, float def=0.0f) { + inline float getSourcef(uint source, ALenum field, float def = 0.0f) { float value = def; - if (source == 0) - return def; + if (source == 0) return def; AL_CHECK(alGetSourcef(source, field, &value)); return value; } @@ -40,10 +43,11 @@ namespace AL { /// @param field enum value /// @param def default value will be returned in case of error /// @return field value or default - inline glm::vec3 getSource3f(uint source, ALenum field, glm::vec3 def={}) { + inline glm::vec3 getSource3f( + uint source, ALenum field, glm::vec3 def = {} + ) { glm::vec3 value = def; - if (source == 0) - return def; + if (source == 0) return def; AL_CHECK(alGetSource3f(source, field, &value.x, &value.y, &value.z)); return value; } @@ -53,32 +57,31 @@ namespace AL { /// @param field enum value /// @param def default value will be returned in case of error /// @return field value or default - inline float getSourcei(uint source, ALenum field, int def=0) { + inline float getSourcei(uint source, ALenum field, int def = 0) { int value = def; - if (source == 0) - return def; + if (source == 0) return def; AL_CHECK(alGetSourcei(source, field, &value)); return value; } - static inline ALenum to_al_format(short channels, short bitsPerSample){ + static inline ALenum to_al_format(short channels, short bitsPerSample) { bool stereo = (channels > 1); switch (bitsPerSample) { - case 16: - if (stereo) - return AL_FORMAT_STEREO16; - else - return AL_FORMAT_MONO16; - case 8: - if (stereo) - return AL_FORMAT_STEREO8; - else - return AL_FORMAT_MONO8; - default: - return -1; + case 16: + if (stereo) + return AL_FORMAT_STEREO16; + else + return AL_FORMAT_MONO16; + case 8: + if (stereo) + return AL_FORMAT_STEREO8; + else + return AL_FORMAT_MONO8; + default: + return -1; } } } -#endif // AUDIO_AUDIOUTIL_HPP_ +#endif // AUDIO_AUDIOUTIL_HPP_ diff --git a/src/audio/NoAudio.cpp b/src/audio/NoAudio.cpp index 337b1192..e25c09a7 100644 --- a/src/audio/NoAudio.cpp +++ b/src/audio/NoAudio.cpp @@ -9,11 +9,15 @@ NoSound::NoSound(const std::shared_ptr& pcm, bool keepPCM) { } } -std::unique_ptr NoAudio::createSound(std::shared_ptr pcm, bool keepPCM) { +std::unique_ptr NoAudio::createSound( + std::shared_ptr pcm, bool keepPCM +) { return std::make_unique(pcm, keepPCM); } -std::unique_ptr NoAudio::openStream(std::shared_ptr stream, bool keepSource) { +std::unique_ptr NoAudio::openStream( + std::shared_ptr stream, bool keepSource +) { return std::make_unique(stream, keepSource); } diff --git a/src/audio/NoAudio.hpp b/src/audio/NoAudio.hpp index f1068e4d..848e322e 100644 --- a/src/audio/NoAudio.hpp +++ b/src/audio/NoAudio.hpp @@ -9,7 +9,8 @@ namespace audio { duration_t duration; public: NoSound(const std::shared_ptr& pcm, bool keepPCM); - ~NoSound() {} + ~NoSound() { + } duration_t getDuration() const override { return duration; @@ -19,7 +20,8 @@ namespace audio { return pcm; } - std::unique_ptr newInstance(int priority, int channel) const override { + std::unique_ptr newInstance(int priority, int channel) + const override { return nullptr; } }; @@ -42,7 +44,8 @@ namespace audio { void bindSpeaker(speakerid_t speaker) override { } - std::unique_ptr createSpeaker(bool loop, int channel) override { + std::unique_ptr createSpeaker(bool loop, int channel) + override { return nullptr; } @@ -63,19 +66,23 @@ namespace audio { class NoAudio : public Backend { public: - ~NoAudio() {} + ~NoAudio() { + } - std::unique_ptr createSound(std::shared_ptr pcm, bool keepPCM) override; - std::unique_ptr openStream(std::shared_ptr stream, bool keepSource) override; + std::unique_ptr createSound( + std::shared_ptr pcm, bool keepPCM + ) override; + std::unique_ptr openStream( + std::shared_ptr stream, bool keepSource + ) override; void setListener( - glm::vec3 position, - glm::vec3 velocity, - glm::vec3 at, - glm::vec3 up - ) override {} + glm::vec3 position, glm::vec3 velocity, glm::vec3 at, glm::vec3 up + ) override { + } - void update(double delta) override {} + void update(double delta) override { + } bool isDummy() const override { return true; @@ -85,4 +92,4 @@ namespace audio { }; } -#endif // AUDIO_NOAUDIO_HPP_ +#endif // AUDIO_NOAUDIO_HPP_ diff --git a/src/audio/audio.cpp b/src/audio/audio.cpp index 384a54a9..ca743b54 100644 --- a/src/audio/audio.cpp +++ b/src/audio/audio.cpp @@ -1,15 +1,14 @@ #include "audio.hpp" -#include "NoAudio.hpp" -#include "AL/ALAudio.hpp" - -#include "../coders/wav.hpp" -#include "../coders/ogg.hpp" - #include #include #include +#include "../coders/ogg.hpp" +#include "../coders/wav.hpp" +#include "AL/ALAudio.hpp" +#include "NoAudio.hpp" + namespace audio { static speakerid_t nextId = 1; static Backend* backend; @@ -85,12 +84,12 @@ class PCMVoidSource : public PCMStream { bool seekable; bool closed = false; public: - PCMVoidSource(size_t totalSamples, uint sampleRate, bool seekable) - : totalSamples(totalSamples), - remain(totalSamples), - sampleRate(sampleRate), - seekable(seekable) - {} + PCMVoidSource(size_t totalSamples, uint sampleRate, bool seekable) + : totalSamples(totalSamples), + remain(totalSamples), + sampleRate(sampleRate), + seekable(seekable) { + } size_t read(char*, size_t bufferSize) override { if (closed) { @@ -117,7 +116,7 @@ public: } duration_t getTotalDuration() const override { - return static_cast(totalSamples) / + return static_cast(totalSamples) / static_cast(sampleRate); } @@ -159,7 +158,7 @@ void audio::initialize(bool enabled) { std::unique_ptr audio::load_PCM(const fs::path& file, bool headerOnly) { if (!fs::exists(file)) { - throw std::runtime_error("file not found '"+file.u8string()+"'"); + throw std::runtime_error("file not found '" + file.u8string() + "'"); } std::string ext = file.extension().u8string(); if (ext == ".wav" || ext == ".WAV") { @@ -171,11 +170,15 @@ std::unique_ptr audio::load_PCM(const fs::path& file, bool headerOnly) { } std::unique_ptr audio::load_sound(const fs::path& file, bool keepPCM) { - std::shared_ptr pcm(load_PCM(file, !keepPCM && backend->isDummy()).release()); + std::shared_ptr pcm( + load_PCM(file, !keepPCM && backend->isDummy()).release() + ); return create_sound(pcm, keepPCM); } -std::unique_ptr audio::create_sound(std::shared_ptr pcm, bool keepPCM) { +std::unique_ptr audio::create_sound( + std::shared_ptr pcm, bool keepPCM +) { return backend->createSound(std::move(pcm), keepPCM); } @@ -189,31 +192,32 @@ std::unique_ptr audio::open_PCM_stream(const fs::path& file) { throw std::runtime_error("unsupported audio stream format"); } -std::unique_ptr audio::open_stream(const fs::path& file, bool keepSource) { +std::unique_ptr audio::open_stream( + const fs::path& file, bool keepSource +) { if (!keepSource && backend->isDummy()) { auto header = load_PCM(file, true); // using void source sized as audio instead of actual audio file return open_stream( - std::make_shared(header->totalSamples, header->sampleRate, header->seekable), + std::make_shared( + header->totalSamples, header->sampleRate, header->seekable + ), keepSource ); } return open_stream( - std::shared_ptr(open_PCM_stream(file)), - keepSource + std::shared_ptr(open_PCM_stream(file)), keepSource ); } -std::unique_ptr audio::open_stream(std::shared_ptr stream, bool keepSource) { +std::unique_ptr audio::open_stream( + std::shared_ptr stream, bool keepSource +) { return backend->openStream(std::move(stream), keepSource); } - void audio::set_listener( - glm::vec3 position, - glm::vec3 velocity, - glm::vec3 lookAt, - glm::vec3 up + glm::vec3 position, glm::vec3 velocity, glm::vec3 lookAt, glm::vec3 up ) { backend->setListener(position, velocity, lookAt, up); } @@ -317,7 +321,7 @@ speakerid_t audio::play_stream( bool loop, int channel ) { - std::shared_ptr stream (open_stream(file, false)); + std::shared_ptr stream(open_stream(file, false)); return play(stream, position, relative, volume, pitch, loop, channel); } @@ -335,14 +339,14 @@ int audio::create_channel(const std::string& name) { return index; } channels.emplace_back(std::make_unique(name)); - return channels.size()-1; + return channels.size() - 1; } int audio::get_channel_index(const std::string& name) { int index = 0; for (auto& channel : channels) { if (channel->getName() == name) { - return index; + return index; } index++; } diff --git a/src/audio/audio.hpp b/src/audio/audio.hpp index 4656de6f..9e6b6f6f 100644 --- a/src/audio/audio.hpp +++ b/src/audio/audio.hpp @@ -1,12 +1,12 @@ #ifndef AUDIO_AUDIO_HPP_ #define AUDIO_AUDIO_HPP_ -#include "../typedefs.hpp" - -#include -#include #include #include +#include +#include + +#include "../typedefs.hpp" namespace fs = std::filesystem; @@ -29,14 +29,11 @@ namespace audio { class Speaker; /// @brief Audio speaker states - enum class State { - playing, - paused, - stopped - }; + enum class State { playing, paused, stopped }; /// @brief Mixer channel controls speakers volume and effects - /// There is main channel 'master' and sub-channels like 'regular', 'music', 'ambient'... + /// There is main channel 'master' and sub-channels like 'regular', 'music', + /// 'ambient'... class Channel { /// @brief Channel name std::string name; @@ -46,7 +43,7 @@ namespace audio { public: Channel(std::string name); - /// @brief Get channel volume + /// @brief Get channel volume float getVolume() const; /// @brief Set channel volume @@ -57,8 +54,7 @@ namespace audio { const std::string& getName() const; inline void setPaused(bool flag) { - if (flag == paused) - return; + if (flag == paused) return; if (flag) { pause(); } else { @@ -92,24 +88,24 @@ namespace audio { /// @brief Audio source is seekable bool seekable; - PCM( - std::vector data, + PCM(std::vector data, size_t totalSamples, uint8_t channels, uint8_t bitsPerSample, uint sampleRate, - bool seekable - ) : data(std::move(data)), - totalSamples(totalSamples), - channels(channels), - bitsPerSample(bitsPerSample), - sampleRate(sampleRate), - seekable(seekable) {} + bool seekable) + : data(std::move(data)), + totalSamples(totalSamples), + channels(channels), + bitsPerSample(bitsPerSample), + sampleRate(sampleRate), + seekable(seekable) { + } /// @brief Get total audio duration - /// @return duration in seconds + /// @return duration in seconds inline duration_t getDuration() const { - return static_cast(totalSamples) / + return static_cast(totalSamples) / static_cast(sampleRate); } }; @@ -123,38 +119,38 @@ namespace audio { /// @param buffer destination buffer /// @param bufferSize destination buffer size /// @param loop loop stream (seek to start when end reached) - /// @return size of data received + /// @return size of data received /// (always equals bufferSize if seekable and looped) virtual size_t readFully(char* buffer, size_t bufferSize, bool loop); virtual size_t read(char* buffer, size_t bufferSize) = 0; /// @brief Close stream - virtual void close()=0; + virtual void close() = 0; /// @brief Check if stream is open - virtual bool isOpen() const=0; + virtual bool isOpen() const = 0; /// @brief Get total samples number if seekable or 0 - virtual size_t getTotalSamples() const=0; + virtual size_t getTotalSamples() const = 0; /// @brief Get total audio track duration if seekable or 0.0 - virtual duration_t getTotalDuration() const=0; + virtual duration_t getTotalDuration() const = 0; /// @brief Get number of audio channels /// @return 1 if mono, 2 if stereo - virtual uint getChannels() const=0; + virtual uint getChannels() const = 0; /// @brief Get audio sampling frequency /// @return number of mono samples per second - virtual uint getSampleRate() const=0; + virtual uint getSampleRate() const = 0; /// @brief Get number of bits per mono sample /// @return 8 or 16 - virtual uint getBitsPerSample() const=0; + virtual uint getBitsPerSample() const = 0; /// @brief Check if the stream does support seek feature - virtual bool isSeekable() const=0; + virtual bool isSeekable() const = 0; /// @brief Move playhead to the selected sample number /// @param position selected sample number @@ -170,16 +166,18 @@ namespace audio { virtual ~Stream() {}; /// @brief Get pcm data source - /// @return PCM stream or nullptr if audio::openStream + /// @return PCM stream or nullptr if audio::openStream /// keepSource argument is set to false virtual std::shared_ptr getSource() const = 0; - /// @brief Create new speaker bound to the Stream + /// @brief Create new speaker bound to the Stream /// and having high priority /// @param loop is stream looped (required for correct buffers preload) /// @param channel channel index /// @return speaker id or 0 - virtual std::unique_ptr createSpeaker(bool loop, int channel) = 0; + virtual std::unique_ptr createSpeaker( + bool loop, int channel + ) = 0; /// @brief Unbind previous speaker and bind new speaker to the stream /// @param speaker speaker id or 0 if all you need is unbind speaker @@ -201,7 +199,7 @@ namespace audio { virtual void setTime(duration_t time) = 0; }; - /// @brief Sound is an audio asset that supposed to support many + /// @brief Sound is an audio asset that supposed to support many /// simultaneously playing instances (speakers). /// So it's audio data is stored in memory. class Sound { @@ -209,7 +207,8 @@ namespace audio { /// @brief Sound variants will be chosen randomly to play std::vector> variants; - virtual ~Sound() {} + virtual ~Sound() { + } /// @brief Get sound duration /// @return duration in seconds (>= 0.0) @@ -220,19 +219,21 @@ namespace audio { virtual std::shared_ptr getPCM() const = 0; /// @brief Create new sound instance - /// @param priority instance priority. High priority instance can + /// @param priority instance priority. High priority instance can /// take out speaker from low priority instance /// @param channel channel index - /// @return new speaker with sound bound or nullptr + /// @return new speaker with sound bound or nullptr /// if all speakers are in use - virtual std::unique_ptr newInstance(int priority, int channel) const = 0; + virtual std::unique_ptr newInstance(int priority, int channel) + const = 0; }; /// @brief Audio source controller interface. /// @attention Speaker is not supposed to be reused class Speaker { public: - virtual ~Speaker() {} + virtual ~Speaker() { + } /// @brief Synchronize the speaker with channel settings /// @param channel speaker channel @@ -277,7 +278,7 @@ namespace audio { /// @brief Stop and destroy speaker virtual void stop() = 0; - + /// @brief Get current time position of playing audio /// @return time position in seconds virtual duration_t getTime() const = 0; @@ -316,17 +317,17 @@ namespace audio { /// @brief Determines if the position is relative to the listener virtual bool isRelative() const = 0; - /// @brief Check if speaker is playing + /// @brief Check if speaker is playing inline bool isPlaying() const { return getState() == State::playing; } - /// @brief Check if speaker is paused + /// @brief Check if speaker is paused inline bool isPaused() const { return getState() == State::paused; } - /// @brief Check if speaker is stopped + /// @brief Check if speaker is stopped inline bool isStopped() const { return getState() == State::stopped; } @@ -336,12 +337,16 @@ namespace audio { public: virtual ~Backend() {}; - virtual std::unique_ptr createSound(std::shared_ptr pcm, bool keepPCM) = 0; - virtual std::unique_ptr openStream(std::shared_ptr stream, bool keepSource) = 0; + virtual std::unique_ptr createSound( + std::shared_ptr pcm, bool keepPCM + ) = 0; + virtual std::unique_ptr openStream( + std::shared_ptr stream, bool keepSource + ) = 0; virtual void setListener( - glm::vec3 position, - glm::vec3 velocity, - glm::vec3 lookAt, + glm::vec3 position, + glm::vec3 velocity, + glm::vec3 lookAt, glm::vec3 up ) = 0; virtual void update(double delta) = 0; @@ -358,21 +363,23 @@ namespace audio { /// @brief Load audio file info and PCM data /// @param file audio file /// @param headerOnly read header only - /// @throws std::runtime_error if I/O error ocurred or format is unknown + /// @throws std::runtime_error if I/O error ocurred or format is unknown /// @return PCM audio data std::unique_ptr load_PCM(const fs::path& file, bool headerOnly); /// @brief Load sound from file /// @param file audio file path - /// @param keepPCM store PCM data in sound to make it accessible with Sound::getPCM - /// @throws std::runtime_error if I/O error ocurred or format is unknown + /// @param keepPCM store PCM data in sound to make it accessible with + /// Sound::getPCM + /// @throws std::runtime_error if I/O error ocurred or format is unknown /// @return new Sound instance std::unique_ptr load_sound(const fs::path& file, bool keepPCM); /// @brief Create new sound from PCM data /// @param pcm PCM data - /// @param keepPCM store PCM data in sound to make it accessible with Sound::getPCM - /// @return new Sound instance + /// @param keepPCM store PCM data in sound to make it accessible with + /// Sound::getPCM + /// @return new Sound instance std::unique_ptr create_sound(std::shared_ptr pcm, bool keepPCM); /// @brief Open new PCM stream from file @@ -383,15 +390,19 @@ namespace audio { /// @brief Open new audio stream from file /// @param file audio file path - /// @param keepSource store PCMStream in stream to make it accessible with Stream::getSource + /// @param keepSource store PCMStream in stream to make it accessible with + /// Stream::getSource /// @return new Stream instance std::unique_ptr open_stream(const fs::path& file, bool keepSource); /// @brief Open new audio stream from source /// @param stream PCM data source - /// @param keepSource store PCMStream in stream to make it accessible with Stream::getSource + /// @param keepSource store PCMStream in stream to make it accessible with + /// Stream::getSource /// @return new Stream instance - std::unique_ptr open_stream(std::shared_ptr stream, bool keepSource); + std::unique_ptr open_stream( + std::shared_ptr stream, bool keepSource + ); /// @brief Configure 3D listener /// @param position listener position @@ -399,10 +410,7 @@ namespace audio { /// @param lookAt point the listener look at /// @param up camera up vector void set_listener( - glm::vec3 position, - glm::vec3 velocity, - glm::vec3 lookAt, - glm::vec3 up + glm::vec3 position, glm::vec3 velocity, glm::vec3 lookAt, glm::vec3 up ); /// @brief Play 3D sound in the world @@ -412,7 +420,7 @@ namespace audio { /// @param volume sound volume [0.0-1.0] /// @param pitch sound pitch multiplier [0.0-...] /// @param loop loop sound - /// @param priority sound priority + /// @param priority sound priority /// (PRIORITY_LOW, PRIORITY_NORMAL, PRIORITY_HIGH) /// @param channel channel index /// @return speaker id or 0 @@ -470,7 +478,7 @@ namespace audio { /// @return speaker or nullptr Speaker* get_speaker(speakerid_t id); - /// @brief Create new channel. + /// @brief Create new channel. /// All non-builtin channels will be destroyed on audio::reset() call /// @param name channel name /// @return new channel index @@ -499,7 +507,7 @@ namespace audio { /// @brief Get alive speakers number (including paused) size_t count_speakers(); - /// @brief Get playing streams number (including paused) + /// @brief Get playing streams number (including paused) size_t count_streams(); /// @brief Update audio streams and sound instanced @@ -508,9 +516,9 @@ namespace audio { /// @brief Stop all playing audio in channel, reset channel state void reset_channel(int channel); - + /// @brief Finalize audio system void close(); }; -#endif // AUDIO_AUDIO_HPP_ +#endif // AUDIO_AUDIO_HPP_ diff --git a/src/coders/GLSLExtension.cpp b/src/coders/GLSLExtension.cpp index 629b2ff6..79bfb1cc 100644 --- a/src/coders/GLSLExtension.cpp +++ b/src/coders/GLSLExtension.cpp @@ -1,15 +1,15 @@ #include "GLSLExtension.hpp" -#include "../util/stringutil.hpp" -#include "../typedefs.hpp" -#include "../files/files.hpp" -#include "../files/engine_paths.hpp" - #include #include #include #include +#include "../files/engine_paths.hpp" +#include "../files/files.hpp" +#include "../typedefs.hpp" +#include "../util/stringutil.hpp" + namespace fs = std::filesystem; void GLSLExtension::setVersion(std::string version) { @@ -21,7 +21,7 @@ void GLSLExtension::setPaths(const ResPaths* paths) { } void GLSLExtension::loadHeader(const std::string& name) { - fs::path file = paths->find("shaders/lib/"+name+".glsl"); + fs::path file = paths->find("shaders/lib/" + name + ".glsl"); std::string source = files::read_string(file); addHeader(name, ""); addHeader(name, process(file, source, true)); @@ -38,7 +38,7 @@ void GLSLExtension::define(const std::string& name, std::string value) { const std::string& GLSLExtension::getHeader(const std::string& name) const { auto found = headers.find(name); if (found == headers.end()) { - throw std::runtime_error("no header '"+name+"' loaded"); + throw std::runtime_error("no header '" + name + "' loaded"); } return found->second; } @@ -46,7 +46,7 @@ const std::string& GLSLExtension::getHeader(const std::string& name) const { const std::string& GLSLExtension::getDefine(const std::string& name) const { auto found = defines.find(name); if (found == defines.end()) { - throw std::runtime_error("name '"+name+"' is not defined"); + throw std::runtime_error("name '" + name + "' is not defined"); } return found->second; } @@ -66,26 +66,29 @@ void GLSLExtension::undefine(const std::string& name) { } inline std::runtime_error parsing_error( - const fs::path& file, - uint linenum, - const std::string& message) { - return std::runtime_error("file "+file.string()+": "+message+ - " at line "+std::to_string(linenum)); + const fs::path& file, uint linenum, const std::string& message +) { + return std::runtime_error( + "file " + file.string() + ": " + message + " at line " + + std::to_string(linenum) + ); } inline void parsing_warning( - const fs::path& file, - uint linenum, const - std::string& message) { - std::cerr << "file "+file.string()+": warning: "+message+ - " at line "+std::to_string(linenum) << std::endl; + const fs::path& file, uint linenum, const std::string& message +) { + std::cerr << "file " + file.string() + ": warning: " + message + + " at line " + std::to_string(linenum) + << std::endl; } inline void source_line(std::stringstream& ss, uint linenum) { ss << "#line " << linenum << "\n"; } -std::string GLSLExtension::process(const fs::path& file, const std::string& source, bool header) { +std::string GLSLExtension::process( + const fs::path& file, const std::string& source, bool header +) { std::stringstream ss; size_t pos = 0; uint linenum = 1; @@ -103,43 +106,45 @@ std::string GLSLExtension::process(const fs::path& file, const std::string& sour } // parsing preprocessor directives if (source[pos] == '#') { - std::string line = source.substr(pos+1, endline-pos); + std::string line = source.substr(pos + 1, endline - pos); util::trim(line); // parsing 'include' directive if (line.find("include") != std::string::npos) { line = line.substr(7); util::trim(line); if (line.length() < 3) { - throw parsing_error(file, linenum, - "invalid 'include' syntax"); + throw parsing_error( + file, linenum, "invalid 'include' syntax" + ); } - if (line[0] != '<' || line[line.length()-1] != '>') { - throw parsing_error(file, linenum, - "expected '#include ' syntax"); + if (line[0] != '<' || line[line.length() - 1] != '>') { + throw parsing_error( + file, linenum, "expected '#include ' syntax" + ); } - std::string name = line.substr(1, line.length()-2); + std::string name = line.substr(1, line.length() - 2); if (!hasHeader(name)) { loadHeader(name); } source_line(ss, 1); ss << getHeader(name) << '\n'; - pos = endline+1; + pos = endline + 1; linenum++; source_line(ss, linenum); continue; - } + } // removing extra 'include' directives else if (line.find("version") != std::string::npos) { parsing_warning(file, linenum, "removed #version directive"); - pos = endline+1; + pos = endline + 1; linenum++; source_line(ss, linenum); continue; } } linenum++; - ss << source.substr(pos, endline+1-pos); - pos = endline+1; + ss << source.substr(pos, endline + 1 - pos); + pos = endline + 1; } - return ss.str(); + return ss.str(); } diff --git a/src/coders/GLSLExtension.hpp b/src/coders/GLSLExtension.hpp index 1c51eec3..fdee2e3e 100644 --- a/src/coders/GLSLExtension.hpp +++ b/src/coders/GLSLExtension.hpp @@ -1,10 +1,10 @@ #ifndef CODERS_GLSL_EXTESION_HPP_ #define CODERS_GLSL_EXTESION_HPP_ -#include -#include -#include #include +#include +#include +#include class ResPaths; @@ -30,10 +30,10 @@ public: bool hasDefine(const std::string& name) const; std::string process( - const std::filesystem::path& file, + const std::filesystem::path& file, const std::string& source, - bool header=false + bool header = false ); }; -#endif // CODERS_GLSL_EXTESION_HPP_ +#endif // CODERS_GLSL_EXTESION_HPP_ diff --git a/src/coders/binary_json.cpp b/src/coders/binary_json.cpp index f1f87af6..b71ac933 100644 --- a/src/coders/binary_json.cpp +++ b/src/coders/binary_json.cpp @@ -1,11 +1,11 @@ #include "binary_json.hpp" -#include "gzip.hpp" -#include "byte_utils.hpp" -#include "../data/dynamic.hpp" - #include +#include "../data/dynamic.hpp" +#include "byte_utils.hpp" +#include "gzip.hpp" + using namespace json; using namespace dynamic; @@ -30,7 +30,7 @@ static void to_binary(ByteBuilder& builder, const Value& value) { if (val >= 0 && val <= 255) { builder.put(BJSON_TYPE_BYTE); builder.put(val); - } else if (val >= INT16_MIN && val <= INT16_MAX){ + } else if (val >= INT16_MIN && val <= INT16_MAX) { builder.put(BJSON_TYPE_INT16); builder.putInt16(val); } else if (val >= INT32_MIN && val <= INT32_MAX) { @@ -115,7 +115,7 @@ static Value value_from_binary(ByteReader& reader) { return reader.getString(); default: throw std::runtime_error( - "type "+std::to_string(typecode)+" is not supported" + "type " + std::to_string(typecode) + " is not supported" ); } } diff --git a/src/coders/binary_json.hpp b/src/coders/binary_json.hpp index 0cb9945b..f0d34efa 100644 --- a/src/coders/binary_json.hpp +++ b/src/coders/binary_json.hpp @@ -1,10 +1,10 @@ #ifndef CODERS_BINARY_JSON_HPP_ #define CODERS_BINARY_JSON_HPP_ -#include "../data/dynamic_fwd.hpp" - -#include #include +#include + +#include "../data/dynamic_fwd.hpp" namespace dynamic { class Map; @@ -26,9 +26,13 @@ namespace json { inline constexpr int BJSON_TYPE_NULL = 0xC; inline constexpr int BJSON_TYPE_CDOCUMENT = 0x1F; - std::vector to_binary(const dynamic::Map* obj, bool compress=false); - std::vector to_binary(const dynamic::Value& obj, bool compress=false); + std::vector to_binary( + const dynamic::Map* obj, bool compress = false + ); + std::vector to_binary( + const dynamic::Value& obj, bool compress = false + ); std::shared_ptr from_binary(const ubyte* src, size_t size); } -#endif // CODERS_BINARY_JSON_HPP_ +#endif // CODERS_BINARY_JSON_HPP_ diff --git a/src/coders/byte_utils.cpp b/src/coders/byte_utils.cpp index 670f5bca..d28e31ce 100644 --- a/src/coders/byte_utils.cpp +++ b/src/coders/byte_utils.cpp @@ -9,7 +9,7 @@ void ByteBuilder::put(ubyte b) { } void ByteBuilder::putCStr(const char* str) { - size_t size = strlen(str)+1; + size_t size = strlen(str) + 1; buffer.reserve(buffer.size() + size); for (size_t i = 0; i < size; i++) { buffer.push_back(str[i]); @@ -37,21 +37,21 @@ void ByteBuilder::putInt16(int16_t val) { void ByteBuilder::putInt32(int32_t val) { buffer.reserve(buffer.size() + 4); buffer.push_back(static_cast(val >> 0 & 255)); - buffer.push_back(static_cast (val >> 8 & 255)); - buffer.push_back(static_cast (val >> 16 & 255)); - buffer.push_back(static_cast (val >> 24 & 255)); + buffer.push_back(static_cast(val >> 8 & 255)); + buffer.push_back(static_cast(val >> 16 & 255)); + buffer.push_back(static_cast(val >> 24 & 255)); } void ByteBuilder::putInt64(int64_t val) { buffer.reserve(buffer.size() + 8); - buffer.push_back(static_cast (val >> 0 & 255)); - buffer.push_back(static_cast (val >> 8 & 255)); - buffer.push_back(static_cast (val >> 16 & 255)); - buffer.push_back(static_cast (val >> 24 & 255)); - buffer.push_back(static_cast (val >> 32 & 255)); - buffer.push_back(static_cast (val >> 40 & 255)); - buffer.push_back(static_cast (val >> 48 & 255)); - buffer.push_back(static_cast (val >> 56 & 255)); + buffer.push_back(static_cast(val >> 0 & 255)); + buffer.push_back(static_cast(val >> 8 & 255)); + buffer.push_back(static_cast(val >> 16 & 255)); + buffer.push_back(static_cast(val >> 24 & 255)); + buffer.push_back(static_cast(val >> 32 & 255)); + buffer.push_back(static_cast(val >> 40 & 255)); + buffer.push_back(static_cast(val >> 48 & 255)); + buffer.push_back(static_cast(val >> 56 & 255)); } void ByteBuilder::putFloat32(float val) { @@ -102,8 +102,7 @@ ByteReader::ByteReader(const ubyte* data, size_t size) : data(data), size(size), pos(0) { } -ByteReader::ByteReader(const ubyte* data) - : data(data), size(4), pos(0) { +ByteReader::ByteReader(const ubyte* data) : data(data), size(4), pos(0) { size = getInt32(); } @@ -112,7 +111,7 @@ void ByteReader::checkMagic(const char* data, size_t size) { throw std::runtime_error("invalid magic number"); } for (size_t i = 0; i < size; i++) { - if (this->data[pos + i] != (ubyte)data[i]){ + if (this->data[pos + i] != (ubyte)data[i]) { throw std::runtime_error("invalid magic number"); } } @@ -130,11 +129,11 @@ ubyte ByteReader::peek() { if (pos == size) { throw std::runtime_error("buffer underflow"); } - return data[pos]; + return data[pos]; } int16_t ByteReader::getInt16() { - if (pos+2 > size) { + if (pos + 2 > size) { throw std::runtime_error("buffer underflow"); } pos += 2; @@ -143,7 +142,7 @@ int16_t ByteReader::getInt16() { } int32_t ByteReader::getInt32() { - if (pos+4 > size) { + if (pos + 4 > size) { throw std::runtime_error("buffer underflow"); } pos += 4; @@ -154,7 +153,7 @@ int32_t ByteReader::getInt32() { } int64_t ByteReader::getInt64() { - if (pos+8 > size) { + if (pos + 8 > size) { throw std::runtime_error("buffer underflow"); } pos += 8; @@ -183,18 +182,20 @@ double ByteReader::getFloat64() { } const char* ByteReader::getCString() { - const char* cstr = reinterpret_cast(data+pos); + const char* cstr = reinterpret_cast(data + pos); pos += strlen(cstr) + 1; return cstr; } std::string ByteReader::getString() { uint32_t length = (uint32_t)getInt32(); - if (pos+length > size) { + if (pos + length > size) { throw std::runtime_error("buffer underflow"); } pos += length; - return std::string(reinterpret_cast(data+pos-length), length); + return std::string( + reinterpret_cast(data + pos - length), length + ); } bool ByteReader::hasNext() const { diff --git a/src/coders/byte_utils.hpp b/src/coders/byte_utils.hpp index 068170af..3e6e2277 100644 --- a/src/coders/byte_utils.hpp +++ b/src/coders/byte_utils.hpp @@ -1,11 +1,11 @@ #ifndef CODERS_BYTE_UTILS_HPP_ #define CODERS_BYTE_UTILS_HPP_ -#include "../typedefs.hpp" - #include #include +#include "../typedefs.hpp" + /* byteorder: little-endian */ class ByteBuilder { std::vector buffer; @@ -23,8 +23,8 @@ public: /* Write 32 bit floating-point number */ void putFloat32(float val); /* Write 64 bit floating-point number */ - void putFloat64(double val); - + void putFloat64(double val); + /* Write string (uint32 length + bytes) */ void put(const std::string& s); /* Write sequence of bytes without any header */ @@ -80,4 +80,4 @@ public: void skip(size_t n); }; -#endif // CODERS_BYTE_UTILS_HPP_ +#endif // CODERS_BYTE_UTILS_HPP_ diff --git a/src/coders/commons.cpp b/src/coders/commons.cpp index c6f3d7c4..36e10db5 100644 --- a/src/coders/commons.cpp +++ b/src/coders/commons.cpp @@ -1,10 +1,11 @@ #include "commons.hpp" -#include "../util/stringutil.hpp" +#include #include #include -#include + +#include "../util/stringutil.hpp" inline double power(double base, int64_t power) { double result = 1.0; @@ -21,21 +22,25 @@ parsing_error::parsing_error( uint pos, uint line, uint linestart -) : std::runtime_error(message), filename(filename), - pos(pos), line(line), linestart(linestart) -{ +) + : std::runtime_error(message), + filename(filename), + pos(pos), + line(line), + linestart(linestart) { size_t end = source.find("\n", linestart); if (end == std::string::npos) { end = source.length(); } - this->source = source.substr(linestart, end-linestart); + this->source = source.substr(linestart, end - linestart); } std::string parsing_error::errorLog() const { std::stringstream ss; uint linepos = pos - linestart; ss << "parsing error in file '" << filename; - ss << "' at " << (line+1) << ":" << linepos << ": " << this->what() << "\n"; + ss << "' at " << (line + 1) << ":" << linepos << ": " << this->what() + << "\n"; ss << source << "\n"; for (uint i = 0; i < linepos; i++) { ss << " "; @@ -44,10 +49,8 @@ std::string parsing_error::errorLog() const { return ss.str(); } -BasicParser::BasicParser( - std::string_view file, - std::string_view source -) : filename(file), source(source) { +BasicParser::BasicParser(std::string_view file, std::string_view source) + : filename(file), source(source) { } void BasicParser::skipWhitespace() { @@ -67,7 +70,7 @@ void BasicParser::skipWhitespace() { } void BasicParser::skip(size_t n) { - n = std::min(n, source.length()-pos); + n = std::min(n, source.length() - pos); for (size_t i = 0; i < n; i++) { char next = source[pos++]; @@ -93,10 +96,10 @@ void BasicParser::skipLine() { bool BasicParser::skipTo(const std::string& substring) { size_t idx = source.find(substring, pos); if (idx == std::string::npos) { - skip(source.length()-pos); + skip(source.length() - pos); return false; } else { - skip(idx-pos); + skip(idx - pos); return true; } } @@ -122,17 +125,16 @@ char BasicParser::nextChar() { void BasicParser::expect(char expected) { char c = peek(); if (c != expected) { - throw error("'"+std::string({expected})+"' expected"); + throw error("'" + std::string({expected}) + "' expected"); } pos++; } void BasicParser::expect(const std::string& substring) { - if (substring.empty()) - return; + if (substring.empty()) return; for (uint i = 0; i < substring.length(); i++) { - if (source.length() <= pos + i || source[pos+i] != substring[i]) { - throw error(util::quote(substring)+" expected"); + if (source.length() <= pos + i || source[pos + i] != substring[i]) { + throw error(util::quote(substring) + " expected"); } } pos += substring.length(); @@ -158,7 +160,7 @@ void BasicParser::goBack(size_t count) { if (pos < count) { throw std::runtime_error("pos < jump"); } - if (pos) { + if (pos) { pos -= count; } } @@ -205,7 +207,7 @@ std::string_view BasicParser::readUntil(char c) { while (hasNext() && source[pos] != c) { pos++; } - return source.substr(start, pos-start); + return source.substr(start, pos - start); } std::string_view BasicParser::readUntilEOL() { @@ -213,7 +215,7 @@ std::string_view BasicParser::readUntilEOL() { while (hasNext() && source[pos] != '\r' && source[pos] != '\n') { pos++; } - return source.substr(start, pos-start); + return source.substr(start, pos - start); } std::string BasicParser::parseName() { @@ -229,7 +231,7 @@ std::string BasicParser::parseName() { while (hasNext() && is_identifier_part(source[pos])) { pos++; } - return std::string(source.substr(start, pos-start)); + return std::string(source.substr(start, pos - start)); } int64_t BasicParser::parseSimpleInt(int base) { @@ -272,14 +274,14 @@ dynamic::Value BasicParser::parseNumber() { dynamic::Value BasicParser::parseNumber(int sign) { char c = peek(); int base = 10; - if (c == '0' && pos + 1 < source.length() && - (base = is_box(source[pos+1])) != 10) { + if (c == '0' && pos + 1 < source.length() && + (base = is_box(source[pos + 1])) != 10) { pos += 2; return parseSimpleInt(base); - } else if (c == 'i' && pos + 2 < source.length() && source[pos+1] == 'n' && source[pos+2] == 'f') { + } else if (c == 'i' && pos + 2 < source.length() && source[pos + 1] == 'n' && source[pos + 2] == 'f') { pos += 3; return INFINITY * sign; - } else if (c == 'n' && pos + 2 < source.length() && source[pos+1] == 'a' && source[pos+2] == 'n') { + } else if (c == 'n' && pos + 2 < source.length() && source[pos + 1] == 'a' && source[pos + 2] == 'n') { pos += 3; return NAN * sign; } @@ -294,7 +296,7 @@ dynamic::Value BasicParser::parseNumber(int sign) { if (peek() == '-') { s = -1; pos++; - } else if (peek() == '+'){ + } else if (peek() == '+') { pos++; } return sign * value * power(10.0, s * parseSimpleInt(10)); @@ -320,7 +322,7 @@ dynamic::Value BasicParser::parseNumber(int sign) { if (peek() == '-') { s = -1; pos++; - } else if (peek() == '+'){ + } else if (peek() == '+') { pos++; } return sign * dvalue * power(10.0, s * parseSimpleInt(10)); @@ -347,19 +349,40 @@ std::string BasicParser::parseString(char quote, bool closeRequired) { continue; } switch (c) { - case 'n': ss << '\n'; break; - case 'r': ss << '\r'; break; - case 'b': ss << '\b'; break; - case 't': ss << '\t'; break; - case 'f': ss << '\f'; break; - case '\'': ss << '\\'; break; - case '"': ss << '"'; break; - case '\\': ss << '\\'; break; - case '/': ss << '/'; break; - case '\n': pos++; continue; + case 'n': + ss << '\n'; + break; + case 'r': + ss << '\r'; + break; + case 'b': + ss << '\b'; + break; + case 't': + ss << '\t'; + break; + case 'f': + ss << '\f'; + break; + case '\'': + ss << '\\'; + break; + case '"': + ss << '"'; + break; + case '\\': + ss << '\\'; + break; + case '/': + ss << '/'; + break; + case '\n': + pos++; + continue; default: - throw error("'\\" + std::string({c}) + - "' is an illegal escape"); + throw error( + "'\\" + std::string({c}) + "' is an illegal escape" + ); } continue; } diff --git a/src/coders/commons.hpp b/src/coders/commons.hpp index b5c99298..4b661880 100644 --- a/src/coders/commons.hpp +++ b/src/coders/commons.hpp @@ -1,12 +1,12 @@ #ifndef CODERS_COMMONS_HPP_ #define CODERS_COMMONS_HPP_ +#include +#include + #include "../data/dynamic.hpp" #include "../typedefs.hpp" -#include -#include - inline int is_box(int c) { switch (c) { case 'B': @@ -17,7 +17,7 @@ inline int is_box(int c) { return 8; case 'X': case 'x': - return 16; + return 16; } return 10; } @@ -31,7 +31,8 @@ inline bool is_whitespace(int c) { } inline bool is_identifier_start(int c) { - return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' || c == '.'; + return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' || + c == '.'; } inline bool is_identifier_part(int c) { @@ -61,10 +62,10 @@ public: parsing_error( const std::string& message, - std::string_view filename, - std::string_view source, - uint pos, - uint line, + std::string_view filename, + std::string_view source, + uint pos, + uint line, uint linestart ); std::string errorLog() const; @@ -86,16 +87,15 @@ protected: void expect(const std::string& substring); bool isNext(const std::string& substring); void expectNewLine(); - void goBack(size_t count=1); + void goBack(size_t count = 1); void reset(); int64_t parseSimpleInt(int base); dynamic::Value parseNumber(int sign); dynamic::Value parseNumber(); - std::string parseString(char chr, bool closeRequired=true); + std::string parseString(char chr, bool closeRequired = true); parsing_error error(const std::string& message); - public: std::string_view readUntil(char c); std::string_view readUntilEOL(); @@ -109,4 +109,4 @@ public: BasicParser(std::string_view file, std::string_view source); }; -#endif // CODERS_COMMONS_HPP_ +#endif // CODERS_COMMONS_HPP_ diff --git a/src/coders/gzip.cpp b/src/coders/gzip.cpp index c9608b53..a7b4adfc 100644 --- a/src/coders/gzip.cpp +++ b/src/coders/gzip.cpp @@ -3,12 +3,13 @@ #include "byte_utils.hpp" #define ZLIB_CONST -#include #include +#include + #include std::vector gzip::compress(const ubyte* src, size_t size) { - size_t buffer_size = 23+size*1.01; + size_t buffer_size = 23 + size * 1.01; std::vector buffer; buffer.resize(buffer_size); @@ -23,8 +24,14 @@ std::vector gzip::compress(const ubyte* src, size_t size) { defstream.next_out = buffer.data(); // compression - deflateInit2(&defstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, - 16 + MAX_WBITS, 8, Z_DEFAULT_STRATEGY); + deflateInit2( + &defstream, + Z_DEFAULT_COMPRESSION, + Z_DEFLATED, + 16 + MAX_WBITS, + 8, + Z_DEFAULT_STRATEGY + ); deflate(&defstream, Z_FINISH); deflateEnd(&defstream); @@ -35,7 +42,8 @@ std::vector gzip::compress(const ubyte* src, size_t size) { std::vector gzip::decompress(const ubyte* src, size_t size) { // getting uncompressed data length from gzip footer - size_t decompressed_size = *reinterpret_cast(src+size-4); + size_t decompressed_size = + *reinterpret_cast(src + size - 4); std::vector buffer; buffer.resize(decompressed_size); @@ -49,7 +57,7 @@ std::vector gzip::decompress(const ubyte* src, size_t size) { infstream.avail_out = decompressed_size; infstream.next_out = buffer.data(); - inflateInit2(&infstream, 16+MAX_WBITS); + inflateInit2(&infstream, 16 + MAX_WBITS); inflate(&infstream, Z_NO_FLUSH); inflateEnd(&infstream); diff --git a/src/coders/gzip.hpp b/src/coders/gzip.hpp index d7b3e944..b35c898b 100644 --- a/src/coders/gzip.hpp +++ b/src/coders/gzip.hpp @@ -1,9 +1,10 @@ #ifndef CODERS_GZIP_HPP_ #define CODERS_GZIP_HPP_ -#include "../typedefs.hpp" #include +#include "../typedefs.hpp" + namespace gzip { const unsigned char MAGIC[] = "\x1F\x8B"; @@ -11,11 +12,11 @@ namespace gzip { @param src source bytes array @param size length of source bytes array */ std::vector compress(const ubyte* src, size_t size); - - /* Decompress bytes array from GZIP + + /* Decompress bytes array from GZIP @param src GZIP data @param size length of GZIP data */ std::vector decompress(const ubyte* src, size_t size); } -#endif // CODERS_GZIP_HPP_ +#endif // CODERS_GZIP_HPP_ diff --git a/src/coders/imageio.cpp b/src/coders/imageio.cpp index cfddb3b2..59917593 100644 --- a/src/coders/imageio.cpp +++ b/src/coders/imageio.cpp @@ -1,15 +1,16 @@ #include "imageio.hpp" -#include "png.hpp" -#include "../graphics/core/ImageData.hpp" - #include #include #include +#include "../graphics/core/ImageData.hpp" +#include "png.hpp" + namespace fs = std::filesystem; -using image_reader = std::function(const std::string&)>; +using image_reader = + std::function(const std::string&)>; using image_writer = std::function; static std::unordered_map readers { @@ -35,7 +36,9 @@ inline std::string extensionOf(const std::string& filename) { std::unique_ptr imageio::read(const std::string& filename) { auto found = readers.find(extensionOf(filename)); if (found == readers.end()) { - throw std::runtime_error("file format is not supported (read): "+filename); + throw std::runtime_error( + "file format is not supported (read): " + filename + ); } return std::unique_ptr(found->second(filename)); } @@ -43,7 +46,9 @@ std::unique_ptr imageio::read(const std::string& filename) { void imageio::write(const std::string& filename, const ImageData* image) { auto found = writers.find(extensionOf(filename)); if (found == writers.end()) { - throw std::runtime_error("file format is not supported (write): "+filename); + throw std::runtime_error( + "file format is not supported (write): " + filename + ); } return found->second(filename, image); } diff --git a/src/coders/imageio.hpp b/src/coders/imageio.hpp index a05cfadc..c5481bea 100644 --- a/src/coders/imageio.hpp +++ b/src/coders/imageio.hpp @@ -1,8 +1,8 @@ #ifndef CODERS_IMAGEIO_HPP_ #define CODERS_IMAGEIO_HPP_ -#include #include +#include class ImageData; @@ -16,4 +16,4 @@ namespace imageio { void write(const std::string& filename, const ImageData* image); } -#endif // CODERS_IMAGEIO_HPP_ +#endif // CODERS_IMAGEIO_HPP_ diff --git a/src/coders/json.cpp b/src/coders/json.cpp index c88e0c1d..102840ec 100644 --- a/src/coders/json.cpp +++ b/src/coders/json.cpp @@ -1,14 +1,14 @@ #include "json.hpp" -#include "commons.hpp" +#include + +#include +#include +#include #include "../data/dynamic.hpp" #include "../util/stringutil.hpp" - -#include -#include -#include -#include +#include "commons.hpp" using namespace json; using namespace dynamic; @@ -19,14 +19,12 @@ class Parser : BasicParser { dynamic::Value parseValue(); public: Parser(std::string_view filename, std::string_view source); - + std::unique_ptr parse(); }; inline void newline( - std::stringstream& ss, - bool nice, uint indent, - const std::string& indentstr + std::stringstream& ss, bool nice, uint indent, const std::string& indentstr ) { if (nice) { ss << "\n"; @@ -39,24 +37,23 @@ inline void newline( } void stringifyObj( - const Map* obj, - std::stringstream& ss, - int indent, - const std::string& indentstr, + const Map* obj, + std::stringstream& ss, + int indent, + const std::string& indentstr, bool nice ); void stringifyValue( - const Value& value, - std::stringstream& ss, - int indent, - const std::string& indentstr, + const Value& value, + std::stringstream& ss, + int indent, + const std::string& indentstr, bool nice ) { if (auto map = std::get_if(&value)) { stringifyObj(map->get(), ss, indent, indentstr, nice); - } - else if (auto listptr = std::get_if(&value)) { + } else if (auto listptr = std::get_if(&value)) { auto list = *listptr; if (list->size() == 0) { ss << "[]"; @@ -68,7 +65,7 @@ void stringifyValue( if (i > 0 || nice) { newline(ss, nice, indent, indentstr); } - stringifyValue(value, ss, indent+1, indentstr, nice); + stringifyValue(value, ss, indent + 1, indentstr, nice); if (i + 1 < list->size()) { ss << ','; } @@ -91,10 +88,10 @@ void stringifyValue( } void stringifyObj( - const Map* obj, - std::stringstream& ss, - int indent, - const std::string& indentstr, + const Map* obj, + std::stringstream& ss, + int indent, + const std::string& indentstr, bool nice ) { if (obj == nullptr) { @@ -114,22 +111,20 @@ void stringifyObj( } const Value& value = entry.second; ss << util::escape(key) << ": "; - stringifyValue(value, ss, indent+1, indentstr, nice); + stringifyValue(value, ss, indent + 1, indentstr, nice); index++; if (index < obj->values.size()) { ss << ','; } } if (nice) { - newline(ss, true, indent-1, indentstr); + newline(ss, true, indent - 1, indentstr); } ss << '}'; } std::string json::stringify( - const Map* obj, - bool nice, - const std::string& indent + const Map* obj, bool nice, const std::string& indent ) { std::stringstream ss; stringifyObj(obj, ss, 1, indent, nice); @@ -137,17 +132,15 @@ std::string json::stringify( } std::string json::stringify( - const dynamic::Value& value, - bool nice, - const std::string& indent + const dynamic::Value& value, bool nice, const std::string& indent ) { std::stringstream ss; stringifyValue(value, ss, 1, indent, nice); return ss.str(); } -Parser::Parser(std::string_view filename, std::string_view source) - : BasicParser(filename, source) { +Parser::Parser(std::string_view filename, std::string_view source) + : BasicParser(filename, source) { } std::unique_ptr Parser::parse() { @@ -239,10 +232,12 @@ Value Parser::parseValue() { pos++; return parseString(next); } - throw error("unexpected character '"+std::string({next})+"'"); + throw error("unexpected character '" + std::string({next}) + "'"); } -dynamic::Map_sptr json::parse(std::string_view filename, std::string_view source) { +dynamic::Map_sptr json::parse( + std::string_view filename, std::string_view source +) { Parser parser(filename, source); return parser.parse(); } diff --git a/src/coders/json.hpp b/src/coders/json.hpp index 7dc7b92e..ad4c0735 100644 --- a/src/coders/json.hpp +++ b/src/coders/json.hpp @@ -1,28 +1,23 @@ #ifndef CODERS_JSON_HPP_ #define CODERS_JSON_HPP_ -#include "binary_json.hpp" +#include #include "../data/dynamic.hpp" #include "../typedefs.hpp" - -#include +#include "binary_json.hpp" namespace json { dynamic::Map_sptr parse(std::string_view filename, std::string_view source); dynamic::Map_sptr parse(std::string_view source); std::string stringify( - const dynamic::Map* obj, - bool nice, - const std::string& indent + const dynamic::Map* obj, bool nice, const std::string& indent ); std::string stringify( - const dynamic::Value& value, - bool nice, - const std::string& indent + const dynamic::Value& value, bool nice, const std::string& indent ); } -#endif // CODERS_JSON_HPP_ +#endif // CODERS_JSON_HPP_ diff --git a/src/coders/obj.cpp b/src/coders/obj.cpp index d7c1687d..c3df555a 100644 --- a/src/coders/obj.cpp +++ b/src/coders/obj.cpp @@ -1,7 +1,7 @@ #include "obj.hpp" -#include "commons.hpp" #include "../graphics/core/Model.hpp" +#include "commons.hpp" using namespace model; @@ -34,8 +34,7 @@ class ObjParser : BasicParser { } while (peekInLine() != '\n' && ++i < 3); vertices.push_back(Vertex { - coords[indices[0]], uvs[indices[1]], normals[indices[2]] - }); + coords[indices[0]], uvs[indices[1]], normals[indices[2]]}); } } if (peekInLine() != '\n' && hasNext()) { @@ -51,7 +50,8 @@ class ObjParser : BasicParser { } } public: - ObjParser(const std::string_view file, const std::string_view src) : BasicParser(file, src) { + ObjParser(const std::string_view file, const std::string_view src) + : BasicParser(file, src) { } std::unique_ptr parse() { @@ -111,7 +111,7 @@ public: } skipLine(); } - } while(hasNext()); + } while (hasNext()); model->clean(); return model; } diff --git a/src/coders/obj.hpp b/src/coders/obj.hpp index 64d0f4ce..786414e8 100644 --- a/src/coders/obj.hpp +++ b/src/coders/obj.hpp @@ -1,8 +1,8 @@ #ifndef CODERS_OBJ_HPP_ #define CODERS_OBJ_HPP_ -#include #include +#include /// Wavefont OBJ files parser @@ -16,4 +16,4 @@ namespace obj { ); } -#endif // CODERS_OBJ_HPP_ +#endif // CODERS_OBJ_HPP_ diff --git a/src/coders/ogg.cpp b/src/coders/ogg.cpp index 6069aa8c..7f4c9940 100644 --- a/src/coders/ogg.cpp +++ b/src/coders/ogg.cpp @@ -1,13 +1,14 @@ #include "ogg.hpp" -#include "../debug/Logger.hpp" -#include "../audio/audio.hpp" -#include "../typedefs.hpp" - -#include #include #include +#include + +#include "../audio/audio.hpp" +#include "../debug/Logger.hpp" +#include "../typedefs.hpp" + static debug::Logger logger("ogg"); namespace fs = std::filesystem; @@ -15,14 +16,21 @@ using namespace audio; static inline std::string vorbis_error_message(int code) { switch (code) { - case 0: return "no error"; - case OV_EREAD: return "a read from media returned an error"; - case OV_ENOTVORBIS: return "the given file/data was not recognized as Ogg Vorbis data"; - case OV_EVERSION: return "vorbis version mismatch"; - case OV_EBADHEADER: return "invalid Vorbis bitstream header"; - case OV_EFAULT: return "internal logic fault"; - case OV_EINVAL: return "invalid read operation"; - case OV_EBADLINK: + case 0: + return "no error"; + case OV_EREAD: + return "a read from media returned an error"; + case OV_ENOTVORBIS: + return "the given file/data was not recognized as Ogg Vorbis data"; + case OV_EVERSION: + return "vorbis version mismatch"; + case OV_EBADHEADER: + return "invalid Vorbis bitstream header"; + case OV_EFAULT: + return "internal logic fault"; + case OV_EINVAL: + return "invalid read operation"; + case OV_EBADLINK: return "the given link exists in the Vorbis data stream," " but is not decipherable due to garbacge or corruption"; case OV_ENOSEEK: @@ -30,15 +38,17 @@ static inline std::string vorbis_error_message(int code) { case OV_EIMPL: return "feature not implemented"; default: - return "unknown error ["+std::to_string(code)+"]"; + return "unknown error [" + std::to_string(code) + "]"; } } -std::unique_ptr ogg::load_pcm(const fs::path& file, bool headerOnly) { +std::unique_ptr ogg::load_pcm( + const fs::path& file, bool headerOnly +) { OggVorbis_File vf; int code; if ((code = ov_fopen(file.u8string().c_str(), &vf))) { - throw std::runtime_error("vorbis: "+vorbis_error_message(code)); + throw std::runtime_error("vorbis: " + vorbis_error_message(code)); } std::vector data; @@ -59,9 +69,12 @@ std::unique_ptr ogg::load_pcm(const fs::path& file, bool headerOnly) if (ret == 0) { eof = true; } else if (ret < 0) { - logger.error() << "ogg::load_pcm: " << vorbis_error_message(ret); + logger.error() + << "ogg::load_pcm: " << vorbis_error_message(ret); } else { - data.insert(data.end(), std::begin(buffer), std::begin(buffer)+ret); + data.insert( + data.end(), std::begin(buffer), std::begin(buffer) + ret + ); } } totalSamples = data.size() / channels / 2; @@ -103,7 +116,8 @@ public: int bitstream = 0; long bytes = ov_read(&vf, buffer, bufferSize, 0, 2, true, &bitstream); if (bytes < 0) { - logger.error() << "ogg::load_pcm: " << vorbis_error_message(bytes) << " " << bytes; + logger.error() << "ogg::load_pcm: " << vorbis_error_message(bytes) + << " " << bytes; return PCMStream::ERROR; } return bytes; @@ -156,7 +170,7 @@ std::unique_ptr ogg::create_stream(const fs::path& file) { OggVorbis_File vf; int code; if ((code = ov_fopen(file.u8string().c_str(), &vf))) { - throw std::runtime_error("vorbis: "+vorbis_error_message(code)); + throw std::runtime_error("vorbis: " + vorbis_error_message(code)); } return std::make_unique(vf); } diff --git a/src/coders/ogg.hpp b/src/coders/ogg.hpp index e704febe..29c3da60 100644 --- a/src/coders/ogg.hpp +++ b/src/coders/ogg.hpp @@ -9,8 +9,12 @@ namespace audio { } namespace ogg { - std::unique_ptr load_pcm(const std::filesystem::path& file, bool headerOnly); - std::unique_ptr create_stream(const std::filesystem::path& file); + std::unique_ptr load_pcm( + const std::filesystem::path& file, bool headerOnly + ); + std::unique_ptr create_stream( + const std::filesystem::path& file + ); } -#endif // CODERS_OGG_HPP_ +#endif // CODERS_OGG_HPP_ diff --git a/src/coders/png.cpp b/src/coders/png.cpp index 7b3ac23b..c7c9b179 100644 --- a/src/coders/png.cpp +++ b/src/coders/png.cpp @@ -1,12 +1,13 @@ #include "png.hpp" -#include "../graphics/core/ImageData.hpp" -#include "../graphics/core/GLTexture.hpp" -#include "../files/files.hpp" -#include "../debug/Logger.hpp" +#include #include -#include + +#include "../debug/Logger.hpp" +#include "../files/files.hpp" +#include "../graphics/core/GLTexture.hpp" +#include "../graphics/core/ImageData.hpp" static debug::Logger logger("png-coder"); @@ -18,7 +19,9 @@ static debug::Logger logger("png-coder"); #include // returns 0 if all-right, 1 otherwise -int _png_write(const char* filename, uint width, uint height, const ubyte* data, bool alpha) { +int _png_write( + const char* filename, uint width, uint height, const ubyte* data, bool alpha +) { uint pixsize = alpha ? 4 : 3; // Open file for writing (binary mode) @@ -30,7 +33,9 @@ int _png_write(const char* filename, uint width, uint height, const ubyte* data, } // Initialize write structure - png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); + png_structp png_ptr = png_create_write_struct( + PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr + ); if (png_ptr == nullptr) { logger.error() << "could not allocate write struct"; fclose(fp); @@ -43,9 +48,8 @@ int _png_write(const char* filename, uint width, uint height, const ubyte* data, logger.error() << "could not allocate info struct"; fclose(fp); png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1); - png_destroy_write_struct(&png_ptr, (png_infopp)nullptr); + png_destroy_write_struct(&png_ptr, (png_infopp) nullptr); return 1; - } // Setup Exception handling @@ -60,13 +64,17 @@ int _png_write(const char* filename, uint width, uint height, const ubyte* data, png_init_io(png_ptr, fp); // Write header (8 bit colour depth) - png_set_IHDR(png_ptr, info_ptr, width, height, - 8, - alpha ? PNG_COLOR_TYPE_RGBA : - PNG_COLOR_TYPE_RGB, - PNG_INTERLACE_NONE, - PNG_COMPRESSION_TYPE_BASE, - PNG_FILTER_TYPE_BASE); + png_set_IHDR( + png_ptr, + info_ptr, + width, + height, + 8, + alpha ? PNG_COLOR_TYPE_RGBA : PNG_COLOR_TYPE_RGB, + PNG_INTERLACE_NONE, + PNG_COMPRESSION_TYPE_BASE, + PNG_FILTER_TYPE_BASE + ); png_write_info(png_ptr, info_ptr); @@ -75,7 +83,8 @@ int _png_write(const char* filename, uint width, uint height, const ubyte* data, for (uint y = 0; y < height; y++) { for (uint x = 0; x < width; x++) { for (uint i = 0; i < pixsize; i++) { - row[x * pixsize + i] = (png_byte)data[(y * width + x) * pixsize + i]; + row[x * pixsize + i] = + (png_byte)data[(y * width + x) * pixsize + i]; } } png_write_row(png_ptr, row.get()); @@ -90,29 +99,31 @@ int _png_write(const char* filename, uint width, uint height, const ubyte* data, return 0; } -std::unique_ptr _png_load(const char* file){ +std::unique_ptr _png_load(const char* file) { FILE* fp = nullptr; if ((fp = fopen(file, "rb")) == nullptr) { return nullptr; } - png_struct* png = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); + png_struct* png = png_create_read_struct( + PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr + ); if (png == nullptr) { fclose(fp); return nullptr; } png_info* info = png_create_info_struct(png); if (info == nullptr) { - png_destroy_read_struct(&png, (png_info**) nullptr, (png_info**) nullptr); + png_destroy_read_struct(&png, (png_info**)nullptr, (png_info**)nullptr); fclose(fp); return nullptr; } png_info* end_info = png_create_info_struct(png); if (end_info == nullptr) { - png_destroy_read_struct(&png, (png_info**) nullptr, (png_info**) nullptr); + png_destroy_read_struct(&png, (png_info**)nullptr, (png_info**)nullptr); fclose(fp); return nullptr; } - + if (setjmp(png_jmpbuf(png))) { png_destroy_read_struct(&png, &info, &end_info); fclose(fp); @@ -122,46 +133,42 @@ std::unique_ptr _png_load(const char* file){ png_init_io(png, fp); png_read_info(png, info); - int width = png_get_image_width(png, info); - int height = png_get_image_height(png, info); + int width = png_get_image_width(png, info); + int height = png_get_image_height(png, info); png_byte color_type = png_get_color_type(png, info); - int bit_depth = png_get_bit_depth(png, info); + int bit_depth = png_get_bit_depth(png, info); - if(bit_depth == 16) - png_set_strip_16(png); + if (bit_depth == 16) png_set_strip_16(png); - if(color_type == PNG_COLOR_TYPE_PALETTE) - png_set_palette_to_rgb(png); + if (color_type == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png); - if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) + if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) png_set_expand_gray_1_2_4_to_8(png); - if(png_get_valid(png, info, PNG_INFO_tRNS)) - png_set_tRNS_to_alpha(png); + if (png_get_valid(png, info, PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png); // These color_type don't have an alpha channel then fill it with 0xff. - if(color_type == PNG_COLOR_TYPE_RGB || - color_type == PNG_COLOR_TYPE_GRAY || + if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_PALETTE) png_set_filler(png, 0xFF, PNG_FILLER_AFTER); - if(color_type == PNG_COLOR_TYPE_GRAY || - color_type == PNG_COLOR_TYPE_GRAY_ALPHA) + if (color_type == PNG_COLOR_TYPE_GRAY || + color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png); png_read_update_info(png, info); int row_bytes = png_get_rowbytes(png, info); - //color_type = png_get_color_type(png, info); - // png_get_color_type returns 2 (RGB) but raster always have alpha channel - // due to PNG_FILLER_AFTER + // color_type = png_get_color_type(png, info); + // png_get_color_type returns 2 (RGB) but raster always have alpha channel + // due to PNG_FILLER_AFTER color_type = 6; - bit_depth = png_get_bit_depth(png, info); + bit_depth = png_get_bit_depth(png, info); auto image_data = std::make_unique(row_bytes * height); auto row_pointers = std::make_unique(height); - for (int i = 0; i < height; ++i ) { + for (int i = 0; i < height; ++i) { row_pointers[height - 1 - i] = image_data.get() + i * row_bytes; } png_read_image(png, row_pointers.get()); @@ -175,29 +182,34 @@ std::unique_ptr _png_load(const char* file){ format = ImageFormat::rgb888; break; default: - logger.error() << "color type " << color_type << " is not supported!"; + logger.error() << "color type " << color_type + << " is not supported!"; png_destroy_read_struct(&png, &info, &end_info); fclose(fp); return nullptr; } - auto image = std::make_unique(format, width, height, std::move(image_data)); + auto image = std::make_unique( + format, width, height, std::move(image_data) + ); png_destroy_read_struct(&png, &info, &end_info); fclose(fp); return image; } #else +#include #include #include -#include static const int SPNG_SUCCESS = 0; -//returns spng result code -int _png_write(const char* filename, uint width, uint height, const ubyte* data, bool alpha) { +// returns spng result code +int _png_write( + const char* filename, uint width, uint height, const ubyte* data, bool alpha +) { int fmt; int ret = 0; spng_ctx* ctx = nullptr; - spng_ihdr ihdr = { 0 }; + spng_ihdr ihdr = {0}; uint pixsize = alpha ? 4 : 3; ctx = spng_ctx_new(SPNG_CTX_ENCODER); @@ -205,12 +217,19 @@ int _png_write(const char* filename, uint width, uint height, const ubyte* data, ihdr.width = width; ihdr.height = height; - ihdr.color_type = alpha ? SPNG_COLOR_TYPE_TRUECOLOR_ALPHA : SPNG_COLOR_TYPE_TRUECOLOR; + ihdr.color_type = + alpha ? SPNG_COLOR_TYPE_TRUECOLOR_ALPHA : SPNG_COLOR_TYPE_TRUECOLOR; ihdr.bit_depth = 8; spng_set_ihdr(ctx, &ihdr); fmt = SPNG_FMT_PNG; - ret = spng_encode_image(ctx, data, (size_t)width * (size_t)height * pixsize , fmt, SPNG_ENCODE_FINALIZE); + ret = spng_encode_image( + ctx, + data, + (size_t)width * (size_t)height * pixsize, + fmt, + SPNG_ENCODE_FINALIZE + ); if (ret != SPNG_SUCCESS) { logger.error() << "spng_encode_image() error: " << spng_strerror(ret); spng_ctx_free(ctx); @@ -222,21 +241,20 @@ int _png_write(const char* filename, uint width, uint height, const ubyte* data, if (png_buf == nullptr) { logger.error() << "spng_get_png_buffer() error: " << spng_strerror(ret); - } - else { + } else { files::write_bytes(filename, (const unsigned char*)png_buf, png_size); } spng_ctx_free(ctx); return ret; } -std::unique_ptr _png_load(const char* file){ +std::unique_ptr _png_load(const char* file) { int r = 0; - FILE *png = nullptr; - spng_ctx *ctx = nullptr; + FILE* png = nullptr; + spng_ctx* ctx = nullptr; png = fopen(file, "rb"); - if (png == nullptr){ + if (png == nullptr) { logger.error() << "could not to open file " << file; return nullptr; } @@ -244,31 +262,32 @@ std::unique_ptr _png_load(const char* file){ fseek(png, 0, SEEK_END); long siz_pngbuf = ftell(png); rewind(png); - if(siz_pngbuf < 1) { + if (siz_pngbuf < 1) { fclose(png); logger.error() << "could not to read file " << file; return nullptr; } auto pngbuf = std::make_unique(siz_pngbuf); - if(fread(pngbuf.get(), siz_pngbuf, 1, png) != 1){ //check of read elements count + if (fread(pngbuf.get(), siz_pngbuf, 1, png) != + 1) { // check of read elements count fclose(png); logger.error() << "fread() failed: " << file; return nullptr; } - fclose(png); // <- finally closing file + fclose(png); // <- finally closing file ctx = spng_ctx_new(0); - if (ctx == nullptr){ + if (ctx == nullptr) { logger.error() << "spng_ctx_new() failed"; return nullptr; } r = spng_set_crc_action(ctx, SPNG_CRC_USE, SPNG_CRC_USE); - if (r != SPNG_SUCCESS){ + if (r != SPNG_SUCCESS) { spng_ctx_free(ctx); logger.error() << "spng_set_crc_action(): " << spng_strerror(r); return nullptr; } r = spng_set_png_buffer(ctx, pngbuf.get(), siz_pngbuf); - if (r != SPNG_SUCCESS){ + if (r != SPNG_SUCCESS) { spng_ctx_free(ctx); logger.error() << "spng_set_png_buffer(): " << spng_strerror(r); return nullptr; @@ -276,7 +295,7 @@ std::unique_ptr _png_load(const char* file){ spng_ihdr ihdr; r = spng_get_ihdr(ctx, &ihdr); - if (r != SPNG_SUCCESS){ + if (r != SPNG_SUCCESS) { spng_ctx_free(ctx); logger.error() << "spng_get_ihdr(): " << spng_strerror(r); return nullptr; @@ -284,28 +303,30 @@ std::unique_ptr _png_load(const char* file){ size_t out_size; r = spng_decoded_image_size(ctx, SPNG_FMT_RGBA8, &out_size); - if (r != SPNG_SUCCESS){ + if (r != SPNG_SUCCESS) { spng_ctx_free(ctx); logger.error() << "spng_decoded_image_size(): " << spng_strerror(r); return nullptr; } auto out = std::make_unique(out_size); r = spng_decode_image(ctx, out.get(), out_size, SPNG_FMT_RGBA8, 0); - if (r != SPNG_SUCCESS){ + if (r != SPNG_SUCCESS) { spng_ctx_free(ctx); logger.error() << "spng_decode_image(): " << spng_strerror(r); return nullptr; } auto flipped = std::make_unique(out_size); - for (size_t i = 0; i < ihdr.height; i+=1){ - size_t rowsize = ihdr.width*4; - for (size_t j = 0; j < rowsize; j++){ - flipped[(ihdr.height-i-1)*rowsize+j] = out[i*rowsize+j]; + for (size_t i = 0; i < ihdr.height; i += 1) { + size_t rowsize = ihdr.width * 4; + for (size_t j = 0; j < rowsize; j++) { + flipped[(ihdr.height - i - 1) * rowsize + j] = out[i * rowsize + j]; } } - auto image = std::make_unique(ImageFormat::rgba8888, ihdr.width, ihdr.height, std::move(flipped)); + auto image = std::make_unique( + ImageFormat::rgba8888, ihdr.width, ihdr.height, std::move(flipped) + ); spng_ctx_free(ctx); return image; } @@ -314,7 +335,7 @@ std::unique_ptr _png_load(const char* file){ std::unique_ptr png::load_image(const std::string& filename) { auto image = _png_load(filename.c_str()); if (image == nullptr) { - throw std::runtime_error("could not load image "+filename); + throw std::runtime_error("could not load image " + filename); } return image; } @@ -328,10 +349,10 @@ std::unique_ptr png::load_texture(const std::string& filename) { void png::write_image(const std::string& filename, const ImageData* image) { _png_write( - filename.c_str(), - image->getWidth(), - image->getHeight(), - (const ubyte*)image->getData(), + filename.c_str(), + image->getWidth(), + image->getHeight(), + (const ubyte*)image->getData(), image->getFormat() == ImageFormat::rgba8888 ); } diff --git a/src/coders/png.hpp b/src/coders/png.hpp index 59af39e5..a092e15b 100644 --- a/src/coders/png.hpp +++ b/src/coders/png.hpp @@ -13,4 +13,4 @@ namespace png { std::unique_ptr load_texture(const std::string& filename); } -#endif // CODERS_PNG_HPP_ +#endif // CODERS_PNG_HPP_ diff --git a/src/coders/rle.cpp b/src/coders/rle.cpp index 8acb5b8b..771d1a41 100644 --- a/src/coders/rle.cpp +++ b/src/coders/rle.cpp @@ -26,8 +26,7 @@ size_t rle::encode(const ubyte* src, size_t srclen, ubyte* dst) { dst[offset++] = c; c = cnext; counter = 0; - } - else { + } else { counter++; } } @@ -36,7 +35,6 @@ size_t rle::encode(const ubyte* src, size_t srclen, ubyte* dst) { return offset; } - size_t extrle::decode(const ubyte* src, size_t srclen, ubyte* dst) { size_t offset = 0; for (size_t i = 0; i < srclen;) { @@ -66,23 +64,20 @@ size_t extrle::encode(const ubyte* src, size_t srclen, ubyte* dst) { if (counter >= 0x80) { dst[offset++] = 0x80 | (counter & 0x7F); dst[offset++] = counter >> 7; - } - else { + } else { dst[offset++] = counter; } dst[offset++] = c; c = cnext; counter = 0; - } - else { + } else { counter++; } } if (counter >= 0x80) { dst[offset++] = 0x80 | (counter & 0x7F); dst[offset++] = counter >> 7; - } - else { + } else { dst[offset++] = counter; } dst[offset++] = c; diff --git a/src/coders/rle.hpp b/src/coders/rle.hpp index 9055296a..b4b5545f 100644 --- a/src/coders/rle.hpp +++ b/src/coders/rle.hpp @@ -14,4 +14,4 @@ namespace extrle { size_t decode(const ubyte* src, size_t length, ubyte* dst); } -#endif // CODERS_RLE_HPP_ +#endif // CODERS_RLE_HPP_ diff --git a/src/coders/toml.cpp b/src/coders/toml.cpp index e20a0875..9250b431 100644 --- a/src/coders/toml.cpp +++ b/src/coders/toml.cpp @@ -1,15 +1,16 @@ #include "toml.hpp" -#include "commons.hpp" -#include "../data/setting.hpp" -#include "../data/dynamic.hpp" -#include "../util/stringutil.hpp" -#include "../files/settings_io.hpp" - +#include #include + #include #include -#include + +#include "../data/dynamic.hpp" +#include "../data/setting.hpp" +#include "../files/settings_io.hpp" +#include "../util/stringutil.hpp" +#include "commons.hpp" using namespace toml; @@ -48,7 +49,7 @@ class TomlReader : BasicParser { } else { rootMap = *map; } - offset = index+1; + offset = index + 1; } while (true); } @@ -93,12 +94,9 @@ class TomlReader : BasicParser { expectNewLine(); } } - public: - TomlReader( - std::string_view file, - std::string_view source) - : BasicParser(file, source) { + TomlReader(std::string_view file, std::string_view source) + : BasicParser(file, source) { root = dynamic::create_map(); } @@ -129,7 +127,7 @@ void toml::parse( for (auto& sectionEntry : (*sectionMap)->values) { const auto& name = sectionEntry.first; auto& value = sectionEntry.second; - auto fullname = sectionName+"."+name; + auto fullname = sectionName + "." + name; if (handler.has(fullname)) { handler.setValue(fullname, value); } @@ -150,9 +148,11 @@ std::string toml::stringify(dynamic::Map& root, const std::string& name) { } for (auto& entry : root.values) { if (auto submap = std::get_if(&entry.second)) { - ss << "\n" << toml::stringify( - **submap, name.empty() ? entry.first : name+"."+entry.first - ); + ss << "\n" + << toml::stringify( + **submap, + name.empty() ? entry.first : name + "." + entry.first + ); } } return ss.str(); @@ -166,7 +166,7 @@ std::string toml::stringify(SettingsHandler& handler) { ss << "[" << section.name << "]\n"; for (const std::string& key : section.keys) { ss << key << " = "; - auto setting = handler.getSetting(section.name+"."+key); + auto setting = handler.getSetting(section.name + "." + key); assert(setting != nullptr); if (auto integer = dynamic_cast(setting)) { ss << integer->get(); diff --git a/src/coders/toml.hpp b/src/coders/toml.hpp index e695a298..28319969 100644 --- a/src/coders/toml.hpp +++ b/src/coders/toml.hpp @@ -1,21 +1,20 @@ #ifndef CODERS_TOML_HPP_ #define CODERS_TOML_HPP_ -#include "../data/dynamic.hpp" #include +#include "../data/dynamic.hpp" + class SettingsHandler; namespace toml { std::string stringify(SettingsHandler& handler); - std::string stringify(dynamic::Map& root, const std::string& name=""); + std::string stringify(dynamic::Map& root, const std::string& name = ""); dynamic::Map_sptr parse(std::string_view file, std::string_view source); void parse( - SettingsHandler& handler, - std::string_view file, - std::string_view source + SettingsHandler& handler, std::string_view file, std::string_view source ); } -#endif // CODERS_TOML_HPP_ +#endif // CODERS_TOML_HPP_ diff --git a/src/coders/wav.cpp b/src/coders/wav.cpp index 809d4f2a..c007308d 100644 --- a/src/coders/wav.cpp +++ b/src/coders/wav.cpp @@ -1,13 +1,13 @@ #include "wav.hpp" -#include "../audio/audio.hpp" -#include "../debug/Logger.hpp" - -#include -#include #include #include #include +#include +#include + +#include "../audio/audio.hpp" +#include "../debug/Logger.hpp" namespace fs = std::filesystem; @@ -20,12 +20,11 @@ bool is_big_endian() { return bytes[0] == 1; } -std::int32_t convert_to_int(char* buffer, std::size_t len){ +std::int32_t convert_to_int(char* buffer, std::size_t len) { std::int32_t a = 0; if (!is_big_endian()) { std::memcpy(&a, buffer, len); - } - else { + } else { for (std::size_t i = 0; i < len; ++i) { reinterpret_cast(&a)[3 - i] = buffer[i]; } @@ -44,18 +43,18 @@ class WavStream : public audio::PCMStream { size_t initialPosition; public: WavStream( - std::ifstream in, - uint channels, + std::ifstream in, + uint channels, uint bitsPerSample, uint sampleRate, size_t size, size_t initialPosition - ) : in(std::move(in)), - channels(channels), - bytesPerSample(bitsPerSample/8), - sampleRate(sampleRate), - totalSize(size) - { + ) + : in(std::move(in)), + channels(channels), + bytesPerSample(bitsPerSample / 8), + sampleRate(sampleRate), + totalSize(size) { totalSamples = totalSize / channels / bytesPerSample; this->initialPosition = initialPosition; } @@ -74,10 +73,9 @@ public: } return in.gcount(); } - + void close() override { - if (!isOpen()) - return; + if (!isOpen()) return; in.close(); } @@ -110,58 +108,66 @@ public: } void seek(size_t position) override { - if (!isOpen()) - return; + if (!isOpen()) return; position %= totalSamples; in.clear(); - in.seekg(initialPosition + position * channels * bytesPerSample, std::ios_base::beg); + in.seekg( + initialPosition + position * channels * bytesPerSample, + std::ios_base::beg + ); } }; std::unique_ptr wav::create_stream(const fs::path& file) { std::ifstream in(file, std::ios::binary); - if(!in.is_open()){ - throw std::runtime_error("could not to open file '"+file.u8string()+"'"); + if (!in.is_open()) { + throw std::runtime_error( + "could not to open file '" + file.u8string() + "'" + ); } char buffer[6]; // the RIFF - if(!in.read(buffer, 4)){ + if (!in.read(buffer, 4)) { throw std::runtime_error("could not to read RIFF"); } - if(std::strncmp(buffer, "RIFF", 4) != 0){ - throw std::runtime_error("file is not a valid WAVE file (header doesn't begin with RIFF)"); + if (std::strncmp(buffer, "RIFF", 4) != 0) { + throw std::runtime_error( + "file is not a valid WAVE file (header doesn't begin with RIFF)" + ); } // the size of the file - if(!in.read(buffer, 4)){ + if (!in.read(buffer, 4)) { throw std::runtime_error("could not read size of file"); } // the WAVE - if(!in.read(buffer, 4)){ + if (!in.read(buffer, 4)) { throw std::runtime_error("could not to read WAVE"); } - if(std::strncmp(buffer, "WAVE", 4) != 0){ - throw std::runtime_error("file is not a valid WAVE file (header doesn't contain WAVE)"); + if (std::strncmp(buffer, "WAVE", 4) != 0) { + throw std::runtime_error( + "file is not a valid WAVE file (header doesn't contain WAVE)" + ); } // "fmt/0" - if(!in.read(buffer, 4)){ + if (!in.read(buffer, 4)) { throw std::runtime_error("could not read fmt/0"); } // this is always 16, the size of the fmt data chunk - if(!in.read(buffer, 4)){ + if (!in.read(buffer, 4)) { throw std::runtime_error("could not read the 16"); } // PCM should be 1? - if(!in.read(buffer, 2)){ + if (!in.read(buffer, 2)) { throw std::runtime_error("could not read PCM"); } // the number of channels - if(!in.read(buffer, 2)){ + if (!in.read(buffer, 2)) { throw std::runtime_error("could not read number of channels"); } int channels = convert_to_int(buffer, 2); // sample rate - if(!in.read(buffer, 4)){ + if (!in.read(buffer, 4)) { throw std::runtime_error("could not read sample rate"); } int sampleRate = convert_to_int(buffer, 4); @@ -170,16 +176,19 @@ std::unique_ptr wav::create_stream(const fs::path& file) { } // bitsPerSample - if(!in.read(buffer, 2)){ + if (!in.read(buffer, 2)) { throw std::runtime_error("could not read bits per sample"); } int bitsPerSample = convert_to_int(buffer, 2); if (bitsPerSample >= 24) { - throw std::runtime_error(std::to_string(bitsPerSample)+" bit depth is not supported by OpenAL"); + throw std::runtime_error( + std::to_string(bitsPerSample) + + " bit depth is not supported by OpenAL" + ); } // data chunk header "data" - if(!in.read(buffer, 4)){ + if (!in.read(buffer, 4)) { throw std::runtime_error("could not read data chunk header"); } @@ -187,7 +196,7 @@ std::unique_ptr wav::create_stream(const fs::path& file) { // skip garbage in WAV if (std::strncmp(buffer, "LIST", 4) == 0) { // chunk size - if(!in.read(buffer, 4)){ + if (!in.read(buffer, 4)) { throw std::runtime_error("could not read comment chunk size"); } int chunkSize = convert_to_int(buffer, 4); @@ -195,26 +204,28 @@ std::unique_ptr wav::create_stream(const fs::path& file) { initialOffset += chunkSize + 4; - if(!in.read(buffer, 4)){ + if (!in.read(buffer, 4)) { throw std::runtime_error("could not read data chunk header"); } } - if(std::strncmp(buffer, "data", 4) != 0){ - throw std::runtime_error("file is not a valid WAVE file (doesn't have 'data' tag)"); + if (std::strncmp(buffer, "data", 4) != 0) { + throw std::runtime_error( + "file is not a valid WAVE file (doesn't have 'data' tag)" + ); } // size of data - if(!in.read(buffer, 4)){ + if (!in.read(buffer, 4)) { throw std::runtime_error("could not read data size"); } size_t size = convert_to_int(buffer, 4); /* cannot be at the end of file */ - if(in.eof()){ + if (in.eof()) { throw std::runtime_error("reached EOF on the file"); } - if(in.fail()){ + if (in.fail()) { throw std::runtime_error("fail state set on the file"); } return std::make_unique( @@ -222,7 +233,9 @@ std::unique_ptr wav::create_stream(const fs::path& file) { ); } -std::unique_ptr wav::load_pcm(const fs::path& file, bool headerOnly) { +std::unique_ptr wav::load_pcm( + const fs::path& file, bool headerOnly +) { auto stream = wav::create_stream(file); size_t totalSamples = stream->getTotalSamples(); @@ -232,9 +245,8 @@ std::unique_ptr wav::load_pcm(const fs::path& file, bool headerOnly) std::vector data; if (!headerOnly) { - size_t size = stream->getTotalSamples() * - (stream->getBitsPerSample()/8) * - stream->getChannels(); + size_t size = stream->getTotalSamples() * + (stream->getBitsPerSample() / 8) * stream->getChannels(); data.resize(size); stream->readFully(data.data(), size, false); } diff --git a/src/coders/wav.hpp b/src/coders/wav.hpp index 19428c4e..7ea8bf59 100644 --- a/src/coders/wav.hpp +++ b/src/coders/wav.hpp @@ -9,8 +9,12 @@ namespace audio { } namespace wav { - std::unique_ptr load_pcm(const std::filesystem::path& file, bool headerOnly); - std::unique_ptr create_stream(const std::filesystem::path& file); + std::unique_ptr load_pcm( + const std::filesystem::path& file, bool headerOnly + ); + std::unique_ptr create_stream( + const std::filesystem::path& file + ); } -#endif // CODERS_WAV_HPP_ +#endif // CODERS_WAV_HPP_ diff --git a/src/coders/xml.cpp b/src/coders/xml.cpp index 51c3046b..15d1f9b4 100644 --- a/src/coders/xml.cpp +++ b/src/coders/xml.cpp @@ -1,17 +1,16 @@ #include "xml.hpp" -#include "../util/stringutil.hpp" - #include -#include #include +#include #include +#include "../util/stringutil.hpp" + using namespace xml; Attribute::Attribute(std::string name, std::string text) - : name(std::move(name)), - text(std::move(text)) { + : name(std::move(name)), text(std::move(text)) { } const std::string& Attribute::getName() const { @@ -42,7 +41,7 @@ glm::vec2 Attribute::asVec2() const { } return glm::vec2( util::parse_double(text, 0, pos), - util::parse_double(text, pos+1, text.length()-pos-1) + util::parse_double(text, pos + 1, text.length() - pos - 1) ); } @@ -52,14 +51,14 @@ glm::vec3 Attribute::asVec3() const { if (pos1 == std::string::npos) { return glm::vec3(util::parse_double(text, 0, text.length())); } - size_t pos2 = text.find(',', pos1+1); + size_t pos2 = text.find(',', pos1 + 1); if (pos2 == std::string::npos) { - throw std::runtime_error("invalid vec3 value "+util::quote(text)); + throw std::runtime_error("invalid vec3 value " + util::quote(text)); } return glm::vec3( util::parse_double(text, 0, pos1), - util::parse_double(text, pos1+1, pos2), - util::parse_double(text, pos2+1, text.length()-pos2-1) + util::parse_double(text, pos1 + 1, pos2), + util::parse_double(text, pos2 + 1, text.length() - pos2 - 1) ); } @@ -69,19 +68,19 @@ glm::vec4 Attribute::asVec4() const { if (pos1 == std::string::npos) { return glm::vec4(util::parse_double(text, 0, text.length())); } - size_t pos2 = text.find(',', pos1+1); + size_t pos2 = text.find(',', pos1 + 1); if (pos2 == std::string::npos) { - throw std::runtime_error("invalid vec4 value "+util::quote(text)); + throw std::runtime_error("invalid vec4 value " + util::quote(text)); } - size_t pos3 = text.find(',', pos2+1); + size_t pos3 = text.find(',', pos2 + 1); if (pos3 == std::string::npos) { - throw std::runtime_error("invalid vec4 value "+util::quote(text)); + throw std::runtime_error("invalid vec4 value " + util::quote(text)); } return glm::vec4( util::parse_double(text, 0, pos1), - util::parse_double(text, pos1+1, pos2-pos1-1), - util::parse_double(text, pos2+1, pos3-pos2-1), - util::parse_double(text, pos3+1, text.length()-pos3-1) + util::parse_double(text, pos1 + 1, pos2 - pos1 - 1), + util::parse_double(text, pos2 + 1, pos3 - pos2 - 1), + util::parse_double(text, pos3 + 1, text.length() - pos3 - 1) ); } @@ -112,7 +111,7 @@ void Node::add(const xmlelement& element) { elements.push_back(element); } -void Node::set(const std::string& name, const std::string &text) { +void Node::set(const std::string& name, const std::string& text) { attrs[name] = Attribute(name, text); } @@ -123,7 +122,9 @@ const std::string& Node::getTag() const { const xmlattribute& Node::attr(const std::string& name) const { auto found = attrs.find(name); if (found == attrs.end()) { - throw std::runtime_error("element <"+tag+" ...> missing attribute "+name); + throw std::runtime_error( + "element <" + tag + " ...> missing attribute " + name + ); } return found->second; } @@ -158,11 +159,10 @@ const xmlelements_map& Node::getAttributes() const { } Document::Document(std::string version, std::string encoding) - : version(std::move(version)), - encoding(std::move(encoding)) { + : version(std::move(version)), encoding(std::move(encoding)) { } -void Document::setRoot(const xmlelement &element) { +void Document::setRoot(const xmlelement& element) { this->root = element; } @@ -178,7 +178,7 @@ const std::string& Document::getEncoding() const { return encoding; } -Parser::Parser(std::string_view filename, std::string_view source) +Parser::Parser(std::string_view filename, std::string_view source) : BasicParser(filename, source) { } @@ -190,15 +190,14 @@ xmlelement Parser::parseOpenTag() { while (true) { skipWhitespace(); c = peek(); - if (c == '/' || c == '>' || c == '?') - break; + if (c == '/' || c == '>' || c == '?') break; std::string attrname = parseXMLName(); std::string attrtext = ""; skipWhitespace(); if (peek() == '=') { nextChar(); skipWhitespace(); - + char quote = peek(); if (quote != '\'' && quote != '"') { throw error("string literal expected"); @@ -251,7 +250,7 @@ std::string Parser::parseText() { } nextChar(); } - return std::string(source.substr(start, pos-start)); + return std::string(source.substr(start, pos - start)); } inline bool is_xml_identifier_start(char c) { @@ -259,7 +258,7 @@ inline bool is_xml_identifier_start(char c) { } inline bool is_xml_identifier_part(char c) { - return is_identifier_part(c) || c == '-' || c == '.' || c == ':'; + return is_identifier_part(c) || c == '-' || c == '.' || c == ':'; } std::string Parser::parseXMLName() { @@ -271,7 +270,7 @@ std::string Parser::parseXMLName() { while (hasNext() && is_xml_identifier_part(source[pos])) { pos++; } - return std::string(source.substr(start, pos-start)); + return std::string(source.substr(start, pos - start)); } xmlelement Parser::parseElement() { @@ -300,12 +299,12 @@ xmlelement Parser::parseElement() { auto element = parseOpenTag(); char c = nextChar(); - + // if (c == '/') { expect('>'); } - // ... + // ... else if (c == '>') { skipWhitespace(); while (!isNext("getTag()); expect('>'); } - // + // else { throw error("invalid syntax"); } @@ -343,13 +342,9 @@ xmldocument xml::parse(const std::string& filename, const std::string& source) { } inline void newline( - std::stringstream& ss, - bool nice, - const std::string& indentStr, - int indent + std::stringstream& ss, bool nice, const std::string& indentStr, int indent ) { - if (!nice) - return; + if (!nice) return; ss << '\n'; for (int i = 0; i < indent; i++) { ss << indentStr; @@ -366,7 +361,7 @@ static void stringifyElement( if (element->isText()) { std::string text = element->attr("#").getText(); util::replaceAll(text, "&", "&"); - util::replaceAll(text, "\"","""); + util::replaceAll(text, "\"", """); util::replaceAll(text, "'", "'"); util::replaceAll(text, "<", "<"); util::replaceAll(text, ">", ">"); @@ -395,32 +390,29 @@ static void stringifyElement( auto& elements = element->getElements(); if (elements.size() == 1 && elements[0]->isText()) { ss << ">"; - stringifyElement(ss, elements[0], nice, indentStr, indent+1); + stringifyElement(ss, elements[0], nice, indentStr, indent + 1); ss << ""; return; } if (!elements.empty()) { ss << '>'; for (auto& sub : elements) { - newline(ss, nice, indentStr, indent+1); - stringifyElement(ss, sub, nice, indentStr, indent+1); + newline(ss, nice, indentStr, indent + 1); + stringifyElement(ss, sub, nice, indentStr, indent + 1); } newline(ss, nice, indentStr, indent); ss << ""; - + } else { ss << "/>"; } - } std::string xml::stringify( - const xmldocument& document, - bool nice, - const std::string& indentStr + const xmldocument& document, bool nice, const std::string& indentStr ) { std::stringstream ss; - + // XML declaration ss << "getVersion(); ss << "\" encoding=\"UTF-8\" ?>"; diff --git a/src/coders/xml.hpp b/src/coders/xml.hpp index 4af2e4b1..72fdb563 100644 --- a/src/coders/xml.hpp +++ b/src/coders/xml.hpp @@ -1,13 +1,13 @@ #ifndef CODERS_XML_HPP_ #define CODERS_XML_HPP_ -#include "commons.hpp" - -#include -#include -#include #include +#include +#include #include +#include + +#include "commons.hpp" namespace xml { class Node; @@ -37,7 +37,8 @@ namespace xml { glm::vec4 asColor() const; }; - /// @brief XML element class. Text element has tag 'text' and attribute 'text' + /// @brief XML element class. Text element has tag 'text' and attribute + /// 'text' class Node { std::string tag; std::unordered_map attrs; @@ -51,8 +52,8 @@ namespace xml { /// @brief Set attribute value. Creates attribute if does not exists /// @param name attribute name /// @param text attribute value - void set(const std::string& name, const std::string &text); - + void set(const std::string& name, const std::string& text); + /// @brief Get element tag const std::string& getTag() const; @@ -66,16 +67,17 @@ namespace xml { /// @brief Get attribute by name /// @param name attribute name - /// @throws std::runtime_error if element has no attribute + /// @throws std::runtime_error if element has no attribute /// @return xmlattribute - {name, value} const xmlattribute& attr(const std::string& name) const; - + /// @brief Get attribute by name /// @param name attribute name /// @param def default value will be returned wrapped in xmlattribute - /// if element has no attribute + /// if element has no attribute /// @return xmlattribute - {name, value} or {name, def} if not found*/ - xmlattribute attr(const std::string& name, const std::string& def) const; + xmlattribute attr(const std::string& name, const std::string& def) + const; /// @brief Check if element has attribute /// @param name attribute name @@ -101,7 +103,7 @@ namespace xml { public: Document(std::string version, std::string encoding); - void setRoot(const xmlelement &element); + void setRoot(const xmlelement& element); xmlelement getRoot() const; const std::string& getVersion() const; @@ -123,22 +125,24 @@ namespace xml { xmldocument parse(); }; - /// @brief Serialize XML Document to string + /// @brief Serialize XML Document to string /// @param document serializing document /// @param nice use human readable format (with indents and line-separators) /// @param indentStr indentation characters sequence (default - 4 spaces) /// @return XML string extern std::string stringify( const xmldocument& document, - bool nice=true, - const std::string& indentStr=" " + bool nice = true, + const std::string& indentStr = " " ); - + /// @brief Read XML Document from string /// @param filename file name will be shown in error messages /// @param source xml source code string /// @return xml document - extern xmldocument parse(const std::string& filename, const std::string& source); + extern xmldocument parse( + const std::string& filename, const std::string& source + ); } -#endif // CODERS_XML_HPP_ +#endif // CODERS_XML_HPP_ diff --git a/src/content/Content.cpp b/src/content/Content.cpp index 2e5612a4..0171f27a 100644 --- a/src/content/Content.cpp +++ b/src/content/Content.cpp @@ -1,29 +1,29 @@ #include "Content.hpp" +#include #include #include -#include #include -#include "../voxels/Block.hpp" #include "../items/ItemDef.hpp" +#include "../logic/scripting/scripting.hpp" #include "../objects/EntityDef.hpp" #include "../objects/rigging.hpp" - +#include "../voxels/Block.hpp" #include "ContentPack.hpp" -#include "../logic/scripting/scripting.hpp" ContentIndices::ContentIndices( ContentUnitIndices blocks, ContentUnitIndices items, ContentUnitIndices entities -) : blocks(std::move(blocks)), - items(std::move(items)), - entities(std::move(entities)) -{} +) + : blocks(std::move(blocks)), + items(std::move(items)), + entities(std::move(entities)) { +} Content::Content( - std::unique_ptr indices, + std::unique_ptr indices, std::unique_ptr drawGroups, ContentUnitDefs blocks, ContentUnitDefs items, @@ -32,15 +32,15 @@ Content::Content( UptrsMap blockMaterials, UptrsMap skeletons, ResourceIndicesSet resourceIndices -) : indices(std::move(indices)), - packs(std::move(packs)), - blockMaterials(std::move(blockMaterials)), - skeletons(std::move(skeletons)), - blocks(std::move(blocks)), - items(std::move(items)), - entities(std::move(entities)), - drawGroups(std::move(drawGroups)) -{ +) + : indices(std::move(indices)), + packs(std::move(packs)), + blockMaterials(std::move(blockMaterials)), + skeletons(std::move(skeletons)), + blocks(std::move(blocks)), + items(std::move(items)), + entities(std::move(entities)), + drawGroups(std::move(drawGroups)) { for (size_t i = 0; i < RESOURCE_TYPES_COUNT; i++) { this->resourceIndices[i] = std::move(resourceIndices[i]); } @@ -48,7 +48,8 @@ Content::Content( Content::~Content() = default; -const rigging::SkeletonConfig* Content::getSkeleton(const std::string& id) const { +const rigging::SkeletonConfig* Content::getSkeleton(const std::string& id +) const { auto found = skeletons.find(id); if (found == skeletons.end()) { return nullptr; @@ -80,6 +81,7 @@ const UptrsMap& Content::getPacks() const { return packs; } -const UptrsMap& Content::getSkeletons() const { +const UptrsMap& Content::getSkeletons( +) const { return skeletons; } diff --git a/src/content/Content.hpp b/src/content/Content.hpp index 16e072b7..1f5245be 100644 --- a/src/content/Content.hpp +++ b/src/content/Content.hpp @@ -1,20 +1,19 @@ #ifndef CONTENT_CONTENT_HPP_ #define CONTENT_CONTENT_HPP_ -#include "content_fwd.hpp" - -#include "../data/dynamic_fwd.hpp" - -#include -#include #include #include -#include -#include #include +#include +#include +#include +#include + +#include "../data/dynamic_fwd.hpp" +#include "content_fwd.hpp" using DrawGroups = std::set; -template +template using UptrsMap = std::unordered_map>; class Block; @@ -28,31 +27,37 @@ namespace rigging { constexpr const char* contenttype_name(contenttype type) { switch (type) { - case contenttype::none: return "none"; - case contenttype::block: return "block"; - case contenttype::item: return "item"; - case contenttype::entity: return "entity"; + case contenttype::none: + return "none"; + case contenttype::block: + return "block"; + case contenttype::item: + return "item"; + case contenttype::entity: + return "entity"; default: return "unknown"; } } -class namereuse_error: public std::runtime_error { +class namereuse_error : public std::runtime_error { contenttype type; public: namereuse_error(const std::string& msg, contenttype type) - : std::runtime_error(msg), type(type) {} + : std::runtime_error(msg), type(type) { + } inline contenttype getType() const { return type; } }; -template +template class ContentUnitIndices { std::vector defs; public: - ContentUnitIndices(std::vector defs) : defs(std::move(defs)) {} + ContentUnitIndices(std::vector defs) : defs(std::move(defs)) { + } inline T* get(blockid_t id) const { if (id >= defs.size()) { @@ -84,12 +89,11 @@ public: ); }; -template +template class ContentUnitDefs { UptrsMap defs; public: - ContentUnitDefs(UptrsMap defs) - : defs(std::move(defs)) { + ContentUnitDefs(UptrsMap defs) : defs(std::move(defs)) { } T* find(const std::string& id) const { @@ -102,7 +106,7 @@ public: T& require(const std::string& id) const { const auto& found = defs.find(id); if (found == defs.end()) { - throw std::runtime_error("missing content unit "+id); + throw std::runtime_error("missing content unit " + id); } return *found->second; } @@ -113,8 +117,8 @@ class ResourceIndices { std::unordered_map indices; std::unique_ptr> savedData; public: - ResourceIndices() - : savedData(std::make_unique>()){ + ResourceIndices() + : savedData(std::make_unique>()) { } static constexpr size_t MISSING = SIZE_MAX; @@ -152,8 +156,10 @@ public: constexpr const char* to_string(ResourceType type) { switch (type) { - case ResourceType::CAMERA: return "camera"; - default: return "unknown"; + case ResourceType::CAMERA: + return "camera"; + default: + return "unknown"; } } @@ -180,7 +186,7 @@ public: ResourceIndicesSet resourceIndices {}; Content( - std::unique_ptr indices, + std::unique_ptr indices, std::unique_ptr drawGroups, ContentUnitDefs blocks, ContentUnitDefs items, @@ -209,4 +215,4 @@ public: const UptrsMap& getSkeletons() const; }; -#endif // CONTENT_CONTENT_HPP_ +#endif // CONTENT_CONTENT_HPP_ diff --git a/src/content/ContentBuilder.cpp b/src/content/ContentBuilder.cpp index 76f3052c..0d94b61e 100644 --- a/src/content/ContentBuilder.cpp +++ b/src/content/ContentBuilder.cpp @@ -24,7 +24,7 @@ std::unique_ptr ContentBuilder::build() { auto groups = std::make_unique(); for (const std::string& name : blocks.names) { Block& def = *blocks.defs[name]; - + // Generating runtime info def.rt.id = blockDefsIndices.size(); def.rt.emissive = *reinterpret_cast(def.emission); @@ -48,7 +48,7 @@ std::unique_ptr ContentBuilder::build() { std::vector itemDefsIndices; for (const std::string& name : items.names) { ItemDef& def = *items.defs[name]; - + // Generating runtime info def.rt.id = itemDefsIndices.size(); def.rt.emissive = *reinterpret_cast(def.emission); @@ -66,11 +66,10 @@ std::unique_ptr ContentBuilder::build() { auto content = std::make_unique( std::make_unique( - blockDefsIndices, - itemDefsIndices, - entityDefsIndices), + blockDefsIndices, itemDefsIndices, entityDefsIndices + ), std::move(groups), - blocks.build(), + blocks.build(), items.build(), entities.build(), std::move(packs), diff --git a/src/content/ContentBuilder.hpp b/src/content/ContentBuilder.hpp index 5c188ca3..10cdd480 100644 --- a/src/content/ContentBuilder.hpp +++ b/src/content/ContentBuilder.hpp @@ -1,17 +1,17 @@ #ifndef CONTENT_CONTENT_BUILDER_HPP_ #define CONTENT_CONTENT_BUILDER_HPP_ -#include "../items/ItemDef.hpp" -#include "../voxels/Block.hpp" -#include "../objects/EntityDef.hpp" +#include +#include +#include + #include "../content/Content.hpp" #include "../content/ContentPack.hpp" +#include "../items/ItemDef.hpp" +#include "../objects/EntityDef.hpp" +#include "../voxels/Block.hpp" -#include -#include -#include - -template +template class ContentUnitBuilder { std::unordered_map& allNames; contenttype type; @@ -19,17 +19,20 @@ class ContentUnitBuilder { void checkIdentifier(const std::string& id) { const auto& found = allNames.find(id); if (found != allNames.end()) { - throw namereuse_error("name "+id+" is already used", found->second); + throw namereuse_error( + "name " + id + " is already used", found->second + ); } } public: UptrsMap defs; std::vector names; - + ContentUnitBuilder( - std::unordered_map& allNames, - contenttype type - ) : allNames(allNames), type(type) {} + std::unordered_map& allNames, contenttype type + ) + : allNames(allNames), type(type) { + } T& create(const std::string& id) { auto found = defs.find(id); @@ -69,4 +72,4 @@ public: std::unique_ptr build(); }; -#endif // CONTENT_CONTENT_BUILDER_HPP_ +#endif // CONTENT_CONTENT_BUILDER_HPP_ diff --git a/src/content/ContentLUT.cpp b/src/content/ContentLUT.cpp index 5aa95bc3..7808b48f 100644 --- a/src/content/ContentLUT.cpp +++ b/src/content/ContentLUT.cpp @@ -1,26 +1,30 @@ #include "ContentLUT.hpp" -#include "Content.hpp" -#include "../constants.hpp" -#include "../files/files.hpp" -#include "../coders/json.hpp" -#include "../voxels/Block.hpp" -#include "../items/ItemDef.hpp" #include -ContentLUT::ContentLUT(const ContentIndices* indices, size_t blocksCount, size_t itemsCount) - : blocks(blocksCount, indices->blocks, BLOCK_VOID, contenttype::block), - items(itemsCount, indices->items, ITEM_VOID, contenttype::item) -{} +#include "../coders/json.hpp" +#include "../constants.hpp" +#include "../files/files.hpp" +#include "../items/ItemDef.hpp" +#include "../voxels/Block.hpp" +#include "Content.hpp" -template static constexpr size_t get_entries_count( - const ContentUnitIndices& indices, const dynamic::List_sptr& list) { +ContentLUT::ContentLUT( + const ContentIndices* indices, size_t blocksCount, size_t itemsCount +) + : blocks(blocksCount, indices->blocks, BLOCK_VOID, contenttype::block), + items(itemsCount, indices->items, ITEM_VOID, contenttype::item) { +} + +template +static constexpr size_t get_entries_count( + const ContentUnitIndices& indices, const dynamic::List_sptr& list +) { return list ? std::max(list->size(), indices.count()) : indices.count(); } std::shared_ptr ContentLUT::create( - const fs::path& filename, - const Content* content + const fs::path& filename, const Content* content ) { auto root = files::read_json(filename); auto blocklist = root->list("blocks"); diff --git a/src/content/ContentLUT.hpp b/src/content/ContentLUT.hpp index baf347d7..be6f4b7a 100644 --- a/src/content/ContentLUT.hpp +++ b/src/content/ContentLUT.hpp @@ -1,16 +1,15 @@ #ifndef CONTENT_CONTENT_LUT_HPP_ #define CONTENT_CONTENT_LUT_HPP_ -#include "Content.hpp" - -#include "../typedefs.hpp" -#include "../constants.hpp" -#include "../data/dynamic.hpp" - +#include #include #include #include -#include + +#include "../constants.hpp" +#include "../data/dynamic.hpp" +#include "../typedefs.hpp" +#include "Content.hpp" namespace fs = std::filesystem; @@ -19,7 +18,7 @@ struct contententry { std::string name; }; -template +template class ContentUnitLUT { std::vector indices; std::vector names; @@ -28,8 +27,13 @@ class ContentUnitLUT { T missingValue; contenttype type; public: - ContentUnitLUT(size_t count, const ContentUnitIndices& unitIndices, T missingValue, contenttype type) - : missingValue(missingValue), type(type) { + ContentUnitLUT( + size_t count, + const ContentUnitIndices& unitIndices, + T missingValue, + contenttype type + ) + : missingValue(missingValue), type(type) { for (size_t i = 0; i < count; i++) { indices.push_back(i); } @@ -47,7 +51,7 @@ public: if (auto def = defs.find(name)) { set(i, name, def->rt.id); } else { - set(i, name, missingValue); + set(i, name, missingValue); } } } @@ -86,7 +90,7 @@ public: } }; -/// @brief Content indices lookup table or report +/// @brief Content indices lookup table or report /// used to convert world with different indices /// Building with indices.json class ContentLUT { @@ -97,10 +101,9 @@ public: ContentLUT(const ContentIndices* indices, size_t blocks, size_t items); static std::shared_ptr create( - const fs::path& filename, - const Content* content + const fs::path& filename, const Content* content ); - + inline bool hasContentReorder() const { return blocks.hasContentReorder() || items.hasContentReorder(); } @@ -111,4 +114,4 @@ public: std::vector getMissingContent() const; }; -#endif // CONTENT_CONTENT_LUT_HPP_ +#endif // CONTENT_CONTENT_LUT_HPP_ diff --git a/src/content/ContentLoader.cpp b/src/content/ContentLoader.cpp index f69b8758..16bccb34 100644 --- a/src/content/ContentLoader.cpp +++ b/src/content/ContentLoader.cpp @@ -1,34 +1,33 @@ #include "ContentLoader.hpp" -#include "Content.hpp" -#include "ContentPack.hpp" -#include "ContentBuilder.hpp" +#include +#include +#include +#include +#include + #include "../coders/json.hpp" #include "../core_defs.hpp" #include "../data/dynamic.hpp" #include "../debug/Logger.hpp" #include "../files/files.hpp" #include "../items/ItemDef.hpp" -#include "../objects/rigging.hpp" #include "../logic/scripting/scripting.hpp" +#include "../objects/rigging.hpp" #include "../typedefs.hpp" #include "../util/listutil.hpp" #include "../util/stringutil.hpp" #include "../voxels/Block.hpp" - -#include -#include -#include -#include -#include +#include "Content.hpp" +#include "ContentBuilder.hpp" +#include "ContentPack.hpp" namespace fs = std::filesystem; static debug::Logger logger("content-loader"); ContentLoader::ContentLoader(ContentPack* pack, ContentBuilder& builder) - : pack(pack), builder(builder) -{ + : pack(pack), builder(builder) { auto runtime = std::make_unique( *pack, scripting::create_pack_environment(*pack) ); @@ -97,9 +96,9 @@ bool ContentLoader::fixPackIndices( void ContentLoader::fixPackIndices() { auto folder = pack->folder; auto indexFile = pack->getContentFile(); - auto blocksFolder = folder/ContentPack::BLOCKS_FOLDER; - auto itemsFolder = folder/ContentPack::ITEMS_FOLDER; - auto entitiesFolder = folder/ContentPack::ENTITIES_FOLDER; + auto blocksFolder = folder / ContentPack::BLOCKS_FOLDER; + auto itemsFolder = folder / ContentPack::ITEMS_FOLDER; + auto entitiesFolder = folder / ContentPack::ENTITIES_FOLDER; dynamic::Map_sptr root; if (fs::is_regular_file(indexFile)) { @@ -113,13 +112,15 @@ void ContentLoader::fixPackIndices() { modified |= fixPackIndices(itemsFolder, root.get(), "items"); modified |= fixPackIndices(entitiesFolder, root.get(), "entities"); - if (modified){ + if (modified) { // rewrite modified json files::write_json(indexFile, root.get()); } } -void ContentLoader::loadBlock(Block& def, const std::string& name, const fs::path& file) { +void ContentLoader::loadBlock( + Block& def, const std::string& name, const fs::path& file +) { auto root = files::read_json(file); root->str("caption", def.caption); @@ -169,7 +170,7 @@ void ContentLoader::loadBlock(Block& def, const std::string& name, const fs::pat logger.error() << "unknown rotation profile " << profile; def.rotatable = false; } - + // block hitbox AABB [x, y, z, width, height, depth] auto boxarr = root->list("hitboxes"); if (boxarr) { @@ -181,16 +182,16 @@ void ContentLoader::loadBlock(Block& def, const std::string& name, const fs::pat hitboxesIndex.b = glm::vec3(box->num(3), box->num(4), box->num(5)); hitboxesIndex.b += hitboxesIndex.a; } - } else if ((boxarr = root->list("hitbox"))){ + } else if ((boxarr = root->list("hitbox"))) { AABB aabb; aabb.a = glm::vec3(boxarr->num(0), boxarr->num(1), boxarr->num(2)); aabb.b = glm::vec3(boxarr->num(3), boxarr->num(4), boxarr->num(5)); aabb.b += aabb.a; - def.hitboxes = { aabb }; + def.hitboxes = {aabb}; } else if (!def.modelBoxes.empty()) { def.hitboxes = def.modelBoxes; } else { - def.hitboxes = { AABB() }; + def.hitboxes = {AABB()}; } // block light emission [r, g, b] where r,g,b in range [0..15] @@ -205,8 +206,8 @@ void ContentLoader::loadBlock(Block& def, const std::string& name, const fs::pat def.size.x = sizearr->num(0); def.size.y = sizearr->num(1); def.size.z = sizearr->num(2); - if (def.model == BlockModel::block && - (def.size.x != 1 || def.size.y != 1 || def.size.z != 1)) { + if (def.model == BlockModel::block && + (def.size.x != 1 || def.size.y != 1 || def.size.z != 1)) { def.model = BlockModel::aabb; def.hitboxes = {AABB(def.size)}; } @@ -233,7 +234,7 @@ void ContentLoader::loadBlock(Block& def, const std::string& name, const fs::pat def.tickInterval = 1; } - if (def.hidden && def.pickingItem == def.name+BLOCK_ITEM_SUFFIX) { + if (def.hidden && def.pickingItem == def.name + BLOCK_ITEM_SUFFIX) { def.pickingItem = CORE_EMPTY; } } @@ -241,12 +242,14 @@ void ContentLoader::loadBlock(Block& def, const std::string& name, const fs::pat void ContentLoader::loadCustomBlockModel(Block& def, dynamic::Map* primitives) { if (primitives->has("aabbs")) { auto modelboxes = primitives->list("aabbs"); - for (uint i = 0; i < modelboxes->size(); i++ ) { + for (uint i = 0; i < modelboxes->size(); i++) { /* Parse aabb */ auto boxarr = modelboxes->list(i); AABB modelbox; - modelbox.a = glm::vec3(boxarr->num(0), boxarr->num(1), boxarr->num(2)); - modelbox.b = glm::vec3(boxarr->num(3), boxarr->num(4), boxarr->num(5)); + modelbox.a = + glm::vec3(boxarr->num(0), boxarr->num(1), boxarr->num(2)); + modelbox.b = + glm::vec3(boxarr->num(3), boxarr->num(4), boxarr->num(5)); modelbox.b += modelbox.a; def.modelBoxes.push_back(modelbox); @@ -270,19 +273,21 @@ void ContentLoader::loadCustomBlockModel(Block& def, dynamic::Map* primitives) { /* Parse tetragon to points */ auto tgonobj = modeltetragons->list(i); glm::vec3 p1(tgonobj->num(0), tgonobj->num(1), tgonobj->num(2)), - xw(tgonobj->num(3), tgonobj->num(4), tgonobj->num(5)), - yh(tgonobj->num(6), tgonobj->num(7), tgonobj->num(8)); + xw(tgonobj->num(3), tgonobj->num(4), tgonobj->num(5)), + yh(tgonobj->num(6), tgonobj->num(7), tgonobj->num(8)); def.modelExtraPoints.push_back(p1); - def.modelExtraPoints.push_back(p1+xw); - def.modelExtraPoints.push_back(p1+xw+yh); - def.modelExtraPoints.push_back(p1+yh); + def.modelExtraPoints.push_back(p1 + xw); + def.modelExtraPoints.push_back(p1 + xw + yh); + def.modelExtraPoints.push_back(p1 + yh); def.modelTextures.emplace_back(tgonobj->str(9)); } } } -void ContentLoader::loadItem(ItemDef& def, const std::string& name, const fs::path& file) { +void ContentLoader::loadItem( + ItemDef& def, const std::string& name, const fs::path& file +) { auto root = files::read_json(file); root->str("caption", def.caption); @@ -294,7 +299,7 @@ void ContentLoader::loadItem(ItemDef& def, const std::string& name, const fs::pa def.iconType = item_icon_type::block; } else if (iconTypeStr == "sprite") { def.iconType = item_icon_type::sprite; - } else if (iconTypeStr.length()){ + } else if (iconTypeStr.length()) { logger.error() << name << ": unknown icon type" << iconTypeStr; } root->str("icon", def.icon); @@ -310,7 +315,9 @@ void ContentLoader::loadItem(ItemDef& def, const std::string& name, const fs::pa } } -void ContentLoader::loadEntity(EntityDef& def, const std::string& name, const fs::path& file) { +void ContentLoader::loadEntity( + EntityDef& def, const std::string& name, const fs::path& file +) { auto root = files::read_json(file); if (auto componentsarr = root->list("components")) { for (size_t i = 0; i < componentsarr->size(); i++) { @@ -325,14 +332,21 @@ void ContentLoader::loadEntity(EntityDef& def, const std::string& name, const fs if (auto sensorarr = sensorsarr->list(i)) { auto sensorType = sensorarr->str(0); if (sensorType == "aabb") { - def.boxSensors.emplace_back(i, AABB{ - {sensorarr->num(1), sensorarr->num(2), sensorarr->num(3)}, - {sensorarr->num(4), sensorarr->num(5), sensorarr->num(6)} - }); + def.boxSensors.emplace_back( + i, + AABB { + {sensorarr->num(1), + sensorarr->num(2), + sensorarr->num(3)}, + {sensorarr->num(4), + sensorarr->num(5), + sensorarr->num(6)}} + ); } else if (sensorType == "radius") { def.radialSensors.emplace_back(i, sensorarr->num(1)); } else { - logger.error() << name << ": sensor #" << i << " - unknown type " + logger.error() + << name << ": sensor #" << i << " - unknown type " << util::quote(sensorType); } } @@ -354,29 +368,33 @@ void ContentLoader::loadEntity(EntityDef& def, const std::string& name, const fs root->flag("blocking", def.blocking); } -void ContentLoader::loadEntity(EntityDef& def, const std::string& full, const std::string& name) { +void ContentLoader::loadEntity( + EntityDef& def, const std::string& full, const std::string& name +) { auto folder = pack->folder; - auto configFile = folder/fs::path("entities/"+name+".json"); + auto configFile = folder / fs::path("entities/" + name + ".json"); if (fs::exists(configFile)) loadEntity(def, full, configFile); } -void ContentLoader::loadBlock(Block& def, const std::string& full, const std::string& name) { +void ContentLoader::loadBlock( + Block& def, const std::string& full, const std::string& name +) { auto folder = pack->folder; - auto configFile = folder/fs::path("blocks/"+name+".json"); + auto configFile = folder / fs::path("blocks/" + name + ".json"); if (fs::exists(configFile)) loadBlock(def, full, configFile); - auto scriptfile = folder/fs::path("scripts/"+def.scriptName+".lua"); + auto scriptfile = folder / fs::path("scripts/" + def.scriptName + ".lua"); if (fs::is_regular_file(scriptfile)) { scripting::load_block_script(env, full, scriptfile, def.rt.funcsset); } if (!def.hidden) { - auto& item = builder.items.create(full+BLOCK_ITEM_SUFFIX); + auto& item = builder.items.create(full + BLOCK_ITEM_SUFFIX); item.generated = true; item.caption = def.caption; item.iconType = item_icon_type::block; item.icon = full; item.placingBlock = full; - + for (uint j = 0; j < 4; j++) { item.emission[j] = def.emission[j]; } @@ -384,18 +402,22 @@ void ContentLoader::loadBlock(Block& def, const std::string& full, const std::st } } -void ContentLoader::loadItem(ItemDef& def, const std::string& full, const std::string& name) { +void ContentLoader::loadItem( + ItemDef& def, const std::string& full, const std::string& name +) { auto folder = pack->folder; - auto configFile = folder/fs::path("items/"+name+".json"); + auto configFile = folder / fs::path("items/" + name + ".json"); if (fs::exists(configFile)) loadItem(def, full, configFile); - auto scriptfile = folder/fs::path("scripts/"+def.scriptName+".lua"); + auto scriptfile = folder / fs::path("scripts/" + def.scriptName + ".lua"); if (fs::is_regular_file(scriptfile)) { scripting::load_item_script(env, full, scriptfile, def.rt.funcsset); } } -void ContentLoader::loadBlockMaterial(BlockMaterial& def, const fs::path& file) { +void ContentLoader::loadBlockMaterial( + BlockMaterial& def, const fs::path& file +) { auto root = files::read_json(file); root->str("steps-sound", def.stepsSound); root->str("place-sound", def.placeSound); @@ -409,13 +431,14 @@ void ContentLoader::load() { auto folder = pack->folder; - fs::path scriptFile = folder/fs::path("scripts/world.lua"); + fs::path scriptFile = folder / fs::path("scripts/world.lua"); if (fs::is_regular_file(scriptFile)) { - scripting::load_world_script(env, pack->id, scriptFile, runtime->worldfuncsset); + scripting::load_world_script( + env, pack->id, scriptFile, runtime->worldfuncsset + ); } - if (!fs::is_regular_file(pack->getContentFile())) - return; + if (!fs::is_regular_file(pack->getContentFile())) return; auto root = files::read_json(pack->getContentFile()); @@ -423,10 +446,12 @@ void ContentLoader::load() { for (size_t i = 0; i < blocksarr->size(); i++) { std::string name = blocksarr->str(i); auto colon = name.find(':'); - std::string full = colon == std::string::npos ? pack->id + ":" + name : name; + std::string full = + colon == std::string::npos ? pack->id + ":" + name : name; if (colon != std::string::npos) name[colon] = '/'; auto& def = builder.blocks.create(full); - if (colon != std::string::npos) def.scriptName = name.substr(0, colon) + '/' + def.scriptName; + if (colon != std::string::npos) + def.scriptName = name.substr(0, colon) + '/' + def.scriptName; loadBlock(def, full, name); stats->totalBlocks++; } @@ -435,10 +460,12 @@ void ContentLoader::load() { for (size_t i = 0; i < itemsarr->size(); i++) { std::string name = itemsarr->str(i); auto colon = name.find(':'); - std::string full = colon == std::string::npos ? pack->id + ":" + name : name; + std::string full = + colon == std::string::npos ? pack->id + ":" + name : name; if (colon != std::string::npos) name[colon] = '/'; auto& def = builder.items.create(full); - if (colon != std::string::npos) def.scriptName = name.substr(0, colon) + '/' + def.scriptName; + if (colon != std::string::npos) + def.scriptName = name.substr(0, colon) + '/' + def.scriptName; loadItem(def, full, name); stats->totalItems++; } @@ -448,7 +475,8 @@ void ContentLoader::load() { for (size_t i = 0; i < entitiesarr->size(); i++) { std::string name = entitiesarr->str(i); auto colon = name.find(':'); - std::string full = colon == std::string::npos ? pack->id + ":" + name : name; + std::string full = + colon == std::string::npos ? pack->id + ":" + name : name; if (colon != std::string::npos) name[colon] = '/'; auto& def = builder.entities.create(full); loadEntity(def, full, name); @@ -460,7 +488,7 @@ void ContentLoader::load() { if (fs::is_directory(materialsDir)) { for (const auto& entry : fs::directory_iterator(materialsDir)) { const fs::path& file = entry.path(); - std::string name = pack->id+":"+file.stem().u8string(); + std::string name = pack->id + ":" + file.stem().u8string(); loadBlockMaterial(builder.createBlockMaterial(name), file); } } @@ -469,9 +497,11 @@ void ContentLoader::load() { if (fs::is_directory(skeletonsDir)) { for (const auto& entry : fs::directory_iterator(skeletonsDir)) { const fs::path& file = entry.path(); - std::string name = pack->id+":"+file.stem().u8string(); + std::string name = pack->id + ":" + file.stem().u8string(); std::string text = files::read_string(file); - builder.add(rigging::SkeletonConfig::parse(text, file.u8string(), name)); + builder.add( + rigging::SkeletonConfig::parse(text, file.u8string(), name) + ); } } @@ -480,7 +510,7 @@ void ContentLoader::load() { for (const auto& entry : fs::directory_iterator(componentsDir)) { fs::path scriptfile = entry.path(); if (fs::is_regular_file(scriptfile)) { - auto name = pack->id+":"+scriptfile.stem().u8string(); + auto name = pack->id + ":" + scriptfile.stem().u8string(); scripting::load_entity_component(name, scriptfile); } } @@ -504,6 +534,7 @@ void ContentLoader::load() { void ContentLoader::loadResources(ResourceType type, dynamic::List* list) { for (size_t i = 0; i < list->size(); i++) { builder.resourceIndices[static_cast(type)].add( - pack->id+":"+list->str(i), nullptr); + pack->id + ":" + list->str(i), nullptr + ); } } diff --git a/src/content/ContentLoader.hpp b/src/content/ContentLoader.hpp index 2aa243df..df3459e0 100644 --- a/src/content/ContentLoader.hpp +++ b/src/content/ContentLoader.hpp @@ -1,11 +1,11 @@ #ifndef CONTENT_CONTENT_LOADER_HPP_ #define CONTENT_CONTENT_LOADER_HPP_ -#include "content_fwd.hpp" - -#include -#include #include +#include +#include + +#include "content_fwd.hpp" namespace fs = std::filesystem; @@ -30,16 +30,28 @@ class ContentLoader { scriptenv env; ContentBuilder& builder; ContentPackStats* stats; - - void loadBlock(Block& def, const std::string& full, const std::string& name); - void loadItem(ItemDef& def, const std::string& full, const std::string& name); - void loadEntity(EntityDef& def, const std::string& full, const std::string& name); + + void loadBlock( + Block& def, const std::string& full, const std::string& name + ); + void loadItem( + ItemDef& def, const std::string& full, const std::string& name + ); + void loadEntity( + EntityDef& def, const std::string& full, const std::string& name + ); static void loadCustomBlockModel(Block& def, dynamic::Map* primitives); static void loadBlockMaterial(BlockMaterial& def, const fs::path& file); - static void loadBlock(Block& def, const std::string& name, const fs::path& file); - static void loadItem(ItemDef& def, const std::string& name, const fs::path& file); - static void loadEntity(EntityDef& def, const std::string& name, const fs::path& file); + static void loadBlock( + Block& def, const std::string& name, const fs::path& file + ); + static void loadItem( + ItemDef& def, const std::string& name, const fs::path& file + ); + static void loadEntity( + EntityDef& def, const std::string& name, const fs::path& file + ); void loadResources(ResourceType type, dynamic::List* list); public: ContentLoader(ContentPack* pack, ContentBuilder& builder); @@ -53,4 +65,4 @@ public: void load(); }; -#endif // CONTENT_CONTENT_LOADER_HPP_ +#endif // CONTENT_CONTENT_LOADER_HPP_ diff --git a/src/content/ContentPack.cpp b/src/content/ContentPack.cpp index 0c88c7b0..8f6ef074 100644 --- a/src/content/ContentPack.cpp +++ b/src/content/ContentPack.cpp @@ -1,25 +1,25 @@ #include "ContentPack.hpp" -#include #include +#include #include #include "../coders/json.hpp" -#include "../files/files.hpp" -#include "../files/engine_paths.hpp" #include "../data/dynamic.hpp" +#include "../files/engine_paths.hpp" +#include "../files/files.hpp" namespace fs = std::filesystem; const std::vector ContentPack::RESERVED_NAMES = { - "res", "abs", "local", "core", "user", "world", "none", "null" -}; + "res", "abs", "local", "core", "user", "world", "none", "null"}; contentpack_error::contentpack_error( - std::string packId, - fs::path folder, - const std::string& message) - : std::runtime_error(message), packId(std::move(packId)), folder(std::move(folder)) { + std::string packId, fs::path folder, const std::string& message +) + : std::runtime_error(message), + packId(std::move(packId)), + folder(std::move(folder)) { } std::string contentpack_error::getPackId() const { @@ -30,36 +30,40 @@ fs::path contentpack_error::getFolder() const { } fs::path ContentPack::getContentFile() const { - return folder/fs::path(CONTENT_FILENAME); + return folder / fs::path(CONTENT_FILENAME); } bool ContentPack::is_pack(const fs::path& folder) { - return fs::is_regular_file(folder/fs::path(PACKAGE_FILENAME)); + return fs::is_regular_file(folder / fs::path(PACKAGE_FILENAME)); } static void checkContentPackId(const std::string& id, const fs::path& folder) { if (id.length() < 2 || id.length() > 24) - throw contentpack_error(id, folder, - "content-pack id length is out of range [2, 24]"); - if (isdigit(id[0])) - throw contentpack_error(id, folder, - "content-pack id must not start with a digit"); + throw contentpack_error( + id, folder, "content-pack id length is out of range [2, 24]" + ); + if (isdigit(id[0])) + throw contentpack_error( + id, folder, "content-pack id must not start with a digit" + ); for (char c : id) { if (!isalnum(c) && c != '_') { - throw contentpack_error(id, folder, - "illegal character in content-pack id"); + throw contentpack_error( + id, folder, "illegal character in content-pack id" + ); } } - if (std::find(ContentPack::RESERVED_NAMES.begin(), - ContentPack::RESERVED_NAMES.end(), id) - != ContentPack::RESERVED_NAMES.end()) { - throw contentpack_error(id, folder, - "this content-pack id is reserved"); + if (std::find( + ContentPack::RESERVED_NAMES.begin(), + ContentPack::RESERVED_NAMES.end(), + id + ) != ContentPack::RESERVED_NAMES.end()) { + throw contentpack_error(id, folder, "this content-pack id is reserved"); } } ContentPack ContentPack::read(const fs::path& folder) { - auto root = files::read_json(folder/fs::path(PACKAGE_FILENAME)); + auto root = files::read_json(folder / fs::path(PACKAGE_FILENAME)); ContentPack pack; root->str("id", pack.id); root->str("title", pack.title); @@ -78,26 +82,24 @@ ContentPack ContentPack::read(const fs::path& folder) { } if (pack.id == "none") - throw contentpack_error(pack.id, folder, - "content-pack id is not specified"); + throw contentpack_error( + pack.id, folder, "content-pack id is not specified" + ); checkContentPackId(pack.id, folder); return pack; } void ContentPack::scanFolder( - const fs::path& folder, - std::vector& packs + const fs::path& folder, std::vector& packs ) { if (!fs::is_directory(folder)) { return; } for (const auto& entry : fs::directory_iterator(folder)) { const fs::path& folder = entry.path(); - if (!fs::is_directory(folder)) - continue; - if (!is_pack(folder)) - continue; + if (!fs::is_directory(folder)) continue; + if (!is_pack(folder)) continue; try { packs.push_back(read(folder)); } catch (const contentpack_error& err) { @@ -119,7 +121,9 @@ std::vector ContentPack::worldPacksList(const fs::path& folder) { return files::read_list(listfile); } -fs::path ContentPack::findPack(const EnginePaths* paths, const fs::path& worldDir, const std::string& name) { +fs::path ContentPack::findPack( + const EnginePaths* paths, const fs::path& worldDir, const std::string& name +) { fs::path folder = worldDir / fs::path("content") / fs::path(name); if (fs::is_directory(folder)) { return folder; @@ -135,11 +139,8 @@ fs::path ContentPack::findPack(const EnginePaths* paths, const fs::path& worldDi return folder; } -ContentPackRuntime::ContentPackRuntime( - ContentPack info, - scriptenv env -) : info(std::move(info)), env(std::move(env)) -{ +ContentPackRuntime::ContentPackRuntime(ContentPack info, scriptenv env) + : info(std::move(info)), env(std::move(env)) { } ContentPackRuntime::~ContentPackRuntime() = default; diff --git a/src/content/ContentPack.hpp b/src/content/ContentPack.hpp index 88c81a4e..da373446 100644 --- a/src/content/ContentPack.hpp +++ b/src/content/ContentPack.hpp @@ -1,12 +1,12 @@ #ifndef CONTENT_CONTENT_PACK_HPP_ #define CONTENT_CONTENT_PACK_HPP_ -#include "../typedefs.hpp" - +#include +#include #include #include -#include -#include + +#include "../typedefs.hpp" class EnginePaths; @@ -16,19 +16,20 @@ class contentpack_error : public std::runtime_error { std::string packId; fs::path folder; public: - contentpack_error(std::string packId, fs::path folder, const std::string& message); + contentpack_error( + std::string packId, fs::path folder, const std::string& message + ); std::string getPackId() const; fs::path getFolder() const; }; enum class DependencyLevel { - required, // dependency must be installed - optional, // dependency will be installed if found - weak, // only affects packs order + required, // dependency must be installed + optional, // dependency will be installed if found + weak, // only affects packs order }; - /// @brief Content-pack that should be installed earlier the dependent struct DependencyPack { DependencyLevel level; @@ -57,14 +58,13 @@ struct ContentPack { static ContentPack read(const fs::path& folder); static void scanFolder( - const fs::path& folder, - std::vector& packs + const fs::path& folder, std::vector& packs ); - + static std::vector worldPacksList(const fs::path& folder); static fs::path findPack( - const EnginePaths* paths, + const EnginePaths* paths, const fs::path& worldDir, const std::string& name ); @@ -92,10 +92,7 @@ class ContentPackRuntime { public: world_funcs_set worldfuncsset {}; - ContentPackRuntime( - ContentPack info, - scriptenv env - ); + ContentPackRuntime(ContentPack info, scriptenv env); ~ContentPackRuntime(); inline const ContentPackStats& getStats() const { @@ -119,4 +116,4 @@ public: } }; -#endif // CONTENT_CONTENT_PACK_HPP_ +#endif // CONTENT_CONTENT_PACK_HPP_ diff --git a/src/content/PacksManager.cpp b/src/content/PacksManager.cpp index 3a47d66d..76a98e3b 100644 --- a/src/content/PacksManager.cpp +++ b/src/content/PacksManager.cpp @@ -1,10 +1,10 @@ #include "PacksManager.hpp" -#include "../util/listutil.hpp" - #include #include +#include "../util/listutil.hpp" + PacksManager::PacksManager() = default; void PacksManager::setSources(std::vector sources) { @@ -13,7 +13,7 @@ void PacksManager::setSources(std::vector sources) { void PacksManager::scan() { packs.clear(); - + std::vector packsList; for (auto& folder : sources) { ContentPack::scanFolder(folder, packsList); @@ -35,7 +35,9 @@ std::vector PacksManager::getAllNames() const { return names; } -std::vector PacksManager::getAll(const std::vector& names) const { +std::vector PacksManager::getAll( + const std::vector& names +) const { std::vector packsList; for (auto& name : names) { auto found = packs.find(name); @@ -47,7 +49,9 @@ std::vector PacksManager::getAll(const std::vector& na return packsList; } -static contentpack_error on_circular_dependency(std::queue& queue) { +static contentpack_error on_circular_dependency( + std::queue& queue +) { const ContentPack* lastPack = queue.back(); // circular dependency std::stringstream ss; @@ -66,10 +70,12 @@ static contentpack_error on_circular_dependency(std::queue& /// @param allNames all already done or enqueued packs /// @param added packs with all dependencies resolved /// @param queue current pass queue -/// @param resolveWeaks make weak dependencies resolved if found but not added to queue -/// @return true if all dependencies are already added or not found (optional/weak) +/// @param resolveWeaks make weak dependencies resolved if found but not added +/// to queue +/// @return true if all dependencies are already added or not found +/// (optional/weak) /// @throws contentpack_error if required dependency is not found -static bool resolve_dependencies ( +static bool resolve_dependencies( const ContentPack* pack, const std::unordered_map& packs, std::vector& allNames, @@ -85,7 +91,9 @@ static bool resolve_dependencies ( auto found = packs.find(dep.id); bool exists = found != packs.end(); if (!exists && dep.level == DependencyLevel::required) { - throw contentpack_error(dep.id, fs::path(), "dependency of '"+pack->id+"'"); + throw contentpack_error( + dep.id, fs::path(), "dependency of '" + pack->id + "'" + ); } if (!exists) { // ignored for optional or weak dependencies @@ -93,11 +101,13 @@ static bool resolve_dependencies ( } if (resolveWeaks && dep.level == DependencyLevel::weak) { // dependency pack is found but not added yet - // resolveWeaks is used on second iteration, so it's will not be added + // resolveWeaks is used on second iteration, so it's will not be + // added continue; } - if (!util::contains(allNames, dep.id) && dep.level != DependencyLevel::weak) { + if (!util::contains(allNames, dep.id) && + dep.level != DependencyLevel::weak) { allNames.push_back(dep.id); queue.push(&found->second); } @@ -106,7 +116,9 @@ static bool resolve_dependencies ( return satisfied; } -std::vector PacksManager::assembly(const std::vector& names) const { +std::vector PacksManager::assembly( + const std::vector& names +) const { std::vector allNames = names; std::vector added; std::queue queue; @@ -126,10 +138,14 @@ std::vector PacksManager::assembly(const std::vector& while (!queue.empty()) { auto* pack = queue.front(); queue.pop(); - - if (resolve_dependencies(pack, packs, allNames, added, queue, resolveWeaks)) { + + if (resolve_dependencies( + pack, packs, allNames, added, queue, resolveWeaks + )) { if (util::contains(added, pack->id)) { - throw contentpack_error(pack->id, pack->folder, "pack duplication"); + throw contentpack_error( + pack->id, pack->folder, "pack duplication" + ); } added.push_back(pack->id); addedInIteration++; @@ -148,7 +164,9 @@ std::vector PacksManager::assembly(const std::vector& return added; } -std::vector PacksManager::getNames(const std::vector& packs) { +std::vector PacksManager::getNames( + const std::vector& packs +) { std::vector result; for (const auto& pack : packs) { result.push_back(pack.id); diff --git a/src/content/PacksManager.hpp b/src/content/PacksManager.hpp index 41c9c179..f8c584d3 100644 --- a/src/content/PacksManager.hpp +++ b/src/content/PacksManager.hpp @@ -1,11 +1,11 @@ #ifndef CONTENT_PACKS_MANAGER_HPP_ #define CONTENT_PACKS_MANAGER_HPP_ -#include "ContentPack.hpp" - -#include #include #include +#include + +#include "ContentPack.hpp" namespace fs = std::filesystem; @@ -31,17 +31,21 @@ public: /// @brief Get packs by names (id) /// @param names pack names /// @throws contentpack_error if pack not found - std::vector getAll(const std::vector& names) const; + std::vector getAll(const std::vector& names + ) const; /// @brief Resolve all dependencies and fix packs order /// @param names required packs (method can add extra packs) /// @return resulting ordered vector of pack names /// @throws contentpack_error if required dependency not found or /// circular dependency detected - std::vector assembly(const std::vector& names) const; + std::vector assembly(const std::vector& names + ) const; /// @brief Collect all pack names (identifiers) into a new vector - static std::vector getNames(const std::vector& packs); + static std::vector getNames( + const std::vector& packs + ); }; -#endif // CONTENT_PACKS_MANAGER_HPP_ +#endif // CONTENT_PACKS_MANAGER_HPP_ diff --git a/src/content/content_fwd.hpp b/src/content/content_fwd.hpp index 52bedab8..92392cc5 100644 --- a/src/content/content_fwd.hpp +++ b/src/content/content_fwd.hpp @@ -6,15 +6,11 @@ class Content; class ContentPackRuntime; -enum class contenttype { - none, block, item, entity -}; +enum class contenttype { none, block, item, entity }; -enum class ResourceType : size_t { - CAMERA, - LAST=CAMERA -}; +enum class ResourceType : size_t { CAMERA, LAST = CAMERA }; -inline constexpr auto RESOURCE_TYPES_COUNT = static_cast(ResourceType::LAST)+1; +inline constexpr auto RESOURCE_TYPES_COUNT = + static_cast(ResourceType::LAST) + 1; -#endif // CONTENT_CONTENT_FWD_HPP_ +#endif // CONTENT_CONTENT_FWD_HPP_ diff --git a/src/data/dynamic.cpp b/src/data/dynamic.cpp index d8819bcd..dc4171cc 100644 --- a/src/data/dynamic.cpp +++ b/src/data/dynamic.cpp @@ -14,7 +14,9 @@ std::ostream& operator<<(std::ostream& stream, const dynamic::Map_sptr& value) { return stream; } -std::ostream& operator<<(std::ostream& stream, const dynamic::List_sptr& value) { +std::ostream& operator<<( + std::ostream& stream, const dynamic::List_sptr& value +) { stream << json::stringify(value, false, " "); return stream; } @@ -22,10 +24,14 @@ std::ostream& operator<<(std::ostream& stream, const dynamic::List_sptr& value) std::string List::str(size_t index) const { const auto& value = values[index]; switch (static_cast(value.index())) { - case Type::string: return std::get(value); - case Type::boolean: return std::get(value) ? "true" : "false"; - case Type::number: return std::to_string(std::get(value)); - case Type::integer: return std::to_string(std::get(value)); + case Type::string: + return std::get(value); + case Type::boolean: + return std::get(value) ? "true" : "false"; + case Type::number: + return std::to_string(std::get(value)); + case Type::integer: + return std::to_string(std::get(value)); default: throw std::runtime_error("type error"); } @@ -34,10 +40,14 @@ std::string List::str(size_t index) const { number_t List::num(size_t index) const { const auto& value = values[index]; switch (static_cast(value.index())) { - case Type::number: return std::get(value); - case Type::integer: return std::get(value); - case Type::string: return std::stoll(std::get(value)); - case Type::boolean: return std::get(value); + case Type::number: + return std::get(value); + case Type::integer: + return std::get(value); + case Type::string: + return std::stoll(std::get(value)); + case Type::boolean: + return std::get(value); default: throw std::runtime_error("type error"); } @@ -46,10 +56,14 @@ number_t List::num(size_t index) const { integer_t List::integer(size_t index) const { const auto& value = values[index]; switch (static_cast(value.index())) { - case Type::number: return std::get(value); - case Type::integer: return std::get(value); - case Type::string: return std::stoll(std::get(value)); - case Type::boolean: return std::get(value); + case Type::number: + return std::get(value); + case Type::integer: + return std::get(value); + case Type::string: + return std::stoll(std::get(value)); + case Type::boolean: + return std::get(value); default: throw std::runtime_error("type error"); } @@ -74,8 +88,10 @@ List* List::list(size_t index) const { bool List::flag(size_t index) const { const auto& value = values[index]; switch (static_cast(value.index())) { - case Type::integer: return std::get(value); - case Type::boolean: return std::get(value); + case Type::integer: + return std::get(value); + case Type::boolean: + return std::get(value); default: throw std::runtime_error("type error"); } @@ -112,55 +128,69 @@ void Map::str(const std::string& key, std::string& dst) const { std::string Map::get(const std::string& key, const std::string& def) const { auto found = values.find(key); - if (found == values.end()) - return def; + if (found == values.end()) return def; auto& value = found->second; switch (static_cast(value.index())) { - case Type::string: return std::get(value); - case Type::boolean: return std::get(value) ? "true" : "false"; - case Type::number: return std::to_string(std::get(value)); - case Type::integer: return std::to_string(std::get(value)); - default: throw std::runtime_error("type error"); + case Type::string: + return std::get(value); + case Type::boolean: + return std::get(value) ? "true" : "false"; + case Type::number: + return std::to_string(std::get(value)); + case Type::integer: + return std::to_string(std::get(value)); + default: + throw std::runtime_error("type error"); } } number_t Map::get(const std::string& key, double def) const { auto found = values.find(key); - if (found == values.end()) - return def; + if (found == values.end()) return def; auto& value = found->second; switch (static_cast(value.index())) { - case Type::number: return std::get(value); - case Type::integer: return std::get(value); - case Type::string: return std::stoull(std::get(value)); - case Type::boolean: return std::get(value); - default: throw std::runtime_error("type error"); + case Type::number: + return std::get(value); + case Type::integer: + return std::get(value); + case Type::string: + return std::stoull(std::get(value)); + case Type::boolean: + return std::get(value); + default: + throw std::runtime_error("type error"); } } integer_t Map::get(const std::string& key, integer_t def) const { auto found = values.find(key); - if (found == values.end()) - return def; + if (found == values.end()) return def; auto& value = found->second; switch (static_cast(value.index())) { - case Type::number: return std::get(value); - case Type::integer: return std::get(value); - case Type::string: return std::stoull(std::get(value)); - case Type::boolean: return std::get(value); - default: throw std::runtime_error("type error"); + case Type::number: + return std::get(value); + case Type::integer: + return std::get(value); + case Type::string: + return std::stoull(std::get(value)); + case Type::boolean: + return std::get(value); + default: + throw std::runtime_error("type error"); } } bool Map::get(const std::string& key, bool def) const { auto found = values.find(key); - if (found == values.end()) - return def; + if (found == values.end()) return def; auto& value = found->second; switch (static_cast(value.index())) { - case Type::integer: return std::get(value); - case Type::boolean: return std::get(value); - default: throw std::runtime_error("type error"); + case Type::integer: + return std::get(value); + case Type::boolean: + return std::get(value); + default: + throw std::runtime_error("type error"); } } @@ -204,8 +234,7 @@ Map_sptr Map::map(const std::string& key) const { List_sptr Map::list(const std::string& key) const { auto found = values.find(key); - if (found != values.end()) - return std::get(found->second); + if (found != values.end()) return std::get(found->second); return nullptr; } @@ -260,7 +289,9 @@ List_sptr dynamic::create_list(std::initializer_list values) { return std::make_shared(values); } -Map_sptr dynamic::create_map(std::initializer_list> entries) { +Map_sptr dynamic::create_map( + std::initializer_list> entries +) { return std::make_shared(entries); } @@ -270,12 +301,12 @@ number_t dynamic::get_number(const Value& value) { } else if (auto num = std::get_if(&value)) { return *num; } - throw std::runtime_error("cannot cast "+type_name(value)+" to number"); + throw std::runtime_error("cannot cast " + type_name(value) + " to number"); } integer_t dynamic::get_integer(const Value& value) { if (auto num = std::get_if(&value)) { return *num; } - throw std::runtime_error("cannot cast "+type_name(value)+" to integer"); + throw std::runtime_error("cannot cast " + type_name(value) + " to integer"); } diff --git a/src/data/dynamic.hpp b/src/data/dynamic.hpp index 6299a1c7..5b52064b 100644 --- a/src/data/dynamic.hpp +++ b/src/data/dynamic.hpp @@ -1,28 +1,27 @@ #ifndef DATA_DYNAMIC_HPP_ #define DATA_DYNAMIC_HPP_ -#include "dynamic_fwd.hpp" - #include -#include -#include #include #include - #include +#include #include +#include + +#include "dynamic_fwd.hpp" namespace dynamic { - enum class Type { - none=0, map, list, string, number, boolean, integer - }; + enum class Type { none = 0, map, list, string, number, boolean, integer }; const std::string& type_name(const Value& value); - List_sptr create_list(std::initializer_list values={}); - Map_sptr create_map(std::initializer_list> entries={}); + List_sptr create_list(std::initializer_list values = {}); + Map_sptr create_map( + std::initializer_list> entries = {} + ); number_t get_number(const Value& value); integer_t get_integer(const Value& value); - + inline bool is_numeric(const Value& value) { return std::holds_alternative(value) || std::holds_alternative(value); @@ -42,7 +41,8 @@ namespace dynamic { std::vector values; List() = default; - List(std::vector values) : values(std::move(values)) {} + List(std::vector values) : values(std::move(values)) { + } std::string str(size_t index) const; number_t num(size_t index) const; @@ -80,13 +80,13 @@ namespace dynamic { std::unordered_map values; Map() = default; - Map(std::unordered_map values) - : values(std::move(values)) {}; + Map(std::unordered_map values) + : values(std::move(values)) {}; - template + template T get(const std::string& key) const { if (!has(key)) { - throw std::runtime_error("missing key '"+key+"'"); + throw std::runtime_error("missing key '" + key + "'"); } return get(key, T()); } @@ -164,4 +164,4 @@ std::ostream& operator<<(std::ostream& stream, const dynamic::Value& value); std::ostream& operator<<(std::ostream& stream, const dynamic::Map_sptr& value); std::ostream& operator<<(std::ostream& stream, const dynamic::List_sptr& value); -#endif // DATA_DYNAMIC_HPP_ +#endif // DATA_DYNAMIC_HPP_ diff --git a/src/data/dynamic_fwd.hpp b/src/data/dynamic_fwd.hpp index 6faff946..f655ed1a 100644 --- a/src/data/dynamic_fwd.hpp +++ b/src/data/dynamic_fwd.hpp @@ -1,12 +1,12 @@ #ifndef DATA_DYNAMIC_FWD_HPP_ #define DATA_DYNAMIC_FWD_HPP_ -#include "../typedefs.hpp" - +#include #include #include #include -#include + +#include "../typedefs.hpp" namespace dynamic { class Map; @@ -26,10 +26,9 @@ namespace dynamic { std::string, number_t, bool, - integer_t - >; + integer_t>; using to_string_func = std::function; } -#endif // DATA_DYNAMIC_FWD_HPP_ +#endif // DATA_DYNAMIC_FWD_HPP_ diff --git a/src/data/dynamic_util.hpp b/src/data/dynamic_util.hpp index 576d84e4..c7808f70 100644 --- a/src/data/dynamic_util.hpp +++ b/src/data/dynamic_util.hpp @@ -1,12 +1,12 @@ #ifndef DATA_DYNAMIC_UTIL_HPP_ #define DATA_DYNAMIC_UTIL_HPP_ -#include "dynamic.hpp" - #include +#include "dynamic.hpp" + namespace dynamic { - template + template inline dynamic::List_sptr to_value(glm::vec vec) { auto list = dynamic::create_list(); for (size_t i = 0; i < n; i++) { @@ -15,7 +15,7 @@ namespace dynamic { return list; } - template + template inline dynamic::List_sptr to_value(glm::mat mat) { auto list = dynamic::create_list(); for (size_t i = 0; i < n; i++) { @@ -26,8 +26,12 @@ namespace dynamic { return list; } - template - void get_vec(const dynamic::Map_sptr& root, const std::string& name, glm::vec& vec) { + template + void get_vec( + const dynamic::Map_sptr& root, + const std::string& name, + glm::vec& vec + ) { if (const auto& list = root->list(name)) { for (size_t i = 0; i < n; i++) { vec[i] = list->num(i); @@ -35,8 +39,10 @@ namespace dynamic { } } - template - void get_vec(const dynamic::List_sptr& root, size_t index, glm::vec& vec) { + template + void get_vec( + const dynamic::List_sptr& root, size_t index, glm::vec& vec + ) { if (const auto& list = root->list(index)) { for (size_t i = 0; i < n; i++) { vec[i] = list->num(i); @@ -44,27 +50,33 @@ namespace dynamic { } } - template - void get_mat(const dynamic::Map_sptr& root, const std::string& name, glm::mat& mat) { + template + void get_mat( + const dynamic::Map_sptr& root, + const std::string& name, + glm::mat& mat + ) { if (const auto& list = root->list(name)) { for (size_t y = 0; y < n; y++) { for (size_t x = 0; x < m; x++) { - mat[y][x] = list->num(y*m+x); + mat[y][x] = list->num(y * m + x); } } } } - template - void get_mat(const dynamic::List_sptr& root, size_t index, glm::mat& mat) { + template + void get_mat( + const dynamic::List_sptr& root, size_t index, glm::mat& mat + ) { if (const auto& list = root->list(index)) { for (size_t y = 0; y < n; y++) { for (size_t x = 0; x < m; x++) { - mat[y][x] = list->num(y*m+x); + mat[y][x] = list->num(y * m + x); } } } } } -#endif // DATA_DYNAMIC_UTIL_HPP_ +#endif // DATA_DYNAMIC_UTIL_HPP_ diff --git a/src/data/setting.cpp b/src/data/setting.cpp index 56f166ce..b6a9bbf7 100644 --- a/src/data/setting.cpp +++ b/src/data/setting.cpp @@ -7,7 +7,8 @@ std::string NumberSetting::toString() const { case setting_format::simple: return util::to_string(value); case setting_format::percent: - return std::to_string(static_cast(round(value * 100))) + "%"; + return std::to_string(static_cast(round(value * 100))) + + "%"; default: return "invalid format"; } diff --git a/src/data/setting.hpp b/src/data/setting.hpp index e0efffbd..b4e74a2d 100644 --- a/src/data/setting.hpp +++ b/src/data/setting.hpp @@ -3,15 +3,13 @@ #include #include -#include #include +#include -#include "../typedefs.hpp" #include "../delegates.hpp" +#include "../typedefs.hpp" -enum class setting_format { - simple, percent -}; +enum class setting_format { simple, percent }; class Setting { protected: @@ -20,7 +18,8 @@ public: Setting(setting_format format) : format(format) { } - virtual ~Setting() {} + virtual ~Setting() { + } virtual void resetToDefault() = 0; @@ -31,7 +30,7 @@ public: virtual std::string toString() const = 0; }; -template +template class ObservableSetting : public Setting { int nextid = 1; std::unordered_map> observers; @@ -39,10 +38,11 @@ protected: T initial; T value; public: - ObservableSetting(T value, setting_format format) - : Setting(format), initial(value), value(value) {} + ObservableSetting(T value, setting_format format) + : Setting(format), initial(value), value(value) { + } - observer_handler observe(consumer callback, bool callOnStart=false) { + observer_handler observe(consumer callback, bool callOnStart = false) { const int id = nextid++; observers.emplace(id, callback); if (callOnStart) { @@ -87,14 +87,13 @@ protected: number_t max; public: NumberSetting( - number_t value, - number_t min=std::numeric_limits::min(), - number_t max=std::numeric_limits::max(), - setting_format format=setting_format::simple - ) : ObservableSetting(value, format), - min(min), - max(max) - {} + number_t value, + number_t min = std::numeric_limits::min(), + number_t max = std::numeric_limits::max(), + setting_format format = setting_format::simple + ) + : ObservableSetting(value, format), min(min), max(max) { + } number_t& operator*() { return value; @@ -129,14 +128,13 @@ protected: integer_t max; public: IntegerSetting( - integer_t value, - integer_t min=std::numeric_limits::min(), - integer_t max=std::numeric_limits::max(), - setting_format format=setting_format::simple - ) : ObservableSetting(value, format), - min(min), - max(max) - {} + integer_t value, + integer_t min = std::numeric_limits::min(), + integer_t max = std::numeric_limits::max(), + setting_format format = setting_format::simple + ) + : ObservableSetting(value, format), min(min), max(max) { + } integer_t getMin() const { return min; @@ -155,10 +153,9 @@ public: class FlagSetting : public ObservableSetting { public: - FlagSetting( - bool value, - setting_format format=setting_format::simple - ) : ObservableSetting(value, format) {} + FlagSetting(bool value, setting_format format = setting_format::simple) + : ObservableSetting(value, format) { + } void toggle() { set(!get()); @@ -170,11 +167,12 @@ public: class StringSetting : public ObservableSetting { public: StringSetting( - std::string value, - setting_format format=setting_format::simple - ) : ObservableSetting(value, format) {} + std::string value, setting_format format = setting_format::simple + ) + : ObservableSetting(value, format) { + } virtual std::string toString() const override; }; -#endif // DATA_SETTING_HPP_ +#endif // DATA_SETTING_HPP_ diff --git a/src/debug/Logger.cpp b/src/debug/Logger.cpp index 1463d66b..e8f4c95b 100644 --- a/src/debug/Logger.cpp +++ b/src/debug/Logger.cpp @@ -1,8 +1,8 @@ #include "Logger.hpp" - + +#include #include #include -#include #include #include @@ -20,15 +20,17 @@ LogMessage::~LogMessage() { Logger::Logger(std::string name) : name(std::move(name)) { } -void Logger::log(LogLevel level, const std::string& name, const std::string& message) { +void Logger::log( + LogLevel level, const std::string& name, const std::string& message +) { using namespace std::chrono; std::stringstream ss; switch (level) { case LogLevel::debug: -# ifdef NDEBUG +#ifdef NDEBUG return; -# endif +#endif ss << "[D]"; break; case LogLevel::info: @@ -42,10 +44,13 @@ void Logger::log(LogLevel level, const std::string& name, const std::string& mes break; } time_t tm = std::time(nullptr); - auto ms = duration_cast(system_clock::now().time_since_epoch()) % 1000; + auto ms = + duration_cast(system_clock::now().time_since_epoch()) % + 1000; ss << " " << std::put_time(std::localtime(&tm), "%Y/%m/%d %T"); ss << '.' << std::setfill('0') << std::setw(3) << ms.count(); - ss << utcOffset << " [" << std::setfill(' ') << std::setw(moduleLen) << name << "] "; + ss << utcOffset << " [" << std::setfill(' ') << std::setw(moduleLen) << name + << "] "; ss << message; { std::lock_guard lock(mutex); diff --git a/src/debug/Logger.hpp b/src/debug/Logger.hpp index 779e8580..eb5b3c4e 100644 --- a/src/debug/Logger.hpp +++ b/src/debug/Logger.hpp @@ -1,14 +1,12 @@ #ifndef DEBUG_LOGGER_HPP_ #define DEBUG_LOGGER_HPP_ -#include #include #include +#include namespace debug { - enum class LogLevel { - debug, info, warning, error - }; + enum class LogLevel { debug, info, warning, error }; class Logger; @@ -17,10 +15,12 @@ namespace debug { LogLevel level; std::stringstream ss; public: - LogMessage(Logger* logger, LogLevel level) : logger(logger), level(level) {} + LogMessage(Logger* logger, LogLevel level) + : logger(logger), level(level) { + } ~LogMessage(); - template + template LogMessage& operator<<(const T& x) { ss << x; return *this; @@ -34,8 +34,10 @@ namespace debug { static unsigned moduleLen; std::string name; - - static void log(LogLevel level, const std::string& name, const std::string& message); + + static void log( + LogLevel level, const std::string& name, const std::string& message + ); public: static void init(const std::string& filename); static void flush(); @@ -62,4 +64,4 @@ namespace debug { }; } -#endif // DEBUG_LOGGER_HPP_ +#endif // DEBUG_LOGGER_HPP_ diff --git a/src/files/WorldConverter.cpp b/src/files/WorldConverter.cpp index 006d031b..317c8240 100644 --- a/src/files/WorldConverter.cpp +++ b/src/files/WorldConverter.cpp @@ -1,6 +1,9 @@ #include "WorldConverter.hpp" -#include "WorldFiles.hpp" +#include +#include +#include +#include #include "../content/ContentLUT.hpp" #include "../data/dynamic.hpp" @@ -9,11 +12,7 @@ #include "../objects/Player.hpp" #include "../util/ThreadPool.hpp" #include "../voxels/Chunk.hpp" - -#include -#include -#include -#include +#include "WorldFiles.hpp" namespace fs = std::filesystem; @@ -22,8 +21,9 @@ static debug::Logger logger("world-converter"); class ConverterWorker : public util::Worker { std::shared_ptr converter; public: - ConverterWorker(std::shared_ptr converter) - : converter(std::move(converter)) {} + ConverterWorker(std::shared_ptr converter) + : converter(std::move(converter)) { + } int operator()(const std::shared_ptr& task) override { converter->convert(*task); @@ -33,18 +33,20 @@ public: WorldConverter::WorldConverter( const fs::path& folder, - const Content* content, + const Content* content, std::shared_ptr lut -) : wfile(std::make_unique(folder)), - lut(std::move(lut)), - content(content) -{ - fs::path regionsFolder = wfile->getRegions().getRegionsFolder(REGION_LAYER_VOXELS); +) + : wfile(std::make_unique(folder)), + lut(std::move(lut)), + content(content) { + fs::path regionsFolder = + wfile->getRegions().getRegionsFolder(REGION_LAYER_VOXELS); if (!fs::is_directory(regionsFolder)) { logger.error() << "nothing to convert"; return; } - tasks.push(convert_task {convert_task_type::player, wfile->getPlayerFile()}); + tasks.push(convert_task {convert_task_type::player, wfile->getPlayerFile()} + ); for (const auto& file : fs::directory_iterator(regionsFolder)) { tasks.push(convert_task {convert_task_type::region, file.path()}); } @@ -55,7 +57,7 @@ WorldConverter::~WorldConverter() { std::shared_ptr WorldConverter::startTask( const fs::path& folder, - const Content* content, + const Content* content, const std::shared_ptr& lut, const runnable& onDone, bool multithreading @@ -70,7 +72,7 @@ std::shared_ptr WorldConverter::startTask( } auto pool = std::make_shared>( "converter-pool", - [=](){return std::make_shared(converter);}, + [=]() { return std::make_shared(converter); }, [=](int&) {} ); auto& converterTasks = converter->tasks; @@ -111,8 +113,7 @@ void WorldConverter::convertPlayer(const fs::path& file) const { } void WorldConverter::convert(const convert_task& task) const { - if (!fs::is_regular_file(task.file)) - return; + if (!fs::is_regular_file(task.file)) return; switch (task.type) { case convert_task_type::region: diff --git a/src/files/WorldConverter.hpp b/src/files/WorldConverter.hpp index 9fb6307a..7e28bcf9 100644 --- a/src/files/WorldConverter.hpp +++ b/src/files/WorldConverter.hpp @@ -1,13 +1,13 @@ #ifndef FILES_WORLD_CONVERTER_HPP_ #define FILES_WORLD_CONVERTER_HPP_ -#include -#include #include +#include +#include -#include "../typedefs.hpp" #include "../delegates.hpp" #include "../interfaces/Task.hpp" +#include "../typedefs.hpp" namespace fs = std::filesystem; @@ -15,9 +15,7 @@ class Content; class ContentLUT; class WorldFiles; -enum class convert_task_type { - region, player -}; +enum class convert_task_type { region, player }; struct convert_task { convert_task_type type; @@ -37,7 +35,7 @@ class WorldConverter : public Task { public: WorldConverter( const fs::path& folder, - const Content* content, + const Content* content, std::shared_ptr lut ); ~WorldConverter(); @@ -56,11 +54,11 @@ public: static std::shared_ptr startTask( const fs::path& folder, - const Content* content, + const Content* content, const std::shared_ptr& lut, const runnable& onDone, bool multithreading ); }; -#endif // FILES_WORLD_CONVERTER_HPP_ +#endif // FILES_WORLD_CONVERTER_HPP_ diff --git a/src/files/WorldFiles.cpp b/src/files/WorldFiles.cpp index 31868e81..80fedc72 100644 --- a/src/files/WorldFiles.cpp +++ b/src/files/WorldFiles.cpp @@ -1,5 +1,13 @@ #include "WorldFiles.hpp" +#include +#include +#include +#include +#include +#include +#include + #include "../coders/byte_utils.hpp" #include "../coders/json.hpp" #include "../constants.hpp" @@ -11,11 +19,11 @@ #include "../items/ItemDef.hpp" #include "../lighting/Lightmap.hpp" #include "../maths/voxmaths.hpp" -#include "../objects/Player.hpp" #include "../objects/EntityDef.hpp" +#include "../objects/Player.hpp" #include "../physics/Hitbox.hpp" -#include "../typedefs.hpp" #include "../settings.hpp" +#include "../typedefs.hpp" #include "../util/data_io.hpp" #include "../voxels/Block.hpp" #include "../voxels/Chunk.hpp" @@ -23,24 +31,16 @@ #include "../window/Camera.hpp" #include "../world/World.hpp" -#include -#include -#include -#include -#include -#include -#include - #define WORLD_FORMAT_MAGIC ".VOXWLD" static debug::Logger logger("world-files"); -WorldFiles::WorldFiles(const fs::path& directory) : directory(directory), regions(directory) { +WorldFiles::WorldFiles(const fs::path& directory) + : directory(directory), regions(directory) { } WorldFiles::WorldFiles(const fs::path& directory, const DebugSettings& settings) - : WorldFiles(directory) -{ + : WorldFiles(directory) { generatorTestMode = settings.generatorTestMode.get(); doWriteLights = settings.doWriteLights.get(); regions.generatorTestMode = generatorTestMode; @@ -55,23 +55,23 @@ void WorldFiles::createDirectories() { } fs::path WorldFiles::getPlayerFile() const { - return directory/fs::path("player.json"); + return directory / fs::path("player.json"); } fs::path WorldFiles::getResourcesFile() const { - return directory/fs::path("resources.json"); + return directory / fs::path("resources.json"); } fs::path WorldFiles::getWorldFile() const { - return directory/fs::path(WORLD_FILE); + return directory / fs::path(WORLD_FILE); } fs::path WorldFiles::getIndicesFile() const { - return directory/fs::path("indices.json"); + return directory / fs::path("indices.json"); } fs::path WorldFiles::getPacksFile() const { - return directory/fs::path("packs.list"); + return directory / fs::path("packs.list"); } void WorldFiles::write(const World* world, const Content* content) { @@ -84,7 +84,7 @@ void WorldFiles::write(const World* world, const Content* content) { if (generatorTestMode) { return; } - + writeIndices(content->getIndices()); regions.write(); } @@ -99,8 +99,10 @@ void WorldFiles::writePacks(const std::vector& packs) { files::write_string(packsFile, ss.str()); } -template -static void write_indices(const ContentUnitIndices& indices, dynamic::List& list) { +template +static void write_indices( + const ContentUnitIndices& indices, dynamic::List& list +) { size_t count = indices.count(); for (size_t i = 0; i < count; i++) { list.put(indices.get(i)->name); @@ -131,9 +133,7 @@ bool WorldFiles::readWorldInfo(World* world) { } static void read_resources_data( - const Content* content, - const dynamic::List_sptr& list, - ResourceType type + const Content* content, const dynamic::List_sptr& list, ResourceType type ) { const auto& indices = content->getIndices(type); for (size_t i = 0; i < list->size(); i++) { @@ -169,12 +169,11 @@ bool WorldFiles::readResourcesData(const Content* content) { } static void erase_pack_indices(dynamic::Map* root, const std::string& id) { - auto prefix = id+":"; + auto prefix = id + ":"; auto blocks = root->list("blocks"); for (uint i = 0; i < blocks->size(); i++) { auto name = blocks->str(i); - if (name.find(prefix) != 0) - continue; + if (name.find(prefix) != 0) continue; auto value = blocks->getValueWriteable(i); *value = CORE_AIR; } @@ -182,8 +181,7 @@ static void erase_pack_indices(dynamic::Map* root, const std::string& id) { auto items = root->list("items"); for (uint i = 0; i < items->size(); i++) { auto name = items->str(i); - if (name.find(prefix) != 0) - continue; + if (name.find(prefix) != 0) continue; auto value = items->getValueWriteable(i); *value = CORE_EMPTY; } diff --git a/src/files/WorldFiles.hpp b/src/files/WorldFiles.hpp index 9e41025a..6f0e9bd6 100644 --- a/src/files/WorldFiles.hpp +++ b/src/files/WorldFiles.hpp @@ -1,19 +1,17 @@ #ifndef FILES_WORLD_FILES_HPP_ #define FILES_WORLD_FILES_HPP_ -#include "WorldRegions.hpp" - -#include "files.hpp" -#include "../typedefs.hpp" -#include "../content/ContentPack.hpp" -#include "../voxels/Chunk.hpp" - -#include -#include -#include #include - #include +#include +#include +#include + +#include "../content/ContentPack.hpp" +#include "../typedefs.hpp" +#include "../voxels/Chunk.hpp" +#include "WorldRegions.hpp" +#include "files.hpp" #define GLM_ENABLE_EXPERIMENTAL #include "glm/gtx/hash.hpp" @@ -41,8 +39,8 @@ class WorldFiles { void writeWorldInfo(const World* world); void writeIndices(const ContentIndices* indices); public: - WorldFiles(const fs::path &directory); - WorldFiles(const fs::path &directory, const DebugSettings& settings); + WorldFiles(const fs::path& directory); + WorldFiles(const fs::path& directory, const DebugSettings& settings); ~WorldFiles(); fs::path getPlayerFile() const; @@ -75,4 +73,4 @@ public: } }; -#endif // FILES_WORLD_FILES_HPP_ +#endif // FILES_WORLD_FILES_HPP_ diff --git a/src/files/WorldRegions.cpp b/src/files/WorldRegions.cpp index 642453f8..5660ab75 100644 --- a/src/files/WorldRegions.cpp +++ b/src/files/WorldRegions.cpp @@ -1,5 +1,9 @@ #include "WorldRegions.hpp" +#include +#include +#include + #include "../coders/byte_utils.hpp" #include "../coders/rle.hpp" #include "../data/dynamic.hpp" @@ -7,10 +11,6 @@ #include "../maths/voxmaths.hpp" #include "../util/data_io.hpp" -#include -#include -#include - #define REGION_FORMAT_MAGIC ".VOXREG" regfile::regfile(fs::path filename) : file(std::move(filename)) { @@ -18,15 +18,16 @@ regfile::regfile(fs::path filename) : file(std::move(filename)) { throw std::runtime_error("incomplete region file header"); char header[REGION_HEADER_SIZE]; file.read(header, REGION_HEADER_SIZE); - + // avoid of use strcmp_s - if (std::string(header, strlen(REGION_FORMAT_MAGIC)) != REGION_FORMAT_MAGIC) { + if (std::string(header, strlen(REGION_FORMAT_MAGIC)) != + REGION_FORMAT_MAGIC) { throw std::runtime_error("invalid region file magic number"); } version = header[8]; if (uint(version) > REGION_FORMAT_VERSION) { throw illegal_region_format( - "region format "+std::to_string(version)+" is not supported" + "region format " + std::to_string(version) + " is not supported" ); } } @@ -39,7 +40,7 @@ std::unique_ptr regfile::read(int index, uint32_t& length) { file.seekg(table_offset + index * 4); file.read(reinterpret_cast(&offset), 4); offset = dataio::read_int32_big(reinterpret_cast(&offset), 0); - if (offset == 0){ + if (offset == 0) { return nullptr; } @@ -52,9 +53,11 @@ std::unique_ptr regfile::read(int index, uint32_t& length) { } WorldRegion::WorldRegion() - : chunksData(std::make_unique[]>(REGION_CHUNKS_COUNT)), - sizes(std::make_unique(REGION_CHUNKS_COUNT)) -{} + : chunksData( + std::make_unique[]>(REGION_CHUNKS_COUNT) + ), + sizes(std::make_unique(REGION_CHUNKS_COUNT)) { +} WorldRegion::~WorldRegion() = default; @@ -88,13 +91,14 @@ uint WorldRegion::getChunkDataSize(uint x, uint z) { } WorldRegions::WorldRegions(const fs::path& directory) : directory(directory) { - for (size_t i = 0; i < sizeof(layers)/sizeof(RegionsLayer); i++) { + for (size_t i = 0; i < sizeof(layers) / sizeof(RegionsLayer); i++) { layers[i].layer = i; } - layers[REGION_LAYER_VOXELS].folder = directory/fs::path("regions"); - layers[REGION_LAYER_LIGHTS].folder = directory/fs::path("lights"); - layers[REGION_LAYER_INVENTORIES].folder = directory/fs::path("inventories"); - layers[REGION_LAYER_ENTITIES].folder = directory/fs::path("entities"); + layers[REGION_LAYER_VOXELS].folder = directory / fs::path("regions"); + layers[REGION_LAYER_LIGHTS].folder = directory / fs::path("lights"); + layers[REGION_LAYER_INVENTORIES].folder = + directory / fs::path("inventories"); + layers[REGION_LAYER_ENTITIES].folder = directory / fs::path("entities"); } WorldRegions::~WorldRegions() = default; @@ -121,10 +125,12 @@ WorldRegion* WorldRegions::getOrCreateRegion(int x, int z, int layer) { return region; } -std::unique_ptr WorldRegions::compress(const ubyte* src, size_t srclen, size_t& len) { +std::unique_ptr WorldRegions::compress( + const ubyte* src, size_t srclen, size_t& len +) { auto buffer = bufferPool.get(); auto bytes = buffer.get(); - + len = extrle::encode(src, srclen, bytes); auto data = std::make_unique(len); for (size_t i = 0; i < len; i++) { @@ -133,7 +139,9 @@ std::unique_ptr WorldRegions::compress(const ubyte* src, size_t srclen, return data; } -std::unique_ptr WorldRegions::decompress(const ubyte* src, size_t srclen, size_t dstlen) { +std::unique_ptr WorldRegions::decompress( + const ubyte* src, size_t srclen, size_t dstlen +) { auto decompressed = std::make_unique(dstlen); extrle::decode(src, srclen, decompressed.get()); return decompressed; @@ -157,8 +165,10 @@ std::unique_ptr WorldRegions::readChunkData( return rfile->read(chunkIndex, length); } -/// @brief Read missing chunks data (null pointers) from region file -void WorldRegions::fetchChunks(WorldRegion* region, int x, int z, regfile* file) { +/// @brief Read missing chunks data (null pointers) from region file +void WorldRegions::fetchChunks( + WorldRegion* region, int x, int z, regfile* file +) { auto* chunks = region->getChunks(); uint32_t* sizes = region->getSizes(); @@ -226,7 +236,8 @@ regfile_ptr WorldRegions::getRegFile(glm::ivec3 coord, bool create) { } regfile_ptr WorldRegions::createRegFile(glm::ivec3 coord) { - fs::path file = layers[coord[2]].folder/getRegionFilename(coord[0], coord[1]); + fs::path file = + layers[coord[2]].folder / getRegionFilename(coord[0], coord[1]); if (!fs::exists(file)) { return nullptr; } @@ -261,8 +272,8 @@ fs::path WorldRegions::getRegionFilename(int x, int z) const { return fs::path(std::to_string(x) + "_" + std::to_string(z) + ".bin"); } -void WorldRegions::writeRegion(int x, int z, int layer, WorldRegion* entry){ - fs::path filename = layers[layer].folder/getRegionFilename(x, z); +void WorldRegions::writeRegion(int x, int z, int layer, WorldRegion* entry) { + fs::path filename = layers[layer].folder / getRegionFilename(x, z); glm::ivec3 regcoord(x, z, layer); if (auto regfile = getRegFile(regcoord, false)) { @@ -272,29 +283,31 @@ void WorldRegions::writeRegion(int x, int z, int layer, WorldRegion* entry){ regfile.reset(); closeRegFile(regcoord); } - + char header[REGION_HEADER_SIZE] = REGION_FORMAT_MAGIC; header[8] = REGION_FORMAT_VERSION; - header[9] = 0; // flags + header[9] = 0; // flags std::ofstream file(filename, std::ios::out | std::ios::binary); file.write(header, REGION_HEADER_SIZE); size_t offset = REGION_HEADER_SIZE; - char intbuf[4]{}; - uint offsets[REGION_CHUNKS_COUNT]{}; - + char intbuf[4] {}; + uint offsets[REGION_CHUNKS_COUNT] {}; + auto* region = entry->getChunks(); uint32_t* sizes = entry->getSizes(); - + for (size_t i = 0; i < REGION_CHUNKS_COUNT; i++) { ubyte* chunk = region[i].get(); - if (chunk == nullptr){ + if (chunk == nullptr) { offsets[i] = 0; } else { offsets[i] = offset; size_t compressedSize = sizes[i]; - dataio::write_int32_big(compressedSize, reinterpret_cast(intbuf), 0); + dataio::write_int32_big( + compressedSize, reinterpret_cast(intbuf), 0 + ); offset += 4 + compressedSize; file.write(intbuf, 4); @@ -302,13 +315,15 @@ void WorldRegions::writeRegion(int x, int z, int layer, WorldRegion* entry){ } } for (size_t i = 0; i < REGION_CHUNKS_COUNT; i++) { - dataio::write_int32_big(offsets[i], reinterpret_cast(intbuf), 0); + dataio::write_int32_big( + offsets[i], reinterpret_cast(intbuf), 0 + ); file.write(intbuf, 4); } } void WorldRegions::writeRegions(int layer) { - for (auto& it : layers[layer].regions){ + for (auto& it : layers[layer].regions) { WorldRegion* region = it.second.get(); if (region->getChunks() == nullptr || !region->isUnsaved()) { continue; @@ -318,7 +333,14 @@ void WorldRegions::writeRegions(int layer) { } } -void WorldRegions::put(int x, int z, int layer, std::unique_ptr data, size_t size, bool rle) { +void WorldRegions::put( + int x, + int z, + int layer, + std::unique_ptr data, + size_t size, + bool rle +) { if (rle) { size_t compressedSize; auto compressed = compress(data.get(), size, compressedSize); @@ -333,7 +355,9 @@ void WorldRegions::put(int x, int z, int layer, std::unique_ptr data, s region->put(localX, localZ, data.release(), size); } -static std::unique_ptr write_inventories(Chunk* chunk, uint& datasize) { +static std::unique_ptr write_inventories( + Chunk* chunk, uint& datasize +) { auto& inventories = chunk->inventories; ByteBuilder builder; builder.putInt32(inventories.size()); @@ -343,7 +367,7 @@ static std::unique_ptr write_inventories(Chunk* chunk, uint& datasize) auto bytes = json::to_binary(map.get(), true); builder.putInt32(bytes.size()); builder.put(bytes.data(), bytes.size()); - } + } auto datavec = builder.data(); datasize = builder.size(); auto data = std::make_unique(datasize); @@ -352,7 +376,7 @@ static std::unique_ptr write_inventories(Chunk* chunk, uint& datasize) } /// @brief Store chunk data (voxels and lights) in region (existing or new) -void WorldRegions::put(Chunk* chunk, std::vector entitiesData){ +void WorldRegions::put(Chunk* chunk, std::vector entitiesData) { assert(chunk != nullptr); if (!chunk->flags.lighted) { return; @@ -365,20 +389,32 @@ void WorldRegions::put(Chunk* chunk, std::vector entitiesData){ int regionX, regionZ, localX, localZ; calc_reg_coords(chunk->x, chunk->z, regionX, regionZ, localX, localZ); - put(chunk->x, chunk->z, REGION_LAYER_VOXELS, - chunk->encode(), CHUNK_DATA_LEN, true); + put(chunk->x, + chunk->z, + REGION_LAYER_VOXELS, + chunk->encode(), + CHUNK_DATA_LEN, + true); // Writing lights cache if (doWriteLights && chunk->flags.lighted) { - put(chunk->x, chunk->z, REGION_LAYER_LIGHTS, - chunk->lightmap.encode(), LIGHTMAP_DATA_LEN, true); + put(chunk->x, + chunk->z, + REGION_LAYER_LIGHTS, + chunk->lightmap.encode(), + LIGHTMAP_DATA_LEN, + true); } // Writing block inventories if (!chunk->inventories.empty()) { uint datasize; auto data = write_inventories(chunk, datasize); - put(chunk->x, chunk->z, REGION_LAYER_INVENTORIES, - std::move(data), datasize, false); + put(chunk->x, + chunk->z, + REGION_LAYER_INVENTORIES, + std::move(data), + datasize, + false); } // Writing entities if (!entitiesData.empty()) { @@ -386,12 +422,16 @@ void WorldRegions::put(Chunk* chunk, std::vector entitiesData){ for (size_t i = 0; i < entitiesData.size(); i++) { data[i] = entitiesData[i]; } - put(chunk->x, chunk->z, REGION_LAYER_ENTITIES, - std::move(data), entitiesData.size(), false); + put(chunk->x, + chunk->z, + REGION_LAYER_ENTITIES, + std::move(data), + entitiesData.size(), + false); } } -std::unique_ptr WorldRegions::getChunk(int x, int z){ +std::unique_ptr WorldRegions::getChunk(int x, int z) { uint32_t size; auto* data = getData(x, z, REGION_LAYER_VOXELS, size); if (data == nullptr) { @@ -400,7 +440,7 @@ std::unique_ptr WorldRegions::getChunk(int x, int z){ return decompress(data, size, CHUNK_DATA_LEN); } -/// @brief Get cached lights for chunk at x,z +/// @brief Get cached lights for chunk at x,z /// @return lights data or nullptr std::unique_ptr WorldRegions::getLights(int x, int z) { uint32_t size; @@ -433,7 +473,7 @@ chunk_inventories_map WorldRegions::fetchInventories(int x, int z) { return meta; } - dynamic::Map_sptr WorldRegions::fetchEntities(int x, int z) { +dynamic::Map_sptr WorldRegions::fetchEntities(int x, int z) { uint32_t bytesSize; const ubyte* data = getData(x, z, REGION_LAYER_ENTITIES, bytesSize); if (data == nullptr) { @@ -444,7 +484,7 @@ chunk_inventories_map WorldRegions::fetchInventories(int x, int z) { return nullptr; } return map; - } +} void WorldRegions::processRegionVoxels(int x, int z, const regionproc& func) { if (getRegion(x, z, REGION_LAYER_VOXELS)) { @@ -465,7 +505,12 @@ void WorldRegions::processRegionVoxels(int x, int z, const regionproc& func) { } data = decompress(data.get(), length, CHUNK_DATA_LEN); if (func(data.get())) { - put(gx, gz, REGION_LAYER_VOXELS, std::move(data), CHUNK_DATA_LEN, true); + put(gx, + gz, + REGION_LAYER_VOXELS, + std::move(data), + CHUNK_DATA_LEN, + true); } } } @@ -475,7 +520,6 @@ fs::path WorldRegions::getRegionsFolder(int layer) const { return layers[layer].folder; } - void WorldRegions::write() { for (auto& layer : layers) { fs::create_directories(layer.folder); @@ -483,14 +527,16 @@ void WorldRegions::write() { } } -bool WorldRegions::parseRegionFilename(const std::string& name, int& x, int& z) { +bool WorldRegions::parseRegionFilename( + const std::string& name, int& x, int& z +) { size_t sep = name.find('_'); - if (sep == std::string::npos || sep == 0 || sep == name.length()-1) { + if (sep == std::string::npos || sep == 0 || sep == name.length() - 1) { return false; } try { x = std::stoi(name.substr(0, sep)); - z = std::stoi(name.substr(sep+1)); + z = std::stoi(name.substr(sep + 1)); } catch (std::invalid_argument& err) { return false; } catch (std::out_of_range& err) { diff --git a/src/files/WorldRegions.hpp b/src/files/WorldRegions.hpp index f681794d..6f8c101c 100644 --- a/src/files/WorldRegions.hpp +++ b/src/files/WorldRegions.hpp @@ -1,20 +1,19 @@ #ifndef FILES_WORLD_REGIONS_HPP_ #define FILES_WORLD_REGIONS_HPP_ -#include "files.hpp" +#include +#include +#include +#include +#include +#include +#include + +#include "../data/dynamic_fwd.hpp" #include "../typedefs.hpp" #include "../util/BufferPool.hpp" #include "../voxels/Chunk.hpp" -#include "../data/dynamic_fwd.hpp" - -#include -#include -#include -#include -#include -#include - -#include +#include "files.hpp" #define GLM_ENABLE_EXPERIMENTAL #include "glm/gtx/hash.hpp" @@ -35,8 +34,9 @@ inline constexpr uint MAX_OPEN_REGION_FILES = 16; class illegal_region_format : public std::runtime_error { public: - illegal_region_format(const std::string& message) - : std::runtime_error(message) {} + illegal_region_format(const std::string& message) + : std::runtime_error(message) { + } }; class WorldRegion { @@ -83,14 +83,14 @@ class regfile_ptr { regfile* file; std::condition_variable* cv; public: - regfile_ptr( - regfile* file, - std::condition_variable* cv - ) : file(file), cv(cv) {} + regfile_ptr(regfile* file, std::condition_variable* cv) + : file(file), cv(cv) { + } regfile_ptr(const regfile_ptr&) = delete; - regfile_ptr(std::nullptr_t) : file(nullptr), cv(nullptr) {} + regfile_ptr(std::nullptr_t) : file(nullptr), cv(nullptr) { + } bool operator==(std::nullptr_t) const { return file == nullptr; @@ -123,8 +123,7 @@ class WorldRegions { std::condition_variable regFilesCv; RegionsLayer layers[4] {}; util::BufferPool bufferPool { - std::max(CHUNK_DATA_LEN, LIGHTMAP_DATA_LEN) * 2 - }; + std::max(CHUNK_DATA_LEN, LIGHTMAP_DATA_LEN) * 2}; WorldRegion* getRegion(int x, int z, int layer); WorldRegion* getOrCreateRegion(int x, int z, int layer); @@ -134,22 +133,28 @@ class WorldRegions { /// @param srclen length of the source buffer /// @param len (out argument) length of result buffer /// @return compressed bytes array - std::unique_ptr compress(const ubyte* src, size_t srclen, size_t& len); + std::unique_ptr compress( + const ubyte* src, size_t srclen, size_t& len + ); /// @brief Decompress buffer with extrle /// @param src compressed buffer /// @param srclen length of compressed buffer /// @param dstlen max expected length of source buffer /// @return decompressed bytes array - std::unique_ptr decompress(const ubyte* src, size_t srclen, size_t dstlen); + std::unique_ptr decompress( + const ubyte* src, size_t srclen, size_t dstlen + ); - std::unique_ptr readChunkData(int x, int y, uint32_t& length, regfile* file); + std::unique_ptr readChunkData( + int x, int y, uint32_t& length, regfile* file + ); void fetchChunks(WorldRegion* region, int x, int y, regfile* file); ubyte* getData(int x, int z, int layer, uint32_t& size); - regfile_ptr getRegFile(glm::ivec3 coord, bool create=true); + regfile_ptr getRegFile(glm::ivec3 coord, bool create = true); void closeRegFile(glm::ivec3 coord); regfile_ptr useRegFile(glm::ivec3 coord); regfile_ptr createRegFile(glm::ivec3 coord); @@ -174,19 +179,26 @@ public: /// @brief Put all chunk data to regions void put(Chunk* chunk, std::vector entitiesData); - /// @brief Store data in specified region + /// @brief Store data in specified region /// @param x chunk.x /// @param z chunk.z /// @param layer regions layer /// @param data target data /// @param size data size /// @param rle compress with ext-RLE - void put(int x, int z, int layer, std::unique_ptr data, size_t size, bool rle); + void put( + int x, + int z, + int layer, + std::unique_ptr data, + size_t size, + bool rle + ); std::unique_ptr getChunk(int x, int z); std::unique_ptr getLights(int x, int z); chunk_inventories_map fetchInventories(int x, int z); - dynamic::Map_sptr fetchEntities(int x, int z); + dynamic::Map_sptr fetchEntities(int x, int z); void processRegionVoxels(int x, int z, const regionproc& func); @@ -202,4 +214,4 @@ public: static bool parseRegionFilename(const std::string& name, int& x, int& y); }; -#endif // FILES_WORLD_REGIONS_HPP_ +#endif // FILES_WORLD_REGIONS_HPP_ diff --git a/src/files/engine_paths.cpp b/src/files/engine_paths.cpp index 00bc7670..18713331 100644 --- a/src/files/engine_paths.cpp +++ b/src/files/engine_paths.cpp @@ -1,13 +1,13 @@ #include "engine_paths.hpp" -#include -#include -#include #include +#include +#include +#include #include -#include "../util/stringutil.hpp" #include "../typedefs.hpp" +#include "../util/stringutil.hpp" #include "WorldFiles.hpp" const fs::path SCREENSHOTS_FOLDER {"screenshots"}; @@ -16,7 +16,7 @@ const fs::path CONTROLS_FILE {"controls.toml"}; const fs::path SETTINGS_FILE {"settings.toml"}; void EnginePaths::prepare() { - fs::path contentFolder = userfiles/fs::path(CONTENT_FOLDER); + fs::path contentFolder = userfiles / fs::path(CONTENT_FOLDER); if (!fs::is_directory(contentFolder)) { fs::create_directories(contentFolder); } @@ -31,7 +31,7 @@ fs::path EnginePaths::getResources() const { } fs::path EnginePaths::getScreenshotFile(const std::string& ext) { - fs::path folder = userfiles/fs::path(SCREENSHOTS_FOLDER); + fs::path folder = userfiles / fs::path(SCREENSHOTS_FOLDER); if (!fs::is_directory(folder)) { fs::create_directory(folder); } @@ -44,17 +44,21 @@ fs::path EnginePaths::getScreenshotFile(const std::string& ext) { ss << std::put_time(&tm, format); std::string datetimestr = ss.str(); - fs::path filename = folder/fs::u8path("screenshot-"+datetimestr+"."+ext); + fs::path filename = + folder / fs::u8path("screenshot-" + datetimestr + "." + ext); uint index = 0; while (fs::exists(filename)) { - filename = folder/fs::u8path("screenshot-"+datetimestr+"-"+std::to_string(index)+"."+ext); + filename = folder / fs::u8path( + "screenshot-" + datetimestr + "-" + + std::to_string(index) + "." + ext + ); index++; } return filename; } fs::path EnginePaths::getWorldsFolder() { - return userfiles/fs::path("worlds"); + return userfiles / fs::path("worlds"); } fs::path EnginePaths::getWorldFolder() { @@ -62,45 +66,44 @@ fs::path EnginePaths::getWorldFolder() { } fs::path EnginePaths::getWorldFolder(const std::string& name) { - return getWorldsFolder()/fs::path(name); + return getWorldsFolder() / fs::path(name); } fs::path EnginePaths::getControlsFile() { - return userfiles/fs::path(CONTROLS_FILE); + return userfiles / fs::path(CONTROLS_FILE); } fs::path EnginePaths::getSettingsFile() { - return userfiles/fs::path(SETTINGS_FILE); + return userfiles / fs::path(SETTINGS_FILE); } std::vector EnginePaths::scanForWorlds() { std::vector folders; fs::path folder = getWorldsFolder(); - if (!fs::is_directory(folder)) - return folders; - + if (!fs::is_directory(folder)) return folders; + for (const auto& entry : fs::directory_iterator(folder)) { if (!entry.is_directory()) { continue; } const fs::path& worldFolder = entry.path(); - fs::path worldFile = worldFolder/fs::u8path(WorldFiles::WORLD_FILE); + fs::path worldFile = worldFolder / fs::u8path(WorldFiles::WORLD_FILE); if (!fs::is_regular_file(worldFile)) { continue; } folders.push_back(worldFolder); } std::sort(folders.begin(), folders.end(), [](fs::path a, fs::path b) { - a = a/fs::u8path(WorldFiles::WORLD_FILE); - b = b/fs::u8path(WorldFiles::WORLD_FILE); + a = a / fs::u8path(WorldFiles::WORLD_FILE); + b = b / fs::u8path(WorldFiles::WORLD_FILE); return fs::last_write_time(a) > fs::last_write_time(b); }); return folders; } bool EnginePaths::isWorldNameUsed(const std::string& name) { - return fs::exists(EnginePaths::getWorldsFolder()/fs::u8path(name)); + return fs::exists(EnginePaths::getWorldsFolder() / fs::u8path(name)); } void EnginePaths::setUserfiles(fs::path folder) { @@ -125,8 +128,7 @@ static fs::path toCanonic(fs::path path) { while (true) { parts.push(path.filename().u8string()); path = path.parent_path(); - if (path.empty()) - break; + if (path.empty()) break; } path = fs::u8path(""); while (!parts.empty()) { @@ -150,38 +152,38 @@ fs::path EnginePaths::resolve(const std::string& path, bool throwErr) { throw files_access_error("no entry point specified"); } std::string prefix = path.substr(0, separator); - std::string filename = path.substr(separator+1); + std::string filename = path.substr(separator + 1); filename = toCanonic(fs::u8path(filename)).u8string(); if (prefix == "res" || prefix == "core") { - return resources/fs::u8path(filename); + return resources / fs::u8path(filename); } if (prefix == "user") { - return userfiles/fs::u8path(filename); + return userfiles / fs::u8path(filename); } if (prefix == "world") { - return worldFolder/fs::u8path(filename); + return worldFolder / fs::u8path(filename); } if (contentPacks) { for (auto& pack : *contentPacks) { if (pack.id == prefix) { - return pack.folder/fs::u8path(filename); + return pack.folder / fs::u8path(filename); } } } if (throwErr) { - throw files_access_error("unknown entry point '"+prefix+"'"); + throw files_access_error("unknown entry point '" + prefix + "'"); } return fs::path(filename); } -ResPaths::ResPaths(fs::path mainRoot, std::vector roots) +ResPaths::ResPaths(fs::path mainRoot, std::vector roots) : mainRoot(std::move(mainRoot)), roots(std::move(roots)) { } fs::path ResPaths::find(const std::string& filename) const { - for (int i = roots.size()-1; i >= 0; i--) { + for (int i = roots.size() - 1; i >= 0; i--) { auto& root = roots[i]; fs::path file = root.path / fs::u8path(filename); if (fs::exists(file)) { @@ -192,7 +194,7 @@ fs::path ResPaths::find(const std::string& filename) const { } std::string ResPaths::findRaw(const std::string& filename) const { - for (int i = roots.size()-1; i >= 0; i--) { + for (int i = roots.size() - 1; i >= 0; i--) { auto& root = roots[i]; if (fs::exists(root.path / fs::path(filename))) { return root.name + ":" + filename; @@ -200,30 +202,29 @@ std::string ResPaths::findRaw(const std::string& filename) const { } auto resDir = mainRoot; if (fs::exists(resDir / fs::path(filename))) { - return "core:"+filename; + return "core:" + filename; } - throw std::runtime_error("could not to find file "+util::quote(filename)); + throw std::runtime_error("could not to find file " + util::quote(filename)); } -std::vector ResPaths::listdirRaw(const std::string& folderName) const { +std::vector ResPaths::listdirRaw(const std::string& folderName +) const { std::vector entries; - for (int i = roots.size()-1; i >= 0; i--) { + for (int i = roots.size() - 1; i >= 0; i--) { auto& root = roots[i]; fs::path folder = root.path / fs::u8path(folderName); - if (!fs::is_directory(folder)) - continue; + if (!fs::is_directory(folder)) continue; for (const auto& entry : fs::directory_iterator(folder)) { auto name = entry.path().filename().u8string(); - entries.emplace_back(root.name+":"+folderName+"/"+name); + entries.emplace_back(root.name + ":" + folderName + "/" + name); } } { fs::path folder = mainRoot / fs::u8path(folderName); - if (!fs::is_directory(folder)) - return entries; + if (!fs::is_directory(folder)) return entries; for (const auto& entry : fs::directory_iterator(folder)) { auto name = entry.path().filename().u8string(); - entries.emplace_back("core:"+folderName+"/"+name); + entries.emplace_back("core:" + folderName + "/" + name); } } return entries; @@ -231,19 +232,17 @@ std::vector ResPaths::listdirRaw(const std::string& folderName) con std::vector ResPaths::listdir(const std::string& folderName) const { std::vector entries; - for (int i = roots.size()-1; i >= 0; i--) { + for (int i = roots.size() - 1; i >= 0; i--) { auto& root = roots[i]; fs::path folder = root.path / fs::u8path(folderName); - if (!fs::is_directory(folder)) - continue; + if (!fs::is_directory(folder)) continue; for (const auto& entry : fs::directory_iterator(folder)) { entries.push_back(entry.path()); } } { fs::path folder = mainRoot / fs::u8path(folderName); - if (!fs::is_directory(folder)) - return entries; + if (!fs::is_directory(folder)) return entries; for (const auto& entry : fs::directory_iterator(folder)) { entries.push_back(entry.path()); } diff --git a/src/files/engine_paths.hpp b/src/files/engine_paths.hpp index 025835ac..6465905f 100644 --- a/src/files/engine_paths.hpp +++ b/src/files/engine_paths.hpp @@ -1,10 +1,10 @@ #ifndef FILES_ENGINE_PATHS_HPP_ #define FILES_ENGINE_PATHS_HPP_ +#include +#include #include #include -#include -#include #include "../content/ContentPack.hpp" @@ -12,12 +12,13 @@ namespace fs = std::filesystem; class files_access_error : public std::runtime_error { public: - files_access_error(const std::string& msg) : std::runtime_error(msg) {} + files_access_error(const std::string& msg) : std::runtime_error(msg) { + } }; class EnginePaths { fs::path userfiles {"."}; - fs::path resources {"res"}; + fs::path resources {"res"}; fs::path worldFolder; std::vector* contentPacks = nullptr; public: @@ -25,7 +26,7 @@ public: fs::path getUserfiles() const; fs::path getResources() const; - + fs::path getScreenshotFile(const std::string& ext); fs::path getWorldsFolder(); fs::path getWorldFolder(); @@ -41,7 +42,7 @@ public: std::vector scanForWorlds(); - fs::path resolve(const std::string& path, bool throwErr=true); + fs::path resolve(const std::string& path, bool throwErr = true); }; struct PathsRoot { @@ -53,11 +54,8 @@ class ResPaths { fs::path mainRoot; std::vector roots; public: - ResPaths( - fs::path mainRoot, - std::vector roots - ); - + ResPaths(fs::path mainRoot, std::vector roots); + fs::path find(const std::string& filename) const; std::string findRaw(const std::string& filename) const; std::vector listdir(const std::string& folder) const; @@ -66,4 +64,4 @@ public: const fs::path& getMainRoot() const; }; -#endif // FILES_ENGINE_PATHS_HPP_ +#endif // FILES_ENGINE_PATHS_HPP_ diff --git a/src/files/files.cpp b/src/files/files.cpp index 4c4d4ffd..e471a627 100644 --- a/src/files/files.cpp +++ b/src/files/files.cpp @@ -1,24 +1,25 @@ #include "files.hpp" -#include "../coders/commons.hpp" -#include "../coders/json.hpp" -#include "../coders/toml.hpp" -#include "../coders/gzip.hpp" -#include "../util/stringutil.hpp" -#include "../data/dynamic.hpp" +#include #include #include #include -#include #include +#include "../coders/commons.hpp" +#include "../coders/gzip.hpp" +#include "../coders/json.hpp" +#include "../coders/toml.hpp" +#include "../data/dynamic.hpp" +#include "../util/stringutil.hpp" + namespace fs = std::filesystem; files::rafile::rafile(const fs::path& filename) : file(filename, std::ios::binary | std::ios::ate) { if (!file) { - throw std::runtime_error("could not to open file "+filename.string()); + throw std::runtime_error("could not to open file " + filename.string()); } filelength = file.tellg(); file.seekg(0); @@ -36,19 +37,21 @@ void files::rafile::read(char* buffer, std::streamsize size) { file.read(buffer, size); } -bool files::write_bytes(const fs::path& filename, const ubyte* data, size_t size) { +bool files::write_bytes( + const fs::path& filename, const ubyte* data, size_t size +) { std::ofstream output(filename, std::ios::binary); - if (!output.is_open()) - return false; + if (!output.is_open()) return false; output.write((const char*)data, size); output.close(); return true; } -uint files::append_bytes(const fs::path& filename, const ubyte* data, size_t size) { +uint files::append_bytes( + const fs::path& filename, const ubyte* data, size_t size +) { std::ofstream output(filename, std::ios::binary | std::ios::app); - if (!output.is_open()) - return 0; + if (!output.is_open()) return 0; uint position = output.tellp(); output.write((const char*)data, size); output.close(); @@ -57,17 +60,17 @@ uint files::append_bytes(const fs::path& filename, const ubyte* data, size_t siz bool files::read(const fs::path& filename, char* data, size_t size) { std::ifstream output(filename, std::ios::binary); - if (!output.is_open()) - return false; + if (!output.is_open()) return false; output.read(data, size); output.close(); return true; } -std::unique_ptr files::read_bytes(const fs::path& filename, size_t& length) { +std::unique_ptr files::read_bytes( + const fs::path& filename, size_t& length +) { std::ifstream input(filename, std::ios::binary); - if (!input.is_open()) - return nullptr; + if (!input.is_open()) return nullptr; input.seekg(0, std::ios_base::end); length = input.tellg(); input.seekg(0, std::ios_base::beg); @@ -80,8 +83,7 @@ std::unique_ptr files::read_bytes(const fs::path& filename, size_t& len std::vector files::read_bytes(const fs::path& filename) { std::ifstream input(filename, std::ios::binary); - if (!input.is_open()) - return {}; + if (!input.is_open()) return {}; input.seekg(0, std::ios_base::end); size_t length = input.tellg(); input.seekg(0, std::ios_base::beg); @@ -95,10 +97,11 @@ std::vector files::read_bytes(const fs::path& filename) { std::string files::read_string(const fs::path& filename) { size_t size; - std::unique_ptr bytes (read_bytes(filename, size)); + std::unique_ptr bytes(read_bytes(filename, size)); if (bytes == nullptr) { - throw std::runtime_error("could not to load file '"+ - filename.string()+"'"); + throw std::runtime_error( + "could not to load file '" + filename.string() + "'" + ); } return std::string((const char*)bytes.get(), size); } @@ -112,11 +115,15 @@ bool files::write_string(const fs::path& filename, const std::string content) { return true; } -bool files::write_json(const fs::path& filename, const dynamic::Map* obj, bool nice) { +bool files::write_json( + const fs::path& filename, const dynamic::Map* obj, bool nice +) { return files::write_string(filename, json::stringify(obj, nice, " ")); } -bool files::write_binary_json(const fs::path& filename, const dynamic::Map* obj, bool compression) { +bool files::write_binary_json( + const fs::path& filename, const dynamic::Map* obj, bool compression +) { auto bytes = json::to_binary(obj, compression); return files::write_bytes(filename, bytes.data(), bytes.size()); } @@ -128,7 +135,7 @@ std::shared_ptr files::read_json(const fs::path& filename) { std::shared_ptr files::read_binary_json(const fs::path& file) { size_t size; - std::unique_ptr bytes (files::read_bytes(file, size)); + std::unique_ptr bytes(files::read_bytes(file, size)); return json::from_binary(bytes.get(), size); } @@ -139,16 +146,16 @@ std::shared_ptr files::read_toml(const fs::path& file) { std::vector files::read_list(const fs::path& filename) { std::ifstream file(filename); if (!file) { - throw std::runtime_error("could not to open file "+filename.u8string()); + throw std::runtime_error( + "could not to open file " + filename.u8string() + ); } std::vector lines; std::string line; while (std::getline(file, line)) { util::trim(line); - if (line.length() == 0) - continue; - if (line[0] == '#') - continue; + if (line.length() == 0) continue; + if (line[0] == '#') continue; lines.push_back(line); } return lines; diff --git a/src/files/files.hpp b/src/files/files.hpp index 1a124b25..99bce793 100644 --- a/src/files/files.hpp +++ b/src/files/files.hpp @@ -1,11 +1,12 @@ #ifndef FILES_FILES_HPP_ #define FILES_FILES_HPP_ +#include +#include +#include #include #include -#include -#include -#include + #include "../typedefs.hpp" namespace fs = std::filesystem; @@ -43,16 +44,19 @@ namespace files { bool write_string(const fs::path& filename, const std::string content); /// @brief Write dynamic data to the JSON file - /// @param nice if true, human readable format will be used, otherwise minimal - bool write_json(const fs::path& filename, const dynamic::Map* obj, bool nice=true); + /// @param nice if true, human readable format will be used, otherwise + /// minimal + bool write_json( + const fs::path& filename, const dynamic::Map* obj, bool nice = true + ); /// @brief Write dynamic data to the binary JSON file /// (see src/coders/binary_json_spec.md) /// @param compressed use gzip compression bool write_binary_json( const fs::path& filename, - const dynamic::Map* obj, - bool compressed=false + const dynamic::Map* obj, + bool compressed = false ); bool read(const fs::path&, char* data, size_t size); diff --git a/src/files/settings_io.cpp b/src/files/settings_io.cpp index f09ee1f2..10589fb1 100644 --- a/src/files/settings_io.cpp +++ b/src/files/settings_io.cpp @@ -1,15 +1,15 @@ #include "settings_io.hpp" -#include "../window/Events.hpp" -#include "../window/input.hpp" -#include "../coders/toml.hpp" -#include "../coders/json.hpp" -#include "../debug/Logger.hpp" -#include "../settings.hpp" - #include #include +#include "../coders/json.hpp" +#include "../coders/toml.hpp" +#include "../debug/Logger.hpp" +#include "../settings.hpp" +#include "../window/Events.hpp" +#include "../window/input.hpp" + static debug::Logger logger("settings_io"); struct SectionsBuilder { @@ -19,16 +19,17 @@ struct SectionsBuilder { SectionsBuilder( std::unordered_map& map, std::vector
& sections - ) : map(map), sections(sections) { + ) + : map(map), sections(sections) { } void section(std::string name) { sections.push_back(Section {std::move(name), {}}); } - void add(const std::string& name, Setting* setting, bool writeable=true) { - Section& section = sections.at(sections.size()-1); - map[section.name+"."+name] = setting; + void add(const std::string& name, Setting* setting, bool writeable = true) { + Section& section = sections.at(sections.size() - 1); + map[section.name + "." + name] = setting; section.keys.push_back(name); } }; @@ -82,7 +83,7 @@ SettingsHandler::SettingsHandler(EngineSettings& settings) { dynamic::Value SettingsHandler::getValue(const std::string& name) const { auto found = map.find(name); if (found == map.end()) { - throw std::runtime_error("setting '"+name+"' does not exist"); + throw std::runtime_error("setting '" + name + "' does not exist"); } auto setting = found->second; if (auto number = dynamic_cast(setting)) { @@ -94,14 +95,14 @@ dynamic::Value SettingsHandler::getValue(const std::string& name) const { } else if (auto string = dynamic_cast(setting)) { return string->get(); } else { - throw std::runtime_error("type is not implemented for '"+name+"'"); + throw std::runtime_error("type is not implemented for '" + name + "'"); } } std::string SettingsHandler::toString(const std::string& name) const { auto found = map.find(name); if (found == map.end()) { - throw std::runtime_error("setting '"+name+"' does not exist"); + throw std::runtime_error("setting '" + name + "' does not exist"); } auto setting = found->second; return setting->toString(); @@ -110,7 +111,7 @@ std::string SettingsHandler::toString(const std::string& name) const { Setting* SettingsHandler::getSetting(const std::string& name) const { auto found = map.find(name); if (found == map.end()) { - throw std::runtime_error("setting '"+name+"' does not exist"); + throw std::runtime_error("setting '" + name + "' does not exist"); } return found->second; } @@ -119,7 +120,7 @@ bool SettingsHandler::has(const std::string& name) const { return map.find(name) != map.end(); } -template +template static void set_numeric_value(T* setting, const dynamic::Value& value) { if (auto num = std::get_if(&value)) { setting->set(*num); @@ -132,10 +133,12 @@ static void set_numeric_value(T* setting, const dynamic::Value& value) { } } -void SettingsHandler::setValue(const std::string& name, const dynamic::Value& value) { +void SettingsHandler::setValue( + const std::string& name, const dynamic::Value& value +) { auto found = map.find(name); if (found == map.end()) { - throw std::runtime_error("setting '"+name+"' does not exist"); + throw std::runtime_error("setting '" + name + "' does not exist"); } auto setting = found->second; if (auto number = dynamic_cast(setting)) { @@ -157,7 +160,9 @@ void SettingsHandler::setValue(const std::string& name, const dynamic::Value& va throw std::runtime_error("not implemented for type"); } } else { - throw std::runtime_error("type is not implement - setting '"+name+"'"); + throw std::runtime_error( + "type is not implement - setting '" + name + "'" + ); } } diff --git a/src/files/settings_io.hpp b/src/files/settings_io.hpp index cc112e43..3daee10d 100644 --- a/src/files/settings_io.hpp +++ b/src/files/settings_io.hpp @@ -1,12 +1,12 @@ #ifndef FILES_SETTINGS_IO_HPP_ #define FILES_SETTINGS_IO_HPP_ -#include "../data/dynamic.hpp" - -#include #include -#include +#include #include +#include + +#include "../data/dynamic.hpp" class Setting; struct EngineSettings; @@ -31,4 +31,4 @@ public: std::vector
& getSections(); }; -#endif // FILES_SETTINGS_IO_HPP_ +#endif // FILES_SETTINGS_IO_HPP_ diff --git a/src/items/Inventories.cpp b/src/items/Inventories.cpp index d14dcb0a..7fbbf789 100644 --- a/src/items/Inventories.cpp +++ b/src/items/Inventories.cpp @@ -40,15 +40,13 @@ void Inventories::remove(int64_t id) { std::shared_ptr Inventories::get(int64_t id) { auto found = map.find(id); - if (found == map.end()) - return nullptr; + if (found == map.end()) return nullptr; return found->second; } std::shared_ptr Inventories::clone(int64_t id) { auto original = get(id); - if (original == nullptr) - return nullptr; + if (original == nullptr) return nullptr; auto clone = std::make_shared(*original); clone->setId(level.getWorld()->getNextInventoryId()); store(clone); diff --git a/src/items/Inventories.hpp b/src/items/Inventories.hpp index 28e89780..e50a95b5 100644 --- a/src/items/Inventories.hpp +++ b/src/items/Inventories.hpp @@ -1,12 +1,12 @@ #ifndef ITEMS_INVENTORIES_HPP_ #define ITEMS_INVENTORIES_HPP_ -#include #include +#include #include -#include "Inventory.hpp" #include "../maths/util.hpp" +#include "Inventory.hpp" class Level; @@ -41,4 +41,4 @@ public: const inventories_map& getMap() const; }; -#endif // ITEMS_INVENTORIES_HPP_ +#endif // ITEMS_INVENTORIES_HPP_ diff --git a/src/items/Inventory.cpp b/src/items/Inventory.cpp index 8361f63d..05d6bb5a 100644 --- a/src/items/Inventory.cpp +++ b/src/items/Inventory.cpp @@ -1,7 +1,7 @@ #include "Inventory.hpp" -#include "../data/dynamic.hpp" #include "../content/ContentLUT.hpp" +#include "../data/dynamic.hpp" Inventory::Inventory(int64_t id, size_t size) : id(id), slots(size) { } @@ -35,11 +35,8 @@ size_t Inventory::findSlotByItem(itemid_t id, size_t begin, size_t end) { } void Inventory::move( - ItemStack& item, - const ContentIndices* indices, - size_t begin, - size_t end) -{ + ItemStack& item, const ContentIndices* indices, size_t begin, size_t end +) { end = std::min(slots.size(), end); for (size_t i = begin; i < end && !item.isEmpty(); i++) { ItemStack& slot = slots[i]; @@ -61,7 +58,7 @@ void Inventory::deserialize(dynamic::Map* src) { itemid_t id = item->get("id", ITEM_EMPTY); itemcount_t count = item->get("count", 0); auto& slot = slots[i]; - slot.set(ItemStack(id, count)); + slot.set(ItemStack(id, count)); } } diff --git a/src/items/Inventory.hpp b/src/items/Inventory.hpp index 78ae2abc..c2c73d41 100644 --- a/src/items/Inventory.hpp +++ b/src/items/Inventory.hpp @@ -1,13 +1,12 @@ #ifndef ITEMS_INVENTORY_HPP_ #define ITEMS_INVENTORY_HPP_ -#include "ItemStack.hpp" - -#include "../typedefs.hpp" -#include "../interfaces/Serializable.hpp" - -#include #include +#include + +#include "../interfaces/Serializable.hpp" +#include "../typedefs.hpp" +#include "ItemStack.hpp" namespace dynamic { class Map; @@ -25,18 +24,19 @@ public: Inventory(const Inventory& orig); ItemStack& getSlot(size_t index); - size_t findEmptySlot(size_t begin=0, size_t end=-1) const; - size_t findSlotByItem(itemid_t id, size_t begin=0, size_t end=-1); - + size_t findEmptySlot(size_t begin = 0, size_t end = -1) const; + size_t findSlotByItem(itemid_t id, size_t begin = 0, size_t end = -1); + inline size_t size() const { return slots.size(); } void move( - ItemStack& item, - const ContentIndices* indices, - size_t begin=0, - size_t end=-1); + ItemStack& item, + const ContentIndices* indices, + size_t begin = 0, + size_t end = -1 + ); /* deserializing inventory */ void deserialize(dynamic::Map* src) override; @@ -60,4 +60,4 @@ public: static const size_t npos; }; -#endif // ITEMS_INVENTORY_HPP_ +#endif // ITEMS_INVENTORY_HPP_ diff --git a/src/items/ItemDef.cpp b/src/items/ItemDef.cpp index c958f364..22c48048 100644 --- a/src/items/ItemDef.cpp +++ b/src/items/ItemDef.cpp @@ -1,4 +1,5 @@ #include "ItemDef.hpp" + #include "../util/stringutil.hpp" ItemDef::ItemDef(const std::string& name) : name(name) { diff --git a/src/items/ItemDef.hpp b/src/items/ItemDef.hpp index 319860e1..def1abb3 100644 --- a/src/items/ItemDef.hpp +++ b/src/items/ItemDef.hpp @@ -1,22 +1,22 @@ #ifndef CONTENT_ITEMS_ITEM_DEF_HPP_ #define CONTENT_ITEMS_ITEM_DEF_HPP_ -#include #include +#include #include "../typedefs.hpp" struct item_funcs_set { - bool init: 1; - bool on_use: 1; - bool on_use_on_block: 1; - bool on_block_break_by: 1; + bool init : 1; + bool on_use : 1; + bool on_use_on_block : 1; + bool on_block_break_by : 1; }; enum class item_icon_type { - none, // invisible (core:empty) must not be rendered - sprite, // textured quad: icon is `atlas_name:texture_name` - block, // block preview: icon is string block id + none, // invisible (core:empty) must not be rendered + sprite, // textured quad: icon is `atlas_name:texture_name` + block, // block preview: icon is string block id }; struct ItemDef { @@ -34,7 +34,7 @@ struct ItemDef { std::string icon = "blocks:notfound"; std::string placingBlock = "core:air"; - std::string scriptName = name.substr(name.find(':')+1); + std::string scriptName = name.substr(name.find(':') + 1); struct { itemid_t id; @@ -47,4 +47,4 @@ struct ItemDef { ItemDef(const ItemDef&) = delete; }; -#endif //CONTENT_ITEMS_ITEM_DEF_HPP_ +#endif // CONTENT_ITEMS_ITEM_DEF_HPP_ diff --git a/src/items/ItemStack.cpp b/src/items/ItemStack.cpp index 4c715064..120972b6 100644 --- a/src/items/ItemStack.cpp +++ b/src/items/ItemStack.cpp @@ -1,12 +1,13 @@ #include "ItemStack.hpp" -#include "ItemDef.hpp" #include "../content/Content.hpp" +#include "ItemDef.hpp" ItemStack::ItemStack() : item(ITEM_EMPTY), count(0) { } -ItemStack::ItemStack(itemid_t item, itemcount_t count) : item(item), count(count) { +ItemStack::ItemStack(itemid_t item, itemcount_t count) + : item(item), count(count) { } void ItemStack::set(const ItemStack& item) { @@ -26,13 +27,13 @@ bool ItemStack::accepts(const ItemStack& other) const { void ItemStack::move(ItemStack& item, const ContentIndices* indices) { auto def = indices->items.get(item.getItemId()); - int count = std::min(item.count, def->stackSize-this->count); + int count = std::min(item.count, def->stackSize - this->count); if (isEmpty()) { set(ItemStack(item.getItemId(), count)); } else { setCount(this->count + count); } - item.setCount(item.count-count); + item.setCount(item.count - count); } void ItemStack::setCount(itemcount_t count) { diff --git a/src/items/ItemStack.hpp b/src/items/ItemStack.hpp index 96861b8f..8cfbd2ed 100644 --- a/src/items/ItemStack.hpp +++ b/src/items/ItemStack.hpp @@ -1,8 +1,8 @@ #ifndef ITEMS_ITEM_STACK_HPP_ #define ITEMS_ITEM_STACK_HPP_ -#include "../typedefs.hpp" #include "../constants.hpp" +#include "../typedefs.hpp" class ContentIndices; @@ -37,4 +37,4 @@ public: } }; -#endif // ITEMS_ITEM_STACK_HPP_ +#endif // ITEMS_ITEM_STACK_HPP_ diff --git a/src/logic/BlocksController.cpp b/src/logic/BlocksController.cpp index 8f49635c..ade2a16f 100644 --- a/src/logic/BlocksController.cpp +++ b/src/logic/BlocksController.cpp @@ -1,23 +1,22 @@ #include "BlocksController.hpp" -#include "../voxels/voxel.hpp" +#include "../content/Content.hpp" +#include "../items/Inventories.hpp" +#include "../items/Inventory.hpp" +#include "../lighting/Lighting.hpp" +#include "../maths/fastmaths.hpp" +#include "../util/timeutil.hpp" #include "../voxels/Block.hpp" #include "../voxels/Chunk.hpp" #include "../voxels/Chunks.hpp" +#include "../voxels/voxel.hpp" #include "../world/Level.hpp" #include "../world/World.hpp" -#include "../content/Content.hpp" -#include "../lighting/Lighting.hpp" -#include "../util/timeutil.hpp" -#include "../maths/fastmaths.hpp" -#include "../items/Inventory.hpp" -#include "../items/Inventories.hpp" - #include "scripting/scripting.hpp" -BlocksController::BlocksController(Level* level, uint padding) - : level(level), - chunks(level->chunks.get()), +BlocksController::BlocksController(Level* level, uint padding) + : level(level), + chunks(level->chunks.get()), lighting(level->lighting.get()), randTickClock(20, 3), blocksTickClock(20, 1), @@ -26,26 +25,32 @@ BlocksController::BlocksController(Level* level, uint padding) } void BlocksController::updateSides(int x, int y, int z) { - updateBlock(x-1, y, z); - updateBlock(x+1, y, z); - updateBlock(x, y-1, z); - updateBlock(x, y+1, z); - updateBlock(x, y, z-1); - updateBlock(x, y, z+1); + updateBlock(x - 1, y, z); + updateBlock(x + 1, y, z); + updateBlock(x, y - 1, z); + updateBlock(x, y + 1, z); + updateBlock(x, y, z - 1); + updateBlock(x, y, z + 1); } -void BlocksController::breakBlock(Player* player, const Block* def, int x, int y, int z) { +void BlocksController::breakBlock( + Player* player, const Block* def, int x, int y, int z +) { onBlockInteraction( - player, glm::ivec3(x, y, z), def, BlockInteraction::destruction); + player, glm::ivec3(x, y, z), def, BlockInteraction::destruction + ); chunks->set(x, y, z, 0, {}); lighting->onBlockSet(x, y, z, 0); scripting::on_block_broken(player, def, x, y, z); updateSides(x, y, z); } -void BlocksController::placeBlock(Player* player, const Block* def, blockstate state, int x, int y, int z) { +void BlocksController::placeBlock( + Player* player, const Block* def, blockstate state, int x, int y, int z +) { onBlockInteraction( - player, glm::ivec3(x, y, z), def, BlockInteraction::placing); + player, glm::ivec3(x, y, z), def, BlockInteraction::placing + ); chunks->set(x, y, z, def->rt.id, state); lighting->onBlockSet(x, y, z, def->rt.id); if (def->rt.funcsset.onplaced) { @@ -56,12 +61,11 @@ void BlocksController::placeBlock(Player* player, const Block* def, blockstate s void BlocksController::updateBlock(int x, int y, int z) { voxel* vox = chunks->get(x, y, z); - if (vox == nullptr) - return; + if (vox == nullptr) return; auto def = level->content->getIndices()->blocks.get(vox->id); if (def->grounded) { const auto& vec = get_ground_direction(def, vox->state.rotation); - if (!chunks->isSolidBlock(x+vec.x, y+vec.y, z+vec.z)) { + if (!chunks->isSolidBlock(x + vec.x, y + vec.y, z + vec.z)) { breakBlock(nullptr, def, x, y, z); return; } @@ -88,8 +92,7 @@ void BlocksController::onBlocksTick(int tickid, int parts) { auto indices = content->getIndices(); int tickRate = blocksTickClock.getTickRate(); for (size_t id = 0; id < indices->blocks.count(); id++) { - if ((id + tickid) % parts != 0) - continue; + if ((id + tickid) % parts != 0) continue; auto def = indices->blocks.get(id); auto interval = def->tickInterval; if (def->rt.funcsset.onblockstick && tickid / parts % interval == 0) { @@ -112,9 +115,7 @@ void BlocksController::randomTick( Block* block = indices->blocks.get(vox.id); if (block->rt.funcsset.randupdate) { scripting::random_update_block( - block, - chunk.x * CHUNK_W + bx, by, - chunk.z * CHUNK_D + bz + block, chunk.x * CHUNK_W + bx, by, chunk.z * CHUNK_D + bz ); } } @@ -126,9 +127,9 @@ void BlocksController::randomTick(int tickid, int parts) { const int w = chunks->w; const int d = chunks->d; int segments = 4; - - for (uint z = padding; z < d-padding; z++){ - for (uint x = padding; x < w-padding; x++){ + + for (uint z = padding; z < d - padding; z++) { + for (uint x = padding; x < w - padding; x++) { int index = z * w + x; if ((index + tickid) % parts != 0) { continue; @@ -187,16 +188,15 @@ void BlocksController::unbindInventory(int x, int y, int z) { } void BlocksController::onBlockInteraction( - Player* player, - glm::ivec3 pos, - const Block* def, - BlockInteraction type + Player* player, glm::ivec3 pos, const Block* def, BlockInteraction type ) { for (const auto& callback : blockInteractionCallbacks) { callback(player, pos, def, type); } } -void BlocksController::listenBlockInteraction(const on_block_interaction& callback) { +void BlocksController::listenBlockInteraction( + const on_block_interaction& callback +) { blockInteractionCallbacks.push_back(callback); } diff --git a/src/logic/BlocksController.hpp b/src/logic/BlocksController.hpp index 0c904932..e2fcf0d4 100644 --- a/src/logic/BlocksController.hpp +++ b/src/logic/BlocksController.hpp @@ -1,14 +1,14 @@ #ifndef LOGIC_BLOCKS_CONTROLLER_HPP_ #define LOGIC_BLOCKS_CONTROLLER_HPP_ -#include "../typedefs.hpp" -#include "../maths/fastmaths.hpp" -#include "../voxels/voxel.hpp" -#include "../util/Clock.hpp" - #include #include +#include "../maths/fastmaths.hpp" +#include "../typedefs.hpp" +#include "../util/Clock.hpp" +#include "../voxels/voxel.hpp" + class Player; class Block; class Level; @@ -17,22 +17,17 @@ class Chunks; class Lighting; class ContentIndices; -enum class BlockInteraction { - step, - destruction, - placing -}; +enum class BlockInteraction { step, destruction, placing }; /// @brief Player argument is nullable -using on_block_interaction = std::function; +using on_block_interaction = std::function< + void(Player*, glm::ivec3, const Block*, BlockInteraction type)>; /// BlocksController manages block updates and data (inventories, metadata) class BlocksController { Level* level; - Chunks* chunks; - Lighting* lighting; + Chunks* chunks; + Lighting* lighting; util::Clock randTickClock; util::Clock blocksTickClock; util::Clock worldTickClock; @@ -46,10 +41,14 @@ public: void updateBlock(int x, int y, int z); void breakBlock(Player* player, const Block* def, int x, int y, int z); - void placeBlock(Player* player, const Block* def, blockstate state, int x, int y, int z); + void placeBlock( + Player* player, const Block* def, blockstate state, int x, int y, int z + ); void update(float delta); - void randomTick(const Chunk& chunk, int segments, const ContentIndices* indices); + void randomTick( + const Chunk& chunk, int segments, const ContentIndices* indices + ); void randomTick(int tickid, int parts); void onBlocksTick(int tickid, int parts); int64_t createBlockInventory(int x, int y, int z); @@ -57,14 +56,11 @@ public: void unbindInventory(int x, int y, int z); void onBlockInteraction( - Player* player, - glm::ivec3 pos, - const Block* def, - BlockInteraction type + Player* player, glm::ivec3 pos, const Block* def, BlockInteraction type ); /// @brief Add block interaction callback void listenBlockInteraction(const on_block_interaction& callback); }; -#endif // LOGIC_BLOCKS_CONTROLLER_HPP_ +#endif // LOGIC_BLOCKS_CONTROLLER_HPP_ diff --git a/src/logic/ChunksController.cpp b/src/logic/ChunksController.cpp index c8ba37fe..148b78ec 100644 --- a/src/logic/ChunksController.cpp +++ b/src/logic/ChunksController.cpp @@ -1,33 +1,36 @@ #include "ChunksController.hpp" +#include + +#include +#include + #include "../content/Content.hpp" +#include "../files/WorldFiles.hpp" +#include "../graphics/core/Mesh.hpp" +#include "../lighting/Lighting.hpp" +#include "../maths/voxmaths.hpp" +#include "../util/timeutil.hpp" #include "../voxels/Block.hpp" #include "../voxels/Chunk.hpp" #include "../voxels/Chunks.hpp" #include "../voxels/ChunksStorage.hpp" #include "../voxels/WorldGenerator.hpp" -#include "../world/WorldGenerators.hpp" -#include "../graphics/core/Mesh.hpp" -#include "../lighting/Lighting.hpp" -#include "../files/WorldFiles.hpp" #include "../world/Level.hpp" #include "../world/World.hpp" -#include "../maths/voxmaths.hpp" -#include "../util/timeutil.hpp" - -#include -#include -#include +#include "../world/WorldGenerators.hpp" const uint MAX_WORK_PER_FRAME = 128; const uint MIN_SURROUNDING = 9; -ChunksController::ChunksController(Level* level, uint padding) - : level(level), - chunks(level->chunks.get()), - lighting(level->lighting.get()), - padding(padding), - generator(WorldGenerators::createGenerator(level->getWorld()->getGenerator(), level->content)) { +ChunksController::ChunksController(Level* level, uint padding) + : level(level), + chunks(level->chunks.get()), + lighting(level->lighting.get()), + padding(padding), + generator(WorldGenerators::createGenerator( + level->getWorld()->getGenerator(), level->content + )) { } ChunksController::~ChunksController() = default; @@ -48,18 +51,18 @@ void ChunksController::update(int64_t maxDuration) { } } -bool ChunksController::loadVisible(){ +bool ChunksController::loadVisible() { const int w = chunks->w; const int d = chunks->d; int nearX = 0; int nearZ = 0; - int minDistance = ((w-padding*2)/2)*((w-padding*2)/2); - for (uint z = padding; z < d-padding; z++){ - for (uint x = padding; x < w-padding; x++){ + int minDistance = ((w - padding * 2) / 2) * ((w - padding * 2) / 2); + for (uint z = padding; z < d - padding; z++) { + for (uint x = padding; x < w - padding; x++) { int index = z * w + x; auto& chunk = chunks->chunks[index]; - if (chunk != nullptr){ + if (chunk != nullptr) { if (chunk->flags.loaded && !chunk->flags.lighted) { if (buildLights(chunk)) { return true; @@ -70,7 +73,7 @@ bool ChunksController::loadVisible(){ int lx = x - w / 2; int lz = z - d / 2; int distance = (lx * lx + lz * lz); - if (distance < minDistance){ + if (distance < minDistance) { minDistance = distance; nearX = x; nearZ = z; @@ -85,16 +88,15 @@ bool ChunksController::loadVisible(){ const int ox = chunks->ox; const int oz = chunks->oz; - createChunk(nearX+ox, nearZ+oz); + createChunk(nearX + ox, nearZ + oz); return true; } bool ChunksController::buildLights(const std::shared_ptr& chunk) { int surrounding = 0; - for (int oz = -1; oz <= 1; oz++){ - for (int ox = -1; ox <= 1; ox++){ - if (chunks->getChunk(chunk->x+ox, chunk->z+oz)) - surrounding++; + for (int oz = -1; oz <= 1; oz++) { + for (int ox = -1; ox <= 1; ox++) { + if (chunks->getChunk(chunk->x + ox, chunk->z + oz)) surrounding++; } } if (surrounding == MIN_SURROUNDING) { @@ -115,18 +117,13 @@ void ChunksController::createChunk(int x, int z) { auto& chunkFlags = chunk->flags; if (!chunkFlags.loaded) { - generator->generate( - chunk->voxels, x, z, - level->getWorld()->getSeed() - ); + generator->generate(chunk->voxels, x, z, level->getWorld()->getSeed()); chunkFlags.unsaved = true; } chunk->updateHeights(); if (!chunkFlags.loadedLights) { - Lighting::prebuildSkyLight( - chunk.get(), level->content->getIndices() - ); + Lighting::prebuildSkyLight(chunk.get(), level->content->getIndices()); } chunkFlags.loaded = true; chunkFlags.ready = true; diff --git a/src/logic/ChunksController.hpp b/src/logic/ChunksController.hpp index fe7f7fd5..b777c405 100644 --- a/src/logic/ChunksController.hpp +++ b/src/logic/ChunksController.hpp @@ -1,9 +1,10 @@ #ifndef VOXELS_CHUNKSCONTROLLER_HPP_ #define VOXELS_CHUNKSCONTROLLER_HPP_ -#include "../typedefs.hpp" #include +#include "../typedefs.hpp" + class Level; class Chunk; class Chunks; @@ -31,4 +32,4 @@ public: void update(int64_t maxDuration); }; -#endif // VOXELS_CHUNKSCONTROLLER_HPP_ +#endif // VOXELS_CHUNKSCONTROLLER_HPP_ diff --git a/src/logic/CommandsInterpreter.cpp b/src/logic/CommandsInterpreter.cpp index 85a082e7..e7dbbac6 100644 --- a/src/logic/CommandsInterpreter.cpp +++ b/src/logic/CommandsInterpreter.cpp @@ -1,15 +1,15 @@ #include "CommandsInterpreter.hpp" -#include "../coders/commons.hpp" -#include "../util/stringutil.hpp" - #include #include +#include "../coders/commons.hpp" +#include "../util/stringutil.hpp" + using namespace cmd; inline bool is_cmd_identifier_part(char c, bool allowColon) { - return is_identifier_part(c) || c == '.' || c == '$' || + return is_identifier_part(c) || c == '.' || c == '$' || (allowColon && c == ':'); } @@ -31,7 +31,7 @@ class CommandParser : BasicParser { while (hasNext() && is_cmd_identifier_part(source[pos], allowColon)) { pos++; } - return std::string(source.substr(start, pos-start)); + return std::string(source.substr(start, pos - start)); } std::unordered_map types { @@ -42,8 +42,8 @@ class CommandParser : BasicParser { {"enum", ArgType::enumvalue}, }; public: - CommandParser(std::string_view filename, std::string_view source) - : BasicParser(filename, source) { + CommandParser(std::string_view filename, std::string_view source) + : BasicParser(filename, source) { } ArgType parseType() { @@ -55,7 +55,7 @@ public: if (found != types.end()) { return found->second; } else { - throw error("unknown type "+util::quote(name)); + throw error("unknown type " + util::quote(name)); } } @@ -83,7 +83,7 @@ public: if (is_digit(c)) { return parseNumber(1); } - throw error("invalid character '"+std::string({c})+"'"); + throw error("invalid character '" + std::string({c}) + "'"); } std::string parseEnum() { @@ -92,10 +92,10 @@ public: if (peek() == ']') { throw error("empty enumeration is not allowed"); } - auto enumvalue = "|"+std::string(readUntil(']'))+"|"; + auto enumvalue = "|" + std::string(readUntil(']')) + "|"; size_t offset = enumvalue.find(' '); if (offset != std::string::npos) { - goBack(enumvalue.length()-offset); + goBack(enumvalue.length() - offset); throw error("use '|' as separator, not a space"); } nextChar(); @@ -156,30 +156,34 @@ public: } } return Command( - name, std::move(args), std::move(kwargs), - std::string(description), std::move(executor) + name, + std::move(args), + std::move(kwargs), + std::string(description), + std::move(executor) ); } inline parsing_error argumentError( - const std::string& argname, - const std::string& message + const std::string& argname, const std::string& message ) { - return error("argument "+util::quote(argname)+": "+message); + return error("argument " + util::quote(argname) + ": " + message); } inline parsing_error typeError( - const std::string& argname, - const std::string& expected, + const std::string& argname, + const std::string& expected, const dynamic::Value& value ) { return argumentError( - argname, expected+" expected, got "+dynamic::type_name(value) + argname, expected + " expected, got " + dynamic::type_name(value) ); } - template - inline bool typeCheck(Argument* arg, const dynamic::Value& value, const std::string& tname) { + template + inline bool typeCheck( + Argument* arg, const dynamic::Value& value, const std::string& tname + ) { if (!std::holds_alternative(value)) { if (arg->optional) { return false; @@ -198,7 +202,7 @@ public: } return true; } - } + } if (arg->optional) { return false; } else { @@ -211,9 +215,12 @@ public: case ArgType::enumvalue: { if (auto* string = std::get_if(&value)) { auto& enumname = arg->enumname; - if (enumname.find("|"+*string+"|") == std::string::npos) { - throw error("argument "+util::quote(arg->name)+ - ": invalid enumeration value"); + if (enumname.find("|" + *string + "|") == + std::string::npos) { + throw error( + "argument " + util::quote(arg->name) + + ": invalid enumeration value" + ); } } else { if (arg->optional) { @@ -245,7 +252,9 @@ public: return true; } - dynamic::Value fetchOrigin(CommandsInterpreter* interpreter, Argument* arg) { + dynamic::Value fetchOrigin( + CommandsInterpreter* interpreter, Argument* arg + ) { if (dynamic::is_numeric(arg->origin)) { return arg->origin; } else if (auto string = std::get_if(&arg->origin)) { @@ -255,9 +264,7 @@ public: } dynamic::Value applyRelative( - Argument* arg, - dynamic::Value value, - const dynamic::Value& origin + Argument* arg, dynamic::Value value, const dynamic::Value& origin ) { if (origin.index() == 0) { return value; @@ -266,14 +273,17 @@ public: if (arg->type == ArgType::number) { return dynamic::get_number(origin) + dynamic::get_number(value); } else { - return dynamic::get_integer(origin) + dynamic::get_integer(value); + return dynamic::get_integer(origin) + + dynamic::get_integer(value); } } catch (std::runtime_error& err) { throw argumentError(arg->name, err.what()); } } - dynamic::Value parseRelativeValue(CommandsInterpreter* interpreter, Argument* arg) { + dynamic::Value parseRelativeValue( + CommandsInterpreter* interpreter, Argument* arg + ) { if (arg->type != ArgType::number && arg->type != ArgType::integer) { throw error("'~' operator is only allowed for numeric arguments"); } @@ -290,17 +300,18 @@ public: } inline dynamic::Value performKeywordArg( - CommandsInterpreter* interpreter, Command* command, const std::string& key + CommandsInterpreter* interpreter, + Command* command, + const std::string& key ) { if (auto arg = command->getArgument(key)) { nextChar(); - auto value = peek() == '~' - ? parseRelativeValue(interpreter, arg) - : parseValue(); + auto value = peek() == '~' ? parseRelativeValue(interpreter, arg) + : parseValue(); typeCheck(arg, value); return value; } else { - throw error("unknown keyword "+util::quote(key)); + throw error("unknown keyword " + util::quote(key)); } } @@ -309,7 +320,7 @@ public: std::string name = parseIdentifier(true); auto command = repo->get(name); if (command == nullptr) { - throw error("unknown command "+util::quote(name)); + throw error("unknown command " + util::quote(name)); } auto args = dynamic::create_list(); auto kwargs = dynamic::create_map(); @@ -324,7 +335,7 @@ public: value = static_cast(0); nextChar(); } - + if (hasNext() && peekNoJump() != ' ') { value = parseValue(); if (auto string = std::get_if(&value)) { @@ -336,7 +347,9 @@ public: // keyword argument if (!relative && hasNext() && peek() == '=') { auto key = std::get(value); - kwargs->put(key, performKeywordArg(interpreter, command, key)); + kwargs->put( + key, performKeywordArg(interpreter, command, key) + ); } } @@ -364,14 +377,15 @@ public: } while (!typeCheck(arg, value)); if (relative) { - value = applyRelative(arg, value, fetchOrigin(interpreter, arg)); + value = + applyRelative(arg, value, fetchOrigin(interpreter, arg)); } args->put(value); } while (auto arg = command->getArgument(arg_index++)) { if (!arg->optional) { - throw error("missing argument "+util::quote(arg->name)); + throw error("missing argument " + util::quote(arg->name)); } else { if (auto string = std::get_if(&arg->def)) { if ((*string)[0] == '$') { @@ -386,13 +400,18 @@ public: } }; -Command Command::create(std::string_view scheme, std::string_view description, executor_func executor) { - return CommandParser("", scheme).parseScheme(std::move(executor), description); +Command Command::create( + std::string_view scheme, + std::string_view description, + executor_func executor +) { + return CommandParser("", scheme) + .parseScheme(std::move(executor), description); } void CommandsRepository::add( - std::string_view scheme, - std::string_view description, + std::string_view scheme, + std::string_view description, executor_func executor ) { Command command = Command::create(scheme, description, std::move(executor)); diff --git a/src/logic/CommandsInterpreter.hpp b/src/logic/CommandsInterpreter.hpp index f9295978..f0886de2 100644 --- a/src/logic/CommandsInterpreter.hpp +++ b/src/logic/CommandsInterpreter.hpp @@ -1,26 +1,30 @@ #ifndef LOGIC_COMMANDS_INTERPRETER_HPP_ #define LOGIC_COMMANDS_INTERPRETER_HPP_ +#include +#include +#include +#include + #include "../data/dynamic.hpp" -#include -#include -#include -#include - namespace cmd { - enum class ArgType { - number, integer, enumvalue, selector, string - }; + enum class ArgType { number, integer, enumvalue, selector, string }; inline std::string argtype_name(ArgType type) { switch (type) { - case ArgType::number: return "number"; - case ArgType::integer: return "integer"; - case ArgType::enumvalue: return "enumeration"; - case ArgType::selector: return "selector"; - case ArgType::string: return "string"; - default: return ""; + case ArgType::number: + return "number"; + case ArgType::integer: + return "integer"; + case ArgType::enumvalue: + return "enumeration"; + case ArgType::selector: + return "selector"; + case ArgType::string: + return "string"; + default: + return ""; } } @@ -38,14 +42,12 @@ namespace cmd { struct Prompt { Command* command; - dynamic::List_sptr args; // positional arguments list - dynamic::Map_sptr kwargs; // keyword arguments table + dynamic::List_sptr args; // positional arguments list + dynamic::Map_sptr kwargs; // keyword arguments table }; using executor_func = std::function; class Command { @@ -63,15 +65,16 @@ namespace cmd { std::unordered_map kwargs, std::string description, executor_func executor - ) : name(name), - args(std::move(args)), - kwargs(std::move(kwargs)), - description(description), - executor(executor) {} - + ) + : name(name), + args(std::move(args)), + kwargs(std::move(kwargs)), + description(description), + executor(executor) { + } + Argument* getArgument(size_t index) { - if (index >= args.size()) - return nullptr; + if (index >= args.size()) return nullptr; return &args[index]; } @@ -83,7 +86,9 @@ namespace cmd { return &found->second; } - dynamic::Value execute(CommandsInterpreter* interpreter, const Prompt& prompt) { + dynamic::Value execute( + CommandsInterpreter* interpreter, const Prompt& prompt + ) { return executor(interpreter, prompt.args, prompt.kwargs); } @@ -104,9 +109,7 @@ namespace cmd { } static Command create( - std::string_view scheme, - std::string_view description, - executor_func + std::string_view scheme, std::string_view description, executor_func ); }; @@ -114,9 +117,7 @@ namespace cmd { std::unordered_map commands; public: void add( - std::string_view scheme, - std::string_view description, - executor_func + std::string_view scheme, std::string_view description, executor_func ); Command* get(const std::string& name); @@ -129,12 +130,15 @@ namespace cmd { std::unique_ptr repository; std::unordered_map variables; public: - CommandsInterpreter() : repository(std::make_unique()) {} + CommandsInterpreter() + : repository(std::make_unique()) { + } CommandsInterpreter(const CommandsInterpreter&) = delete; CommandsInterpreter(std::unique_ptr repository) - : repository(std::move(repository)){} + : repository(std::move(repository)) { + } Prompt parse(std::string_view text); @@ -156,4 +160,4 @@ namespace cmd { }; } -#endif // LOGIC_COMMANDS_INTERPRETER_HPP_ +#endif // LOGIC_COMMANDS_INTERPRETER_HPP_ diff --git a/src/logic/EngineController.cpp b/src/logic/EngineController.cpp index 2ea9296c..e7128e27 100644 --- a/src/logic/EngineController.cpp +++ b/src/logic/EngineController.cpp @@ -1,27 +1,27 @@ #include "EngineController.hpp" +#include +#include +#include + #include "../coders/commons.hpp" #include "../content/ContentLUT.hpp" #include "../debug/Logger.hpp" #include "../engine.hpp" -#include "../files/WorldFiles.hpp" #include "../files/WorldConverter.hpp" +#include "../files/WorldFiles.hpp" #include "../frontend/locale.hpp" -#include "../frontend/screens/MenuScreen.hpp" -#include "../frontend/screens/LevelScreen.hpp" #include "../frontend/menu.hpp" +#include "../frontend/screens/LevelScreen.hpp" +#include "../frontend/screens/MenuScreen.hpp" #include "../graphics/ui/elements/Menu.hpp" #include "../graphics/ui/gui_util.hpp" #include "../interfaces/Task.hpp" #include "../util/stringutil.hpp" -#include "../world/World.hpp" #include "../world/Level.hpp" +#include "../world/World.hpp" #include "LevelController.hpp" -#include -#include -#include - namespace fs = std::filesystem; static debug::Logger logger("engine-control"); @@ -31,46 +31,62 @@ EngineController::EngineController(Engine* engine) : engine(engine) { void EngineController::deleteWorld(const std::string& name) { fs::path folder = engine->getPaths()->getWorldFolder(name); - guiutil::confirm(engine->getGUI(), langs::get(L"delete-confirm", L"world")+ - L" ("+util::str2wstr_utf8(folder.u8string())+L")", [=]() { - logger.info() << "deleting " << folder.u8string(); - fs::remove_all(folder); - }); + guiutil::confirm( + engine->getGUI(), + langs::get(L"delete-confirm", L"world") + L" (" + + util::str2wstr_utf8(folder.u8string()) + L")", + [=]() { + logger.info() << "deleting " << folder.u8string(); + fs::remove_all(folder); + } + ); } std::shared_ptr create_converter( Engine* engine, const fs::path& folder, - const Content* content, + const Content* content, const std::shared_ptr& lut, - const runnable& postRunnable) -{ - return WorldConverter::startTask(folder, content, lut, [=](){ - auto menu = engine->getGUI()->getMenu(); - menu->reset(); - menu->setPage("main", false); - engine->getGUI()->postRunnable([=]() { - postRunnable(); - }); - }, true); + const runnable& postRunnable +) { + return WorldConverter::startTask( + folder, + content, + lut, + [=]() { + auto menu = engine->getGUI()->getMenu(); + menu->reset(); + menu->setPage("main", false); + engine->getGUI()->postRunnable([=]() { postRunnable(); }); + }, + true + ); } void show_convert_request( - Engine* engine, - const Content* content, + Engine* engine, + const Content* content, const std::shared_ptr& lut, const fs::path& folder, const runnable& postRunnable ) { - guiutil::confirm(engine->getGUI(), langs::get(L"world.convert-request"), [=]() { - auto converter = create_converter(engine, folder, content, lut, postRunnable); - menus::show_process_panel(engine, converter, L"Converting world..."); - }, L"", langs::get(L"Cancel")); + guiutil::confirm( + engine->getGUI(), + langs::get(L"world.convert-request"), + [=]() { + auto converter = + create_converter(engine, folder, content, lut, postRunnable); + menus::show_process_panel( + engine, converter, L"Converting world..." + ); + }, + L"", + langs::get(L"Cancel") + ); } static void show_content_missing( - Engine* engine, - const std::shared_ptr& lut + Engine* engine, const std::shared_ptr& lut ) { using namespace dynamic; auto root = create_map(); @@ -97,11 +113,13 @@ static void loadWorld(Engine* engine, const fs::path& folder) { auto& settings = engine->getSettings(); auto level = World::load(folder, settings, content, packs); - engine->setScreen(std::make_shared(engine, std::move(level))); + engine->setScreen( + std::make_shared(engine, std::move(level)) + ); } catch (const world_load_error& error) { guiutil::alert( - engine->getGUI(), langs::get(L"Error")+L": "+ - util::str2wstr_utf8(error.what()) + engine->getGUI(), + langs::get(L"Error") + L": " + util::str2wstr_utf8(error.what()) ); return; } @@ -109,25 +127,33 @@ static void loadWorld(Engine* engine, const fs::path& folder) { void EngineController::openWorld(const std::string& name, bool confirmConvert) { auto paths = engine->getPaths(); - auto folder = paths->getWorldsFolder()/fs::u8path(name); + auto folder = paths->getWorldsFolder() / fs::u8path(name); if (!loadWorldContent(engine, folder)) { return; } auto* content = engine->getContent(); - std::shared_ptr lut (World::checkIndices(folder, content)); + std::shared_ptr lut(World::checkIndices(folder, content)); if (lut) { if (lut->hasMissingContent()) { engine->setScreen(std::make_shared(engine)); show_content_missing(engine, lut); } else { if (confirmConvert) { - menus::show_process_panel(engine, create_converter(engine, folder, content, lut, [=]() { - openWorld(name, false); - }), L"Converting world..."); + menus::show_process_panel( + engine, + create_converter( + engine, + folder, + content, + lut, + [=]() { openWorld(name, false); } + ), + L"Converting world..." + ); } else { - show_convert_request(engine, content, lut, folder, [=](){ + show_convert_request(engine, content, lut, folder, [=]() { openWorld(name, false); }); } @@ -152,24 +178,27 @@ inline uint64_t str2seed(const std::string& seedstr) { } void EngineController::createWorld( - const std::string& name, + const std::string& name, const std::string& seedstr, const std::string& generatorID ) { uint64_t seed = str2seed(seedstr); EnginePaths* paths = engine->getPaths(); - auto folder = paths->getWorldsFolder()/fs::u8path(name); + auto folder = paths->getWorldsFolder() / fs::u8path(name); if (!menus::call(engine, [this, paths, folder]() { - engine->loadContent(); - paths->setWorldFolder(folder); - })) { + engine->loadContent(); + paths->setWorldFolder(folder); + })) { return; } auto level = World::create( - name, generatorID, folder, seed, - engine->getSettings(), + name, + generatorID, + folder, + seed, + engine->getSettings(), engine->getContent(), engine->getContentPacks() ); @@ -208,7 +237,8 @@ void EngineController::reconfigPacks( try { auto manager = engine->createPacksManager(fs::path("")); manager.scan(); - std::vector names = PacksManager::getNames(engine->getContentPacks()); + std::vector names = + PacksManager::getNames(engine->getContentPacks()); for (const auto& id : packsToAdd) { names.push_back(id); } @@ -219,7 +249,9 @@ void EngineController::reconfigPacks( names = manager.assembly(names); engine->getContentPacks() = manager.getAll(names); } catch (const contentpack_error& err) { - throw std::runtime_error(std::string(err.what())+" ["+err.getPackId()+"]"); + throw std::runtime_error( + std::string(err.what()) + " [" + err.getPackId() + "]" + ); } } else { auto world = controller->getLevel()->getWorld(); @@ -244,10 +276,10 @@ void EngineController::reconfigPacks( if (hasIndices) { guiutil::confirm( - engine->getGUI(), - langs::get(L"remove-confirm", L"pack")+ - L" ("+util::str2wstr_utf8(ss.str())+L")", - [=]() {removeFunc();} + engine->getGUI(), + langs::get(L"remove-confirm", L"pack") + L" (" + + util::str2wstr_utf8(ss.str()) + L")", + [=]() { removeFunc(); } ); } else { removeFunc(); diff --git a/src/logic/EngineController.hpp b/src/logic/EngineController.hpp index 1a5f101a..c548b94f 100644 --- a/src/logic/EngineController.hpp +++ b/src/logic/EngineController.hpp @@ -29,7 +29,7 @@ public: ); void createWorld( - const std::string& name, + const std::string& name, const std::string& seedstr, const std::string& generatorID ); @@ -37,4 +37,4 @@ public: void reopenWorld(World* world); }; -#endif // LOGIC_ENGINE_CONTROLLER_HPP_ +#endif // LOGIC_ENGINE_CONTROLLER_HPP_ diff --git a/src/logic/LevelController.cpp b/src/logic/LevelController.cpp index 053eb15e..c86d6c75 100644 --- a/src/logic/LevelController.cpp +++ b/src/logic/LevelController.cpp @@ -1,36 +1,45 @@ #include "LevelController.hpp" -#include "../settings.hpp" -#include "../files/WorldFiles.hpp" -#include "../debug/Logger.hpp" -#include "../world/Level.hpp" -#include "../world/World.hpp" -#include "../physics/Hitbox.hpp" -#include "../objects/Entities.hpp" - -#include "scripting/scripting.hpp" -#include "../interfaces/Object.hpp" - #include +#include "../debug/Logger.hpp" +#include "../files/WorldFiles.hpp" +#include "../interfaces/Object.hpp" +#include "../objects/Entities.hpp" +#include "../physics/Hitbox.hpp" +#include "../settings.hpp" +#include "../world/Level.hpp" +#include "../world/World.hpp" +#include "scripting/scripting.hpp" + static debug::Logger logger("level-control"); -LevelController::LevelController(EngineSettings& settings, std::unique_ptr level) - : settings(settings), level(std::move(level)), - blocks(std::make_unique(this->level.get(), settings.chunks.padding.get())), - chunks(std::make_unique(this->level.get(), settings.chunks.padding.get())), - player(std::make_unique(this->level.get(), settings, blocks.get())) { - +LevelController::LevelController( + EngineSettings& settings, std::unique_ptr level +) + : settings(settings), + level(std::move(level)), + blocks(std::make_unique( + this->level.get(), settings.chunks.padding.get() + )), + chunks(std::make_unique( + this->level.get(), settings.chunks.padding.get() + )), + player(std::make_unique( + this->level.get(), settings, blocks.get() + )) { scripting::on_world_load(this); } void LevelController::update(float delta, bool input, bool pause) { glm::vec3 position = player->getPlayer()->getPosition(); - level->loadMatrix(position.x, position.z, - settings.chunks.loadDistance.get() + - settings.chunks.padding.get() * 2); + level->loadMatrix( + position.x, + position.z, + settings.chunks.loadDistance.get() + settings.chunks.padding.get() * 2 + ); chunks->update(settings.chunks.loadSpeed.get()); - + if (!pause) { // update all objects that needed for (const auto& obj : level->objects) { @@ -50,8 +59,10 @@ void LevelController::update(float delta, bool input, bool pause) { auto& objects = level->objects; objects.erase( std::remove_if( - objects.begin(), objects.end(), - [](auto obj) { return obj == nullptr; }), + objects.begin(), + objects.end(), + [](auto obj) { return obj == nullptr; } + ), objects.end() ); } diff --git a/src/logic/LevelController.hpp b/src/logic/LevelController.hpp index 3530df68..6251e58d 100644 --- a/src/logic/LevelController.hpp +++ b/src/logic/LevelController.hpp @@ -3,9 +3,9 @@ #include -#include "PlayerController.hpp" #include "BlocksController.hpp" #include "ChunksController.hpp" +#include "PlayerController.hpp" class Level; class Player; @@ -25,14 +25,10 @@ public: /// @param delta time elapsed since the last update /// @param input is user input allowed to be handled /// @param pause is world and player simulation paused - void update( - float delta, - bool input, - bool pause - ); + void update(float delta, bool input, bool pause); void saveWorld(); - + void onWorldQuit(); Level* getLevel(); @@ -42,4 +38,4 @@ public: PlayerController* getPlayerController(); }; -#endif // LOGIC_LEVEL_CONTROLLER_HPP_ +#endif // LOGIC_LEVEL_CONTROLLER_HPP_ diff --git a/src/logic/PlayerController.cpp b/src/logic/PlayerController.cpp index dec48579..3c710cef 100644 --- a/src/logic/PlayerController.cpp +++ b/src/logic/PlayerController.cpp @@ -1,31 +1,30 @@ #define _USE_MATH_DEFINES -#include - #include "PlayerController.hpp" -#include "BlocksController.hpp" -#include "scripting/scripting.hpp" - -#include "../objects/Player.hpp" -#include "../objects/Entities.hpp" -#include "../physics/PhysicsSolver.hpp" -#include "../physics/Hitbox.hpp" -#include "../lighting/Lighting.hpp" -#include "../world/Level.hpp" -#include "../content/Content.hpp" -#include "../voxels/Block.hpp" -#include "../voxels/voxel.hpp" -#include "../voxels/Chunks.hpp" -#include "../window/Camera.hpp" -#include "../window/Window.hpp" -#include "../window/Events.hpp" -#include "../window/input.hpp" -#include "../items/ItemDef.hpp" -#include "../items/ItemStack.hpp" -#include "../items/Inventory.hpp" -#include "../core_defs.hpp" -#include "../settings.hpp" #include +#include + +#include "../content/Content.hpp" +#include "../core_defs.hpp" +#include "../items/Inventory.hpp" +#include "../items/ItemDef.hpp" +#include "../items/ItemStack.hpp" +#include "../lighting/Lighting.hpp" +#include "../objects/Entities.hpp" +#include "../objects/Player.hpp" +#include "../physics/Hitbox.hpp" +#include "../physics/PhysicsSolver.hpp" +#include "../settings.hpp" +#include "../voxels/Block.hpp" +#include "../voxels/Chunks.hpp" +#include "../voxels/voxel.hpp" +#include "../window/Camera.hpp" +#include "../window/Events.hpp" +#include "../window/Window.hpp" +#include "../window/input.hpp" +#include "../world/Level.hpp" +#include "BlocksController.hpp" +#include "scripting/scripting.hpp" const float STEPS_SPEED = 2.2f; const float CAM_SHAKE_OFFSET = 0.0075f; @@ -38,11 +37,13 @@ const float RUN_ZOOM = 1.1f; const float C_ZOOM = 0.1f; const float CROUCH_SHIFT_Y = -0.2f; -CameraControl::CameraControl(const std::shared_ptr& player, const CameraSettings& settings) - : player(player), - camera(player->camera), - settings(settings), - offset(0.0f, 0.7f, 0.0f) { +CameraControl::CameraControl( + const std::shared_ptr& player, const CameraSettings& settings +) + : player(player), + camera(player->camera), + settings(settings), + offset(0.0f, 0.7f, 0.0f) { } void CameraControl::refresh() { @@ -52,39 +53,41 @@ void CameraControl::refresh() { void CameraControl::updateMouse(PlayerInput& input) { glm::vec3& cam = player->cam; - float sensitivity = (input.zoom - ? settings.sensitivity.get() / 4.f - : settings.sensitivity.get()); + float sensitivity = + (input.zoom ? settings.sensitivity.get() / 4.f + : settings.sensitivity.get()); auto d = glm::degrees(Events::delta / (float)Window::height * sensitivity); cam.x -= d.x; cam.y -= d.y; - + if (cam.y < -89.9f) { cam.y = -89.9f; - } - else if (cam.y > 89.9f) { + } else if (cam.y > 89.9f) { cam.y = 89.9f; } if (cam.x > 180.f) { cam.x -= 360.f; - } - else if (cam.x < -180.f) { + } else if (cam.x < -180.f) { cam.x += 360.f; } camera->rotation = glm::mat4(1.0f); - camera->rotate(glm::radians(cam.y), glm::radians(cam.x), glm::radians(cam.z)); + camera->rotate( + glm::radians(cam.y), glm::radians(cam.x), glm::radians(cam.z) + ); } -glm::vec3 CameraControl::updateCameraShaking(const Hitbox& hitbox, float delta) { +glm::vec3 CameraControl::updateCameraShaking( + const Hitbox& hitbox, float delta +) { glm::vec3 offset {}; const float k = CAM_SHAKE_DELTA_K; const float ov = CAM_SHAKE_OFFSET_Y; const glm::vec3& vel = hitbox.velocity; interpVel = interpVel * (1.0f - delta * 5) + vel * delta * 0.1f; - if (hitbox.grounded && interpVel.y < 0.0f){ + if (hitbox.grounded && interpVel.y < 0.0f) { interpVel.y *= -30.0f; } shake = shake * (1.0f - delta * k); @@ -95,7 +98,7 @@ glm::vec3 CameraControl::updateCameraShaking(const Hitbox& hitbox, float delta) shake += f * delta * k; oh *= glm::sqrt(f); } - + offset += camera->right * glm::sin(shakeTimer) * oh * shake; offset += camera->up * glm::abs(glm::cos(shakeTimer)) * ov * shake; if (settings.inertia.get()) { @@ -104,20 +107,20 @@ glm::vec3 CameraControl::updateCameraShaking(const Hitbox& hitbox, float delta) return offset; } -void CameraControl::updateFovEffects(const Hitbox& hitbox, - PlayerInput input, float delta) { +void CameraControl::updateFovEffects( + const Hitbox& hitbox, PlayerInput input, float delta +) { bool crouch = input.shift && hitbox.grounded && !input.sprint; float dt = fmin(1.0f, delta * ZOOM_SPEED); float zoomValue = 1.0f; - if (crouch){ + if (crouch) { offset += glm::vec3(0.f, CROUCH_SHIFT_Y, 0.f); zoomValue = CROUCH_ZOOM; - } else if (input.sprint){ + } else if (input.sprint) { zoomValue = RUN_ZOOM; } - if (input.zoom) - zoomValue *= C_ZOOM; + if (input.zoom) zoomValue *= C_ZOOM; camera->zoom = zoomValue * dt + camera->zoom * (1.0f - dt); } @@ -125,17 +128,14 @@ void CameraControl::updateFovEffects(const Hitbox& hitbox, // more extensible but uglier void CameraControl::switchCamera() { const std::vector> playerCameras { - camera, player->tpCamera, player->spCamera - }; + camera, player->tpCamera, player->spCamera}; auto index = std::distance( playerCameras.begin(), std::find_if( - playerCameras.begin(), - playerCameras.end(), - [=](auto ptr) { - return ptr.get() == player->currentCamera.get(); - } + playerCameras.begin(), + playerCameras.end(), + [=](auto ptr) { return ptr.get() == player->currentCamera.get(); } ) ); if (static_cast(index) != playerCameras.size()) { @@ -150,11 +150,11 @@ void CameraControl::update(PlayerInput input, float delta, Chunks* chunks) { offset = glm::vec3(0.0f, 0.0f, 0.0f); if (auto hitbox = player->getHitbox()) { - offset.y += hitbox->halfsize.y * (0.7f/0.9f); + offset.y += hitbox->halfsize.y * (0.7f / 0.9f); if (settings.shaking.get() && !input.cheat) { offset += updateCameraShaking(*hitbox, delta); } - if (settings.fovEffects.get()){ + if (settings.fovEffects.get()) { updateFovEffects(*hitbox, input, delta); } } @@ -168,34 +168,34 @@ void CameraControl::update(PlayerInput input, float delta, Chunks* chunks) { refresh(); if (player->currentCamera == spCamera) { - spCamera->position = chunks->rayCastToObstacle( - camera->position, camera->front, 3.0f) - 0.4f * camera->front; + spCamera->position = + chunks->rayCastToObstacle(camera->position, camera->front, 3.0f) - + 0.4f * camera->front; spCamera->dir = -camera->dir; spCamera->front = -camera->front; - } - else if (player->currentCamera == tpCamera) { - tpCamera->position = chunks->rayCastToObstacle( - camera->position, -camera->front, 3.0f) + 0.4f * camera->front; + } else if (player->currentCamera == tpCamera) { + tpCamera->position = + chunks->rayCastToObstacle(camera->position, -camera->front, 3.0f) + + 0.4f * camera->front; tpCamera->dir = camera->dir; tpCamera->front = camera->front; } - if (player->currentCamera == spCamera || - player->currentCamera == tpCamera || - player->currentCamera == camera) { + if (player->currentCamera == spCamera || + player->currentCamera == tpCamera || player->currentCamera == camera) { player->currentCamera->setFov(glm::radians(settings.fov.get())); } } PlayerController::PlayerController( - Level* level, + Level* level, const EngineSettings& settings, BlocksController* blocksController -) : level(level), - player(level->getObject(0)), - camControl(player, settings.camera), - blocksController(blocksController) -{} - +) + : level(level), + player(level->getObject(0)), + camControl(player, settings.camera), + blocksController(blocksController) { +} void PlayerController::onFootstep(const Hitbox& hitbox) { auto pos = hitbox.position; @@ -203,17 +203,17 @@ void PlayerController::onFootstep(const Hitbox& hitbox) { for (int offsetZ = -1; offsetZ <= 1; offsetZ++) { for (int offsetX = -1; offsetX <= 1; offsetX++) { - int x = std::floor(pos.x+half.x*offsetX); - int y = std::floor(pos.y-half.y*1.1f); - int z = std::floor(pos.z+half.z*offsetZ); + int x = std::floor(pos.x + half.x * offsetX); + int y = std::floor(pos.y - half.y * 1.1f); + int z = std::floor(pos.z + half.z * offsetZ); auto vox = level->chunks->get(x, y, z); if (vox) { auto def = level->content->getIndices()->blocks.get(vox->id); - if (!def->obstacle) - continue; + if (!def->obstacle) continue; blocksController->onBlockInteraction( player.get(), - glm::ivec3(x, y, z), def, + glm::ivec3(x, y, z), + def, BlockInteraction::step ); return; @@ -298,23 +298,30 @@ void PlayerController::updatePlayer(float delta) { player->updateInput(input, delta); } -static int determine_rotation(Block* def, const glm::ivec3& norm, glm::vec3& camDir) { - if (def && def->rotatable){ +static int determine_rotation( + Block* def, const glm::ivec3& norm, glm::vec3& camDir +) { + if (def && def->rotatable) { const std::string& name = def->rotations.name; if (name == "pipe") { - if (norm.x < 0.0f) return BLOCK_DIR_WEST; - else if (norm.x > 0.0f) return BLOCK_DIR_EAST; - else if (norm.y > 0.0f) return BLOCK_DIR_UP; - else if (norm.y < 0.0f) return BLOCK_DIR_DOWN; - else if (norm.z > 0.0f) return BLOCK_DIR_NORTH; - else if (norm.z < 0.0f) return BLOCK_DIR_SOUTH; - } - else if (name == "pane") { - if (abs(camDir.x) > abs(camDir.z)){ + if (norm.x < 0.0f) + return BLOCK_DIR_WEST; + else if (norm.x > 0.0f) + return BLOCK_DIR_EAST; + else if (norm.y > 0.0f) + return BLOCK_DIR_UP; + else if (norm.y < 0.0f) + return BLOCK_DIR_DOWN; + else if (norm.z > 0.0f) + return BLOCK_DIR_NORTH; + else if (norm.z < 0.0f) + return BLOCK_DIR_SOUTH; + } else if (name == "pane") { + if (abs(camDir.x) > abs(camDir.z)) { if (camDir.x > 0.0f) return BLOCK_DIR_EAST; if (camDir.x < 0.0f) return BLOCK_DIR_WEST; } - if (abs(camDir.x) < abs(camDir.z)){ + if (abs(camDir.x) < abs(camDir.z)) { if (camDir.z > 0.0f) return BLOCK_DIR_SOUTH; if (camDir.z < 0.0f) return BLOCK_DIR_NORTH; } @@ -323,9 +330,10 @@ static int determine_rotation(Block* def, const glm::ivec3& norm, glm::vec3& cam return 0; } -static void pick_block(ContentIndices* indices, Chunks* chunks, Player* player, - int x, int y, int z) { - auto block = indices->blocks.get(chunks->get(x,y,z)->id); +static void pick_block( + ContentIndices* indices, Chunks* chunks, Player* player, int x, int y, int z +) { + auto block = indices->blocks.get(chunks->get(x, y, z)->id); itemid_t id = block->rt.pickingItem; auto inventory = player->getInventory(); size_t slotid = inventory->findSlotByItem(id, 0, 10); @@ -350,10 +358,7 @@ voxel* PlayerController::updateSelection(float maxDistance) { glm::ivec3 iend; glm::ivec3 norm; voxel* vox = chunks->rayCast( - camera->position, - camera->front, - maxDistance, - end, norm, iend + camera->position, camera->front, maxDistance, end, norm, iend ); if (vox) { maxDistance = glm::distance(camera->position, end); @@ -362,9 +367,11 @@ voxel* PlayerController::updateSelection(float maxDistance) { selection.entity = ENTITY_NONE; selection.actualPosition = iend; if (auto result = level->entities->rayCast( - camera->position, camera->front, maxDistance, player->getEntity())) { + camera->position, camera->front, maxDistance, player->getEntity() + )) { selection.entity = result->entity; - selection.hitPosition = camera->position + camera->front * result->distance; + selection.hitPosition = + camera->position + camera->front * result->distance; selection.position = selection.hitPosition; selection.actualPosition = selection.position; selection.normal = result->normal; @@ -413,19 +420,21 @@ void PlayerController::processRightClick(Block* def, Block* target) { state.rotation = determine_rotation(def, selection.normal, camera->dir); if (!input.shift && target->rt.funcsset.oninteract) { - if (scripting::on_block_interact(player.get(), target, selection.position)) { + if (scripting::on_block_interact( + player.get(), target, selection.position + )) { return; } } auto coord = selection.actualPosition; - if (!target->replaceable){ + if (!target->replaceable) { coord += selection.normal; } else if (def->rotations.name == BlockRotProfile::PIPE_NAME) { state.rotation = BLOCK_DIR_UP; } blockid_t chosenBlock = def->rt.id; - AABB blockAABB(coord, coord+1); + AABB blockAABB(coord, coord + 1); bool blocked = level->entities->hasBlockingInside(blockAABB); if (def->obstacle && blocked) { @@ -440,17 +449,22 @@ void PlayerController::processRightClick(Block* def, Block* target) { } if (def->grounded) { const auto& vec = get_ground_direction(def, state.rotation); - if (!chunks->isSolidBlock(coord.x+vec.x, coord.y+vec.y, coord.z+vec.z)) { + if (!chunks->isSolidBlock( + coord.x + vec.x, coord.y + vec.y, coord.z + vec.z + )) { return; } } if (chosenBlock != vox->id && chosenBlock) { blocksController->placeBlock( - player.get(), def, state, coord.x, coord.y, coord.z); + player.get(), def, state, coord.x, coord.y, coord.z + ); } } -void PlayerController::updateEntityInteraction(entityid_t eid, bool lclick, bool rclick) { +void PlayerController::updateEntityInteraction( + entityid_t eid, bool lclick, bool rclick +) { auto entityOpt = level->entities->get(eid); if (!entityOpt.has_value()) { return; @@ -470,10 +484,12 @@ void PlayerController::updateInteraction() { const auto& selection = player->selection; bool xkey = Events::pressed(keycode::X); - bool lclick = Events::jactive(BIND_PLAYER_ATTACK) || (xkey && Events::active(BIND_PLAYER_ATTACK)); - bool rclick = Events::jactive(BIND_PLAYER_BUILD) || (xkey && Events::active(BIND_PLAYER_BUILD)); + bool lclick = Events::jactive(BIND_PLAYER_ATTACK) || + (xkey && Events::active(BIND_PLAYER_ATTACK)); + bool rclick = Events::jactive(BIND_PLAYER_BUILD) || + (xkey && Events::active(BIND_PLAYER_BUILD)); float maxDistance = xkey ? 200.0f : 10.0f; - + auto inventory = player->getInventory(); const ItemStack& stack = inventory->getSlot(player->getChosenSlot()); ItemDef* item = indices->items.get(stack.getItemId()); @@ -488,16 +504,20 @@ void PlayerController::updateInteraction() { } return; } - + auto iend = selection.position; if (lclick && !input.shift && item->rt.funcsset.on_block_break_by) { - if (scripting::on_item_break_block(player.get(), item, iend.x, iend.y, iend.z)) { + if (scripting::on_item_break_block( + player.get(), item, iend.x, iend.y, iend.z + )) { return; } } auto target = indices->blocks.get(vox->id); - if (lclick && target->breakable){ - blocksController->breakBlock(player.get(), target, iend.x, iend.y, iend.z); + if (lclick && target->breakable) { + blocksController->breakBlock( + player.get(), target, iend.x, iend.y, iend.z + ); } if (rclick && !input.shift) { bool preventDefault = false; diff --git a/src/logic/PlayerController.hpp b/src/logic/PlayerController.hpp index c90d1408..5df66dc3 100644 --- a/src/logic/PlayerController.hpp +++ b/src/logic/PlayerController.hpp @@ -1,11 +1,11 @@ #ifndef PLAYER_CONTROL_HPP_ #define PLAYER_CONTROL_HPP_ -#include "../objects/Player.hpp" - +#include #include #include -#include + +#include "../objects/Player.hpp" class Camera; class Level; @@ -32,14 +32,14 @@ class CameraControl { /// @brief Update field-of-view effects /// @param input player inputs /// @param delta delta time - void updateFovEffects(const Hitbox& hitbox, PlayerInput input, - float delta); + void updateFovEffects(const Hitbox& hitbox, PlayerInput input, float delta); /// @brief Switch active player camera void switchCamera(); public: - CameraControl(const std::shared_ptr& player, - const CameraSettings& settings); + CameraControl( + const std::shared_ptr& player, const CameraSettings& settings + ); void updateMouse(PlayerInput& input); void update(PlayerInput input, float delta, Chunks* chunks); void refresh(); @@ -66,7 +66,7 @@ class PlayerController { voxel* updateSelection(float maxDistance); public: PlayerController( - Level* level, + Level* level, const EngineSettings& settings, BlocksController* blocksController ); diff --git a/src/logic/scripting/lua/api_lua.hpp b/src/logic/scripting/lua/api_lua.hpp index 50587e2c..3ef61650 100644 --- a/src/logic/scripting/lua/api_lua.hpp +++ b/src/logic/scripting/lua/api_lua.hpp @@ -1,12 +1,12 @@ #ifndef LOGIC_SCRIPTING_API_LUA_HPP_ #define LOGIC_SCRIPTING_API_LUA_HPP_ +#include +#include + #include "lua_util.hpp" -#include -#include - -/// Definitions can be found in local .cpp files +/// Definitions can be found in local .cpp files /// having same names as declarations /// l_ prefix means that function is lua_CFunction: @@ -15,34 +15,34 @@ /// int l_function_name(lua::State* L); // Libraries -extern const luaL_Reg audiolib []; -extern const luaL_Reg blocklib []; -extern const luaL_Reg cameralib []; -extern const luaL_Reg consolelib []; -extern const luaL_Reg corelib []; -extern const luaL_Reg entitylib []; -extern const luaL_Reg filelib []; -extern const luaL_Reg guilib []; -extern const luaL_Reg hudlib []; -extern const luaL_Reg inputlib []; -extern const luaL_Reg inventorylib []; -extern const luaL_Reg itemlib []; -extern const luaL_Reg jsonlib []; -extern const luaL_Reg mat4lib []; -extern const luaL_Reg packlib []; -extern const luaL_Reg playerlib []; -extern const luaL_Reg quatlib []; // quat.cpp -extern const luaL_Reg timelib []; -extern const luaL_Reg tomllib []; -extern const luaL_Reg vec2lib []; // vecn.cpp -extern const luaL_Reg vec3lib []; // vecn.cpp -extern const luaL_Reg vec4lib []; // vecn.cpp -extern const luaL_Reg worldlib []; +extern const luaL_Reg audiolib[]; +extern const luaL_Reg blocklib[]; +extern const luaL_Reg cameralib[]; +extern const luaL_Reg consolelib[]; +extern const luaL_Reg corelib[]; +extern const luaL_Reg entitylib[]; +extern const luaL_Reg filelib[]; +extern const luaL_Reg guilib[]; +extern const luaL_Reg hudlib[]; +extern const luaL_Reg inputlib[]; +extern const luaL_Reg inventorylib[]; +extern const luaL_Reg itemlib[]; +extern const luaL_Reg jsonlib[]; +extern const luaL_Reg mat4lib[]; +extern const luaL_Reg packlib[]; +extern const luaL_Reg playerlib[]; +extern const luaL_Reg quatlib[]; // quat.cpp +extern const luaL_Reg timelib[]; +extern const luaL_Reg tomllib[]; +extern const luaL_Reg vec2lib[]; // vecn.cpp +extern const luaL_Reg vec3lib[]; // vecn.cpp +extern const luaL_Reg vec4lib[]; // vecn.cpp +extern const luaL_Reg worldlib[]; // Components -extern const luaL_Reg skeletonlib []; -extern const luaL_Reg rigidbodylib []; -extern const luaL_Reg transformlib []; +extern const luaL_Reg skeletonlib[]; +extern const luaL_Reg rigidbodylib[]; +extern const luaL_Reg transformlib[]; // Lua Overrides extern int l_print(lua::State* L); @@ -55,23 +55,24 @@ namespace lua { } else { throw std::runtime_error( "invalid number of arguments (" + std::to_string(a) + - " expected)"); + " expected)" + ); } } - - [[nodiscard]] - inline uint check_argc(lua::State* L, int a, int b) { + + [[nodiscard]] inline uint check_argc(lua::State* L, int a, int b) { int argc = lua::gettop(L); if (argc == a || argc == b) { return static_cast(argc); } else { throw std::runtime_error( "invalid number of arguments (" + std::to_string(a) + " or " + - std::to_string(b) + " expected)"); + std::to_string(b) + " expected)" + ); } } } void initialize_libs_extends(lua::State* L); -#endif // LOGIC_SCRIPTING_API_LUA_HPP_ +#endif // LOGIC_SCRIPTING_API_LUA_HPP_ diff --git a/src/logic/scripting/lua/lib__rigidbody.cpp b/src/logic/scripting/lua/lib__rigidbody.cpp index ea9c138f..5175a36f 100644 --- a/src/logic/scripting/lua/lib__rigidbody.cpp +++ b/src/logic/scripting/lua/lib__rigidbody.cpp @@ -1,6 +1,5 @@ -#include "libentity.hpp" - #include "../../../util/stringutil.hpp" +#include "libentity.hpp" static int l_get_vel(lua::State* L) { if (auto entity = get_entity(L, 1)) { @@ -60,7 +59,9 @@ static int l_set_gravity_scale(lua::State* L) { static int l_is_vdamping(lua::State* L) { if (auto entity = get_entity(L, 1)) { - return lua::pushboolean(L, entity->getRigidbody().hitbox.verticalDamping); + return lua::pushboolean( + L, entity->getRigidbody().hitbox.verticalDamping + ); } return 0; } @@ -95,7 +96,9 @@ static int l_set_crouching(lua::State* L) { static int l_get_body_type(lua::State* L) { if (auto entity = get_entity(L, 1)) { - return lua::pushstring(L, to_string(entity->getRigidbody().hitbox.type)); + return lua::pushstring( + L, to_string(entity->getRigidbody().hitbox.type) + ); } return 0; } @@ -106,7 +109,8 @@ static int l_set_body_type(lua::State* L) { entity->getRigidbody().hitbox.type = *type; } else { throw std::runtime_error( - "unknown body type "+util::quote(lua::tostring(L, 2))); + "unknown body type " + util::quote(lua::tostring(L, 2)) + ); } } return 0; @@ -126,7 +130,7 @@ static int l_set_linear_damping(lua::State* L) { return 0; } -const luaL_Reg rigidbodylib [] = { +const luaL_Reg rigidbodylib[] = { {"is_enabled", lua::wrap}, {"set_enabled", lua::wrap}, {"get_vel", lua::wrap}, @@ -144,5 +148,4 @@ const luaL_Reg rigidbodylib [] = { {"set_crouching", lua::wrap}, {"get_body_type", lua::wrap}, {"set_body_type", lua::wrap}, - {NULL, NULL} -}; + {NULL, NULL}}; diff --git a/src/logic/scripting/lua/lib__skeleton.cpp b/src/logic/scripting/lua/lib__skeleton.cpp index 6eb00a97..8ce77c98 100644 --- a/src/logic/scripting/lua/lib__skeleton.cpp +++ b/src/logic/scripting/lua/lib__skeleton.cpp @@ -1,12 +1,14 @@ +#include "../../../objects/rigging.hpp" #include "libentity.hpp" -#include "../../../objects/rigging.hpp" - -static int index_range_check(const rigging::Skeleton& skeleton, lua::Integer index) { +static int index_range_check( + const rigging::Skeleton& skeleton, lua::Integer index +) { if (static_cast(index) >= skeleton.pose.matrices.size()) { - throw std::runtime_error("index out of range [0, " + - std::to_string(skeleton.pose.matrices.size()) + - "]"); + throw std::runtime_error( + "index out of range [0, " + + std::to_string(skeleton.pose.matrices.size()) + "]" + ); } return static_cast(index); } @@ -60,7 +62,8 @@ static int l_set_matrix(lua::State* L) { static int l_get_texture(lua::State* L) { if (auto entity = get_entity(L, 1)) { auto& skeleton = entity->getSkeleton(); - skeleton.textures[lua::require_string(L, 2)] = lua::require_string(L, 3); + skeleton.textures[lua::require_string(L, 2)] = + lua::require_string(L, 3); const auto& found = skeleton.textures.find(lua::require_string(L, 2)); if (found != skeleton.textures.end()) { return lua::pushstring(L, found->second); @@ -72,7 +75,8 @@ static int l_get_texture(lua::State* L) { static int l_set_texture(lua::State* L) { if (auto entity = get_entity(L, 1)) { auto& skeleton = entity->getSkeleton(); - skeleton.textures[lua::require_string(L, 2)] = lua::require_string(L, 3); + skeleton.textures[lua::require_string(L, 2)] = + lua::require_string(L, 3); } return 0; } @@ -128,7 +132,7 @@ static int l_set_color(lua::State* L) { return 0; } -const luaL_Reg skeletonlib [] = { +const luaL_Reg skeletonlib[] = { {"get_model", lua::wrap}, {"set_model", lua::wrap}, {"get_matrix", lua::wrap}, @@ -140,5 +144,4 @@ const luaL_Reg skeletonlib [] = { {"set_visible", lua::wrap}, {"get_color", lua::wrap}, {"set_color", lua::wrap}, - {NULL, NULL} -}; + {NULL, NULL}}; diff --git a/src/logic/scripting/lua/lib__transform.cpp b/src/logic/scripting/lua/lib__transform.cpp index 0eb7fc9c..99534964 100644 --- a/src/logic/scripting/lua/lib__transform.cpp +++ b/src/logic/scripting/lua/lib__transform.cpp @@ -44,12 +44,11 @@ static int l_set_rot(lua::State* L) { return 0; } -const luaL_Reg transformlib [] = { +const luaL_Reg transformlib[] = { {"get_pos", lua::wrap}, {"set_pos", lua::wrap}, {"get_size", lua::wrap}, {"set_size", lua::wrap}, {"get_rot", lua::wrap}, {"set_rot", lua::wrap}, - {NULL, NULL} -}; + {NULL, NULL}}; diff --git a/src/logic/scripting/lua/libaudio.cpp b/src/logic/scripting/lua/libaudio.cpp index 398bd6b5..1bf3704b 100644 --- a/src/logic/scripting/lua/libaudio.cpp +++ b/src/logic/scripting/lua/libaudio.cpp @@ -1,7 +1,6 @@ -#include "api_lua.hpp" - #include "../../../audio/audio.hpp" #include "../../../engine.hpp" +#include "api_lua.hpp" inline const char* DEFAULT_CHANNEL = "regular"; @@ -37,17 +36,15 @@ inline audio::speakerid_t play_sound( return 0; } return audio::play( - sound, + sound, glm::vec3( - static_cast(x), - static_cast(y), - static_cast(z) - ), - relative, - volume, + static_cast(x), static_cast(y), static_cast(z) + ), + relative, + volume, pitch, loop, - audio::PRIORITY_NORMAL, + audio::PRIORITY_NORMAL, channel ); } @@ -68,32 +65,31 @@ inline audio::speakerid_t play_stream( } auto paths = scripting::engine->getResPaths(); return audio::play_stream( - paths->find(filename), + paths->find(filename), glm::vec3( - static_cast(x), - static_cast(y), - static_cast(z) - ), - relative, - volume, - pitch, - loop, + static_cast(x), static_cast(y), static_cast(z) + ), + relative, + volume, + pitch, + loop, channel ); } /// @brief audio.play_stream( /// name: string, -/// x: number, -/// y: number, -/// z: number, +/// x: number, +/// y: number, +/// z: number, /// volume: number, /// pitch: number, /// channel: string = "regular", /// loop: bool = false) static int l_audio_play_stream(lua::State* L) { - return lua::pushinteger(L, static_cast( - play_stream( + return lua::pushinteger( + L, + static_cast(play_stream( lua::tostring(L, 1), false, lua::tonumber(L, 2), @@ -103,8 +99,8 @@ static int l_audio_play_stream(lua::State* L) { lua::tonumber(L, 6), lua::toboolean(L, 8), extract_channel_index(L, 7) - ) - )); + )) + ); } /// @brief audio.play_stream_2d( @@ -114,31 +110,35 @@ static int l_audio_play_stream(lua::State* L) { /// channel: string = "regular", /// loop: bool = false) static int l_audio_play_stream_2d(lua::State* L) { - return lua::pushinteger(L, static_cast( - play_stream( + return lua::pushinteger( + L, + static_cast(play_stream( lua::tostring(L, 1), true, - 0.0, 0.0, 0.0, + 0.0, + 0.0, + 0.0, lua::tonumber(L, 2), lua::tonumber(L, 3), lua::toboolean(L, 5), extract_channel_index(L, 4) - ) - )); + )) + ); } /// @brief audio.play_sound( -/// name: string, -/// x: number, -/// y: number, -/// z: number, +/// name: string, +/// x: number, +/// y: number, +/// z: number, /// volume: number, /// pitch: number, /// channel: string = "regular", /// loop: bool = false) static int l_audio_play_sound(lua::State* L) { - return lua::pushinteger(L, static_cast( - play_sound( + return lua::pushinteger( + L, + static_cast(play_sound( lua::tostring(L, 1), false, lua::tonumber(L, 2), @@ -148,28 +148,31 @@ static int l_audio_play_sound(lua::State* L) { lua::tonumber(L, 6), lua::toboolean(L, 8), extract_channel_index(L, 7) - ) - )); + )) + ); } /// @brief audio.play_sound_2d( -/// name: string, +/// name: string, /// volume: number, /// pitch: number, /// channel: string = "regular", /// loop: bool = false) static int l_audio_play_sound_2d(lua::State* L) { - return lua::pushinteger(L, static_cast( - play_sound( + return lua::pushinteger( + L, + static_cast(play_sound( lua::tostring(L, 1), true, - 0.0, 0.0, 0.0, + 0.0, + 0.0, + 0.0, lua::tonumber(L, 2), lua::tonumber(L, 3), lua::toboolean(L, 5), extract_channel_index(L, 4) - ) - )); + )) + ); } /// @brief audio.stop(speakerid: integer) -> nil @@ -181,7 +184,7 @@ static int l_audio_stop(lua::State* L) { return 0; } -/// @brief audio.pause(speakerid: integer) -> nil +/// @brief audio.pause(speakerid: integer) -> nil static int l_audio_pause(lua::State* L) { auto speaker = audio::get_speaker(lua::tointeger(L, 1)); if (speaker != nullptr) { @@ -190,7 +193,7 @@ static int l_audio_pause(lua::State* L) { return 0; } -/// @brief audio.resume(speakerid: integer) -> nil +/// @brief audio.resume(speakerid: integer) -> nil static int l_audio_resume(lua::State* L) { auto speaker = audio::get_speaker(lua::tointeger(L, 1)); if (speaker != nullptr && speaker->isPaused()) { @@ -199,7 +202,7 @@ static int l_audio_resume(lua::State* L) { return 0; } -/// @brief audio.set_loop(speakerid: integer, value: bool) -> nil +/// @brief audio.set_loop(speakerid: integer, value: bool) -> nil static int l_audio_set_loop(lua::State* L) { auto speaker = audio::get_speaker(lua::tointeger(L, 1)); if (speaker != nullptr) { @@ -208,7 +211,7 @@ static int l_audio_set_loop(lua::State* L) { return 0; } -/// @brief audio.set_volume(speakerid: integer, value: number) -> nil +/// @brief audio.set_volume(speakerid: integer, value: number) -> nil static int l_audio_set_volume(lua::State* L) { auto speaker = audio::get_speaker(lua::tointeger(L, 1)); if (speaker != nullptr) { @@ -217,7 +220,7 @@ static int l_audio_set_volume(lua::State* L) { return 0; } -/// @brief audio.set_pitch(speakerid: integer, value: number) -> nil +/// @brief audio.set_pitch(speakerid: integer, value: number) -> nil static int l_audio_set_pitch(lua::State* L) { auto speaker = audio::get_speaker(lua::tointeger(L, 1)); if (speaker != nullptr) { @@ -226,7 +229,7 @@ static int l_audio_set_pitch(lua::State* L) { return 0; } -/// @brief audio.set_time(speakerid: integer, value: number) -> nil +/// @brief audio.set_time(speakerid: integer, value: number) -> nil static int l_audio_set_time(lua::State* L) { auto speaker = audio::get_speaker(lua::tointeger(L, 1)); if (speaker != nullptr) { @@ -235,7 +238,8 @@ static int l_audio_set_time(lua::State* L) { return 0; } -/// @brief audio.set_position(speakerid: integer, x: number, y: number, z: number) -> nil +/// @brief audio.set_position(speakerid: integer, x: number, y: number, z: +/// number) -> nil static int l_audio_set_position(lua::State* L) { auto speaker = audio::get_speaker(lua::tointeger(L, 1)); if (speaker != nullptr) { @@ -243,15 +247,14 @@ static int l_audio_set_position(lua::State* L) { auto y = lua::tonumber(L, 3); auto z = lua::tonumber(L, 4); speaker->setPosition(glm::vec3( - static_cast(x), - static_cast(y), - static_cast(z) + static_cast(x), static_cast(y), static_cast(z) )); } return 0; } -/// @brief audio.set_velocity(speakerid: integer, x: number, y: number, z: number) -> nil +/// @brief audio.set_velocity(speakerid: integer, x: number, y: number, z: +/// number) -> nil static int l_audio_set_velocity(lua::State* L) { auto speaker = audio::get_speaker(lua::tointeger(L, 1)); if (speaker != nullptr) { @@ -259,15 +262,13 @@ static int l_audio_set_velocity(lua::State* L) { auto y = lua::tonumber(L, 3); auto z = lua::tonumber(L, 4); speaker->setVelocity(glm::vec3( - static_cast(x), - static_cast(y), - static_cast(z) + static_cast(x), static_cast(y), static_cast(z) )); } return 0; } -/// @brief audio.is_playing(speakerid: integer) -> bool +/// @brief audio.is_playing(speakerid: integer) -> bool static int l_audio_is_playing(lua::State* L) { auto speaker = audio::get_speaker(lua::tointeger(L, 1)); if (speaker != nullptr) { @@ -276,7 +277,7 @@ static int l_audio_is_playing(lua::State* L) { return lua::pushboolean(L, false); } -/// @brief audio.is_paused(speakerid: integer) -> bool +/// @brief audio.is_paused(speakerid: integer) -> bool static int l_audio_is_paused(lua::State* L) { auto speaker = audio::get_speaker(lua::tointeger(L, 1)); if (speaker != nullptr) { @@ -358,7 +359,7 @@ static int l_audio_count_streams(lua::State* L) { return lua::pushinteger(L, audio::count_streams()); } -const luaL_Reg audiolib [] = { +const luaL_Reg audiolib[] = { {"play_sound", lua::wrap}, {"play_sound_2d", lua::wrap}, {"play_stream", lua::wrap}, @@ -383,5 +384,4 @@ const luaL_Reg audiolib [] = { {"get_velocity", lua::wrap}, {"count_speakers", lua::wrap}, {"count_streams", lua::wrap}, - {NULL, NULL} -}; + {NULL, NULL}}; diff --git a/src/logic/scripting/lua/libblock.cpp b/src/logic/scripting/lua/libblock.cpp index 0d24db89..cc1c6cd0 100644 --- a/src/logic/scripting/lua/libblock.cpp +++ b/src/logic/scripting/lua/libblock.cpp @@ -1,14 +1,13 @@ -#include "api_lua.hpp" - -#include "../../../world/Level.hpp" -#include "../../../voxels/Chunks.hpp" -#include "../../../voxels/Chunk.hpp" -#include "../../../voxels/Block.hpp" -#include "../../../voxels/voxel.hpp" -#include "../../../lighting/Lighting.hpp" #include "../../../content/Content.hpp" +#include "../../../lighting/Lighting.hpp" #include "../../../logic/BlocksController.hpp" #include "../../../logic/LevelController.hpp" +#include "../../../voxels/Block.hpp" +#include "../../../voxels/Chunk.hpp" +#include "../../../voxels/Chunks.hpp" +#include "../../../voxels/voxel.hpp" +#include "../../../world/Level.hpp" +#include "api_lua.hpp" using namespace scripting; @@ -80,14 +79,16 @@ static int l_seek_origin(lua::State* L) { auto z = lua::tointeger(L, 3); auto vox = level->chunks->get(x, y, z); auto def = indices->blocks.get(vox->id); - return lua::pushivec3_stack(L, level->chunks->seekOrigin({x, y, z}, def, vox->state)); + return lua::pushivec3_stack( + L, level->chunks->seekOrigin({x, y, z}, def, vox->state) + ); } static int l_set(lua::State* L) { auto x = lua::tointeger(L, 1); auto y = lua::tointeger(L, 2); auto z = lua::tointeger(L, 3); - auto id = lua::tointeger(L, 4); + auto id = lua::tointeger(L, 4); auto state = lua::tointeger(L, 5); bool noupdate = lua::toboolean(L, 6); if (static_cast(id) >= indices->blocks.count()) { @@ -97,7 +98,7 @@ static int l_set(lua::State* L) { return 0; } level->chunks->set(x, y, z, id, int2blockstate(state)); - level->lighting->onBlockSet(x,y,z, id); + level->lighting->onBlockSet(x, y, z, id); if (!noupdate) { blocks->updateSides(x, y, z); } @@ -232,7 +233,7 @@ static int l_set_user_bits(lua::State* L) { size_t mask = ((1 << bits) - 1) << offset; auto value = (lua::tointeger(L, 6) << offset) & mask; - + auto chunk = level->chunks->getChunkByVoxel(x, y, z); if (chunk == nullptr) { return 0; @@ -243,7 +244,7 @@ static int l_set_user_bits(lua::State* L) { } vox->state.userbits = (vox->state.userbits & (~mask)) | value; chunk->setModifiedAndUnsaved(); - return 0; + return 0; } static int l_is_replaceable_at(lua::State* L) { @@ -265,7 +266,7 @@ static int l_get_textures(lua::State* L) { lua::createtable(L, 6, 0); for (size_t i = 0; i < 6; i++) { lua::pushstring(L, def->textureFaces[i]); - lua::rawseti(L, i+1); + lua::rawseti(L, i + 1); } return 1; } @@ -283,7 +284,7 @@ static int l_get_hitbox(lua::State* L) { if (auto def = require_block(L)) { auto& hitbox = def->rt.hitboxes[lua::tointeger(L, 2)].at(0); lua::createtable(L, 2, 0); - + lua::pushvec3(L, hitbox.min()); lua::rawseti(L, 1); @@ -296,14 +297,14 @@ static int l_get_hitbox(lua::State* L) { static int l_get_rotation_profile(lua::State* L) { if (auto def = require_block(L)) { - return lua::pushstring(L, def->rotations.name); + return lua::pushstring(L, def->rotations.name); } return 0; } static int l_get_picking_item(lua::State* L) { if (auto def = require_block(L)) { - return lua::pushinteger(L, def->rt.pickingItem); + return lua::pushinteger(L, def->rt.pickingItem); } return 0; } @@ -323,11 +324,14 @@ static int l_place(lua::State* L) { } const auto def = level->content->getIndices()->blocks.get(id); if (def == nullptr) { - throw std::runtime_error("there is no block with index "+std::to_string(id)); + throw std::runtime_error( + "there is no block with index " + std::to_string(id) + ); } auto player = level->getObject(playerid); controller->getBlocksController()->placeBlock( - player ? player.get() : nullptr, def, int2blockstate(state), x, y, z); + player ? player.get() : nullptr, def, int2blockstate(state), x, y, z + ); return 0; } @@ -343,7 +347,8 @@ static int l_destruct(lua::State* L) { const auto def = level->content->getIndices()->blocks.get(voxel->id); auto player = level->getObject(playerid); controller->getBlocksController()->breakBlock( - player ? player.get() : nullptr, def, x, y, z); + player ? player.get() : nullptr, def, x, y, z + ); return 0; } @@ -354,13 +359,15 @@ static int l_raycast(lua::State* L) { glm::vec3 end; glm::ivec3 normal; glm::ivec3 iend; - if (auto voxel = level->chunks->rayCast(start, dir, maxDistance, end, normal, iend)) { + if (auto voxel = level->chunks->rayCast( + start, dir, maxDistance, end, normal, iend + )) { if (lua::gettop(L) >= 4) { lua::pushvalue(L, 4); } else { lua::createtable(L, 0, 5); } - + lua::pushvec3(L, end); lua::setfield(L, "endpoint"); @@ -385,10 +392,16 @@ static int l_compose_state(lua::State* L) { throw std::runtime_error("expected array of 3 integers"); } blockstate state {}; - - lua::rawgeti(L, 1, 1); state.rotation = lua::tointeger(L, -1); lua::pop(L); - lua::rawgeti(L, 2, 1); state.segment = lua::tointeger(L, -1); lua::pop(L); - lua::rawgeti(L, 3, 1); state.userbits = lua::tointeger(L, -1); lua::pop(L); + + lua::rawgeti(L, 1, 1); + state.rotation = lua::tointeger(L, -1); + lua::pop(L); + lua::rawgeti(L, 2, 1); + state.segment = lua::tointeger(L, -1); + lua::pop(L); + lua::rawgeti(L, 3, 1); + state.userbits = lua::tointeger(L, -1); + lua::pop(L); return lua::pushinteger(L, blockstate2int(state)); } @@ -409,7 +422,7 @@ static int l_decompose_state(lua::State* L) { return 1; } -const luaL_Reg blocklib [] = { +const luaL_Reg blocklib[] = { {"index", lua::wrap}, {"name", lua::wrap}, {"material", lua::wrap}, @@ -442,5 +455,4 @@ const luaL_Reg blocklib [] = { {"raycast", lua::wrap}, {"compose_state", lua::wrap}, {"decompose_state", lua::wrap}, - {NULL, NULL} -}; + {NULL, NULL}}; diff --git a/src/logic/scripting/lua/libcamera.cpp b/src/logic/scripting/lua/libcamera.cpp index 24aaeaf4..74c0ec2a 100644 --- a/src/logic/scripting/lua/libcamera.cpp +++ b/src/logic/scripting/lua/libcamera.cpp @@ -1,20 +1,19 @@ -#include "api_lua.hpp" +#include #include "../../../content/Content.hpp" -#include "../../../world/Level.hpp" #include "../../../window/Camera.hpp" - -#include +#include "../../../world/Level.hpp" +#include "api_lua.hpp" using namespace scripting; -template +template static int l_camera_getter(lua::State* L) { size_t index = static_cast(lua::tointeger(L, 1)); return getterfunc(L, *level->cameras.at(index)); } -template +template static int l_camera_setter(lua::State* L) { size_t index = static_cast(lua::tointeger(L, 1)); setterfunc(L, *level->cameras.at(index), 2); @@ -92,19 +91,22 @@ static int l_look_at(lua::State* L) { size_t index = static_cast(lua::tointeger(L, 1)); auto& camera = *level->cameras.at(index); auto center = lua::tovec<3>(L, 2); - auto matrix = glm::inverse(glm::lookAt(glm::vec3(), center-camera.position, glm::vec3(0, 1, 0))); + auto matrix = glm::inverse( + glm::lookAt(glm::vec3(), center - camera.position, glm::vec3(0, 1, 0)) + ); if (lua::isnumber(L, 3)) { matrix = glm::mat4_cast(glm::slerp( glm::quat(camera.rotation), glm::quat(matrix), - static_cast(lua::tonumber(L, 3)))); + static_cast(lua::tonumber(L, 3)) + )); } camera.rotation = matrix; camera.updateVectors(); return 0; } -const luaL_Reg cameralib [] = { +const luaL_Reg cameralib[] = { {"index", lua::wrap}, {"name", lua::wrap}, {"get_pos", lua::wrap>}, @@ -123,5 +125,4 @@ const luaL_Reg cameralib [] = { {"get_right", lua::wrap>}, {"get_up", lua::wrap>}, {"look_at", lua::wrap}, - {NULL, NULL} -}; + {NULL, NULL}}; diff --git a/src/logic/scripting/lua/libconsole.cpp b/src/logic/scripting/lua/libconsole.cpp index 13f33e26..4a106f95 100644 --- a/src/logic/scripting/lua/libconsole.cpp +++ b/src/logic/scripting/lua/libconsole.cpp @@ -1,8 +1,7 @@ -#include "api_lua.hpp" - -#include "../../CommandsInterpreter.hpp" -#include "../../../engine.hpp" #include "../../../coders/commons.hpp" +#include "../../../engine.hpp" +#include "../../CommandsInterpreter.hpp" +#include "api_lua.hpp" using namespace scripting; @@ -16,12 +15,16 @@ static int l_add_command(lua::State* L) { auto func = lua::create_lambda(L); try { engine->getCommandsInterpreter()->getRepository()->add( - scheme, description, [func](auto, auto args, auto kwargs) { + scheme, + description, + [func](auto, auto args, auto kwargs) { return func({args, kwargs}); } ); } catch (const parsing_error& err) { - throw std::runtime_error(("command scheme error:\n"+err.errorLog()).c_str()); + throw std::runtime_error( + ("command scheme error:\n" + err.errorLog()).c_str() + ); } return 0; } @@ -64,7 +67,7 @@ static int l_get_command_info(lua::State* L) { } const auto& args = command->getArgs(); const auto& kwargs = command->getKwArgs(); - + lua::createtable(L, 0, 4); lua::pushstring(L, name); @@ -72,15 +75,15 @@ static int l_get_command_info(lua::State* L) { lua::pushstring(L, command->getDescription()); lua::setfield(L, "description"); - + lua::createtable(L, args.size(), 0); for (size_t i = 0; i < args.size(); i++) { auto& arg = args[i]; lua::createtable(L, 0, 2); - + lua::pushstring(L, arg.name); lua::setfield(L, "name"); - + lua::pushstring(L, cmd::argtype_name(arg.type)); lua::setfield(L, "type"); @@ -88,7 +91,7 @@ static int l_get_command_info(lua::State* L) { lua::pushboolean(L, true); lua::setfield(L, "optional"); } - lua::rawseti(L, i+1); + lua::rawseti(L, i + 1); } lua::setfield(L, "args"); @@ -99,18 +102,17 @@ static int l_get_command_info(lua::State* L) { lua::pushstring(L, cmd::argtype_name(arg.type)); lua::setfield(L, "type"); - + lua::setfield(L, arg.name); } lua::setfield(L, "kwargs"); return 1; } -const luaL_Reg consolelib [] = { +const luaL_Reg consolelib[] = { {"add_command", lua::wrap}, {"execute", lua::wrap}, {"set", lua::wrap}, {"get_commands_list", lua::wrap}, {"get_command_info", lua::wrap}, - {NULL, NULL} -}; + {NULL, NULL}}; diff --git a/src/logic/scripting/lua/libcore.cpp b/src/logic/scripting/lua/libcore.cpp index 2b3e2ca8..0b28ddbd 100644 --- a/src/logic/scripting/lua/libcore.cpp +++ b/src/logic/scripting/lua/libcore.cpp @@ -1,25 +1,24 @@ -#include "api_lua.hpp" +#include +#include +#include "../../../constants.hpp" #include "../../../engine.hpp" -#include "../../../files/settings_io.hpp" #include "../../../files/engine_paths.hpp" +#include "../../../files/settings_io.hpp" #include "../../../frontend/menu.hpp" #include "../../../frontend/screens/MenuScreen.hpp" -#include "../../../logic/LevelController.hpp" #include "../../../logic/EngineController.hpp" -#include "../../../world/Level.hpp" +#include "../../../logic/LevelController.hpp" #include "../../../window/Events.hpp" #include "../../../window/Window.hpp" +#include "../../../world/Level.hpp" #include "../../../world/WorldGenerators.hpp" -#include "../../../constants.hpp" - -#include -#include +#include "api_lua.hpp" using namespace scripting; /// @brief Creating new world -/// @param name Name world +/// @param name Name world /// @param seed Seed world /// @param generator Type of generation static int l_new_world(lua::State* L) { @@ -32,7 +31,7 @@ static int l_new_world(lua::State* L) { } /// @brief Open world -/// @param name Name world +/// @param name Name world static int l_open_world(lua::State* L) { auto name = lua::require_string(L, 1); @@ -79,10 +78,12 @@ static int l_delete_world(lua::State* L) { /// @param remPacks An array of packs to remove static int l_reconfig_packs(lua::State* L) { if (!lua::istable(L, 1)) { - throw std::runtime_error("strings array expected as the first argument"); + throw std::runtime_error("strings array expected as the first argument" + ); } if (!lua::istable(L, 2)) { - throw std::runtime_error("strings array expected as the second argument"); + throw std::runtime_error("strings array expected as the second argument" + ); } std::vector addPacks; if (!lua::istable(L, 1)) { @@ -90,7 +91,7 @@ static int l_reconfig_packs(lua::State* L) { } int addLen = lua::objlen(L, 1); for (int i = 0; i < addLen; i++) { - lua::rawgeti(L, i+1, 1); + lua::rawgeti(L, i + 1, 1); addPacks.emplace_back(lua::tostring(L, -1)); lua::pop(L); } @@ -101,7 +102,7 @@ static int l_reconfig_packs(lua::State* L) { } int remLen = lua::objlen(L, 2); for (int i = 0; i < remLen; i++) { - lua::rawgeti(L, i+1, 2); + lua::rawgeti(L, i + 1, 2); remPacks.emplace_back(lua::tostring(L, -1)); lua::pop(L); } @@ -190,7 +191,7 @@ static int l_get_generators(lua::State* L) { return 1; } -const luaL_Reg corelib [] = { +const luaL_Reg corelib[] = { {"new_world", lua::wrap}, {"open_world", lua::wrap}, {"reopen_world", lua::wrap}, @@ -204,5 +205,4 @@ const luaL_Reg corelib [] = { {"quit", lua::wrap}, {"get_default_generator", lua::wrap}, {"get_generators", lua::wrap}, - {NULL, NULL} -}; + {NULL, NULL}}; diff --git a/src/logic/scripting/lua/libentity.cpp b/src/logic/scripting/lua/libentity.cpp index 5c98307e..ec24f54f 100644 --- a/src/logic/scripting/lua/libentity.cpp +++ b/src/logic/scripting/lua/libentity.cpp @@ -1,14 +1,14 @@ #include "libentity.hpp" -#include "../../../objects/Player.hpp" +#include "../../../content/Content.hpp" +#include "../../../engine.hpp" #include "../../../objects/Entities.hpp" #include "../../../objects/EntityDef.hpp" +#include "../../../objects/Player.hpp" #include "../../../objects/rigging.hpp" #include "../../../physics/Hitbox.hpp" -#include "../../../window/Camera.hpp" -#include "../../../content/Content.hpp" #include "../../../voxels/Chunks.hpp" -#include "../../../engine.hpp" +#include "../../../window/Camera.hpp" using namespace scripting; @@ -21,7 +21,6 @@ static EntityDef* require_entity_def(lua::State* L) { return indices->entities.get(id); } - static int l_exists(lua::State* L) { return lua::pushboolean(L, get_entity(L, 1).has_value()); } @@ -83,7 +82,9 @@ static int l_set_skeleton(lua::State* L) { std::string skeletonName = lua::require_string(L, 2); auto rigConfig = content->getSkeleton(skeletonName); if (rigConfig == nullptr) { - throw std::runtime_error("skeleton not found '"+skeletonName+"'"); + throw std::runtime_error( + "skeleton not found '" + skeletonName + "'" + ); } entity->setRig(rigConfig); } @@ -98,7 +99,7 @@ static int l_get_all_in_box(lua::State* L) { for (size_t i = 0; i < found.size(); i++) { const auto& entity = found[i]; lua::pushinteger(L, entity.getUID()); - lua::rawseti(L, i+1); + lua::rawseti(L, i + 1); } return 1; } @@ -111,9 +112,9 @@ static int l_get_all_in_radius(lua::State* L) { for (size_t i = 0; i < found.size(); i++) { const auto& entity = found[i]; lua::pushinteger(L, entity.getUID()); - lua::rawseti(L, i+1); + lua::rawseti(L, i + 1); } - return 1; + return 1; } static int l_raycast(lua::State* L) { @@ -127,7 +128,9 @@ static int l_raycast(lua::State* L) { blockid_t block = BLOCK_VOID; - if (auto voxel = level->chunks->rayCast(start, dir, maxDistance, end, normal, iend)) { + if (auto voxel = level->chunks->rayCast( + start, dir, maxDistance, end, normal, iend + )) { maxDistance = glm::distance(start, end); block = voxel->id; } @@ -137,7 +140,7 @@ static int l_raycast(lua::State* L) { } else { lua::createtable(L, 0, 6); } - + lua::pushvec3(L, start + dir * ray->distance); lua::setfield(L, "endpoint"); @@ -181,7 +184,7 @@ static int l_raycast(lua::State* L) { return 0; } -const luaL_Reg entitylib [] = { +const luaL_Reg entitylib[] = { {"exists", lua::wrap}, {"def_index", lua::wrap}, {"def_name", lua::wrap}, @@ -194,5 +197,4 @@ const luaL_Reg entitylib [] = { {"get_all_in_box", lua::wrap}, {"get_all_in_radius", lua::wrap}, {"raycast", lua::wrap}, - {NULL, NULL} -}; + {NULL, NULL}}; diff --git a/src/logic/scripting/lua/libentity.hpp b/src/logic/scripting/lua/libentity.hpp index f2fa38e0..724aaefb 100644 --- a/src/logic/scripting/lua/libentity.hpp +++ b/src/logic/scripting/lua/libentity.hpp @@ -1,15 +1,14 @@ #ifndef LOGIC_SCRIPTING_LUA_LIBENTITY_HPP_ #define LOGIC_SCRIPTING_LUA_LIBENTITY_HPP_ -#include "api_lua.hpp" - -#include "../../LevelController.hpp" -#include "../../../frontend/hud.hpp" -#include "../../../world/Level.hpp" -#include "../../../objects/Entities.hpp" - #include +#include "../../../frontend/hud.hpp" +#include "../../../objects/Entities.hpp" +#include "../../../world/Level.hpp" +#include "../../LevelController.hpp" +#include "api_lua.hpp" + namespace scripting { extern Hud* hud; } @@ -20,4 +19,4 @@ inline std::optional get_entity(lua::State* L, int idx) { return level->entities->get(id); } -#endif // LOGIC_SCRIPTING_LUA_LIBENTITY_HPP_ +#endif // LOGIC_SCRIPTING_LUA_LIBENTITY_HPP_ diff --git a/src/logic/scripting/lua/libfile.cpp b/src/logic/scripting/lua/libfile.cpp index 5c5dc27b..785235a7 100644 --- a/src/logic/scripting/lua/libfile.cpp +++ b/src/logic/scripting/lua/libfile.cpp @@ -1,13 +1,12 @@ -#include "api_lua.hpp" - -#include "../../../engine.hpp" -#include "../../../coders/gzip.hpp" -#include "../../../files/files.hpp" -#include "../../../files/engine_paths.hpp" -#include "../../../util/stringutil.hpp" - -#include #include +#include + +#include "../../../coders/gzip.hpp" +#include "../../../engine.hpp" +#include "../../../files/engine_paths.hpp" +#include "../../../files/files.hpp" +#include "../../../util/stringutil.hpp" +#include "api_lua.hpp" namespace fs = std::filesystem; using namespace scripting; @@ -42,14 +41,16 @@ static int l_file_read(lua::State* L) { if (fs::is_regular_file(path)) { return lua::pushstring(L, files::read_string(path)); } - throw std::runtime_error("file does not exists "+util::quote(path.u8string())); + throw std::runtime_error( + "file does not exists " + util::quote(path.u8string()) + ); } static int l_file_write(lua::State* L) { fs::path path = resolve_path(lua::require_string(L, 1)); std::string text = lua::require_string(L, 2); files::write_string(path, text); - return 1; + return 1; } static int l_file_remove(lua::State* L) { @@ -89,7 +90,7 @@ static int l_file_isdir(lua::State* L) { static int l_file_length(lua::State* L) { fs::path path = resolve_path(lua::require_string(L, 1)); - if (fs::exists(path)){ + if (fs::exists(path)) { return lua::pushinteger(L, fs::file_size(path)); } else { return lua::pushinteger(L, -1); @@ -98,12 +99,12 @@ static int l_file_length(lua::State* L) { static int l_file_mkdir(lua::State* L) { fs::path path = resolve_path(lua::require_string(L, 1)); - return lua::pushboolean(L, fs::create_directory(path)); + return lua::pushboolean(L, fs::create_directory(path)); } static int l_file_mkdirs(lua::State* L) { fs::path path = resolve_path(lua::require_string(L, 1)); - return lua::pushboolean(L, fs::create_directories(path)); + return lua::pushboolean(L, fs::create_directories(path)); } static int l_file_read_bytes(lua::State* L) { @@ -116,26 +117,32 @@ static int l_file_read_bytes(lua::State* L) { lua::createtable(L, length, 0); int newTable = lua::gettop(L); - for(size_t i = 0; i < length; i++) { + for (size_t i = 0; i < length; i++) { lua::pushinteger(L, bytes[i]); - lua::rawseti(L, i+1, newTable); + lua::rawseti(L, i + 1, newTable); } return 1; } - throw std::runtime_error("file does not exists "+util::quote(path.u8string())); + throw std::runtime_error( + "file does not exists " + util::quote(path.u8string()) + ); } -static int read_bytes_from_table(lua::State* L, int tableIndex, std::vector& bytes) { - if(!lua::istable(L, tableIndex)) { +static int read_bytes_from_table( + lua::State* L, int tableIndex, std::vector& bytes +) { + if (!lua::istable(L, tableIndex)) { throw std::runtime_error("table expected"); } else { lua::pushnil(L); - while(lua::next(L, tableIndex - 1) != 0) { + while (lua::next(L, tableIndex - 1) != 0) { const int byte = lua::tointeger(L, -1); - if(byte < 0 || byte > 255) { - throw std::runtime_error("invalid byte '"+std::to_string(byte)+"'"); + if (byte < 0 || byte > 255) { + throw std::runtime_error( + "invalid byte '" + std::to_string(byte) + "'" + ); } - bytes.push_back(byte); + bytes.push_back(byte); lua::pop(L); } return 1; @@ -145,7 +152,7 @@ static int read_bytes_from_table(lua::State* L, int tableIndex, std::vector(L, -1)) { auto& bytes = bytearray->data(); - return lua::pushboolean(L, files::write_bytes(path, bytes.data(), bytes.size())); + return lua::pushboolean( + L, files::write_bytes(path, bytes.data(), bytes.size()) + ); } std::vector bytes; int result = read_bytes_from_table(L, -1, bytes); - if(result != 1) { + if (result != 1) { return result; } else { - return lua::pushboolean(L, files::write_bytes(path, bytes.data(), bytes.size())); + return lua::pushboolean( + L, files::write_bytes(path, bytes.data(), bytes.size()) + ); } } @@ -170,7 +181,7 @@ static int l_file_list_all_res(lua::State* L, const std::string& path) { lua::createtable(L, files.size(), 0); for (size_t i = 0; i < files.size(); i++) { lua::pushstring(L, files[i]); - lua::rawseti(L, i+1); + lua::rawseti(L, i + 1); } return 1; } @@ -182,7 +193,9 @@ static int l_file_list(lua::State* L) { } fs::path path = resolve_path(dirname); if (!fs::is_directory(path)) { - throw std::runtime_error(util::quote(path.u8string())+" is not a directory"); + throw std::runtime_error( + util::quote(path.u8string()) + " is not a directory" + ); } lua::createtable(L, 0, 0); size_t index = 1; @@ -197,46 +210,44 @@ static int l_file_list(lua::State* L) { } static int l_file_gzip_compress(lua::State* L) { - std::vector bytes; int result = read_bytes_from_table(L, -1, bytes); - if(result != 1) { + if (result != 1) { return result; } else { auto compressed_bytes = gzip::compress(bytes.data(), bytes.size()); int newTable = lua::gettop(L); - for(size_t i = 0; i < compressed_bytes.size(); i++) { + for (size_t i = 0; i < compressed_bytes.size(); i++) { lua::pushinteger(L, compressed_bytes.data()[i]); - lua::rawseti(L, i+1, newTable); + lua::rawseti(L, i + 1, newTable); } return 1; } } -static int l_file_gzip_decompress(lua::State* L) { - +static int l_file_gzip_decompress(lua::State* L) { std::vector bytes; int result = read_bytes_from_table(L, -1, bytes); - if(result != 1) { + if (result != 1) { return result; } else { auto decompressed_bytes = gzip::decompress(bytes.data(), bytes.size()); int newTable = lua::gettop(L); - for(size_t i = 0; i < decompressed_bytes.size(); i++) { + for (size_t i = 0; i < decompressed_bytes.size(); i++) { lua::pushinteger(L, decompressed_bytes.data()[i]); - lua::rawseti(L, i+1, newTable); + lua::rawseti(L, i + 1, newTable); } return 1; } } -const luaL_Reg filelib [] = { +const luaL_Reg filelib[] = { {"exists", lua::wrap}, {"find", lua::wrap}, {"isdir", lua::wrap}, @@ -254,5 +265,4 @@ const luaL_Reg filelib [] = { {"write", lua::wrap}, {"gzip_compress", lua::wrap}, {"gzip_decompress", lua::wrap}, - {NULL, NULL} -}; + {NULL, NULL}}; diff --git a/src/logic/scripting/lua/libgui.cpp b/src/logic/scripting/lua/libgui.cpp index 1829df06..99a4c569 100644 --- a/src/logic/scripting/lua/libgui.cpp +++ b/src/logic/scripting/lua/libgui.cpp @@ -1,22 +1,21 @@ -#include "api_lua.hpp" - -#include "../../../engine.hpp" #include "../../../assets/Assets.hpp" -#include "../../../items/Inventories.hpp" -#include "../../../graphics/ui/gui_util.hpp" -#include "../../../graphics/ui/elements/UINode.hpp" -#include "../../../graphics/ui/elements/Button.hpp" -#include "../../../graphics/ui/elements/Image.hpp" -#include "../../../graphics/ui/elements/CheckBox.hpp" -#include "../../../graphics/ui/elements/TextBox.hpp" -#include "../../../graphics/ui/elements/TrackBar.hpp" -#include "../../../graphics/ui/elements/Panel.hpp" -#include "../../../graphics/ui/elements/Menu.hpp" -#include "../../../graphics/ui/elements/InventoryView.hpp" +#include "../../../engine.hpp" #include "../../../frontend/UiDocument.hpp" #include "../../../frontend/locale.hpp" +#include "../../../graphics/ui/elements/Button.hpp" +#include "../../../graphics/ui/elements/CheckBox.hpp" +#include "../../../graphics/ui/elements/Image.hpp" +#include "../../../graphics/ui/elements/InventoryView.hpp" +#include "../../../graphics/ui/elements/Menu.hpp" +#include "../../../graphics/ui/elements/Panel.hpp" +#include "../../../graphics/ui/elements/TextBox.hpp" +#include "../../../graphics/ui/elements/TrackBar.hpp" +#include "../../../graphics/ui/elements/UINode.hpp" +#include "../../../graphics/ui/gui_util.hpp" +#include "../../../items/Inventories.hpp" #include "../../../util/stringutil.hpp" #include "../../../world/Level.hpp" +#include "api_lua.hpp" using namespace gui; using namespace scripting; @@ -26,19 +25,23 @@ struct DocumentNode { std::shared_ptr node; }; -static DocumentNode getDocumentNode(lua::State*, const std::string& name, const std::string& nodeName) { +static DocumentNode getDocumentNode( + lua::State*, const std::string& name, const std::string& nodeName +) { auto doc = engine->getAssets()->get(name); if (doc == nullptr) { - throw std::runtime_error("document '"+name+"' not found"); + throw std::runtime_error("document '" + name + "' not found"); } auto node = doc->get(nodeName); if (node == nullptr) { - throw std::runtime_error("document '"+name+"' has no element with id '"+nodeName+"'"); + throw std::runtime_error( + "document '" + name + "' has no element with id '" + nodeName + "'" + ); } return {doc, node}; } -static DocumentNode getDocumentNode(lua::State* L, int idx=1) { +static DocumentNode getDocumentNode(lua::State* L, int idx = 1) { lua::getfield(L, "docname", idx); lua::getfield(L, "name", idx); auto docname = lua::require_string(L, -2); @@ -75,7 +78,8 @@ static int l_container_add(lua::State* L) { auto node = dynamic_cast(docnode.node.get()); auto xmlsrc = lua::require_string(L, 2); try { - auto subnode = guiutil::create(xmlsrc, docnode.document->getEnvironment()); + auto subnode = + guiutil::create(xmlsrc, docnode.document->getEnvironment()); node->add(subnode); UINode::getIndices(subnode, docnode.document->getMapWriteable()); } catch (const std::exception& err) { @@ -118,7 +122,9 @@ static int l_container_set_interval(lua::State* L) { static int l_move_into(lua::State* L) { auto node = getDocumentNode(L, 1); auto dest = getDocumentNode(L, 2); - UINode::moveInto(node.node, std::dynamic_pointer_cast(dest.node)); + UINode::moveInto( + node.node, std::dynamic_pointer_cast(dest.node) + ); return 0; } @@ -325,44 +331,47 @@ static int l_gui_getattr(lua::State* L) { auto element = lua::require_string(L, 2); auto attr = lua::require_string(L, 3); - static const std::unordered_map> getters { - {"color", p_get_color}, - {"hoverColor", p_get_hover_color}, - {"pressedColor", p_get_pressed_color}, - {"tooltip", p_get_tooltip}, - {"tooltipDelay", p_get_tooltip_delay}, - {"pos", p_get_pos}, - {"wpos", p_get_wpos}, - {"size", p_get_size}, - {"interactive", p_is_interactive}, - {"visible", p_is_visible}, - {"enabled", p_is_enabled}, - {"move_into", p_move_into}, // deprecated - {"moveInto", p_move_into}, - {"add", p_get_add}, - {"destruct", p_get_destruct}, - {"clear", p_get_clear}, - {"setInterval", p_set_interval}, - {"placeholder", p_get_placeholder}, - {"valid", p_is_valid}, - {"caret", p_get_caret}, - {"text", p_get_text}, - {"editable", p_get_editable}, - {"src", p_get_src}, - {"value", p_get_value}, - {"min", p_get_min}, - {"max", p_get_max}, - {"step", p_get_step}, - {"trackWidth", p_get_track_width}, - {"trackColor", p_get_track_color}, - {"checked", p_is_checked}, - {"page", p_get_page}, - {"back", p_get_back}, - {"reset", p_get_reset}, - {"paste", p_get_paste}, - {"inventory", p_get_inventory}, - {"focused", p_get_focused}, - }; + static const std::unordered_map< + std::string_view, + std::function> + getters { + {"color", p_get_color}, + {"hoverColor", p_get_hover_color}, + {"pressedColor", p_get_pressed_color}, + {"tooltip", p_get_tooltip}, + {"tooltipDelay", p_get_tooltip_delay}, + {"pos", p_get_pos}, + {"wpos", p_get_wpos}, + {"size", p_get_size}, + {"interactive", p_is_interactive}, + {"visible", p_is_visible}, + {"enabled", p_is_enabled}, + {"move_into", p_move_into}, // deprecated + {"moveInto", p_move_into}, + {"add", p_get_add}, + {"destruct", p_get_destruct}, + {"clear", p_get_clear}, + {"setInterval", p_set_interval}, + {"placeholder", p_get_placeholder}, + {"valid", p_is_valid}, + {"caret", p_get_caret}, + {"text", p_get_text}, + {"editable", p_get_editable}, + {"src", p_get_src}, + {"value", p_get_value}, + {"min", p_get_min}, + {"max", p_get_max}, + {"step", p_get_step}, + {"trackWidth", p_get_track_width}, + {"trackColor", p_get_track_color}, + {"checked", p_is_checked}, + {"page", p_get_page}, + {"back", p_get_back}, + {"reset", p_get_reset}, + {"paste", p_get_paste}, + {"inventory", p_get_inventory}, + {"focused", p_get_focused}, + }; auto func = getters.find(attr); if (func != getters.end()) { auto docnode = getDocumentNode(L, docname, element); @@ -391,7 +400,7 @@ static void p_set_pos(UINode* node, lua::State* L, int idx) { node->setPos(lua::tovec2(L, idx)); } static void p_set_wpos(UINode* node, lua::State* L, int idx) { - node->setPos(lua::tovec2(L, idx)-node->calcPos()); + node->setPos(lua::tovec2(L, idx) - node->calcPos()); } static void p_set_size(UINode* node, lua::State* L, int idx) { node->setSize(lua::tovec2(L, idx)); @@ -486,10 +495,12 @@ static void p_set_inventory(UINode* node, lua::State* L, int idx) { } } } -static void p_set_focused(const std::shared_ptr &node, lua::State* L, int idx) { +static void p_set_focused( + const std::shared_ptr& node, lua::State* L, int idx +) { if (lua::toboolean(L, idx) && !node->isFocused()) { engine->getGUI()->setFocus(node); - } else if (node->isFocused()){ + } else if (node->isFocused()) { node->defocus(); } } @@ -502,40 +513,46 @@ static int l_gui_setattr(lua::State* L) { auto docnode = getDocumentNode(L, docname, element); auto node = docnode.node; - static const std::unordered_map> setters { - {"color", p_set_color}, - {"hoverColor", p_set_hover_color}, - {"pressedColor", p_set_pressed_color}, - {"tooltip", p_set_tooltip}, - {"tooltipDelay", p_set_tooltip_delay}, - {"pos", p_set_pos}, - {"wpos", p_set_wpos}, - {"size", p_set_size}, - {"interactive", p_set_interactive}, - {"visible", p_set_visible}, - {"enabled", p_set_enabled}, - {"placeholder", p_set_placeholder}, - {"text", p_set_text}, - {"editable", p_set_editable}, - {"src", p_set_src}, - {"caret", p_set_caret}, - {"value", p_set_value}, - {"min", p_set_min}, - {"max", p_set_max}, - {"step", p_set_step}, - {"trackWidth", p_set_track_width}, - {"trackColor", p_set_track_color}, - {"checked", p_set_checked}, - {"page", p_set_page}, - {"inventory", p_set_inventory}, - }; + static const std::unordered_map< + std::string_view, + std::function> + setters { + {"color", p_set_color}, + {"hoverColor", p_set_hover_color}, + {"pressedColor", p_set_pressed_color}, + {"tooltip", p_set_tooltip}, + {"tooltipDelay", p_set_tooltip_delay}, + {"pos", p_set_pos}, + {"wpos", p_set_wpos}, + {"size", p_set_size}, + {"interactive", p_set_interactive}, + {"visible", p_set_visible}, + {"enabled", p_set_enabled}, + {"placeholder", p_set_placeholder}, + {"text", p_set_text}, + {"editable", p_set_editable}, + {"src", p_set_src}, + {"caret", p_set_caret}, + {"value", p_set_value}, + {"min", p_set_min}, + {"max", p_set_max}, + {"step", p_set_step}, + {"trackWidth", p_set_track_width}, + {"trackColor", p_set_track_color}, + {"checked", p_set_checked}, + {"page", p_set_page}, + {"inventory", p_set_inventory}, + }; auto func = setters.find(attr); if (func != setters.end()) { func->second(node.get(), L, 4); } - static const std::unordered_map,lua::State*,int)>> setters2 { - {"focused", p_set_focused}, - }; + static const std::unordered_map< + std::string_view, + std::function, lua::State*, int)>> + setters2 { + {"focused", p_set_focused}, + }; auto func2 = setters2.find(attr); if (func2 != setters2.end()) { func2->second(node, L, 4); @@ -547,7 +564,9 @@ static int l_gui_get_env(lua::State* L) { auto name = lua::require_string(L, 1); auto doc = engine->getAssets()->get(name); if (doc == nullptr) { - throw std::runtime_error("document '"+std::string(name)+"' not found"); + throw std::runtime_error( + "document '" + std::string(name) + "' not found" + ); } lua::getglobal(L, lua::env_name(*doc->getEnvironment())); return 1; @@ -568,13 +587,15 @@ static int l_gui_reindex(lua::State* L) { auto name = lua::require_string(L, 1); auto doc = engine->getAssets()->get(name); if (doc == nullptr) { - throw std::runtime_error("document '"+std::string(name)+"' not found"); + throw std::runtime_error( + "document '" + std::string(name) + "' not found" + ); } doc->rebuildIndices(); return 0; } -/// @brief gui.get_locales_info() -> table of tables +/// @brief gui.get_locales_info() -> table of tables static int l_gui_get_locales_info(lua::State* L) { auto& locales = langs::locales_info; lua::createtable(L, 0, locales.size()); @@ -591,7 +612,7 @@ static int l_gui_getviewport(lua::State* L) { return lua::pushvec2(L, engine->getGUI()->getContainer()->getSize()); } -const luaL_Reg guilib [] = { +const luaL_Reg guilib[] = { {"get_viewport", lua::wrap}, {"getattr", lua::wrap}, {"setattr", lua::wrap}, @@ -599,5 +620,4 @@ const luaL_Reg guilib [] = { {"str", lua::wrap}, {"get_locales_info", lua::wrap}, {"__reindex", lua::wrap}, - {NULL, NULL} -}; + {NULL, NULL}}; diff --git a/src/logic/scripting/lua/libhud.cpp b/src/logic/scripting/lua/libhud.cpp index 80b597eb..775c4ef0 100644 --- a/src/logic/scripting/lua/libhud.cpp +++ b/src/logic/scripting/lua/libhud.cpp @@ -1,10 +1,11 @@ -#include "api_lua.hpp" +#include +#include #include "../../../assets/Assets.hpp" #include "../../../content/Content.hpp" #include "../../../engine.hpp" -#include "../../../frontend/hud.hpp" #include "../../../frontend/UiDocument.hpp" +#include "../../../frontend/hud.hpp" #include "../../../graphics/ui/elements/InventoryView.hpp" #include "../../../items/Inventories.hpp" #include "../../../logic/BlocksController.hpp" @@ -14,9 +15,7 @@ #include "../../../voxels/Chunks.hpp" #include "../../../voxels/voxel.hpp" #include "../../../world/Level.hpp" - -#include -#include +#include "api_lua.hpp" namespace scripting { extern Hud* hud; @@ -45,20 +44,24 @@ static int l_hud_open_block(lua::State* L) { auto vox = level->chunks->get(x, y, z); if (vox == nullptr) { - throw std::runtime_error("block does not exists at " + - std::to_string(x) + " " + std::to_string(y) + " " + std::to_string(z) + throw std::runtime_error( + "block does not exists at " + std::to_string(x) + " " + + std::to_string(y) + " " + std::to_string(z) ); } auto def = content->getIndices()->blocks.get(vox->id); auto assets = engine->getAssets(); auto layout = assets->get(def->uiLayout); if (layout == nullptr) { - throw std::runtime_error("block '"+def->name+"' has no ui layout"); + throw std::runtime_error("block '" + def->name + "' has no ui layout"); } auto id = blocks->createBlockInventory(x, y, z); hud->openInventory( - glm::ivec3(x, y, z), layout, level->inventories->get(id), playerInventory + glm::ivec3(x, y, z), + layout, + level->inventories->get(id), + playerInventory ); lua::pushinteger(L, id); @@ -73,7 +76,7 @@ static int l_hud_show_overlay(lua::State* L) { auto assets = engine->getAssets(); auto layout = assets->get(name); if (layout == nullptr) { - throw std::runtime_error("there is no ui layout "+util::quote(name)); + throw std::runtime_error("there is no ui layout " + util::quote(name)); } hud->showOverlay(layout, playerInventory); return 0; @@ -83,7 +86,9 @@ static UiDocument* require_layout(const char* name) { auto assets = engine->getAssets(); auto layout = assets->get(name); if (layout == nullptr) { - throw std::runtime_error("layout '"+std::string(name)+"' is not found"); + throw std::runtime_error( + "layout '" + std::string(name) + "' is not found" + ); } return layout; } @@ -132,7 +137,7 @@ static int l_hud_is_inventory_open(lua::State* L) { return lua::pushboolean(L, hud->isInventoryOpen()); } -const luaL_Reg hudlib [] = { +const luaL_Reg hudlib[] = { {"open_inventory", lua::wrap}, {"close_inventory", lua::wrap}, {"open_block", lua::wrap}, @@ -145,5 +150,4 @@ const luaL_Reg hudlib [] = { {"is_paused", lua::wrap}, {"is_inventory_open", lua::wrap}, {"get_player", lua::wrap}, - {NULL, NULL} -}; + {NULL, NULL}}; diff --git a/src/logic/scripting/lua/libinput.cpp b/src/logic/scripting/lua/libinput.cpp index f09cc4a4..92fb4299 100644 --- a/src/logic/scripting/lua/libinput.cpp +++ b/src/logic/scripting/lua/libinput.cpp @@ -1,12 +1,11 @@ -#include "api_lua.hpp" - -#include "../../../window/input.hpp" -#include "../../../window/Events.hpp" -#include "../../../util/stringutil.hpp" -#include "../../../graphics/ui/GUI.hpp" -#include "../../../frontend/screens/Screen.hpp" -#include "../../../frontend/hud.hpp" #include "../../../engine.hpp" +#include "../../../frontend/hud.hpp" +#include "../../../frontend/screens/Screen.hpp" +#include "../../../graphics/ui/GUI.hpp" +#include "../../../util/stringutil.hpp" +#include "../../../window/Events.hpp" +#include "../../../window/input.hpp" +#include "api_lua.hpp" namespace scripting { extern Hud* hud; @@ -15,19 +14,23 @@ using namespace scripting; static int l_keycode(lua::State* L) { auto name = lua::require_string(L, 1); - return lua::pushinteger(L, static_cast(input_util::keycode_from(name))); + return lua::pushinteger( + L, static_cast(input_util::keycode_from(name)) + ); } static int l_mousecode(lua::State* L) { auto name = lua::require_string(L, 1); - return lua::pushinteger(L, static_cast(input_util::mousecode_from(name))); + return lua::pushinteger( + L, static_cast(input_util::mousecode_from(name)) + ); } static int l_add_callback(lua::State* L) { auto bindname = lua::require_string(L, 1); const auto& bind = Events::bindings.find(bindname); if (bind == Events::bindings.end()) { - throw std::runtime_error("unknown binding "+util::quote(bindname)); + throw std::runtime_error("unknown binding " + util::quote(bindname)); } lua::pushvalue(L, 2); runnable actual_callback = lua::create_runnable(L); @@ -65,7 +68,7 @@ static int l_is_active(lua::State* L) { auto bindname = lua::require_string(L, 1); const auto& bind = Events::bindings.find(bindname); if (bind == Events::bindings.end()) { - throw std::runtime_error("unknown binding "+util::quote(bindname)); + throw std::runtime_error("unknown binding " + util::quote(bindname)); } return lua::pushboolean(L, bind->second.active()); } @@ -77,17 +80,22 @@ static int l_is_pressed(lua::State* L) { throw std::runtime_error("expected 'input_type:key' format"); } auto prefix = code.substr(0, sep); - auto name = code.substr(sep+1); + auto name = code.substr(sep + 1); if (prefix == "key") { - return lua::pushboolean(L, Events::pressed(static_cast(input_util::keycode_from(name)))); + return lua::pushboolean( + L, Events::pressed(static_cast(input_util::keycode_from(name))) + ); } else if (prefix == "mouse") { - return lua::pushboolean(L, Events::clicked(static_cast(input_util::mousecode_from(name)))); + return lua::pushboolean( + L, + Events::clicked(static_cast(input_util::mousecode_from(name))) + ); } else { - throw std::runtime_error("unknown input type "+util::quote(code)); + throw std::runtime_error("unknown input type " + util::quote(code)); } } -const luaL_Reg inputlib [] = { +const luaL_Reg inputlib[] = { {"keycode", lua::wrap}, {"mousecode", lua::wrap}, {"add_callback", lua::wrap}, @@ -95,6 +103,4 @@ const luaL_Reg inputlib [] = { {"get_bindings", lua::wrap}, {"is_active", lua::wrap}, {"is_pressed", lua::wrap}, - {NULL, NULL} -}; - + {NULL, NULL}}; diff --git a/src/logic/scripting/lua/libinventory.cpp b/src/logic/scripting/lua/libinventory.cpp index 67f4e6f1..85c6cc27 100644 --- a/src/logic/scripting/lua/libinventory.cpp +++ b/src/logic/scripting/lua/libinventory.cpp @@ -1,10 +1,9 @@ -#include "api_lua.hpp" - #include "../../../content/Content.hpp" -#include "../../../world/Level.hpp" -#include "../../../items/ItemStack.hpp" #include "../../../items/Inventories.hpp" +#include "../../../items/ItemStack.hpp" #include "../../../logic/BlocksController.hpp" +#include "../../../world/Level.hpp" +#include "api_lua.hpp" using namespace scripting; @@ -17,7 +16,7 @@ static void validate_itemid(itemid_t id) { static std::shared_ptr get_inventory(int64_t id) { auto inv = level->inventories->get(id); if (inv == nullptr) { - throw std::runtime_error("inventory not found: "+std::to_string(id)); + throw std::runtime_error("inventory not found: " + std::to_string(id)); } return inv; } @@ -25,15 +24,19 @@ static std::shared_ptr get_inventory(int64_t id) { static std::shared_ptr get_inventory(int64_t id, int arg) { auto inv = level->inventories->get(id); if (inv == nullptr) { - throw std::runtime_error("inventory not found: "+std::to_string(id)+ - " argument "+std::to_string(arg)); + throw std::runtime_error( + "inventory not found: " + std::to_string(id) + " argument " + + std::to_string(arg) + ); } return inv; } static void validate_slotid(int slotid, Inventory* inv) { if (static_cast(slotid) >= inv->size()) { - throw std::runtime_error("slot index is out of range [0..inventory.size(invid)]"); + throw std::runtime_error( + "slot index is out of range [0..inventory.size(invid)]" + ); } } @@ -128,12 +131,12 @@ static int l_inventory_move(lua::State* L) { if (slotBid == -1) { invB->move(slot, content->getIndices()); } else { - invB->move(slot, content->getIndices(), slotBid, slotBid+1); + invB->move(slot, content->getIndices(), slotBid, slotBid + 1); } return 0; } -const luaL_Reg inventorylib [] = { +const luaL_Reg inventorylib[] = { {"get", lua::wrap}, {"set", lua::wrap}, {"size", lua::wrap}, @@ -143,6 +146,4 @@ const luaL_Reg inventorylib [] = { {"bind_block", lua::wrap}, {"unbind_block", lua::wrap}, {"clone", lua::wrap}, - {NULL, NULL} -}; - + {NULL, NULL}}; diff --git a/src/logic/scripting/lua/libitem.cpp b/src/logic/scripting/lua/libitem.cpp index c033fd36..1213620f 100644 --- a/src/logic/scripting/lua/libitem.cpp +++ b/src/logic/scripting/lua/libitem.cpp @@ -1,7 +1,6 @@ -#include "api_lua.hpp" - #include "../../../content/Content.hpp" #include "../../../items/ItemDef.hpp" +#include "api_lua.hpp" using namespace scripting; @@ -45,17 +44,16 @@ static int l_item_get_icon(lua::State* L) { case item_icon_type::sprite: return lua::pushstring(L, def->icon); case item_icon_type::block: - return lua::pushstring(L, "block-previews:"+def->icon); + return lua::pushstring(L, "block-previews:" + def->icon); } } return 0; } -const luaL_Reg itemlib [] = { +const luaL_Reg itemlib[] = { {"index", lua::wrap}, {"name", lua::wrap}, {"stack_size", lua::wrap}, {"defs_count", lua::wrap}, {"icon", lua::wrap}, - {NULL, NULL} -}; + {NULL, NULL}}; diff --git a/src/logic/scripting/lua/libjson.cpp b/src/logic/scripting/lua/libjson.cpp index 0a68fd89..3fbe173c 100644 --- a/src/logic/scripting/lua/libjson.cpp +++ b/src/logic/scripting/lua/libjson.cpp @@ -1,7 +1,6 @@ -#include "api_lua.hpp" - #include "../../../coders/json.hpp" #include "../../../data/dynamic.hpp" +#include "api_lua.hpp" static int l_json_stringify(lua::State* L) { auto value = lua::tovalue(L, 1); @@ -21,8 +20,7 @@ static int l_json_parse(lua::State* L) { return lua::pushvalue(L, element); } -const luaL_Reg jsonlib [] = { +const luaL_Reg jsonlib[] = { {"tostring", lua::wrap}, {"parse", lua::wrap}, - {NULL, NULL} -}; + {NULL, NULL}}; diff --git a/src/logic/scripting/lua/libmat4.cpp b/src/logic/scripting/lua/libmat4.cpp index 9ab0dde2..44721ca6 100644 --- a/src/logic/scripting/lua/libmat4.cpp +++ b/src/logic/scripting/lua/libmat4.cpp @@ -1,7 +1,7 @@ -#include "api_lua.hpp" - #include +#include "api_lua.hpp" + #define GLM_ENABLE_EXPERIMENTAL #include #include @@ -32,10 +32,13 @@ static int l_determinant(lua::State* L) { } /// Overloads: -/// mat4.mul(m1: float[16], m2: float[16]) -> float[16] - creates matrix of m1 and m2 multiplication result -/// mat4.mul(m1: float[16], m2: float[16], dst: float[16]) -> float[16] - updates dst matrix with m1 and m2 multiplication result -/// mat4.mul(m1: float[16], v: float[3 or 4]) -> float[3 or 4] - creates vector of m1 and v multiplication result -/// mat4.mul(m1: float[16], v: float[3 or 4], dst: float[3 or 4]) -> float[3 or 4] - updates dst vector with m1 and v multiplication result +/// mat4.mul(m1: float[16], m2: float[16]) -> float[16] - creates matrix of m1 +/// and m2 multiplication result mat4.mul(m1: float[16], m2: float[16], dst: +/// float[16]) -> float[16] - updates dst matrix with m1 and m2 multiplication +/// result mat4.mul(m1: float[16], v: float[3 or 4]) -> float[3 or 4] - creates +/// vector of m1 and v multiplication result mat4.mul(m1: float[16], v: float[3 +/// or 4], dst: float[3 or 4]) -> float[3 or 4] - updates dst vector with m1 and +/// v multiplication result static int l_mul(lua::State* L) { uint argc = lua::check_argc(L, 2, 3); auto matrix1 = lua::tomat4(L, 1); @@ -46,17 +49,21 @@ static int l_mul(lua::State* L) { switch (argc) { case 2: { if (len2 == 4) { - return lua::pushvec4_stack(L, matrix1 * lua::tovec4(L, 2)); + return lua::pushvec4_stack(L, matrix1 * lua::tovec4(L, 2)); } else if (len2 == 3) { - return lua::pushvec3_stack(L, matrix1 * glm::vec4(lua::tovec3(L, 2), 1.0f)); + return lua::pushvec3_stack( + L, matrix1 * glm::vec4(lua::tovec3(L, 2), 1.0f) + ); } return lua::pushmat4(L, matrix1 * lua::tomat4(L, 2)); } case 3: { if (len2 == 4) { - return lua::setvec(L, 3, matrix1 * lua::tovec4(L, 2)); + return lua::setvec(L, 3, matrix1 * lua::tovec4(L, 2)); } else if (len2 == 3) { - return lua::setvec(L, 3, matrix1 * glm::vec4(lua::tovec3(L, 2), 1.0f)); + return lua::setvec( + L, 3, matrix1 * glm::vec4(lua::tovec3(L, 2), 1.0f) + ); } return lua::setmat4(L, 3, matrix1 * lua::tomat4(L, 2)); } @@ -66,9 +73,10 @@ static int l_mul(lua::State* L) { /// Overloads: /// mat4.(vec: float[3]) -> float[16] - creates transform matrix -/// mat4.(matrix: float[16], vec: float[3]) -> float[16] - creates transformed copy of matrix -/// mat4.(matrix: float[16], vec: float[3], dst: float[16]) -> sets dst to transformed version of matrix -template +/// mat4.(matrix: float[16], vec: float[3]) -> float[16] - creates +/// transformed copy of matrix mat4.(matrix: float[16], vec: float[3], +/// dst: float[16]) -> sets dst to transformed version of matrix +template inline int l_transform_func(lua::State* L) { uint argc = lua::gettop(L); switch (argc) { @@ -87,16 +95,20 @@ inline int l_transform_func(lua::State* L) { return lua::setmat4(L, 3, func(matrix, vec)); } default: { - throw std::runtime_error("invalid arguments number (1, 2 or 3 expected)"); + throw std::runtime_error( + "invalid arguments number (1, 2 or 3 expected)" + ); } } return 0; } /// Overloads: -/// mat4.rotate(vec: float[3], angle: float) -> float[16] - creates rotation matrix -/// mat4.rotate(matrix: float[16], vec: float[3], angle: float) -> float[16] - creates rotated copy of matrix -/// mat4.rotate(matrix: float[16], vec: float[3], angle: float, dst: float[16]) -> sets dst to rotated version of matrix +/// mat4.rotate(vec: float[3], angle: float) -> float[16] - creates rotation +/// matrix mat4.rotate(matrix: float[16], vec: float[3], angle: float) -> +/// float[16] - creates rotated copy of matrix mat4.rotate(matrix: float[16], +/// vec: float[3], angle: float, dst: float[16]) -> sets dst to rotated version +/// of matrix inline int l_rotate(lua::State* L) { uint argc = lua::gettop(L); switch (argc) { @@ -118,15 +130,18 @@ inline int l_rotate(lua::State* L) { return lua::setmat4(L, 4, glm::rotate(matrix, angle, vec)); } default: { - throw std::runtime_error("invalid arguments number (2, 3 or 4 expected)"); + throw std::runtime_error( + "invalid arguments number (2, 3 or 4 expected)" + ); } } return 0; } /// Overloads: -/// mat4.inverse(matrix: float[16]) -> float[16] - creates inversed version of the matrix -/// mat4.inverse(matrix: float[16], dst: float[16]) -> float[16] - updates dst matrix with inversed version of the matrix +/// mat4.inverse(matrix: float[16]) -> float[16] - creates inversed version of +/// the matrix mat4.inverse(matrix: float[16], dst: float[16]) -> float[16] - +/// updates dst matrix with inversed version of the matrix static int l_inverse(lua::State* L) { uint argc = lua::check_argc(L, 1, 2); auto matrix = lua::tomat4(L, 1); @@ -142,8 +157,9 @@ static int l_inverse(lua::State* L) { } /// Overloads: -/// mat4.transpose(matrix: float[16]) -> float[16] - creates transposed version of the matrix -/// mat4.transpose(matrix: float[16], dst: float[16]) -> float[16] - updates dst matrix with transposed version of the matrix +/// mat4.transpose(matrix: float[16]) -> float[16] - creates transposed version +/// of the matrix mat4.transpose(matrix: float[16], dst: float[16]) -> float[16] +/// - updates dst matrix with transposed version of the matrix static int l_transpose(lua::State* L) { uint argc = lua::check_argc(L, 1, 2); auto matrix = lua::tomat4(L, 1); @@ -174,15 +190,10 @@ static int l_decompose(lua::State* L) { glm::vec3 skew; glm::vec4 perspective; if (glm::decompose( - matrix, - scale, - rotation, - translation, - skew, - perspective - )) { + matrix, scale, rotation, translation, skew, perspective + )) { lua::createtable(L, 0, 6); - + lua::pushvec3(L, scale); lua::setfield(L, "scale"); @@ -258,7 +269,7 @@ static int l_tostring(lua::State* L) { return lua::pushstring(L, ss.str()); } -const luaL_Reg mat4lib [] = { +const luaL_Reg mat4lib[] = { {"idt", lua::wrap}, {"mul", lua::wrap}, {"scale", lua::wrap>}, @@ -271,6 +282,4 @@ const luaL_Reg mat4lib [] = { {"look_at", lua::wrap}, {"from_quat", lua::wrap}, {"tostring", lua::wrap}, - {NULL, NULL} -}; - + {NULL, NULL}}; diff --git a/src/logic/scripting/lua/libpack.cpp b/src/logic/scripting/lua/libpack.cpp index f441e79f..b7a20ca5 100644 --- a/src/logic/scripting/lua/libpack.cpp +++ b/src/logic/scripting/lua/libpack.cpp @@ -1,29 +1,28 @@ -#include "api_lua.hpp" +#include +#include +#include +#include -#include "../../../engine.hpp" -#include "../../../content/Content.hpp" #include "../../../assets/AssetsLoader.hpp" -#include "../../../files/engine_paths.hpp" +#include "../../../content/Content.hpp" +#include "../../../engine.hpp" #include "../../../files/WorldFiles.hpp" +#include "../../../files/engine_paths.hpp" #include "../../../world/Level.hpp" #include "../../../world/World.hpp" - -#include -#include -#include -#include +#include "api_lua.hpp" using namespace scripting; static int l_pack_get_folder(lua::State* L) { std::string packName = lua::tostring(L, 1); if (packName == "core") { - auto folder = engine->getPaths()->getResources().u8string()+"/"; + auto folder = engine->getPaths()->getResources().u8string() + "/"; return lua::pushstring(L, folder); } for (auto& pack : engine->getContentPacks()) { if (pack.id == packName) { - return lua::pushstring(L, pack.folder.u8string()+"/"); + return lua::pushstring(L, pack.folder.u8string() + "/"); } } return lua::pushstring(L, ""); @@ -54,7 +53,7 @@ static int l_pack_get_available(lua::State* L) { manager.exclude(pack.id); } auto names = manager.getAllNames(); - + lua::createtable(L, names.size(), 0); for (size_t i = 0; i < names.size(); i++) { lua::pushstring(L, names[i]); @@ -63,7 +62,9 @@ static int l_pack_get_available(lua::State* L) { return 1; } -static int l_pack_get_info(lua::State* L, const ContentPack& pack, const Content* content) { +static int l_pack_get_info( + lua::State* L, const ContentPack& pack, const Content* content +) { lua::createtable(L, 0, 5); lua::pushstring(L, pack.id); @@ -82,10 +83,10 @@ static int l_pack_get_info(lua::State* L, const ContentPack& pack, const Content lua::setfield(L, "version"); auto assets = engine->getAssets(); - std::string icon = pack.id+".icon"; - if (!AssetsLoader::loadExternalTexture(assets, icon, { - pack.folder/fs::path("icon.png") - })) { + std::string icon = pack.id + ".icon"; + if (!AssetsLoader::loadExternalTexture( + assets, icon, {pack.folder / fs::path("icon.png")} + )) { icon = "gui/no_icon"; } @@ -98,13 +99,20 @@ static int l_pack_get_info(lua::State* L, const ContentPack& pack, const Content auto& dpack = pack.dependencies[i]; std::string prefix; switch (dpack.level) { - case DependencyLevel::required: prefix = "!"; break; - case DependencyLevel::optional: prefix = "?"; break; - case DependencyLevel::weak: prefix = "~"; break; - default: throw std::runtime_error(""); + case DependencyLevel::required: + prefix = "!"; + break; + case DependencyLevel::optional: + prefix = "?"; + break; + case DependencyLevel::weak: + prefix = "~"; + break; + default: + throw std::runtime_error(""); } lua::pushfstring(L, "%s%s", prefix.c_str(), dpack.id.c_str()); - lua::rawseti(L, i+1); + lua::rawseti(L, i + 1); } lua::setfield(L, "dependencies"); } @@ -126,12 +134,13 @@ static int l_pack_get_info(lua::State* L, const ContentPack& pack, const Content /// } or nil static int l_pack_get_info(lua::State* L) { auto packid = lua::tostring(L, 1); - + auto content = engine->getContent(); auto& packs = engine->getContentPacks(); - auto found = std::find_if(packs.begin(), packs.end(), [packid](const auto& pack) { - return pack.id == packid; - }); + auto found = + std::find_if(packs.begin(), packs.end(), [packid](const auto& pack) { + return pack.id == packid; + }); if (found == packs.end()) { // TODO: optimize fs::path worldFolder(""); @@ -160,11 +169,10 @@ static int l_pack_get_base_packs(lua::State* L) { return 1; } -const luaL_Reg packlib [] = { +const luaL_Reg packlib[] = { {"get_folder", lua::wrap}, {"get_installed", lua::wrap}, {"get_available", lua::wrap}, {"get_info", lua::wrap}, {"get_base_packs", lua::wrap}, - {NULL, NULL} -}; + {NULL, NULL}}; diff --git a/src/logic/scripting/lua/libplayer.cpp b/src/logic/scripting/lua/libplayer.cpp index 492c72da..d11e7d35 100644 --- a/src/logic/scripting/lua/libplayer.cpp +++ b/src/logic/scripting/lua/libplayer.cpp @@ -1,14 +1,13 @@ -#include "libentity.hpp" +#include +#include -#include "../../../world/Level.hpp" -#include "../../../objects/Player.hpp" +#include "../../../items/Inventory.hpp" #include "../../../objects/Entities.hpp" +#include "../../../objects/Player.hpp" #include "../../../physics/Hitbox.hpp" #include "../../../window/Camera.hpp" -#include "../../../items/Inventory.hpp" - -#include -#include +#include "../../../world/Level.hpp" +#include "libentity.hpp" using namespace scripting; @@ -41,7 +40,7 @@ static int l_get_vel(lua::State* L) { return lua::pushvec3_stack(L, hitbox->velocity); } } - return 0; + return 0; } static int l_set_vel(lua::State* L) { @@ -155,7 +154,6 @@ static int l_get_spawnpoint(lua::State* L) { return 0; } - static int l_set_spawnpoint(lua::State* L) { auto player = get_player(L, 1); @@ -193,7 +191,8 @@ static int l_get_camera(lua::State* L) { return 0; } auto found = std::find( - level->cameras.begin(), level->cameras.end(), player->currentCamera); + level->cameras.begin(), level->cameras.end(), player->currentCamera + ); if (found == level->cameras.end()) { return 0; } @@ -210,7 +209,7 @@ static int l_set_camera(lua::State* L) { return 0; } -const luaL_Reg playerlib [] = { +const luaL_Reg playerlib[] = { {"get_pos", lua::wrap}, {"set_pos", lua::wrap}, {"get_vel", lua::wrap}, @@ -231,5 +230,4 @@ const luaL_Reg playerlib [] = { {"set_entity", lua::wrap}, {"get_camera", lua::wrap}, {"set_camera", lua::wrap}, - {NULL, NULL} -}; + {NULL, NULL}}; diff --git a/src/logic/scripting/lua/libquat.cpp b/src/logic/scripting/lua/libquat.cpp index b2abb4c5..49aebce2 100644 --- a/src/logic/scripting/lua/libquat.cpp +++ b/src/logic/scripting/lua/libquat.cpp @@ -32,7 +32,8 @@ static int l_tostring(lua::State* L) { auto quat = lua::toquat(L, 1); std::stringstream ss; - ss << "quat" << "{"; + ss << "quat" + << "{"; for (int i = 0; i < 4; i++) { if (i > 0) { ss << ", "; @@ -43,9 +44,8 @@ static int l_tostring(lua::State* L) { return lua::pushstring(L, ss.str()); } -const luaL_Reg quatlib [] = { +const luaL_Reg quatlib[] = { {"from_mat4", lua::wrap}, {"slerp", lua::wrap}, {"tostring", lua::wrap}, - {NULL, NULL} -}; + {NULL, NULL}}; diff --git a/src/logic/scripting/lua/libtime.cpp b/src/logic/scripting/lua/libtime.cpp index c1f770e0..29c501d3 100644 --- a/src/logic/scripting/lua/libtime.cpp +++ b/src/logic/scripting/lua/libtime.cpp @@ -1,7 +1,6 @@ -#include "api_lua.hpp" - #include "../../../engine.hpp" #include "../../../window/Window.hpp" +#include "api_lua.hpp" static int l_time_uptime(lua::State* L) { return lua::pushnumber(L, Window::time()); @@ -11,8 +10,7 @@ static int l_time_delta(lua::State* L) { return lua::pushnumber(L, scripting::engine->getDelta()); } -const luaL_Reg timelib [] = { +const luaL_Reg timelib[] = { {"uptime", lua::wrap}, {"delta", lua::wrap}, - {NULL, NULL} -}; + {NULL, NULL}}; diff --git a/src/logic/scripting/lua/libtoml.cpp b/src/logic/scripting/lua/libtoml.cpp index 7fbe2302..5b3c0162 100644 --- a/src/logic/scripting/lua/libtoml.cpp +++ b/src/logic/scripting/lua/libtoml.cpp @@ -1,7 +1,6 @@ -#include "api_lua.hpp" - #include "../../../coders/toml.hpp" #include "../../../data/dynamic.hpp" +#include "api_lua.hpp" using namespace scripting; @@ -23,8 +22,7 @@ static int l_toml_parse(lua::State* L) { return lua::pushvalue(L, *value); } -const luaL_Reg tomllib [] = { +const luaL_Reg tomllib[] = { {"tostring", lua::wrap}, {"parse", lua::wrap}, - {NULL, NULL} -}; + {NULL, NULL}}; diff --git a/src/logic/scripting/lua/libvecn.cpp b/src/logic/scripting/lua/libvecn.cpp index fc69ad75..724885fe 100644 --- a/src/logic/scripting/lua/libvecn.cpp +++ b/src/logic/scripting/lua/libvecn.cpp @@ -1,11 +1,12 @@ -#include "api_lua.hpp" - -#include +#define GLM_ENABLE_EXPERIMENTAL #include #include #include +#include -template +#include "api_lua.hpp" + +template inline T angle(glm::vec<2, T> vec) { auto val = std::atan2(vec.y, vec.x); if (val < 0.0) { @@ -14,19 +15,19 @@ inline T angle(glm::vec<2, T> vec) { return val; } -template class Op> +template class Op> static int l_binop(lua::State* L) { uint argc = lua::check_argc(L, 2, 3); auto a = lua::tovec(L, 1); - if (lua::isnumber(L, 2)) { // scalar second operand overload + if (lua::isnumber(L, 2)) { // scalar second operand overload auto b = lua::tonumber(L, 2); Op op; if (argc == 2) { lua::createtable(L, n, 0); for (uint i = 0; i < n; i++) { lua::pushnumber(L, op(a[i], b)); - lua::rawseti(L, i+1); + lua::rawseti(L, i + 1); } return 1; } else { @@ -39,7 +40,7 @@ static int l_binop(lua::State* L) { lua::createtable(L, n, 0); for (uint i = 0; i < n; i++) { lua::pushnumber(L, op(a[i], b[i])); - lua::rawseti(L, i+1); + lua::rawseti(L, i + 1); } return 1; } else { @@ -48,7 +49,7 @@ static int l_binop(lua::State* L) { } } -template(*func)(const glm::vec&)> +template (*func)(const glm::vec&)> static int l_unaryop(lua::State* L) { uint argc = lua::check_argc(L, 1, 2); auto vec = func(lua::tovec(L, 1)); @@ -57,7 +58,7 @@ static int l_unaryop(lua::State* L) { lua::createtable(L, n, 0); for (uint i = 0; i < n; i++) { lua::pushnumber(L, vec[i]); - lua::rawseti(L, i+1); + lua::rawseti(L, i + 1); } return 1; case 2: @@ -66,25 +67,25 @@ static int l_unaryop(lua::State* L) { return 0; } -template&)> +template &)> static int l_scalar_op(lua::State* L) { lua::check_argc(L, 1); auto vec = lua::tovec(L, 1); return lua::pushnumber(L, func(vec)); } -template +template static int l_pow(lua::State* L) { uint argc = lua::check_argc(L, 2, 3); auto a = lua::tovec(L, 1); - if (lua::isnumber(L, 2)) { + if (lua::isnumber(L, 2)) { auto b = lua::tonumber(L, 2); if (argc == 2) { lua::createtable(L, n, 0); for (uint i = 0; i < n; i++) { lua::pushnumber(L, pow(a[i], b)); - lua::rawseti(L, i+1); + lua::rawseti(L, i + 1); } return 1; } else { @@ -96,7 +97,7 @@ static int l_pow(lua::State* L) { lua::createtable(L, n, 0); for (uint i = 0; i < n; i++) { lua::pushnumber(L, pow(a[i], b[i])); - lua::rawseti(L, i+1); + lua::rawseti(L, i + 1); } return 1; } else { @@ -105,7 +106,7 @@ static int l_pow(lua::State* L) { } } -template +template static int l_dot(lua::State* L) { lua::check_argc(L, 2); const auto& a = lua::tovec(L, 1); @@ -113,7 +114,7 @@ static int l_dot(lua::State* L) { return lua::pushnumber(L, glm::dot(a, b)); } -template +template static int l_inverse(lua::State* L) { uint argc = lua::check_argc(L, 1, 2); auto vec = lua::tovec(L, 1); @@ -121,8 +122,8 @@ static int l_inverse(lua::State* L) { case 1: lua::createtable(L, n, 0); for (uint i = 0; i < n; i++) { - lua::pushnumber(L, (-1)*vec[i]); - lua::rawseti(L, i+1); + lua::pushnumber(L, (-1) * vec[i]); + lua::rawseti(L, i + 1); } return 1; case 2: @@ -137,8 +138,11 @@ static int l_spherical_rand(lua::State* L) { case 1: return lua::pushvec3(L, glm::sphericalRand(lua::tonumber(L, 1))); case 2: - return lua::setvec(L, 2, - glm::sphericalRand(static_cast(lua::tonumber(L, 1)))); + return lua::setvec( + L, + 2, + glm::sphericalRand(static_cast(lua::tonumber(L, 1))) + ); } return 0; } @@ -148,12 +152,16 @@ static int l_vec2_angle(lua::State* L) { if (argc == 1) { return lua::pushnumber(L, glm::degrees(angle(lua::tovec2(L, 1)))); } else { - return lua::pushnumber(L, glm::degrees(angle( - glm::vec2(lua::tonumber(L, 1), lua::tonumber(L, 2))))); + return lua::pushnumber( + L, + glm::degrees( + angle(glm::vec2(lua::tonumber(L, 1), lua::tonumber(L, 2))) + ) + ); } } -template +template static int l_tostring(lua::State* L) { lua::check_argc(L, 1); auto vec = lua::tovec(L, 1); @@ -169,7 +177,7 @@ static int l_tostring(lua::State* L) { return lua::pushstring(L, ss.str()); } -const luaL_Reg vec2lib [] = { +const luaL_Reg vec2lib[] = { {"add", lua::wrap>}, {"sub", lua::wrap>}, {"mul", lua::wrap>}, @@ -183,10 +191,9 @@ const luaL_Reg vec2lib [] = { {"pow", lua::wrap>}, {"dot", lua::wrap>}, {"angle", lua::wrap}, - {NULL, NULL} -}; + {NULL, NULL}}; -const luaL_Reg vec3lib [] = { +const luaL_Reg vec3lib[] = { {"add", lua::wrap>}, {"sub", lua::wrap>}, {"mul", lua::wrap>}, @@ -200,10 +207,9 @@ const luaL_Reg vec3lib [] = { {"pow", lua::wrap>}, {"dot", lua::wrap>}, {"spherical_rand", lua::wrap}, - {NULL, NULL} -}; + {NULL, NULL}}; -const luaL_Reg vec4lib [] = { +const luaL_Reg vec4lib[] = { {"add", lua::wrap>}, {"sub", lua::wrap>}, {"mul", lua::wrap>}, @@ -216,5 +222,4 @@ const luaL_Reg vec4lib [] = { {"inverse", lua::wrap>}, {"pow", lua::wrap>}, {"dot", lua::wrap>}, - {NULL, NULL} -}; + {NULL, NULL}}; diff --git a/src/logic/scripting/lua/libworld.cpp b/src/logic/scripting/lua/libworld.cpp index e7d24005..38ad347f 100644 --- a/src/logic/scripting/lua/libworld.cpp +++ b/src/logic/scripting/lua/libworld.cpp @@ -1,14 +1,13 @@ -#include "api_lua.hpp" +#include +#include #include "../../../assets/Assets.hpp" #include "../../../assets/AssetsLoader.hpp" +#include "../../../engine.hpp" #include "../../../files/engine_paths.hpp" #include "../../../world/Level.hpp" #include "../../../world/World.hpp" -#include "../../../engine.hpp" - -#include -#include +#include "api_lua.hpp" using namespace scripting; namespace fs = std::filesystem; @@ -20,17 +19,19 @@ static int l_world_get_list(lua::State* L) { lua::createtable(L, worlds.size(), 0); for (size_t i = 0; i < worlds.size(); i++) { lua::createtable(L, 0, 1); - + auto name = worlds[i].filename().u8string(); lua::pushstring(L, name); lua::setfield(L, "name"); - + auto assets = engine->getAssets(); - std::string icon = "world#"+name+".icon"; - if (!AssetsLoader::loadExternalTexture(assets, icon, { - worlds[i]/fs::path("icon.png"), - worlds[i]/fs::path("preview.png") - })) { + std::string icon = "world#" + name + ".icon"; + if (!AssetsLoader::loadExternalTexture( + assets, + icon, + {worlds[i] / fs::path("icon.png"), + worlds[i] / fs::path("preview.png")} + )) { icon = "gui/no_world_icon"; } lua::pushstring(L, icon); @@ -84,7 +85,7 @@ static int l_world_is_night(lua::State* L) { return lua::pushboolean(L, daytime < 0.2 || daytime > 0.8); } -const luaL_Reg worldlib [] = { +const luaL_Reg worldlib[] = { {"get_list", lua::wrap}, {"get_total_time", lua::wrap}, {"get_day_time", lua::wrap}, @@ -95,5 +96,4 @@ const luaL_Reg worldlib [] = { {"is_day", lua::wrap}, {"is_night", lua::wrap}, {"exists", lua::wrap}, - {NULL, NULL} -}; + {NULL, NULL}}; diff --git a/src/logic/scripting/lua/lua_commons.hpp b/src/logic/scripting/lua/lua_commons.hpp index 9b8478c8..8e82899c 100644 --- a/src/logic/scripting/lua/lua_commons.hpp +++ b/src/logic/scripting/lua/lua_commons.hpp @@ -4,16 +4,16 @@ #include "../../../delegates.hpp" #include "../scripting.hpp" -#ifdef __linux__ +#ifdef __linux__ #include + #include #else #include #endif #include - -#include #include +#include #ifndef LUAJIT_VERSION #error LuaJIT required @@ -32,4 +32,4 @@ namespace lua { using Integer = lua_Integer; } -#endif // LOGIC_SCRIPTING_LUA_HPP_ +#endif // LOGIC_SCRIPTING_LUA_HPP_ diff --git a/src/logic/scripting/lua/lua_custom_types.cpp b/src/logic/scripting/lua/lua_custom_types.cpp index 2983e1b1..8ee90d92 100644 --- a/src/logic/scripting/lua/lua_custom_types.cpp +++ b/src/logic/scripting/lua/lua_custom_types.cpp @@ -1,14 +1,12 @@ #include "lua_custom_types.hpp" -#include "lua_util.hpp" - #include +#include "lua_util.hpp" + using namespace lua; - -Bytearray::Bytearray(size_t capacity) - : buffer(capacity) { +Bytearray::Bytearray(size_t capacity) : buffer(capacity) { buffer.resize(capacity); } @@ -32,7 +30,7 @@ static int l_bytearray_insert(lua::State* L) { return 0; } auto& data = buffer->data(); - auto index = tointeger(L, 2)-1; + auto index = tointeger(L, 2) - 1; if (static_cast(index) > data.size()) { return 0; } @@ -47,11 +45,11 @@ static int l_bytearray_remove(lua::State* L) { return 0; } auto& data = buffer->data(); - auto index = tointeger(L, 2)-1; + auto index = tointeger(L, 2) - 1; if (static_cast(index) > data.size()) { return 0; } - data.erase(data.begin()+index); + data.erase(data.begin() + index); return 0; } @@ -67,7 +65,7 @@ static int l_bytearray_meta_meta_call(lua::State* L) { std::vector buffer(len); buffer.resize(len); for (size_t i = 0; i < len; i++) { - rawgeti(L, i+1); + rawgeti(L, i + 1); buffer[i] = static_cast(tointeger(L, -1)); pop(L); } @@ -92,7 +90,7 @@ static int l_bytearray_meta_index(lua::State* L) { return pushcfunction(L, found->second); } } - auto index = tointeger(L, 2)-1; + auto index = tointeger(L, 2) - 1; if (static_cast(index) > data.size()) { return 0; } @@ -105,7 +103,7 @@ static int l_bytearray_meta_newindex(lua::State* L) { return 0; } auto& data = buffer->data(); - auto index = static_cast(tointeger(L, 2)-1); + auto index = static_cast(tointeger(L, 2) - 1); auto value = tointeger(L, 3); if (index >= data.size()) { if (index == data.size()) { @@ -131,7 +129,9 @@ static int l_bytearray_meta_tostring(lua::State* L) { } auto& data = buffer->data(); if (data.size() > 512) { - return pushstring(L, "bytearray["+std::to_string(data.size())+"]{...}"); + return pushstring( + L, "bytearray[" + std::to_string(data.size()) + "]{...}" + ); } else { std::stringstream ss; ss << "bytearray[" << std::to_string(data.size()) << "]{"; diff --git a/src/logic/scripting/lua/lua_custom_types.hpp b/src/logic/scripting/lua/lua_custom_types.hpp index c69bd2b0..a3f9427b 100644 --- a/src/logic/scripting/lua/lua_custom_types.hpp +++ b/src/logic/scripting/lua/lua_custom_types.hpp @@ -1,11 +1,11 @@ #ifndef LOGIC_SCRIPTING_LUA_LUA_CUSTOM_TYPES_HPP_ #define LOGIC_SCRIPTING_LUA_LUA_CUSTOM_TYPES_HPP_ -#include "lua_commons.hpp" - #include #include +#include "lua_commons.hpp" + namespace lua { class Userdata { public: @@ -19,7 +19,7 @@ namespace lua { Bytearray(size_t capacity); Bytearray(std::vector buffer); virtual ~Bytearray(); - + const std::string& getTypeName() const override { return TYPENAME; } @@ -32,4 +32,4 @@ namespace lua { }; } -#endif // LOGIC_SCRIPTING_LUA_LUA_CUSTOM_TYPES_HPP_ +#endif // LOGIC_SCRIPTING_LUA_LUA_CUSTOM_TYPES_HPP_ diff --git a/src/logic/scripting/lua/lua_engine.cpp b/src/logic/scripting/lua/lua_engine.cpp index f3852c30..fa83b0a1 100644 --- a/src/logic/scripting/lua/lua_engine.cpp +++ b/src/logic/scripting/lua/lua_engine.cpp @@ -1,13 +1,13 @@ #include "lua_engine.hpp" -#include "api_lua.hpp" -#include "lua_custom_types.hpp" -#include "../../../debug/Logger.hpp" -#include "../../../util/stringutil.hpp" - #include #include +#include "../../../debug/Logger.hpp" +#include "../../../util/stringutil.hpp" +#include "api_lua.hpp" +#include "lua_custom_types.hpp" + static debug::Logger logger("lua-state"); static lua::State* main_thread = nullptr; @@ -16,7 +16,9 @@ using namespace lua; luaerror::luaerror(const std::string& message) : std::runtime_error(message) { } -static void remove_lib_funcs(lua::State* L, const char* libname, const char* funcs[]) { +static void remove_lib_funcs( + lua::State* L, const char* libname, const char* funcs[] +) { if (getglobal(L, libname)) { for (uint i = 0; funcs[i]; i++) { pushnil(L); @@ -78,14 +80,7 @@ void lua::initialize() { pop(L, luaopen_bit(L)); pop(L, luaopen_os(L)); const char* removed_os[] { - "execute", - "exit", - "remove", - "rename", - "setlocale", - "tmpname", - nullptr - }; + "execute", "exit", "remove", "rename", "setlocale", "tmpname", nullptr}; remove_lib_funcs(L, "os", removed_os); create_libs(L); @@ -107,7 +102,9 @@ void lua::finalize() { lua_close(main_thread); } -bool lua::emit_event(lua::State* L, const std::string &name, std::function args) { +bool lua::emit_event( + lua::State* L, const std::string& name, std::function args +) { getglobal(L, "events"); getfield(L, "emit"); pushstring(L, name); diff --git a/src/logic/scripting/lua/lua_engine.hpp b/src/logic/scripting/lua/lua_engine.hpp index dae3c4b0..a21d4292 100644 --- a/src/logic/scripting/lua/lua_engine.hpp +++ b/src/logic/scripting/lua/lua_engine.hpp @@ -1,21 +1,24 @@ #ifndef LOGIC_SCRIPTING_LUA_STATE_HPP_ #define LOGIC_SCRIPTING_LUA_STATE_HPP_ -#include "lua_util.hpp" +#include +#include -#include "../scripting_functional.hpp" #include "../../../data/dynamic.hpp" #include "../../../delegates.hpp" - -#include -#include +#include "../scripting_functional.hpp" +#include "lua_util.hpp" namespace lua { void initialize(); void finalize(); - bool emit_event(lua::State*, const std::string& name, std::function args=[](auto*){return 0;}); + bool emit_event( + lua::State*, + const std::string& name, + std::function args = [](auto*) { return 0; } + ); lua::State* get_main_thread(); } -#endif // LOGIC_SCRIPTING_LUA_STATE_HPP_ +#endif // LOGIC_SCRIPTING_LUA_STATE_HPP_ diff --git a/src/logic/scripting/lua/lua_extensions.cpp b/src/logic/scripting/lua/lua_extensions.cpp index 6b3a1397..df88b3dd 100644 --- a/src/logic/scripting/lua/lua_extensions.cpp +++ b/src/logic/scripting/lua/lua_extensions.cpp @@ -1,6 +1,5 @@ -#include "api_lua.hpp" - #include "../../../debug/Logger.hpp" +#include "api_lua.hpp" static debug::Logger logger("lua-debug"); @@ -24,7 +23,6 @@ static int l_debug_log(lua::State* L) { void initialize_libs_extends(lua::State* L) { if (lua::getglobal(L, "debug")) { - lua::pushcfunction(L, lua::wrap); lua::setfield(L, "error"); diff --git a/src/logic/scripting/lua/lua_overrides.cpp b/src/logic/scripting/lua/lua_overrides.cpp index 4e72882c..8233d95a 100644 --- a/src/logic/scripting/lua/lua_overrides.cpp +++ b/src/logic/scripting/lua/lua_overrides.cpp @@ -1,25 +1,25 @@ -#include "api_lua.hpp" - #include +#include "api_lua.hpp" + /// @brief Modified version of luaB_print from lbaselib.c int l_print(lua::State* L) { - int n = lua::gettop(L); /* number of arguments */ + int n = lua::gettop(L); /* number of arguments */ lua::getglobal(L, "tostring"); - for (int i=1; i<=n; i++) { - lua::pushvalue(L, -1); /* function to be called */ - lua::pushvalue(L, i); /* value to print */ + for (int i = 1; i <= n; i++) { + lua::pushvalue(L, -1); /* function to be called */ + lua::pushvalue(L, i); /* value to print */ lua::call(L, 1, 1); - const char* s = lua::tostring(L, -1); /* get result */ + const char* s = lua::tostring(L, -1); /* get result */ if (s == NULL) - return luaL_error(L, LUA_QL("tostring") " must return a string to " - LUA_QL("print")); - if (i > 1) - std::cout << "\t"; + return luaL_error( + L, + LUA_QL("tostring") " must return a string to " LUA_QL("print") + ); + if (i > 1) std::cout << "\t"; std::cout << s; - lua::pop(L); /* pop result */ + lua::pop(L); /* pop result */ } std::cout << std::endl; return 0; } - diff --git a/src/logic/scripting/lua/lua_util.cpp b/src/logic/scripting/lua/lua_util.cpp index 25ddce9d..50069cad 100644 --- a/src/logic/scripting/lua/lua_util.cpp +++ b/src/logic/scripting/lua/lua_util.cpp @@ -1,9 +1,9 @@ #include "lua_util.hpp" -#include "../../../util/stringutil.hpp" - -#include #include +#include + +#include "../../../util/stringutil.hpp" using namespace lua; @@ -19,7 +19,7 @@ int lua::userdata_destructor(lua::State* L) { } std::string lua::env_name(int env) { - return "_ENV"+util::mangleid(env); + return "_ENV" + util::mangleid(env); } int lua::pushvalue(State* L, const dynamic::Value& value) { @@ -38,7 +38,7 @@ int lua::pushvalue(State* L, const dynamic::Value& value) { createtable(L, list->size(), 0); for (size_t i = 0; i < list->size(); i++) { pushvalue(L, list->get(i)); - rawseti(L, i+1); + rawseti(L, i + 1); } } else if (auto mapptr = std::get_if(&value)) { auto map = *mapptr; @@ -80,8 +80,11 @@ dynamic::Value lua::tovalue(State* L, int idx) { } } case LUA_TFUNCTION: - return "(lua_topointer(L, idx)))+">"; + return "(lua_topointer(L, idx)) + ) + + ">"; case LUA_TSTRING: return std::string(tostring(L, idx)); case LUA_TTABLE: { @@ -112,19 +115,20 @@ dynamic::Value lua::tovalue(State* L, int idx) { } default: throw std::runtime_error( - "lua type "+std::string(lua_typename(L, type))+" is not supported" + "lua type " + std::string(lua_typename(L, type)) + + " is not supported" ); } } static int l_error_handler(lua_State* L) { - if (!isstring(L, 1)) { // 'message' not a string? - return 1; // keep it intact + if (!isstring(L, 1)) { // 'message' not a string? + return 1; // keep it intact } if (get_from(L, "debug", "traceback")) { - lua_pushvalue(L, 1); // pass error message - lua_pushinteger(L, 2); // skip this function and traceback - lua_call(L, 2, 1); // call debug.traceback + lua_pushvalue(L, 1); // pass error message + lua_pushinteger(L, 2); // skip this function and traceback + lua_call(L, 2, 1); // call debug.traceback } return 1; } @@ -160,7 +164,8 @@ int lua::call_nothrow(State* L, int argc, int nresults) { void lua::dump_stack(State* L) { int top = gettop(L); for (int i = 1; i <= top; i++) { - std::cout << std::setw(3) << i << std::setw(20) << luaL_typename(L, i) << std::setw(30); + std::cout << std::setw(3) << i << std::setw(20) << luaL_typename(L, i) + << std::setw(30); switch (lua::type(L, i)) { case LUA_TNUMBER: std::cout << tonumber(L, i); @@ -190,13 +195,16 @@ static std::shared_ptr create_lambda_handler(State* L) { setfield(L, name); pop(L, 2); - return std::shared_ptr(new std::string(name), [=](std::string* name) { - getglobal(L, LAMBDAS_TABLE); - pushnil(L); - setfield(L, *name); - pop(L); - delete name; - }); + return std::shared_ptr( + new std::string(name), + [=](std::string* name) { + getglobal(L, LAMBDAS_TABLE); + pushnil(L); + setfield(L, *name); + pop(L); + delete name; + } + ); } runnable lua::create_runnable(State* L) { @@ -231,7 +239,7 @@ int lua::create_environment(State* L, int parent) { // local env = {} createtable(L, 0, 1); - + // setmetatable(env, {__index=_G}) createtable(L, 0, 1); if (parent == 0) { @@ -249,7 +257,6 @@ int lua::create_environment(State* L, int parent) { return id; } - void lua::removeEnvironment(State* L, int id) { if (id == 0) { return; diff --git a/src/logic/scripting/lua/lua_util.hpp b/src/logic/scripting/lua/lua_util.hpp index 973dfc30..aa111bb1 100644 --- a/src/logic/scripting/lua/lua_util.hpp +++ b/src/logic/scripting/lua/lua_util.hpp @@ -1,31 +1,32 @@ #ifndef LOGIC_SCRIPTING_LUA_UTIL_HPP_ #define LOGIC_SCRIPTING_LUA_UTIL_HPP_ -#include "lua_commons.hpp" -#include "lua_custom_types.hpp" - -#include #include #include +#include + +#include "lua_commons.hpp" +#include "lua_custom_types.hpp" #define GLM_ENABLE_EXPERIMENTAL #include // NOTE: const std::string& used instead of string_view because c_str() needed namespace lua { - inline std::string LAMBDAS_TABLE = "$L"; // lambdas storage - inline std::string CHUNKS_TABLE = "$C"; // precompiled lua chunks + inline std::string LAMBDAS_TABLE = "$L"; // lambdas storage + inline std::string CHUNKS_TABLE = "$C"; // precompiled lua chunks extern std::unordered_map usertypeNames; int userdata_destructor(lua::State* L); std::string env_name(int env); - template int wrap(lua_State *L) { + template + int wrap(lua_State* L) { int result = 0; try { result = func(L); } // transform exception with description into lua_error - catch (std::exception &e) { + catch (std::exception& e) { luaL_error(L, e.what()); } // Rethrow any other exception (lua error for example) @@ -35,7 +36,7 @@ namespace lua { return result; } - inline void pop(lua::State* L, int n=1) { + inline void pop(lua::State* L, int n = 1) { lua_pop(L, n); } inline void insert(lua::State* L, int idx) { @@ -59,15 +60,15 @@ namespace lua { inline const char* type_name(lua::State* L, int idx) { return lua_typename(L, idx); } - inline int rawget(lua::State* L, int idx=-2) { + inline int rawget(lua::State* L, int idx = -2) { lua_rawget(L, idx); return 1; } - inline int rawgeti(lua::State* L, int n, int idx=-1) { + inline int rawgeti(lua::State* L, int n, int idx = -1) { lua_rawgeti(L, idx, n); return 1; } - inline void rawseti(lua::State* L, int n, int idx=-2) { + inline void rawseti(lua::State* L, int n, int idx = -2) { lua_rawseti(L, idx, n); } @@ -93,7 +94,7 @@ namespace lua { if (getglobal(L, name)) { return 1; } else { - throw std::runtime_error("global name "+name+" not found"); + throw std::runtime_error("global name " + name + " not found"); } } @@ -124,27 +125,29 @@ namespace lua { return 1; } - template + template inline int pushvec(lua::State* L, glm::vec vec) { createtable(L, n, 0); for (int i = 0; i < n; i++) { pushnumber(L, vec[i]); - rawseti(L, i+1); + rawseti(L, i + 1); } return 1; } - template + template inline int pushivec(lua::State* L, glm::vec vec) { createtable(L, n, 0); for (int i = 0; i < n; i++) { pushinteger(L, vec[i]); - rawseti(L, i+1); + rawseti(L, i + 1); } return 1; } - inline int pushivec3_stack(lua::State* L, lua::Integer x, lua::Integer y, lua::Integer z) { + inline int pushivec3_stack( + lua::State* L, lua::Integer x, lua::Integer y, lua::Integer z + ) { pushinteger(L, x); pushinteger(L, y); pushinteger(L, z); @@ -172,7 +175,7 @@ namespace lua { return 4; } - inline void setmetatable(lua::State* L, int idx=-2) { + inline void setmetatable(lua::State* L, int idx = -2) { lua_setmetatable(L, idx); } inline int pushvalue(lua::State* L, int idx) { @@ -191,14 +194,14 @@ namespace lua { return pushvec(L, vec); } inline int pushcolor(lua::State* L, glm::vec4 vec) { - return pushivec(L, glm::ivec4(vec*255.0f)); + return pushivec(L, glm::ivec4(vec * 255.0f)); } inline int pushquat(lua::State* L, glm::quat quat) { createtable(L, 4, 0); for (size_t i = 0; i < 4; i++) { pushnumber(L, quat[i]); - rawseti(L, i+1); + rawseti(L, i + 1); } return 1; } @@ -206,7 +209,7 @@ namespace lua { pushvalue(L, idx); for (int i = 0; i < 4; i++) { pushnumber(L, quat[i]); - rawseti(L, i+1); + rawseti(L, i + 1); } return 1; } @@ -216,29 +219,29 @@ namespace lua { for (uint x = 0; x < 4; x++) { uint i = y * 4 + x; pushnumber(L, matrix[y][x]); - rawseti(L, i+1); + rawseti(L, i + 1); } } return 1; } - /// @brief pushes matrix table to the stack and updates it with glm matrix + /// @brief pushes matrix table to the stack and updates it with glm matrix inline int setmat4(lua::State* L, int idx, glm::mat4 matrix) { pushvalue(L, idx); for (uint y = 0; y < 4; y++) { for (uint x = 0; x < 4; x++) { uint i = y * 4 + x; pushnumber(L, matrix[y][x]); - rawseti(L, i+1); + rawseti(L, i + 1); } } return 1; } - template + template inline int setvec(lua::State* L, int idx, glm::vec vec) { pushvalue(L, idx); for (int i = 0; i < n; i++) { pushnumber(L, vec[i]); - rawseti(L, i+1); + rawseti(L, i + 1); } return 1; } @@ -251,8 +254,8 @@ namespace lua { return 1; } - template - inline int pushfstring(lua_State *L, const char * fmt, Args... args) { + template + inline int pushfstring(lua_State* L, const char* fmt, Args... args) { lua_pushfstring(L, fmt, args...); return 1; } @@ -287,7 +290,7 @@ namespace lua { inline bool isuserdata(lua::State* L, int idx) { return lua_isuserdata(L, idx); } - inline void setfield(lua::State* L, const std::string& name, int idx=-2) { + inline void setfield(lua::State* L, const std::string& name, int idx = -2) { lua_setfield(L, idx, name.c_str()); } inline bool toboolean(lua::State* L, int idx) { @@ -308,28 +311,30 @@ namespace lua { inline void setglobal(lua::State* L, const std::string& name) { lua_setglobal(L, name.c_str()); } - template + template inline T* touserdata(lua::State* L, int idx) { if (void* rawptr = lua_touserdata(L, idx)) { return static_cast(rawptr); } return nullptr; } - template + template inline int newuserdata(lua::State* L, Args&&... args) { const auto& found = usertypeNames.find(typeid(T)); void* ptr = lua_newuserdata(L, sizeof(T)); new (ptr) T(args...); if (found == usertypeNames.end()) { - log_error("usertype is not registred: "+std::string(typeid(T).name())); + log_error( + "usertype is not registred: " + std::string(typeid(T).name()) + ); } else if (getglobal(L, found->second)) { setmetatable(L); } return 1; } - template + template inline void newusertype(lua::State* L, const std::string& name) { usertypeNames[typeid(T)] = name; func(L); @@ -338,63 +343,74 @@ namespace lua { setfield(L, "__gc"); setglobal(L, name); - } + } - template - inline glm::vec tovec(lua::State* L, int idx) { + template + inline glm::vec tovec(lua::State* L, int idx) { pushvalue(L, idx); if (!istable(L, idx) || objlen(L, idx) < n) { - throw std::runtime_error("value must be an array of "+std::to_string(n)+" numbers"); + throw std::runtime_error( + "value must be an array of " + std::to_string(n) + " numbers" + ); } glm::vec vec; for (int i = 0; i < n; i++) { - rawgeti(L, i+1); - vec[i] = tonumber(L, -1); + rawgeti(L, i + 1); + vec[i] = tonumber(L, -1); pop(L); } pop(L); return vec; } - inline glm::vec2 tovec2(lua::State* L, int idx) { + inline glm::vec2 tovec2(lua::State* L, int idx) { pushvalue(L, idx); if (!istable(L, idx) || objlen(L, idx) < 2) { throw std::runtime_error("value must be an array of two numbers"); } rawgeti(L, 1); - auto x = tonumber(L, -1); pop(L); + auto x = tonumber(L, -1); + pop(L); rawgeti(L, 2); - auto y = tonumber(L, -1); pop(L); + auto y = tonumber(L, -1); + pop(L); pop(L); return glm::vec2(x, y); } - inline glm::vec3 tovec3(lua::State* L, int idx) { + inline glm::vec3 tovec3(lua::State* L, int idx) { pushvalue(L, idx); if (!istable(L, idx) || objlen(L, idx) < 3) { throw std::runtime_error("value must be an array of three numbers"); } rawgeti(L, 1); - auto x = tonumber(L, -1); pop(L); + auto x = tonumber(L, -1); + pop(L); rawgeti(L, 2); - auto y = tonumber(L, -1); pop(L); + auto y = tonumber(L, -1); + pop(L); rawgeti(L, 3); - auto z = tonumber(L, -1); pop(L); + auto z = tonumber(L, -1); + pop(L); pop(L); return glm::vec3(x, y, z); } - inline glm::vec4 tovec4(lua::State* L, int idx) { + inline glm::vec4 tovec4(lua::State* L, int idx) { pushvalue(L, idx); if (!istable(L, idx) || objlen(L, idx) < 4) { throw std::runtime_error("value must be an array of four numbers"); } rawgeti(L, 1); - auto x = tonumber(L, -1); pop(L); + auto x = tonumber(L, -1); + pop(L); rawgeti(L, 2); - auto y = tonumber(L, -1); pop(L); + auto y = tonumber(L, -1); + pop(L); rawgeti(L, 3); - auto z = tonumber(L, -1); pop(L); + auto z = tonumber(L, -1); + pop(L); rawgeti(L, 4); - auto w = tonumber(L, -1); pop(L); + auto w = tonumber(L, -1); + pop(L); pop(L); return glm::vec4(x, y, z, w); } @@ -405,25 +421,32 @@ namespace lua { throw std::runtime_error("value must be an array of four numbers"); } rawgeti(L, 1); - auto x = tonumber(L, -1); pop(L); + auto x = tonumber(L, -1); + pop(L); rawgeti(L, 2); - auto y = tonumber(L, -1); pop(L); + auto y = tonumber(L, -1); + pop(L); rawgeti(L, 3); - auto z = tonumber(L, -1); pop(L); + auto z = tonumber(L, -1); + pop(L); rawgeti(L, 4); - auto w = tonumber(L, -1); pop(L); + auto w = tonumber(L, -1); + pop(L); pop(L); return glm::quat(x, y, z, w); } - inline glm::vec3 tovec3_stack(lua::State* L, int idx) { + inline glm::vec3 tovec3_stack(lua::State* L, int idx) { return glm::vec3( - tonumber(L, idx), tonumber(L, idx+1), tonumber(L, idx+2) + tonumber(L, idx), tonumber(L, idx + 1), tonumber(L, idx + 2) ); } - inline glm::vec4 tovec4_stack(lua::State* L, int idx) { + inline glm::vec4 tovec4_stack(lua::State* L, int idx) { return glm::vec4( - tonumber(L, idx), tonumber(L, idx+1), tonumber(L, idx+2), tonumber(L, idx+3) + tonumber(L, idx), + tonumber(L, idx + 1), + tonumber(L, idx + 2), + tonumber(L, idx + 3) ); } inline glm::mat4 tomat4(lua::State* L, int idx) { @@ -435,7 +458,7 @@ namespace lua { for (uint y = 0; y < 4; y++) { for (uint x = 0; x < 4; x++) { uint i = y * 4 + x; - rawgeti(L, i+1); + rawgeti(L, i + 1); matrix[y][x] = static_cast(tonumber(L, -1)); pop(L); } @@ -450,21 +473,25 @@ namespace lua { throw std::runtime_error("RGBA array required"); } rawgeti(L, 1); - auto r = tonumber(L, -1); pop(L); - rawgeti(L, 2); - auto g = tonumber(L, -1); pop(L); - rawgeti(L, 3); - auto b = tonumber(L, -1); pop(L); - rawgeti(L, 4); - auto a = tonumber(L, -1); pop(L); + auto r = tonumber(L, -1); pop(L); - return glm::vec4(r/255, g/255, b/255, a/255); + rawgeti(L, 2); + auto g = tonumber(L, -1); + pop(L); + rawgeti(L, 3); + auto b = tonumber(L, -1); + pop(L); + rawgeti(L, 4); + auto a = tonumber(L, -1); + pop(L); + pop(L); + return glm::vec4(r / 255, g / 255, b / 255, a / 255); } int pushvalue(lua::State*, const dynamic::Value& value); dynamic::Value tovalue(lua::State*, int idx); - inline bool getfield(lua::State* L, const std::string& name, int idx=-1) { + inline bool getfield(lua::State* L, const std::string& name, int idx = -1) { lua_getfield(L, idx, name.c_str()); if (isnil(L, -1)) { pop(L); @@ -473,7 +500,7 @@ namespace lua { return true; } - inline bool hasfield(lua::State* L, const std::string& name, int idx=-1) { + inline bool hasfield(lua::State* L, const std::string& name, int idx = -1) { lua_getfield(L, idx, name.c_str()); if (isnil(L, -1)) { pop(L); @@ -485,21 +512,23 @@ namespace lua { inline const char* require_string(lua::State* L, int idx) { if (!isstring(L, idx)) { - throw luaerror("string expected at "+std::to_string(idx)); + throw luaerror("string expected at " + std::to_string(idx)); } return tostring(L, idx); } std::wstring require_wstring(lua::State*, int idx); - inline bool rename(lua::State* L, const std::string& from, const std::string& to) { + inline bool rename( + lua::State* L, const std::string& from, const std::string& to + ) { getglobal(L, from); if (isnil(L, -1)) { pop(L, 1); return false; } setglobal(L, to); - + // remove previous pushnil(L); setglobal(L, from); @@ -511,11 +540,13 @@ namespace lua { setglobal(L, name); } - inline int setfenv(lua::State* L, int idx=-2) { + inline int setfenv(lua::State* L, int idx = -2) { return lua_setfenv(L, idx); } - inline void loadbuffer(lua::State* L, int env, const std::string& src, const std::string& file) { + inline void loadbuffer( + lua::State* L, int env, const std::string& src, const std::string& file + ) { if (luaL_loadbuffer(L, src.c_str(), src.length(), file.c_str())) { throw luaerror(tostring(L, -1)); } @@ -524,45 +555,64 @@ namespace lua { } } - inline void store_in(lua::State* L, const std::string& tableName, const std::string& name) { + inline void store_in( + lua::State* L, const std::string& tableName, const std::string& name + ) { if (getglobal(L, tableName)) { pushvalue(L, -2); setfield(L, name); pop(L, 2); } else { - throw std::runtime_error("table "+tableName+" not found"); + throw std::runtime_error("table " + tableName + " not found"); } } - inline int get_from(lua::State* L, const std::string& tableName, const std::string& name, bool required=false) { + inline int get_from( + lua::State* L, + const std::string& tableName, + const std::string& name, + bool required = false + ) { if (getglobal(L, tableName)) { if (getfield(L, name)) { return 1; } else if (required) { - throw std::runtime_error("table "+tableName+" has no member "+name); + throw std::runtime_error( + "table " + tableName + " has no member " + name + ); } return 0; } else { - throw std::runtime_error("table "+tableName+" not found"); + throw std::runtime_error("table " + tableName + " not found"); } } - int call(lua::State*, int argc, int nresults=-1); - int call_nothrow(lua::State*, int argc, int nresults=1); + int call(lua::State*, int argc, int nresults = -1); + int call_nothrow(lua::State*, int argc, int nresults = 1); - inline int eval(lua::State* L, int env, const std::string& src, const std::string& file="") { - auto srcText = "return "+src; + inline int eval( + lua::State* L, + int env, + const std::string& src, + const std::string& file = "" + ) { + auto srcText = "return " + src; loadbuffer(L, env, srcText, file); return call(L, 0); } - inline int execute(lua::State* L, int env, const std::string& src, const std::string& file="") { + inline int execute( + lua::State* L, + int env, + const std::string& src, + const std::string& file = "" + ) { loadbuffer(L, env, src, file); return call_nothrow(L, 0); } runnable create_runnable(lua::State*); - scripting::common_func create_lambda(lua::State* ); + scripting::common_func create_lambda(lua::State*); inline int pushenv(lua::State* L, int env) { if (getglobal(L, env_name(env))) { @@ -574,16 +624,20 @@ namespace lua { void removeEnvironment(lua::State*, int id); void dump_stack(lua::State*); - inline void addfunc(lua::State* L, const std::string& name, lua_CFunction func) { + inline void addfunc( + lua::State* L, const std::string& name, lua_CFunction func + ) { pushcfunction(L, func); setglobal(L, name); } - inline void openlib(lua::State* L, const std::string& name, const luaL_Reg* libfuncs) { + inline void openlib( + lua::State* L, const std::string& name, const luaL_Reg* libfuncs + ) { createtable(L, 0, 0); luaL_setfuncs(L, libfuncs, 0); setglobal(L, name); } } -#endif // LOGIC_SCRIPTING_LUA_UTIL_HPP_ +#endif // LOGIC_SCRIPTING_LUA_UTIL_HPP_ diff --git a/src/logic/scripting/scripting.cpp b/src/logic/scripting/scripting.cpp index 681cf3fa..a34594cb 100644 --- a/src/logic/scripting/scripting.cpp +++ b/src/logic/scripting/scripting.cpp @@ -1,6 +1,7 @@ #include "scripting.hpp" -#include "lua/lua_engine.hpp" +#include +#include #include "../../content/Content.hpp" #include "../../content/ContentPack.hpp" @@ -13,17 +14,14 @@ #include "../../items/ItemDef.hpp" #include "../../logic/BlocksController.hpp" #include "../../logic/LevelController.hpp" -#include "../../objects/Player.hpp" -#include "../../objects/EntityDef.hpp" #include "../../objects/Entities.hpp" +#include "../../objects/EntityDef.hpp" +#include "../../objects/Player.hpp" #include "../../util/stringutil.hpp" #include "../../util/timeutil.hpp" -#include "../../util/timeutil.hpp" #include "../../voxels/Block.hpp" #include "../../world/Level.hpp" - -#include -#include +#include "lua/lua_engine.hpp" using namespace scripting; @@ -40,7 +38,7 @@ LevelController* scripting::controller = nullptr; static void load_script(const fs::path& name, bool throwable) { auto paths = scripting::engine->getPaths(); - fs::path file = paths->getResources()/fs::path("scripts")/name; + fs::path file = paths->getResources() / fs::path("scripts") / name; std::string src = files::read_string(file); auto L = lua::get_main_thread(); @@ -61,13 +59,13 @@ void scripting::initialize(Engine* engine) { load_script(fs::path("classes.lua"), true); } -[[nodiscard]] -scriptenv scripting::get_root_environment() { +[[nodiscard]] scriptenv scripting::get_root_environment() { return std::make_shared(0); } -[[nodiscard]] -scriptenv scripting::create_pack_environment(const ContentPack& pack) { +[[nodiscard]] scriptenv scripting::create_pack_environment( + const ContentPack& pack +) { auto L = lua::get_main_thread(); int id = lua::create_environment(L, 0); lua::pushenv(L, id); @@ -82,8 +80,9 @@ scriptenv scripting::create_pack_environment(const ContentPack& pack) { }); } -[[nodiscard]] -scriptenv scripting::create_doc_environment(const scriptenv& parent, const std::string& name) { +[[nodiscard]] scriptenv scripting::create_doc_environment( + const scriptenv& parent, const std::string& name +) { auto L = lua::get_main_thread(); int id = lua::create_environment(L, *parent); lua::pushenv(L, id); @@ -91,7 +90,7 @@ scriptenv scripting::create_doc_environment(const scriptenv& parent, const std:: lua::setfield(L, "DOC_ENV"); lua::pushstring(L, name); lua::setfield(L, "DOC_NAME"); - + if (lua::getglobal(L, "Document")) { if (lua::getfield(L, "new")) { lua::pushstring(L, name); @@ -108,10 +107,9 @@ scriptenv scripting::create_doc_environment(const scriptenv& parent, const std:: }); } -[[nodiscard]] -static scriptenv create_component_environment(const scriptenv& parent, - int entityIdx, - const std::string& name) { +[[nodiscard]] static scriptenv create_component_environment( + const scriptenv& parent, int entityIdx, const std::string& name +) { auto L = lua::get_main_thread(); int id = lua::create_environment(L, *parent); @@ -184,10 +182,10 @@ void scripting::on_world_quit() { for (auto& pack : scripting::engine->getContentPacks()) { lua::getfield(L, "unload"); lua::pushstring(L, pack.id); - lua::call_nothrow(L, 1); + lua::call_nothrow(L, 1); } lua::pop(L); - + if (lua::getglobal(L, "__scripts_cleanup")) { lua::call_nothrow(L, 0); } @@ -200,33 +198,35 @@ void scripting::on_world_quit() { void scripting::on_blocks_tick(const Block* block, int tps) { std::string name = block->name + ".blockstick"; - lua::emit_event(lua::get_main_thread(), name, [tps] (auto L) { + lua::emit_event(lua::get_main_thread(), name, [tps](auto L) { return lua::pushinteger(L, tps); }); } void scripting::update_block(const Block* block, int x, int y, int z) { std::string name = block->name + ".update"; - lua::emit_event(lua::get_main_thread(), name, [x, y, z] (auto L) { + lua::emit_event(lua::get_main_thread(), name, [x, y, z](auto L) { return lua::pushivec3_stack(L, x, y, z); }); } void scripting::random_update_block(const Block* block, int x, int y, int z) { std::string name = block->name + ".randupdate"; - lua::emit_event(lua::get_main_thread(), name, [x, y, z] (auto L) { + lua::emit_event(lua::get_main_thread(), name, [x, y, z](auto L) { return lua::pushivec3_stack(L, x, y, z); }); } -void scripting::on_block_placed(Player* player, const Block* block, int x, int y, int z) { +void scripting::on_block_placed( + Player* player, const Block* block, int x, int y, int z +) { std::string name = block->name + ".placed"; - lua::emit_event(lua::get_main_thread(), name, [x, y, z, player] (auto L) { + lua::emit_event(lua::get_main_thread(), name, [x, y, z, player](auto L) { lua::pushivec3_stack(L, x, y, z); lua::pushinteger(L, player ? player->getId() : -1); return 4; }); - auto world_event_args = [block, x, y, z, player] (lua::State* L) { + auto world_event_args = [block, x, y, z, player](lua::State* L) { lua::pushinteger(L, block->rt.id); lua::pushivec3_stack(L, x, y, z); lua::pushinteger(L, player ? player->getId() : -1); @@ -234,21 +234,31 @@ void scripting::on_block_placed(Player* player, const Block* block, int x, int y }; for (auto& [packid, pack] : content->getPacks()) { if (pack->worldfuncsset.onblockplaced) { - lua::emit_event(lua::get_main_thread(), packid + ".blockplaced", world_event_args); + lua::emit_event( + lua::get_main_thread(), + packid + ".blockplaced", + world_event_args + ); } } } -void scripting::on_block_broken(Player* player, const Block* block, int x, int y, int z) { +void scripting::on_block_broken( + Player* player, const Block* block, int x, int y, int z +) { if (block->rt.funcsset.onbroken) { std::string name = block->name + ".broken"; - lua::emit_event(lua::get_main_thread(), name, [x, y, z, player] (auto L) { - lua::pushivec3_stack(L, x, y, z); - lua::pushinteger(L, player ? player->getId() : -1); - return 4; - }); + lua::emit_event( + lua::get_main_thread(), + name, + [x, y, z, player](auto L) { + lua::pushivec3_stack(L, x, y, z); + lua::pushinteger(L, player ? player->getId() : -1); + return 4; + } + ); } - auto world_event_args = [block, x, y, z, player] (lua::State* L) { + auto world_event_args = [block, x, y, z, player](lua::State* L) { lua::pushinteger(L, block->rt.id); lua::pushivec3_stack(L, x, y, z); lua::pushinteger(L, player ? player->getId() : -1); @@ -256,14 +266,20 @@ void scripting::on_block_broken(Player* player, const Block* block, int x, int y }; for (auto& [packid, pack] : content->getPacks()) { if (pack->worldfuncsset.onblockbroken) { - lua::emit_event(lua::get_main_thread(), packid + ".blockbroken", world_event_args); + lua::emit_event( + lua::get_main_thread(), + packid + ".blockbroken", + world_event_args + ); } } } -bool scripting::on_block_interact(Player* player, const Block* block, glm::ivec3 pos) { +bool scripting::on_block_interact( + Player* player, const Block* block, glm::ivec3 pos +) { std::string name = block->name + ".interact"; - return lua::emit_event(lua::get_main_thread(), name, [pos, player] (auto L) { + return lua::emit_event(lua::get_main_thread(), name, [pos, player](auto L) { lua::pushivec3_stack(L, pos.x, pos.y, pos.z); lua::pushinteger(L, player->getId()); return 4; @@ -272,31 +288,47 @@ bool scripting::on_block_interact(Player* player, const Block* block, glm::ivec3 bool scripting::on_item_use(Player* player, const ItemDef* item) { std::string name = item->name + ".use"; - return lua::emit_event(lua::get_main_thread(), name, [player] (lua::State* L) { - return lua::pushinteger(L, player->getId()); - }); + return lua::emit_event( + lua::get_main_thread(), + name, + [player](lua::State* L) { return lua::pushinteger(L, player->getId()); } + ); } -bool scripting::on_item_use_on_block(Player* player, const ItemDef* item, glm::ivec3 ipos, glm::ivec3 normal) { +bool scripting::on_item_use_on_block( + Player* player, const ItemDef* item, glm::ivec3 ipos, glm::ivec3 normal +) { std::string name = item->name + ".useon"; - return lua::emit_event(lua::get_main_thread(), name, [ipos, normal, player] (auto L) { - lua::pushivec3_stack(L, ipos.x, ipos.y, ipos.z); - lua::pushinteger(L, player->getId()); - lua::pushivec(L, normal); - return 5; - }); + return lua::emit_event( + lua::get_main_thread(), + name, + [ipos, normal, player](auto L) { + lua::pushivec3_stack(L, ipos.x, ipos.y, ipos.z); + lua::pushinteger(L, player->getId()); + lua::pushivec(L, normal); + return 5; + } + ); } -bool scripting::on_item_break_block(Player* player, const ItemDef* item, int x, int y, int z) { +bool scripting::on_item_break_block( + Player* player, const ItemDef* item, int x, int y, int z +) { std::string name = item->name + ".blockbreakby"; - return lua::emit_event(lua::get_main_thread(), name, [x, y, z, player] (auto L) { - lua::pushivec3_stack(L, x, y, z); - lua::pushinteger(L, player->getId()); - return 4; - }); + return lua::emit_event( + lua::get_main_thread(), + name, + [x, y, z, player](auto L) { + lua::pushivec3_stack(L, x, y, z); + lua::pushinteger(L, player->getId()); + return 4; + } + ); } -dynamic::Value scripting::get_component_value(const scriptenv& env, const std::string& name) { +dynamic::Value scripting::get_component_value( + const scriptenv& env, const std::string& name +) { auto L = lua::get_main_thread(); lua::pushenv(L, *env); if (lua::getfield(L, name)) { @@ -319,13 +351,14 @@ void scripting::on_entity_spawn( lua::call(L, 1); } if (components.size() > 1) { - for (size_t i = 0; i < components.size()-1; i++) { + for (size_t i = 0; i < components.size() - 1; i++) { lua::pushvalue(L, -1); } } for (auto& component : components) { - auto compenv = create_component_environment(get_root_environment(), -1, - component->name); + auto compenv = create_component_environment( + get_root_environment(), -1, component->name + ); lua::get_from(L, lua::CHUNKS_TABLE, component->name, true); lua::pushenv(L, *compenv); @@ -375,8 +408,8 @@ void scripting::on_entity_spawn( } static void process_entity_callback( - const scriptenv& env, - const std::string& name, + const scriptenv& env, + const std::string& name, std::function args ) { auto L = lua::get_main_thread(); @@ -406,7 +439,9 @@ static void process_entity_callback( } void scripting::on_entity_despawn(const Entity& entity) { - process_entity_callback(entity, "on_despawn", &entity_funcs_set::on_despawn, nullptr); + process_entity_callback( + entity, "on_despawn", &entity_funcs_set::on_despawn, nullptr + ); auto L = lua::get_main_thread(); lua::get_from(L, "stdcomp", "remove_Entity", true); lua::pushinteger(L, entity.getUID()); @@ -414,65 +449,96 @@ void scripting::on_entity_despawn(const Entity& entity) { } void scripting::on_entity_grounded(const Entity& entity, float force) { - process_entity_callback(entity, "on_grounded", &entity_funcs_set::on_grounded, [force](auto L){ - return lua::pushnumber(L, force); - }); + process_entity_callback( + entity, + "on_grounded", + &entity_funcs_set::on_grounded, + [force](auto L) { return lua::pushnumber(L, force); } + ); } void scripting::on_entity_fall(const Entity& entity) { - process_entity_callback(entity, "on_fall", &entity_funcs_set::on_fall, nullptr); + process_entity_callback( + entity, "on_fall", &entity_funcs_set::on_fall, nullptr + ); } void scripting::on_entity_save(const Entity& entity) { - process_entity_callback(entity, "on_save", &entity_funcs_set::on_save, nullptr); + process_entity_callback( + entity, "on_save", &entity_funcs_set::on_save, nullptr + ); } -void scripting::on_sensor_enter(const Entity& entity, size_t index, entityid_t oid) { - process_entity_callback(entity, "on_sensor_enter", - &entity_funcs_set::on_sensor_enter, [index, oid](auto L) { - lua::pushinteger(L, index); - lua::pushinteger(L, oid); - return 2; - }); +void scripting::on_sensor_enter( + const Entity& entity, size_t index, entityid_t oid +) { + process_entity_callback( + entity, + "on_sensor_enter", + &entity_funcs_set::on_sensor_enter, + [index, oid](auto L) { + lua::pushinteger(L, index); + lua::pushinteger(L, oid); + return 2; + } + ); } -void scripting::on_sensor_exit(const Entity& entity, size_t index, entityid_t oid) { - process_entity_callback(entity, "on_sensor_exit", - &entity_funcs_set::on_sensor_exit, [index, oid](auto L) { - lua::pushinteger(L, index); - lua::pushinteger(L, oid); - return 2; - }); +void scripting::on_sensor_exit( + const Entity& entity, size_t index, entityid_t oid +) { + process_entity_callback( + entity, + "on_sensor_exit", + &entity_funcs_set::on_sensor_exit, + [index, oid](auto L) { + lua::pushinteger(L, index); + lua::pushinteger(L, oid); + return 2; + } + ); } void scripting::on_aim_on(const Entity& entity, Player* player) { - process_entity_callback(entity, "on_aim_on", - &entity_funcs_set::on_aim_on, [player](auto L) { - return lua::pushinteger(L, player->getId()); - }); + process_entity_callback( + entity, + "on_aim_on", + &entity_funcs_set::on_aim_on, + [player](auto L) { return lua::pushinteger(L, player->getId()); } + ); } void scripting::on_aim_off(const Entity& entity, Player* player) { - process_entity_callback(entity, "on_aim_off", - &entity_funcs_set::on_aim_off, [player](auto L) { - return lua::pushinteger(L, player->getId()); - }); + process_entity_callback( + entity, + "on_aim_off", + &entity_funcs_set::on_aim_off, + [player](auto L) { return lua::pushinteger(L, player->getId()); } + ); } -void scripting::on_attacked(const Entity& entity, Player* player, entityid_t attacker) { - process_entity_callback(entity, "on_attacked", - &entity_funcs_set::on_attacked, [player, attacker](auto L) { - lua::pushinteger(L, attacker); - lua::pushinteger(L, player->getId()); - return 2; - }); +void scripting::on_attacked( + const Entity& entity, Player* player, entityid_t attacker +) { + process_entity_callback( + entity, + "on_attacked", + &entity_funcs_set::on_attacked, + [player, attacker](auto L) { + lua::pushinteger(L, attacker); + lua::pushinteger(L, player->getId()); + return 2; + } + ); } void scripting::on_entity_used(const Entity& entity, Player* player) { - process_entity_callback(entity, "on_used", - &entity_funcs_set::on_used, [player](auto L) { - return lua::pushinteger(L, player->getId()); - }); + process_entity_callback( + entity, + "on_used", + &entity_funcs_set::on_used, + [player](auto L) { return lua::pushinteger(L, player->getId()); } + ); } void scripting::on_entities_update(int tps, int parts, int part) { @@ -494,12 +560,12 @@ void scripting::on_entities_render(float delta) { } void scripting::on_ui_open( - UiDocument* layout, - std::vector args + UiDocument* layout, std::vector args ) { - auto argsptr = std::make_shared>(std::move(args)); + auto argsptr = + std::make_shared>(std::move(args)); std::string name = layout->getId() + ".open"; - lua::emit_event(lua::get_main_thread(), name, [=] (auto L) { + lua::emit_event(lua::get_main_thread(), name, [=](auto L) { for (const auto& value : *argsptr) { lua::pushvalue(L, value); } @@ -507,9 +573,11 @@ void scripting::on_ui_open( }); } -void scripting::on_ui_progress(UiDocument* layout, int workDone, int workTotal) { +void scripting::on_ui_progress( + UiDocument* layout, int workDone, int workTotal +) { std::string name = layout->getId() + ".progress"; - lua::emit_event(lua::get_main_thread(), name, [=] (auto L) { + lua::emit_event(lua::get_main_thread(), name, [=](auto L) { lua::pushinteger(L, workDone); lua::pushinteger(L, workTotal); return 2; @@ -518,12 +586,14 @@ void scripting::on_ui_progress(UiDocument* layout, int workDone, int workTotal) void scripting::on_ui_close(UiDocument* layout, Inventory* inventory) { std::string name = layout->getId() + ".close"; - lua::emit_event(lua::get_main_thread(), name, [inventory] (auto L) { + lua::emit_event(lua::get_main_thread(), name, [inventory](auto L) { return lua::pushinteger(L, inventory ? inventory->getId() : 0); }); } -bool scripting::register_event(int env, const std::string& name, const std::string& id) { +bool scripting::register_event( + int env, const std::string& name, const std::string& id +) { auto L = lua::get_main_thread(); if (lua::pushenv(L, env) == 0) { lua::pushglobals(L); @@ -549,62 +619,91 @@ int scripting::get_values_on_stack() { return lua::gettop(lua::get_main_thread()); } -static void load_script(int env, const std::string& type, const fs::path& file) { +static void load_script( + int env, const std::string& type, const fs::path& file +) { std::string src = files::read_string(file); logger.info() << "script (" << type << ") " << file.u8string(); lua::execute(lua::get_main_thread(), env, src, file.u8string()); } -void scripting::load_block_script(const scriptenv& senv, const std::string& prefix, const fs::path& file, block_funcs_set& funcsset) { +void scripting::load_block_script( + const scriptenv& senv, + const std::string& prefix, + const fs::path& file, + block_funcs_set& funcsset +) { int env = *senv; load_script(env, "block", file); - funcsset.init = register_event(env, "init", prefix+".init"); - funcsset.update = register_event(env, "on_update", prefix+".update"); - funcsset.randupdate = register_event(env, "on_random_update", prefix+".randupdate"); - funcsset.onbroken = register_event(env, "on_broken", prefix+".broken"); - funcsset.onplaced = register_event(env, "on_placed", prefix+".placed"); - funcsset.oninteract = register_event(env, "on_interact", prefix+".interact"); - funcsset.onblockstick = register_event(env, "on_blocks_tick", prefix+".blockstick"); + funcsset.init = register_event(env, "init", prefix + ".init"); + funcsset.update = register_event(env, "on_update", prefix + ".update"); + funcsset.randupdate = + register_event(env, "on_random_update", prefix + ".randupdate"); + funcsset.onbroken = register_event(env, "on_broken", prefix + ".broken"); + funcsset.onplaced = register_event(env, "on_placed", prefix + ".placed"); + funcsset.oninteract = + register_event(env, "on_interact", prefix + ".interact"); + funcsset.onblockstick = + register_event(env, "on_blocks_tick", prefix + ".blockstick"); } -void scripting::load_item_script(const scriptenv& senv, const std::string& prefix, const fs::path& file, item_funcs_set& funcsset) { +void scripting::load_item_script( + const scriptenv& senv, + const std::string& prefix, + const fs::path& file, + item_funcs_set& funcsset +) { int env = *senv; load_script(env, "item", file); - funcsset.init = register_event(env, "init", prefix+".init"); - funcsset.on_use = register_event(env, "on_use", prefix+".use"); - funcsset.on_use_on_block = register_event(env, "on_use_on_block", prefix+".useon"); - funcsset.on_block_break_by = register_event(env, "on_block_break_by", prefix+".blockbreakby"); + funcsset.init = register_event(env, "init", prefix + ".init"); + funcsset.on_use = register_event(env, "on_use", prefix + ".use"); + funcsset.on_use_on_block = + register_event(env, "on_use_on_block", prefix + ".useon"); + funcsset.on_block_break_by = + register_event(env, "on_block_break_by", prefix + ".blockbreakby"); } -void scripting::load_entity_component(const std::string& name, const fs::path& file) { +void scripting::load_entity_component( + const std::string& name, const fs::path& file +) { auto L = lua::get_main_thread(); std::string src = files::read_string(file); logger.info() << "script (component) " << file.u8string(); - lua::loadbuffer(L, 0, src, "C!"+name); + lua::loadbuffer(L, 0, src, "C!" + name); lua::store_in(L, lua::CHUNKS_TABLE, name); } -void scripting::load_world_script(const scriptenv& senv, - const std::string& prefix, - const fs::path& file, - world_funcs_set& funcsset) { +void scripting::load_world_script( + const scriptenv& senv, + const std::string& prefix, + const fs::path& file, + world_funcs_set& funcsset +) { int env = *senv; load_script(env, "world", file); - register_event(env, "init", prefix+".init"); - register_event(env, "on_world_open", prefix+".worldopen"); - register_event(env, "on_world_tick", prefix+".worldtick"); - register_event(env, "on_world_save", prefix+".worldsave"); - register_event(env, "on_world_quit", prefix+".worldquit"); - funcsset.onblockplaced = register_event(env, "on_block_placed", prefix+".blockplaced"); - funcsset.onblockbroken = register_event(env, "on_block_broken", prefix+".blockbroken"); + register_event(env, "init", prefix + ".init"); + register_event(env, "on_world_open", prefix + ".worldopen"); + register_event(env, "on_world_tick", prefix + ".worldtick"); + register_event(env, "on_world_save", prefix + ".worldsave"); + register_event(env, "on_world_quit", prefix + ".worldquit"); + funcsset.onblockplaced = + register_event(env, "on_block_placed", prefix + ".blockplaced"); + funcsset.onblockbroken = + register_event(env, "on_block_broken", prefix + ".blockbroken"); } -void scripting::load_layout_script(const scriptenv& senv, const std::string& prefix, const fs::path& file, uidocscript& script) { +void scripting::load_layout_script( + const scriptenv& senv, + const std::string& prefix, + const fs::path& file, + uidocscript& script +) { int env = *senv; load_script(env, "layout", file); - script.onopen = register_event(env, "on_open", prefix+".open"); - script.onprogress = register_event(env, "on_progress", prefix+".progress"); - script.onclose = register_event(env, "on_close", prefix+".close"); + script.onopen = register_event(env, "on_open", prefix + ".open"); + script.onprogress = + register_event(env, "on_progress", prefix + ".progress"); + script.onclose = register_event(env, "on_close", prefix + ".close"); } void scripting::close() { diff --git a/src/logic/scripting/scripting.hpp b/src/logic/scripting/scripting.hpp index d0c96d90..e389320d 100644 --- a/src/logic/scripting/scripting.hpp +++ b/src/logic/scripting/scripting.hpp @@ -1,17 +1,16 @@ #ifndef LOGIC_SCRIPTING_SCRIPTING_HPP_ #define LOGIC_SCRIPTING_SCRIPTING_HPP_ -#include "../../data/dynamic.hpp" -#include "../../typedefs.hpp" -#include "../../delegates.hpp" - -#include "scripting_functional.hpp" - -#include -#include -#include #include #include +#include +#include +#include + +#include "../../data/dynamic.hpp" +#include "../../delegates.hpp" +#include "../../typedefs.hpp" +#include "scripting_functional.hpp" namespace fs = std::filesystem; @@ -45,12 +44,16 @@ namespace scripting { void initialize(Engine* engine); - bool register_event(int env, const std::string& name, const std::string& id); + bool register_event( + int env, const std::string& name, const std::string& id + ); int get_values_on_stack(); scriptenv get_root_environment(); scriptenv create_pack_environment(const ContentPack& pack); - scriptenv create_doc_environment(const scriptenv& parent, const std::string& name); + scriptenv create_doc_environment( + const scriptenv& parent, const std::string& name + ); void process_post_runnables(); @@ -61,26 +64,36 @@ namespace scripting { void on_blocks_tick(const Block* block, int tps); void update_block(const Block* block, int x, int y, int z); void random_update_block(const Block* block, int x, int y, int z); - void on_block_placed(Player* player, const Block* block, int x, int y, int z); - void on_block_broken(Player* player, const Block* block, int x, int y, int z); + void on_block_placed( + Player* player, const Block* block, int x, int y, int z + ); + void on_block_broken( + Player* player, const Block* block, int x, int y, int z + ); bool on_block_interact(Player* player, const Block* block, glm::ivec3 pos); - /// @brief Called on RMB click with the item selected + /// @brief Called on RMB click with the item selected /// @return true if prevents default action bool on_item_use(Player* player, const ItemDef* item); - /// @brief Called on RMB click on block with the item selected + /// @brief Called on RMB click on block with the item selected /// @return true if prevents default action - bool on_item_use_on_block(Player* player, const ItemDef* item, glm::ivec3 ipos, glm::ivec3 normal); + bool on_item_use_on_block( + Player* player, const ItemDef* item, glm::ivec3 ipos, glm::ivec3 normal + ); - /// @brief Called on LMB click on block with the item selected + /// @brief Called on LMB click on block with the item selected /// @return true if prevents default action - bool on_item_break_block(Player* player, const ItemDef* item, int x, int y, int z); + bool on_item_break_block( + Player* player, const ItemDef* item, int x, int y, int z + ); - dynamic::Value get_component_value(const scriptenv& env, const std::string& name); + dynamic::Value get_component_value( + const scriptenv& env, const std::string& name + ); void on_entity_spawn( const EntityDef& def, - entityid_t eid, + entityid_t eid, const std::vector>& components, dynamic::Map_sptr args, dynamic::Map_sptr saved @@ -99,10 +112,7 @@ namespace scripting { void on_entity_used(const Entity& entity, Player* player); /// @brief Called on UI view show - void on_ui_open( - UiDocument* layout, - std::vector args - ); + void on_ui_open(UiDocument* layout, std::vector args); void on_ui_progress(UiDocument* layout, int workDone, int totalWork); @@ -115,10 +125,11 @@ namespace scripting { /// @param file item script file /// @param funcsset block callbacks set void load_block_script( - const scriptenv& env, + const scriptenv& env, const std::string& prefix, const fs::path& file, - block_funcs_set& funcsset); + block_funcs_set& funcsset + ); /// @brief Load script associated with an Item /// @param env environment @@ -128,28 +139,37 @@ namespace scripting { void load_item_script( const scriptenv& env, const std::string& prefix, - const fs::path& file, - item_funcs_set& funcsset); + const fs::path& file, + item_funcs_set& funcsset + ); - void load_entity_component( - const std::string& name, - const fs::path& file); - - /// @brief Load package-specific world script + void load_entity_component(const std::string& name, const fs::path& file); + + /// @brief Load package-specific world script /// @param env environment /// @param packid content-pack id /// @param file script file path - void load_world_script(const scriptenv& env, const std::string& packid, const fs::path& file, world_funcs_set& funcsset); + void load_world_script( + const scriptenv& env, + const std::string& packid, + const fs::path& file, + world_funcs_set& funcsset + ); /// @brief Load script associated with an UiDocument /// @param env environment /// @param prefix pack id /// @param file item script file /// @param script document script info - void load_layout_script(const scriptenv& env, const std::string& prefix, const fs::path& file, uidocscript& script); + void load_layout_script( + const scriptenv& env, + const std::string& prefix, + const fs::path& file, + uidocscript& script + ); /// @brief Finalize lua state. Using scripting after will lead to Lua panic void close(); } -#endif // LOGIC_SCRIPTING_SCRIPTING_HPP_ +#endif // LOGIC_SCRIPTING_SCRIPTING_HPP_ diff --git a/src/logic/scripting/scripting_functional.cpp b/src/logic/scripting/scripting_functional.cpp index 557ece1d..db26db80 100644 --- a/src/logic/scripting/scripting_functional.cpp +++ b/src/logic/scripting/scripting_functional.cpp @@ -1,18 +1,16 @@ #include "scripting_functional.hpp" -#include "lua/lua_engine.hpp" -#include "../../debug/Logger.hpp" #include "../../coders/json.hpp" +#include "../../debug/Logger.hpp" #include "../../util/stringutil.hpp" +#include "lua/lua_engine.hpp" using namespace scripting; static debug::Logger logger("scripting_func"); runnable scripting::create_runnable( - const scriptenv& env, - const std::string& src, - const std::string& file + const scriptenv& env, const std::string& src, const std::string& file ) { auto L = lua::get_main_thread(); try { @@ -20,14 +18,12 @@ runnable scripting::create_runnable( return lua::create_runnable(L); } catch (const lua::luaerror& err) { logger.error() << err.what(); - return [](){}; + return []() {}; } } static lua::State* process_callback( - const scriptenv& env, - const std::string& src, - const std::string& file + const scriptenv& env, const std::string& src, const std::string& file ) { auto L = lua::get_main_thread(); try { @@ -41,11 +37,9 @@ static lua::State* process_callback( } wstringconsumer scripting::create_wstring_consumer( - const scriptenv& env, - const std::string& src, - const std::string& file + const scriptenv& env, const std::string& src, const std::string& file ) { - return [=](const std::wstring& x){ + return [=](const std::wstring& x) { if (auto L = process_callback(env, src, file)) { lua::pushwstring(L, x); lua::call_nothrow(L, 1); @@ -54,16 +48,15 @@ wstringconsumer scripting::create_wstring_consumer( } wstringsupplier scripting::create_wstring_supplier( - const scriptenv& env, - const std::string& src, - const std::string& file + const scriptenv& env, const std::string& src, const std::string& file ) { - return [=](){ + return [=]() { if (auto L = process_callback(env, src, file)) { if (lua::isfunction(L, -1)) { lua::call_nothrow(L, 0); } - auto str = lua::require_wstring(L, -1); lua::pop(L); + auto str = lua::require_wstring(L, -1); + lua::pop(L); return str; } return std::wstring(); @@ -71,26 +64,21 @@ wstringsupplier scripting::create_wstring_supplier( } wstringchecker scripting::create_wstring_validator( - const scriptenv& env, - const std::string& src, - const std::string& file + const scriptenv& env, const std::string& src, const std::string& file ) { - return [=](const std::wstring& x){ + return [=](const std::wstring& x) { if (auto L = process_callback(env, src, file)) { lua::pushwstring(L, x); - if (lua::call_nothrow(L, 1)) - return lua::toboolean(L, -1); + if (lua::call_nothrow(L, 1)) return lua::toboolean(L, -1); } return false; }; } boolconsumer scripting::create_bool_consumer( - const scriptenv& env, - const std::string& src, - const std::string& file + const scriptenv& env, const std::string& src, const std::string& file ) { - return [=](bool x){ + return [=](bool x) { if (auto L = process_callback(env, src, file)) { lua::pushboolean(L, x); lua::call_nothrow(L, 1); @@ -99,16 +87,15 @@ boolconsumer scripting::create_bool_consumer( } boolsupplier scripting::create_bool_supplier( - const scriptenv& env, - const std::string& src, - const std::string& file + const scriptenv& env, const std::string& src, const std::string& file ) { - return [=](){ + return [=]() { if (auto L = process_callback(env, src, file)) { if (lua::isfunction(L, -1)) { lua::call_nothrow(L, 0); } - bool x = lua::toboolean(L,-1); lua::pop(L); + bool x = lua::toboolean(L, -1); + lua::pop(L); return x; } return false; @@ -116,11 +103,9 @@ boolsupplier scripting::create_bool_supplier( } doubleconsumer scripting::create_number_consumer( - const scriptenv& env, - const std::string& src, - const std::string& file + const scriptenv& env, const std::string& src, const std::string& file ) { - return [=](double x){ + return [=](double x) { if (auto L = process_callback(env, src, file)) { lua::pushnumber(L, x); lua::call_nothrow(L, 1); @@ -129,16 +114,14 @@ doubleconsumer scripting::create_number_consumer( } doublesupplier scripting::create_number_supplier( - const scriptenv& env, - const std::string& src, - const std::string& file + const scriptenv& env, const std::string& src, const std::string& file ) { - return [=](){ + return [=]() { if (auto L = process_callback(env, src, file)) { if (lua::isfunction(L, -1)) { lua::call_nothrow(L, 0); } - auto x = lua::tonumber(L, -1); + auto x = lua::tonumber(L, -1); lua::pop(L); return x; } @@ -147,9 +130,7 @@ doublesupplier scripting::create_number_supplier( } int_array_consumer scripting::create_int_array_consumer( - const scriptenv& env, - const std::string& src, - const std::string& file + const scriptenv& env, const std::string& src, const std::string& file ) { return [=](const int arr[], size_t len) { if (auto L = process_callback(env, src, file)) { @@ -162,17 +143,17 @@ int_array_consumer scripting::create_int_array_consumer( } vec2supplier scripting::create_vec2_supplier( - const scriptenv& env, - const std::string& src, - const std::string& file + const scriptenv& env, const std::string& src, const std::string& file ) { return [=]() { if (auto L = process_callback(env, src, file)) { if (lua::isfunction(L, -1)) { lua::call_nothrow(L, 0); } - auto y = lua::tonumber(L, -1); lua::pop(L); - auto x = lua::tonumber(L, -1); lua::pop(L); + auto y = lua::tonumber(L, -1); + lua::pop(L); + auto x = lua::tonumber(L, -1); + lua::pop(L); return glm::vec2(x, y); } return glm::vec2(0, 0); @@ -180,9 +161,7 @@ vec2supplier scripting::create_vec2_supplier( } dynamic::to_string_func scripting::create_tostring( - const scriptenv& env, - const std::string& src, - const std::string& file + const scriptenv& env, const std::string& src, const std::string& file ) { auto L = lua::get_main_thread(); try { diff --git a/src/logic/scripting/scripting_functional.hpp b/src/logic/scripting/scripting_functional.hpp index 01141262..b0bec218 100644 --- a/src/logic/scripting/scripting_functional.hpp +++ b/src/logic/scripting/scripting_functional.hpp @@ -1,83 +1,82 @@ #ifndef LOGIC_SCRIPTING_SCRIPTING_FUNCTIONAL_HPP_ #define LOGIC_SCRIPTING_SCRIPTING_FUNCTIONAL_HPP_ -#include "../../typedefs.hpp" -#include "../../delegates.hpp" -#include "../../data/dynamic.hpp" - #include #include -#include +#include "../../data/dynamic.hpp" +#include "../../delegates.hpp" +#include "../../typedefs.hpp" namespace scripting { - using common_func = std::function&)>; + using common_func = + std::function&)>; runnable create_runnable( const scriptenv& env, const std::string& src, - const std::string& file="" + const std::string& file = "" ); - + wstringconsumer create_wstring_consumer( const scriptenv& env, const std::string& src, - const std::string& file="" + const std::string& file = "" ); wstringsupplier create_wstring_supplier( const scriptenv& env, const std::string& src, - const std::string& file="" + const std::string& file = "" ); wstringchecker create_wstring_validator( const scriptenv& env, const std::string& src, - const std::string& file="" + const std::string& file = "" ); boolconsumer create_bool_consumer( const scriptenv& env, const std::string& src, - const std::string& file="" + const std::string& file = "" ); boolsupplier create_bool_supplier( const scriptenv& env, const std::string& src, - const std::string& file="" + const std::string& file = "" ); doubleconsumer create_number_consumer( const scriptenv& env, const std::string& src, - const std::string& file="" + const std::string& file = "" ); doublesupplier create_number_supplier( const scriptenv& env, const std::string& src, - const std::string& file="" + const std::string& file = "" ); int_array_consumer create_int_array_consumer( const scriptenv& env, - const std::string& src, - const std::string& file="" + const std::string& src, + const std::string& file = "" ); - + vec2supplier create_vec2_supplier( const scriptenv& env, - const std::string& src, - const std::string& file="" + const std::string& src, + const std::string& file = "" ); dynamic::to_string_func create_tostring( const scriptenv& env, const std::string& src, - const std::string& file="" + const std::string& file = "" ); } -#endif // LOGIC_SCRIPTING_SCRIPTING_FUNCTIONAL_HPP_ +#endif // LOGIC_SCRIPTING_SCRIPTING_FUNCTIONAL_HPP_ diff --git a/src/logic/scripting/scripting_hud.cpp b/src/logic/scripting/scripting_hud.cpp index 2ae7a9f3..97154337 100644 --- a/src/logic/scripting/scripting_hud.cpp +++ b/src/logic/scripting/scripting_hud.cpp @@ -1,14 +1,13 @@ #include "scripting_hud.hpp" -#include "scripting.hpp" - -#include "lua/api_lua.hpp" -#include "lua/lua_engine.hpp" #include "../../debug/Logger.hpp" +#include "../../engine.hpp" +#include "../../files/files.hpp" #include "../../frontend/hud.hpp" #include "../../objects/Player.hpp" -#include "../../files/files.hpp" -#include "../../engine.hpp" +#include "lua/api_lua.hpp" +#include "lua/lua_engine.hpp" +#include "scripting.hpp" using namespace scripting; @@ -21,41 +20,50 @@ void scripting::on_frontend_init(Hud* hud) { lua::openlib(lua::get_main_thread(), "hud", hudlib); for (auto& pack : engine->getContentPacks()) { - lua::emit_event(lua::get_main_thread(), pack.id + ".hudopen", - [&] (lua::State* L) { - return lua::pushinteger(L, hud->getPlayer()->getId()); - }); + lua::emit_event( + lua::get_main_thread(), + pack.id + ".hudopen", + [&](lua::State* L) { + return lua::pushinteger(L, hud->getPlayer()->getId()); + } + ); } } void scripting::on_frontend_render() { for (auto& pack : engine->getContentPacks()) { - lua::emit_event(lua::get_main_thread(), pack.id + ".hudrender", - [&] (lua::State* L) { - return 0; - }); + lua::emit_event( + lua::get_main_thread(), + pack.id + ".hudrender", + [&](lua::State* L) { return 0; } + ); } } void scripting::on_frontend_close() { for (auto& pack : engine->getContentPacks()) { - lua::emit_event(lua::get_main_thread(), pack.id + ".hudclose", - [&] (lua::State* L) { - return lua::pushinteger(L, hud->getPlayer()->getId()); - }); + lua::emit_event( + lua::get_main_thread(), + pack.id + ".hudclose", + [&](lua::State* L) { + return lua::pushinteger(L, hud->getPlayer()->getId()); + } + ); } scripting::hud = nullptr; } -void scripting::load_hud_script(const scriptenv& senv, const std::string& packid, const fs::path& file) { +void scripting::load_hud_script( + const scriptenv& senv, const std::string& packid, const fs::path& file +) { int env = *senv; std::string src = files::read_string(file); logger.info() << "loading script " << file.u8string(); lua::execute(lua::get_main_thread(), env, src, file.u8string()); - register_event(env, "init", packid+".init"); - register_event(env, "on_hud_open", packid+".hudopen"); - register_event(env, "on_hud_render", packid+".hudrender"); - register_event(env, "on_hud_close", packid+".hudclose"); + register_event(env, "init", packid + ".init"); + register_event(env, "on_hud_open", packid + ".hudopen"); + register_event(env, "on_hud_render", packid + ".hudrender"); + register_event(env, "on_hud_close", packid + ".hudclose"); } diff --git a/src/logic/scripting/scripting_hud.hpp b/src/logic/scripting/scripting_hud.hpp index ad36cda2..0ca10c04 100644 --- a/src/logic/scripting/scripting_hud.hpp +++ b/src/logic/scripting/scripting_hud.hpp @@ -1,29 +1,31 @@ #ifndef LOGIC_SCRIPTING_SCRIPTING_HUD_HPP_ #define LOGIC_SCRIPTING_SCRIPTING_HUD_HPP_ -#include "../../typedefs.hpp" - -#include #include +#include + +#include "../../typedefs.hpp" namespace fs = std::filesystem; class Hud; namespace scripting { - extern Hud* hud; + extern Hud *hud; - void on_frontend_init(Hud* hud); + void on_frontend_init(Hud *hud); void on_frontend_render(); void on_frontend_close(); - /** + /** * Load package-specific hud script * @param env environment id * @param packid content-pack id * @param file script file path */ - void load_hud_script(const scriptenv &env, const std::string &packid, const fs::path &file); + void load_hud_script( + const scriptenv &env, const std::string &packid, const fs::path &file + ); } -#endif // LOGIC_SCRIPTING_SCRIPTING_HUD_HPP_ +#endif // LOGIC_SCRIPTING_SCRIPTING_HUD_HPP_ diff --git a/src/maths/FastNoiseLite.h b/src/maths/FastNoiseLite.h index eff196e3..e9c48172 100644 --- a/src/maths/FastNoiseLite.h +++ b/src/maths/FastNoiseLite.h @@ -10,8 +10,8 @@ // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, @@ -21,26 +21,41 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // -// .'',;:cldxkO00KKXXNNWWWNNXKOkxdollcc::::::;:::ccllloooolllllllllooollc:,'... ...........',;cldxkO000Okxdlc::;;;,,;;;::cclllllll -// ..',;:ldxO0KXXNNNNNNNNXXK0kxdolcc::::::;;;,,,,,,;;;;;;;;;;:::cclllllc:;'.... ...........',;:ldxO0KXXXK0Okxdolc::;;;;::cllodddddo +// .'',;:cldxkO00KKXXNNWWWNNXKOkxdollcc::::::;:::ccllloooolllllllllooollc:,'... +// ...........',;cldxkO000Okxdlc::;;;,,;;;::cclllllll +// ..',;:ldxO0KXXNNNNNNNNXXK0kxdolcc::::::;;;,,,,,,;;;;;;;;;;:::cclllllc:;'.... +// ...........',;:ldxO0KXXXK0Okxdolc::;;;;::cllodddddo // ...',:loxO0KXNNNNNXXKK0Okxdolc::;::::::::;;;,,'''''.....''',;:clllllc:;,'............''''''''',;:loxO0KXNNNNNXK0Okxdollccccllodxxxxxxd -// ....';:ldkO0KXXXKK00Okxdolcc:;;;;;::cclllcc:;;,''..... ....',;clooddolcc:;;;;,,;;;;;::::;;;;;;:cloxk0KXNWWWWWWNXKK0Okxddoooddxxkkkkkxx -// .....';:ldxkOOOOOkxxdolcc:;;;,,,;;:cllooooolcc:;'... ..,:codxkkkxddooollloooooooollcc:::::clodkO0KXNWWWWWWNNXK00Okxxxxxxxxkkkkxxx -// . ....';:cloddddo___________,,,,;;:clooddddoolc:,... ..,:ldx__00OOOkkk___kkkkkkxxdollc::::cclodkO0KXXNNNNNNXXK0OOkxxxxxxxxxxxxddd -// .......',;:cccc:| |,,,;;:cclooddddoll:;'.. ..';cox| \KKK000| |KK00OOkxdocc___;::clldxxkO0KKKKK00Okkxdddddddddddddddoo -// .......'',,,,,''| ________|',,;;::cclloooooolc:;'......___:ldk| \KK000| |XKKK0Okxolc| |;;::cclodxxkkkkxxdoolllcclllooodddooooo -// ''......''''....| | ....'',,,,;;;::cclloooollc:;,''.'| |oxk| \OOO0| |KKK00Oxdoll|___|;;;;;::ccllllllcc::;;,,;;;:cclloooooooo -// ;;,''.......... | |_____',,;;;____:___cllo________.___| |___| \xkk| |KK_______ool___:::;________;;;_______...'',;;:ccclllloo -// c:;,''......... | |:::/ ' |lo/ | | \dx| |0/ \d| |cc/ |'/ \......',,;;:ccllo -// ol:;,'..........| _____|ll/ __ |o/ ______|____ ___| | \o| |/ ___ \| |o/ ______|/ ___ \ .......'',;:clo -// dlc;,...........| |::clooo| / | |x\___ \KXKKK0| |dol| |\ \| | | | | |d\___ \..| | / / ....',:cl -// xoc;'... .....'| |llodddd| \__| |_____\ \KKK0O| |lc:| |'\ | |___| | |_____\ \.| |_/___/... ...',;:c -// dlc;'... ....',;| |oddddddo\ | |Okkx| |::;| |..\ |\ /| | | \ |... ....',;:c -// ol:,'.......',:c|___|xxxddollc\_____,___|_________/ddoll|___|,,,|___|...\_____|:\ ______/l|___|_________/...\________|'........',;::cc +// ....';:ldkO0KXXXKK00Okxdolcc:;;;;;::cclllcc:;;,''..... +// ....',;clooddolcc:;;;;,,;;;;;::::;;;;;;:cloxk0KXNWWWWWWNXKK0Okxddoooddxxkkkkkxx +// .....';:ldxkOOOOOkxxdolcc:;;;,,,;;:cllooooolcc:;'... +// ..,:codxkkkxddooollloooooooollcc:::::clodkO0KXNWWWWWWNNXK00Okxxxxxxxxkkkkxxx +// . ....';:cloddddo___________,,,,;;:clooddddoolc:,... +// ..,:ldx__00OOOkkk___kkkkkkxxdollc::::cclodkO0KXXNNNNNNXXK0OOkxxxxxxxxxxxxddd +// .......',;:cccc:| |,,,;;:cclooddddoll:;'.. ..';cox| \KKK000| +// |KK00OOkxdocc___;::clldxxkO0KKKKK00Okkxdddddddddddddddoo +// .......'',,,,,''| ________|',,;;::cclloooooolc:;'......___:ldk| \KK000| +// |XKKK0Okxolc| |;;::cclodxxkkkkxxdoolllcclllooodddooooo +// ''......''''....| | ....'',,,,;;;::cclloooollc:;,''.'| |oxk| \OOO0| +// |KKK00Oxdoll|___|;;;;;::ccllllllcc::;;,,;;;:cclloooooooo +// ;;,''.......... | |_____',,;;;____:___cllo________.___| |___| \xkk| +// |KK_______ool___:::;________;;;_______...'',;;:ccclllloo c:;,''......... | +// |:::/ ' |lo/ | | \dx| |0/ \d| |cc/ |'/ +// \......',,;;:ccllo ol:;,'..........| _____|ll/ __ |o/ ______|____ +// ___| | \o| |/ ___ \| |o/ ______|/ ___ \ .......'',;:clo +// dlc;,...........| |::clooo| / | |x\___ \KXKKK0| |dol| |\ \| +// | | | | |d\___ \..| | / / ....',:cl xoc;'... .....'| +// |llodddd| \__| |_____\ \KKK0O| |lc:| |'\ | |___| | +// |_____\ \.| |_/___/... ...',;:c dlc;'... ....',;| |oddddddo\ | +// |Okkx| |::;| |..\ |\ /| | | \ |... +// ....',;:c +// ol:,'.......',:c|___|xxxddollc\_____,___|_________/ddoll|___|,,,|___|...\_____|:\ +// ______/l|___|_________/...\________|'........',;::cc // c:;'.......';:codxxkkkkxxolc::;::clodxkOO0OOkkxdollc::;;,,''''',,,,''''''''''',,'''''',;:loxkkOOkxol:;,'''',,;:ccllcc:;,'''''',;::ccll // ;,'.......',:codxkOO0OOkxdlc:;,,;;:cldxxkkxxdolc:;;,,''.....'',;;:::;;,,,'''''........,;cldkO0KK0Okdoc::;;::cloodddoolc:;;;;;::ccllooo // .........',;:lodxOO0000Okdoc:,,',,;:clloddoolc:;,''.......'',;:clooollc:;;,,''.......',:ldkOKXNNXX0Oxdolllloddxxxxxxdolccccccllooodddd -// . .....';:cldxkO0000Okxol:;,''',,;::cccc:;,,'.......'',;:cldxxkkxxdolc:;;,'.......';coxOKXNWWWNXKOkxddddxxkkkkkkxdoollllooddxxxxkkk +// . +// .....';:cldxkO0000Okxol:;,''',,;::cccc:;,,'.......'',;:cldxxkkxxdolc:;;,'.......';coxOKXNWWWNXKOkxddddxxkkkkkkxdoollllooddxxxxkkk // ....',;:codxkO000OOxdoc:;,''',,,;;;;,''.......',,;:clodkO00000Okxolc::;,,''..',;:ldxOKXNWWWNNK0OkkkkkkkkkkkxxddooooodxxkOOOOO000 // ....',;;clodxkkOOOkkdolc:;,,,,,,,,'..........,;:clodxkO0KKXKK0Okxdolcc::;;,,,;;:codkO0XXNNNNXKK0OOOOOkkkkxxdoollloodxkO0KKKXXXXX // @@ -54,20 +69,19 @@ // Switch between using floats or doubles for input position typedef float FNLfloat; -//typedef double FNLfloat; +// typedef double FNLfloat; #if defined(__cplusplus) extern "C" { #endif -#include -#include -#include #include +#include +#include +#include // Enums -typedef enum -{ +typedef enum { FNL_NOISE_OPENSIMPLEX2, FNL_NOISE_OPENSIMPLEX2S, FNL_NOISE_CELLULAR, @@ -76,15 +90,13 @@ typedef enum FNL_NOISE_VALUE } fnl_noise_type; -typedef enum -{ +typedef enum { FNL_ROTATION_NONE, FNL_ROTATION_IMPROVE_XY_PLANES, FNL_ROTATION_IMPROVE_XZ_PLANES } fnl_rotation_type_3d; -typedef enum -{ +typedef enum { FNL_FRACTAL_NONE, FNL_FRACTAL_FBM, FNL_FRACTAL_RIDGED, @@ -93,16 +105,14 @@ typedef enum FNL_FRACTAL_DOMAIN_WARP_INDEPENDENT } fnl_fractal_type; -typedef enum -{ +typedef enum { FNL_CELLULAR_DISTANCE_EUCLIDEAN, FNL_CELLULAR_DISTANCE_EUCLIDEANSQ, FNL_CELLULAR_DISTANCE_MANHATTAN, FNL_CELLULAR_DISTANCE_HYBRID } fnl_cellular_distance_func; -typedef enum -{ +typedef enum { FNL_CELLULAR_RETURN_VALUE_CELLVALUE, FNL_CELLULAR_RETURN_VALUE_DISTANCE, FNL_CELLULAR_RETURN_VALUE_DISTANCE2, @@ -112,8 +122,7 @@ typedef enum FNL_CELLULAR_RETURN_VALUE_DISTANCE2DIV, } fnl_cellular_return_type; -typedef enum -{ +typedef enum { FNL_DOMAIN_WARP_OPENSIMPLEX2, FNL_DOMAIN_WARP_OPENSIMPLEX2_REDUCED, FNL_DOMAIN_WARP_BASICGRID @@ -121,10 +130,10 @@ typedef enum /** * Structure containing entire noise system state. - * @note Must only be created using fnlCreateState(optional: seed). To ensure defaults are set. + * @note Must only be created using fnlCreateState(optional: seed). To ensure + * defaults are set. */ -typedef struct fnl_state -{ +typedef struct fnl_state { /** * Seed used for all noise types. * @remark Default: 1337 @@ -213,7 +222,8 @@ typedef struct fnl_state fnl_domain_warp_type domain_warp_type; /** - * The maximum warp distance from original position when using fnlDomainWarp... + * The maximum warp distance from original position when using + * fnlDomainWarp... * @remark Default: 1.0 */ float domain_warp_amp; @@ -267,146 +277,515 @@ void fnlDomainWarp3D(fnl_state *state, FNLfloat *x, FNLfloat *y, FNLfloat *z); // Constants -static const float GRADIENTS_2D[] = -{ - 0.130526192220052f, 0.99144486137381f, 0.38268343236509f, 0.923879532511287f, 0.608761429008721f, 0.793353340291235f, 0.793353340291235f, 0.608761429008721f, - 0.923879532511287f, 0.38268343236509f, 0.99144486137381f, 0.130526192220051f, 0.99144486137381f, -0.130526192220051f, 0.923879532511287f, -0.38268343236509f, - 0.793353340291235f, -0.60876142900872f, 0.608761429008721f, -0.793353340291235f, 0.38268343236509f, -0.923879532511287f, 0.130526192220052f, -0.99144486137381f, - -0.130526192220052f, -0.99144486137381f, -0.38268343236509f, -0.923879532511287f, -0.608761429008721f, -0.793353340291235f, -0.793353340291235f, -0.608761429008721f, - -0.923879532511287f, -0.38268343236509f, -0.99144486137381f, -0.130526192220052f, -0.99144486137381f, 0.130526192220051f, -0.923879532511287f, 0.38268343236509f, - -0.793353340291235f, 0.608761429008721f, -0.608761429008721f, 0.793353340291235f, -0.38268343236509f, 0.923879532511287f, -0.130526192220052f, 0.99144486137381f, - 0.130526192220052f, 0.99144486137381f, 0.38268343236509f, 0.923879532511287f, 0.608761429008721f, 0.793353340291235f, 0.793353340291235f, 0.608761429008721f, - 0.923879532511287f, 0.38268343236509f, 0.99144486137381f, 0.130526192220051f, 0.99144486137381f, -0.130526192220051f, 0.923879532511287f, -0.38268343236509f, - 0.793353340291235f, -0.60876142900872f, 0.608761429008721f, -0.793353340291235f, 0.38268343236509f, -0.923879532511287f, 0.130526192220052f, -0.99144486137381f, - -0.130526192220052f, -0.99144486137381f, -0.38268343236509f, -0.923879532511287f, -0.608761429008721f, -0.793353340291235f, -0.793353340291235f, -0.608761429008721f, - -0.923879532511287f, -0.38268343236509f, -0.99144486137381f, -0.130526192220052f, -0.99144486137381f, 0.130526192220051f, -0.923879532511287f, 0.38268343236509f, - -0.793353340291235f, 0.608761429008721f, -0.608761429008721f, 0.793353340291235f, -0.38268343236509f, 0.923879532511287f, -0.130526192220052f, 0.99144486137381f, - 0.130526192220052f, 0.99144486137381f, 0.38268343236509f, 0.923879532511287f, 0.608761429008721f, 0.793353340291235f, 0.793353340291235f, 0.608761429008721f, - 0.923879532511287f, 0.38268343236509f, 0.99144486137381f, 0.130526192220051f, 0.99144486137381f, -0.130526192220051f, 0.923879532511287f, -0.38268343236509f, - 0.793353340291235f, -0.60876142900872f, 0.608761429008721f, -0.793353340291235f, 0.38268343236509f, -0.923879532511287f, 0.130526192220052f, -0.99144486137381f, - -0.130526192220052f, -0.99144486137381f, -0.38268343236509f, -0.923879532511287f, -0.608761429008721f, -0.793353340291235f, -0.793353340291235f, -0.608761429008721f, - -0.923879532511287f, -0.38268343236509f, -0.99144486137381f, -0.130526192220052f, -0.99144486137381f, 0.130526192220051f, -0.923879532511287f, 0.38268343236509f, - -0.793353340291235f, 0.608761429008721f, -0.608761429008721f, 0.793353340291235f, -0.38268343236509f, 0.923879532511287f, -0.130526192220052f, 0.99144486137381f, - 0.130526192220052f, 0.99144486137381f, 0.38268343236509f, 0.923879532511287f, 0.608761429008721f, 0.793353340291235f, 0.793353340291235f, 0.608761429008721f, - 0.923879532511287f, 0.38268343236509f, 0.99144486137381f, 0.130526192220051f, 0.99144486137381f, -0.130526192220051f, 0.923879532511287f, -0.38268343236509f, - 0.793353340291235f, -0.60876142900872f, 0.608761429008721f, -0.793353340291235f, 0.38268343236509f, -0.923879532511287f, 0.130526192220052f, -0.99144486137381f, - -0.130526192220052f, -0.99144486137381f, -0.38268343236509f, -0.923879532511287f, -0.608761429008721f, -0.793353340291235f, -0.793353340291235f, -0.608761429008721f, - -0.923879532511287f, -0.38268343236509f, -0.99144486137381f, -0.130526192220052f, -0.99144486137381f, 0.130526192220051f, -0.923879532511287f, 0.38268343236509f, - -0.793353340291235f, 0.608761429008721f, -0.608761429008721f, 0.793353340291235f, -0.38268343236509f, 0.923879532511287f, -0.130526192220052f, 0.99144486137381f, - 0.130526192220052f, 0.99144486137381f, 0.38268343236509f, 0.923879532511287f, 0.608761429008721f, 0.793353340291235f, 0.793353340291235f, 0.608761429008721f, - 0.923879532511287f, 0.38268343236509f, 0.99144486137381f, 0.130526192220051f, 0.99144486137381f, -0.130526192220051f, 0.923879532511287f, -0.38268343236509f, - 0.793353340291235f, -0.60876142900872f, 0.608761429008721f, -0.793353340291235f, 0.38268343236509f, -0.923879532511287f, 0.130526192220052f, -0.99144486137381f, - -0.130526192220052f, -0.99144486137381f, -0.38268343236509f, -0.923879532511287f, -0.608761429008721f, -0.793353340291235f, -0.793353340291235f, -0.608761429008721f, - -0.923879532511287f, -0.38268343236509f, -0.99144486137381f, -0.130526192220052f, -0.99144486137381f, 0.130526192220051f, -0.923879532511287f, 0.38268343236509f, - -0.793353340291235f, 0.608761429008721f, -0.608761429008721f, 0.793353340291235f, -0.38268343236509f, 0.923879532511287f, -0.130526192220052f, 0.99144486137381f, - 0.38268343236509f, 0.923879532511287f, 0.923879532511287f, 0.38268343236509f, 0.923879532511287f, -0.38268343236509f, 0.38268343236509f, -0.923879532511287f, - -0.38268343236509f, -0.923879532511287f, -0.923879532511287f, -0.38268343236509f, -0.923879532511287f, 0.38268343236509f, -0.38268343236509f, 0.923879532511287f, +static const float GRADIENTS_2D[] = { + 0.130526192220052f, 0.99144486137381f, 0.38268343236509f, + 0.923879532511287f, 0.608761429008721f, 0.793353340291235f, + 0.793353340291235f, 0.608761429008721f, 0.923879532511287f, + 0.38268343236509f, 0.99144486137381f, 0.130526192220051f, + 0.99144486137381f, -0.130526192220051f, 0.923879532511287f, + -0.38268343236509f, 0.793353340291235f, -0.60876142900872f, + 0.608761429008721f, -0.793353340291235f, 0.38268343236509f, + -0.923879532511287f, 0.130526192220052f, -0.99144486137381f, + -0.130526192220052f, -0.99144486137381f, -0.38268343236509f, + -0.923879532511287f, -0.608761429008721f, -0.793353340291235f, + -0.793353340291235f, -0.608761429008721f, -0.923879532511287f, + -0.38268343236509f, -0.99144486137381f, -0.130526192220052f, + -0.99144486137381f, 0.130526192220051f, -0.923879532511287f, + 0.38268343236509f, -0.793353340291235f, 0.608761429008721f, + -0.608761429008721f, 0.793353340291235f, -0.38268343236509f, + 0.923879532511287f, -0.130526192220052f, 0.99144486137381f, + 0.130526192220052f, 0.99144486137381f, 0.38268343236509f, + 0.923879532511287f, 0.608761429008721f, 0.793353340291235f, + 0.793353340291235f, 0.608761429008721f, 0.923879532511287f, + 0.38268343236509f, 0.99144486137381f, 0.130526192220051f, + 0.99144486137381f, -0.130526192220051f, 0.923879532511287f, + -0.38268343236509f, 0.793353340291235f, -0.60876142900872f, + 0.608761429008721f, -0.793353340291235f, 0.38268343236509f, + -0.923879532511287f, 0.130526192220052f, -0.99144486137381f, + -0.130526192220052f, -0.99144486137381f, -0.38268343236509f, + -0.923879532511287f, -0.608761429008721f, -0.793353340291235f, + -0.793353340291235f, -0.608761429008721f, -0.923879532511287f, + -0.38268343236509f, -0.99144486137381f, -0.130526192220052f, + -0.99144486137381f, 0.130526192220051f, -0.923879532511287f, + 0.38268343236509f, -0.793353340291235f, 0.608761429008721f, + -0.608761429008721f, 0.793353340291235f, -0.38268343236509f, + 0.923879532511287f, -0.130526192220052f, 0.99144486137381f, + 0.130526192220052f, 0.99144486137381f, 0.38268343236509f, + 0.923879532511287f, 0.608761429008721f, 0.793353340291235f, + 0.793353340291235f, 0.608761429008721f, 0.923879532511287f, + 0.38268343236509f, 0.99144486137381f, 0.130526192220051f, + 0.99144486137381f, -0.130526192220051f, 0.923879532511287f, + -0.38268343236509f, 0.793353340291235f, -0.60876142900872f, + 0.608761429008721f, -0.793353340291235f, 0.38268343236509f, + -0.923879532511287f, 0.130526192220052f, -0.99144486137381f, + -0.130526192220052f, -0.99144486137381f, -0.38268343236509f, + -0.923879532511287f, -0.608761429008721f, -0.793353340291235f, + -0.793353340291235f, -0.608761429008721f, -0.923879532511287f, + -0.38268343236509f, -0.99144486137381f, -0.130526192220052f, + -0.99144486137381f, 0.130526192220051f, -0.923879532511287f, + 0.38268343236509f, -0.793353340291235f, 0.608761429008721f, + -0.608761429008721f, 0.793353340291235f, -0.38268343236509f, + 0.923879532511287f, -0.130526192220052f, 0.99144486137381f, + 0.130526192220052f, 0.99144486137381f, 0.38268343236509f, + 0.923879532511287f, 0.608761429008721f, 0.793353340291235f, + 0.793353340291235f, 0.608761429008721f, 0.923879532511287f, + 0.38268343236509f, 0.99144486137381f, 0.130526192220051f, + 0.99144486137381f, -0.130526192220051f, 0.923879532511287f, + -0.38268343236509f, 0.793353340291235f, -0.60876142900872f, + 0.608761429008721f, -0.793353340291235f, 0.38268343236509f, + -0.923879532511287f, 0.130526192220052f, -0.99144486137381f, + -0.130526192220052f, -0.99144486137381f, -0.38268343236509f, + -0.923879532511287f, -0.608761429008721f, -0.793353340291235f, + -0.793353340291235f, -0.608761429008721f, -0.923879532511287f, + -0.38268343236509f, -0.99144486137381f, -0.130526192220052f, + -0.99144486137381f, 0.130526192220051f, -0.923879532511287f, + 0.38268343236509f, -0.793353340291235f, 0.608761429008721f, + -0.608761429008721f, 0.793353340291235f, -0.38268343236509f, + 0.923879532511287f, -0.130526192220052f, 0.99144486137381f, + 0.130526192220052f, 0.99144486137381f, 0.38268343236509f, + 0.923879532511287f, 0.608761429008721f, 0.793353340291235f, + 0.793353340291235f, 0.608761429008721f, 0.923879532511287f, + 0.38268343236509f, 0.99144486137381f, 0.130526192220051f, + 0.99144486137381f, -0.130526192220051f, 0.923879532511287f, + -0.38268343236509f, 0.793353340291235f, -0.60876142900872f, + 0.608761429008721f, -0.793353340291235f, 0.38268343236509f, + -0.923879532511287f, 0.130526192220052f, -0.99144486137381f, + -0.130526192220052f, -0.99144486137381f, -0.38268343236509f, + -0.923879532511287f, -0.608761429008721f, -0.793353340291235f, + -0.793353340291235f, -0.608761429008721f, -0.923879532511287f, + -0.38268343236509f, -0.99144486137381f, -0.130526192220052f, + -0.99144486137381f, 0.130526192220051f, -0.923879532511287f, + 0.38268343236509f, -0.793353340291235f, 0.608761429008721f, + -0.608761429008721f, 0.793353340291235f, -0.38268343236509f, + 0.923879532511287f, -0.130526192220052f, 0.99144486137381f, + 0.38268343236509f, 0.923879532511287f, 0.923879532511287f, + 0.38268343236509f, 0.923879532511287f, -0.38268343236509f, + 0.38268343236509f, -0.923879532511287f, -0.38268343236509f, + -0.923879532511287f, -0.923879532511287f, -0.38268343236509f, + -0.923879532511287f, 0.38268343236509f, -0.38268343236509f, + 0.923879532511287f, }; -static const float RAND_VECS_2D[] = -{ - -0.2700222198f, -0.9628540911f, 0.3863092627f, -0.9223693152f, 0.04444859006f, -0.999011673f, -0.5992523158f, -0.8005602176f, -0.7819280288f, 0.6233687174f, 0.9464672271f, 0.3227999196f, -0.6514146797f, -0.7587218957f, 0.9378472289f, 0.347048376f, - -0.8497875957f, -0.5271252623f, -0.879042592f, 0.4767432447f, -0.892300288f, -0.4514423508f, -0.379844434f, -0.9250503802f, -0.9951650832f, 0.0982163789f, 0.7724397808f, -0.6350880136f, 0.7573283322f, -0.6530343002f, -0.9928004525f, -0.119780055f, - -0.0532665713f, 0.9985803285f, 0.9754253726f, -0.2203300762f, -0.7665018163f, 0.6422421394f, 0.991636706f, 0.1290606184f, -0.994696838f, 0.1028503788f, -0.5379205513f, -0.84299554f, 0.5022815471f, -0.8647041387f, 0.4559821461f, -0.8899889226f, - -0.8659131224f, -0.5001944266f, 0.0879458407f, -0.9961252577f, -0.5051684983f, 0.8630207346f, 0.7753185226f, -0.6315704146f, -0.6921944612f, 0.7217110418f, -0.5191659449f, -0.8546734591f, 0.8978622882f, -0.4402764035f, -0.1706774107f, 0.9853269617f, - -0.9353430106f, -0.3537420705f, -0.9992404798f, 0.03896746794f, -0.2882064021f, -0.9575683108f, -0.9663811329f, 0.2571137995f, -0.8759714238f, -0.4823630009f, -0.8303123018f, -0.5572983775f, 0.05110133755f, -0.9986934731f, -0.8558373281f, -0.5172450752f, - 0.09887025282f, 0.9951003332f, 0.9189016087f, 0.3944867976f, -0.2439375892f, -0.9697909324f, -0.8121409387f, -0.5834613061f, -0.9910431363f, 0.1335421355f, 0.8492423985f, -0.5280031709f, -0.9717838994f, -0.2358729591f, 0.9949457207f, 0.1004142068f, - 0.6241065508f, -0.7813392434f, 0.662910307f, 0.7486988212f, -0.7197418176f, 0.6942418282f, -0.8143370775f, -0.5803922158f, 0.104521054f, -0.9945226741f, -0.1065926113f, -0.9943027784f, 0.445799684f, -0.8951327509f, 0.105547406f, 0.9944142724f, - -0.992790267f, 0.1198644477f, -0.8334366408f, 0.552615025f, 0.9115561563f, -0.4111755999f, 0.8285544909f, -0.5599084351f, 0.7217097654f, -0.6921957921f, 0.4940492677f, -0.8694339084f, -0.3652321272f, -0.9309164803f, -0.9696606758f, 0.2444548501f, - 0.08925509731f, -0.996008799f, 0.5354071276f, -0.8445941083f, -0.1053576186f, 0.9944343981f, -0.9890284586f, 0.1477251101f, 0.004856104961f, 0.9999882091f, 0.9885598478f, 0.1508291331f, 0.9286129562f, -0.3710498316f, -0.5832393863f, -0.8123003252f, - 0.3015207509f, 0.9534596146f, -0.9575110528f, 0.2883965738f, 0.9715802154f, -0.2367105511f, 0.229981792f, 0.9731949318f, 0.955763816f, -0.2941352207f, 0.740956116f, 0.6715534485f, -0.9971513787f, -0.07542630764f, 0.6905710663f, -0.7232645452f, - -0.290713703f, -0.9568100872f, 0.5912777791f, -0.8064679708f, -0.9454592212f, -0.325740481f, 0.6664455681f, 0.74555369f, 0.6236134912f, 0.7817328275f, 0.9126993851f, -0.4086316587f, -0.8191762011f, 0.5735419353f, -0.8812745759f, -0.4726046147f, - 0.9953313627f, 0.09651672651f, 0.9855650846f, -0.1692969699f, -0.8495980887f, 0.5274306472f, 0.6174853946f, -0.7865823463f, 0.8508156371f, 0.52546432f, 0.9985032451f, -0.05469249926f, 0.1971371563f, -0.9803759185f, 0.6607855748f, -0.7505747292f, - -0.03097494063f, 0.9995201614f, -0.6731660801f, 0.739491331f, -0.7195018362f, -0.6944905383f, 0.9727511689f, 0.2318515979f, 0.9997059088f, -0.0242506907f, 0.4421787429f, -0.8969269532f, 0.9981350961f, -0.061043673f, -0.9173660799f, -0.3980445648f, - -0.8150056635f, -0.5794529907f, -0.8789331304f, 0.4769450202f, 0.0158605829f, 0.999874213f, -0.8095464474f, 0.5870558317f, -0.9165898907f, -0.3998286786f, -0.8023542565f, 0.5968480938f, -0.5176737917f, 0.8555780767f, -0.8154407307f, -0.5788405779f, - 0.4022010347f, -0.9155513791f, -0.9052556868f, -0.4248672045f, 0.7317445619f, 0.6815789728f, -0.5647632201f, -0.8252529947f, -0.8403276335f, -0.5420788397f, -0.9314281527f, 0.363925262f, 0.5238198472f, 0.8518290719f, 0.7432803869f, -0.6689800195f, - -0.985371561f, -0.1704197369f, 0.4601468731f, 0.88784281f, 0.825855404f, 0.5638819483f, 0.6182366099f, 0.7859920446f, 0.8331502863f, -0.553046653f, 0.1500307506f, 0.9886813308f, -0.662330369f, -0.7492119075f, -0.668598664f, 0.743623444f, - 0.7025606278f, 0.7116238924f, -0.5419389763f, -0.8404178401f, -0.3388616456f, 0.9408362159f, 0.8331530315f, 0.5530425174f, -0.2989720662f, -0.9542618632f, 0.2638522993f, 0.9645630949f, 0.124108739f, -0.9922686234f, -0.7282649308f, -0.6852956957f, - 0.6962500149f, 0.7177993569f, -0.9183535368f, 0.3957610156f, -0.6326102274f, -0.7744703352f, -0.9331891859f, -0.359385508f, -0.1153779357f, -0.9933216659f, 0.9514974788f, -0.3076565421f, -0.08987977445f, -0.9959526224f, 0.6678496916f, 0.7442961705f, - 0.7952400393f, -0.6062947138f, -0.6462007402f, -0.7631674805f, -0.2733598753f, 0.9619118351f, 0.9669590226f, -0.254931851f, -0.9792894595f, 0.2024651934f, -0.5369502995f, -0.8436138784f, -0.270036471f, -0.9628500944f, -0.6400277131f, 0.7683518247f, - -0.7854537493f, -0.6189203566f, 0.06005905383f, -0.9981948257f, -0.02455770378f, 0.9996984141f, -0.65983623f, 0.751409442f, -0.6253894466f, -0.7803127835f, -0.6210408851f, -0.7837781695f, 0.8348888491f, 0.5504185768f, -0.1592275245f, 0.9872419133f, - 0.8367622488f, 0.5475663786f, -0.8675753916f, -0.4973056806f, -0.2022662628f, -0.9793305667f, 0.9399189937f, 0.3413975472f, 0.9877404807f, -0.1561049093f, -0.9034455656f, 0.4287028224f, 0.1269804218f, -0.9919052235f, -0.3819600854f, 0.924178821f, - 0.9754625894f, 0.2201652486f, -0.3204015856f, -0.9472818081f, -0.9874760884f, 0.1577687387f, 0.02535348474f, -0.9996785487f, 0.4835130794f, -0.8753371362f, -0.2850799925f, -0.9585037287f, -0.06805516006f, -0.99768156f, -0.7885244045f, -0.6150034663f, - 0.3185392127f, -0.9479096845f, 0.8880043089f, 0.4598351306f, 0.6476921488f, -0.7619021462f, 0.9820241299f, 0.1887554194f, 0.9357275128f, -0.3527237187f, -0.8894895414f, 0.4569555293f, 0.7922791302f, 0.6101588153f, 0.7483818261f, 0.6632681526f, - -0.7288929755f, -0.6846276581f, 0.8729032783f, -0.4878932944f, 0.8288345784f, 0.5594937369f, 0.08074567077f, 0.9967347374f, 0.9799148216f, -0.1994165048f, -0.580730673f, -0.8140957471f, -0.4700049791f, -0.8826637636f, 0.2409492979f, 0.9705377045f, - 0.9437816757f, -0.3305694308f, -0.8927998638f, -0.4504535528f, -0.8069622304f, 0.5906030467f, 0.06258973166f, 0.9980393407f, -0.9312597469f, 0.3643559849f, 0.5777449785f, 0.8162173362f, -0.3360095855f, -0.941858566f, 0.697932075f, -0.7161639607f, - -0.002008157227f, -0.9999979837f, -0.1827294312f, -0.9831632392f, -0.6523911722f, 0.7578824173f, -0.4302626911f, -0.9027037258f, -0.9985126289f, -0.05452091251f, -0.01028102172f, -0.9999471489f, -0.4946071129f, 0.8691166802f, -0.2999350194f, 0.9539596344f, - 0.8165471961f, 0.5772786819f, 0.2697460475f, 0.962931498f, -0.7306287391f, -0.6827749597f, -0.7590952064f, -0.6509796216f, -0.907053853f, 0.4210146171f, -0.5104861064f, -0.8598860013f, 0.8613350597f, 0.5080373165f, 0.5007881595f, -0.8655698812f, - -0.654158152f, 0.7563577938f, -0.8382755311f, -0.545246856f, 0.6940070834f, 0.7199681717f, 0.06950936031f, 0.9975812994f, 0.1702942185f, -0.9853932612f, 0.2695973274f, 0.9629731466f, 0.5519612192f, -0.8338697815f, 0.225657487f, -0.9742067022f, - 0.4215262855f, -0.9068161835f, 0.4881873305f, -0.8727388672f, -0.3683854996f, -0.9296731273f, -0.9825390578f, 0.1860564427f, 0.81256471f, 0.5828709909f, 0.3196460933f, -0.9475370046f, 0.9570913859f, 0.2897862643f, -0.6876655497f, -0.7260276109f, - -0.9988770922f, -0.047376731f, -0.1250179027f, 0.992154486f, -0.8280133617f, 0.560708367f, 0.9324863769f, -0.3612051451f, 0.6394653183f, 0.7688199442f, -0.01623847064f, -0.9998681473f, -0.9955014666f, -0.09474613458f, -0.81453315f, 0.580117012f, - 0.4037327978f, -0.9148769469f, 0.9944263371f, 0.1054336766f, -0.1624711654f, 0.9867132919f, -0.9949487814f, -0.100383875f, -0.6995302564f, 0.7146029809f, 0.5263414922f, -0.85027327f, -0.5395221479f, 0.841971408f, 0.6579370318f, 0.7530729462f, - 0.01426758847f, -0.9998982128f, -0.6734383991f, 0.7392433447f, 0.639412098f, -0.7688642071f, 0.9211571421f, 0.3891908523f, -0.146637214f, -0.9891903394f, -0.782318098f, 0.6228791163f, -0.5039610839f, -0.8637263605f, -0.7743120191f, -0.6328039957f, +static const float RAND_VECS_2D[] = { + -0.2700222198f, -0.9628540911f, 0.3863092627f, -0.9223693152f, + 0.04444859006f, -0.999011673f, -0.5992523158f, -0.8005602176f, + -0.7819280288f, 0.6233687174f, 0.9464672271f, 0.3227999196f, + -0.6514146797f, -0.7587218957f, 0.9378472289f, 0.347048376f, + -0.8497875957f, -0.5271252623f, -0.879042592f, 0.4767432447f, + -0.892300288f, -0.4514423508f, -0.379844434f, -0.9250503802f, + -0.9951650832f, 0.0982163789f, 0.7724397808f, -0.6350880136f, + 0.7573283322f, -0.6530343002f, -0.9928004525f, -0.119780055f, + -0.0532665713f, 0.9985803285f, 0.9754253726f, -0.2203300762f, + -0.7665018163f, 0.6422421394f, 0.991636706f, 0.1290606184f, + -0.994696838f, 0.1028503788f, -0.5379205513f, -0.84299554f, + 0.5022815471f, -0.8647041387f, 0.4559821461f, -0.8899889226f, + -0.8659131224f, -0.5001944266f, 0.0879458407f, -0.9961252577f, + -0.5051684983f, 0.8630207346f, 0.7753185226f, -0.6315704146f, + -0.6921944612f, 0.7217110418f, -0.5191659449f, -0.8546734591f, + 0.8978622882f, -0.4402764035f, -0.1706774107f, 0.9853269617f, + -0.9353430106f, -0.3537420705f, -0.9992404798f, 0.03896746794f, + -0.2882064021f, -0.9575683108f, -0.9663811329f, 0.2571137995f, + -0.8759714238f, -0.4823630009f, -0.8303123018f, -0.5572983775f, + 0.05110133755f, -0.9986934731f, -0.8558373281f, -0.5172450752f, + 0.09887025282f, 0.9951003332f, 0.9189016087f, 0.3944867976f, + -0.2439375892f, -0.9697909324f, -0.8121409387f, -0.5834613061f, + -0.9910431363f, 0.1335421355f, 0.8492423985f, -0.5280031709f, + -0.9717838994f, -0.2358729591f, 0.9949457207f, 0.1004142068f, + 0.6241065508f, -0.7813392434f, 0.662910307f, 0.7486988212f, + -0.7197418176f, 0.6942418282f, -0.8143370775f, -0.5803922158f, + 0.104521054f, -0.9945226741f, -0.1065926113f, -0.9943027784f, + 0.445799684f, -0.8951327509f, 0.105547406f, 0.9944142724f, + -0.992790267f, 0.1198644477f, -0.8334366408f, 0.552615025f, + 0.9115561563f, -0.4111755999f, 0.8285544909f, -0.5599084351f, + 0.7217097654f, -0.6921957921f, 0.4940492677f, -0.8694339084f, + -0.3652321272f, -0.9309164803f, -0.9696606758f, 0.2444548501f, + 0.08925509731f, -0.996008799f, 0.5354071276f, -0.8445941083f, + -0.1053576186f, 0.9944343981f, -0.9890284586f, 0.1477251101f, + 0.004856104961f, 0.9999882091f, 0.9885598478f, 0.1508291331f, + 0.9286129562f, -0.3710498316f, -0.5832393863f, -0.8123003252f, + 0.3015207509f, 0.9534596146f, -0.9575110528f, 0.2883965738f, + 0.9715802154f, -0.2367105511f, 0.229981792f, 0.9731949318f, + 0.955763816f, -0.2941352207f, 0.740956116f, 0.6715534485f, + -0.9971513787f, -0.07542630764f, 0.6905710663f, -0.7232645452f, + -0.290713703f, -0.9568100872f, 0.5912777791f, -0.8064679708f, + -0.9454592212f, -0.325740481f, 0.6664455681f, 0.74555369f, + 0.6236134912f, 0.7817328275f, 0.9126993851f, -0.4086316587f, + -0.8191762011f, 0.5735419353f, -0.8812745759f, -0.4726046147f, + 0.9953313627f, 0.09651672651f, 0.9855650846f, -0.1692969699f, + -0.8495980887f, 0.5274306472f, 0.6174853946f, -0.7865823463f, + 0.8508156371f, 0.52546432f, 0.9985032451f, -0.05469249926f, + 0.1971371563f, -0.9803759185f, 0.6607855748f, -0.7505747292f, + -0.03097494063f, 0.9995201614f, -0.6731660801f, 0.739491331f, + -0.7195018362f, -0.6944905383f, 0.9727511689f, 0.2318515979f, + 0.9997059088f, -0.0242506907f, 0.4421787429f, -0.8969269532f, + 0.9981350961f, -0.061043673f, -0.9173660799f, -0.3980445648f, + -0.8150056635f, -0.5794529907f, -0.8789331304f, 0.4769450202f, + 0.0158605829f, 0.999874213f, -0.8095464474f, 0.5870558317f, + -0.9165898907f, -0.3998286786f, -0.8023542565f, 0.5968480938f, + -0.5176737917f, 0.8555780767f, -0.8154407307f, -0.5788405779f, + 0.4022010347f, -0.9155513791f, -0.9052556868f, -0.4248672045f, + 0.7317445619f, 0.6815789728f, -0.5647632201f, -0.8252529947f, + -0.8403276335f, -0.5420788397f, -0.9314281527f, 0.363925262f, + 0.5238198472f, 0.8518290719f, 0.7432803869f, -0.6689800195f, + -0.985371561f, -0.1704197369f, 0.4601468731f, 0.88784281f, + 0.825855404f, 0.5638819483f, 0.6182366099f, 0.7859920446f, + 0.8331502863f, -0.553046653f, 0.1500307506f, 0.9886813308f, + -0.662330369f, -0.7492119075f, -0.668598664f, 0.743623444f, + 0.7025606278f, 0.7116238924f, -0.5419389763f, -0.8404178401f, + -0.3388616456f, 0.9408362159f, 0.8331530315f, 0.5530425174f, + -0.2989720662f, -0.9542618632f, 0.2638522993f, 0.9645630949f, + 0.124108739f, -0.9922686234f, -0.7282649308f, -0.6852956957f, + 0.6962500149f, 0.7177993569f, -0.9183535368f, 0.3957610156f, + -0.6326102274f, -0.7744703352f, -0.9331891859f, -0.359385508f, + -0.1153779357f, -0.9933216659f, 0.9514974788f, -0.3076565421f, + -0.08987977445f, -0.9959526224f, 0.6678496916f, 0.7442961705f, + 0.7952400393f, -0.6062947138f, -0.6462007402f, -0.7631674805f, + -0.2733598753f, 0.9619118351f, 0.9669590226f, -0.254931851f, + -0.9792894595f, 0.2024651934f, -0.5369502995f, -0.8436138784f, + -0.270036471f, -0.9628500944f, -0.6400277131f, 0.7683518247f, + -0.7854537493f, -0.6189203566f, 0.06005905383f, -0.9981948257f, + -0.02455770378f, 0.9996984141f, -0.65983623f, 0.751409442f, + -0.6253894466f, -0.7803127835f, -0.6210408851f, -0.7837781695f, + 0.8348888491f, 0.5504185768f, -0.1592275245f, 0.9872419133f, + 0.8367622488f, 0.5475663786f, -0.8675753916f, -0.4973056806f, + -0.2022662628f, -0.9793305667f, 0.9399189937f, 0.3413975472f, + 0.9877404807f, -0.1561049093f, -0.9034455656f, 0.4287028224f, + 0.1269804218f, -0.9919052235f, -0.3819600854f, 0.924178821f, + 0.9754625894f, 0.2201652486f, -0.3204015856f, -0.9472818081f, + -0.9874760884f, 0.1577687387f, 0.02535348474f, -0.9996785487f, + 0.4835130794f, -0.8753371362f, -0.2850799925f, -0.9585037287f, + -0.06805516006f, -0.99768156f, -0.7885244045f, -0.6150034663f, + 0.3185392127f, -0.9479096845f, 0.8880043089f, 0.4598351306f, + 0.6476921488f, -0.7619021462f, 0.9820241299f, 0.1887554194f, + 0.9357275128f, -0.3527237187f, -0.8894895414f, 0.4569555293f, + 0.7922791302f, 0.6101588153f, 0.7483818261f, 0.6632681526f, + -0.7288929755f, -0.6846276581f, 0.8729032783f, -0.4878932944f, + 0.8288345784f, 0.5594937369f, 0.08074567077f, 0.9967347374f, + 0.9799148216f, -0.1994165048f, -0.580730673f, -0.8140957471f, + -0.4700049791f, -0.8826637636f, 0.2409492979f, 0.9705377045f, + 0.9437816757f, -0.3305694308f, -0.8927998638f, -0.4504535528f, + -0.8069622304f, 0.5906030467f, 0.06258973166f, 0.9980393407f, + -0.9312597469f, 0.3643559849f, 0.5777449785f, 0.8162173362f, + -0.3360095855f, -0.941858566f, 0.697932075f, -0.7161639607f, + -0.002008157227f, -0.9999979837f, -0.1827294312f, -0.9831632392f, + -0.6523911722f, 0.7578824173f, -0.4302626911f, -0.9027037258f, + -0.9985126289f, -0.05452091251f, -0.01028102172f, -0.9999471489f, + -0.4946071129f, 0.8691166802f, -0.2999350194f, 0.9539596344f, + 0.8165471961f, 0.5772786819f, 0.2697460475f, 0.962931498f, + -0.7306287391f, -0.6827749597f, -0.7590952064f, -0.6509796216f, + -0.907053853f, 0.4210146171f, -0.5104861064f, -0.8598860013f, + 0.8613350597f, 0.5080373165f, 0.5007881595f, -0.8655698812f, + -0.654158152f, 0.7563577938f, -0.8382755311f, -0.545246856f, + 0.6940070834f, 0.7199681717f, 0.06950936031f, 0.9975812994f, + 0.1702942185f, -0.9853932612f, 0.2695973274f, 0.9629731466f, + 0.5519612192f, -0.8338697815f, 0.225657487f, -0.9742067022f, + 0.4215262855f, -0.9068161835f, 0.4881873305f, -0.8727388672f, + -0.3683854996f, -0.9296731273f, -0.9825390578f, 0.1860564427f, + 0.81256471f, 0.5828709909f, 0.3196460933f, -0.9475370046f, + 0.9570913859f, 0.2897862643f, -0.6876655497f, -0.7260276109f, + -0.9988770922f, -0.047376731f, -0.1250179027f, 0.992154486f, + -0.8280133617f, 0.560708367f, 0.9324863769f, -0.3612051451f, + 0.6394653183f, 0.7688199442f, -0.01623847064f, -0.9998681473f, + -0.9955014666f, -0.09474613458f, -0.81453315f, 0.580117012f, + 0.4037327978f, -0.9148769469f, 0.9944263371f, 0.1054336766f, + -0.1624711654f, 0.9867132919f, -0.9949487814f, -0.100383875f, + -0.6995302564f, 0.7146029809f, 0.5263414922f, -0.85027327f, + -0.5395221479f, 0.841971408f, 0.6579370318f, 0.7530729462f, + 0.01426758847f, -0.9998982128f, -0.6734383991f, 0.7392433447f, + 0.639412098f, -0.7688642071f, 0.9211571421f, 0.3891908523f, + -0.146637214f, -0.9891903394f, -0.782318098f, 0.6228791163f, + -0.5039610839f, -0.8637263605f, -0.7743120191f, -0.6328039957f, }; -static const float GRADIENTS_3D[] = -{ - 0, 1, 1, 0, 0,-1, 1, 0, 0, 1,-1, 0, 0,-1,-1, 0, - 1, 0, 1, 0, -1, 0, 1, 0, 1, 0,-1, 0, -1, 0,-1, 0, - 1, 1, 0, 0, -1, 1, 0, 0, 1,-1, 0, 0, -1,-1, 0, 0, - 0, 1, 1, 0, 0,-1, 1, 0, 0, 1,-1, 0, 0,-1,-1, 0, - 1, 0, 1, 0, -1, 0, 1, 0, 1, 0,-1, 0, -1, 0,-1, 0, - 1, 1, 0, 0, -1, 1, 0, 0, 1,-1, 0, 0, -1,-1, 0, 0, - 0, 1, 1, 0, 0,-1, 1, 0, 0, 1,-1, 0, 0,-1,-1, 0, - 1, 0, 1, 0, -1, 0, 1, 0, 1, 0,-1, 0, -1, 0,-1, 0, - 1, 1, 0, 0, -1, 1, 0, 0, 1,-1, 0, 0, -1,-1, 0, 0, - 0, 1, 1, 0, 0,-1, 1, 0, 0, 1,-1, 0, 0,-1,-1, 0, - 1, 0, 1, 0, -1, 0, 1, 0, 1, 0,-1, 0, -1, 0,-1, 0, - 1, 1, 0, 0, -1, 1, 0, 0, 1,-1, 0, 0, -1,-1, 0, 0, - 0, 1, 1, 0, 0,-1, 1, 0, 0, 1,-1, 0, 0,-1,-1, 0, - 1, 0, 1, 0, -1, 0, 1, 0, 1, 0,-1, 0, -1, 0,-1, 0, - 1, 1, 0, 0, -1, 1, 0, 0, 1,-1, 0, 0, -1,-1, 0, 0, - 1, 1, 0, 0, 0,-1, 1, 0, -1, 1, 0, 0, 0,-1,-1, 0 -}; +static const float GRADIENTS_3D[] = { + 0, 1, 1, 0, 0, -1, 1, 0, 0, 1, -1, 0, 0, -1, -1, 0, 1, 0, 1, 0, + -1, 0, 1, 0, 1, 0, -1, 0, -1, 0, -1, 0, 1, 1, 0, 0, -1, 1, 0, 0, + 1, -1, 0, 0, -1, -1, 0, 0, 0, 1, 1, 0, 0, -1, 1, 0, 0, 1, -1, 0, + 0, -1, -1, 0, 1, 0, 1, 0, -1, 0, 1, 0, 1, 0, -1, 0, -1, 0, -1, 0, + 1, 1, 0, 0, -1, 1, 0, 0, 1, -1, 0, 0, -1, -1, 0, 0, 0, 1, 1, 0, + 0, -1, 1, 0, 0, 1, -1, 0, 0, -1, -1, 0, 1, 0, 1, 0, -1, 0, 1, 0, + 1, 0, -1, 0, -1, 0, -1, 0, 1, 1, 0, 0, -1, 1, 0, 0, 1, -1, 0, 0, + -1, -1, 0, 0, 0, 1, 1, 0, 0, -1, 1, 0, 0, 1, -1, 0, 0, -1, -1, 0, + 1, 0, 1, 0, -1, 0, 1, 0, 1, 0, -1, 0, -1, 0, -1, 0, 1, 1, 0, 0, + -1, 1, 0, 0, 1, -1, 0, 0, -1, -1, 0, 0, 0, 1, 1, 0, 0, -1, 1, 0, + 0, 1, -1, 0, 0, -1, -1, 0, 1, 0, 1, 0, -1, 0, 1, 0, 1, 0, -1, 0, + -1, 0, -1, 0, 1, 1, 0, 0, -1, 1, 0, 0, 1, -1, 0, 0, -1, -1, 0, 0, + 1, 1, 0, 0, 0, -1, 1, 0, -1, 1, 0, 0, 0, -1, -1, 0}; -static const float RAND_VECS_3D[] = -{ - -0.7292736885f, -0.6618439697f, 0.1735581948f, 0, 0.790292081f, -0.5480887466f, -0.2739291014f, 0, 0.7217578935f, 0.6226212466f, -0.3023380997f, 0, 0.565683137f, -0.8208298145f, -0.0790000257f, 0, 0.760049034f, -0.5555979497f, -0.3370999617f, 0, 0.3713945616f, 0.5011264475f, 0.7816254623f, 0, -0.1277062463f, -0.4254438999f, -0.8959289049f, 0, -0.2881560924f, -0.5815838982f, 0.7607405838f, 0, - 0.5849561111f, -0.662820239f, -0.4674352136f, 0, 0.3307171178f, 0.0391653737f, 0.94291689f, 0, 0.8712121778f, -0.4113374369f, -0.2679381538f, 0, 0.580981015f, 0.7021915846f, 0.4115677815f, 0, 0.503756873f, 0.6330056931f, -0.5878203852f, 0, 0.4493712205f, 0.601390195f, 0.6606022552f, 0, -0.6878403724f, 0.09018890807f, -0.7202371714f, 0, -0.5958956522f, -0.6469350577f, 0.475797649f, 0, - -0.5127052122f, 0.1946921978f, -0.8361987284f, 0, -0.9911507142f, -0.05410276466f, -0.1212153153f, 0, -0.2149721042f, 0.9720882117f, -0.09397607749f, 0, -0.7518650936f, -0.5428057603f, 0.3742469607f, 0, 0.5237068895f, 0.8516377189f, -0.02107817834f, 0, 0.6333504779f, 0.1926167129f, -0.7495104896f, 0, -0.06788241606f, 0.3998305789f, 0.9140719259f, 0, -0.5538628599f, -0.4729896695f, -0.6852128902f, 0, - -0.7261455366f, -0.5911990757f, 0.3509933228f, 0, -0.9229274737f, -0.1782808786f, 0.3412049336f, 0, -0.6968815002f, 0.6511274338f, 0.3006480328f, 0, 0.9608044783f, -0.2098363234f, -0.1811724921f, 0, 0.06817146062f, -0.9743405129f, 0.2145069156f, 0, -0.3577285196f, -0.6697087264f, -0.6507845481f, 0, -0.1868621131f, 0.7648617052f, -0.6164974636f, 0, -0.6541697588f, 0.3967914832f, 0.6439087246f, 0, - 0.6993340405f, -0.6164538506f, 0.3618239211f, 0, -0.1546665739f, 0.6291283928f, 0.7617583057f, 0, -0.6841612949f, -0.2580482182f, -0.6821542638f, 0, 0.5383980957f, 0.4258654885f, 0.7271630328f, 0, -0.5026987823f, -0.7939832935f, -0.3418836993f, 0, 0.3202971715f, 0.2834415347f, 0.9039195862f, 0, 0.8683227101f, -0.0003762656404f, -0.4959995258f, 0, 0.791120031f, -0.08511045745f, 0.6057105799f, 0, - -0.04011016052f, -0.4397248749f, 0.8972364289f, 0, 0.9145119872f, 0.3579346169f, -0.1885487608f, 0, -0.9612039066f, -0.2756484276f, 0.01024666929f, 0, 0.6510361721f, -0.2877799159f, -0.7023778346f, 0, -0.2041786351f, 0.7365237271f, 0.644859585f, 0, -0.7718263711f, 0.3790626912f, 0.5104855816f, 0, -0.3060082741f, -0.7692987727f, 0.5608371729f, 0, 0.454007341f, -0.5024843065f, 0.7357899537f, 0, - 0.4816795475f, 0.6021208291f, -0.6367380315f, 0, 0.6961980369f, -0.3222197429f, 0.641469197f, 0, -0.6532160499f, -0.6781148932f, 0.3368515753f, 0, 0.5089301236f, -0.6154662304f, -0.6018234363f, 0, -0.1635919754f, -0.9133604627f, -0.372840892f, 0, 0.52408019f, -0.8437664109f, 0.1157505864f, 0, 0.5902587356f, 0.4983817807f, -0.6349883666f, 0, 0.5863227872f, 0.494764745f, 0.6414307729f, 0, - 0.6779335087f, 0.2341345225f, 0.6968408593f, 0, 0.7177054546f, -0.6858979348f, 0.120178631f, 0, -0.5328819713f, -0.5205125012f, 0.6671608058f, 0, -0.8654874251f, -0.0700727088f, -0.4960053754f, 0, -0.2861810166f, 0.7952089234f, 0.5345495242f, 0, -0.04849529634f, 0.9810836427f, -0.1874115585f, 0, -0.6358521667f, 0.6058348682f, 0.4781800233f, 0, 0.6254794696f, -0.2861619734f, 0.7258696564f, 0, - -0.2585259868f, 0.5061949264f, -0.8227581726f, 0, 0.02136306781f, 0.5064016808f, -0.8620330371f, 0, 0.200111773f, 0.8599263484f, 0.4695550591f, 0, 0.4743561372f, 0.6014985084f, -0.6427953014f, 0, 0.6622993731f, -0.5202474575f, -0.5391679918f, 0, 0.08084972818f, -0.6532720452f, 0.7527940996f, 0, -0.6893687501f, 0.0592860349f, 0.7219805347f, 0, -0.1121887082f, -0.9673185067f, 0.2273952515f, 0, - 0.7344116094f, 0.5979668656f, -0.3210532909f, 0, 0.5789393465f, -0.2488849713f, 0.7764570201f, 0, 0.6988182827f, 0.3557169806f, -0.6205791146f, 0, -0.8636845529f, -0.2748771249f, -0.4224826141f, 0, -0.4247027957f, -0.4640880967f, 0.777335046f, 0, 0.5257722489f, -0.8427017621f, 0.1158329937f, 0, 0.9343830603f, 0.316302472f, -0.1639543925f, 0, -0.1016836419f, -0.8057303073f, -0.5834887393f, 0, - -0.6529238969f, 0.50602126f, -0.5635892736f, 0, -0.2465286165f, -0.9668205684f, -0.06694497494f, 0, -0.9776897119f, -0.2099250524f, -0.007368825344f, 0, 0.7736893337f, 0.5734244712f, 0.2694238123f, 0, -0.6095087895f, 0.4995678998f, 0.6155736747f, 0, 0.5794535482f, 0.7434546771f, 0.3339292269f, 0, -0.8226211154f, 0.08142581855f, 0.5627293636f, 0, -0.510385483f, 0.4703667658f, 0.7199039967f, 0, - -0.5764971849f, -0.07231656274f, -0.8138926898f, 0, 0.7250628871f, 0.3949971505f, -0.5641463116f, 0, -0.1525424005f, 0.4860840828f, -0.8604958341f, 0, -0.5550976208f, -0.4957820792f, 0.667882296f, 0, -0.1883614327f, 0.9145869398f, 0.357841725f, 0, 0.7625556724f, -0.5414408243f, -0.3540489801f, 0, -0.5870231946f, -0.3226498013f, -0.7424963803f, 0, 0.3051124198f, 0.2262544068f, -0.9250488391f, 0, - 0.6379576059f, 0.577242424f, -0.5097070502f, 0, -0.5966775796f, 0.1454852398f, -0.7891830656f, 0, -0.658330573f, 0.6555487542f, -0.3699414651f, 0, 0.7434892426f, 0.2351084581f, 0.6260573129f, 0, 0.5562114096f, 0.8264360377f, -0.0873632843f, 0, -0.3028940016f, -0.8251527185f, 0.4768419182f, 0, 0.1129343818f, -0.985888439f, -0.1235710781f, 0, 0.5937652891f, -0.5896813806f, 0.5474656618f, 0, - 0.6757964092f, -0.5835758614f, -0.4502648413f, 0, 0.7242302609f, -0.1152719764f, 0.6798550586f, 0, -0.9511914166f, 0.0753623979f, -0.2992580792f, 0, 0.2539470961f, -0.1886339355f, 0.9486454084f, 0, 0.571433621f, -0.1679450851f, -0.8032795685f, 0, -0.06778234979f, 0.3978269256f, 0.9149531629f, 0, 0.6074972649f, 0.733060024f, -0.3058922593f, 0, -0.5435478392f, 0.1675822484f, 0.8224791405f, 0, - -0.5876678086f, -0.3380045064f, -0.7351186982f, 0, -0.7967562402f, 0.04097822706f, -0.6029098428f, 0, -0.1996350917f, 0.8706294745f, 0.4496111079f, 0, -0.02787660336f, -0.9106232682f, -0.4122962022f, 0, -0.7797625996f, -0.6257634692f, 0.01975775581f, 0, -0.5211232846f, 0.7401644346f, -0.4249554471f, 0, 0.8575424857f, 0.4053272873f, -0.3167501783f, 0, 0.1045223322f, 0.8390195772f, -0.5339674439f, 0, - 0.3501822831f, 0.9242524096f, -0.1520850155f, 0, 0.1987849858f, 0.07647613266f, 0.9770547224f, 0, 0.7845996363f, 0.6066256811f, -0.1280964233f, 0, 0.09006737436f, -0.9750989929f, -0.2026569073f, 0, -0.8274343547f, -0.542299559f, 0.1458203587f, 0, -0.3485797732f, -0.415802277f, 0.840000362f, 0, -0.2471778936f, -0.7304819962f, -0.6366310879f, 0, -0.3700154943f, 0.8577948156f, 0.3567584454f, 0, - 0.5913394901f, -0.548311967f, -0.5913303597f, 0, 0.1204873514f, -0.7626472379f, -0.6354935001f, 0, 0.616959265f, 0.03079647928f, 0.7863922953f, 0, 0.1258156836f, -0.6640829889f, -0.7369967419f, 0, -0.6477565124f, -0.1740147258f, -0.7417077429f, 0, 0.6217889313f, -0.7804430448f, -0.06547655076f, 0, 0.6589943422f, -0.6096987708f, 0.4404473475f, 0, -0.2689837504f, -0.6732403169f, -0.6887635427f, 0, - -0.3849775103f, 0.5676542638f, 0.7277093879f, 0, 0.5754444408f, 0.8110471154f, -0.1051963504f, 0, 0.9141593684f, 0.3832947817f, 0.131900567f, 0, -0.107925319f, 0.9245493968f, 0.3654593525f, 0, 0.377977089f, 0.3043148782f, 0.8743716458f, 0, -0.2142885215f, -0.8259286236f, 0.5214617324f, 0, 0.5802544474f, 0.4148098596f, -0.7008834116f, 0, -0.1982660881f, 0.8567161266f, -0.4761596756f, 0, - -0.03381553704f, 0.3773180787f, -0.9254661404f, 0, -0.6867922841f, -0.6656597827f, 0.2919133642f, 0, 0.7731742607f, -0.2875793547f, -0.5652430251f, 0, -0.09655941928f, 0.9193708367f, -0.3813575004f, 0, 0.2715702457f, -0.9577909544f, -0.09426605581f, 0, 0.2451015704f, -0.6917998565f, -0.6792188003f, 0, 0.977700782f, -0.1753855374f, 0.1155036542f, 0, -0.5224739938f, 0.8521606816f, 0.02903615945f, 0, - -0.7734880599f, -0.5261292347f, 0.3534179531f, 0, -0.7134492443f, -0.269547243f, 0.6467878011f, 0, 0.1644037271f, 0.5105846203f, -0.8439637196f, 0, 0.6494635788f, 0.05585611296f, 0.7583384168f, 0, -0.4711970882f, 0.5017280509f, -0.7254255765f, 0, -0.6335764307f, -0.2381686273f, -0.7361091029f, 0, -0.9021533097f, -0.270947803f, -0.3357181763f, 0, -0.3793711033f, 0.872258117f, 0.3086152025f, 0, - -0.6855598966f, -0.3250143309f, 0.6514394162f, 0, 0.2900942212f, -0.7799057743f, -0.5546100667f, 0, -0.2098319339f, 0.85037073f, 0.4825351604f, 0, -0.4592603758f, 0.6598504336f, -0.5947077538f, 0, 0.8715945488f, 0.09616365406f, -0.4807031248f, 0, -0.6776666319f, 0.7118504878f, -0.1844907016f, 0, 0.7044377633f, 0.312427597f, 0.637304036f, 0, -0.7052318886f, -0.2401093292f, -0.6670798253f, 0, - 0.081921007f, -0.7207336136f, -0.6883545647f, 0, -0.6993680906f, -0.5875763221f, -0.4069869034f, 0, -0.1281454481f, 0.6419895885f, 0.7559286424f, 0, -0.6337388239f, -0.6785471501f, -0.3714146849f, 0, 0.5565051903f, -0.2168887573f, -0.8020356851f, 0, -0.5791554484f, 0.7244372011f, -0.3738578718f, 0, 0.1175779076f, -0.7096451073f, 0.6946792478f, 0, -0.6134619607f, 0.1323631078f, 0.7785527795f, 0, - 0.6984635305f, -0.02980516237f, -0.715024719f, 0, 0.8318082963f, -0.3930171956f, 0.3919597455f, 0, 0.1469576422f, 0.05541651717f, -0.9875892167f, 0, 0.708868575f, -0.2690503865f, 0.6520101478f, 0, 0.2726053183f, 0.67369766f, -0.68688995f, 0, -0.6591295371f, 0.3035458599f, -0.6880466294f, 0, 0.4815131379f, -0.7528270071f, 0.4487723203f, 0, 0.9430009463f, 0.1675647412f, -0.2875261255f, 0, - 0.434802957f, 0.7695304522f, -0.4677277752f, 0, 0.3931996188f, 0.594473625f, 0.7014236729f, 0, 0.7254336655f, -0.603925654f, 0.3301814672f, 0, 0.7590235227f, -0.6506083235f, 0.02433313207f, 0, -0.8552768592f, -0.3430042733f, 0.3883935666f, 0, -0.6139746835f, 0.6981725247f, 0.3682257648f, 0, -0.7465905486f, -0.5752009504f, 0.3342849376f, 0, 0.5730065677f, 0.810555537f, -0.1210916791f, 0, - -0.9225877367f, -0.3475211012f, -0.167514036f, 0, -0.7105816789f, -0.4719692027f, -0.5218416899f, 0, -0.08564609717f, 0.3583001386f, 0.929669703f, 0, -0.8279697606f, -0.2043157126f, 0.5222271202f, 0, 0.427944023f, 0.278165994f, 0.8599346446f, 0, 0.5399079671f, -0.7857120652f, -0.3019204161f, 0, 0.5678404253f, -0.5495413974f, -0.6128307303f, 0, -0.9896071041f, 0.1365639107f, -0.04503418428f, 0, - -0.6154342638f, -0.6440875597f, 0.4543037336f, 0, 0.1074204368f, -0.7946340692f, 0.5975094525f, 0, -0.3595449969f, -0.8885529948f, 0.28495784f, 0, -0.2180405296f, 0.1529888965f, 0.9638738118f, 0, -0.7277432317f, -0.6164050508f, -0.3007234646f, 0, 0.7249729114f, -0.00669719484f, 0.6887448187f, 0, -0.5553659455f, -0.5336586252f, 0.6377908264f, 0, 0.5137558015f, 0.7976208196f, -0.3160000073f, 0, - -0.3794024848f, 0.9245608561f, -0.03522751494f, 0, 0.8229248658f, 0.2745365933f, -0.4974176556f, 0, -0.5404114394f, 0.6091141441f, 0.5804613989f, 0, 0.8036581901f, -0.2703029469f, 0.5301601931f, 0, 0.6044318879f, 0.6832968393f, 0.4095943388f, 0, 0.06389988817f, 0.9658208605f, -0.2512108074f, 0, 0.1087113286f, 0.7402471173f, -0.6634877936f, 0, -0.713427712f, -0.6926784018f, 0.1059128479f, 0, - 0.6458897819f, -0.5724548511f, -0.5050958653f, 0, -0.6553931414f, 0.7381471625f, 0.159995615f, 0, 0.3910961323f, 0.9188871375f, -0.05186755998f, 0, -0.4879022471f, -0.5904376907f, 0.6429111375f, 0, 0.6014790094f, 0.7707441366f, -0.2101820095f, 0, -0.5677173047f, 0.7511360995f, 0.3368851762f, 0, 0.7858573506f, 0.226674665f, 0.5753666838f, 0, -0.4520345543f, -0.604222686f, -0.6561857263f, 0, - 0.002272116345f, 0.4132844051f, -0.9105991643f, 0, -0.5815751419f, -0.5162925989f, 0.6286591339f, 0, -0.03703704785f, 0.8273785755f, 0.5604221175f, 0, -0.5119692504f, 0.7953543429f, -0.3244980058f, 0, -0.2682417366f, -0.9572290247f, -0.1084387619f, 0, -0.2322482736f, -0.9679131102f, -0.09594243324f, 0, 0.3554328906f, -0.8881505545f, 0.2913006227f, 0, 0.7346520519f, -0.4371373164f, 0.5188422971f, 0, - 0.9985120116f, 0.04659011161f, -0.02833944577f, 0, -0.3727687496f, -0.9082481361f, 0.1900757285f, 0, 0.91737377f, -0.3483642108f, 0.1925298489f, 0, 0.2714911074f, 0.4147529736f, -0.8684886582f, 0, 0.5131763485f, -0.7116334161f, 0.4798207128f, 0, -0.8737353606f, 0.18886992f, -0.4482350644f, 0, 0.8460043821f, -0.3725217914f, 0.3814499973f, 0, 0.8978727456f, -0.1780209141f, -0.4026575304f, 0, - 0.2178065647f, -0.9698322841f, -0.1094789531f, 0, -0.1518031304f, -0.7788918132f, -0.6085091231f, 0, -0.2600384876f, -0.4755398075f, -0.8403819825f, 0, 0.572313509f, -0.7474340931f, -0.3373418503f, 0, -0.7174141009f, 0.1699017182f, -0.6756111411f, 0, -0.684180784f, 0.02145707593f, -0.7289967412f, 0, -0.2007447902f, 0.06555605789f, -0.9774476623f, 0, -0.1148803697f, -0.8044887315f, 0.5827524187f, 0, - -0.7870349638f, 0.03447489231f, 0.6159443543f, 0, -0.2015596421f, 0.6859872284f, 0.6991389226f, 0, -0.08581082512f, -0.10920836f, -0.9903080513f, 0, 0.5532693395f, 0.7325250401f, -0.396610771f, 0, -0.1842489331f, -0.9777375055f, -0.1004076743f, 0, 0.0775473789f, -0.9111505856f, 0.4047110257f, 0, 0.1399838409f, 0.7601631212f, -0.6344734459f, 0, 0.4484419361f, -0.845289248f, 0.2904925424f, 0 -}; +static const float RAND_VECS_3D[] = { + -0.7292736885f, -0.6618439697f, 0.1735581948f, 0, + 0.790292081f, -0.5480887466f, -0.2739291014f, 0, + 0.7217578935f, 0.6226212466f, -0.3023380997f, 0, + 0.565683137f, -0.8208298145f, -0.0790000257f, 0, + 0.760049034f, -0.5555979497f, -0.3370999617f, 0, + 0.3713945616f, 0.5011264475f, 0.7816254623f, 0, + -0.1277062463f, -0.4254438999f, -0.8959289049f, 0, + -0.2881560924f, -0.5815838982f, 0.7607405838f, 0, + 0.5849561111f, -0.662820239f, -0.4674352136f, 0, + 0.3307171178f, 0.0391653737f, 0.94291689f, 0, + 0.8712121778f, -0.4113374369f, -0.2679381538f, 0, + 0.580981015f, 0.7021915846f, 0.4115677815f, 0, + 0.503756873f, 0.6330056931f, -0.5878203852f, 0, + 0.4493712205f, 0.601390195f, 0.6606022552f, 0, + -0.6878403724f, 0.09018890807f, -0.7202371714f, 0, + -0.5958956522f, -0.6469350577f, 0.475797649f, 0, + -0.5127052122f, 0.1946921978f, -0.8361987284f, 0, + -0.9911507142f, -0.05410276466f, -0.1212153153f, 0, + -0.2149721042f, 0.9720882117f, -0.09397607749f, 0, + -0.7518650936f, -0.5428057603f, 0.3742469607f, 0, + 0.5237068895f, 0.8516377189f, -0.02107817834f, 0, + 0.6333504779f, 0.1926167129f, -0.7495104896f, 0, + -0.06788241606f, 0.3998305789f, 0.9140719259f, 0, + -0.5538628599f, -0.4729896695f, -0.6852128902f, 0, + -0.7261455366f, -0.5911990757f, 0.3509933228f, 0, + -0.9229274737f, -0.1782808786f, 0.3412049336f, 0, + -0.6968815002f, 0.6511274338f, 0.3006480328f, 0, + 0.9608044783f, -0.2098363234f, -0.1811724921f, 0, + 0.06817146062f, -0.9743405129f, 0.2145069156f, 0, + -0.3577285196f, -0.6697087264f, -0.6507845481f, 0, + -0.1868621131f, 0.7648617052f, -0.6164974636f, 0, + -0.6541697588f, 0.3967914832f, 0.6439087246f, 0, + 0.6993340405f, -0.6164538506f, 0.3618239211f, 0, + -0.1546665739f, 0.6291283928f, 0.7617583057f, 0, + -0.6841612949f, -0.2580482182f, -0.6821542638f, 0, + 0.5383980957f, 0.4258654885f, 0.7271630328f, 0, + -0.5026987823f, -0.7939832935f, -0.3418836993f, 0, + 0.3202971715f, 0.2834415347f, 0.9039195862f, 0, + 0.8683227101f, -0.0003762656404f, -0.4959995258f, 0, + 0.791120031f, -0.08511045745f, 0.6057105799f, 0, + -0.04011016052f, -0.4397248749f, 0.8972364289f, 0, + 0.9145119872f, 0.3579346169f, -0.1885487608f, 0, + -0.9612039066f, -0.2756484276f, 0.01024666929f, 0, + 0.6510361721f, -0.2877799159f, -0.7023778346f, 0, + -0.2041786351f, 0.7365237271f, 0.644859585f, 0, + -0.7718263711f, 0.3790626912f, 0.5104855816f, 0, + -0.3060082741f, -0.7692987727f, 0.5608371729f, 0, + 0.454007341f, -0.5024843065f, 0.7357899537f, 0, + 0.4816795475f, 0.6021208291f, -0.6367380315f, 0, + 0.6961980369f, -0.3222197429f, 0.641469197f, 0, + -0.6532160499f, -0.6781148932f, 0.3368515753f, 0, + 0.5089301236f, -0.6154662304f, -0.6018234363f, 0, + -0.1635919754f, -0.9133604627f, -0.372840892f, 0, + 0.52408019f, -0.8437664109f, 0.1157505864f, 0, + 0.5902587356f, 0.4983817807f, -0.6349883666f, 0, + 0.5863227872f, 0.494764745f, 0.6414307729f, 0, + 0.6779335087f, 0.2341345225f, 0.6968408593f, 0, + 0.7177054546f, -0.6858979348f, 0.120178631f, 0, + -0.5328819713f, -0.5205125012f, 0.6671608058f, 0, + -0.8654874251f, -0.0700727088f, -0.4960053754f, 0, + -0.2861810166f, 0.7952089234f, 0.5345495242f, 0, + -0.04849529634f, 0.9810836427f, -0.1874115585f, 0, + -0.6358521667f, 0.6058348682f, 0.4781800233f, 0, + 0.6254794696f, -0.2861619734f, 0.7258696564f, 0, + -0.2585259868f, 0.5061949264f, -0.8227581726f, 0, + 0.02136306781f, 0.5064016808f, -0.8620330371f, 0, + 0.200111773f, 0.8599263484f, 0.4695550591f, 0, + 0.4743561372f, 0.6014985084f, -0.6427953014f, 0, + 0.6622993731f, -0.5202474575f, -0.5391679918f, 0, + 0.08084972818f, -0.6532720452f, 0.7527940996f, 0, + -0.6893687501f, 0.0592860349f, 0.7219805347f, 0, + -0.1121887082f, -0.9673185067f, 0.2273952515f, 0, + 0.7344116094f, 0.5979668656f, -0.3210532909f, 0, + 0.5789393465f, -0.2488849713f, 0.7764570201f, 0, + 0.6988182827f, 0.3557169806f, -0.6205791146f, 0, + -0.8636845529f, -0.2748771249f, -0.4224826141f, 0, + -0.4247027957f, -0.4640880967f, 0.777335046f, 0, + 0.5257722489f, -0.8427017621f, 0.1158329937f, 0, + 0.9343830603f, 0.316302472f, -0.1639543925f, 0, + -0.1016836419f, -0.8057303073f, -0.5834887393f, 0, + -0.6529238969f, 0.50602126f, -0.5635892736f, 0, + -0.2465286165f, -0.9668205684f, -0.06694497494f, 0, + -0.9776897119f, -0.2099250524f, -0.007368825344f, 0, + 0.7736893337f, 0.5734244712f, 0.2694238123f, 0, + -0.6095087895f, 0.4995678998f, 0.6155736747f, 0, + 0.5794535482f, 0.7434546771f, 0.3339292269f, 0, + -0.8226211154f, 0.08142581855f, 0.5627293636f, 0, + -0.510385483f, 0.4703667658f, 0.7199039967f, 0, + -0.5764971849f, -0.07231656274f, -0.8138926898f, 0, + 0.7250628871f, 0.3949971505f, -0.5641463116f, 0, + -0.1525424005f, 0.4860840828f, -0.8604958341f, 0, + -0.5550976208f, -0.4957820792f, 0.667882296f, 0, + -0.1883614327f, 0.9145869398f, 0.357841725f, 0, + 0.7625556724f, -0.5414408243f, -0.3540489801f, 0, + -0.5870231946f, -0.3226498013f, -0.7424963803f, 0, + 0.3051124198f, 0.2262544068f, -0.9250488391f, 0, + 0.6379576059f, 0.577242424f, -0.5097070502f, 0, + -0.5966775796f, 0.1454852398f, -0.7891830656f, 0, + -0.658330573f, 0.6555487542f, -0.3699414651f, 0, + 0.7434892426f, 0.2351084581f, 0.6260573129f, 0, + 0.5562114096f, 0.8264360377f, -0.0873632843f, 0, + -0.3028940016f, -0.8251527185f, 0.4768419182f, 0, + 0.1129343818f, -0.985888439f, -0.1235710781f, 0, + 0.5937652891f, -0.5896813806f, 0.5474656618f, 0, + 0.6757964092f, -0.5835758614f, -0.4502648413f, 0, + 0.7242302609f, -0.1152719764f, 0.6798550586f, 0, + -0.9511914166f, 0.0753623979f, -0.2992580792f, 0, + 0.2539470961f, -0.1886339355f, 0.9486454084f, 0, + 0.571433621f, -0.1679450851f, -0.8032795685f, 0, + -0.06778234979f, 0.3978269256f, 0.9149531629f, 0, + 0.6074972649f, 0.733060024f, -0.3058922593f, 0, + -0.5435478392f, 0.1675822484f, 0.8224791405f, 0, + -0.5876678086f, -0.3380045064f, -0.7351186982f, 0, + -0.7967562402f, 0.04097822706f, -0.6029098428f, 0, + -0.1996350917f, 0.8706294745f, 0.4496111079f, 0, + -0.02787660336f, -0.9106232682f, -0.4122962022f, 0, + -0.7797625996f, -0.6257634692f, 0.01975775581f, 0, + -0.5211232846f, 0.7401644346f, -0.4249554471f, 0, + 0.8575424857f, 0.4053272873f, -0.3167501783f, 0, + 0.1045223322f, 0.8390195772f, -0.5339674439f, 0, + 0.3501822831f, 0.9242524096f, -0.1520850155f, 0, + 0.1987849858f, 0.07647613266f, 0.9770547224f, 0, + 0.7845996363f, 0.6066256811f, -0.1280964233f, 0, + 0.09006737436f, -0.9750989929f, -0.2026569073f, 0, + -0.8274343547f, -0.542299559f, 0.1458203587f, 0, + -0.3485797732f, -0.415802277f, 0.840000362f, 0, + -0.2471778936f, -0.7304819962f, -0.6366310879f, 0, + -0.3700154943f, 0.8577948156f, 0.3567584454f, 0, + 0.5913394901f, -0.548311967f, -0.5913303597f, 0, + 0.1204873514f, -0.7626472379f, -0.6354935001f, 0, + 0.616959265f, 0.03079647928f, 0.7863922953f, 0, + 0.1258156836f, -0.6640829889f, -0.7369967419f, 0, + -0.6477565124f, -0.1740147258f, -0.7417077429f, 0, + 0.6217889313f, -0.7804430448f, -0.06547655076f, 0, + 0.6589943422f, -0.6096987708f, 0.4404473475f, 0, + -0.2689837504f, -0.6732403169f, -0.6887635427f, 0, + -0.3849775103f, 0.5676542638f, 0.7277093879f, 0, + 0.5754444408f, 0.8110471154f, -0.1051963504f, 0, + 0.9141593684f, 0.3832947817f, 0.131900567f, 0, + -0.107925319f, 0.9245493968f, 0.3654593525f, 0, + 0.377977089f, 0.3043148782f, 0.8743716458f, 0, + -0.2142885215f, -0.8259286236f, 0.5214617324f, 0, + 0.5802544474f, 0.4148098596f, -0.7008834116f, 0, + -0.1982660881f, 0.8567161266f, -0.4761596756f, 0, + -0.03381553704f, 0.3773180787f, -0.9254661404f, 0, + -0.6867922841f, -0.6656597827f, 0.2919133642f, 0, + 0.7731742607f, -0.2875793547f, -0.5652430251f, 0, + -0.09655941928f, 0.9193708367f, -0.3813575004f, 0, + 0.2715702457f, -0.9577909544f, -0.09426605581f, 0, + 0.2451015704f, -0.6917998565f, -0.6792188003f, 0, + 0.977700782f, -0.1753855374f, 0.1155036542f, 0, + -0.5224739938f, 0.8521606816f, 0.02903615945f, 0, + -0.7734880599f, -0.5261292347f, 0.3534179531f, 0, + -0.7134492443f, -0.269547243f, 0.6467878011f, 0, + 0.1644037271f, 0.5105846203f, -0.8439637196f, 0, + 0.6494635788f, 0.05585611296f, 0.7583384168f, 0, + -0.4711970882f, 0.5017280509f, -0.7254255765f, 0, + -0.6335764307f, -0.2381686273f, -0.7361091029f, 0, + -0.9021533097f, -0.270947803f, -0.3357181763f, 0, + -0.3793711033f, 0.872258117f, 0.3086152025f, 0, + -0.6855598966f, -0.3250143309f, 0.6514394162f, 0, + 0.2900942212f, -0.7799057743f, -0.5546100667f, 0, + -0.2098319339f, 0.85037073f, 0.4825351604f, 0, + -0.4592603758f, 0.6598504336f, -0.5947077538f, 0, + 0.8715945488f, 0.09616365406f, -0.4807031248f, 0, + -0.6776666319f, 0.7118504878f, -0.1844907016f, 0, + 0.7044377633f, 0.312427597f, 0.637304036f, 0, + -0.7052318886f, -0.2401093292f, -0.6670798253f, 0, + 0.081921007f, -0.7207336136f, -0.6883545647f, 0, + -0.6993680906f, -0.5875763221f, -0.4069869034f, 0, + -0.1281454481f, 0.6419895885f, 0.7559286424f, 0, + -0.6337388239f, -0.6785471501f, -0.3714146849f, 0, + 0.5565051903f, -0.2168887573f, -0.8020356851f, 0, + -0.5791554484f, 0.7244372011f, -0.3738578718f, 0, + 0.1175779076f, -0.7096451073f, 0.6946792478f, 0, + -0.6134619607f, 0.1323631078f, 0.7785527795f, 0, + 0.6984635305f, -0.02980516237f, -0.715024719f, 0, + 0.8318082963f, -0.3930171956f, 0.3919597455f, 0, + 0.1469576422f, 0.05541651717f, -0.9875892167f, 0, + 0.708868575f, -0.2690503865f, 0.6520101478f, 0, + 0.2726053183f, 0.67369766f, -0.68688995f, 0, + -0.6591295371f, 0.3035458599f, -0.6880466294f, 0, + 0.4815131379f, -0.7528270071f, 0.4487723203f, 0, + 0.9430009463f, 0.1675647412f, -0.2875261255f, 0, + 0.434802957f, 0.7695304522f, -0.4677277752f, 0, + 0.3931996188f, 0.594473625f, 0.7014236729f, 0, + 0.7254336655f, -0.603925654f, 0.3301814672f, 0, + 0.7590235227f, -0.6506083235f, 0.02433313207f, 0, + -0.8552768592f, -0.3430042733f, 0.3883935666f, 0, + -0.6139746835f, 0.6981725247f, 0.3682257648f, 0, + -0.7465905486f, -0.5752009504f, 0.3342849376f, 0, + 0.5730065677f, 0.810555537f, -0.1210916791f, 0, + -0.9225877367f, -0.3475211012f, -0.167514036f, 0, + -0.7105816789f, -0.4719692027f, -0.5218416899f, 0, + -0.08564609717f, 0.3583001386f, 0.929669703f, 0, + -0.8279697606f, -0.2043157126f, 0.5222271202f, 0, + 0.427944023f, 0.278165994f, 0.8599346446f, 0, + 0.5399079671f, -0.7857120652f, -0.3019204161f, 0, + 0.5678404253f, -0.5495413974f, -0.6128307303f, 0, + -0.9896071041f, 0.1365639107f, -0.04503418428f, 0, + -0.6154342638f, -0.6440875597f, 0.4543037336f, 0, + 0.1074204368f, -0.7946340692f, 0.5975094525f, 0, + -0.3595449969f, -0.8885529948f, 0.28495784f, 0, + -0.2180405296f, 0.1529888965f, 0.9638738118f, 0, + -0.7277432317f, -0.6164050508f, -0.3007234646f, 0, + 0.7249729114f, -0.00669719484f, 0.6887448187f, 0, + -0.5553659455f, -0.5336586252f, 0.6377908264f, 0, + 0.5137558015f, 0.7976208196f, -0.3160000073f, 0, + -0.3794024848f, 0.9245608561f, -0.03522751494f, 0, + 0.8229248658f, 0.2745365933f, -0.4974176556f, 0, + -0.5404114394f, 0.6091141441f, 0.5804613989f, 0, + 0.8036581901f, -0.2703029469f, 0.5301601931f, 0, + 0.6044318879f, 0.6832968393f, 0.4095943388f, 0, + 0.06389988817f, 0.9658208605f, -0.2512108074f, 0, + 0.1087113286f, 0.7402471173f, -0.6634877936f, 0, + -0.713427712f, -0.6926784018f, 0.1059128479f, 0, + 0.6458897819f, -0.5724548511f, -0.5050958653f, 0, + -0.6553931414f, 0.7381471625f, 0.159995615f, 0, + 0.3910961323f, 0.9188871375f, -0.05186755998f, 0, + -0.4879022471f, -0.5904376907f, 0.6429111375f, 0, + 0.6014790094f, 0.7707441366f, -0.2101820095f, 0, + -0.5677173047f, 0.7511360995f, 0.3368851762f, 0, + 0.7858573506f, 0.226674665f, 0.5753666838f, 0, + -0.4520345543f, -0.604222686f, -0.6561857263f, 0, + 0.002272116345f, 0.4132844051f, -0.9105991643f, 0, + -0.5815751419f, -0.5162925989f, 0.6286591339f, 0, + -0.03703704785f, 0.8273785755f, 0.5604221175f, 0, + -0.5119692504f, 0.7953543429f, -0.3244980058f, 0, + -0.2682417366f, -0.9572290247f, -0.1084387619f, 0, + -0.2322482736f, -0.9679131102f, -0.09594243324f, 0, + 0.3554328906f, -0.8881505545f, 0.2913006227f, 0, + 0.7346520519f, -0.4371373164f, 0.5188422971f, 0, + 0.9985120116f, 0.04659011161f, -0.02833944577f, 0, + -0.3727687496f, -0.9082481361f, 0.1900757285f, 0, + 0.91737377f, -0.3483642108f, 0.1925298489f, 0, + 0.2714911074f, 0.4147529736f, -0.8684886582f, 0, + 0.5131763485f, -0.7116334161f, 0.4798207128f, 0, + -0.8737353606f, 0.18886992f, -0.4482350644f, 0, + 0.8460043821f, -0.3725217914f, 0.3814499973f, 0, + 0.8978727456f, -0.1780209141f, -0.4026575304f, 0, + 0.2178065647f, -0.9698322841f, -0.1094789531f, 0, + -0.1518031304f, -0.7788918132f, -0.6085091231f, 0, + -0.2600384876f, -0.4755398075f, -0.8403819825f, 0, + 0.572313509f, -0.7474340931f, -0.3373418503f, 0, + -0.7174141009f, 0.1699017182f, -0.6756111411f, 0, + -0.684180784f, 0.02145707593f, -0.7289967412f, 0, + -0.2007447902f, 0.06555605789f, -0.9774476623f, 0, + -0.1148803697f, -0.8044887315f, 0.5827524187f, 0, + -0.7870349638f, 0.03447489231f, 0.6159443543f, 0, + -0.2015596421f, 0.6859872284f, 0.6991389226f, 0, + -0.08581082512f, -0.10920836f, -0.9903080513f, 0, + 0.5532693395f, 0.7325250401f, -0.396610771f, 0, + -0.1842489331f, -0.9777375055f, -0.1004076743f, 0, + 0.0775473789f, -0.9111505856f, 0.4047110257f, 0, + 0.1399838409f, 0.7601631212f, -0.6344734459f, 0, + 0.4484419361f, -0.845289248f, 0.2904925424f, 0}; // Utilities -static inline float _fnlFastMin(float x, float y) { return x < y ? x : y; } +static inline float _fnlFastMin(float x, float y) { + return x < y ? x : y; +} -static inline float _fnlFastMax(float x, float y) { return x > y ? x : y; } +static inline float _fnlFastMax(float x, float y) { + return x > y ? x : y; +} -static inline float _fnlFastAbs(float f) { return f < 0 ? -f : f; } +static inline float _fnlFastAbs(float f) { + return f < 0 ? -f : f; +} -static inline float _fnlCasti32Tof32(int i) -{ - union - { +static inline float _fnlCasti32Tof32(int i) { + union { float f; int32_t i; } u; @@ -414,10 +793,8 @@ static inline float _fnlCasti32Tof32(int i) return u.f; } -static inline int _fnlCastf32Toi32(float f) -{ - union - { +static inline int _fnlCastf32Toi32(float f) { + union { float f; int32_t i; } u; @@ -425,46 +802,54 @@ static inline int _fnlCastf32Toi32(float f) return u.i; } -static inline float _fnlInvSqrt(float a) -{ +static inline float _fnlInvSqrt(float a) { float xhalf = 0.5f * a; a = _fnlCasti32Tof32(0x5f3759df - (_fnlCastf32Toi32(a) >> 1)); a = a * (1.5f - xhalf * a * a); return a; } -// NOTE: If your language does not support this method (seen above), then simply use the native sqrt function. -static inline float _fnlFastSqrt(float a) { return a * _fnlInvSqrt(a); } +// NOTE: If your language does not support this method (seen above), then simply +// use the native sqrt function. +static inline float _fnlFastSqrt(float a) { + return a * _fnlInvSqrt(a); +} -static inline int _fnlFastFloor(FNLfloat f) { return (f >= 0 ? (int)f : (int)f - 1); } +static inline int _fnlFastFloor(FNLfloat f) { + return (f >= 0 ? (int)f : (int)f - 1); +} -static inline int _fnlFastRound(FNLfloat f) { return (f >= 0) ? (int)(f + 0.5f) : (int)(f - 0.5f); } +static inline int _fnlFastRound(FNLfloat f) { + return (f >= 0) ? (int)(f + 0.5f) : (int)(f - 0.5f); +} -static inline float _fnlLerp(float a, float b, float t) { return a + t * (b - a); } +static inline float _fnlLerp(float a, float b, float t) { + return a + t * (b - a); +} -static inline float _fnlInterpHermite(float t) { return t * t * (3 - 2 * t); } +static inline float _fnlInterpHermite(float t) { + return t * t * (3 - 2 * t); +} -static inline float _fnlInterpQuintic(float t) { return t * t * t * (t * (t * 6 - 15) + 10); } +static inline float _fnlInterpQuintic(float t) { + return t * t * t * (t * (t * 6 - 15) + 10); +} -static inline float _fnlCubicLerp(float a, float b, float c, float d, float t) -{ +static inline float _fnlCubicLerp(float a, float b, float c, float d, float t) { float p = (d - c) - (a - b); return t * t * t * p + t * t * ((a - b) - p) + t * (c - a) + b; } -static inline float _fnlPingPong(float t) -{ +static inline float _fnlPingPong(float t) { t -= (int)(t * 0.5f) * 2; return t < 1 ? t : 2 - t; } -static float _fnlCalculateFractalBounding(fnl_state *state) -{ +static float _fnlCalculateFractalBounding(fnl_state *state) { float gain = _fnlFastAbs(state->gain); float amp = gain; float ampFractal = 1.0f; - for (int i = 1; i < state->octaves; i++) - { + for (int i = 1; i < state->octaves; i++) { ampFractal += amp; amp *= gain; } @@ -477,64 +862,79 @@ static const int PRIME_X = 501125321; static const int PRIME_Y = 1136930381; static const int PRIME_Z = 1720413743; -static inline int _fnlHash2D(int seed, int xPrimed, int yPrimed) -{ +static inline int _fnlHash2D(int seed, int xPrimed, int yPrimed) { int hash = seed ^ xPrimed ^ yPrimed; hash *= 0x27d4eb2d; return hash; } -static inline int _fnlHash3D(int seed, int xPrimed, int yPrimed, int zPrimed) -{ +static inline int _fnlHash3D(int seed, int xPrimed, int yPrimed, int zPrimed) { int hash = seed ^ xPrimed ^ yPrimed ^ zPrimed; hash *= 0x27d4eb2d; return hash; } -static inline float _fnlValCoord2D(int seed, int xPrimed, int yPrimed) -{ +static inline float _fnlValCoord2D(int seed, int xPrimed, int yPrimed) { int hash = _fnlHash2D(seed, xPrimed, yPrimed); hash *= hash; hash ^= hash << 19; return hash * (1 / 2147483648.0f); } -static inline float _fnlValCoord3D(int seed, int xPrimed, int yPrimed, int zPrimed) -{ +static inline float _fnlValCoord3D( + int seed, int xPrimed, int yPrimed, int zPrimed +) { int hash = _fnlHash3D(seed, xPrimed, yPrimed, zPrimed); hash *= hash; hash ^= hash << 19; return hash * (1 / 2147483648.0f); } -static inline float _fnlGradCoord2D(int seed, int xPrimed, int yPrimed, float xd, float yd) -{ +static inline float _fnlGradCoord2D( + int seed, int xPrimed, int yPrimed, float xd, float yd +) { int hash = _fnlHash2D(seed, xPrimed, yPrimed); hash ^= hash >> 15; hash &= 127 << 1; return xd * GRADIENTS_2D[hash] + yd * GRADIENTS_2D[hash | 1]; } -static inline float _fnlGradCoord3D(int seed, int xPrimed, int yPrimed, int zPrimed, float xd, float yd, float zd) -{ +static inline float _fnlGradCoord3D( + int seed, + int xPrimed, + int yPrimed, + int zPrimed, + float xd, + float yd, + float zd +) { int hash = _fnlHash3D(seed, xPrimed, yPrimed, zPrimed); hash ^= hash >> 15; hash &= 63 << 2; - return xd * GRADIENTS_3D[hash] + yd * GRADIENTS_3D[hash | 1] + zd * GRADIENTS_3D[hash | 2]; + return xd * GRADIENTS_3D[hash] + yd * GRADIENTS_3D[hash | 1] + + zd * GRADIENTS_3D[hash | 2]; } -static inline void _fnlGradCoordOut2D(int seed, int xPrimed, int yPrimed, float *xo, float *yo) -{ +static inline void _fnlGradCoordOut2D( + int seed, int xPrimed, int yPrimed, float *xo, float *yo +) { int hash = _fnlHash2D(seed, xPrimed, yPrimed) & (255 << 1); *xo = RAND_VECS_2D[hash]; *yo = RAND_VECS_2D[hash | 1]; } -static inline void _fnlGradCoordOut3D(int seed, int xPrimed, int yPrimed, int zPrimed, float *xo, float *yo, float *zo) -{ +static inline void _fnlGradCoordOut3D( + int seed, + int xPrimed, + int yPrimed, + int zPrimed, + float *xo, + float *yo, + float *zo +) { int hash = _fnlHash3D(seed, xPrimed, yPrimed, zPrimed) & (255 << 2); *xo = RAND_VECS_3D[hash]; @@ -542,8 +942,9 @@ static inline void _fnlGradCoordOut3D(int seed, int xPrimed, int yPrimed, int zP *zo = RAND_VECS_3D[hash | 2]; } -static inline void _fnlGradCoordDual2D(int seed, int xPrimed, int yPrimed, float xd, float yd, float *xo, float *yo) -{ +static inline void _fnlGradCoordDual2D( + int seed, int xPrimed, int yPrimed, float xd, float yd, float *xo, float *yo +) { int hash = _fnlHash2D(seed, xPrimed, yPrimed); int index1 = hash & (127 << 1); int index2 = (hash >> 7) & (255 << 1); @@ -559,8 +960,18 @@ static inline void _fnlGradCoordDual2D(int seed, int xPrimed, int yPrimed, float *yo = value * ygo; } -static inline void _fnlGradCoordDual3D(int seed, int xPrimed, int yPrimed, int zPrimed, float xd, float yd, float zd, float *xo, float *yo, float *zo) -{ +static inline void _fnlGradCoordDual3D( + int seed, + int xPrimed, + int yPrimed, + int zPrimed, + float xd, + float yd, + float zd, + float *xo, + float *yo, + float *zo +) { int hash = _fnlHash3D(seed, xPrimed, yPrimed, zPrimed); int index1 = hash & (63 << 2); int index2 = (hash >> 6) & (255 << 2); @@ -582,207 +993,199 @@ static inline void _fnlGradCoordDual3D(int seed, int xPrimed, int yPrimed, int z // Generic Noise Gen static float _fnlSingleSimplex2D(int seed, FNLfloat x, FNLfloat y); -static float _fnlSingleOpenSimplex23D(int seed, FNLfloat x, FNLfloat y, FNLfloat z); +static float _fnlSingleOpenSimplex23D( + int seed, FNLfloat x, FNLfloat y, FNLfloat z +); static float _fnlSingleOpenSimplex2S2D(int seed, FNLfloat x, FNLfloat y); -static float _fnlSingleOpenSimplex2S3D(int seed, FNLfloat x, FNLfloat y, FNLfloat z); -static float _fnlSingleCellular2D(fnl_state *state, int seed, FNLfloat x, FNLfloat y); -static float _fnlSingleCellular3D(fnl_state *state, int seed, FNLfloat x, FNLfloat y, FNLfloat z); +static float _fnlSingleOpenSimplex2S3D( + int seed, FNLfloat x, FNLfloat y, FNLfloat z +); +static float _fnlSingleCellular2D( + fnl_state *state, int seed, FNLfloat x, FNLfloat y +); +static float _fnlSingleCellular3D( + fnl_state *state, int seed, FNLfloat x, FNLfloat y, FNLfloat z +); static float _fnlSinglePerlin2D(int seed, FNLfloat x, FNLfloat y); static float _fnlSinglePerlin3D(int seed, FNLfloat x, FNLfloat y, FNLfloat z); static float _fnlSingleValueCubic2D(int seed, FNLfloat x, FNLfloat y); -static float _fnlSingleValueCubic3D(int seed, FNLfloat x, FNLfloat y, FNLfloat z); +static float _fnlSingleValueCubic3D( + int seed, FNLfloat x, FNLfloat y, FNLfloat z +); static float _fnlSingleValue2D(int seed, FNLfloat x, FNLfloat y); static float _fnlSingleValue3D(int seed, FNLfloat x, FNLfloat y, FNLfloat z); -static float _fnlGenNoiseSingle2D(fnl_state *state, int seed, FNLfloat x, FNLfloat y) -{ - switch (state->noise_type) - { - case FNL_NOISE_OPENSIMPLEX2: - return _fnlSingleSimplex2D(seed, x, y); - case FNL_NOISE_OPENSIMPLEX2S: - return _fnlSingleOpenSimplex2S2D(seed, x, y); - case FNL_NOISE_CELLULAR: - return _fnlSingleCellular2D(state, seed, x, y); - case FNL_NOISE_PERLIN: - return _fnlSinglePerlin2D(seed, x, y); - case FNL_NOISE_VALUE_CUBIC: - return _fnlSingleValueCubic2D(seed, x, y); - case FNL_NOISE_VALUE: - return _fnlSingleValue2D(seed, x, y); - default: - return 0; +static float _fnlGenNoiseSingle2D( + fnl_state *state, int seed, FNLfloat x, FNLfloat y +) { + switch (state->noise_type) { + case FNL_NOISE_OPENSIMPLEX2: + return _fnlSingleSimplex2D(seed, x, y); + case FNL_NOISE_OPENSIMPLEX2S: + return _fnlSingleOpenSimplex2S2D(seed, x, y); + case FNL_NOISE_CELLULAR: + return _fnlSingleCellular2D(state, seed, x, y); + case FNL_NOISE_PERLIN: + return _fnlSinglePerlin2D(seed, x, y); + case FNL_NOISE_VALUE_CUBIC: + return _fnlSingleValueCubic2D(seed, x, y); + case FNL_NOISE_VALUE: + return _fnlSingleValue2D(seed, x, y); + default: + return 0; } } -static float _fnlGenNoiseSingle3D(fnl_state *state, int seed, FNLfloat x, FNLfloat y, FNLfloat z) -{ - switch (state->noise_type) - { - case FNL_NOISE_OPENSIMPLEX2: - return _fnlSingleOpenSimplex23D(seed, x, y, z); - case FNL_NOISE_OPENSIMPLEX2S: - return _fnlSingleOpenSimplex2S3D(seed, x, y, z); - case FNL_NOISE_CELLULAR: - return _fnlSingleCellular3D(state, seed, x, y, z); - case FNL_NOISE_PERLIN: - return _fnlSinglePerlin3D(seed, x, y, z); - case FNL_NOISE_VALUE_CUBIC: - return _fnlSingleValueCubic3D(seed, x, y, z); - case FNL_NOISE_VALUE: - return _fnlSingleValue3D(seed, x, y, z); - default: - return 0; +static float _fnlGenNoiseSingle3D( + fnl_state *state, int seed, FNLfloat x, FNLfloat y, FNLfloat z +) { + switch (state->noise_type) { + case FNL_NOISE_OPENSIMPLEX2: + return _fnlSingleOpenSimplex23D(seed, x, y, z); + case FNL_NOISE_OPENSIMPLEX2S: + return _fnlSingleOpenSimplex2S3D(seed, x, y, z); + case FNL_NOISE_CELLULAR: + return _fnlSingleCellular3D(state, seed, x, y, z); + case FNL_NOISE_PERLIN: + return _fnlSinglePerlin3D(seed, x, y, z); + case FNL_NOISE_VALUE_CUBIC: + return _fnlSingleValueCubic3D(seed, x, y, z); + case FNL_NOISE_VALUE: + return _fnlSingleValue3D(seed, x, y, z); + default: + return 0; } } // Noise Coordinate Transforms (frequency, and possible skew or rotation) -static void _fnlTransformNoiseCoordinate2D(fnl_state *state, FNLfloat *x, FNLfloat *y) -{ +static void _fnlTransformNoiseCoordinate2D( + fnl_state *state, FNLfloat *x, FNLfloat *y +) { *x *= state->frequency; *y *= state->frequency; - switch (state->noise_type) - { - case FNL_NOISE_OPENSIMPLEX2: - case FNL_NOISE_OPENSIMPLEX2S: - { - const FNLfloat SQRT3 = (FNLfloat)1.7320508075688772935274463415059; - const FNLfloat F2 = 0.5f * (SQRT3 - 1); - FNLfloat t = (*x + *y) * F2; - *x += t; - *y += t; - } - break; - default: - break; + switch (state->noise_type) { + case FNL_NOISE_OPENSIMPLEX2: + case FNL_NOISE_OPENSIMPLEX2S: { + const FNLfloat SQRT3 = (FNLfloat)1.7320508075688772935274463415059; + const FNLfloat F2 = 0.5f * (SQRT3 - 1); + FNLfloat t = (*x + *y) * F2; + *x += t; + *y += t; + } break; + default: + break; } } -static void _fnlTransformNoiseCoordinate3D(fnl_state *state, FNLfloat *x, FNLfloat *y, FNLfloat *z) -{ +static void _fnlTransformNoiseCoordinate3D( + fnl_state *state, FNLfloat *x, FNLfloat *y, FNLfloat *z +) { *x *= state->frequency; *y *= state->frequency; *z *= state->frequency; - switch (state->rotation_type_3d) - { - case FNL_ROTATION_IMPROVE_XY_PLANES: - { - FNLfloat xy = *x + *y; - FNLfloat s2 = xy * -(FNLfloat)0.211324865405187; - *z *= (FNLfloat)0.577350269189626; - *x += s2 - *z; - *y = *y + s2 - *z; - *z += xy * (FNLfloat)0.577350269189626; - } - break; - case FNL_ROTATION_IMPROVE_XZ_PLANES: - { - FNLfloat xz = *x + *z; - FNLfloat s2 = xz * -(FNLfloat)0.211324865405187; - *y *= (FNLfloat)0.577350269189626; - *x += s2 - *y; - *z += s2 - *y; - *y += xz * (FNLfloat)0.577350269189626; - } - break; - default: - switch (state->noise_type) - { - case FNL_NOISE_OPENSIMPLEX2: - case FNL_NOISE_OPENSIMPLEX2S: - { - const FNLfloat R3 = (FNLfloat)(2.0 / 3.0); - FNLfloat r = (*x + *y + *z) * R3; // Rotation, not skew - *x = r - *x; - *y = r - *y; - *z = r - *z; - } - break; + switch (state->rotation_type_3d) { + case FNL_ROTATION_IMPROVE_XY_PLANES: { + FNLfloat xy = *x + *y; + FNLfloat s2 = xy * -(FNLfloat)0.211324865405187; + *z *= (FNLfloat)0.577350269189626; + *x += s2 - *z; + *y = *y + s2 - *z; + *z += xy * (FNLfloat)0.577350269189626; + } break; + case FNL_ROTATION_IMPROVE_XZ_PLANES: { + FNLfloat xz = *x + *z; + FNLfloat s2 = xz * -(FNLfloat)0.211324865405187; + *y *= (FNLfloat)0.577350269189626; + *x += s2 - *y; + *z += s2 - *y; + *y += xz * (FNLfloat)0.577350269189626; + } break; default: - break; - } + switch (state->noise_type) { + case FNL_NOISE_OPENSIMPLEX2: + case FNL_NOISE_OPENSIMPLEX2S: { + const FNLfloat R3 = (FNLfloat)(2.0 / 3.0); + FNLfloat r = (*x + *y + *z) * R3; // Rotation, not skew + *x = r - *x; + *y = r - *y; + *z = r - *z; + } break; + default: + break; + } } } // Domain Warp Coordinate Transforms -static void _fnlTransformDomainWarpCoordinate2D(fnl_state *state, FNLfloat *x, FNLfloat *y) -{ - switch (state->domain_warp_type) - { - case FNL_DOMAIN_WARP_OPENSIMPLEX2: - case FNL_DOMAIN_WARP_OPENSIMPLEX2_REDUCED: - { - const FNLfloat SQRT3 = (FNLfloat)1.7320508075688772935274463415059; - const FNLfloat F2 = 0.5f * (SQRT3 - 1); - FNLfloat t = (*x + *y) * F2; - *x += t; - *y += t; - } - break; - default: - break; +static void _fnlTransformDomainWarpCoordinate2D( + fnl_state *state, FNLfloat *x, FNLfloat *y +) { + switch (state->domain_warp_type) { + case FNL_DOMAIN_WARP_OPENSIMPLEX2: + case FNL_DOMAIN_WARP_OPENSIMPLEX2_REDUCED: { + const FNLfloat SQRT3 = (FNLfloat)1.7320508075688772935274463415059; + const FNLfloat F2 = 0.5f * (SQRT3 - 1); + FNLfloat t = (*x + *y) * F2; + *x += t; + *y += t; + } break; + default: + break; } } -static void _fnlTransformDomainWarpCoordinate3D(fnl_state *state, FNLfloat *x, FNLfloat *y, FNLfloat *z) -{ - switch (state->rotation_type_3d) - { - case FNL_ROTATION_IMPROVE_XY_PLANES: - { - FNLfloat xy = *x + *y; - FNLfloat s2 = xy * -(FNLfloat)0.211324865405187; - *z *= (FNLfloat)0.577350269189626; - *x += s2 - *z; - *y = *y + s2 - *z; - *z += xy * (FNLfloat)0.577350269189626; - } - break; - case FNL_ROTATION_IMPROVE_XZ_PLANES: - { - FNLfloat xz = *x + *z; - FNLfloat s2 = xz * -(FNLfloat)0.211324865405187; - *y *= (FNLfloat)0.577350269189626; - *x += s2 - *y; - *z += s2 - *y; - *y += xz * (FNLfloat)0.577350269189626; - } - break; - default: - switch (state->domain_warp_type) - { - case FNL_DOMAIN_WARP_OPENSIMPLEX2: - case FNL_DOMAIN_WARP_OPENSIMPLEX2_REDUCED: - { - const FNLfloat R3 = (FNLfloat)(2.0 / 3.0); - FNLfloat r = (*x + *y + *z) * R3; // Rotation, not skew - *x = r - *x; - *y = r - *y; - *z = r - *z; - } - break; +static void _fnlTransformDomainWarpCoordinate3D( + fnl_state *state, FNLfloat *x, FNLfloat *y, FNLfloat *z +) { + switch (state->rotation_type_3d) { + case FNL_ROTATION_IMPROVE_XY_PLANES: { + FNLfloat xy = *x + *y; + FNLfloat s2 = xy * -(FNLfloat)0.211324865405187; + *z *= (FNLfloat)0.577350269189626; + *x += s2 - *z; + *y = *y + s2 - *z; + *z += xy * (FNLfloat)0.577350269189626; + } break; + case FNL_ROTATION_IMPROVE_XZ_PLANES: { + FNLfloat xz = *x + *z; + FNLfloat s2 = xz * -(FNLfloat)0.211324865405187; + *y *= (FNLfloat)0.577350269189626; + *x += s2 - *y; + *z += s2 - *y; + *y += xz * (FNLfloat)0.577350269189626; + } break; default: - break; - } + switch (state->domain_warp_type) { + case FNL_DOMAIN_WARP_OPENSIMPLEX2: + case FNL_DOMAIN_WARP_OPENSIMPLEX2_REDUCED: { + const FNLfloat R3 = (FNLfloat)(2.0 / 3.0); + FNLfloat r = (*x + *y + *z) * R3; // Rotation, not skew + *x = r - *x; + *y = r - *y; + *z = r - *z; + } break; + default: + break; + } } } // Fractal FBm -static float _fnlGenFractalFBM2D(fnl_state *state, FNLfloat x, FNLfloat y) -{ +static float _fnlGenFractalFBM2D(fnl_state *state, FNLfloat x, FNLfloat y) { int seed = state->seed; float sum = 0; float amp = _fnlCalculateFractalBounding(state); - for (int i = 0; i < state->octaves; i++) - { + for (int i = 0; i < state->octaves; i++) { float noise = _fnlGenNoiseSingle2D(state, seed++, x, y); sum += noise * amp; - amp *= _fnlLerp(1.0f, _fnlFastMin(noise + 1, 2) * 0.5f, state->weighted_strength); + amp *= _fnlLerp( + 1.0f, _fnlFastMin(noise + 1, 2) * 0.5f, state->weighted_strength + ); x *= state->lacunarity; y *= state->lacunarity; @@ -792,14 +1195,14 @@ static float _fnlGenFractalFBM2D(fnl_state *state, FNLfloat x, FNLfloat y) return sum; } -static float _fnlGenFractalFBM3D(fnl_state *state, FNLfloat x, FNLfloat y, FNLfloat z) -{ +static float _fnlGenFractalFBM3D( + fnl_state *state, FNLfloat x, FNLfloat y, FNLfloat z +) { int seed = state->seed; float sum = 0; float amp = _fnlCalculateFractalBounding(state); - for (int i = 0; i < state->octaves; i++) - { + for (int i = 0; i < state->octaves; i++) { float noise = _fnlGenNoiseSingle3D(state, seed++, x, y, z); sum += noise * amp; amp *= _fnlLerp(1.0f, (noise + 1) * 0.5f, state->weighted_strength); @@ -815,14 +1218,12 @@ static float _fnlGenFractalFBM3D(fnl_state *state, FNLfloat x, FNLfloat y, FNLfl // Fractal Ridged -static float _fnlGenFractalRidged2D(fnl_state *state, FNLfloat x, FNLfloat y) -{ +static float _fnlGenFractalRidged2D(fnl_state *state, FNLfloat x, FNLfloat y) { int seed = state->seed; float sum = 0; float amp = _fnlCalculateFractalBounding(state); - for (int i = 0; i < state->octaves; i++) - { + for (int i = 0; i < state->octaves; i++) { float noise = _fnlFastAbs(_fnlGenNoiseSingle2D(state, seed++, x, y)); sum += (noise * -2 + 1) * amp; amp *= _fnlLerp(1.0f, 1 - noise, state->weighted_strength); @@ -835,14 +1236,14 @@ static float _fnlGenFractalRidged2D(fnl_state *state, FNLfloat x, FNLfloat y) return sum; } -static float _fnlGenFractalRidged3D(fnl_state *state, FNLfloat x, FNLfloat y, FNLfloat z) -{ +static float _fnlGenFractalRidged3D( + fnl_state *state, FNLfloat x, FNLfloat y, FNLfloat z +) { int seed = state->seed; float sum = 0; float amp = _fnlCalculateFractalBounding(state); - for (int i = 0; i < state->octaves; i++) - { + for (int i = 0; i < state->octaves; i++) { float noise = _fnlFastAbs(_fnlGenNoiseSingle3D(state, seed++, x, y, z)); sum += (noise * -2 + 1) * amp; amp *= _fnlLerp(1.0f, 1 - noise, state->weighted_strength); @@ -858,15 +1259,18 @@ static float _fnlGenFractalRidged3D(fnl_state *state, FNLfloat x, FNLfloat y, FN // Fractal PingPong -static float _fnlGenFractalPingPong2D(fnl_state *state, FNLfloat x, FNLfloat y) -{ +static float _fnlGenFractalPingPong2D( + fnl_state *state, FNLfloat x, FNLfloat y +) { int seed = state->seed; float sum = 0; float amp = _fnlCalculateFractalBounding(state); - for (int i = 0; i < state->octaves; i++) - { - float noise = _fnlPingPong((_fnlGenNoiseSingle2D(state, seed++, x, y) + 1) * state->ping_pong_strength); + for (int i = 0; i < state->octaves; i++) { + float noise = _fnlPingPong( + (_fnlGenNoiseSingle2D(state, seed++, x, y) + 1) * + state->ping_pong_strength + ); sum += (noise - 0.5f) * 2 * amp; amp *= _fnlLerp(1.0f, noise, state->weighted_strength); @@ -878,15 +1282,18 @@ static float _fnlGenFractalPingPong2D(fnl_state *state, FNLfloat x, FNLfloat y) return sum; } -static float _fnlGenFractalPingPong3D(fnl_state *state, FNLfloat x, FNLfloat y, FNLfloat z) -{ +static float _fnlGenFractalPingPong3D( + fnl_state *state, FNLfloat x, FNLfloat y, FNLfloat z +) { int seed = state->seed; float sum = 0; float amp = _fnlCalculateFractalBounding(state); - for (int i = 0; i < state->octaves; i++) - { - float noise = _fnlPingPong((_fnlGenNoiseSingle3D(state, seed++, x, y, z) + 1) * state->ping_pong_strength); + for (int i = 0; i < state->octaves; i++) { + float noise = _fnlPingPong( + (_fnlGenNoiseSingle3D(state, seed++, x, y, z) + 1) * + state->ping_pong_strength + ); sum += (noise - 0.5f) * 2 * amp; amp *= _fnlLerp(1.0f, noise, state->weighted_strength); @@ -901,8 +1308,7 @@ static float _fnlGenFractalPingPong3D(fnl_state *state, FNLfloat x, FNLfloat y, // Simplex/OpenSimplex2 Noise -static float _fnlSingleSimplex2D(int seed, FNLfloat x, FNLfloat y) -{ +static float _fnlSingleSimplex2D(int seed, FNLfloat x, FNLfloat y) { // 2D OpenSimplex2 case uses the same algorithm as ordinary Simplex. const float SQRT3 = 1.7320508075688772935274463415059f; @@ -932,51 +1338,49 @@ static float _fnlSingleSimplex2D(int seed, FNLfloat x, FNLfloat y) float a = 0.5f - x0 * x0 - y0 * y0; if (a <= 0) n0 = 0; - else - { + else { n0 = (a * a) * (a * a) * _fnlGradCoord2D(seed, i, j, x0, y0); } - float c = (float)(2 * (1 - 2 * G2) * (1 / G2 - 2)) * t + ((float)(-2 * (1 - 2 * G2) * (1 - 2 * G2)) + a); + float c = (float)(2 * (1 - 2 * G2) * (1 / G2 - 2)) * t + + ((float)(-2 * (1 - 2 * G2) * (1 - 2 * G2)) + a); if (c <= 0) n2 = 0; - else - { + else { float x2 = x0 + (2 * (float)G2 - 1); float y2 = y0 + (2 * (float)G2 - 1); - n2 = (c * c) * (c * c) * _fnlGradCoord2D(seed, i + PRIME_X, j + PRIME_Y, x2, y2); + n2 = (c * c) * (c * c) * + _fnlGradCoord2D(seed, i + PRIME_X, j + PRIME_Y, x2, y2); } - if (y0 > x0) - { + if (y0 > x0) { float x1 = x0 + (float)G2; float y1 = y0 + ((float)G2 - 1); float b = 0.5f - x1 * x1 - y1 * y1; if (b <= 0) n1 = 0; - else - { - n1 = (b * b) * (b * b) * _fnlGradCoord2D(seed, i, j + PRIME_Y, x1, y1); + else { + n1 = (b * b) * (b * b) * + _fnlGradCoord2D(seed, i, j + PRIME_Y, x1, y1); } - } - else - { + } else { float x1 = x0 + ((float)G2 - 1); float y1 = y0 + (float)G2; float b = 0.5f - x1 * x1 - y1 * y1; if (b <= 0) n1 = 0; - else - { - n1 = (b * b) * (b * b) * _fnlGradCoord2D(seed, i + PRIME_X, j, x1, y1); + else { + n1 = (b * b) * (b * b) * + _fnlGradCoord2D(seed, i + PRIME_X, j, x1, y1); } } return (n0 + n1 + n2) * 99.83685446303647f; } -static float _fnlSingleOpenSimplex23D(int seed, FNLfloat x, FNLfloat y, FNLfloat z) -{ +static float _fnlSingleOpenSimplex23D( + int seed, FNLfloat x, FNLfloat y, FNLfloat z +) { // 3D OpenSimplex2 case uses two offset rotated cube grids. /* @@ -1008,11 +1412,10 @@ static float _fnlSingleOpenSimplex23D(int seed, FNLfloat x, FNLfloat y, FNLfloat float value = 0; float a = (0.6f - x0 * x0) - (y0 * y0 + z0 * z0); - for (int l = 0; ; l++) - { - if (a > 0) - { - value += (a * a) * (a * a) * _fnlGradCoord3D(seed, i, j, k, x0, y0, z0); + for (int l = 0;; l++) { + if (a > 0) { + value += + (a * a) * (a * a) * _fnlGradCoord3D(seed, i, j, k, x0, y0, z0); } float b = a + 1; @@ -1022,32 +1425,26 @@ static float _fnlSingleOpenSimplex23D(int seed, FNLfloat x, FNLfloat y, FNLfloat float x1 = x0; float y1 = y0; float z1 = z0; - if (ax0 >= ay0 && ax0 >= az0) - { + if (ax0 >= ay0 && ax0 >= az0) { x1 += xNSign; b -= xNSign * 2 * x1; i1 -= xNSign * PRIME_X; - } - else if (ay0 > ax0 && ay0 >= az0) - { + } else if (ay0 > ax0 && ay0 >= az0) { y1 += yNSign; b -= yNSign * 2 * y1; j1 -= yNSign * PRIME_Y; - } - else - { + } else { z1 += zNSign; b -= zNSign * 2 * z1; k1 -= zNSign * PRIME_Z; } - if (b > 0) - { - value += (b * b) * (b * b) * _fnlGradCoord3D(seed, i1, j1, k1, x1, y1, z1); + if (b > 0) { + value += (b * b) * (b * b) * + _fnlGradCoord3D(seed, i1, j1, k1, x1, y1, z1); } - if (l == 1) - break; + if (l == 1) break; ax0 = 0.5f - ax0; ay0 = 0.5f - ay0; @@ -1075,8 +1472,7 @@ static float _fnlSingleOpenSimplex23D(int seed, FNLfloat x, FNLfloat y, FNLfloat // OpenSimplex2S Noise -static float _fnlSingleOpenSimplex2S2D(int seed, FNLfloat x, FNLfloat y) -{ +static float _fnlSingleOpenSimplex2S2D(int seed, FNLfloat x, FNLfloat y) { // 2D OpenSimplex2S case is a modified 2D simplex noise. const FNLfloat SQRT3 = (FNLfloat)1.7320508075688772935274463415059; @@ -1087,7 +1483,7 @@ static float _fnlSingleOpenSimplex2S2D(int seed, FNLfloat x, FNLfloat y) * const FNLfloat F2 = 0.5f * (SQRT3 - 1); * FNLfloat s = (x + y) * F2; * x += s; y += s; - */ + */ int i = _fnlFastFloor(x); int j = _fnlFastFloor(y); @@ -1106,98 +1502,88 @@ static float _fnlSingleOpenSimplex2S2D(int seed, FNLfloat x, FNLfloat y) float a0 = (2.0f / 3.0f) - x0 * x0 - y0 * y0; float value = (a0 * a0) * (a0 * a0) * _fnlGradCoord2D(seed, i, j, x0, y0); - float a1 = (float)(2 * (1 - 2 * G2) * (1 / G2 - 2)) * t + ((float)(-2 * (1 - 2 * G2) * (1 - 2 * G2)) + a0); + float a1 = (float)(2 * (1 - 2 * G2) * (1 / G2 - 2)) * t + + ((float)(-2 * (1 - 2 * G2) * (1 - 2 * G2)) + a0); float x1 = x0 - (float)(1 - 2 * G2); float y1 = y0 - (float)(1 - 2 * G2); value += (a1 * a1) * (a1 * a1) * _fnlGradCoord2D(seed, i1, j1, x1, y1); // Nested conditionals were faster than compact bit logic/arithmetic. float xmyi = xi - yi; - if (t > G2) - { - if (xi + xmyi > 1) - { + if (t > G2) { + if (xi + xmyi > 1) { float x2 = x0 + (float)(3 * G2 - 2); float y2 = y0 + (float)(3 * G2 - 1); float a2 = (2.0f / 3.0f) - x2 * x2 - y2 * y2; - if (a2 > 0) - { - value += (a2 * a2) * (a2 * a2) * _fnlGradCoord2D(seed, i + (PRIME_X << 1), j + PRIME_Y, x2, y2); + if (a2 > 0) { + value += (a2 * a2) * (a2 * a2) * + _fnlGradCoord2D( + seed, i + (PRIME_X << 1), j + PRIME_Y, x2, y2 + ); } - } - else - { + } else { float x2 = x0 + (float)G2; float y2 = y0 + (float)(G2 - 1); float a2 = (2.0f / 3.0f) - x2 * x2 - y2 * y2; - if (a2 > 0) - { - value += (a2 * a2) * (a2 * a2) * _fnlGradCoord2D(seed, i, j + PRIME_Y, x2, y2); + if (a2 > 0) { + value += (a2 * a2) * (a2 * a2) * + _fnlGradCoord2D(seed, i, j + PRIME_Y, x2, y2); } } - if (yi - xmyi > 1) - { + if (yi - xmyi > 1) { float x3 = x0 + (float)(3 * G2 - 1); float y3 = y0 + (float)(3 * G2 - 2); float a3 = (2.0f / 3.0f) - x3 * x3 - y3 * y3; - if (a3 > 0) - { - value += (a3 * a3) * (a3 * a3) * _fnlGradCoord2D(seed, i + PRIME_X, j + (PRIME_Y << 1), x3, y3); + if (a3 > 0) { + value += (a3 * a3) * (a3 * a3) * + _fnlGradCoord2D( + seed, i + PRIME_X, j + (PRIME_Y << 1), x3, y3 + ); } - } - else - { + } else { float x3 = x0 + (float)(G2 - 1); float y3 = y0 + (float)G2; float a3 = (2.0f / 3.0f) - x3 * x3 - y3 * y3; - if (a3 > 0) - { - value += (a3 * a3) * (a3 * a3) * _fnlGradCoord2D(seed, i + PRIME_X, j, x3, y3); + if (a3 > 0) { + value += (a3 * a3) * (a3 * a3) * + _fnlGradCoord2D(seed, i + PRIME_X, j, x3, y3); } } - } - else - { - if (xi + xmyi < 0) - { + } else { + if (xi + xmyi < 0) { float x2 = x0 + (float)(1 - G2); float y2 = y0 - (float)G2; float a2 = (2.0f / 3.0f) - x2 * x2 - y2 * y2; - if (a2 > 0) - { - value += (a2 * a2) * (a2 * a2) * _fnlGradCoord2D(seed, i - PRIME_X, j, x2, y2); + if (a2 > 0) { + value += (a2 * a2) * (a2 * a2) * + _fnlGradCoord2D(seed, i - PRIME_X, j, x2, y2); } - } - else - { + } else { float x2 = x0 + (float)(G2 - 1); float y2 = y0 + (float)G2; float a2 = (2.0f / 3.0f) - x2 * x2 - y2 * y2; - if (a2 > 0) - { - value += (a2 * a2) * (a2 * a2) * _fnlGradCoord2D(seed, i + PRIME_X, j, x2, y2); + if (a2 > 0) { + value += (a2 * a2) * (a2 * a2) * + _fnlGradCoord2D(seed, i + PRIME_X, j, x2, y2); } } - if (yi < xmyi) - { + if (yi < xmyi) { float x2 = x0 - (float)G2; float y2 = y0 - (float)(G2 - 1); float a2 = (2.0f / 3.0f) - x2 * x2 - y2 * y2; - if (a2 > 0) - { - value += (a2 * a2) * (a2 * a2) * _fnlGradCoord2D(seed, i, j - PRIME_Y, x2, y2); + if (a2 > 0) { + value += (a2 * a2) * (a2 * a2) * + _fnlGradCoord2D(seed, i, j - PRIME_Y, x2, y2); } - } - else - { + } else { float x2 = x0 + (float)G2; float y2 = y0 + (float)(G2 - 1); float a2 = (2.0f / 3.0f) - x2 * x2 - y2 * y2; - if (a2 > 0) - { - value += (a2 * a2) * (a2 * a2) * _fnlGradCoord2D(seed, i, j + PRIME_Y, x2, y2); + if (a2 > 0) { + value += (a2 * a2) * (a2 * a2) * + _fnlGradCoord2D(seed, i, j + PRIME_Y, x2, y2); } } } @@ -1205,8 +1591,9 @@ static float _fnlSingleOpenSimplex2S2D(int seed, FNLfloat x, FNLfloat y) return value * 18.24196194486065f; } -static float _fnlSingleOpenSimplex2S3D(int seed, FNLfloat x, FNLfloat y, FNLfloat z) -{ +static float _fnlSingleOpenSimplex2S3D( + int seed, FNLfloat x, FNLfloat y, FNLfloat z +) { // 3D OpenSimplex2S case uses two offset rotated cube grids. /* @@ -1236,15 +1623,25 @@ static float _fnlSingleOpenSimplex2S3D(int seed, FNLfloat x, FNLfloat y, FNLfloa float y0 = yi + yNMask; float z0 = zi + zNMask; float a0 = 0.75f - x0 * x0 - y0 * y0 - z0 * z0; - float value = (a0 * a0) * (a0 * a0) * _fnlGradCoord3D(seed, - i + (xNMask & PRIME_X), j + (yNMask & PRIME_Y), k + (zNMask & PRIME_Z), x0, y0, z0); + float value = (a0 * a0) * (a0 * a0) * + _fnlGradCoord3D( + seed, + i + (xNMask & PRIME_X), + j + (yNMask & PRIME_Y), + k + (zNMask & PRIME_Z), + x0, + y0, + z0 + ); float x1 = xi - 0.5f; float y1 = yi - 0.5f; float z1 = zi - 0.5f; float a1 = 0.75f - x1 * x1 - y1 * y1 - z1 * z1; - value += (a1 * a1) * (a1 * a1) * _fnlGradCoord3D(seed2, - i + PRIME_X, j + PRIME_Y, k + PRIME_Z, x1, y1, z1); + value += (a1 * a1) * (a1 * a1) * + _fnlGradCoord3D( + seed2, i + PRIME_X, j + PRIME_Y, k + PRIME_Z, x1, y1, z1 + ); float xAFlipMask0 = ((xNMask | 1) << 1) * x1; float yAFlipMask0 = ((yNMask | 1) << 1) * y1; @@ -1255,142 +1652,217 @@ static float _fnlSingleOpenSimplex2S3D(int seed, FNLfloat x, FNLfloat y, FNLfloa bool skip5 = false; float a2 = xAFlipMask0 + a0; - if (a2 > 0) - { + if (a2 > 0) { float x2 = x0 - (xNMask | 1); float y2 = y0; float z2 = z0; - value += (a2 * a2) * (a2 * a2) * _fnlGradCoord3D(seed, - i + (~xNMask & PRIME_X), j + (yNMask & PRIME_Y), k + (zNMask & PRIME_Z), x2, y2, z2); - } - else - { + value += (a2 * a2) * (a2 * a2) * + _fnlGradCoord3D( + seed, + i + (~xNMask & PRIME_X), + j + (yNMask & PRIME_Y), + k + (zNMask & PRIME_Z), + x2, + y2, + z2 + ); + } else { float a3 = yAFlipMask0 + zAFlipMask0 + a0; - if (a3 > 0) - { + if (a3 > 0) { float x3 = x0; float y3 = y0 - (yNMask | 1); float z3 = z0 - (zNMask | 1); - value += (a3 * a3) * (a3 * a3) * _fnlGradCoord3D(seed, - i + (xNMask & PRIME_X), j + (~yNMask & PRIME_Y), k + (~zNMask & PRIME_Z), x3, y3, z3); + value += (a3 * a3) * (a3 * a3) * + _fnlGradCoord3D( + seed, + i + (xNMask & PRIME_X), + j + (~yNMask & PRIME_Y), + k + (~zNMask & PRIME_Z), + x3, + y3, + z3 + ); } float a4 = xAFlipMask1 + a1; - if (a4 > 0) - { + if (a4 > 0) { float x4 = (xNMask | 1) + x1; float y4 = y1; float z4 = z1; - value += (a4 * a4) * (a4 * a4) * _fnlGradCoord3D(seed2, - i + (xNMask & (PRIME_X * 2)), j + PRIME_Y, k + PRIME_Z, x4, y4, z4); + value += (a4 * a4) * (a4 * a4) * + _fnlGradCoord3D( + seed2, + i + (xNMask & (PRIME_X * 2)), + j + PRIME_Y, + k + PRIME_Z, + x4, + y4, + z4 + ); skip5 = true; } } bool skip9 = false; float a6 = yAFlipMask0 + a0; - if (a6 > 0) - { + if (a6 > 0) { float x6 = x0; float y6 = y0 - (yNMask | 1); float z6 = z0; - value += (a6 * a6) * (a6 * a6) * _fnlGradCoord3D(seed, - i + (xNMask & PRIME_X), j + (~yNMask & PRIME_Y), k + (zNMask & PRIME_Z), x6, y6, z6); - } - else - { + value += (a6 * a6) * (a6 * a6) * + _fnlGradCoord3D( + seed, + i + (xNMask & PRIME_X), + j + (~yNMask & PRIME_Y), + k + (zNMask & PRIME_Z), + x6, + y6, + z6 + ); + } else { float a7 = xAFlipMask0 + zAFlipMask0 + a0; - if (a7 > 0) - { + if (a7 > 0) { float x7 = x0 - (xNMask | 1); float y7 = y0; float z7 = z0 - (zNMask | 1); - value += (a7 * a7) * (a7 * a7) * _fnlGradCoord3D(seed, - i + (~xNMask & PRIME_X), j + (yNMask & PRIME_Y), k + (~zNMask & PRIME_Z), x7, y7, z7); + value += (a7 * a7) * (a7 * a7) * + _fnlGradCoord3D( + seed, + i + (~xNMask & PRIME_X), + j + (yNMask & PRIME_Y), + k + (~zNMask & PRIME_Z), + x7, + y7, + z7 + ); } float a8 = yAFlipMask1 + a1; - if (a8 > 0) - { + if (a8 > 0) { float x8 = x1; float y8 = (yNMask | 1) + y1; float z8 = z1; - value += (a8 * a8) * (a8 * a8) * _fnlGradCoord3D(seed2, - i + PRIME_X, j + (yNMask & (PRIME_Y << 1)), k + PRIME_Z, x8, y8, z8); + value += (a8 * a8) * (a8 * a8) * + _fnlGradCoord3D( + seed2, + i + PRIME_X, + j + (yNMask & (PRIME_Y << 1)), + k + PRIME_Z, + x8, + y8, + z8 + ); skip9 = true; } } bool skipD = false; float aA = zAFlipMask0 + a0; - if (aA > 0) - { + if (aA > 0) { float xA = x0; float yA = y0; float zA = z0 - (zNMask | 1); - value += (aA * aA) * (aA * aA) * _fnlGradCoord3D(seed, - i + (xNMask & PRIME_X), j + (yNMask & PRIME_Y), k + (~zNMask & PRIME_Z), xA, yA, zA); - } - else - { + value += (aA * aA) * (aA * aA) * + _fnlGradCoord3D( + seed, + i + (xNMask & PRIME_X), + j + (yNMask & PRIME_Y), + k + (~zNMask & PRIME_Z), + xA, + yA, + zA + ); + } else { float aB = xAFlipMask0 + yAFlipMask0 + a0; - if (aB > 0) - { + if (aB > 0) { float xB = x0 - (xNMask | 1); float yB = y0 - (yNMask | 1); float zB = z0; - value += (aB * aB) * (aB * aB) * _fnlGradCoord3D(seed, - i + (~xNMask & PRIME_X), j + (~yNMask & PRIME_Y), k + (zNMask & PRIME_Z), xB, yB, zB); + value += (aB * aB) * (aB * aB) * + _fnlGradCoord3D( + seed, + i + (~xNMask & PRIME_X), + j + (~yNMask & PRIME_Y), + k + (zNMask & PRIME_Z), + xB, + yB, + zB + ); } float aC = zAFlipMask1 + a1; - if (aC > 0) - { + if (aC > 0) { float xC = x1; float yC = y1; float zC = (zNMask | 1) + z1; - value += (aC * aC) * (aC * aC) * _fnlGradCoord3D(seed2, - i + PRIME_X, j + PRIME_Y, k + (zNMask & (PRIME_Z << 1)), xC, yC, zC); + value += (aC * aC) * (aC * aC) * + _fnlGradCoord3D( + seed2, + i + PRIME_X, + j + PRIME_Y, + k + (zNMask & (PRIME_Z << 1)), + xC, + yC, + zC + ); skipD = true; } } - if (!skip5) - { + if (!skip5) { float a5 = yAFlipMask1 + zAFlipMask1 + a1; - if (a5 > 0) - { + if (a5 > 0) { float x5 = x1; float y5 = (yNMask | 1) + y1; float z5 = (zNMask | 1) + z1; - value += (a5 * a5) * (a5 * a5) * _fnlGradCoord3D(seed2, - i + PRIME_X, j + (yNMask & (PRIME_Y << 1)), k + (zNMask & (PRIME_Z << 1)), x5, y5, z5); + value += (a5 * a5) * (a5 * a5) * + _fnlGradCoord3D( + seed2, + i + PRIME_X, + j + (yNMask & (PRIME_Y << 1)), + k + (zNMask & (PRIME_Z << 1)), + x5, + y5, + z5 + ); } } - if (!skip9) - { + if (!skip9) { float a9 = xAFlipMask1 + zAFlipMask1 + a1; - if (a9 > 0) - { + if (a9 > 0) { float x9 = (xNMask | 1) + x1; float y9 = y1; float z9 = (zNMask | 1) + z1; - value += (a9 * a9) * (a9 * a9) * _fnlGradCoord3D(seed2, - i + (xNMask & (PRIME_X * 2)), j + PRIME_Y, k + (zNMask & (PRIME_Z << 1)), x9, y9, z9); + value += (a9 * a9) * (a9 * a9) * + _fnlGradCoord3D( + seed2, + i + (xNMask & (PRIME_X * 2)), + j + PRIME_Y, + k + (zNMask & (PRIME_Z << 1)), + x9, + y9, + z9 + ); } } - if (!skipD) - { + if (!skipD) { float aD = xAFlipMask1 + yAFlipMask1 + a1; - if (aD > 0) - { + if (aD > 0) { float xD = (xNMask | 1) + x1; float yD = (yNMask | 1) + y1; float zD = z1; - value += (aD * aD) * (aD * aD) * _fnlGradCoord3D(seed2, - i + (xNMask & (PRIME_X << 1)), j + (yNMask & (PRIME_Y << 1)), k + PRIME_Z, xD, yD, zD); + value += (aD * aD) * (aD * aD) * + _fnlGradCoord3D( + seed2, + i + (xNMask & (PRIME_X << 1)), + j + (yNMask & (PRIME_Y << 1)), + k + PRIME_Z, + xD, + yD, + zD + ); } } @@ -1399,8 +1871,9 @@ static float _fnlSingleOpenSimplex2S3D(int seed, FNLfloat x, FNLfloat y, FNLfloa // Cellular Noise -static float _fnlSingleCellular2D(fnl_state *state, int seed, FNLfloat x, FNLfloat y) -{ +static float _fnlSingleCellular2D( + fnl_state *state, int seed, FNLfloat x, FNLfloat y +) { int xr = _fnlFastRound(x); int yr = _fnlFastRound(y); @@ -1413,119 +1886,123 @@ static float _fnlSingleCellular2D(fnl_state *state, int seed, FNLfloat x, FNLflo int xPrimed = (xr - 1) * PRIME_X; int yPrimedBase = (yr - 1) * PRIME_Y; - switch (state->cellular_distance_func) - { - default: - case FNL_CELLULAR_DISTANCE_EUCLIDEAN: - case FNL_CELLULAR_DISTANCE_EUCLIDEANSQ: - for (int xi = xr - 1; xi <= xr + 1; xi++) - { - int yPrimed = yPrimedBase; + switch (state->cellular_distance_func) { + default: + case FNL_CELLULAR_DISTANCE_EUCLIDEAN: + case FNL_CELLULAR_DISTANCE_EUCLIDEANSQ: + for (int xi = xr - 1; xi <= xr + 1; xi++) { + int yPrimed = yPrimedBase; - for (int yi = yr - 1; yi <= yr + 1; yi++) - { - int hash = _fnlHash2D(seed, xPrimed, yPrimed); - int idx = hash & (255 << 1); + for (int yi = yr - 1; yi <= yr + 1; yi++) { + int hash = _fnlHash2D(seed, xPrimed, yPrimed); + int idx = hash & (255 << 1); - float vecX = (float)(xi - x) + RAND_VECS_2D[idx] * cellularJitter; - float vecY = (float)(yi - y) + RAND_VECS_2D[idx | 1] * cellularJitter; + float vecX = + (float)(xi - x) + RAND_VECS_2D[idx] * cellularJitter; + float vecY = (float)(yi - y) + + RAND_VECS_2D[idx | 1] * cellularJitter; - float newDistance = vecX * vecX + vecY * vecY; + float newDistance = vecX * vecX + vecY * vecY; - distance1 = _fnlFastMax(_fnlFastMin(distance1, newDistance), distance0); - if (newDistance < distance0) - { - distance0 = newDistance; - closestHash = hash; + distance1 = _fnlFastMax( + _fnlFastMin(distance1, newDistance), distance0 + ); + if (newDistance < distance0) { + distance0 = newDistance; + closestHash = hash; + } + yPrimed += PRIME_Y; } - yPrimed += PRIME_Y; + xPrimed += PRIME_X; } - xPrimed += PRIME_X; - } - break; - case FNL_CELLULAR_DISTANCE_MANHATTAN: - for (int xi = xr - 1; xi <= xr + 1; xi++) - { - int yPrimed = yPrimedBase; + break; + case FNL_CELLULAR_DISTANCE_MANHATTAN: + for (int xi = xr - 1; xi <= xr + 1; xi++) { + int yPrimed = yPrimedBase; - for (int yi = yr - 1; yi <= yr + 1; yi++) - { - int hash = _fnlHash2D(seed, xPrimed, yPrimed); - int idx = hash & (255 << 1); + for (int yi = yr - 1; yi <= yr + 1; yi++) { + int hash = _fnlHash2D(seed, xPrimed, yPrimed); + int idx = hash & (255 << 1); - float vecX = (float)(xi - x) + RAND_VECS_2D[idx] * cellularJitter; - float vecY = (float)(yi - y) + RAND_VECS_2D[idx | 1] * cellularJitter; + float vecX = + (float)(xi - x) + RAND_VECS_2D[idx] * cellularJitter; + float vecY = (float)(yi - y) + + RAND_VECS_2D[idx | 1] * cellularJitter; - float newDistance = _fnlFastAbs(vecX) + _fnlFastAbs(vecY); + float newDistance = _fnlFastAbs(vecX) + _fnlFastAbs(vecY); - distance1 = _fnlFastMax(_fnlFastMin(distance1, newDistance), distance0); - if (newDistance < distance0) - { - distance0 = newDistance; - closestHash = hash; + distance1 = _fnlFastMax( + _fnlFastMin(distance1, newDistance), distance0 + ); + if (newDistance < distance0) { + distance0 = newDistance; + closestHash = hash; + } + yPrimed += PRIME_Y; } - yPrimed += PRIME_Y; + xPrimed += PRIME_X; } - xPrimed += PRIME_X; - } - break; - case FNL_CELLULAR_DISTANCE_HYBRID: - for (int xi = xr - 1; xi <= xr + 1; xi++) - { - int yPrimed = yPrimedBase; - for (int yi = yr - 1; yi <= yr + 1; yi++) - { - int hash = _fnlHash2D(seed, xPrimed, yPrimed); - int idx = hash & (255 << 1); + break; + case FNL_CELLULAR_DISTANCE_HYBRID: + for (int xi = xr - 1; xi <= xr + 1; xi++) { + int yPrimed = yPrimedBase; + for (int yi = yr - 1; yi <= yr + 1; yi++) { + int hash = _fnlHash2D(seed, xPrimed, yPrimed); + int idx = hash & (255 << 1); - float vecX = (float)(xi - x) + RAND_VECS_2D[idx] * cellularJitter; - float vecY = (float)(yi - y) + RAND_VECS_2D[idx | 1] * cellularJitter; + float vecX = + (float)(xi - x) + RAND_VECS_2D[idx] * cellularJitter; + float vecY = (float)(yi - y) + + RAND_VECS_2D[idx | 1] * cellularJitter; - float newDistance = (_fnlFastAbs(vecX) + _fnlFastAbs(vecY)) + (vecX * vecX + vecY * vecY); + float newDistance = + (_fnlFastAbs(vecX) + _fnlFastAbs(vecY)) + + (vecX * vecX + vecY * vecY); - distance1 = _fnlFastMax(_fnlFastMin(distance1, newDistance), distance0); - if (newDistance < distance0) - { - distance0 = newDistance; - closestHash = hash; + distance1 = _fnlFastMax( + _fnlFastMin(distance1, newDistance), distance0 + ); + if (newDistance < distance0) { + distance0 = newDistance; + closestHash = hash; + } + yPrimed += PRIME_Y; } - yPrimed += PRIME_Y; + xPrimed += PRIME_X; } - xPrimed += PRIME_X; - } - break; + break; } - if (state->cellular_distance_func == FNL_CELLULAR_DISTANCE_EUCLIDEAN && state->cellular_return_type >= FNL_CELLULAR_RETURN_VALUE_DISTANCE) - { + if (state->cellular_distance_func == FNL_CELLULAR_DISTANCE_EUCLIDEAN && + state->cellular_return_type >= FNL_CELLULAR_RETURN_VALUE_DISTANCE) { distance0 = _fnlFastSqrt(distance0); if (state->cellular_return_type >= FNL_CELLULAR_RETURN_VALUE_DISTANCE2) distance1 = _fnlFastSqrt(distance1); } - switch (state->cellular_return_type) - { - case FNL_CELLULAR_RETURN_VALUE_CELLVALUE: - return closestHash * (1 / 2147483648.0f); - case FNL_CELLULAR_RETURN_VALUE_DISTANCE: - return distance0 - 1; - case FNL_CELLULAR_RETURN_VALUE_DISTANCE2: - return distance1 - 1; - case FNL_CELLULAR_RETURN_VALUE_DISTANCE2ADD: - return (distance1 + distance0) * 0.5f - 1; - case FNL_CELLULAR_RETURN_VALUE_DISTANCE2SUB: - return distance1 - distance0 - 1; - case FNL_CELLULAR_RETURN_VALUE_DISTANCE2MUL: - return distance1 * distance0 * 0.5f - 1; - case FNL_CELLULAR_RETURN_VALUE_DISTANCE2DIV: - return distance0 / distance1 - 1; - default: - return 0; + switch (state->cellular_return_type) { + case FNL_CELLULAR_RETURN_VALUE_CELLVALUE: + return closestHash * (1 / 2147483648.0f); + case FNL_CELLULAR_RETURN_VALUE_DISTANCE: + return distance0 - 1; + case FNL_CELLULAR_RETURN_VALUE_DISTANCE2: + return distance1 - 1; + case FNL_CELLULAR_RETURN_VALUE_DISTANCE2ADD: + return (distance1 + distance0) * 0.5f - 1; + case FNL_CELLULAR_RETURN_VALUE_DISTANCE2SUB: + return distance1 - distance0 - 1; + case FNL_CELLULAR_RETURN_VALUE_DISTANCE2MUL: + return distance1 * distance0 * 0.5f - 1; + case FNL_CELLULAR_RETURN_VALUE_DISTANCE2DIV: + return distance0 / distance1 - 1; + default: + return 0; } } -static float _fnlSingleCellular3D(fnl_state *state, int seed, FNLfloat x, FNLfloat y, FNLfloat z) -{ +static float _fnlSingleCellular3D( + fnl_state *state, int seed, FNLfloat x, FNLfloat y, FNLfloat z +) { int xr = _fnlFastRound(x); int yr = _fnlFastRound(y); int zr = _fnlFastRound(z); @@ -1540,143 +2017,149 @@ static float _fnlSingleCellular3D(fnl_state *state, int seed, FNLfloat x, FNLflo int yPrimedBase = (yr - 1) * PRIME_Y; int zPrimedBase = (zr - 1) * PRIME_Z; - switch (state->cellular_distance_func) - { - default: - case FNL_CELLULAR_DISTANCE_EUCLIDEAN: - case FNL_CELLULAR_DISTANCE_EUCLIDEANSQ: - for (int xi = xr - 1; xi <= xr + 1; xi++) - { - int yPrimed = yPrimedBase; + switch (state->cellular_distance_func) { + default: + case FNL_CELLULAR_DISTANCE_EUCLIDEAN: + case FNL_CELLULAR_DISTANCE_EUCLIDEANSQ: + for (int xi = xr - 1; xi <= xr + 1; xi++) { + int yPrimed = yPrimedBase; - for (int yi = yr - 1; yi <= yr + 1; yi++) - { - int zPrimed = zPrimedBase; + for (int yi = yr - 1; yi <= yr + 1; yi++) { + int zPrimed = zPrimedBase; - for (int zi = zr - 1; zi <= zr + 1; zi++) - { - int hash = _fnlHash3D(seed, xPrimed, yPrimed, zPrimed); - int idx = hash & (255 << 2); + for (int zi = zr - 1; zi <= zr + 1; zi++) { + int hash = _fnlHash3D(seed, xPrimed, yPrimed, zPrimed); + int idx = hash & (255 << 2); - float vecX = (float)(xi - x) + RAND_VECS_3D[idx] * cellularJitter; - float vecY = (float)(yi - y) + RAND_VECS_3D[idx | 1] * cellularJitter; - float vecZ = (float)(zi - z) + RAND_VECS_3D[idx | 2] * cellularJitter; + float vecX = (float)(xi - x) + + RAND_VECS_3D[idx] * cellularJitter; + float vecY = (float)(yi - y) + + RAND_VECS_3D[idx | 1] * cellularJitter; + float vecZ = (float)(zi - z) + + RAND_VECS_3D[idx | 2] * cellularJitter; - float newDistance = vecX * vecX + vecY * vecY + vecZ * vecZ; + float newDistance = + vecX * vecX + vecY * vecY + vecZ * vecZ; - distance1 = _fnlFastMax(_fnlFastMin(distance1, newDistance), distance0); - if (newDistance < distance0) - { - distance0 = newDistance; - closestHash = hash; + distance1 = _fnlFastMax( + _fnlFastMin(distance1, newDistance), distance0 + ); + if (newDistance < distance0) { + distance0 = newDistance; + closestHash = hash; + } + zPrimed += PRIME_Z; } - zPrimed += PRIME_Z; + yPrimed += PRIME_Y; } - yPrimed += PRIME_Y; + xPrimed += PRIME_X; } - xPrimed += PRIME_X; - } - break; - case FNL_CELLULAR_DISTANCE_MANHATTAN: - for (int xi = xr - 1; xi <= xr + 1; xi++) - { - int yPrimed = yPrimedBase; + break; + case FNL_CELLULAR_DISTANCE_MANHATTAN: + for (int xi = xr - 1; xi <= xr + 1; xi++) { + int yPrimed = yPrimedBase; - for (int yi = yr - 1; yi <= yr + 1; yi++) - { - int zPrimed = zPrimedBase; + for (int yi = yr - 1; yi <= yr + 1; yi++) { + int zPrimed = zPrimedBase; - for (int zi = zr - 1; zi <= zr + 1; zi++) - { - int hash = _fnlHash3D(seed, xPrimed, yPrimed, zPrimed); - int idx = hash & (255 << 2); + for (int zi = zr - 1; zi <= zr + 1; zi++) { + int hash = _fnlHash3D(seed, xPrimed, yPrimed, zPrimed); + int idx = hash & (255 << 2); - float vecX = (float)(xi - x) + RAND_VECS_3D[idx] * cellularJitter; - float vecY = (float)(yi - y) + RAND_VECS_3D[idx | 1] * cellularJitter; - float vecZ = (float)(zi - z) + RAND_VECS_3D[idx | 2] * cellularJitter; + float vecX = (float)(xi - x) + + RAND_VECS_3D[idx] * cellularJitter; + float vecY = (float)(yi - y) + + RAND_VECS_3D[idx | 1] * cellularJitter; + float vecZ = (float)(zi - z) + + RAND_VECS_3D[idx | 2] * cellularJitter; - float newDistance = _fnlFastAbs(vecX) + _fnlFastAbs(vecY) + _fnlFastAbs(vecZ); + float newDistance = _fnlFastAbs(vecX) + + _fnlFastAbs(vecY) + + _fnlFastAbs(vecZ); - distance1 = _fnlFastMax(_fnlFastMin(distance1, newDistance), distance0); - if (newDistance < distance0) - { - distance0 = newDistance; - closestHash = hash; + distance1 = _fnlFastMax( + _fnlFastMin(distance1, newDistance), distance0 + ); + if (newDistance < distance0) { + distance0 = newDistance; + closestHash = hash; + } + zPrimed += PRIME_Z; } - zPrimed += PRIME_Z; + yPrimed += PRIME_Y; } - yPrimed += PRIME_Y; + xPrimed += PRIME_X; } - xPrimed += PRIME_X; - } - break; - case FNL_CELLULAR_DISTANCE_HYBRID: - for (int xi = xr - 1; xi <= xr + 1; xi++) - { - int yPrimed = yPrimedBase; + break; + case FNL_CELLULAR_DISTANCE_HYBRID: + for (int xi = xr - 1; xi <= xr + 1; xi++) { + int yPrimed = yPrimedBase; - for (int yi = yr - 1; yi <= yr + 1; yi++) - { - int zPrimed = zPrimedBase; + for (int yi = yr - 1; yi <= yr + 1; yi++) { + int zPrimed = zPrimedBase; - for (int zi = zr - 1; zi <= zr + 1; zi++) - { - int hash = _fnlHash3D(seed, xPrimed, yPrimed, zPrimed); - int idx = hash & (255 << 2); + for (int zi = zr - 1; zi <= zr + 1; zi++) { + int hash = _fnlHash3D(seed, xPrimed, yPrimed, zPrimed); + int idx = hash & (255 << 2); - float vecX = (float)(xi - x) + RAND_VECS_3D[idx] * cellularJitter; - float vecY = (float)(yi - y) + RAND_VECS_3D[idx | 1] * cellularJitter; - float vecZ = (float)(zi - z) + RAND_VECS_3D[idx | 2] * cellularJitter; + float vecX = (float)(xi - x) + + RAND_VECS_3D[idx] * cellularJitter; + float vecY = (float)(yi - y) + + RAND_VECS_3D[idx | 1] * cellularJitter; + float vecZ = (float)(zi - z) + + RAND_VECS_3D[idx | 2] * cellularJitter; - float newDistance = (_fnlFastAbs(vecX) + _fnlFastAbs(vecY) + _fnlFastAbs(vecZ)) + (vecX * vecX + vecY * vecY + vecZ * vecZ); + float newDistance = + (_fnlFastAbs(vecX) + _fnlFastAbs(vecY) + + _fnlFastAbs(vecZ)) + + (vecX * vecX + vecY * vecY + vecZ * vecZ); - distance1 = _fnlFastMax(_fnlFastMin(distance1, newDistance), distance0); - if (newDistance < distance0) - { - distance0 = newDistance; - closestHash = hash; + distance1 = _fnlFastMax( + _fnlFastMin(distance1, newDistance), distance0 + ); + if (newDistance < distance0) { + distance0 = newDistance; + closestHash = hash; + } + zPrimed += PRIME_Z; } - zPrimed += PRIME_Z; + yPrimed += PRIME_Y; } - yPrimed += PRIME_Y; + xPrimed += PRIME_X; } - xPrimed += PRIME_X; - } - break; + break; } - if (state->cellular_distance_func == FNL_CELLULAR_DISTANCE_EUCLIDEAN && state->cellular_return_type >= FNL_CELLULAR_RETURN_VALUE_DISTANCE) - { + if (state->cellular_distance_func == FNL_CELLULAR_DISTANCE_EUCLIDEAN && + state->cellular_return_type >= FNL_CELLULAR_RETURN_VALUE_DISTANCE) { distance0 = _fnlFastSqrt(distance0); if (state->cellular_return_type >= FNL_CELLULAR_RETURN_VALUE_DISTANCE2) distance1 = _fnlFastSqrt(distance1); } - switch (state->cellular_return_type) - { - case FNL_CELLULAR_RETURN_VALUE_CELLVALUE: - return closestHash * (1 / 2147483648.0f); - case FNL_CELLULAR_RETURN_VALUE_DISTANCE: - return distance0 - 1; - case FNL_CELLULAR_RETURN_VALUE_DISTANCE2: - return distance1 - 1; - case FNL_CELLULAR_RETURN_VALUE_DISTANCE2ADD: - return (distance1 + distance0) * 0.5f - 1; - case FNL_CELLULAR_RETURN_VALUE_DISTANCE2SUB: - return distance1 - distance0 - 1; - case FNL_CELLULAR_RETURN_VALUE_DISTANCE2MUL: - return distance1 * distance0 * 0.5f - 1; - case FNL_CELLULAR_RETURN_VALUE_DISTANCE2DIV: - return distance0 / distance1 - 1; - default: - return 0; + switch (state->cellular_return_type) { + case FNL_CELLULAR_RETURN_VALUE_CELLVALUE: + return closestHash * (1 / 2147483648.0f); + case FNL_CELLULAR_RETURN_VALUE_DISTANCE: + return distance0 - 1; + case FNL_CELLULAR_RETURN_VALUE_DISTANCE2: + return distance1 - 1; + case FNL_CELLULAR_RETURN_VALUE_DISTANCE2ADD: + return (distance1 + distance0) * 0.5f - 1; + case FNL_CELLULAR_RETURN_VALUE_DISTANCE2SUB: + return distance1 - distance0 - 1; + case FNL_CELLULAR_RETURN_VALUE_DISTANCE2MUL: + return distance1 * distance0 * 0.5f - 1; + case FNL_CELLULAR_RETURN_VALUE_DISTANCE2DIV: + return distance0 / distance1 - 1; + default: + return 0; } } // Perlin Noise -static float _fnlSinglePerlin2D(int seed, FNLfloat x, FNLfloat y) -{ +static float _fnlSinglePerlin2D(int seed, FNLfloat x, FNLfloat y) { int x0 = _fnlFastFloor(x); int y0 = _fnlFastFloor(y); @@ -1693,14 +2176,21 @@ static float _fnlSinglePerlin2D(int seed, FNLfloat x, FNLfloat y) int x1 = x0 + PRIME_X; int y1 = y0 + PRIME_Y; - float xf0 = _fnlLerp(_fnlGradCoord2D(seed, x0, y0, xd0, yd0), _fnlGradCoord2D(seed, x1, y0, xd1, yd0), xs); - float xf1 = _fnlLerp(_fnlGradCoord2D(seed, x0, y1, xd0, yd1), _fnlGradCoord2D(seed, x1, y1, xd1, yd1), xs); + float xf0 = _fnlLerp( + _fnlGradCoord2D(seed, x0, y0, xd0, yd0), + _fnlGradCoord2D(seed, x1, y0, xd1, yd0), + xs + ); + float xf1 = _fnlLerp( + _fnlGradCoord2D(seed, x0, y1, xd0, yd1), + _fnlGradCoord2D(seed, x1, y1, xd1, yd1), + xs + ); return _fnlLerp(xf0, xf1, ys) * 1.4247691104677813f; } -static float _fnlSinglePerlin3D(int seed, FNLfloat x, FNLfloat y, FNLfloat z) -{ +static float _fnlSinglePerlin3D(int seed, FNLfloat x, FNLfloat y, FNLfloat z) { int x0 = _fnlFastFloor(x); int y0 = _fnlFastFloor(y); int z0 = _fnlFastFloor(z); @@ -1723,10 +2213,26 @@ static float _fnlSinglePerlin3D(int seed, FNLfloat x, FNLfloat y, FNLfloat z) int y1 = y0 + PRIME_Y; int z1 = z0 + PRIME_Z; - float xf00 = _fnlLerp(_fnlGradCoord3D(seed, x0, y0, z0, xd0, yd0, zd0), _fnlGradCoord3D(seed, x1, y0, z0, xd1, yd0, zd0), xs); - float xf10 = _fnlLerp(_fnlGradCoord3D(seed, x0, y1, z0, xd0, yd1, zd0), _fnlGradCoord3D(seed, x1, y1, z0, xd1, yd1, zd0), xs); - float xf01 = _fnlLerp(_fnlGradCoord3D(seed, x0, y0, z1, xd0, yd0, zd1), _fnlGradCoord3D(seed, x1, y0, z1, xd1, yd0, zd1), xs); - float xf11 = _fnlLerp(_fnlGradCoord3D(seed, x0, y1, z1, xd0, yd1, zd1), _fnlGradCoord3D(seed, x1, y1, z1, xd1, yd1, zd1), xs); + float xf00 = _fnlLerp( + _fnlGradCoord3D(seed, x0, y0, z0, xd0, yd0, zd0), + _fnlGradCoord3D(seed, x1, y0, z0, xd1, yd0, zd0), + xs + ); + float xf10 = _fnlLerp( + _fnlGradCoord3D(seed, x0, y1, z0, xd0, yd1, zd0), + _fnlGradCoord3D(seed, x1, y1, z0, xd1, yd1, zd0), + xs + ); + float xf01 = _fnlLerp( + _fnlGradCoord3D(seed, x0, y0, z1, xd0, yd0, zd1), + _fnlGradCoord3D(seed, x1, y0, z1, xd1, yd0, zd1), + xs + ); + float xf11 = _fnlLerp( + _fnlGradCoord3D(seed, x0, y1, z1, xd0, yd1, zd1), + _fnlGradCoord3D(seed, x1, y1, z1, xd1, yd1, zd1), + xs + ); float yf0 = _fnlLerp(xf00, xf10, ys); float yf1 = _fnlLerp(xf01, xf11, ys); @@ -1736,8 +2242,7 @@ static float _fnlSinglePerlin3D(int seed, FNLfloat x, FNLfloat y, FNLfloat z) // Value Cubic -static float _fnlSingleValueCubic2D(int seed, FNLfloat x, FNLfloat y) -{ +static float _fnlSingleValueCubic2D(int seed, FNLfloat x, FNLfloat y) { int x1 = _fnlFastFloor(x); int y1 = _fnlFastFloor(y); @@ -1755,19 +2260,42 @@ static float _fnlSingleValueCubic2D(int seed, FNLfloat x, FNLfloat y) int y3 = y1 + (int)((long)PRIME_Y << 1); return _fnlCubicLerp( - _fnlCubicLerp(_fnlValCoord2D(seed, x0, y0), _fnlValCoord2D(seed, x1, y0), _fnlValCoord2D(seed, x2, y0), _fnlValCoord2D(seed, x3, y0), - xs), - _fnlCubicLerp(_fnlValCoord2D(seed, x0, y1), _fnlValCoord2D(seed, x1, y1), _fnlValCoord2D(seed, x2, y1), _fnlValCoord2D(seed, x3, y1), - xs), - _fnlCubicLerp(_fnlValCoord2D(seed, x0, y2), _fnlValCoord2D(seed, x1, y2), _fnlValCoord2D(seed, x2, y2), _fnlValCoord2D(seed, x3, y2), - xs), - _fnlCubicLerp(_fnlValCoord2D(seed, x0, y3), _fnlValCoord2D(seed, x1, y3), _fnlValCoord2D(seed, x2, y3), _fnlValCoord2D(seed, x3, y3), - xs), - ys) * (1 / (1.5f * 1.5f)); + _fnlCubicLerp( + _fnlValCoord2D(seed, x0, y0), + _fnlValCoord2D(seed, x1, y0), + _fnlValCoord2D(seed, x2, y0), + _fnlValCoord2D(seed, x3, y0), + xs + ), + _fnlCubicLerp( + _fnlValCoord2D(seed, x0, y1), + _fnlValCoord2D(seed, x1, y1), + _fnlValCoord2D(seed, x2, y1), + _fnlValCoord2D(seed, x3, y1), + xs + ), + _fnlCubicLerp( + _fnlValCoord2D(seed, x0, y2), + _fnlValCoord2D(seed, x1, y2), + _fnlValCoord2D(seed, x2, y2), + _fnlValCoord2D(seed, x3, y2), + xs + ), + _fnlCubicLerp( + _fnlValCoord2D(seed, x0, y3), + _fnlValCoord2D(seed, x1, y3), + _fnlValCoord2D(seed, x2, y3), + _fnlValCoord2D(seed, x3, y3), + xs + ), + ys + ) * + (1 / (1.5f * 1.5f)); } -static float _fnlSingleValueCubic3D(int seed, FNLfloat x, FNLfloat y, FNLfloat z) -{ +static float _fnlSingleValueCubic3D( + int seed, FNLfloat x, FNLfloat y, FNLfloat z +) { int x1 = _fnlFastFloor(x); int y1 = _fnlFastFloor(y); int z1 = _fnlFastFloor(z); @@ -1791,37 +2319,138 @@ static float _fnlSingleValueCubic3D(int seed, FNLfloat x, FNLfloat y, FNLfloat z int z3 = z1 + (int)((long)PRIME_Z << 1); return _fnlCubicLerp( - _fnlCubicLerp( - _fnlCubicLerp(_fnlValCoord3D(seed, x0, y0, z0), _fnlValCoord3D(seed, x1, y0, z0), _fnlValCoord3D(seed, x2, y0, z0), _fnlValCoord3D(seed, x3, y0, z0), xs), - _fnlCubicLerp(_fnlValCoord3D(seed, x0, y1, z0), _fnlValCoord3D(seed, x1, y1, z0), _fnlValCoord3D(seed, x2, y1, z0), _fnlValCoord3D(seed, x3, y1, z0), xs), - _fnlCubicLerp(_fnlValCoord3D(seed, x0, y2, z0), _fnlValCoord3D(seed, x1, y2, z0), _fnlValCoord3D(seed, x2, y2, z0), _fnlValCoord3D(seed, x3, y2, z0), xs), - _fnlCubicLerp(_fnlValCoord3D(seed, x0, y3, z0), _fnlValCoord3D(seed, x1, y3, z0), _fnlValCoord3D(seed, x2, y3, z0), _fnlValCoord3D(seed, x3, y3, z0), xs), - ys), - _fnlCubicLerp( - _fnlCubicLerp(_fnlValCoord3D(seed, x0, y0, z1), _fnlValCoord3D(seed, x1, y0, z1), _fnlValCoord3D(seed, x2, y0, z1), _fnlValCoord3D(seed, x3, y0, z1), xs), - _fnlCubicLerp(_fnlValCoord3D(seed, x0, y1, z1), _fnlValCoord3D(seed, x1, y1, z1), _fnlValCoord3D(seed, x2, y1, z1), _fnlValCoord3D(seed, x3, y1, z1), xs), - _fnlCubicLerp(_fnlValCoord3D(seed, x0, y2, z1), _fnlValCoord3D(seed, x1, y2, z1), _fnlValCoord3D(seed, x2, y2, z1), _fnlValCoord3D(seed, x3, y2, z1), xs), - _fnlCubicLerp(_fnlValCoord3D(seed, x0, y3, z1), _fnlValCoord3D(seed, x1, y3, z1), _fnlValCoord3D(seed, x2, y3, z1), _fnlValCoord3D(seed, x3, y3, z1), xs), - ys), - _fnlCubicLerp( - _fnlCubicLerp(_fnlValCoord3D(seed, x0, y0, z2), _fnlValCoord3D(seed, x1, y0, z2), _fnlValCoord3D(seed, x2, y0, z2), _fnlValCoord3D(seed, x3, y0, z2), xs), - _fnlCubicLerp(_fnlValCoord3D(seed, x0, y1, z2), _fnlValCoord3D(seed, x1, y1, z2), _fnlValCoord3D(seed, x2, y1, z2), _fnlValCoord3D(seed, x3, y1, z2), xs), - _fnlCubicLerp(_fnlValCoord3D(seed, x0, y2, z2), _fnlValCoord3D(seed, x1, y2, z2), _fnlValCoord3D(seed, x2, y2, z2), _fnlValCoord3D(seed, x3, y2, z2), xs), - _fnlCubicLerp(_fnlValCoord3D(seed, x0, y3, z2), _fnlValCoord3D(seed, x1, y3, z2), _fnlValCoord3D(seed, x2, y3, z2), _fnlValCoord3D(seed, x3, y3, z2), xs), - ys), - _fnlCubicLerp( - _fnlCubicLerp(_fnlValCoord3D(seed, x0, y0, z3), _fnlValCoord3D(seed, x1, y0, z3), _fnlValCoord3D(seed, x2, y0, z3), _fnlValCoord3D(seed, x3, y0, z3), xs), - _fnlCubicLerp(_fnlValCoord3D(seed, x0, y1, z3), _fnlValCoord3D(seed, x1, y1, z3), _fnlValCoord3D(seed, x2, y1, z3), _fnlValCoord3D(seed, x3, y1, z3), xs), - _fnlCubicLerp(_fnlValCoord3D(seed, x0, y2, z3), _fnlValCoord3D(seed, x1, y2, z3), _fnlValCoord3D(seed, x2, y2, z3), _fnlValCoord3D(seed, x3, y2, z3), xs), - _fnlCubicLerp(_fnlValCoord3D(seed, x0, y3, z3), _fnlValCoord3D(seed, x1, y3, z3), _fnlValCoord3D(seed, x2, y3, z3), _fnlValCoord3D(seed, x3, y3, z3), xs), - ys), - zs) * (1 / 1.5f * 1.5f * 1.5f); + _fnlCubicLerp( + _fnlCubicLerp( + _fnlValCoord3D(seed, x0, y0, z0), + _fnlValCoord3D(seed, x1, y0, z0), + _fnlValCoord3D(seed, x2, y0, z0), + _fnlValCoord3D(seed, x3, y0, z0), + xs + ), + _fnlCubicLerp( + _fnlValCoord3D(seed, x0, y1, z0), + _fnlValCoord3D(seed, x1, y1, z0), + _fnlValCoord3D(seed, x2, y1, z0), + _fnlValCoord3D(seed, x3, y1, z0), + xs + ), + _fnlCubicLerp( + _fnlValCoord3D(seed, x0, y2, z0), + _fnlValCoord3D(seed, x1, y2, z0), + _fnlValCoord3D(seed, x2, y2, z0), + _fnlValCoord3D(seed, x3, y2, z0), + xs + ), + _fnlCubicLerp( + _fnlValCoord3D(seed, x0, y3, z0), + _fnlValCoord3D(seed, x1, y3, z0), + _fnlValCoord3D(seed, x2, y3, z0), + _fnlValCoord3D(seed, x3, y3, z0), + xs + ), + ys + ), + _fnlCubicLerp( + _fnlCubicLerp( + _fnlValCoord3D(seed, x0, y0, z1), + _fnlValCoord3D(seed, x1, y0, z1), + _fnlValCoord3D(seed, x2, y0, z1), + _fnlValCoord3D(seed, x3, y0, z1), + xs + ), + _fnlCubicLerp( + _fnlValCoord3D(seed, x0, y1, z1), + _fnlValCoord3D(seed, x1, y1, z1), + _fnlValCoord3D(seed, x2, y1, z1), + _fnlValCoord3D(seed, x3, y1, z1), + xs + ), + _fnlCubicLerp( + _fnlValCoord3D(seed, x0, y2, z1), + _fnlValCoord3D(seed, x1, y2, z1), + _fnlValCoord3D(seed, x2, y2, z1), + _fnlValCoord3D(seed, x3, y2, z1), + xs + ), + _fnlCubicLerp( + _fnlValCoord3D(seed, x0, y3, z1), + _fnlValCoord3D(seed, x1, y3, z1), + _fnlValCoord3D(seed, x2, y3, z1), + _fnlValCoord3D(seed, x3, y3, z1), + xs + ), + ys + ), + _fnlCubicLerp( + _fnlCubicLerp( + _fnlValCoord3D(seed, x0, y0, z2), + _fnlValCoord3D(seed, x1, y0, z2), + _fnlValCoord3D(seed, x2, y0, z2), + _fnlValCoord3D(seed, x3, y0, z2), + xs + ), + _fnlCubicLerp( + _fnlValCoord3D(seed, x0, y1, z2), + _fnlValCoord3D(seed, x1, y1, z2), + _fnlValCoord3D(seed, x2, y1, z2), + _fnlValCoord3D(seed, x3, y1, z2), + xs + ), + _fnlCubicLerp( + _fnlValCoord3D(seed, x0, y2, z2), + _fnlValCoord3D(seed, x1, y2, z2), + _fnlValCoord3D(seed, x2, y2, z2), + _fnlValCoord3D(seed, x3, y2, z2), + xs + ), + _fnlCubicLerp( + _fnlValCoord3D(seed, x0, y3, z2), + _fnlValCoord3D(seed, x1, y3, z2), + _fnlValCoord3D(seed, x2, y3, z2), + _fnlValCoord3D(seed, x3, y3, z2), + xs + ), + ys + ), + _fnlCubicLerp( + _fnlCubicLerp( + _fnlValCoord3D(seed, x0, y0, z3), + _fnlValCoord3D(seed, x1, y0, z3), + _fnlValCoord3D(seed, x2, y0, z3), + _fnlValCoord3D(seed, x3, y0, z3), + xs + ), + _fnlCubicLerp( + _fnlValCoord3D(seed, x0, y1, z3), + _fnlValCoord3D(seed, x1, y1, z3), + _fnlValCoord3D(seed, x2, y1, z3), + _fnlValCoord3D(seed, x3, y1, z3), + xs + ), + _fnlCubicLerp( + _fnlValCoord3D(seed, x0, y2, z3), + _fnlValCoord3D(seed, x1, y2, z3), + _fnlValCoord3D(seed, x2, y2, z3), + _fnlValCoord3D(seed, x3, y2, z3), + xs + ), + _fnlCubicLerp( + _fnlValCoord3D(seed, x0, y3, z3), + _fnlValCoord3D(seed, x1, y3, z3), + _fnlValCoord3D(seed, x2, y3, z3), + _fnlValCoord3D(seed, x3, y3, z3), + xs + ), + ys + ), + zs + ) * + (1 / 1.5f * 1.5f * 1.5f); } // Value noise -static float _fnlSingleValue2D(int seed, FNLfloat x, FNLfloat y) -{ +static float _fnlSingleValue2D(int seed, FNLfloat x, FNLfloat y) { int x0 = _fnlFastFloor(x); int y0 = _fnlFastFloor(y); @@ -1833,14 +2462,17 @@ static float _fnlSingleValue2D(int seed, FNLfloat x, FNLfloat y) int x1 = x0 + PRIME_X; int y1 = y0 + PRIME_Y; - float xf0 = _fnlLerp(_fnlValCoord2D(seed, x0, y0), _fnlValCoord2D(seed, x1, y0), xs); - float xf1 = _fnlLerp(_fnlValCoord2D(seed, x0, y1), _fnlValCoord2D(seed, x1, y1), xs); + float xf0 = _fnlLerp( + _fnlValCoord2D(seed, x0, y0), _fnlValCoord2D(seed, x1, y0), xs + ); + float xf1 = _fnlLerp( + _fnlValCoord2D(seed, x0, y1), _fnlValCoord2D(seed, x1, y1), xs + ); return _fnlLerp(xf0, xf1, ys); } -static float _fnlSingleValue3D(int seed, FNLfloat x, FNLfloat y, FNLfloat z) -{ +static float _fnlSingleValue3D(int seed, FNLfloat x, FNLfloat y, FNLfloat z) { int x0 = _fnlFastFloor(x); int y0 = _fnlFastFloor(y); int z0 = _fnlFastFloor(z); @@ -1856,10 +2488,18 @@ static float _fnlSingleValue3D(int seed, FNLfloat x, FNLfloat y, FNLfloat z) int y1 = y0 + PRIME_Y; int z1 = z0 + PRIME_Z; - float xf00 = _fnlLerp(_fnlValCoord3D(seed, x0, y0, z0), _fnlValCoord3D(seed, x1, y0, z0), xs); - float xf10 = _fnlLerp(_fnlValCoord3D(seed, x0, y1, z0), _fnlValCoord3D(seed, x1, y1, z0), xs); - float xf01 = _fnlLerp(_fnlValCoord3D(seed, x0, y0, z1), _fnlValCoord3D(seed, x1, y0, z1), xs); - float xf11 = _fnlLerp(_fnlValCoord3D(seed, x0, y1, z1), _fnlValCoord3D(seed, x1, y1, z1), xs); + float xf00 = _fnlLerp( + _fnlValCoord3D(seed, x0, y0, z0), _fnlValCoord3D(seed, x1, y0, z0), xs + ); + float xf10 = _fnlLerp( + _fnlValCoord3D(seed, x0, y1, z0), _fnlValCoord3D(seed, x1, y1, z0), xs + ); + float xf01 = _fnlLerp( + _fnlValCoord3D(seed, x0, y0, z1), _fnlValCoord3D(seed, x1, y0, z1), xs + ); + float xf11 = _fnlLerp( + _fnlValCoord3D(seed, x0, y1, z1), _fnlValCoord3D(seed, x1, y1, z1), xs + ); float yf0 = _fnlLerp(xf00, xf10, ys); float yf1 = _fnlLerp(xf01, xf11, ys); @@ -1870,47 +2510,119 @@ static float _fnlSingleValue3D(int seed, FNLfloat x, FNLfloat y, FNLfloat z) // Domain Warp // Forward declare -static void _fnlSingleDomainWarpBasicGrid2D(int seed, float warpAmp, float frequency, FNLfloat x, FNLfloat y, FNLfloat *xp, FNLfloat *yp); -static void _fnlSingleDomainWarpBasicGrid3D(int seed, float warpAmp, float frequency, FNLfloat x, FNLfloat y, FNLfloat z, FNLfloat *xp, FNLfloat *yp, FNLfloat *zp); -static void _fnlSingleDomainWarpSimplexGradient(int seed, float warpAmp, float frequency, FNLfloat x, FNLfloat y, FNLfloat *xr, FNLfloat *yr, bool outGradOnly); -static void _fnlSingleDomainWarpOpenSimplex2Gradient(int seed, float warpAmp, float frequency, FNLfloat x, FNLfloat y, FNLfloat z, FNLfloat *xr, FNLfloat *yr, FNLfloat *zr, bool outGradOnly); +static void _fnlSingleDomainWarpBasicGrid2D( + int seed, + float warpAmp, + float frequency, + FNLfloat x, + FNLfloat y, + FNLfloat *xp, + FNLfloat *yp +); +static void _fnlSingleDomainWarpBasicGrid3D( + int seed, + float warpAmp, + float frequency, + FNLfloat x, + FNLfloat y, + FNLfloat z, + FNLfloat *xp, + FNLfloat *yp, + FNLfloat *zp +); +static void _fnlSingleDomainWarpSimplexGradient( + int seed, + float warpAmp, + float frequency, + FNLfloat x, + FNLfloat y, + FNLfloat *xr, + FNLfloat *yr, + bool outGradOnly +); +static void _fnlSingleDomainWarpOpenSimplex2Gradient( + int seed, + float warpAmp, + float frequency, + FNLfloat x, + FNLfloat y, + FNLfloat z, + FNLfloat *xr, + FNLfloat *yr, + FNLfloat *zr, + bool outGradOnly +); -static inline void _fnlDoSingleDomainWarp2D(fnl_state *state, int seed, float amp, float freq, FNLfloat x, FNLfloat y, FNLfloat *xp, FNLfloat *yp) -{ - switch (state->domain_warp_type) - { - case FNL_DOMAIN_WARP_OPENSIMPLEX2: - _fnlSingleDomainWarpSimplexGradient(seed, amp * 38.283687591552734375f, freq, x, y, xp, yp, false); - break; - case FNL_DOMAIN_WARP_OPENSIMPLEX2_REDUCED: - _fnlSingleDomainWarpSimplexGradient(seed, amp * 16.0f, freq, x, y, xp, yp, true); - break; - case FNL_DOMAIN_WARP_BASICGRID: - _fnlSingleDomainWarpBasicGrid2D(seed, amp, freq, x, y, xp, yp); - break; +static inline void _fnlDoSingleDomainWarp2D( + fnl_state *state, + int seed, + float amp, + float freq, + FNLfloat x, + FNLfloat y, + FNLfloat *xp, + FNLfloat *yp +) { + switch (state->domain_warp_type) { + case FNL_DOMAIN_WARP_OPENSIMPLEX2: + _fnlSingleDomainWarpSimplexGradient( + seed, amp * 38.283687591552734375f, freq, x, y, xp, yp, false + ); + break; + case FNL_DOMAIN_WARP_OPENSIMPLEX2_REDUCED: + _fnlSingleDomainWarpSimplexGradient( + seed, amp * 16.0f, freq, x, y, xp, yp, true + ); + break; + case FNL_DOMAIN_WARP_BASICGRID: + _fnlSingleDomainWarpBasicGrid2D(seed, amp, freq, x, y, xp, yp); + break; } } -static inline void _fnlDoSingleDomainWarp3D(fnl_state *state, int seed, float amp, float freq, FNLfloat x, FNLfloat y, FNLfloat z, FNLfloat *xp, FNLfloat *yp, FNLfloat *zp) -{ - switch (state->domain_warp_type) - { - case FNL_DOMAIN_WARP_OPENSIMPLEX2: - _fnlSingleDomainWarpOpenSimplex2Gradient(seed, amp * 32.69428253173828125f, freq, x, y, z, xp, yp, zp, false); - break; - case FNL_DOMAIN_WARP_OPENSIMPLEX2_REDUCED: - _fnlSingleDomainWarpOpenSimplex2Gradient(seed, amp * 7.71604938271605f, freq, x, y, z, xp, yp, zp, true); - break; - case FNL_DOMAIN_WARP_BASICGRID: - _fnlSingleDomainWarpBasicGrid3D(seed, amp, freq, x, y, z, xp, yp, zp); - break; +static inline void _fnlDoSingleDomainWarp3D( + fnl_state *state, + int seed, + float amp, + float freq, + FNLfloat x, + FNLfloat y, + FNLfloat z, + FNLfloat *xp, + FNLfloat *yp, + FNLfloat *zp +) { + switch (state->domain_warp_type) { + case FNL_DOMAIN_WARP_OPENSIMPLEX2: + _fnlSingleDomainWarpOpenSimplex2Gradient( + seed, + amp * 32.69428253173828125f, + freq, + x, + y, + z, + xp, + yp, + zp, + false + ); + break; + case FNL_DOMAIN_WARP_OPENSIMPLEX2_REDUCED: + _fnlSingleDomainWarpOpenSimplex2Gradient( + seed, amp * 7.71604938271605f, freq, x, y, z, xp, yp, zp, true + ); + break; + case FNL_DOMAIN_WARP_BASICGRID: + _fnlSingleDomainWarpBasicGrid3D( + seed, amp, freq, x, y, z, xp, yp, zp + ); + break; } } // Domain Warp Single Wrapper -static void _fnlDomainWarpSingle2D(fnl_state *state, FNLfloat *x, FNLfloat *y) -{ +static void _fnlDomainWarpSingle2D(fnl_state *state, FNLfloat *x, FNLfloat *y) { int seed = state->seed; float amp = state->domain_warp_amp * _fnlCalculateFractalBounding(state); float freq = state->frequency; @@ -1922,8 +2634,9 @@ static void _fnlDomainWarpSingle2D(fnl_state *state, FNLfloat *x, FNLfloat *y) _fnlDoSingleDomainWarp2D(state, seed, amp, freq, xs, ys, x, y); } -static void _fnlDomainWarpSingle3D(fnl_state *state, FNLfloat *x, FNLfloat *y, FNLfloat *z) -{ +static void _fnlDomainWarpSingle3D( + fnl_state *state, FNLfloat *x, FNLfloat *y, FNLfloat *z +) { int seed = state->seed; float amp = state->domain_warp_amp * _fnlCalculateFractalBounding(state); float freq = state->frequency; @@ -1938,14 +2651,14 @@ static void _fnlDomainWarpSingle3D(fnl_state *state, FNLfloat *x, FNLfloat *y, F // Domain Warp Fractal Progressive -static void _fnlDomainWarpFractalProgressive2D(fnl_state *state, FNLfloat *x, FNLfloat *y) -{ +static void _fnlDomainWarpFractalProgressive2D( + fnl_state *state, FNLfloat *x, FNLfloat *y +) { int seed = state->seed; float amp = state->domain_warp_amp * _fnlCalculateFractalBounding(state); float freq = state->frequency; - for (int i = 0; i < state->octaves; i++) - { + for (int i = 0; i < state->octaves; i++) { FNLfloat xs = *x; FNLfloat ys = *y; _fnlTransformDomainWarpCoordinate2D(state, &xs, &ys); @@ -1958,14 +2671,14 @@ static void _fnlDomainWarpFractalProgressive2D(fnl_state *state, FNLfloat *x, FN } } -static void _fnlDomainWarpFractalProgressive3D(fnl_state *state, FNLfloat *x, FNLfloat *y, FNLfloat *z) -{ +static void _fnlDomainWarpFractalProgressive3D( + fnl_state *state, FNLfloat *x, FNLfloat *y, FNLfloat *z +) { int seed = state->seed; float amp = state->domain_warp_amp * _fnlCalculateFractalBounding(state); float freq = state->frequency; - for (int i = 0; i < state->octaves; i++) - { + for (int i = 0; i < state->octaves; i++) { FNLfloat xs = *x; FNLfloat ys = *y; FNLfloat zs = *z; @@ -1981,8 +2694,9 @@ static void _fnlDomainWarpFractalProgressive3D(fnl_state *state, FNLfloat *x, FN // Domain Warp Fractal Independent -static void _fnlDomainWarpFractalIndependent2D(fnl_state *state, FNLfloat *x, FNLfloat *y) -{ +static void _fnlDomainWarpFractalIndependent2D( + fnl_state *state, FNLfloat *x, FNLfloat *y +) { FNLfloat xs = *x; FNLfloat ys = *y; _fnlTransformDomainWarpCoordinate2D(state, &xs, &ys); @@ -1991,8 +2705,7 @@ static void _fnlDomainWarpFractalIndependent2D(fnl_state *state, FNLfloat *x, FN float amp = state->domain_warp_amp * _fnlCalculateFractalBounding(state); float freq = state->frequency; - for (int i = 0; i < state->octaves; i++) - { + for (int i = 0; i < state->octaves; i++) { _fnlDoSingleDomainWarp2D(state, seed, amp, freq, xs, ys, x, y); seed++; @@ -2001,8 +2714,9 @@ static void _fnlDomainWarpFractalIndependent2D(fnl_state *state, FNLfloat *x, FN } } -static void _fnlDomainWarpFractalIndependent3D(fnl_state *state, FNLfloat *x, FNLfloat *y, FNLfloat *z) -{ +static void _fnlDomainWarpFractalIndependent3D( + fnl_state *state, FNLfloat *x, FNLfloat *y, FNLfloat *z +) { FNLfloat xs = *x; FNLfloat ys = *y; FNLfloat zs = *z; @@ -2012,8 +2726,7 @@ static void _fnlDomainWarpFractalIndependent3D(fnl_state *state, FNLfloat *x, FN float amp = state->domain_warp_amp * _fnlCalculateFractalBounding(state); float freq = state->frequency; - for (int i = 0; i < state->octaves; i++) - { + for (int i = 0; i < state->octaves; i++) { _fnlDoSingleDomainWarp3D(state, seed, amp, freq, xs, ys, zs, x, y, z); seed++; @@ -2024,8 +2737,15 @@ static void _fnlDomainWarpFractalIndependent3D(fnl_state *state, FNLfloat *x, FN // Domain Warp Basic Grid -static void _fnlSingleDomainWarpBasicGrid2D(int seed, float warpAmp, float frequency, FNLfloat x, FNLfloat y, FNLfloat *xp, FNLfloat *yp) -{ +static void _fnlSingleDomainWarpBasicGrid2D( + int seed, + float warpAmp, + float frequency, + FNLfloat x, + FNLfloat y, + FNLfloat *xp, + FNLfloat *yp +) { FNLfloat xf = x * frequency; FNLfloat yf = y * frequency; @@ -2056,8 +2776,17 @@ static void _fnlSingleDomainWarpBasicGrid2D(int seed, float warpAmp, float frequ *yp += _fnlLerp(ly0x, ly1x, ys) * warpAmp; } -static void _fnlSingleDomainWarpBasicGrid3D(int seed, float warpAmp, float frequency, FNLfloat x, FNLfloat y, FNLfloat z, FNLfloat *xp, FNLfloat *yp, FNLfloat *zp) -{ +static void _fnlSingleDomainWarpBasicGrid3D( + int seed, + float warpAmp, + float frequency, + FNLfloat x, + FNLfloat y, + FNLfloat z, + FNLfloat *xp, + FNLfloat *yp, + FNLfloat *zp +) { FNLfloat xf = x * frequency; FNLfloat yf = y * frequency; FNLfloat zf = z * frequency; @@ -2116,8 +2845,16 @@ static void _fnlSingleDomainWarpBasicGrid3D(int seed, float warpAmp, float frequ // Domain Warp Simplex/OpenSimplex2 -static void _fnlSingleDomainWarpSimplexGradient(int seed, float warpAmp, float frequency, FNLfloat x, FNLfloat y, FNLfloat *xr, FNLfloat *yr, bool outGradOnly) -{ +static void _fnlSingleDomainWarpSimplexGradient( + int seed, + float warpAmp, + float frequency, + FNLfloat x, + FNLfloat y, + FNLfloat *xr, + FNLfloat *yr, + bool outGradOnly +) { const float SQRT3 = 1.7320508075688772935274463415059f; const float G2 = (3 - SQRT3) / 6; @@ -2147,8 +2884,7 @@ static void _fnlSingleDomainWarpSimplexGradient(int seed, float warpAmp, float f vx = vy = 0; float a = 0.5f - x0 * x0 - y0 * y0; - if (a > 0) - { + if (a > 0) { float aaaa = (a * a) * (a * a); float xo, yo; if (outGradOnly) @@ -2159,9 +2895,9 @@ static void _fnlSingleDomainWarpSimplexGradient(int seed, float warpAmp, float f vy += aaaa * yo; } - float c = (float)(2 * (1 - 2 * G2) * (1 / G2 - 2)) * t + ((float)(-2 * (1 - 2 * G2) * (1 - 2 * G2)) + a); - if (c > 0) - { + float c = (float)(2 * (1 - 2 * G2) * (1 / G2 - 2)) * t + + ((float)(-2 * (1 - 2 * G2) * (1 - 2 * G2)) + a); + if (c > 0) { float x2 = x0 + (2 * (float)G2 - 1); float y2 = y0 + (2 * (float)G2 - 1); float cccc = (c * c) * (c * c); @@ -2169,18 +2905,18 @@ static void _fnlSingleDomainWarpSimplexGradient(int seed, float warpAmp, float f if (outGradOnly) _fnlGradCoordOut2D(seed, i + PRIME_X, j + PRIME_Y, &xo, &yo); else - _fnlGradCoordDual2D(seed, i + PRIME_X, j + PRIME_Y, x2, y2, &xo, &yo); + _fnlGradCoordDual2D( + seed, i + PRIME_X, j + PRIME_Y, x2, y2, &xo, &yo + ); vx += cccc * xo; vy += cccc * yo; } - if (y0 > x0) - { + if (y0 > x0) { float x1 = x0 + (float)G2; float y1 = y0 + ((float)G2 - 1); float b = 0.5f - x1 * x1 - y1 * y1; - if (b > 0) - { + if (b > 0) { float bbbb = (b * b) * (b * b); float xo, yo; if (outGradOnly) @@ -2190,14 +2926,11 @@ static void _fnlSingleDomainWarpSimplexGradient(int seed, float warpAmp, float f vx += bbbb * xo; vy += bbbb * yo; } - } - else - { + } else { float x1 = x0 + ((float)G2 - 1); float y1 = y0 + (float)G2; float b = 0.5f - x1 * x1 - y1 * y1; - if (b > 0) - { + if (b > 0) { float bbbb = (b * b) * (b * b); float xo, yo; if (outGradOnly) @@ -2213,8 +2946,18 @@ static void _fnlSingleDomainWarpSimplexGradient(int seed, float warpAmp, float f *yr += vy * warpAmp; } -static void _fnlSingleDomainWarpOpenSimplex2Gradient(int seed, float warpAmp, float frequency, FNLfloat x, FNLfloat y, FNLfloat z, FNLfloat *xr, FNLfloat *yr, FNLfloat *zr, bool outGradOnly) -{ +static void _fnlSingleDomainWarpOpenSimplex2Gradient( + int seed, + float warpAmp, + float frequency, + FNLfloat x, + FNLfloat y, + FNLfloat z, + FNLfloat *xr, + FNLfloat *yr, + FNLfloat *zr, + bool outGradOnly +) { x *= frequency; y *= frequency; z *= frequency; @@ -2249,10 +2992,8 @@ static void _fnlSingleDomainWarpOpenSimplex2Gradient(int seed, float warpAmp, fl vx = vy = vz = 0; float a = (0.6f - x0 * x0) - (y0 * y0 + z0 * z0); - for (int l = 0; l < 2; l++) - { - if (a > 0) - { + for (int l = 0; l < 2; l++) { + if (a > 0) { float aaaa = (a * a) * (a * a); float xo, yo, zo; if (outGradOnly) @@ -2271,40 +3012,35 @@ static void _fnlSingleDomainWarpOpenSimplex2Gradient(int seed, float warpAmp, fl float x1 = x0; float y1 = y0; float z1 = z0; - if (ax0 >= ay0 && ax0 >= az0) - { + if (ax0 >= ay0 && ax0 >= az0) { x1 += xNSign; b -= xNSign * 2 * x1; i1 -= xNSign * PRIME_X; - } - else if (ay0 > ax0 && ay0 >= az0) - { + } else if (ay0 > ax0 && ay0 >= az0) { y1 += yNSign; b -= yNSign * 2 * y1; j1 -= yNSign * PRIME_Y; - } - else - { + } else { z1 += zNSign; b -= zNSign * 2 * z1; k1 -= zNSign * PRIME_Z; } - if (b > 0) - { + if (b > 0) { float bbbb = (b * b) * (b * b); float xo, yo, zo; if (outGradOnly) _fnlGradCoordOut3D(seed, i1, j1, k1, &xo, &yo, &zo); else - _fnlGradCoordDual3D(seed, i1, j1, k1, x1, y1, z1, &xo, &yo, &zo); + _fnlGradCoordDual3D( + seed, i1, j1, k1, x1, y1, z1, &xo, &yo, &zo + ); vx += bbbb * xo; vy += bbbb * yo; vz += bbbb * zo; } - if (l == 1) - break; + if (l == 1) break; ax0 = 0.5f - ax0; ay0 = 0.5f - ay0; @@ -2336,8 +3072,7 @@ static void _fnlSingleDomainWarpOpenSimplex2Gradient(int seed, float warpAmp, fl // Public API // ==================== -fnl_state fnlCreateState() -{ +fnl_state fnlCreateState() { fnl_state newState; newState.seed = 1337; newState.frequency = 0.01f; @@ -2357,77 +3092,69 @@ fnl_state fnlCreateState() return newState; } -float fnlGetNoise2D(fnl_state *state, FNLfloat x, FNLfloat y) -{ +float fnlGetNoise2D(fnl_state *state, FNLfloat x, FNLfloat y) { _fnlTransformNoiseCoordinate2D(state, &x, &y); - switch (state->fractal_type) - { - default: - return _fnlGenNoiseSingle2D(state, state->seed, x, y); - case FNL_FRACTAL_FBM: - return _fnlGenFractalFBM2D(state, x, y); - case FNL_FRACTAL_RIDGED: - return _fnlGenFractalRidged2D(state, x, y); - case FNL_FRACTAL_PINGPONG: - return _fnlGenFractalPingPong2D(state, x, y); + switch (state->fractal_type) { + default: + return _fnlGenNoiseSingle2D(state, state->seed, x, y); + case FNL_FRACTAL_FBM: + return _fnlGenFractalFBM2D(state, x, y); + case FNL_FRACTAL_RIDGED: + return _fnlGenFractalRidged2D(state, x, y); + case FNL_FRACTAL_PINGPONG: + return _fnlGenFractalPingPong2D(state, x, y); } } -float fnlGetNoise3D(fnl_state *state, FNLfloat x, FNLfloat y, FNLfloat z) -{ +float fnlGetNoise3D(fnl_state *state, FNLfloat x, FNLfloat y, FNLfloat z) { _fnlTransformNoiseCoordinate3D(state, &x, &y, &z); // Select a noise type - switch (state->fractal_type) - { - default: - return _fnlGenNoiseSingle3D(state, state->seed, x, y, z); - case FNL_FRACTAL_FBM: - return _fnlGenFractalFBM3D(state, x, y, z); - case FNL_FRACTAL_RIDGED: - return _fnlGenFractalRidged3D(state, x, y, z); - case FNL_FRACTAL_PINGPONG: - return _fnlGenFractalPingPong3D(state, x, y, z); + switch (state->fractal_type) { + default: + return _fnlGenNoiseSingle3D(state, state->seed, x, y, z); + case FNL_FRACTAL_FBM: + return _fnlGenFractalFBM3D(state, x, y, z); + case FNL_FRACTAL_RIDGED: + return _fnlGenFractalRidged3D(state, x, y, z); + case FNL_FRACTAL_PINGPONG: + return _fnlGenFractalPingPong3D(state, x, y, z); } } -void fnlDomainWarp2D(fnl_state *state, FNLfloat *x, FNLfloat *y) -{ - switch (state->fractal_type) - { - default: - _fnlDomainWarpSingle2D(state, x, y); - break; - case FNL_FRACTAL_DOMAIN_WARP_PROGRESSIVE: - _fnlDomainWarpFractalProgressive2D(state, x, y); - break; - case FNL_FRACTAL_DOMAIN_WARP_INDEPENDENT: - _fnlDomainWarpFractalIndependent2D(state, x, y); - break; +void fnlDomainWarp2D(fnl_state *state, FNLfloat *x, FNLfloat *y) { + switch (state->fractal_type) { + default: + _fnlDomainWarpSingle2D(state, x, y); + break; + case FNL_FRACTAL_DOMAIN_WARP_PROGRESSIVE: + _fnlDomainWarpFractalProgressive2D(state, x, y); + break; + case FNL_FRACTAL_DOMAIN_WARP_INDEPENDENT: + _fnlDomainWarpFractalIndependent2D(state, x, y); + break; } } -void fnlDomainWarp3D(fnl_state *state, FNLfloat *x, FNLfloat *y, FNLfloat *z) -{ - switch (state->fractal_type) - { - default: - _fnlDomainWarpSingle3D(state, x, y, z); - break; - case FNL_FRACTAL_DOMAIN_WARP_PROGRESSIVE: - _fnlDomainWarpFractalProgressive3D(state, x, y, z); - break; - case FNL_FRACTAL_DOMAIN_WARP_INDEPENDENT: - _fnlDomainWarpFractalIndependent3D(state, x, y, z); - break; +void fnlDomainWarp3D(fnl_state *state, FNLfloat *x, FNLfloat *y, FNLfloat *z) { + switch (state->fractal_type) { + default: + _fnlDomainWarpSingle3D(state, x, y, z); + break; + case FNL_FRACTAL_DOMAIN_WARP_PROGRESSIVE: + _fnlDomainWarpFractalProgressive3D(state, x, y, z); + break; + case FNL_FRACTAL_DOMAIN_WARP_INDEPENDENT: + _fnlDomainWarpFractalIndependent3D(state, x, y, z); + break; } } -#endif // FNL_IMPL +#endif // FNL_IMPL #if defined(__cplusplus) } #endif -#endif // FASTNOISELITE_H +#endif // FASTNOISELITE_H diff --git a/src/maths/FrustumCulling.hpp b/src/maths/FrustumCulling.hpp index 1f3f3e67..00cd9686 100644 --- a/src/maths/FrustumCulling.hpp +++ b/src/maths/FrustumCulling.hpp @@ -9,7 +9,6 @@ public: void update(glm::mat4 projview); bool isBoxVisible(const glm::vec3& minp, const glm::vec3& maxp) const; - private: enum Planes { Left = 0, @@ -22,16 +21,16 @@ private: Combinations = Count * (Count - 1) / 2 }; - template + template struct ij2k { enum { k = i * (9 - i) / 2 + j - 1 }; }; - template + template glm::vec3 intersection(const glm::vec3* crosses) const; - glm::vec4 m_planes[Count]; - glm::vec3 m_points[8]; + glm::vec4 m_planes[Count]; + glm::vec3 m_points[8]; }; inline void Frustum::update(glm::mat4 m) { @@ -44,22 +43,21 @@ inline void Frustum::update(glm::mat4 m) { m_planes[Far] = m[3] - m[2]; glm::vec3 crosses[Combinations] = { - glm::cross(glm::vec3(m_planes[Left]), glm::vec3(m_planes[Right])), - glm::cross(glm::vec3(m_planes[Left]), glm::vec3(m_planes[Bottom])), - glm::cross(glm::vec3(m_planes[Left]), glm::vec3(m_planes[Top])), - glm::cross(glm::vec3(m_planes[Left]), glm::vec3(m_planes[Near])), - glm::cross(glm::vec3(m_planes[Left]), glm::vec3(m_planes[Far])), - glm::cross(glm::vec3(m_planes[Right]), glm::vec3(m_planes[Bottom])), - glm::cross(glm::vec3(m_planes[Right]), glm::vec3(m_planes[Top])), - glm::cross(glm::vec3(m_planes[Right]), glm::vec3(m_planes[Near])), - glm::cross(glm::vec3(m_planes[Right]), glm::vec3(m_planes[Far])), + glm::cross(glm::vec3(m_planes[Left]), glm::vec3(m_planes[Right])), + glm::cross(glm::vec3(m_planes[Left]), glm::vec3(m_planes[Bottom])), + glm::cross(glm::vec3(m_planes[Left]), glm::vec3(m_planes[Top])), + glm::cross(glm::vec3(m_planes[Left]), glm::vec3(m_planes[Near])), + glm::cross(glm::vec3(m_planes[Left]), glm::vec3(m_planes[Far])), + glm::cross(glm::vec3(m_planes[Right]), glm::vec3(m_planes[Bottom])), + glm::cross(glm::vec3(m_planes[Right]), glm::vec3(m_planes[Top])), + glm::cross(glm::vec3(m_planes[Right]), glm::vec3(m_planes[Near])), + glm::cross(glm::vec3(m_planes[Right]), glm::vec3(m_planes[Far])), glm::cross(glm::vec3(m_planes[Bottom]), glm::vec3(m_planes[Top])), glm::cross(glm::vec3(m_planes[Bottom]), glm::vec3(m_planes[Near])), glm::cross(glm::vec3(m_planes[Bottom]), glm::vec3(m_planes[Far])), - glm::cross(glm::vec3(m_planes[Top]), glm::vec3(m_planes[Near])), - glm::cross(glm::vec3(m_planes[Top]), glm::vec3(m_planes[Far])), - glm::cross(glm::vec3(m_planes[Near]), glm::vec3(m_planes[Far])) - }; + glm::cross(glm::vec3(m_planes[Top]), glm::vec3(m_planes[Near])), + glm::cross(glm::vec3(m_planes[Top]), glm::vec3(m_planes[Far])), + glm::cross(glm::vec3(m_planes[Near]), glm::vec3(m_planes[Far]))}; m_points[0] = intersection(crosses); m_points[1] = intersection(crosses); @@ -69,43 +67,66 @@ inline void Frustum::update(glm::mat4 m) { m_points[5] = intersection(crosses); m_points[6] = intersection(crosses); m_points[7] = intersection(crosses); - } -inline bool Frustum::isBoxVisible(const glm::vec3& minp, const glm::vec3& maxp) const { +inline bool Frustum::isBoxVisible(const glm::vec3& minp, const glm::vec3& maxp) + const { // check box outside/inside of frustum for (int i = 0; i < Count; i++) { - if ((glm::dot(m_planes[i], glm::vec4(minp.x, minp.y, minp.z, 1.0f)) < 0.0) && - (glm::dot(m_planes[i], glm::vec4(maxp.x, minp.y, minp.z, 1.0f)) < 0.0) && - (glm::dot(m_planes[i], glm::vec4(minp.x, maxp.y, minp.z, 1.0f)) < 0.0) && - (glm::dot(m_planes[i], glm::vec4(maxp.x, maxp.y, minp.z, 1.0f)) < 0.0) && - (glm::dot(m_planes[i], glm::vec4(minp.x, minp.y, maxp.z, 1.0f)) < 0.0) && - (glm::dot(m_planes[i], glm::vec4(maxp.x, minp.y, maxp.z, 1.0f)) < 0.0) && - (glm::dot(m_planes[i], glm::vec4(minp.x, maxp.y, maxp.z, 1.0f)) < 0.0) && - (glm::dot(m_planes[i], glm::vec4(maxp.x, maxp.y, maxp.z, 1.0f)) < 0.0)) - { + if ((glm::dot(m_planes[i], glm::vec4(minp.x, minp.y, minp.z, 1.0f)) < + 0.0) && + (glm::dot(m_planes[i], glm::vec4(maxp.x, minp.y, minp.z, 1.0f)) < + 0.0) && + (glm::dot(m_planes[i], glm::vec4(minp.x, maxp.y, minp.z, 1.0f)) < + 0.0) && + (glm::dot(m_planes[i], glm::vec4(maxp.x, maxp.y, minp.z, 1.0f)) < + 0.0) && + (glm::dot(m_planes[i], glm::vec4(minp.x, minp.y, maxp.z, 1.0f)) < + 0.0) && + (glm::dot(m_planes[i], glm::vec4(maxp.x, minp.y, maxp.z, 1.0f)) < + 0.0) && + (glm::dot(m_planes[i], glm::vec4(minp.x, maxp.y, maxp.z, 1.0f)) < + 0.0) && + (glm::dot(m_planes[i], glm::vec4(maxp.x, maxp.y, maxp.z, 1.0f)) < + 0.0)) { return false; } } // check frustum outside/inside box int out; - out = 0; for (int i = 0; i < 8; i++) out += ((m_points[i].x > maxp.x) ? 1 : 0); if (out == 8) return false; - out = 0; for (int i = 0; i < 8; i++) out += ((m_points[i].x < minp.x) ? 1 : 0); if (out == 8) return false; - out = 0; for (int i = 0; i < 8; i++) out += ((m_points[i].y > maxp.y) ? 1 : 0); if (out == 8) return false; - out = 0; for (int i = 0; i < 8; i++) out += ((m_points[i].y < minp.y) ? 1 : 0); if (out == 8) return false; - out = 0; for (int i = 0; i < 8; i++) out += ((m_points[i].z > maxp.z) ? 1 : 0); if (out == 8) return false; - out = 0; for (int i = 0; i < 8; i++) out += ((m_points[i].z < minp.z) ? 1 : 0); if (out == 8) return false; + out = 0; + for (int i = 0; i < 8; i++) out += ((m_points[i].x > maxp.x) ? 1 : 0); + if (out == 8) return false; + out = 0; + for (int i = 0; i < 8; i++) out += ((m_points[i].x < minp.x) ? 1 : 0); + if (out == 8) return false; + out = 0; + for (int i = 0; i < 8; i++) out += ((m_points[i].y > maxp.y) ? 1 : 0); + if (out == 8) return false; + out = 0; + for (int i = 0; i < 8; i++) out += ((m_points[i].y < minp.y) ? 1 : 0); + if (out == 8) return false; + out = 0; + for (int i = 0; i < 8; i++) out += ((m_points[i].z > maxp.z) ? 1 : 0); + if (out == 8) return false; + out = 0; + for (int i = 0; i < 8; i++) out += ((m_points[i].z < minp.z) ? 1 : 0); + if (out == 8) return false; return true; } -template +template inline glm::vec3 Frustum::intersection(const glm::vec3* crosses) const { float D = glm::dot(glm::vec3(m_planes[a]), crosses[ij2k::k]); - glm::vec3 res = glm::mat3(crosses[ij2k::k], -crosses[ij2k::k], crosses[ij2k::k]) * - glm::vec3(m_planes[a].w, m_planes[b].w, m_planes[c].w); + glm::vec3 res = glm::mat3( + crosses[ij2k::k], + -crosses[ij2k::k], + crosses[ij2k::k] + ) * + glm::vec3(m_planes[a].w, m_planes[b].w, m_planes[c].w); return res * (-1.0f / D); } -#endif // MATHS_FRUSTUM_CULLING_HPP_ +#endif // MATHS_FRUSTUM_CULLING_HPP_ diff --git a/src/maths/LMPacker.cpp b/src/maths/LMPacker.cpp index c0878b8b..bf024a73 100644 --- a/src/maths/LMPacker.cpp +++ b/src/maths/LMPacker.cpp @@ -3,13 +3,12 @@ #include static int get_packer_score(const rectangle& rect) { - if (rect.width * rect.height > 100) - return rect.height * rect.height * 1000; + if (rect.width * rect.height > 100) return rect.height * rect.height * 1000; return (rect.width * rect.height * rect.height); } LMPacker::LMPacker(const uint32_t sizes[], size_t length) { - for (unsigned int i = 0; i < length/2; i++) { + for (unsigned int i = 0; i < length / 2; i++) { rectangle rect(i, 0, 0, (int)sizes[i * 2], (int)sizes[i * 2 + 1]); rects.push_back(rect); } @@ -27,8 +26,13 @@ void LMPacker::cleanup() { placed.clear(); } -bool LMPacker::build(uint32_t width, uint32_t height, - uint16_t extension, uint32_t mbit, uint32_t vstep) { +bool LMPacker::build( + uint32_t width, + uint32_t height, + uint16_t extension, + uint32_t mbit, + uint32_t vstep +) { cleanup(); this->mbit = mbit; this->width = width; @@ -53,7 +57,7 @@ bool LMPacker::build(uint32_t width, uint32_t height, rect.height += extension * 2; if (mpix > 1) { if (rect.width % mpix > 0) { - rect.extX = mpix - (rect.width % mpix); + rect.extX = mpix - (rect.width % mpix); } if (rect.height % mpix > 0) { rect.extY = mpix - (rect.height % mpix); @@ -83,8 +87,8 @@ bool LMPacker::build(uint32_t width, uint32_t height, inline rectangle* find_collision( const LMPacker::matrix_ptr& matrix, int x, int y, int w, int h ) { - for (int row = y; row < y+h; row++) { - for (int col = x; col < x+w; col++) { + for (int row = y; row < y + h; row++) { + for (int col = x; col < x + w; col++) { rectangle* rect = matrix[row][col]; if (rect) { return rect; @@ -94,9 +98,11 @@ inline rectangle* find_collision( return nullptr; } -inline void fill(LMPacker::matrix_ptr& matrix, rectangle* rect, int x, int y, int w, int h) { - for (int row = y; row < y+h; row++) { - for (int col = x; col < x+w; col++) { +inline void fill( + LMPacker::matrix_ptr& matrix, rectangle* rect, int x, int y, int w, int h +) { + for (int row = y; row < y + h; row++) { + for (int col = x; col < x + w; col++) { matrix[row][col] = rect; } } @@ -122,11 +128,11 @@ bool LMPacker::place(rectangle* rectptr, uint32_t vstep) { } else { if (skiplines) { unsigned int lfree = 0; - while (lfree + x < mwidth && !lower[x + lfree] && lfree < rw) { + while (lfree + x < mwidth && !lower[x + lfree] && lfree < rw + ) { lfree++; } - if (lfree >= rw) - skiplines = false; + if (lfree >= rw) skiplines = false; } prect = find_collision(matrix, x, y, rw, rh); if (prect) { @@ -146,4 +152,3 @@ bool LMPacker::place(rectangle* rectptr, uint32_t vstep) { } return false; } - diff --git a/src/maths/LMPacker.hpp b/src/maths/LMPacker.hpp index 4bba767b..5eb86ee7 100644 --- a/src/maths/LMPacker.hpp +++ b/src/maths/LMPacker.hpp @@ -3,10 +3,11 @@ #ifndef LMPACKER_HPP_ #define LMPACKER_HPP_ -#include #include -#include +#include + #include +#include struct rectangle { unsigned int idx; @@ -18,7 +19,7 @@ struct rectangle { int extY = 0; rectangle(unsigned int idx, int x, int y, int width, int height) - : idx(idx), x(x), y(y), width(width), height(height){ + : idx(idx), x(x), y(y), width(width), height(height) { } }; @@ -46,11 +47,17 @@ public: bool buildFast(uint32_t width, uint32_t height, uint16_t extension) { return build(width, height, extension, 1, 2); } - bool build(uint32_t width, uint32_t height, uint16_t extension, uint32_t mbit, uint32_t vstep); + bool build( + uint32_t width, + uint32_t height, + uint16_t extension, + uint32_t mbit, + uint32_t vstep + ); std::vector getResult() { return rects; } }; -#endif // LMPACKER_HPP_ +#endif // LMPACKER_HPP_ diff --git a/src/maths/UVRegion.hpp b/src/maths/UVRegion.hpp index 85833ba4..21f7694e 100644 --- a/src/maths/UVRegion.hpp +++ b/src/maths/UVRegion.hpp @@ -10,17 +10,19 @@ struct UVRegion { float v2; UVRegion(float u1, float v1, float u2, float v2) - : u1(u1), v1(v1), u2(u2), v2(v2){} + : u1(u1), v1(v1), u2(u2), v2(v2) { + } - UVRegion() : u1(0.0f), v1(0.0f), u2(1.0f), v2(1.0f){} + UVRegion() : u1(0.0f), v1(0.0f), u2(1.0f), v2(1.0f) { + } inline float getWidth() const { - return fabs(u2-u1); + return fabs(u2 - u1); } inline float getHeight() const { - return fabs(v2-v1); + return fabs(v2 - v1); } }; -#endif // MATHS_UVREGION_HPP_ +#endif // MATHS_UVREGION_HPP_ diff --git a/src/maths/aabb.hpp b/src/maths/aabb.hpp index 1a86338c..34f97383 100644 --- a/src/maths/aabb.hpp +++ b/src/maths/aabb.hpp @@ -28,11 +28,7 @@ struct AABB { /// @brief Get AABB dimensions: width, height, depth inline glm::vec3 size() const { - return glm::vec3( - fabs(b.x - a.x), - fabs(b.y - a.y), - fabs(b.z - a.z) - ); + return glm::vec3(fabs(b.x - a.x), fabs(b.y - a.y), fabs(b.z - a.z)); } inline glm::vec3 center() const { @@ -59,8 +55,10 @@ struct AABB { inline bool contains(const glm::vec3 pos) const { const glm::vec3 p = min(); const glm::vec3 s = size(); - return !(pos.x < p.x || pos.y < p.y || pos.z < p.z || - pos.x >= p.x+s.x || pos.y >= p.y+s.y || pos.z >= p.z+s.z); + return !( + pos.x < p.x || pos.y < p.y || pos.z < p.z || pos.x >= p.x + s.x || + pos.y >= p.y + s.y || pos.z >= p.z + s.z + ); } void fix() { @@ -92,25 +90,18 @@ struct AABB { inline bool intersect(const AABB& aabb) { return ( - a.x <= aabb.b.x && - b.x >= aabb.a.x && - a.y <= aabb.b.y && - b.y >= aabb.a.y && - a.z <= aabb.b.z && - b.z >= aabb.a.z + a.x <= aabb.b.x && b.x >= aabb.a.x && a.y <= aabb.b.y && + b.y >= aabb.a.y && a.z <= aabb.b.z && b.z >= aabb.a.z ); } inline bool intersect(const AABB& aabb, float margin) { return ( - a.x <= aabb.b.x+margin && - b.x >= aabb.a.x-margin && - a.y <= aabb.b.y+margin && - b.y >= aabb.a.y-margin && - a.z <= aabb.b.z+margin && - b.z >= aabb.a.z-margin + a.x <= aabb.b.x + margin && b.x >= aabb.a.x - margin && + a.y <= aabb.b.y + margin && b.y >= aabb.a.y - margin && + a.z <= aabb.b.z + margin && b.z >= aabb.a.z - margin ); } }; -#endif // MATHS_AABB_HPP_ +#endif // MATHS_AABB_HPP_ diff --git a/src/maths/fastmaths.hpp b/src/maths/fastmaths.hpp index 52895eec..bade0390 100644 --- a/src/maths/fastmaths.hpp +++ b/src/maths/fastmaths.hpp @@ -12,7 +12,7 @@ public: inline int rand() { seed = (214013 * seed + 2531011); - return (seed>>16) & 0x7FFF; + return (seed >> 16) & 0x7FFF; } inline float randFloat() { @@ -20,4 +20,4 @@ public: } }; -#endif // MATHS_FASTMATHS_HPP_ +#endif // MATHS_FASTMATHS_HPP_ diff --git a/src/maths/rays.cpp b/src/maths/rays.cpp index b3bc02f7..d47850ee 100644 --- a/src/maths/rays.cpp +++ b/src/maths/rays.cpp @@ -1,258 +1,288 @@ #include "rays.hpp" -#include "aabb.hpp" +#include "aabb.hpp" #include "glm/glm.hpp" -static const rayvec3 X_AXIS = rayvec3(1,0,0), Y_AXIS = rayvec3(0,1,0), Z_AXIS = rayvec3(0,0,1); +static const rayvec3 X_AXIS = rayvec3(1, 0, 0), Y_AXIS = rayvec3(0, 1, 0), + Z_AXIS = rayvec3(0, 0, 1); -Ray::Ray(const rayvec3& origin, const rayvec3& dir) : origin(origin), dir(dir) {} +Ray::Ray(const rayvec3& origin, const rayvec3& dir) : origin(origin), dir(dir) { +} -//make faces from AABB -AABBFaces::AABBFaces(const rayvec3& parentBoxPos, const AABB& parentBox){ - rayvec3 pbMin = parentBox.min(), // every face is min-point and opposite corner point - pbMax = parentBox.max(), - pbRealPos = parentBoxPos + pbMin; - rayvec2 yzMax = rayvec2(parentBoxPos.y + pbMax.y, parentBoxPos.z + pbMax.z ), - xzMax = rayvec2(parentBoxPos.x + pbMax.x, parentBoxPos.z + pbMax.z ), - xyMax = rayvec2(parentBoxPos.x + pbMax.x, parentBoxPos.y + pbMax.y ); - faces[0] = { parentBoxPos + rayvec3(pbMax.x, pbMin.y, pbMin.z), yzMax }; +// make faces from AABB +AABBFaces::AABBFaces(const rayvec3& parentBoxPos, const AABB& parentBox) { + rayvec3 pbMin = parentBox.min( + ), // every face is min-point and opposite corner point + pbMax = parentBox.max(), pbRealPos = parentBoxPos + pbMin; + rayvec2 yzMax = rayvec2(parentBoxPos.y + pbMax.y, parentBoxPos.z + pbMax.z), + xzMax = rayvec2(parentBoxPos.x + pbMax.x, parentBoxPos.z + pbMax.z), + xyMax = rayvec2(parentBoxPos.x + pbMax.x, parentBoxPos.y + pbMax.y); + faces[0] = {parentBoxPos + rayvec3(pbMax.x, pbMin.y, pbMin.z), yzMax}; faces[1] = {pbRealPos, yzMax}; - faces[2] = { parentBoxPos + rayvec3(pbMin.x, pbMax.y, pbMin.z), xzMax }; + faces[2] = {parentBoxPos + rayvec3(pbMin.x, pbMax.y, pbMin.z), xzMax}; faces[3] = {pbRealPos, xzMax}; - faces[4] = { parentBoxPos + rayvec3(pbMin.x, pbMin.y, pbMax.z), xyMax }; + faces[4] = {parentBoxPos + rayvec3(pbMin.x, pbMin.y, pbMax.z), xyMax}; faces[5] = {pbRealPos, xyMax}; - } -RayRelation Ray::intersectYZFace( - const rayvec3& faceMin, - const rayvec2& faceOppositeCorner, //y and z global coords of opposite corner - glm::ivec3& normal_ret, - scalar_t& distance_ret //sinonym of rayCoef - ){ - if (fabs(glm::dot(dir, X_AXIS)) < 1.0E-8){ //precision +RayRelation Ray::intersectYZFace( + const rayvec3& faceMin, + const rayvec2& + faceOppositeCorner, // y and z global coords of opposite corner + glm::ivec3& normal_ret, + scalar_t& distance_ret // sinonym of rayCoef +) { + if (fabs(glm::dot(dir, X_AXIS)) < 1.0E-8) { // precision return RayRelation::Parallel; } - scalar_t rayCoef = (faceMin.x - origin.x) / (dir.x);// equivalent to distance if dir normalized + scalar_t rayCoef = (faceMin.x - origin.x) / + (dir.x); // equivalent to distance if dir normalized if (rayCoef < 0) return RayRelation::None; - rayvec3 intersectPoint = {faceMin.x, - rayCoef*dir.y + origin.y, - rayCoef*dir.z + origin.z}; + rayvec3 intersectPoint = { + faceMin.x, rayCoef * dir.y + origin.y, rayCoef * dir.z + origin.z}; - if (intersectPoint.y >= faceMin.y - && intersectPoint.y <= faceOppositeCorner[0] - && intersectPoint.z >= faceMin.z - && intersectPoint.z <= faceOppositeCorner[1]){ - distance_ret = rayCoef; // believe that dir normalized - if (dir.x > 0) normal_ret = -X_AXIS; - else normal_ret = X_AXIS; - return RayRelation::Intersect; - } + if (intersectPoint.y >= faceMin.y && + intersectPoint.y <= faceOppositeCorner[0] && + intersectPoint.z >= faceMin.z && + intersectPoint.z <= faceOppositeCorner[1]) { + distance_ret = rayCoef; // believe that dir normalized + if (dir.x > 0) + normal_ret = -X_AXIS; + else + normal_ret = X_AXIS; + return RayRelation::Intersect; + } return RayRelation::None; } RayRelation Ray::intersectXZFace( - const rayvec3& faceMin, - const rayvec2& faceOppositeCorner, //x and z global coords of opposite corner - glm::ivec3& normal_ret, - scalar_t& distance_ret - ){ - if (fabs(glm::dot(dir, Y_AXIS)) < 1.0E-8){ //precision + const rayvec3& faceMin, + const rayvec2& + faceOppositeCorner, // x and z global coords of opposite corner + glm::ivec3& normal_ret, + scalar_t& distance_ret +) { + if (fabs(glm::dot(dir, Y_AXIS)) < 1.0E-8) { // precision return RayRelation::Parallel; } - scalar_t rayCoef = (faceMin.y - origin.y) / (dir.y);// equivalent to distance if dir normalized + scalar_t rayCoef = (faceMin.y - origin.y) / + (dir.y); // equivalent to distance if dir normalized if (rayCoef < 0) return RayRelation::None; - rayvec3 intersectPoint = { rayCoef *dir.x + origin.x, - faceMin.y, - rayCoef*dir.z + origin.z}; + rayvec3 intersectPoint = { + rayCoef * dir.x + origin.x, faceMin.y, rayCoef * dir.z + origin.z}; - if (intersectPoint.x >= faceMin.x //Face-hit check - && intersectPoint.x <= faceOppositeCorner[0] - && intersectPoint.z >= faceMin.z - && intersectPoint.z <= faceOppositeCorner[1] ){ - distance_ret = rayCoef; // believe that dir normalized - if (dir.y > 0) normal_ret = -Y_AXIS; - else normal_ret = Y_AXIS; + if (intersectPoint.x >= faceMin.x // Face-hit check + && intersectPoint.x <= faceOppositeCorner[0] && + intersectPoint.z >= faceMin.z && + intersectPoint.z <= faceOppositeCorner[1]) { + distance_ret = rayCoef; // believe that dir normalized + if (dir.y > 0) + normal_ret = -Y_AXIS; + else + normal_ret = Y_AXIS; return RayRelation::Intersect; - } + } return RayRelation::None; } RayRelation Ray::intersectXYFace( - const rayvec3& faceMin, - const rayvec2& faceOppositeCorner, //x and y global coords of opposite corner - glm::ivec3& normal_ret, - scalar_t& distance_ret - ){ - if (fabs(glm::dot(dir, Z_AXIS)) < 1.0E-8){ //precision + const rayvec3& faceMin, + const rayvec2& + faceOppositeCorner, // x and y global coords of opposite corner + glm::ivec3& normal_ret, + scalar_t& distance_ret +) { + if (fabs(glm::dot(dir, Z_AXIS)) < 1.0E-8) { // precision return RayRelation::Parallel; } - - scalar_t rayCoef = (faceMin.z - origin.z) / (dir.z); // equivalent to distance if dir normalized + + scalar_t rayCoef = (faceMin.z - origin.z) / + (dir.z); // equivalent to distance if dir normalized if (rayCoef < 0) return RayRelation::None; - rayvec3 intersectPoint = { rayCoef *dir.x + origin.x, - rayCoef*dir.y + origin.y, - faceMin.z}; - - if (intersectPoint.x >= faceMin.x //Face-hit check - && intersectPoint.x <= faceOppositeCorner[0] - && intersectPoint.y >= faceMin.y - && intersectPoint.y <= faceOppositeCorner[1] ){ - distance_ret = rayCoef; // believe that dir normalized - if (dir.z > 0) normal_ret = -Z_AXIS; - else normal_ret = Z_AXIS; + rayvec3 intersectPoint = { + rayCoef * dir.x + origin.x, rayCoef * dir.y + origin.y, faceMin.z}; + + if (intersectPoint.x >= faceMin.x // Face-hit check + && intersectPoint.x <= faceOppositeCorner[0] && + intersectPoint.y >= faceMin.y && + intersectPoint.y <= faceOppositeCorner[1]) { + distance_ret = rayCoef; // believe that dir normalized + if (dir.z > 0) + normal_ret = -Z_AXIS; + else + normal_ret = Z_AXIS; return RayRelation::Intersect; } return RayRelation::None; } RayRelation Ray::isIntersectsYZFace( - const rayvec3& faceMin, - const rayvec2& faceOppositeCorner - ){ - if (fabs(glm::dot(dir, X_AXIS)) < 1.0E-8) { //precision of "parallelity" + const rayvec3& faceMin, const rayvec2& faceOppositeCorner +) { + if (fabs(glm::dot(dir, X_AXIS)) < 1.0E-8) { // precision of "parallelity" return RayRelation::Parallel; } scalar_t rayCoef = (faceMin.x - origin.x) / (dir.x); if (rayCoef < 0) return RayRelation::None; - rayvec3 intersectPoint = { faceMin.x, - rayCoef * dir.y + origin.y, - rayCoef * dir.z + origin.z }; + rayvec3 intersectPoint = { + faceMin.x, rayCoef * dir.y + origin.y, rayCoef * dir.z + origin.z}; - if (intersectPoint.y >= faceMin.y - && intersectPoint.y <= faceOppositeCorner[0] - && intersectPoint.z >= faceMin.z - && intersectPoint.z <= faceOppositeCorner[1]) { + if (intersectPoint.y >= faceMin.y && + intersectPoint.y <= faceOppositeCorner[0] && + intersectPoint.z >= faceMin.z && + intersectPoint.z <= faceOppositeCorner[1]) { return RayRelation::Intersect; } return RayRelation::None; } RayRelation Ray::isIntersectsXZFace( - const rayvec3& faceMin, - const rayvec2& faceOppositeCorner - ) { - if (fabs(glm::dot(dir, Y_AXIS)) < 1.0E-8) { //precision of "parallelity" + const rayvec3& faceMin, const rayvec2& faceOppositeCorner +) { + if (fabs(glm::dot(dir, Y_AXIS)) < 1.0E-8) { // precision of "parallelity" return RayRelation::Parallel; } scalar_t rayCoef = (faceMin.y - origin.y) / (dir.y); if (rayCoef < 0) return RayRelation::None; - rayvec3 intersectPoint = { rayCoef * dir.x + origin.x, - faceMin.y, - rayCoef * dir.z + origin.z }; + rayvec3 intersectPoint = { + rayCoef * dir.x + origin.x, faceMin.y, rayCoef * dir.z + origin.z}; - if (intersectPoint.x >= faceMin.x //Face-hit check - && intersectPoint.x <= faceOppositeCorner[0] - && intersectPoint.z >= faceMin.z - && intersectPoint.z <= faceOppositeCorner[1]) { + if (intersectPoint.x >= faceMin.x // Face-hit check + && intersectPoint.x <= faceOppositeCorner[0] && + intersectPoint.z >= faceMin.z && + intersectPoint.z <= faceOppositeCorner[1]) { return RayRelation::Intersect; } return RayRelation::None; } RayRelation Ray::isIntersectsXYFace( - const rayvec3& faceMin, - const rayvec2& faceOppositeCorner - ) { - if (fabs(glm::dot(dir, Z_AXIS)) < 1.0E-8) { //precision of "parallelity" + const rayvec3& faceMin, const rayvec2& faceOppositeCorner +) { + if (fabs(glm::dot(dir, Z_AXIS)) < 1.0E-8) { // precision of "parallelity" return RayRelation::Parallel; } scalar_t rayCoef = (faceMin.z - origin.z) / (dir.z); if (rayCoef < 0) return RayRelation::None; - rayvec3 intersectPoint = { rayCoef * dir.x + origin.x, - rayCoef * dir.y + origin.y, - faceMin.z }; + rayvec3 intersectPoint = { + rayCoef * dir.x + origin.x, rayCoef * dir.y + origin.y, faceMin.z}; - if (intersectPoint.x >= faceMin.x //Face-hit check - && intersectPoint.x <= faceOppositeCorner[0] - && intersectPoint.y >= faceMin.y - && intersectPoint.y <= faceOppositeCorner[1]) { + if (intersectPoint.x >= faceMin.x // Face-hit check + && intersectPoint.x <= faceOppositeCorner[0] && + intersectPoint.y >= faceMin.y && + intersectPoint.y <= faceOppositeCorner[1]) { return RayRelation::Intersect; } return RayRelation::None; } RayRelation Ray::intersectAABB( - const rayvec3& boxPos, - const AABB& box, - float maxDist, - glm::ivec3& normal_ret, - scalar_t& distance_ret){ + const rayvec3& boxPos, + const AABB& box, + float maxDist, + glm::ivec3& normal_ret, + scalar_t& distance_ret +) { const AABBFaces& boxFaces = AABBFaces(boxPos, box); return intersectAABBFaces(boxFaces, maxDist, normal_ret, distance_ret); } RayRelation Ray::intersectAABBFaces( - const AABBFaces& boxFaces, - float maxDist, - glm::ivec3& normal_ret, - scalar_t& distance_ret){ - + const AABBFaces& boxFaces, + float maxDist, + glm::ivec3& normal_ret, + scalar_t& distance_ret +) { scalar_t faceDist; distance_ret = maxDist; glm::ivec3 bufNormal; - //unsigned char intersectedCount = 0; //this code is very uncomfortable, DONT LEARN IT! + // unsigned char intersectedCount = 0; //this code is very uncomfortable, + // DONT LEARN IT! bool isIntersect = false; if (intersectYZFace( - boxFaces.faces[0].first, boxFaces.faces[0].second, bufNormal, faceDist - ) > RayRelation::None && faceDist < distance_ret){ + boxFaces.faces[0].first, + boxFaces.faces[0].second, + bufNormal, + faceDist + ) > RayRelation::None && + faceDist < distance_ret) { isIntersect = true; normal_ret = bufNormal; distance_ret = faceDist; } if (intersectYZFace( - boxFaces.faces[1].first, boxFaces.faces[1].second, bufNormal, faceDist - ) > RayRelation::None && faceDist < distance_ret) { + boxFaces.faces[1].first, + boxFaces.faces[1].second, + bufNormal, + faceDist + ) > RayRelation::None && + faceDist < distance_ret) { isIntersect = true; normal_ret = bufNormal; distance_ret = faceDist; } if (intersectXZFace( - boxFaces.faces[2].first, boxFaces.faces[2].second, bufNormal, faceDist - ) > RayRelation::None && faceDist < distance_ret) { + boxFaces.faces[2].first, + boxFaces.faces[2].second, + bufNormal, + faceDist + ) > RayRelation::None && + faceDist < distance_ret) { isIntersect = true; normal_ret = bufNormal; distance_ret = faceDist; } if (intersectXZFace( - boxFaces.faces[3].first, boxFaces.faces[3].second, bufNormal, faceDist - ) > RayRelation::None && faceDist < distance_ret) { + boxFaces.faces[3].first, + boxFaces.faces[3].second, + bufNormal, + faceDist + ) > RayRelation::None && + faceDist < distance_ret) { isIntersect = true; normal_ret = bufNormal; distance_ret = faceDist; } if (intersectXYFace( - boxFaces.faces[4].first, boxFaces.faces[4].second, bufNormal, faceDist - ) > RayRelation::None && faceDist < distance_ret) { + boxFaces.faces[4].first, + boxFaces.faces[4].second, + bufNormal, + faceDist + ) > RayRelation::None && + faceDist < distance_ret) { isIntersect = true; normal_ret = bufNormal; distance_ret = faceDist; } if (intersectXYFace( - boxFaces.faces[5].first, boxFaces.faces[5].second, bufNormal, faceDist - ) > RayRelation::None && faceDist < distance_ret) { + boxFaces.faces[5].first, + boxFaces.faces[5].second, + bufNormal, + faceDist + ) > RayRelation::None && + faceDist < distance_ret) { isIntersect = true; normal_ret = bufNormal; distance_ret = faceDist; } - + if (isIntersect) return RayRelation::Intersect; return RayRelation::None; } diff --git a/src/maths/rays.hpp b/src/maths/rays.hpp index 339c109b..7d053267 100644 --- a/src/maths/rays.hpp +++ b/src/maths/rays.hpp @@ -4,22 +4,21 @@ #include "aabb.hpp" #include "glm/glm.hpp" #define GLM_ENABLE_EXPERIMENTAL -#include "glm/gtx/hash.hpp" - #include +#include "glm/gtx/hash.hpp" + using rayvec3 = glm::highp_dvec3; using rayvec2 = glm::highp_dvec2; using scalar_t = double; -enum class RayRelation { - Embed=2, Intersect=1, Parallel=0, None=0 -}; +enum class RayRelation { Embed = 2, Intersect = 1, Parallel = 0, None = 0 }; class AABBFaces { static const unsigned char AABBFACES_COUNT = 6; public: - std::array, AABBFACES_COUNT> faces; // every face is min-point and opposite corner point + std::array, AABBFACES_COUNT> + faces; // every face is min-point and opposite corner point AABBFaces() = default; AABBFaces(const rayvec3& parentBoxPos, const AABB& parentBox); @@ -30,48 +29,52 @@ public: rayvec3 origin; rayvec3 dir; - Ray(const rayvec3& rayOrigin, - const rayvec3& rayDir); + Ray(const rayvec3& rayOrigin, const rayvec3& rayDir); RayRelation isIntersectsYZFace( - const rayvec3& faceMin, - const rayvec2& faceOppositeCorner); + const rayvec3& faceMin, const rayvec2& faceOppositeCorner + ); RayRelation isIntersectsXZFace( - const rayvec3& faceMin, - const rayvec2& faceOppositeCorner); + const rayvec3& faceMin, const rayvec2& faceOppositeCorner + ); RayRelation isIntersectsXYFace( - const rayvec3& faceMin, - const rayvec2& faceOppositeCorner); + const rayvec3& faceMin, const rayvec2& faceOppositeCorner + ); -///returns normal and distance - RayRelation intersectYZFace( + /// returns normal and distance + RayRelation intersectYZFace( const rayvec3& faceMin, const rayvec2& faceOppositeCorner, glm::ivec3& normal_ret, - scalar_t& distance_ret); + scalar_t& distance_ret + ); RayRelation intersectXZFace( const rayvec3& faceMin, const rayvec2& faceOppositeCorner, glm::ivec3& normal_ret, - scalar_t& distance_ret); + scalar_t& distance_ret + ); RayRelation intersectXYFace( const rayvec3& faceMin, const rayvec2& faceOppositeCorner, glm::ivec3& normal_ret, - scalar_t& distance_ret); + scalar_t& distance_ret + ); RayRelation intersectAABB( const rayvec3& boxPos, const AABB& box, float maxDist, glm::ivec3& normal_ret, - scalar_t& distance_ret); + scalar_t& distance_ret + ); - RayRelation intersectAABBFaces( // calculates only normal and distance + RayRelation intersectAABBFaces( // calculates only normal and distance const AABBFaces& boxFaces, float maxDist, glm::ivec3& normal_ret, - scalar_t& distance_ret); + scalar_t& distance_ret + ); }; -#endif // SRC_VOXNATHS_HPP_ +#endif // SRC_VOXNATHS_HPP_ diff --git a/src/maths/util.hpp b/src/maths/util.hpp index 16977383..d6a14f7e 100644 --- a/src/maths/util.hpp +++ b/src/maths/util.hpp @@ -1,17 +1,18 @@ #ifndef MATHS_UTIL_HPP_ #define MATHS_UTIL_HPP_ -#include #include +#include + class PseudoRandom { unsigned short seed; public: - PseudoRandom(){ + PseudoRandom() { seed = (unsigned short)time(0); } - int rand(){ + int rand() { seed = (seed + 0x7ed5 + (seed << 6)); seed = (seed ^ 0xc23c ^ (seed >> 9)); seed = (seed + 0x1656 + (seed << 3)); @@ -36,14 +37,19 @@ public: return (x << 32ULL) | y; } - void setSeed(int number){ - seed = ((unsigned short)(number*23729) ^ (unsigned short)(number+16786)); + void setSeed(int number) { + seed = + ((unsigned short)(number * 23729) ^ (unsigned short)(number + 16786) + ); rand(); } - void setSeed(int number1, int number2){ - seed = (((unsigned short)(number1*23729) | (unsigned short)(number2%16786)) ^ (unsigned short)(number2*number1)); + void setSeed(int number1, int number2) { + seed = + (((unsigned short)(number1 * 23729) | + (unsigned short)(number2 % 16786)) ^ + (unsigned short)(number2 * number1)); rand(); } }; -#endif // MATHS_UTIL_HPP_ +#endif // MATHS_UTIL_HPP_ diff --git a/src/maths/voxmaths.hpp b/src/maths/voxmaths.hpp index 142ca1a0..daae514c 100644 --- a/src/maths/voxmaths.hpp +++ b/src/maths/voxmaths.hpp @@ -48,4 +48,4 @@ inline light_t light_pack(ubyte r, ubyte g, ubyte b, ubyte s) { return r | (g << 4) | (b << 8) | (s << 12); } -#endif // VOXNATHS_HPP_ +#endif // VOXNATHS_HPP_ diff --git a/src/objects/Entities.cpp b/src/objects/Entities.cpp index 6e6d593d..de5dc116 100644 --- a/src/objects/Entities.cpp +++ b/src/objects/Entities.cpp @@ -1,25 +1,25 @@ #include "Entities.hpp" -#include "../debug/Logger.hpp" -#include "../data/dynamic_util.hpp" +#include +#include + #include "../assets/Assets.hpp" -#include "../world/Level.hpp" -#include "../maths/rays.hpp" #include "../content/Content.hpp" -#include "../physics/Hitbox.hpp" -#include "../physics/PhysicsSolver.hpp" -#include "../graphics/render/ModelBatch.hpp" +#include "../data/dynamic_util.hpp" +#include "../debug/Logger.hpp" +#include "../engine.hpp" +#include "../graphics/core/DrawContext.hpp" #include "../graphics/core/LineBatch.hpp" #include "../graphics/core/Model.hpp" -#include "../graphics/core/DrawContext.hpp" +#include "../graphics/render/ModelBatch.hpp" +#include "../logic/scripting/scripting.hpp" #include "../maths/FrustumCulling.hpp" +#include "../maths/rays.hpp" #include "../objects/EntityDef.hpp" #include "../objects/rigging.hpp" -#include "../logic/scripting/scripting.hpp" -#include "../engine.hpp" - -#include -#include +#include "../physics/Hitbox.hpp" +#include "../physics/PhysicsSolver.hpp" +#include "../world/Level.hpp" static debug::Logger logger("entities"); @@ -39,7 +39,7 @@ void Transform::refresh() { } void Entity::destroy() { - if (isValid()){ + if (isValid()) { entities.despawn(id); } } @@ -59,11 +59,11 @@ void Entity::setRig(const rigging::SkeletonConfig* rigConfig) { ); } -Entities::Entities(Level* level) -: level(level), sensorsTickClock(20, 3), updateTickClock(20, 3) { +Entities::Entities(Level* level) + : level(level), sensorsTickClock(20, 3), updateTickClock(20, 3) { } -template +template static sensorcallback create_sensor_callback(Entities* entities) { return [=](auto entityid, auto index, auto otherid) { if (auto entity = entities->get(entityid)) { @@ -82,7 +82,14 @@ static void initialize_body( SensorParams params {}; params.aabb = box; body.sensors[i] = Sensor { - true, SensorType::AABB, i, id, params, params, {}, {}, + true, + SensorType::AABB, + i, + id, + params, + params, + {}, + {}, create_sensor_callback(entities), create_sensor_callback(entities)}; } @@ -90,7 +97,14 @@ static void initialize_body( SensorParams params {}; params.radial = glm::vec4(radius); body.sensors[i] = Sensor { - true, SensorType::RADIUS, i, id, params, params, {}, {}, + true, + SensorType::RADIUS, + i, + id, + params, + params, + {}, + {}, create_sensor_callback(entities), create_sensor_callback(entities)}; } @@ -101,11 +115,11 @@ entityid_t Entities::spawn( glm::vec3 position, dynamic::Map_sptr args, dynamic::Map_sptr saved, - entityid_t uid) -{ + entityid_t uid +) { auto skeleton = level->content->getSkeleton(def.skeletonName); if (skeleton == nullptr) { - throw std::runtime_error("skeleton "+def.skeletonName+" not found"); + throw std::runtime_error("skeleton " + def.skeletonName + " not found"); } entityid_t id; if (uid == 0) { @@ -145,7 +159,7 @@ entityid_t Entities::spawn( auto& scripting = registry.emplace(entity); registry.emplace(entity, skeleton->instance()); - + for (auto& componentName : def.components) { auto component = std::make_unique( componentName, entity_funcs_set {}, nullptr @@ -334,8 +348,8 @@ dynamic::Value Entities::serialize(const Entity& entity) { if (!scripts.components.empty()) { auto& compsMap = root->putMap("comps"); for (auto& comp : scripts.components) { - auto data = scripting::get_component_value( - comp->env, SAVED_DATA_VARNAME); + auto data = + scripting::get_component_value(comp->env, SAVED_DATA_VARNAME); compsMap.put(comp->name, data); } } @@ -383,8 +397,8 @@ void Entities::updateSensors( body.hitbox.position.x, body.hitbox.position.y, body.hitbox.position.z, - sensor.params.radial.w* - sensor.params.radial.w); + sensor.params.radial.w * sensor.params.radial.w + ); break; } sensors.push_back(&sensor); @@ -428,18 +442,13 @@ void Entities::updatePhysics(float delta) { float vel = glm::length(prevVel); int substeps = static_cast(delta * vel * 20); substeps = std::min(100, std::max(2, substeps)); - physics->step( - level->chunks.get(), - &hitbox, - delta, - substeps, - eid.uid - ); + physics->step(level->chunks.get(), &hitbox, delta, substeps, eid.uid); hitbox.linearDamping = hitbox.grounded * 24; transform.setPos(hitbox.position); if (hitbox.grounded && !grounded) { scripting::on_entity_grounded( - *get(eid.uid), glm::length(prevVel-hitbox.velocity)); + *get(eid.uid), glm::length(prevVel - hitbox.velocity) + ); } if (!hitbox.grounded && grounded) { scripting::on_entity_fall(*get(eid.uid)); @@ -452,21 +461,28 @@ void Entities::update(float delta) { scripting::on_entities_update( updateTickClock.getTickRate(), updateTickClock.getParts(), - updateTickClock.getPart()); + updateTickClock.getPart() + ); } } static void debug_render_skeleton( - LineBatch& batch, - const rigging::Bone* bone, + LineBatch& batch, + const rigging::Bone* bone, const rigging::Skeleton& skeleton ) { size_t pindex = bone->getIndex(); for (auto& sub : bone->getSubnodes()) { size_t sindex = sub->getIndex(); - batch.line(glm::vec3(skeleton.calculated.matrices[pindex] * glm::vec4(0,0,0,1)), - glm::vec3(skeleton.calculated.matrices[sindex] * glm::vec4(0,0,0,1)), - glm::vec4(0,0.5f,0,1)); + batch.line( + glm::vec3( + skeleton.calculated.matrices[pindex] * glm::vec4(0, 0, 0, 1) + ), + glm::vec3( + skeleton.calculated.matrices[sindex] * glm::vec4(0, 0, 0, 1) + ), + glm::vec4(0, 0.5f, 0, 1) + ); debug_render_skeleton(batch, sub.get(), skeleton); } } @@ -482,18 +498,18 @@ void Entities::renderDebug( const auto& hitbox = rigidbody.hitbox; const auto& pos = transform.pos; const auto& size = transform.size; - if (frustum && !frustum->isBoxVisible(pos-size, pos+size)) { + if (frustum && !frustum->isBoxVisible(pos - size, pos + size)) { continue; } batch.box(hitbox.position, hitbox.halfsize * 2.0f, glm::vec4(1.0f)); for (auto& sensor : rigidbody.sensors) { - if (sensor.type != SensorType::AABB) - continue; + if (sensor.type != SensorType::AABB) continue; batch.box( - sensor.calculated.aabb.center(), - sensor.calculated.aabb.size(), - glm::vec4(1.0f, 1.0f, 0.0f, 1.0f)); + sensor.calculated.aabb.center(), + sensor.calculated.aabb.size(), + glm::vec4(1.0f, 1.0f, 0.0f, 1.0f) + ); } } } @@ -507,7 +523,7 @@ void Entities::renderDebug( auto config = skeleton.config; const auto& pos = transform.pos; const auto& size = transform.size; - if (frustum && !frustum->isBoxVisible(pos-size, pos+size)) { + if (frustum && !frustum->isBoxVisible(pos - size, pos + size)) { continue; } auto bone = config->getRoot(); @@ -517,7 +533,11 @@ void Entities::renderDebug( } void Entities::render( - Assets* assets, ModelBatch& batch, const Frustum* frustum, float delta, bool pause + Assets* assets, + ModelBatch& batch, + const Frustum* frustum, + float delta, + bool pause ) { if (!pause) { scripting::on_entities_render(delta); @@ -530,7 +550,7 @@ void Entities::render( } const auto& pos = transform.pos; const auto& size = transform.size; - if (!frustum || frustum->isBoxVisible(pos-size, pos+size)) { + if (!frustum || frustum->isBoxVisible(pos - size, pos + size)) { const auto* rigConfig = skeleton.config; rigConfig->render(assets, batch, skeleton, transform.combined); } @@ -568,7 +588,7 @@ std::vector Entities::getAllInRadius(glm::vec3 center, float radius) { std::vector collected; auto view = registry.view(); for (auto [entity, transform] : view.each()) { - if (glm::distance2(transform.pos, center) <= radius*radius) { + if (glm::distance2(transform.pos, center) <= radius * radius) { const auto& found = uids.find(entity); if (found == uids.end()) { continue; diff --git a/src/objects/Entities.hpp b/src/objects/Entities.hpp index 6e6839c9..eb4d963f 100644 --- a/src/objects/Entities.hpp +++ b/src/objects/Entities.hpp @@ -1,19 +1,19 @@ #ifndef OBJECTS_ENTITIES_HPP_ #define OBJECTS_ENTITIES_HPP_ -#include "../typedefs.hpp" -#include "../physics/Hitbox.hpp" -#include "../data/dynamic.hpp" -#include "../util/Clock.hpp" - -#include +#include #include #include -#include +#include + +#include "../data/dynamic.hpp" +#include "../physics/Hitbox.hpp" +#include "../typedefs.hpp" +#include "../util/Clock.hpp" #define GLM_ENABLE_EXPERIMENTAL +#include #include #include -#include struct entity_funcs_set { bool init; @@ -48,7 +48,7 @@ struct Transform { glm::vec3 displaySize; void refresh(); - + inline void setRot(glm::mat3 m) { rot = m; dirty = true; @@ -80,8 +80,11 @@ struct UserComponent { entity_funcs_set funcsset; scriptenv env; - UserComponent(const std::string& name, entity_funcs_set funcsset, scriptenv env) - : name(name), funcsset(funcsset), env(env) {} + UserComponent( + const std::string& name, entity_funcs_set funcsset, scriptenv env + ) + : name(name), funcsset(funcsset), env(env) { + } }; struct ScriptComponents { @@ -115,11 +118,12 @@ class Entity { public: Entity( Entities& entities, - entityid_t id, - entt::registry& registry, + entityid_t id, + entt::registry& registry, const entt::entity entity ) - : entities(entities), id(id), registry(registry), entity(entity) {} + : entities(entities), id(id), registry(registry), entity(entity) { + } EntityId& getID() const { return registry.get(entity); @@ -186,15 +190,24 @@ public: void updatePhysics(float delta); void update(float delta); - void renderDebug(LineBatch& batch, const Frustum* frustum, const DrawContext& ctx); - void render(Assets* assets, ModelBatch& batch, const Frustum* frustum, float delta, bool pause); + void renderDebug( + LineBatch& batch, const Frustum* frustum, const DrawContext& ctx + ); + void render( + Assets* assets, + ModelBatch& batch, + const Frustum* frustum, + float delta, + bool pause + ); entityid_t spawn( EntityDef& def, glm::vec3 position, - dynamic::Map_sptr args=nullptr, - dynamic::Map_sptr saved=nullptr, - entityid_t uid=0); + dynamic::Map_sptr args = nullptr, + dynamic::Map_sptr saved = nullptr, + entityid_t uid = 0 + ); std::optional get(entityid_t id) { const auto& found = entities.find(id); @@ -212,7 +225,11 @@ public: /// @param ignore Ignored entity ID /// @return An optional structure containing entity, normal and distance std::optional rayCast( - glm::vec3 start, glm::vec3 dir, float maxDistance, entityid_t ignore=-1); + glm::vec3 start, + glm::vec3 dir, + float maxDistance, + entityid_t ignore = -1 + ); void loadEntities(dynamic::Map_sptr map); void loadEntity(const dynamic::Map_sptr& map); @@ -237,4 +254,4 @@ public: } }; -#endif // OBJECTS_ENTITIES_HPP_ +#endif // OBJECTS_ENTITIES_HPP_ diff --git a/src/objects/Player.cpp b/src/objects/Player.cpp index ac924b7e..fcbf19f2 100644 --- a/src/objects/Player.cpp +++ b/src/objects/Player.cpp @@ -1,20 +1,20 @@ #include "Player.hpp" -#include "../content/ContentLUT.hpp" -#include "../physics/Hitbox.hpp" -#include "../physics/PhysicsSolver.hpp" -#include "../voxels/Chunks.hpp" -#include "../world/Level.hpp" -#include "../window/Events.hpp" -#include "../window/Camera.hpp" -#include "../items/Inventory.hpp" -#include "../objects/Entities.hpp" -#include "../objects/rigging.hpp" - #include #include #include +#include "../content/ContentLUT.hpp" +#include "../items/Inventory.hpp" +#include "../objects/Entities.hpp" +#include "../objects/rigging.hpp" +#include "../physics/Hitbox.hpp" +#include "../physics/PhysicsSolver.hpp" +#include "../voxels/Chunks.hpp" +#include "../window/Camera.hpp" +#include "../window/Events.hpp" +#include "../world/Level.hpp" + const float CROUCH_SPEED_MUL = 0.35f; const float RUN_SPEED_MUL = 1.5f; const float PLAYER_GROUND_DAMPING = 10.0f; @@ -23,19 +23,23 @@ const float FLIGHT_SPEED_MUL = 4.0f; const float CHEAT_SPEED_MUL = 5.0f; const float JUMP_FORCE = 8.0f; -Player::Player(Level* level, glm::vec3 position, float speed, - std::shared_ptr inv, entityid_t eid) : - level(level), - speed(speed), - chosenSlot(0), - position(position), - inventory(std::move(inv)), - eid(eid), - camera(level->getCamera("base:first-person")), - spCamera(level->getCamera("base:third-person-front")), - tpCamera(level->getCamera("base:third-person-back")), - currentCamera(camera) -{ +Player::Player( + Level* level, + glm::vec3 position, + float speed, + std::shared_ptr inv, + entityid_t eid +) + : level(level), + speed(speed), + chosenSlot(0), + position(position), + inventory(std::move(inv)), + eid(eid), + camera(level->getCamera("base:first-person")), + spCamera(level->getCamera("base:third-person-front")), + tpCamera(level->getCamera("base:third-person-back")), + currentCamera(camera) { camera->setFov(glm::radians(90.0f)); spCamera->setFov(glm::radians(90.0f)); tpCamera->setFov(glm::radians(90.0f)); @@ -69,10 +73,10 @@ void Player::updateInput(PlayerInput& input, float delta) { } bool crouch = input.shift && hitbox->grounded && !input.sprint; float speed = this->speed; - if (flight){ + if (flight) { speed *= FLIGHT_SPEED_MUL; } - if (input.cheat){ + if (input.cheat) { speed *= CHEAT_SPEED_MUL; } @@ -83,20 +87,20 @@ void Player::updateInput(PlayerInput& input, float delta) { speed *= RUN_SPEED_MUL; } - glm::vec3 dir(0,0,0); - if (input.moveForward){ + glm::vec3 dir(0, 0, 0); + if (input.moveForward) { dir += camera->dir; } - if (input.moveBack){ + if (input.moveBack) { dir -= camera->dir; } - if (input.moveRight){ + if (input.moveRight) { dir += camera->right; } - if (input.moveLeft){ + if (input.moveLeft) { dir -= camera->right; } - if (glm::length(dir) > 0.0f){ + if (glm::length(dir) > 0.0f) { dir = glm::normalize(dir); hitbox->velocity += dir * speed * delta * 9.0f; } @@ -104,12 +108,12 @@ void Player::updateInput(PlayerInput& input, float delta) { hitbox->linearDamping = PLAYER_GROUND_DAMPING; hitbox->verticalDamping = flight; hitbox->gravityScale = flight ? 0.0f : 1.0f; - if (flight){ + if (flight) { hitbox->linearDamping = PLAYER_AIR_DAMPING; - if (input.jump){ + if (input.jump) { hitbox->velocity.y += speed * delta * 9; } - if (input.shift){ + if (input.shift) { hitbox->velocity.y -= speed * delta * 9; } } @@ -117,14 +121,13 @@ void Player::updateInput(PlayerInput& input, float delta) { hitbox->linearDamping = PLAYER_AIR_DAMPING; } - if (input.jump && hitbox->grounded){ + if (input.jump && hitbox->grounded) { hitbox->velocity.y = JUMP_FORCE; } - if ((input.flight && !noclip) || - (input.noclip && flight == noclip)){ + if ((input.flight && !noclip) || (input.noclip && flight == noclip)) { flight = !flight; - if (flight){ + if (flight) { hitbox->velocity.y += 1.0f; } } @@ -163,10 +166,10 @@ void Player::postUpdate() { size_t bodyIndex = skeleton.config->find("body")->getIndex(); size_t headIndex = skeleton.config->find("head")->getIndex(); - skeleton.pose.matrices[bodyIndex] = + skeleton.pose.matrices[bodyIndex] = glm::rotate(glm::mat4(1.0f), glm::radians(cam.x), glm::vec3(0, 1, 0)); - skeleton.pose.matrices[headIndex] = glm::rotate( - glm::mat4(1.0f), glm::radians(cam.y), glm::vec3(1, 0, 0)); + skeleton.pose.matrices[headIndex] = + glm::rotate(glm::mat4(1.0f), glm::radians(cam.y), glm::vec3(1, 0, 0)); } void Player::teleport(glm::vec3 position) { @@ -177,16 +180,17 @@ void Player::teleport(glm::vec3 position) { } void Player::attemptToFindSpawnpoint() { - glm::vec3 newpos ( + glm::vec3 newpos( position.x + (rand() % 200 - 100), rand() % 80 + 100, position.z + (rand() % 200 - 100) ); - while (newpos.y > 0 && !level->chunks->isObstacleBlock(newpos.x, newpos.y-2, newpos.z)) { + while (newpos.y > 0 && + !level->chunks->isObstacleBlock(newpos.x, newpos.y - 2, newpos.z)) { newpos.y--; } - voxel* headvox = level->chunks->get(newpos.x, newpos.y+1, newpos.z); + voxel* headvox = level->chunks->get(newpos.x, newpos.y + 1, newpos.z); if (level->chunks->isObstacleBlock(newpos.x, newpos.y, newpos.z) || headvox == nullptr || headvox->id != 0) { return; @@ -269,16 +273,19 @@ std::unique_ptr Player::serialize() const { root->put("chosen-slot", chosenSlot); root->put("entity", eid); root->put("inventory", inventory->serialize()); - auto found = std::find( - level->cameras.begin(), level->cameras.end(), currentCamera); + auto found = + std::find(level->cameras.begin(), level->cameras.end(), currentCamera); if (found != level->cameras.end()) { - root->put("camera", level->content->getIndices( - ResourceType::CAMERA).getName(found - level->cameras.begin())); + root->put( + "camera", + level->content->getIndices(ResourceType::CAMERA) + .getName(found - level->cameras.begin()) + ); } return root; } -void Player::deserialize(dynamic::Map *src) { +void Player::deserialize(dynamic::Map* src) { auto posarr = src->list("position"); position.x = posarr->num(0); position.y = posarr->num(1); @@ -294,11 +301,7 @@ void Player::deserialize(dynamic::Map *src) { if (src->has("spawnpoint")) { auto sparr = src->list("spawnpoint"); - setSpawnPoint(glm::vec3( - sparr->num(0), - sparr->num(1), - sparr->num(2) - )); + setSpawnPoint(glm::vec3(sparr->num(0), sparr->num(1), sparr->num(2))); } else { setSpawnPoint(position); } @@ -307,11 +310,11 @@ void Player::deserialize(dynamic::Map *src) { src->flag("noclip", noclip); setChosenSlot(src->get("chosen-slot", getChosenSlot())); src->num("entity", eid); - + if (auto invmap = src->map("inventory")) { getInventory()->deserialize(invmap.get()); } - + if (src->has("camera")) { std::string name; src->str("camera", name); @@ -330,7 +333,7 @@ void Player::convert(dynamic::Map* data, const ContentLUT* lut) { Inventory::convert(inventory.get(), lut); } } - + } else { if (auto inventory = data->map("inventory")) { Inventory::convert(inventory.get(), lut); diff --git a/src/objects/Player.hpp b/src/objects/Player.hpp index 7fa62c5a..8e97bde1 100644 --- a/src/objects/Player.hpp +++ b/src/objects/Player.hpp @@ -1,15 +1,15 @@ #ifndef SRC_OBJECTS_PLAYER_HPP_ #define SRC_OBJECTS_PLAYER_HPP_ -#include "../settings.hpp" -#include "../data/dynamic.hpp" -#include "../voxels/voxel.hpp" -#include "../interfaces/Serializable.hpp" -#include "../interfaces/Object.hpp" - +#include #include #include -#include + +#include "../data/dynamic.hpp" +#include "../interfaces/Object.hpp" +#include "../interfaces/Serializable.hpp" +#include "../settings.hpp" +#include "../voxels/voxel.hpp" class Camera; class Inventory; @@ -60,8 +60,13 @@ public: glm::vec3 cam {}; CursorSelection selection {}; - Player(Level* level, glm::vec3 position, float speed, - std::shared_ptr inv, entityid_t eid); + Player( + Level* level, + glm::vec3 position, + float speed, + std::shared_ptr inv, + entityid_t eid + ); ~Player(); void teleport(glm::vec3 position); @@ -87,7 +92,7 @@ public: void setEntity(entityid_t eid); entityid_t getSelectedEntity() const; - + std::shared_ptr getInventory() const; glm::vec3 getPosition() const { @@ -100,7 +105,7 @@ public: glm::vec3 getSpawnPoint() const; std::unique_ptr serialize() const override; - void deserialize(dynamic::Map *src) override; + void deserialize(dynamic::Map* src) override; static void convert(dynamic::Map* data, const ContentLUT* lut); @@ -109,4 +114,4 @@ public: } }; -#endif // SRC_OBJECTS_PLAYER_HPP_ +#endif // SRC_OBJECTS_PLAYER_HPP_ diff --git a/src/objects/rigging.cpp b/src/objects/rigging.cpp index 67b14c18..c592e104 100644 --- a/src/objects/rigging.cpp +++ b/src/objects/rigging.cpp @@ -1,14 +1,14 @@ #include "rigging.hpp" #include "../assets/Assets.hpp" -#include "../graphics/render/ModelBatch.hpp" -#include "../graphics/core/Model.hpp" #include "../coders/json.hpp" #include "../data/dynamic_util.hpp" +#include "../graphics/core/Model.hpp" +#include "../graphics/render/ModelBatch.hpp" #define GLM_ENABLE_EXPERIMENTAL -#include #include +#include using namespace rigging; @@ -20,17 +20,18 @@ void ModelReference::refresh(const Assets* assets) { } Bone::Bone( - size_t index, - std::string name, + size_t index, + std::string name, std::string model, std::vector> bones, - glm::vec3 offset) - : index(index), - name(std::move(name)), - bones(std::move(bones)), - offset(offset), - model({model, nullptr, true}) -{} + glm::vec3 offset +) + : index(index), + name(std::move(name)), + bones(std::move(bones)), + offset(offset), + model({model, nullptr, true}) { +} void Bone::setModel(const std::string& name) { if (model.name == name) { @@ -39,7 +40,7 @@ void Bone::setModel(const std::string& name) { model = {name, nullptr, true}; } -Skeleton::Skeleton(const SkeletonConfig* config) +Skeleton::Skeleton(const SkeletonConfig* config) : config(config), pose(config->getBones().size()), calculated(config->getBones().size()), @@ -60,27 +61,31 @@ static void get_all_nodes(std::vector& nodes, Bone* node) { } } -SkeletonConfig::SkeletonConfig(const std::string& name, std::unique_ptr root, size_t nodesCount) - : name(name), root(std::move(root)), nodes(nodesCount) { +SkeletonConfig::SkeletonConfig( + const std::string& name, std::unique_ptr root, size_t nodesCount +) + : name(name), root(std::move(root)), nodes(nodesCount) { get_all_nodes(nodes, this->root.get()); } size_t SkeletonConfig::update( - size_t index, - Skeleton& skeleton, - Bone* node, - glm::mat4 matrix) const -{ + size_t index, Skeleton& skeleton, Bone* node, glm::mat4 matrix +) const { auto boneMatrix = skeleton.pose.matrices[index]; auto boneOffset = node->getOffset(); glm::mat4 baseMatrix(1.0f); if (glm::length2(boneOffset) > 0.0f) { baseMatrix = glm::translate(glm::mat4(1.0f), boneOffset); } - skeleton.calculated.matrices[index] = matrix * baseMatrix * boneMatrix; + skeleton.calculated.matrices[index] = matrix * baseMatrix * boneMatrix; size_t count = 1; for (auto& subnode : node->getSubnodes()) { - count += update(index+count, skeleton, subnode.get(), skeleton.calculated.matrices[index]); + count += update( + index + count, + skeleton, + subnode.get(), + skeleton.calculated.matrices[index] + ); } return count; } @@ -93,8 +98,8 @@ void SkeletonConfig::render( Assets* assets, ModelBatch& batch, Skeleton& skeleton, - const glm::mat4& matrix) const -{ + const glm::mat4& matrix +) const { update(skeleton, matrix); if (!skeleton.visible) { @@ -113,8 +118,12 @@ void SkeletonConfig::render( } model = modelOverride.model ? modelOverride.model : model; if (model) { - batch.draw(skeleton.calculated.matrices[i], skeleton.tint, model, - &skeleton.textures); + batch.draw( + skeleton.calculated.matrices[i], + skeleton.tint, + model, + &skeleton.textures + ); } } } @@ -145,19 +154,19 @@ static std::tuple> read_node( if (auto nodesList = root->list("nodes")) { for (size_t i = 0; i < nodesList->size(); i++) { if (const auto& map = nodesList->map(i)) { - auto [subcount, subNode] = read_node(map, index+count); + auto [subcount, subNode] = read_node(map, index + count); count += subcount; bones.push_back(std::move(subNode)); } } } - return {count, std::make_unique(index, name, model, std::move(bones), offset)}; + return { + count, + std::make_unique(index, name, model, std::move(bones), offset)}; } std::unique_ptr SkeletonConfig::parse( - std::string_view src, - std::string_view file, - std::string_view name + std::string_view src, std::string_view file, std::string_view name ) { auto root = json::parse(file, src); auto rootNodeMap = root->map("root"); @@ -165,5 +174,7 @@ std::unique_ptr SkeletonConfig::parse( throw std::runtime_error("missing 'root' element"); } auto [count, rootNode] = read_node(rootNodeMap, 0); - return std::make_unique(std::string(name), std::move(rootNode), count); + return std::make_unique( + std::string(name), std::move(rootNode), count + ); } diff --git a/src/objects/rigging.hpp b/src/objects/rigging.hpp index 6d4469ee..2b1b54a1 100644 --- a/src/objects/rigging.hpp +++ b/src/objects/rigging.hpp @@ -1,13 +1,13 @@ #ifndef OBJECTS_RIGGING_HPP_ #define OBJECTS_RIGGING_HPP_ -#include "../typedefs.hpp" - -#include +#include #include #include -#include #include +#include + +#include "../typedefs.hpp" class Assets; class ModelBatch; @@ -44,18 +44,19 @@ namespace rigging { public: ModelReference model; Bone( - size_t index, + size_t index, std::string name, std::string model, std::vector> bones, - glm::vec3 offset); + glm::vec3 offset + ); void setModel(const std::string& name); const std::string& getName() const { return name; } - + size_t getIndex() const { return index; } @@ -70,7 +71,7 @@ namespace rigging { }; struct BoneFlags { - bool visible: 1; + bool visible : 1; }; struct Skeleton { @@ -85,12 +86,12 @@ namespace rigging { Skeleton(const SkeletonConfig* config); }; - + class SkeletonConfig { std::string name; std::unique_ptr root; std::unordered_map indices; - + /// Nodes and indices are ordered from root to bones. /// Example: /// 0 - root @@ -100,20 +101,22 @@ namespace rigging { std::vector nodes; size_t update( - size_t index, - Skeleton& skeleton, - Bone* node, - glm::mat4 matrix) const; + size_t index, Skeleton& skeleton, Bone* node, glm::mat4 matrix + ) const; public: - SkeletonConfig(const std::string& name, std::unique_ptr root, - size_t nodesCount); + SkeletonConfig( + const std::string& name, + std::unique_ptr root, + size_t nodesCount + ); void update(Skeleton& skeleton, glm::mat4 matrix) const; void render( Assets* assets, ModelBatch& batch, - Skeleton& skeleton, - const glm::mat4& matrix) const; + Skeleton& skeleton, + const glm::mat4& matrix + ) const; Skeleton instance() const { return Skeleton(this); @@ -122,15 +125,13 @@ namespace rigging { Bone* find(std::string_view str) const; static std::unique_ptr parse( - std::string_view src, - std::string_view file, - std::string_view name + std::string_view src, std::string_view file, std::string_view name ); const std::vector& getBones() const { return nodes; } - + const std::string& getName() const { return name; } @@ -141,4 +142,4 @@ namespace rigging { }; }; -#endif // OBJECTS_RIGGING_HPP_ +#endif // OBJECTS_RIGGING_HPP_ diff --git a/src/util/BufferPool.hpp b/src/util/BufferPool.hpp index 1fcf130b..4b72acf6 100644 --- a/src/util/BufferPool.hpp +++ b/src/util/BufferPool.hpp @@ -1,17 +1,17 @@ #ifndef UTIL_BUFFER_POOL_HPP_ #define UTIL_BUFFER_POOL_HPP_ -#include "../typedefs.hpp" - -#include -#include -#include #include +#include +#include +#include + +#include "../typedefs.hpp" namespace util { /// @brief Thread-safe pool of same-sized buffers /// @tparam T array type - template + template class BufferPool { std::vector> buffers; std::queue freeBuffers; @@ -27,7 +27,7 @@ namespace util { std::lock_guard lock(mutex); if (freeBuffers.empty()) { buffers.emplace_back(std::make_unique(bufferSize)); - freeBuffers.push(buffers[buffers.size()-1].get()); + freeBuffers.push(buffers[buffers.size() - 1].get()); } auto* buffer = freeBuffers.front(); freeBuffers.pop(); @@ -39,4 +39,4 @@ namespace util { }; } -#endif // UTIL_BUFFER_POOL_HPP_ +#endif // UTIL_BUFFER_POOL_HPP_ diff --git a/src/util/Clock.cpp b/src/util/Clock.cpp index bb81112e..4434e800 100644 --- a/src/util/Clock.cpp +++ b/src/util/Clock.cpp @@ -5,19 +5,18 @@ using namespace util; Clock::Clock(int tickRate, int tickParts) - : tickRate(tickRate), - tickParts(tickParts) { + : tickRate(tickRate), tickParts(tickParts) { } bool Clock::update(float delta) { tickTimer += delta; - float delay = 1.0f / float(tickRate); + float delay = 1.0f / float(tickRate); if (tickTimer > delay || tickPartsUndone) { if (tickPartsUndone) { tickPartsUndone--; } else { tickTimer = std::fmod(tickTimer, delay); - tickPartsUndone = tickParts-1; + tickPartsUndone = tickParts - 1; } return true; } @@ -29,7 +28,7 @@ int Clock::getParts() const { } int Clock::getPart() const { - return tickParts-tickPartsUndone-1; + return tickParts - tickPartsUndone - 1; } int Clock::getTickRate() const { diff --git a/src/util/Clock.hpp b/src/util/Clock.hpp index 6a59051a..8fb45cfb 100644 --- a/src/util/Clock.hpp +++ b/src/util/Clock.hpp @@ -21,4 +21,4 @@ namespace util { }; } -#endif // UTIL_CLOCK_HPP_ +#endif // UTIL_CLOCK_HPP_ diff --git a/src/util/ObjectsKeeper.hpp b/src/util/ObjectsKeeper.hpp index 8b5ba5b5..5a046408 100644 --- a/src/util/ObjectsKeeper.hpp +++ b/src/util/ObjectsKeeper.hpp @@ -1,15 +1,16 @@ #ifndef UTIL_OBJECTS_KEEPER_HPP_ #define UTIL_OBJECTS_KEEPER_HPP_ -#include #include +#include namespace util { /// @brief Keeps shared pointers alive until destruction class ObjectsKeeper { std::vector> ptrs; public: - virtual ~ObjectsKeeper() {} + virtual ~ObjectsKeeper() { + } virtual void keepAlive(std::shared_ptr ptr) { ptrs.push_back(ptr); @@ -17,4 +18,4 @@ namespace util { }; } -#endif // UTIL_OBJECTS_KEEPER_HPP_ +#endif // UTIL_OBJECTS_KEEPER_HPP_ diff --git a/src/util/RunnablesList.hpp b/src/util/RunnablesList.hpp index 4360df8d..f8130ff1 100644 --- a/src/util/RunnablesList.hpp +++ b/src/util/RunnablesList.hpp @@ -1,13 +1,13 @@ #ifndef UTIL_RUNNABLES_LIST_HPP_ #define UTIL_RUNNABLES_LIST_HPP_ -#include "../typedefs.hpp" -#include "../delegates.hpp" - #include #include #include +#include "../delegates.hpp" +#include "../typedefs.hpp" + namespace util { class RunnablesList { int nextid = 1; @@ -30,4 +30,4 @@ namespace util { }; } -#endif // UTIL_RUNNABLES_LIST_HPP_ +#endif // UTIL_RUNNABLES_LIST_HPP_ diff --git a/src/util/ThreadPool.hpp b/src/util/ThreadPool.hpp index 594885f2..93c61aec 100644 --- a/src/util/ThreadPool.hpp +++ b/src/util/ThreadPool.hpp @@ -1,255 +1,259 @@ #ifndef UTIL_THREAD_POOL_HPP_ #define UTIL_THREAD_POOL_HPP_ -#include "../delegates.hpp" -#include "../debug/Logger.hpp" -#include "../interfaces/Task.hpp" - -#include #include -#include #include -#include -#include #include +#include +#include +#include +#include #include +#include "../debug/Logger.hpp" +#include "../delegates.hpp" +#include "../interfaces/Task.hpp" + namespace util { - -template -struct ThreadPoolResult { - std::shared_ptr job; - std::condition_variable& variable; - int workerIndex; - bool& locked; - T entry; -}; -template -class Worker { -public: - Worker() = default; - virtual ~Worker() = default; - virtual R operator()(const std::shared_ptr&) = 0; -}; + template + struct ThreadPoolResult { + std::shared_ptr job; + std::condition_variable& variable; + int workerIndex; + bool& locked; + T entry; + }; -template -class ThreadPool : public Task { - debug::Logger logger; - std::queue> jobs; - std::queue> results; - std::mutex resultsMutex; - std::vector threads; - std::condition_variable jobsMutexCondition; - std::mutex jobsMutex; - std::vector> workersBlocked; - consumer resultConsumer; - consumer&> onJobFailed = nullptr; - runnable onComplete = nullptr; - std::atomic busyWorkers = 0; - std::atomic jobsDone = 0; - std::atomic working = true; - bool failed = false; - bool standaloneResults = true; - bool stopOnFail = true; + template + class Worker { + public: + Worker() = default; + virtual ~Worker() = default; + virtual R operator()(const std::shared_ptr&) = 0; + }; - void threadLoop(int index, std::shared_ptr> worker) { - std::condition_variable variable; - std::mutex mutex; - bool locked = false; - while (working) { - std::shared_ptr job; - { - std::unique_lock lock(jobsMutex); - jobsMutexCondition.wait(lock, [this] { - return !jobs.empty() || !working; - }); - if (!working || failed) { - break; - } - job = jobs.front(); - jobs.pop(); + template + class ThreadPool : public Task { + debug::Logger logger; + std::queue> jobs; + std::queue> results; + std::mutex resultsMutex; + std::vector threads; + std::condition_variable jobsMutexCondition; + std::mutex jobsMutex; + std::vector> workersBlocked; + consumer resultConsumer; + consumer&> onJobFailed = nullptr; + runnable onComplete = nullptr; + std::atomic busyWorkers = 0; + std::atomic jobsDone = 0; + std::atomic working = true; + bool failed = false; + bool standaloneResults = true; + bool stopOnFail = true; - busyWorkers++; - } - try { - R result = (*worker)(job); + void threadLoop(int index, std::shared_ptr> worker) { + std::condition_variable variable; + std::mutex mutex; + bool locked = false; + while (working) { + std::shared_ptr job; { - std::lock_guard lock(resultsMutex); - results.push(ThreadPoolResult {job, variable, index, locked, result}); - if (!standaloneResults) { - locked = true; - } - busyWorkers--; - } - if (!standaloneResults){ - std::unique_lock lock(mutex); - variable.wait(lock, [&] { - return !working || !locked; + std::unique_lock lock(jobsMutex); + jobsMutexCondition.wait(lock, [this] { + return !jobs.empty() || !working; }); + if (!working || failed) { + break; + } + job = jobs.front(); + jobs.pop(); + + busyWorkers++; } - } catch (std::exception& err) { - busyWorkers--; - if (onJobFailed) { - onJobFailed(job); - } - if (stopOnFail) { - std::lock_guard lock(jobsMutex); - failed = true; - } - logger.error() << "uncaught exception: " << err.what(); - } - jobsDone++; - } - } -public: - ThreadPool( - std::string name, - supplier>> workersSupplier, - consumer resultConsumer - ) : logger(std::move(name)), resultConsumer(resultConsumer) { - const uint num_threads = std::thread::hardware_concurrency(); - for (uint i = 0; i < num_threads; i++) { - threads.emplace_back(&ThreadPool::threadLoop, this, i, workersSupplier()); - workersBlocked.emplace_back(); - } - } - ~ThreadPool(){ - terminate(); - } - - bool isActive() const override { - return working; - } - - void terminate() override { - if (!working) { - return; - } - { - std::lock_guard lock(jobsMutex); - working = false; - } - { - std::lock_guard lock(resultsMutex); - while (!results.empty()) { - ThreadPoolResult entry = results.front(); - results.pop(); - if (!standaloneResults) { - entry.locked = false; - entry.variable.notify_all(); - } - } - } - - jobsMutexCondition.notify_all(); - for (auto& thread : threads) { - thread.join(); - } - } - - void update() override { - if (!working) { - return; - } - if (failed) { - throw std::runtime_error("some job failed"); - } - - bool complete = false; - { - std::lock_guard lock(resultsMutex); - while (!results.empty()) { - ThreadPoolResult entry = results.front(); - results.pop(); - try { - resultConsumer(entry.entry); + R result = (*worker)(job); + { + std::lock_guard lock(resultsMutex); + results.push(ThreadPoolResult { + job, variable, index, locked, result}); + if (!standaloneResults) { + locked = true; + } + busyWorkers--; + } + if (!standaloneResults) { + std::unique_lock lock(mutex); + variable.wait(lock, [&] { + return !working || !locked; + }); + } } catch (std::exception& err) { - logger.error() << err.what(); + busyWorkers--; if (onJobFailed) { - onJobFailed(entry.job); + onJobFailed(job); } if (stopOnFail) { - std::lock_guard jobsLock(jobsMutex); + std::lock_guard lock(jobsMutex); failed = true; - complete = false; } - break; - } - - if (!standaloneResults) { - entry.locked = false; - entry.variable.notify_all(); - } - } - - if (onComplete && busyWorkers == 0) { - std::lock_guard jobsLock(jobsMutex); - if (jobs.empty()) { - onComplete(); - complete = true; + logger.error() << "uncaught exception: " << err.what(); } + jobsDone++; } } - if (failed) { - throw std::runtime_error("some job failed"); + public: + ThreadPool( + std::string name, + supplier>> workersSupplier, + consumer resultConsumer + ) + : logger(std::move(name)), resultConsumer(resultConsumer) { + const uint num_threads = std::thread::hardware_concurrency(); + for (uint i = 0; i < num_threads; i++) { + threads.emplace_back( + &ThreadPool::threadLoop, this, i, workersSupplier() + ); + workersBlocked.emplace_back(); + } } - if (complete) { + ~ThreadPool() { terminate(); } - } - void enqueueJob(const std::shared_ptr& job) { - { - std::lock_guard lock(jobsMutex); - jobs.push(job); + bool isActive() const override { + return working; } - jobsMutexCondition.notify_one(); - } - /// @brief If false: worker will be blocked until it's result performed - void setStandaloneResults(bool flag) { - standaloneResults = flag; - } + void terminate() override { + if (!working) { + return; + } + { + std::lock_guard lock(jobsMutex); + working = false; + } + { + std::lock_guard lock(resultsMutex); + while (!results.empty()) { + ThreadPoolResult entry = results.front(); + results.pop(); + if (!standaloneResults) { + entry.locked = false; + entry.variable.notify_all(); + } + } + } - void setStopOnFail(bool flag) { - stopOnFail = flag; - } - - /// @brief onJobFailed called on exception thrown in worker thread. - /// Use engine.postRunnable when calling terminate() - void setOnJobFailed(consumer callback) { - this->onJobFailed = callback; - } - - /// @brief onComplete called in ThreadPool.update() when all jobs done - /// if ThreadPool was not terminated - void setOnComplete(runnable callback) { - this->onComplete = callback; - } - - uint getWorkTotal() const override { - return jobs.size()+jobsDone+busyWorkers; - } - - uint getWorkDone() const override { - return jobsDone; - } - - virtual void waitForEnd() override { - using namespace std::chrono_literals; - while (working) { - std::this_thread::sleep_for(2ms); - update(); + jobsMutexCondition.notify_all(); + for (auto& thread : threads) { + thread.join(); + } } - } - uint getWorkersCount() const { - return threads.size(); - } -}; + void update() override { + if (!working) { + return; + } + if (failed) { + throw std::runtime_error("some job failed"); + } -} // namespace util + bool complete = false; + { + std::lock_guard lock(resultsMutex); + while (!results.empty()) { + ThreadPoolResult entry = results.front(); + results.pop(); -#endif // UTIL_THREAD_POOL_HPP_ + try { + resultConsumer(entry.entry); + } catch (std::exception& err) { + logger.error() << err.what(); + if (onJobFailed) { + onJobFailed(entry.job); + } + if (stopOnFail) { + std::lock_guard jobsLock(jobsMutex); + failed = true; + complete = false; + } + break; + } + + if (!standaloneResults) { + entry.locked = false; + entry.variable.notify_all(); + } + } + + if (onComplete && busyWorkers == 0) { + std::lock_guard jobsLock(jobsMutex); + if (jobs.empty()) { + onComplete(); + complete = true; + } + } + } + if (failed) { + throw std::runtime_error("some job failed"); + } + if (complete) { + terminate(); + } + } + + void enqueueJob(const std::shared_ptr& job) { + { + std::lock_guard lock(jobsMutex); + jobs.push(job); + } + jobsMutexCondition.notify_one(); + } + + /// @brief If false: worker will be blocked until it's result performed + void setStandaloneResults(bool flag) { + standaloneResults = flag; + } + + void setStopOnFail(bool flag) { + stopOnFail = flag; + } + + /// @brief onJobFailed called on exception thrown in worker thread. + /// Use engine.postRunnable when calling terminate() + void setOnJobFailed(consumer callback) { + this->onJobFailed = callback; + } + + /// @brief onComplete called in ThreadPool.update() when all jobs done + /// if ThreadPool was not terminated + void setOnComplete(runnable callback) { + this->onComplete = callback; + } + + uint getWorkTotal() const override { + return jobs.size() + jobsDone + busyWorkers; + } + + uint getWorkDone() const override { + return jobsDone; + } + + virtual void waitForEnd() override { + using namespace std::chrono_literals; + while (working) { + std::this_thread::sleep_for(2ms); + update(); + } + } + + uint getWorkersCount() const { + return threads.size(); + } + }; + +} // namespace util + +#endif // UTIL_THREAD_POOL_HPP_ diff --git a/src/util/command_line.cpp b/src/util/command_line.cpp index 16178662..1f988e5c 100644 --- a/src/util/command_line.cpp +++ b/src/util/command_line.cpp @@ -1,12 +1,12 @@ #include "command_line.hpp" -#include "../files/engine_paths.hpp" - -#include -#include -#include #include +#include +#include #include +#include + +#include "../files/engine_paths.hpp" namespace fs = std::filesystem; @@ -16,7 +16,8 @@ class ArgsReader { int argc; int pos = 0; public: - ArgsReader(int argc, char** argv) : argv(argv), argc(argc) {} + ArgsReader(int argc, char** argv) : argv(argv), argc(argc) { + } void skip() { pos++; @@ -39,11 +40,13 @@ public: } }; -bool perform_keyword(ArgsReader& reader, const std::string& keyword, EnginePaths& paths) { +bool perform_keyword( + ArgsReader& reader, const std::string& keyword, EnginePaths& paths +) { if (keyword == "--res") { auto token = reader.next(); if (!fs::is_directory(fs::path(token))) { - throw std::runtime_error(token+" is not a directory"); + throw std::runtime_error(token + " is not a directory"); } paths.setResources(fs::path(token)); std::cout << "resources folder: " << token << std::endl; diff --git a/src/util/command_line.hpp b/src/util/command_line.hpp index 179ece70..0dd157d7 100644 --- a/src/util/command_line.hpp +++ b/src/util/command_line.hpp @@ -6,4 +6,4 @@ class EnginePaths; /// @return false if engine start can bool parse_cmdline(int argc, char** argv, EnginePaths& paths); -#endif // UTIL_COMMAND_LINE_HPP_ +#endif // UTIL_COMMAND_LINE_HPP_ diff --git a/src/util/data_io.hpp b/src/util/data_io.hpp index 131fa63f..dbfae0c6 100644 --- a/src/util/data_io.hpp +++ b/src/util/data_io.hpp @@ -6,51 +6,46 @@ namespace dataio { /* Read big-endian 16 bit signed integer from bytes */ inline int16_t read_int16_big(const ubyte* src, size_t offset) { - return (src[offset] << 8) | - (src[offset+1]); + return (src[offset] << 8) | (src[offset + 1]); } /* Read big-endian 32 bit signed integer from bytes */ inline int32_t read_int32_big(const ubyte* src, size_t offset) { - return (src[offset] << 24) | - (src[offset+1] << 16) | - (src[offset+2] << 8) | - (src[offset+3]); + return (src[offset] << 24) | (src[offset + 1] << 16) | + (src[offset + 2] << 8) | (src[offset + 3]); } /* Read big-endian 64 bit signed integer from bytes */ inline int64_t read_int64_big(const ubyte* src, size_t offset) { - return (int64_t(src[offset]) << 56) | - (int64_t(src[offset+1]) << 48) | - (int64_t(src[offset+2]) << 40) | - (int64_t(src[offset+3]) << 32) | - (int64_t(src[offset+4]) << 24) | - (int64_t(src[offset+5]) << 16) | - (int64_t(src[offset+6]) << 8) | - (int64_t(src[offset+7])); + return (int64_t(src[offset]) << 56) | (int64_t(src[offset + 1]) << 48) | + (int64_t(src[offset + 2]) << 40) | + (int64_t(src[offset + 3]) << 32) | + (int64_t(src[offset + 4]) << 24) | + (int64_t(src[offset + 5]) << 16) | + (int64_t(src[offset + 6]) << 8) | (int64_t(src[offset + 7])); } /* Write big-endian 16 bit signed integer to bytes */ inline void write_int16_big(int16_t value, ubyte* dest, size_t offset) { - dest[offset] = (char) (value >> 8 & 255); - dest[offset+1] = (char) (value >> 0 & 255); + dest[offset] = (char)(value >> 8 & 255); + dest[offset + 1] = (char)(value >> 0 & 255); } /* Write big-endian 32 bit signed integer to bytes */ inline void write_int32_big(int32_t value, ubyte* dest, size_t offset) { - dest[offset] = (char) (value >> 24 & 255); - dest[offset+1] = (char) (value >> 16 & 255); - dest[offset+2] = (char) (value >> 8 & 255); - dest[offset+3] = (char) (value >> 0 & 255); + dest[offset] = (char)(value >> 24 & 255); + dest[offset + 1] = (char)(value >> 16 & 255); + dest[offset + 2] = (char)(value >> 8 & 255); + dest[offset + 3] = (char)(value >> 0 & 255); } /* Write big-endian 64 bit signed integer to bytes */ inline void write_int64_big(int64_t value, ubyte* dest, size_t offset) { - dest[offset] = (char) (value >> 56 & 255); - dest[offset+1] = (char) (value >> 48 & 255); - dest[offset+2] = (char) (value >> 40 & 255); - dest[offset+3] = (char) (value >> 32 & 255); + dest[offset] = (char)(value >> 56 & 255); + dest[offset + 1] = (char)(value >> 48 & 255); + dest[offset + 2] = (char)(value >> 40 & 255); + dest[offset + 3] = (char)(value >> 32 & 255); - dest[offset+4] = (char) (value >> 24 & 255); - dest[offset+5] = (char) (value >> 16 & 255); - dest[offset+6] = (char) (value >> 8 & 255); - dest[offset+7] = (char) (value >> 0 & 255); + dest[offset + 4] = (char)(value >> 24 & 255); + dest[offset + 5] = (char)(value >> 16 & 255); + dest[offset + 6] = (char)(value >> 8 & 255); + dest[offset + 7] = (char)(value >> 0 & 255); } } -#endif // UTIL_DATA_IO_HPP_ +#endif // UTIL_DATA_IO_HPP_ diff --git a/src/util/listutil.cpp b/src/util/listutil.cpp index a9bc5000..ccbe0d15 100644 --- a/src/util/listutil.cpp +++ b/src/util/listutil.cpp @@ -1,14 +1,15 @@ #include "listutil.hpp" -#include "../util/stringutil.hpp" #include +#include "../util/stringutil.hpp" + std::string util::to_string(const std::vector& vec) { std::stringstream ss; ss << "["; for (size_t i = 0; i < vec.size(); i++) { ss << util::quote(vec[1]); - if (i < vec.size()-1) { + if (i < vec.size() - 1) { ss << ", "; } } diff --git a/src/util/listutil.hpp b/src/util/listutil.hpp index 00d73cb7..dc96b945 100644 --- a/src/util/listutil.hpp +++ b/src/util/listutil.hpp @@ -2,12 +2,12 @@ #define UTIL_LISTUTIL_HPP_ #include -#include -#include #include +#include +#include namespace util { - template + template bool contains(const std::vector& vec, const T& value) { return std::find(vec.begin(), vec.end(), value) != vec.end(); } @@ -15,4 +15,4 @@ namespace util { std::string to_string(const std::vector& vec); } -#endif // UTIL_LISTUTIL_HPP_ +#endif // UTIL_LISTUTIL_HPP_ diff --git a/src/util/platform.cpp b/src/util/platform.cpp index fa45ca11..c7b71bbf 100644 --- a/src/util/platform.cpp +++ b/src/util/platform.cpp @@ -1,11 +1,12 @@ #include "platform.hpp" -#include "../typedefs.hpp" - -#include -#include #include + +#include #include +#include + +#include "../typedefs.hpp" #ifdef _WIN32 #include @@ -20,22 +21,30 @@ void platform::configure_encoding() { std::string platform::detect_locale() { LCID lcid = GetThreadLocale(); - wchar_t preferredLocaleName[LOCALE_NAME_MAX_LENGTH];//locale name format: ll-CC - if (LCIDToLocaleName(lcid, preferredLocaleName, LOCALE_NAME_MAX_LENGTH, 0) == 0) { - std::cerr << "error in platform::detect_locale! LCIDToLocaleName failed." << std::endl; + wchar_t preferredLocaleName[LOCALE_NAME_MAX_LENGTH]; // locale name format: + // ll-CC + if (LCIDToLocaleName( + lcid, preferredLocaleName, LOCALE_NAME_MAX_LENGTH, 0 + ) == 0) { + std::cerr + << "error in platform::detect_locale! LCIDToLocaleName failed." + << std::endl; } - //ll_CC format - return util::wstr2str_utf8(preferredLocaleName).replace(2, 1, "_").substr(0, 5); + // ll_CC format + return util::wstr2str_utf8(preferredLocaleName) + .replace(2, 1, "_") + .substr(0, 5); } #else -void platform::configure_encoding(){ +void platform::configure_encoding() { } std::string platform::detect_locale() { std::string programLocaleName = setlocale(LC_ALL, nullptr); - std::string preferredLocaleName = setlocale(LC_ALL, ""); //locale name format: ll_CC.encoding + std::string preferredLocaleName = + setlocale(LC_ALL, ""); // locale name format: ll_CC.encoding setlocale(LC_ALL, programLocaleName.c_str()); return preferredLocaleName.substr(0, 5); diff --git a/src/util/platform.hpp b/src/util/platform.hpp index e82a48b5..8b04ed5f 100644 --- a/src/util/platform.hpp +++ b/src/util/platform.hpp @@ -9,4 +9,4 @@ namespace platform { std::string detect_locale(); } -#endif // UTIL_PLATFORM_HPP_ +#endif // UTIL_PLATFORM_HPP_ diff --git a/src/util/stringutil.cpp b/src/util/stringutil.cpp index bc155c6a..c494a759 100644 --- a/src/util/stringutil.cpp +++ b/src/util/stringutil.cpp @@ -1,25 +1,39 @@ #include "stringutil.hpp" +#include #include -#include #include +#include #include #include -#include -// TODO: finish +// TODO: finish std::string util::escape(const std::string& s) { std::stringstream ss; ss << '"'; for (char c : s) { switch (c) { - case '\n': ss << "\\n"; break; - case '\r': ss << "\\r"; break; - case '\t': ss << "\\t"; break; - case '\f': ss << "\\f"; break; - case '\b': ss << "\\b"; break; - case '"': ss << "\\\""; break; - case '\\': ss << "\\\\"; break; + case '\n': + ss << "\\n"; + break; + case '\r': + ss << "\\r"; + break; + case '\t': + ss << "\\t"; + break; + case '\f': + ss << "\\f"; + break; + case '\b': + ss << "\\b"; + break; + case '"': + ss << "\\\""; + break; + case '\\': + ss << "\\\\"; + break; default: if (c < ' ') { ss << "\\" << std::oct << uint(ubyte(c)); @@ -42,7 +56,7 @@ std::wstring util::lfill(std::wstring s, uint length, wchar_t c) { return s; } std::wstringstream ss; - for (uint i = 0; i < length-s.length(); i++) { + for (uint i = 0; i < length - s.length(); i++) { ss << c; } ss << s; @@ -55,7 +69,7 @@ std::wstring util::rfill(std::wstring s, uint length, wchar_t c) { } std::wstringstream ss; ss << s; - for (uint i = 0; i < length-s.length(); i++) { + for (uint i = 0; i < length - s.length(); i++) { ss << c; } return ss.str(); @@ -93,24 +107,23 @@ struct utf_t { const utf_t utf[] = { /* mask lead beg end bits */ - {(char)0b00111111, (char)0b10000000, 0, 0, 6}, - {(char)0b01111111, (char)0b00000000, 0000, 0177, 7}, - {(char)0b00011111, (char)0b11000000, 0200, 03777, 5}, - {(char)0b00001111, (char)0b11100000, 04000, 0177777, 4}, + {(char)0b00111111, (char)0b10000000, 0, 0, 6}, + {(char)0b01111111, (char)0b00000000, 0000, 0177, 7}, + {(char)0b00011111, (char)0b11000000, 0200, 03777, 5}, + {(char)0b00001111, (char)0b11100000, 04000, 0177777, 4}, {(char)0b00000111, (char)0b11110000, 0200000, 04177777, 3}, {0, 0, 0, 0, 0}, }; - inline uint utf8_len(ubyte cp) { uint len = 0; for (const utf_t* u = utf; u->mask; ++u) { - if((cp >= u->beg) && (cp <= u->end)) { + if ((cp >= u->beg) && (cp <= u->end)) { break; } ++len; } - if(len > 4) /* Out of bounds */ + if (len > 4) /* Out of bounds */ throw std::runtime_error("utf-8 decode error"); return len; @@ -121,7 +134,7 @@ extern uint32_t util::decode_utf8(uint& size, const char* chr) { int shift = utf[0].bits_stored * (size - 1); uint32_t code = (*chr++ & utf[size].mask) << shift; - for(uint i = 1; i < size; ++i, ++chr) { + for (uint i = 1; i < size; ++i, ++chr) { shift -= utf[0].bits_stored; code |= ((char)*chr & utf[0].mask) << shift; } @@ -153,16 +166,14 @@ std::wstring util::str2wstr_utf8(const std::string& s) { bool util::is_integer(const std::string& text) { for (char c : text) { - if (c < '0' || c > '9') - return false; + if (c < '0' || c > '9') return false; } return true; } bool util::is_integer(const std::wstring& text) { for (wchar_t c : text) { - if (c < L'0' || c > L'9') - return false; + if (c < L'0' || c > L'9') return false; } return true; } @@ -170,26 +181,31 @@ bool util::is_integer(const std::wstring& text) { bool util::is_valid_filename(const std::wstring& name) { for (wchar_t c : name) { if (c < 31 || c == '/' || c == '\\' || c == '<' || c == '>' || - c == ':' || c == '"' || c == '|' || c == '?' || c == '*'){ + c == ':' || c == '"' || c == '|' || c == '?' || c == '*') { return false; } } return true; } -void util::ltrim(std::string &s) { +void util::ltrim(std::string& s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) { - return !std::isspace(ch); - })); + return !std::isspace(ch); + })); } -void util::rtrim(std::string &s) { - s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) { - return !std::isspace(ch); - }).base(), s.end()); +void util::rtrim(std::string& s) { + s.erase( + std::find_if( + s.rbegin(), + s.rend(), + [](unsigned char ch) { return !std::isspace(ch); } + ).base(), + s.end() + ); } -void util::trim(std::string &s) { +void util::trim(std::string& s) { rtrim(s); ltrim(s); } @@ -198,7 +214,7 @@ std::string util::to_string(double x) { std::stringstream ss; ss << std::setprecision(6); ss << x; - return ss.str(); + return ss.str(); } std::wstring util::to_wstring(double x, int precision) { @@ -207,59 +223,56 @@ std::wstring util::to_wstring(double x, int precision) { return ss.str(); } -const char B64ABC[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789" - "+/"; +const char B64ABC[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789" + "+/"; inline ubyte base64_decode_char(char c) { - if (c >= 'A' && c <= 'Z') - return c - 'A'; - if (c >= 'a' && c <= 'z') - return c - 'a' + 26; - if (c >= '0' && c <= '9') - return c - '0' + 52; - if (c == '+') - return 62; - if (c == '/') - return 63; + if (c >= 'A' && c <= 'Z') return c - 'A'; + if (c >= 'a' && c <= 'z') return c - 'a' + 26; + if (c >= '0' && c <= '9') return c - '0' + 52; + if (c == '+') return 62; + if (c == '/') return 63; return 0; } inline void base64_encode_(const ubyte* segment, char* output) { output[0] = B64ABC[(segment[0] & 0b11111100) >> 2]; - output[1] = B64ABC[((segment[0] & 0b11) << 4) | ((segment[1] & 0b11110000) >> 4)]; - output[2] = B64ABC[((segment[1] & 0b1111) << 2) | ((segment[2] & 0b11000000) >> 6)]; + output[1] = + B64ABC[((segment[0] & 0b11) << 4) | ((segment[1] & 0b11110000) >> 4)]; + output[2] = + B64ABC[((segment[1] & 0b1111) << 2) | ((segment[2] & 0b11000000) >> 6)]; output[3] = B64ABC[segment[2] & 0b111111]; } std::string util::base64_encode(const ubyte* data, size_t size) { std::stringstream ss; - size_t fullsegments = (size/3)*3; + size_t fullsegments = (size / 3) * 3; size_t i = 0; - for (; i < fullsegments; i+=3) { + for (; i < fullsegments; i += 3) { char output[] = "===="; - base64_encode_(data+i, output); + base64_encode_(data + i, output); ss << output; } ubyte ending[3] {}; for (; i < size; i++) { - ending[i-fullsegments] = data[i]; + ending[i - fullsegments] = data[i]; } - size_t trailing = size-fullsegments; + size_t trailing = size - fullsegments; { char output[] = "===="; output[0] = B64ABC[(ending[0] & 0b11111100) >> 2]; - output[1] = B64ABC[((ending[0] & 0b11) << 4) | - ((ending[1] & 0b11110000) >> 4)]; + output[1] = + B64ABC[((ending[0] & 0b11) << 4) | ((ending[1] & 0b11110000) >> 4)]; if (trailing > 1) - output[2] = B64ABC[((ending[1] & 0b1111) << 2) | - ((ending[2] & 0b11000000) >> 6)]; - if (trailing > 2) - output[3] = B64ABC[ending[2] & 0b111111]; + output[2] = B64ABC + [((ending[1] & 0b1111) << 2) | ((ending[2] & 0b11000000) >> 6)]; + if (trailing > 2) output[3] = B64ABC[ending[2] & 0b111111]; ss << output; } return ss.str(); @@ -273,7 +286,7 @@ std::string util::mangleid(uint64_t value) { } std::vector util::base64_decode(const char* str, size_t size) { - std::vector bytes((size/4)*3); + std::vector bytes((size / 4) * 3); ubyte* dst = bytes.data(); for (size_t i = 0; i < size;) { ubyte a = base64_decode_char(ubyte(str[i++])); @@ -286,8 +299,8 @@ std::vector util::base64_decode(const char* str, size_t size) { } if (size >= 2) { size_t outsize = bytes.size(); - if (str[size-1] == '=') outsize--; - if (str[size-2] == '=') outsize--; + if (str[size - 1] == '=') outsize--; + if (str[size - 2] == '=') outsize--; bytes.resize(outsize); } return bytes; @@ -297,13 +310,14 @@ std::vector util::base64_decode(const std::string& str) { return base64_decode(str.c_str(), str.size()); } -int util::replaceAll(std::string& str, const std::string& from, const std::string& to) { +int util::replaceAll( + std::string& str, const std::string& from, const std::string& to +) { int count = 0; size_t offset = 0; while (true) { size_t start_pos = str.find(from, offset); - if(start_pos == std::string::npos) - break; + if (start_pos == std::string::npos) break; str.replace(start_pos, from.length(), to); offset = start_pos + to.length(); count++; @@ -321,7 +335,7 @@ double util::parse_double(const std::string& str) { if (ss.fail()) { throw std::runtime_error("invalid number format"); } - return d; + return d; } double util::parse_double(const std::string& str, size_t offset, size_t len) { @@ -347,15 +361,14 @@ std::wstring util::upper_case(const std::wstring& str) { } std::wstring util::capitalized(const std::wstring& str) { - if (str.empty()) - return str; + if (str.empty()) return str; static const std::locale loc(""); - return std::wstring({static_cast(std::toupper(str[0], loc))}) + str.substr(1); + return std::wstring({static_cast(std::toupper(str[0], loc))}) + + str.substr(1); } std::wstring util::pascal_case(const std::wstring& str) { - if (str.empty()) - return str; + if (str.empty()) return str; static const std::locale loc(""); std::wstring result = str; bool upper = true; @@ -375,14 +388,15 @@ std::string util::id_to_caption(const std::string& id) { std::string result = id; size_t index = result.find(':'); - if (index < result.length()-1) { - result = result.substr(index+1); + if (index < result.length() - 1) { + result = result.substr(index + 1); } else { return ""; } size_t offset = 0; - for (; offset < result.length() && result[offset] == '_'; offset++) {} - + for (; offset < result.length() && result[offset] == '_'; offset++) { + } + for (; offset < result.length(); offset++) { if (result[offset] == '_') { result[offset] = ' '; @@ -427,11 +441,10 @@ std::vector util::split(const std::wstring& str, char delimiter) { std::string util::format_data_size(size_t size) { if (size < 1024) { - return std::to_string(size)+" B"; + return std::to_string(size) + " B"; } const std::string postfixes[] { - " B", " KiB", " MiB", " GiB", " TiB", " EiB", " PiB" - }; + " B", " KiB", " MiB", " GiB", " TiB", " EiB", " PiB"}; int group = 0; size_t remainder = 0; while (size >= 1024) { @@ -439,18 +452,19 @@ std::string util::format_data_size(size_t size) { remainder = size % 1024; size /= 1024; } - return std::to_string(size)+"."+ - std::to_string(static_cast(round(remainder/1024.0f)))+ + return std::to_string(size) + "." + + std::to_string(static_cast(round(remainder / 1024.0f))) + postfixes[group]; } -std::pair util::split_at(std::string_view view, char c) { +std::pair util::split_at( + std::string_view view, char c +) { size_t idx = view.find(c); if (idx == std::string::npos) { - throw std::runtime_error(util::quote(std::string({c}))+" not found"); + throw std::runtime_error(util::quote(std::string({c})) + " not found"); } return std::make_pair( - std::string(view.substr(0, idx)), - std::string(view.substr(idx+1)) + std::string(view.substr(0, idx)), std::string(view.substr(idx + 1)) ); } diff --git a/src/util/stringutil.hpp b/src/util/stringutil.hpp index 273a9264..c25bd182 100644 --- a/src/util/stringutil.hpp +++ b/src/util/stringutil.hpp @@ -1,13 +1,13 @@ #ifndef UTIL_STRINGUTIL_HPP_ #define UTIL_STRINGUTIL_HPP_ -#include "../typedefs.hpp" - #include #include +#include "../typedefs.hpp" + namespace util { - /// @brief Function used for string serialization in text formats + /// @brief Function used for string serialization in text formats std::string escape(const std::string& s); /// @brief Function used for error messages @@ -18,15 +18,15 @@ namespace util { uint encode_utf8(uint32_t c, ubyte* bytes); uint32_t decode_utf8(uint& size, const char* bytes); - std::string wstr2str_utf8(const std::wstring &ws); - std::wstring str2wstr_utf8(const std::string &s); + std::string wstr2str_utf8(const std::wstring& ws); + std::wstring str2wstr_utf8(const std::string& s); bool is_integer(const std::string& text); bool is_integer(const std::wstring& text); - bool is_valid_filename(const std::wstring &name); + bool is_valid_filename(const std::wstring& name); - void ltrim(std::string &s); - void rtrim(std::string &s); - void trim(std::string &s); + void ltrim(std::string& s); + void rtrim(std::string& s); + void trim(std::string& s); std::string to_string(double x); std::wstring to_wstring(double x, int precision); @@ -37,7 +37,9 @@ namespace util { std::string mangleid(uint64_t value); - int replaceAll(std::string& str, const std::string& from, const std::string& to); + int replaceAll( + std::string& str, const std::string& from, const std::string& to + ); double parse_double(const std::string& str); double parse_double(const std::string& str, size_t offset, size_t len); @@ -61,4 +63,4 @@ namespace util { std::pair split_at(std::string_view view, char c); } -#endif // UTIL_STRINGUTIL_HPP_ +#endif // UTIL_STRINGUTIL_HPP_ diff --git a/src/util/timeutil.cpp b/src/util/timeutil.cpp index 78f1cf39..1c24ba1c 100644 --- a/src/util/timeutil.cpp +++ b/src/util/timeutil.cpp @@ -2,21 +2,24 @@ #include -using std::chrono::high_resolution_clock; using std::chrono::duration_cast; +using std::chrono::high_resolution_clock; using std::chrono::microseconds; timeutil::Timer::Timer() { start = high_resolution_clock::now(); } int64_t timeutil::Timer::stop() { - return duration_cast(high_resolution_clock::now()-start).count(); + return duration_cast(high_resolution_clock::now() - start) + .count(); } -timeutil::ScopeLogTimer::ScopeLogTimer(long long id) : scopeid_(id) {} +timeutil::ScopeLogTimer::ScopeLogTimer(long long id) : scopeid_(id) { +} timeutil::ScopeLogTimer::~ScopeLogTimer() { - std::cout << "Scope "<< scopeid_ <<" finished in "<< ScopeLogTimer::stop() << " micros. \n"; + std::cout << "Scope " << scopeid_ << " finished in " + << ScopeLogTimer::stop() << " micros. \n"; } void timeutil::from_value(float value, int& hour, int& minute, int& second) { diff --git a/src/util/timeutil.hpp b/src/util/timeutil.hpp index 75f72bfd..4e032d9d 100644 --- a/src/util/timeutil.hpp +++ b/src/util/timeutil.hpp @@ -1,9 +1,10 @@ #ifndef UTIL_TIMEUTIL_HPP_ #define UTIL_TIMEUTIL_HPP_ -#include "../typedefs.hpp" #include +#include "../typedefs.hpp" + namespace timeutil { class Timer { std::chrono::high_resolution_clock::time_point start; @@ -12,13 +13,13 @@ namespace timeutil { int64_t stop(); }; - /** + /** * Timer that stops and prints time when destructor called * @example: * { // some scope (custom, function, if/else, cycle etc.) * timeutil::ScopeLogTimer scopeclock(); * ... - * } + * } */ class ScopeLogTimer : public Timer { long long scopeid_; @@ -30,8 +31,8 @@ namespace timeutil { inline constexpr float time_value(float hour, float minute, float second) { return (hour + (minute + second / 60.0f) / 60.0f) / 24.0f; } - + void from_value(float value, int& hour, int& minute, int& second); } -#endif // UTIL_TIMEUTIL_HPP_ +#endif // UTIL_TIMEUTIL_HPP_ diff --git a/src/voxels/Block.cpp b/src/voxels/Block.cpp index a15506e7..4abdd339 100644 --- a/src/voxels/Block.cpp +++ b/src/voxels/Block.cpp @@ -7,12 +7,18 @@ std::string to_string(BlockModel model) { switch (model) { - case BlockModel::none: return "none"; - case BlockModel::block: return "block"; - case BlockModel::xsprite: return "X"; - case BlockModel::aabb: return "aabb"; - case BlockModel::custom: return "custom"; - default: return "unknown"; + case BlockModel::none: + return "none"; + case BlockModel::block: + return "block"; + case BlockModel::xsprite: + return "X"; + case BlockModel::aabb: + return "aabb"; + case BlockModel::custom: + return "custom"; + default: + return "unknown"; } } @@ -32,8 +38,7 @@ std::optional BlockModel_from(std::string_view str) { } CoordSystem::CoordSystem(glm::ivec3 axisX, glm::ivec3 axisY, glm::ivec3 axisZ) - : axisX(axisX), axisY(axisY), axisZ(axisZ) -{ + : axisX(axisX), axisY(axisY), axisZ(axisZ) { fix = glm::ivec3(0); if (isVectorHasNegatives(axisX)) fix -= axisX; if (isVectorHasNegatives(axisY)) fix -= axisY; @@ -50,39 +55,50 @@ void CoordSystem::transform(AABB& aabb) const { aabb.b += fix; } -const BlockRotProfile BlockRotProfile::NONE {"none", { - {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, // North - {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, // East - {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, // South - {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, // West - {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, // Up - {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, // Down -}}; +const BlockRotProfile BlockRotProfile::NONE { + "none", + { + {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, // North + {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, // East + {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, // South + {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, // West + {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, // Up + {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, // Down + }}; +const BlockRotProfile BlockRotProfile::PIPE { + "pipe", + { + {{1, 0, 0}, {0, 0, 1}, {0, -1, 0}}, // North + {{0, 0, 1}, {-1, 0, 0}, {0, -1, 0}}, // East + {{-1, 0, 0}, {0, 0, -1}, {0, -1, 0}}, // South + {{0, 0, -1}, {1, 0, 0}, {0, -1, 0}}, // West + {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, // Up + {{1, 0, 0}, {0, -1, 0}, {0, 0, -1}}, // Down + }}; -const BlockRotProfile BlockRotProfile::PIPE {"pipe", { - { { 1, 0, 0 }, { 0, 0, 1 }, { 0, -1, 0 }}, // North - { { 0, 0, 1 }, {-1, 0, 0 }, { 0, -1, 0 }}, // East - { {-1, 0, 0 }, { 0, 0,-1 }, { 0, -1, 0 }}, // South - { { 0, 0,-1 }, { 1, 0, 0 }, { 0, -1, 0 }}, // West - { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 }}, // Up - { { 1, 0, 0 }, { 0,-1, 0 }, { 0, 0,-1 }}, // Down -}}; - -const BlockRotProfile BlockRotProfile::PANE {"pane", { - { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 }}, // North - { { 0, 0,-1 }, { 0, 1, 0 }, { 1, 0, 0 }}, // East - { {-1, 0, 0 }, { 0, 1, 0 }, { 0, 0,-1 }}, // South - { { 0, 0, 1 }, { 0, 1, 0 }, {-1, 0, 0 }}, // West -}}; +const BlockRotProfile BlockRotProfile::PANE { + "pane", + { + {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, // North + {{0, 0, -1}, {0, 1, 0}, {1, 0, 0}}, // East + {{-1, 0, 0}, {0, 1, 0}, {0, 0, -1}}, // South + {{0, 0, 1}, {0, 1, 0}, {-1, 0, 0}}, // West + }}; Block::Block(const std::string& name) - : name(name), + : name(name), caption(util::id_to_caption(name)), - textureFaces {TEXTURE_NOTFOUND,TEXTURE_NOTFOUND,TEXTURE_NOTFOUND, - TEXTURE_NOTFOUND,TEXTURE_NOTFOUND,TEXTURE_NOTFOUND} -{} + textureFaces { + TEXTURE_NOTFOUND, + TEXTURE_NOTFOUND, + TEXTURE_NOTFOUND, + TEXTURE_NOTFOUND, + TEXTURE_NOTFOUND, + TEXTURE_NOTFOUND} { +} -Block::Block(std::string name, const std::string& texture) : name(std::move(name)), - textureFaces{texture,texture,texture,texture,texture,texture} -{} +Block::Block(std::string name, const std::string& texture) + : name(std::move(name)), + textureFaces {texture, texture, texture, texture, texture, texture} { +} diff --git a/src/voxels/Block.hpp b/src/voxels/Block.hpp index 5c0dcfaa..28a01389 100644 --- a/src/voxels/Block.hpp +++ b/src/voxels/Block.hpp @@ -1,13 +1,13 @@ #ifndef VOXELS_BLOCK_HPP_ #define VOXELS_BLOCK_HPP_ +#include +#include #include #include -#include -#include -#include "../maths/aabb.hpp" #include "../maths/UVRegion.hpp" +#include "../maths/aabb.hpp" #include "../typedefs.hpp" inline std::string BLOCK_ITEM_SUFFIX = ".item"; @@ -26,13 +26,13 @@ inline constexpr uint BLOCK_AABB_GRID = 16; inline std::string DEFAULT_MATERIAL = "base:stone"; struct block_funcs_set { - bool init: 1; - bool update: 1; - bool onplaced: 1; - bool onbroken: 1; - bool oninteract: 1; - bool randupdate: 1; - bool onblockstick: 1; + bool init : 1; + bool update : 1; + bool onplaced : 1; + bool onbroken : 1; + bool oninteract : 1; + bool randupdate : 1; + bool onblockstick : 1; }; struct CoordSystem { @@ -89,7 +89,6 @@ std::optional BlockModel_from(std::string_view str); using BoxModel = AABB; - /// @brief Common kit of block properties applied to groups of blocks struct BlockMaterial { std::string name; @@ -105,32 +104,34 @@ public: std::string const name; std::string caption; - + /// @brief Textures set applied to block sides - std::string textureFaces[6]; // -x,x, -y,y, -z,z - + std::string textureFaces[6]; // -x,x, -y,y, -z,z + std::vector modelTextures = {}; std::vector modelBoxes = {}; - std::vector modelExtraPoints = {}; //initially made for tetragons - std::vector modelUVs = {}; // boxes' tex-UVs also there + std::vector modelExtraPoints = + {}; // initially made for tetragons + std::vector modelUVs = {}; // boxes' tex-UVs also there /// @brief id of used BlockMaterial, may specify non-existing material std::string material = DEFAULT_MATERIAL; - /// @brief Light emission R, G, B, S (sky lights: sun, moon, radioactive clouds) + /// @brief Light emission R, G, B, S (sky lights: sun, moon, radioactive + /// clouds) uint8_t emission[4] {0, 0, 0, 0}; glm::i8vec3 size {1, 1, 1}; /// @brief Influences visible block sides for transparent blocks uint8_t drawGroup = 0; - + /// @brief Block model type BlockModel model = BlockModel::block; - + /// @brief Does the block passing lights into itself bool lightPassing = false; - + /// @brief Does the block passing top-down sky lights into itself bool skyLightPassing = false; @@ -139,70 +140,71 @@ public: /// @brief Does block model have vertex-based AO effect bool ambientOcclusion = true; - + /// @brief Is the block a physical obstacle bool obstacle = true; - + /// @brief Can the block be selected bool selectable = true; - - /// @brief Can the block be replaced with other. + + /// @brief Can the block be replaced with other. /// Examples of replaceable blocks: air, flower, water bool replaceable = false; - + /// @brief Can player destroy the block bool breakable = true; - + /// @brief Can the block be oriented different ways bool rotatable = false; - - /// @brief Can the block exist without physical support be a solid block below + + /// @brief Can the block exist without physical support be a solid block + /// below bool grounded = false; - + /// @brief Turns off block item generation bool hidden = false; - + /// @brief Set of block physical hitboxes std::vector hitboxes; - + /// @brief Set of available block rotations (coord-systems) BlockRotProfile rotations = BlockRotProfile::NONE; - + /// @brief Item will be picked on MMB click on the block - std::string pickingItem = name+BLOCK_ITEM_SUFFIX; - + std::string pickingItem = name + BLOCK_ITEM_SUFFIX; + /// @brief Block script name in blocks/ without extension - std::string scriptName = name.substr(name.find(':')+1); - + std::string scriptName = name.substr(name.find(':') + 1); + /// @brief Default block layout will be used by hud.open_block(...) std::string uiLayout = name; - + /// @brief Block inventory size. 0 - no inventory uint inventorySize = 0; // @brief Block tick interval (1 - 20tps, 2 - 10tps) - uint tickInterval = 1; + uint tickInterval = 1; /// @brief Runtime indices (content indexing results) struct { /// @brief block runtime integer id blockid_t id; - + /// @brief is the block completely opaque for render and raycast bool solid = true; - + /// @brief does the block emit any lights bool emissive = false; // @brief block size is greather than 1x1x1 bool extended = false; - + /// @brief set of hitboxes sets with all coord-systems precalculated std::vector hitboxes[BlockRotProfile::MAX_COUNT]; - + /// @brief set of block callbacks flags block_funcs_set funcsset {}; - + /// @brief picking item integer id itemid_t pickingItem = 0; } rt {}; @@ -216,4 +218,4 @@ inline glm::ivec3 get_ground_direction(const Block* def, int rotation) { return -def->rotations.variants[rotation].axisY; } -#endif // VOXELS_BLOCK_HPP_ +#endif // VOXELS_BLOCK_HPP_ diff --git a/src/voxels/Chunk.cpp b/src/voxels/Chunk.cpp index bd6dc0bc..6a299221 100644 --- a/src/voxels/Chunk.cpp +++ b/src/voxels/Chunk.cpp @@ -2,21 +2,20 @@ #include +#include "../content/ContentLUT.hpp" +#include "../items/Inventory.hpp" +#include "../lighting/Lightmap.hpp" #include "voxel.hpp" -#include "../items/Inventory.hpp" -#include "../content/ContentLUT.hpp" -#include "../lighting/Lightmap.hpp" - -Chunk::Chunk(int xpos, int zpos) : x(xpos), z(zpos){ +Chunk::Chunk(int xpos, int zpos) : x(xpos), z(zpos) { bottom = 0; top = CHUNK_H; } -bool Chunk::isEmpty(){ +bool Chunk::isEmpty() { int id = -1; - for (uint i = 0; i < CHUNK_VOL; i++){ - if (voxels[i].id != id){ + for (uint i = 0; i < CHUNK_VOL; i++) { + if (voxels[i].id != id) { if (id != -1) return false; else @@ -41,8 +40,9 @@ void Chunk::updateHeights() { } } -void Chunk::addBlockInventory(std::shared_ptr inventory, - uint x, uint y, uint z) { +void Chunk::addBlockInventory( + std::shared_ptr inventory, uint x, uint y, uint z +) { inventories[vox_index(x, y, z)] = std::move(inventory); flags.unsaved = true; } @@ -57,9 +57,9 @@ void Chunk::setBlockInventories(chunk_inventories_map map) { inventories = std::move(map); } -std::shared_ptr Chunk::getBlockInventory(uint x, uint y, uint z) const { - if (x >= CHUNK_W || y >= CHUNK_H || z >= CHUNK_D) - return nullptr; +std::shared_ptr Chunk::getBlockInventory(uint x, uint y, uint z) + const { + if (x >= CHUNK_W || y >= CHUNK_H || z >= CHUNK_D) return nullptr; const auto& found = inventories.find(vox_index(x, y, z)); if (found == inventories.end()) { return nullptr; @@ -68,7 +68,7 @@ std::shared_ptr Chunk::getBlockInventory(uint x, uint y, uint z) cons } std::unique_ptr Chunk::clone() const { - auto other = std::make_unique(x,z); + auto other = std::make_unique(x, z); for (uint i = 0; i < CHUNK_VOL; i++) { other->voxels[i] = voxels[i]; } @@ -76,7 +76,7 @@ std::unique_ptr Chunk::clone() const { return other; } -/** +/** Current chunk format: - byte-order: big-endian - [don't panic!] first and second bytes are separated for RLE efficiency @@ -94,11 +94,11 @@ std::unique_ptr Chunk::encode() const { auto buffer = std::make_unique(CHUNK_DATA_LEN); for (uint i = 0; i < CHUNK_VOL; i++) { buffer[i] = voxels[i].id >> 8; - buffer[CHUNK_VOL+i] = voxels[i].id & 0xFF; + buffer[CHUNK_VOL + i] = voxels[i].id & 0xFF; blockstate_t state = blockstate2int(voxels[i].state); - buffer[CHUNK_VOL*2 + i] = state >> 8; - buffer[CHUNK_VOL*3 + i] = state & 0xFF; + buffer[CHUNK_VOL * 2 + i] = state >> 8; + buffer[CHUNK_VOL * 3 + i] = state & 0xFF; } return buffer; } @@ -109,15 +109,16 @@ bool Chunk::decode(const ubyte* data) { ubyte bid1 = data[i]; ubyte bid2 = data[CHUNK_VOL + i]; - - ubyte bst1 = data[CHUNK_VOL*2 + i]; - ubyte bst2 = data[CHUNK_VOL*3 + i]; - vox.id = (static_cast(bid1) << 8) | - static_cast(bid2); + ubyte bst1 = data[CHUNK_VOL * 2 + i]; + ubyte bst2 = data[CHUNK_VOL * 3 + i]; + + vox.id = + (static_cast(bid1) << 8) | static_cast(bid2); vox.state = int2blockstate( - (static_cast(bst1) << 8) | - static_cast(bst2)); + (static_cast(bst1) << 8) | + static_cast(bst2) + ); } return true; } @@ -125,10 +126,11 @@ bool Chunk::decode(const ubyte* data) { void Chunk::convert(ubyte* data, const ContentLUT* lut) { for (uint i = 0; i < CHUNK_VOL; i++) { // see encode method to understand what the hell is going on here - blockid_t id = ((static_cast(data[i]) << 8) | - static_cast(data[CHUNK_VOL+i])); + blockid_t id = + ((static_cast(data[i]) << 8) | + static_cast(data[CHUNK_VOL + i])); blockid_t replacement = lut->blocks.getId(id); data[i] = replacement >> 8; - data[CHUNK_VOL+i] = replacement & 0xFF; + data[CHUNK_VOL + i] = replacement & 0xFF; } } diff --git a/src/voxels/Chunk.hpp b/src/voxels/Chunk.hpp index b04accc6..0d8b0d8a 100644 --- a/src/voxels/Chunk.hpp +++ b/src/voxels/Chunk.hpp @@ -1,16 +1,16 @@ #ifndef VOXELS_CHUNK_HPP_ #define VOXELS_CHUNK_HPP_ -#include #include -#include -#include "voxel.hpp" +#include +#include #include "../constants.hpp" #include "../lighting/Lightmap.hpp" +#include "voxel.hpp" -inline constexpr int CHUNK_DATA_LEN = CHUNK_VOL*4; +inline constexpr int CHUNK_DATA_LEN = CHUNK_VOL * 4; class Lightmap; class ContentLUT; @@ -20,7 +20,8 @@ namespace dynamic { class Map; } -using chunk_inventories_map = std::unordered_map>; +using chunk_inventories_map = + std::unordered_map>; class Chunk { public: @@ -29,13 +30,13 @@ public: voxel voxels[CHUNK_VOL] {}; Lightmap lightmap; struct { - bool modified: 1; - bool ready: 1; - bool loaded: 1; - bool lighted: 1; - bool unsaved: 1; - bool loadedLights: 1; - bool entities: 1; + bool modified : 1; + bool ready : 1; + bool loaded : 1; + bool lighted : 1; + bool unsaved : 1; + bool loadedLights : 1; + bool entities : 1; } flags {}; /// @brief Block inventories map where key is index of block in voxels array diff --git a/src/voxels/Chunks.cpp b/src/voxels/Chunks.cpp index 1b8aff43..a479569c 100644 --- a/src/voxels/Chunks.cpp +++ b/src/voxels/Chunks.cpp @@ -1,44 +1,51 @@ #include "Chunks.hpp" -#include "Chunk.hpp" -#include "voxel.hpp" -#include "Block.hpp" -#include "WorldGenerator.hpp" -#include "../content/Content.hpp" -#include "../lighting/Lightmap.hpp" -#include "../files/WorldFiles.hpp" -#include "../world/LevelEvents.hpp" -#include "../world/Level.hpp" -#include "../objects/Entities.hpp" -#include "../graphics/core/Mesh.hpp" -#include "../maths/voxmaths.hpp" -#include "../maths/aabb.hpp" -#include "../maths/rays.hpp" + +#include +#include + +#include +#include + #include "../coders/byte_utils.hpp" #include "../coders/json.hpp" - -#include -#include -#include -#include +#include "../content/Content.hpp" +#include "../files/WorldFiles.hpp" +#include "../graphics/core/Mesh.hpp" +#include "../lighting/Lightmap.hpp" +#include "../maths/aabb.hpp" +#include "../maths/rays.hpp" +#include "../maths/voxmaths.hpp" +#include "../objects/Entities.hpp" +#include "../world/Level.hpp" +#include "../world/LevelEvents.hpp" +#include "Block.hpp" +#include "Chunk.hpp" +#include "WorldGenerator.hpp" +#include "voxel.hpp" Chunks::Chunks( - uint32_t w, uint32_t d, - int32_t ox, int32_t oz, + uint32_t w, + uint32_t d, + int32_t ox, + int32_t oz, WorldFiles* wfile, Level* level -) : level(level), - indices(level->content->getIndices()), - chunks(w*d), - chunksSecond(w*d), - w(w), d(d), ox(ox), oz(oz), - worldFiles(wfile) -{ - volume = static_cast(w)*static_cast(d); +) + : level(level), + indices(level->content->getIndices()), + chunks(w * d), + chunksSecond(w * d), + w(w), + d(d), + ox(ox), + oz(oz), + worldFiles(wfile) { + volume = static_cast(w) * static_cast(d); chunksCount = 0; } voxel* Chunks::get(int32_t x, int32_t y, int32_t z) const { - x -= ox * CHUNK_W; + x -= ox * CHUNK_W; z -= oz * CHUNK_D; int cx = floordiv(x, CHUNK_W); int cy = floordiv(y, CHUNK_H); @@ -46,7 +53,7 @@ voxel* Chunks::get(int32_t x, int32_t y, int32_t z) const { if (cx < 0 || cy < 0 || cz < 0 || cx >= int(w) || cy >= 1 || cz >= int(d)) { return nullptr; } - auto& chunk = chunks[cz * w + cx]; // not thread safe + auto& chunk = chunks[cz * w + cx]; // not thread safe if (chunk == nullptr) { return nullptr; } @@ -56,7 +63,7 @@ voxel* Chunks::get(int32_t x, int32_t y, int32_t z) const { return &chunk->voxels[(ly * CHUNK_D + lz) * CHUNK_W + lx]; } -const AABB* Chunks::isObstacleAt(float x, float y, float z){ +const AABB* Chunks::isObstacleAt(float x, float y, float z) { int ix = floor(x); int iy = floor(y); int iz = floor(z); @@ -76,11 +83,12 @@ const AABB* Chunks::isObstacleAt(float x, float y, float z){ glm::ivec3 point(ix, iy, iz); offset = seekOrigin(point, def, v->state) - point; } - const auto& boxes = def->rotatable - ? def->rt.hitboxes[v->state.rotation] - : def->hitboxes; + const auto& boxes = def->rotatable ? def->rt.hitboxes[v->state.rotation] + : def->hitboxes; for (const auto& hitbox : boxes) { - if (hitbox.contains({x - ix - offset.x, y - iy - offset.y, z - iz - offset.z})) { + if (hitbox.contains( + {x - ix - offset.x, y - iy - offset.y, z - iz - offset.z} + )) { return &hitbox; } } @@ -90,26 +98,23 @@ const AABB* Chunks::isObstacleAt(float x, float y, float z){ bool Chunks::isSolidBlock(int32_t x, int32_t y, int32_t z) { voxel* v = get(x, y, z); - if (v == nullptr) - return false; + if (v == nullptr) return false; return indices->blocks.get(v->id)->rt.solid; } bool Chunks::isReplaceableBlock(int32_t x, int32_t y, int32_t z) { voxel* v = get(x, y, z); - if (v == nullptr) - return false; + if (v == nullptr) return false; return indices->blocks.get(v->id)->replaceable; } bool Chunks::isObstacleBlock(int32_t x, int32_t y, int32_t z) { voxel* v = get(x, y, z); - if (v == nullptr) - return false; + if (v == nullptr) return false; return indices->blocks.get(v->id)->obstacle; } -ubyte Chunks::getLight(int32_t x, int32_t y, int32_t z, int channel){ +ubyte Chunks::getLight(int32_t x, int32_t y, int32_t z, int channel) { x -= ox * CHUNK_W; z -= oz * CHUNK_D; int cx = floordiv(x, CHUNK_W); @@ -128,7 +133,7 @@ ubyte Chunks::getLight(int32_t x, int32_t y, int32_t z, int channel){ return chunk->lightmap.get(lx, ly, lz, channel); } -light_t Chunks::getLight(int32_t x, int32_t y, int32_t z){ +light_t Chunks::getLight(int32_t x, int32_t y, int32_t z) { x -= ox * CHUNK_W; z -= oz * CHUNK_D; int cx = floordiv(x, CHUNK_W); @@ -144,31 +149,32 @@ light_t Chunks::getLight(int32_t x, int32_t y, int32_t z){ int lx = x - cx * CHUNK_W; int ly = y - cy * CHUNK_H; int lz = z - cz * CHUNK_D; - return chunk->lightmap.get(lx,ly,lz); + return chunk->lightmap.get(lx, ly, lz); } Chunk* Chunks::getChunkByVoxel(int32_t x, int32_t y, int32_t z) { - if (y < 0 || y >= CHUNK_H) - return nullptr; + if (y < 0 || y >= CHUNK_H) return nullptr; x -= ox * CHUNK_W; z -= oz * CHUNK_D; int cx = floordiv(x, CHUNK_W); int cz = floordiv(z, CHUNK_D); - if (cx < 0 || cz < 0 || cx >= int(w) || cz >= int(d)) - return nullptr; + if (cx < 0 || cz < 0 || cx >= int(w) || cz >= int(d)) return nullptr; return chunks[cz * w + cx].get(); } -Chunk* Chunks::getChunk(int x, int z){ +Chunk* Chunks::getChunk(int x, int z) { x -= ox; z -= oz; - if (x < 0 || z < 0 || x >= static_cast(w) || z >= static_cast(d)) { + if (x < 0 || z < 0 || x >= static_cast(w) || + z >= static_cast(d)) { return nullptr; } return chunks[z * w + x].get(); } -glm::ivec3 Chunks::seekOrigin(glm::ivec3 pos, const Block* def, blockstate state) { +glm::ivec3 Chunks::seekOrigin( + glm::ivec3 pos, const Block* def, blockstate state +) { const auto& rotation = def->rotations.variants[state.rotation]; auto segment = state.segment; while (true) { @@ -187,7 +193,9 @@ glm::ivec3 Chunks::seekOrigin(glm::ivec3 pos, const Block* def, blockstate state } } -void Chunks::eraseSegments(const Block* def, blockstate state, int x, int y, int z) { +void Chunks::eraseSegments( + const Block* def, blockstate state, int x, int y, int z +) { const auto& rotation = def->rotations.variants[state.rotation]; for (int sy = 0; sy < def->size.y; sy++) { for (int sz = 0; sz < def->size.z; sz++) { @@ -209,7 +217,9 @@ static constexpr uint8_t segment_to_int(int sx, int sy, int sz) { return ((sx > 0) | ((sy > 0) << 1) | ((sz > 0) << 2)); } -void Chunks::repairSegments(const Block* def, blockstate state, int x, int y, int z) { +void Chunks::repairSegments( + const Block* def, blockstate state, int x, int y, int z +) { const auto& rotation = def->rotations.variants[state.rotation]; const auto id = def->rt.id; const auto size = def->size; @@ -232,7 +242,9 @@ void Chunks::repairSegments(const Block* def, blockstate state, int x, int y, in } } -bool Chunks::checkReplaceability(const Block* def, blockstate state, glm::ivec3 origin, blockid_t ignore) { +bool Chunks::checkReplaceability( + const Block* def, blockstate state, glm::ivec3 origin, blockid_t ignore +) { const auto& rotation = def->rotations.variants[state.rotation]; const auto size = def->size; for (int sy = 0; sy < size.y; sy++) { @@ -261,7 +273,7 @@ void Chunks::setRotationExtended( ) { auto newstate = state; newstate.rotation = index; - + // unable to rotate block (cause: obstacles) if (!checkReplaceability(def, newstate, origin, def->rt.id)) { return; @@ -281,7 +293,7 @@ void Chunks::setRotationExtended( blockstate segState = newstate; segState.segment = segment_to_int(sx, sy, sz); - + auto vox = get(pos); // checked for nullptr by checkReplaceability if (vox->id != def->rt.id) { @@ -303,7 +315,9 @@ void Chunks::setRotationExtended( pos += prevRotation.axisX * sx; pos += prevRotation.axisY * sy; pos += prevRotation.axisZ * sz; - if (std::find(segmentBlocks.begin(), segmentBlocks.end(), pos) == segmentBlocks.end()) { + if (std::find( + segmentBlocks.begin(), segmentBlocks.end(), pos + ) == segmentBlocks.end()) { set(pos.x, pos.y, pos.z, 0, {}); } } @@ -328,11 +342,13 @@ void Chunks::setRotation(int32_t x, int32_t y, int32_t z, uint8_t index) { } else { vox->state.rotation = index; auto chunk = getChunkByVoxel(x, y, z); - chunk->setModifiedAndUnsaved(); + chunk->setModifiedAndUnsaved(); } } -void Chunks::set(int32_t x, int32_t y, int32_t z, uint32_t id, blockstate state) { +void Chunks::set( + int32_t x, int32_t y, int32_t z, uint32_t id, blockstate state +) { if (y < 0 || y >= CHUNK_H) { return; } @@ -342,7 +358,8 @@ void Chunks::set(int32_t x, int32_t y, int32_t z, uint32_t id, blockstate state) z -= oz * CHUNK_D; int cx = floordiv(x, CHUNK_W); int cz = floordiv(z, CHUNK_D); - if (cx < 0 || cz < 0 || cx >= static_cast(w) || cz >= static_cast(d)) { + if (cx < 0 || cz < 0 || cx >= static_cast(w) || + cz >= static_cast(d)) { return; } Chunk* chunk = chunks[cz * w + cx].get(); @@ -351,9 +368,9 @@ void Chunks::set(int32_t x, int32_t y, int32_t z, uint32_t id, blockstate state) } int lx = x - cx * CHUNK_W; int lz = z - cz * CHUNK_D; - + // block finalization - voxel& vox = chunk->voxels[(y * CHUNK_D + lz) * CHUNK_W + lx]; + voxel& vox = chunk->voxels[(y * CHUNK_D + lz) * CHUNK_W + lx]; auto prevdef = indices->blocks.get(vox.id); if (prevdef->inventorySize == 0) { chunk->removeBlockInventory(lx, y, lz); @@ -371,27 +388,30 @@ void Chunks::set(int32_t x, int32_t y, int32_t z, uint32_t id, blockstate state) repairSegments(newdef, state, gx, y, gz); } - if (y < chunk->bottom) chunk->bottom = y; - else if (y + 1 > chunk->top) chunk->top = y + 1; - else if (id == 0) chunk->updateHeights(); + if (y < chunk->bottom) + chunk->bottom = y; + else if (y + 1 > chunk->top) + chunk->top = y + 1; + else if (id == 0) + chunk->updateHeights(); - if (lx == 0 && (chunk = getChunk(cx+ox-1, cz+oz))) + if (lx == 0 && (chunk = getChunk(cx + ox - 1, cz + oz))) chunk->flags.modified = true; - if (lz == 0 && (chunk = getChunk(cx+ox, cz+oz-1))) + if (lz == 0 && (chunk = getChunk(cx + ox, cz + oz - 1))) chunk->flags.modified = true; - if (lx == CHUNK_W-1 && (chunk = getChunk(cx+ox+1, cz+oz))) + if (lx == CHUNK_W - 1 && (chunk = getChunk(cx + ox + 1, cz + oz))) chunk->flags.modified = true; - if (lz == CHUNK_D-1 && (chunk = getChunk(cx+ox, cz+oz+1))) + if (lz == CHUNK_D - 1 && (chunk = getChunk(cx + ox, cz + oz + 1))) chunk->flags.modified = true; } voxel* Chunks::rayCast( - glm::vec3 start, - glm::vec3 dir, - float maxDist, - glm::vec3& end, - glm::ivec3& norm, + glm::vec3 start, + glm::vec3 dir, + float maxDist, + glm::vec3& end, + glm::ivec3& norm, glm::ivec3& iend ) { float px = start.x; @@ -425,11 +445,11 @@ voxel* Chunks::rayCast( float tyMax = (tyDelta < infinity) ? tyDelta * ydist : infinity; float tzMax = (tzDelta < infinity) ? tzDelta * zdist : infinity; - int steppedIndex = -1; - - while (t <= maxDist) { - voxel* voxel = get(ix, iy, iz); - if (voxel == nullptr){ + int steppedIndex = -1; + + while (t <= maxDist) { + voxel* voxel = get(ix, iy, iz); + if (voxel == nullptr) { return nullptr; } const auto def = indices->blocks.get(voxel->id); @@ -440,11 +460,11 @@ voxel* Chunks::rayCast( iend.x = ix; iend.y = iy; iend.z = iz; - + if (!def->rt.solid) { - const std::vector& hitboxes = def->rotatable - ? def->rt.hitboxes[voxel->state.rotation] - : def->hitboxes; + const std::vector& hitboxes = + def->rotatable ? def->rt.hitboxes[voxel->state.rotation] + : def->hitboxes; scalar_t distance = maxDist; Ray ray(start, dir); @@ -461,7 +481,9 @@ voxel* Chunks::rayCast( box.b += offset; scalar_t boxDistance; glm::ivec3 boxNorm; - if (ray.intersectAABB(iend, box, maxDist, boxNorm, boxDistance) > RayRelation::None && + if (ray.intersectAABB( + iend, box, maxDist, boxNorm, boxDistance + ) > RayRelation::None && boxDistance < distance) { hit = true; distance = boxDistance; @@ -520,7 +542,9 @@ voxel* Chunks::rayCast( return nullptr; } -glm::vec3 Chunks::rayCastToObstacle(glm::vec3 start, glm::vec3 dir, float maxDist) { +glm::vec3 Chunks::rayCastToObstacle( + glm::vec3 start, glm::vec3 dir, float maxDist +) { const float px = start.x; const float py = start.y; const float pz = start.z; @@ -558,9 +582,9 @@ glm::vec3 Chunks::rayCastToObstacle(glm::vec3 start, glm::vec3 dir, float maxDis const auto def = indices->blocks.get(voxel->id); if (def->obstacle) { if (!def->rt.solid) { - const std::vector& hitboxes = def->rotatable - ? def->rt.hitboxes[voxel->state.rotation] - : def->modelBoxes; + const std::vector& hitboxes = + def->rotatable ? def->rt.hitboxes[voxel->state.rotation] + : def->modelBoxes; scalar_t distance; glm::ivec3 norm; @@ -568,17 +592,23 @@ glm::vec3 Chunks::rayCastToObstacle(glm::vec3 start, glm::vec3 dir, float maxDis glm::ivec3 offset {}; if (voxel->state.segment) { - offset = seekOrigin({ix, iy, iz}, def, voxel->state) - glm::ivec3(ix, iy, iz); + offset = seekOrigin({ix, iy, iz}, def, voxel->state) - + glm::ivec3(ix, iy, iz); } for (const auto& box : hitboxes) { // norm is dummy now, can be inefficient - if (ray.intersectAABB(glm::ivec3(ix, iy, iz)+offset, box, maxDist, norm, distance) > RayRelation::None) { + if (ray.intersectAABB( + glm::ivec3(ix, iy, iz) + offset, + box, + maxDist, + norm, + distance + ) > RayRelation::None) { return start + (dir * glm::vec3(distance)); } } - } - else { + } else { return glm::vec3(px + t * dx, py + t * dy, pz + t * dz); } } @@ -588,20 +618,17 @@ glm::vec3 Chunks::rayCastToObstacle(glm::vec3 start, glm::vec3 dir, float maxDis ix += stepx; t = txMax; txMax += txDelta; - } - else { + } else { iz += stepz; t = tzMax; tzMax += tzDelta; } - } - else { + } else { if (tyMax < tzMax) { iy += stepy; t = tyMax; tyMax += tyDelta; - } - else { + } else { iz += stepz; t = tzMax; tzMax += tzDelta; @@ -611,19 +638,18 @@ glm::vec3 Chunks::rayCastToObstacle(glm::vec3 start, glm::vec3 dir, float maxDis return glm::vec3(px + maxDist * dx, py + maxDist * dy, pz + maxDist * dz); } - void Chunks::setCenter(int32_t x, int32_t z) { int cx = floordiv(x, CHUNK_W); int cz = floordiv(z, CHUNK_D); cx -= ox + w / 2; cz -= oz + d / 2; if (cx | cz) { - translate(cx,cz); + translate(cx, cz); } } void Chunks::translate(int32_t dx, int32_t dz) { - for (uint i = 0; i < volume; i++){ + for (uint i = 0; i < volume; i++) { chunksSecond[i] = nullptr; } for (uint32_t z = 0; z < d; z++) { @@ -631,9 +657,9 @@ void Chunks::translate(int32_t dx, int32_t dz) { auto chunk = chunks[z * w + x]; int nx = x - dx; int nz = z - dz; - if (chunk == nullptr) - continue; - if (nx < 0 || nz < 0 || nx >= static_cast(w) || nz >= static_cast(d)) { + if (chunk == nullptr) continue; + if (nx < 0 || nz < 0 || nx >= static_cast(w) || + nz >= static_cast(d)) { level->events->trigger(EVT_CHUNK_HIDDEN, chunk.get()); save(chunk.get()); chunksCount--; @@ -664,8 +690,10 @@ void Chunks::resize(uint32_t newW, uint32_t newD) { const int newVolume = newW * newD; std::vector> newChunks(newVolume); std::vector> newChunksSecond(newVolume); - for (int z = 0; z < static_cast(d) && z < static_cast(newD); z++) { - for (int x = 0; x < static_cast(w) && x < static_cast(newW); x++) { + for (int z = 0; z < static_cast(d) && z < static_cast(newD); + z++) { + for (int x = 0; x < static_cast(w) && x < static_cast(newW); + x++) { newChunks[z * newW + x] = chunks[z * w + x]; } } @@ -686,7 +714,8 @@ bool Chunks::putChunk(const std::shared_ptr& chunk) { int z = chunk->z; x -= ox; z -= oz; - if (x < 0 || z < 0 || x >= static_cast(w) || z >= static_cast(d)) { + if (x < 0 || z < 0 || x >= static_cast(w) || + z >= static_cast(d)) { return false; } chunks[z * w + x] = chunk; @@ -695,7 +724,7 @@ bool Chunks::putChunk(const std::shared_ptr& chunk) { } void Chunks::saveAndClear() { - for (size_t i = 0; i < volume; i++){ + for (size_t i = 0; i < volume; i++) { auto chunk = chunks[i].get(); chunks[i] = nullptr; save(chunk); @@ -705,9 +734,11 @@ void Chunks::saveAndClear() { void Chunks::save(Chunk* chunk) { if (chunk != nullptr) { - AABB aabb ( + AABB aabb( glm::vec3(chunk->x * CHUNK_W, -INFINITY, chunk->z * CHUNK_D), - glm::vec3((chunk->x+1) * CHUNK_W, INFINITY, (chunk->z + 1) * CHUNK_D) + glm::vec3( + (chunk->x + 1) * CHUNK_W, INFINITY, (chunk->z + 1) * CHUNK_D + ) ); auto entities = level->entities->getAllInside(aabb); auto root = dynamic::create_map(); diff --git a/src/voxels/Chunks.hpp b/src/voxels/Chunks.hpp index 860d3da0..795b6046 100644 --- a/src/voxels/Chunks.hpp +++ b/src/voxels/Chunks.hpp @@ -2,12 +2,13 @@ #define VOXELS_CHUNKS_HPP_ #include -#include -#include -#include -#include "voxel.hpp" +#include +#include +#include + #include "../typedefs.hpp" +#include "voxel.hpp" class VoxelRenderer; @@ -26,8 +27,12 @@ class Chunks { const ContentIndices* const indices; void eraseSegments(const Block* def, blockstate state, int x, int y, int z); - void repairSegments(const Block* def, blockstate state, int x, int y, int z); - void setRotationExtended(Block* def, blockstate state, glm::ivec3 origin, uint8_t rotation); + void repairSegments( + const Block* def, blockstate state, int x, int y, int z + ); + void setRotationExtended( + Block* def, blockstate state, glm::ivec3 origin, uint8_t rotation + ); public: std::vector> chunks; std::vector> chunksSecond; @@ -38,8 +43,14 @@ public: int32_t ox, oz; WorldFiles* worldFiles; - Chunks(uint32_t w, uint32_t d, int32_t ox, int32_t oz, - WorldFiles* worldFiles, Level* level); + Chunks( + uint32_t w, + uint32_t d, + int32_t ox, + int32_t oz, + WorldFiles* worldFiles, + Level* level + ); ~Chunks() = default; bool putChunk(const std::shared_ptr& chunk); @@ -68,16 +79,21 @@ public: /// @param state the block state /// @param coord position of the zone start /// @param ignore ignored block id (will be counted as replaceable) - bool checkReplaceability(const Block* def, blockstate state, glm::ivec3 coord, blockid_t ignore=0); + bool checkReplaceability( + const Block* def, + blockstate state, + glm::ivec3 coord, + blockid_t ignore = 0 + ); void setRotation(int32_t x, int32_t y, int32_t z, uint8_t rotation); voxel* rayCast( - glm::vec3 start, - glm::vec3 dir, - float maxLength, - glm::vec3& end, - glm::ivec3& norm, + glm::vec3 start, + glm::vec3 dir, + float maxLength, + glm::vec3& end, + glm::ivec3& norm, glm::ivec3& iend ); @@ -100,4 +116,4 @@ public: void saveAll(); }; -#endif // VOXELS_CHUNKS_HPP_ +#endif // VOXELS_CHUNKS_HPP_ diff --git a/src/voxels/ChunksStorage.cpp b/src/voxels/ChunksStorage.cpp index 3231ce35..eab8a002 100644 --- a/src/voxels/ChunksStorage.cpp +++ b/src/voxels/ChunksStorage.cpp @@ -1,18 +1,18 @@ #include "ChunksStorage.hpp" -#include "VoxelsVolume.hpp" -#include "Chunk.hpp" -#include "Block.hpp" #include "../content/Content.hpp" +#include "../debug/Logger.hpp" #include "../files/WorldFiles.hpp" +#include "../items/Inventories.hpp" +#include "../lighting/Lightmap.hpp" +#include "../maths/voxmaths.hpp" #include "../objects/Entities.hpp" +#include "../typedefs.hpp" #include "../world/Level.hpp" #include "../world/World.hpp" -#include "../maths/voxmaths.hpp" -#include "../lighting/Lightmap.hpp" -#include "../items/Inventories.hpp" -#include "../typedefs.hpp" -#include "../debug/Logger.hpp" +#include "Block.hpp" +#include "Chunk.hpp" +#include "VoxelsVolume.hpp" static debug::Logger logger("chunks-storage"); @@ -20,22 +20,22 @@ ChunksStorage::ChunksStorage(Level* level) : level(level) { } void ChunksStorage::store(const std::shared_ptr& chunk) { - chunksMap[glm::ivec2(chunk->x, chunk->z)] = chunk; + chunksMap[glm::ivec2(chunk->x, chunk->z)] = chunk; } std::shared_ptr ChunksStorage::get(int x, int z) const { - auto found = chunksMap.find(glm::ivec2(x, z)); - if (found == chunksMap.end()) { - return nullptr; - } - return found->second; + auto found = chunksMap.find(glm::ivec2(x, z)); + if (found == chunksMap.end()) { + return nullptr; + } + return found->second; } void ChunksStorage::remove(int x, int z) { - auto found = chunksMap.find(glm::ivec2(x, z)); - if (found != chunksMap.end()) { - chunksMap.erase(found->first); - } + auto found = chunksMap.find(glm::ivec2(x, z)); + if (found != chunksMap.end()) { + chunksMap.erase(found->first); + } } static void verifyLoadedChunk(ContentIndices* indices, Chunk* chunk) { @@ -52,17 +52,17 @@ static void verifyLoadedChunk(ContentIndices* indices, Chunk* chunk) { } std::shared_ptr ChunksStorage::create(int x, int z) { - World* world = level->getWorld(); + World* world = level->getWorld(); auto& regions = world->wfile.get()->getRegions(); auto chunk = std::make_shared(x, z); - store(chunk); - auto data = regions.getChunk(chunk->x, chunk->z); - if (data) { - chunk->decode(data.get()); + store(chunk); + auto data = regions.getChunk(chunk->x, chunk->z); + if (data) { + chunk->decode(data.get()); - auto invs = regions.fetchInventories(chunk->x, chunk->z); - chunk->setBlockInventories(std::move(invs)); + auto invs = regions.fetchInventories(chunk->x, chunk->z); + chunk->setBlockInventories(std::move(invs)); if (auto map = regions.fetchEntities(chunk->x, chunk->z)) { level->entities->loadEntities(std::move(map)); @@ -70,95 +70,104 @@ std::shared_ptr ChunksStorage::create(int x, int z) { } chunk->flags.loaded = true; - for(auto& entry : chunk->inventories) { - level->inventories->store(entry.second); - } + for (auto& entry : chunk->inventories) { + level->inventories->store(entry.second); + } verifyLoadedChunk(level->content->getIndices(), chunk.get()); - } + } - auto lights = regions.getLights(chunk->x, chunk->z); - if (lights) { - chunk->lightmap.set(lights.get()); + auto lights = regions.getLights(chunk->x, chunk->z); + if (lights) { + chunk->lightmap.set(lights.get()); chunk->flags.loadedLights = true; - } - return chunk; + } + return chunk; } // reduce nesting on next modification // 25.06.2024: not now void ChunksStorage::getVoxels(VoxelsVolume* volume, bool backlight) const { - const Content* content = level->content; - auto indices = content->getIndices(); - voxel* voxels = volume->getVoxels(); - light_t* lights = volume->getLights(); - int x = volume->getX(); - int y = volume->getY(); - int z = volume->getZ(); + const Content* content = level->content; + auto indices = content->getIndices(); + voxel* voxels = volume->getVoxels(); + light_t* lights = volume->getLights(); + int x = volume->getX(); + int y = volume->getY(); + int z = volume->getZ(); - int w = volume->getW(); - int h = volume->getH(); - int d = volume->getD(); + int w = volume->getW(); + int h = volume->getH(); + int d = volume->getD(); - int scx = floordiv(x, CHUNK_W); - int scz = floordiv(z, CHUNK_D); + int scx = floordiv(x, CHUNK_W); + int scz = floordiv(z, CHUNK_D); - int ecx = floordiv(x + w, CHUNK_W); - int ecz = floordiv(z + d, CHUNK_D); + int ecx = floordiv(x + w, CHUNK_W); + int ecz = floordiv(z + d, CHUNK_D); - int cw = ecx - scx + 1; - int ch = ecz - scz + 1; + int cw = ecx - scx + 1; + int ch = ecz - scz + 1; - // cw*ch chunks will be scanned - for (int cz = scz; cz < scz + ch; cz++) { - for (int cx = scx; cx < scx + cw; cx++) { - const auto& found = chunksMap.find(glm::ivec2(cx, cz)); - if (found == chunksMap.end()) { - // no chunk loaded -> filling with BLOCK_VOID - for (int ly = y; ly < y + h; ly++) { - for (int lz = max(z, cz * CHUNK_D); - lz < min(z + d, (cz + 1) * CHUNK_D); - lz++) { - for (int lx = max(x, cx * CHUNK_W); - lx < min(x + w, (cx + 1) * CHUNK_W); - lx++) { - uint idx = vox_index(lx - x, ly - y, lz - z, w, d); - voxels[idx].id = BLOCK_VOID; - lights[idx] = 0; - } - } - } - } else { - auto& chunk = found->second; - const voxel* cvoxels = chunk->voxels; - const light_t* clights = chunk->lightmap.getLights(); - for (int ly = y; ly < y + h; ly++) { - for (int lz = max(z, cz * CHUNK_D); - lz < min(z + d, (cz + 1) * CHUNK_D); - lz++) { - for (int lx = max(x, cx * CHUNK_W); - lx < min(x + w, (cx + 1) * CHUNK_W); - lx++) { - uint vidx = vox_index(lx - x, ly - y, lz - z, w, d); - uint cidx = vox_index(lx - cx * CHUNK_W, ly, - lz - cz * CHUNK_D, CHUNK_W, CHUNK_D); - voxels[vidx] = cvoxels[cidx]; - light_t light = clights[cidx]; - if (backlight) { - auto block = indices->blocks.get(voxels[vidx].id); - if (block->lightPassing) { - light = Lightmap::combine( - min(15, Lightmap::extract(light, 0)+1), - min(15, Lightmap::extract(light, 1)+1), - min(15, Lightmap::extract(light, 2)+1), - min(15, Lightmap::extract(light, 3)) - ); - } - } - lights[vidx] = light; - } - } - } - } - } - } + // cw*ch chunks will be scanned + for (int cz = scz; cz < scz + ch; cz++) { + for (int cx = scx; cx < scx + cw; cx++) { + const auto& found = chunksMap.find(glm::ivec2(cx, cz)); + if (found == chunksMap.end()) { + // no chunk loaded -> filling with BLOCK_VOID + for (int ly = y; ly < y + h; ly++) { + for (int lz = max(z, cz * CHUNK_D); + lz < min(z + d, (cz + 1) * CHUNK_D); + lz++) { + for (int lx = max(x, cx * CHUNK_W); + lx < min(x + w, (cx + 1) * CHUNK_W); + lx++) { + uint idx = vox_index(lx - x, ly - y, lz - z, w, d); + voxels[idx].id = BLOCK_VOID; + lights[idx] = 0; + } + } + } + } else { + auto& chunk = found->second; + const voxel* cvoxels = chunk->voxels; + const light_t* clights = chunk->lightmap.getLights(); + for (int ly = y; ly < y + h; ly++) { + for (int lz = max(z, cz * CHUNK_D); + lz < min(z + d, (cz + 1) * CHUNK_D); + lz++) { + for (int lx = max(x, cx * CHUNK_W); + lx < min(x + w, (cx + 1) * CHUNK_W); + lx++) { + uint vidx = vox_index(lx - x, ly - y, lz - z, w, d); + uint cidx = vox_index( + lx - cx * CHUNK_W, + ly, + lz - cz * CHUNK_D, + CHUNK_W, + CHUNK_D + ); + voxels[vidx] = cvoxels[cidx]; + light_t light = clights[cidx]; + if (backlight) { + auto block = + indices->blocks.get(voxels[vidx].id); + if (block->lightPassing) { + light = Lightmap::combine( + min(15, + Lightmap::extract(light, 0) + 1), + min(15, + Lightmap::extract(light, 1) + 1), + min(15, + Lightmap::extract(light, 2) + 1), + min(15, Lightmap::extract(light, 3)) + ); + } + } + lights[vidx] = light; + } + } + } + } + } + } } diff --git a/src/voxels/ChunksStorage.hpp b/src/voxels/ChunksStorage.hpp index 16f2fe61..7560b8a4 100644 --- a/src/voxels/ChunksStorage.hpp +++ b/src/voxels/ChunksStorage.hpp @@ -3,8 +3,9 @@ #include #include -#include "voxel.hpp" + #include "../typedefs.hpp" +#include "voxel.hpp" #define GLM_ENABLE_EXPERIMENTAL #include "glm/gtx/hash.hpp" @@ -23,9 +24,8 @@ public: std::shared_ptr get(int x, int z) const; void store(const std::shared_ptr& chunk); void remove(int x, int y); - void getVoxels(VoxelsVolume* volume, bool backlight=false) const; + void getVoxels(VoxelsVolume* volume, bool backlight = false) const; std::shared_ptr create(int x, int z); }; - -#endif // VOXELS_CHUNKSSTORAGE_HPP_ +#endif // VOXELS_CHUNKSSTORAGE_HPP_ diff --git a/src/voxels/DefaultWorldGenerator.cpp b/src/voxels/DefaultWorldGenerator.cpp index 49747519..99a5a0f2 100644 --- a/src/voxels/DefaultWorldGenerator.cpp +++ b/src/voxels/DefaultWorldGenerator.cpp @@ -1,34 +1,30 @@ #include "DefaultWorldGenerator.hpp" -#include "voxel.hpp" -#include "Chunk.hpp" + #include "Block.hpp" +#include "Chunk.hpp" +#include "voxel.hpp" #define FNL_IMPL -#include "../maths/FastNoiseLite.h" - -#include "../content/Content.hpp" -#include "../maths/voxmaths.hpp" -#include "../maths/util.hpp" -#include "../core_defs.hpp" - -#include -#include -#include -#include #include +#include + #include #include +#include +#include +#include + +#include "../content/Content.hpp" +#include "../core_defs.hpp" +#include "../maths/FastNoiseLite.h" +#include "../maths/util.hpp" +#include "../maths/voxmaths.hpp" // will be refactored in generators update const int SEA_LEVEL = 55; -enum class MAPS{ - SAND, - TREE, - CLIFF, - HEIGHT -}; +enum class MAPS { SAND, TREE, CLIFF, HEIGHT }; #define MAPS_LEN 4 class Map2D { @@ -37,12 +33,10 @@ class Map2D { float* heights[MAPS_LEN]; public: Map2D(int x, int z, int w, int d) : x(x), z(z), w(w), d(d) { - for (int i = 0; i < MAPS_LEN; i++) - heights[i] = new float[w*d]; + for (int i = 0; i < MAPS_LEN; i++) heights[i] = new float[w * d]; } ~Map2D() { - for (int i = 0; i < MAPS_LEN; i++) - delete[] heights[i]; + for (int i = 0; i < MAPS_LEN; i++) delete[] heights[i]; } inline float get(MAPS map, int x, int z) { @@ -64,63 +58,85 @@ public: } }; -float calc_height(fnl_state *noise, int cur_x, int cur_z){ +float calc_height(fnl_state* noise, int cur_x, int cur_z) { float height = 0; - height += fnlGetNoise2D(noise, cur_x*0.0125f*8-125567,cur_z*0.0125f*8+3546); - height += fnlGetNoise2D(noise, cur_x*0.025f*8+4647,cur_z*0.025f*8-3436)*0.5f; - height += fnlGetNoise2D(noise, cur_x*0.05f*8-834176,cur_z*0.05f*8+23678)*0.25f; - height += fnlGetNoise2D(noise, - cur_x*0.2f*8 + fnlGetNoise2D(noise, cur_x*0.1f*8-23557,cur_z*0.1f*8-6568)*50, - cur_z*0.2f*8 + fnlGetNoise2D(noise, cur_x*0.1f*8+4363,cur_z*0.1f*8+4456)*50 - ) * fnlGetNoise2D(noise, cur_x*0.01f-834176,cur_z*0.01f+23678) * 0.25; - height += fnlGetNoise2D(noise, cur_x*0.1f*8-3465,cur_z*0.1f*8+4534)*0.125f; - height *= fnlGetNoise2D(noise, cur_x*0.1f+1000,cur_z*0.1f+1000)*0.5f+0.5f; + height += fnlGetNoise2D( + noise, cur_x * 0.0125f * 8 - 125567, cur_z * 0.0125f * 8 + 3546 + ); + height += fnlGetNoise2D( + noise, cur_x * 0.025f * 8 + 4647, cur_z * 0.025f * 8 - 3436 + ) * + 0.5f; + height += fnlGetNoise2D( + noise, cur_x * 0.05f * 8 - 834176, cur_z * 0.05f * 8 + 23678 + ) * + 0.25f; + height += + fnlGetNoise2D( + noise, + cur_x * 0.2f * 8 + + fnlGetNoise2D( + noise, cur_x * 0.1f * 8 - 23557, cur_z * 0.1f * 8 - 6568 + ) * 50, + cur_z * 0.2f * 8 + + fnlGetNoise2D( + noise, cur_x * 0.1f * 8 + 4363, cur_z * 0.1f * 8 + 4456 + ) * 50 + ) * + fnlGetNoise2D(noise, cur_x * 0.01f - 834176, cur_z * 0.01f + 23678) * + 0.25; + height += + fnlGetNoise2D(noise, cur_x * 0.1f * 8 - 3465, cur_z * 0.1f * 8 + 4534) * + 0.125f; + height *= + fnlGetNoise2D(noise, cur_x * 0.1f + 1000, cur_z * 0.1f + 1000) * 0.5f + + 0.5f; height += 1.0f; height *= 64.0f; return height; } -int generate_tree(fnl_state *noise, - PseudoRandom* random, - Map2D& heights, - // Map2D& humidity, - int cur_x, - int cur_y, - int cur_z, - int tileSize, - blockid_t idWood, - blockid_t idLeaves){ +int generate_tree( + fnl_state* noise, + PseudoRandom* random, + Map2D& heights, + // Map2D& humidity, + int cur_x, + int cur_y, + int cur_z, + int tileSize, + blockid_t idWood, + blockid_t idLeaves +) { const int tileX = floordiv(cur_x, tileSize); const int tileZ = floordiv(cur_z, tileSize); - random->setSeed(tileX*4325261+tileZ*12160951+tileSize*9431111); + random->setSeed(tileX * 4325261 + tileZ * 12160951 + tileSize * 9431111); - int randomX = (random->rand() % (tileSize/2)) - tileSize/4; - int randomZ = (random->rand() % (tileSize/2)) - tileSize/4; + int randomX = (random->rand() % (tileSize / 2)) - tileSize / 4; + int randomZ = (random->rand() % (tileSize / 2)) - tileSize / 4; - int centerX = tileX * tileSize + tileSize/2 + randomX; - int centerZ = tileZ * tileSize + tileSize/2 + randomZ; + int centerX = tileX * tileSize + tileSize / 2 + randomX; + int centerZ = tileZ * tileSize + tileSize / 2 + randomZ; - bool gentree = (random->rand() % 10) < heights.get(MAPS::TREE, centerX, centerZ) * 13; - if (!gentree) - return 0; + bool gentree = + (random->rand() % 10) < heights.get(MAPS::TREE, centerX, centerZ) * 13; + if (!gentree) return 0; int height = (int)(heights.get(MAPS::HEIGHT, centerX, centerZ)); - if (height < SEA_LEVEL+1) - return 0; + if (height < SEA_LEVEL + 1) return 0; int lx = cur_x - centerX; int radius = random->rand() % 4 + 2; int ly = cur_y - height - 3 * radius; int lz = cur_z - centerZ; - if (lx == 0 && lz == 0 && cur_y - height < (3*radius + radius/2)) + if (lx == 0 && lz == 0 && cur_y - height < (3 * radius + radius / 2)) return idWood; - if (lx*lx+ly*ly/2+lz*lz < radius*radius) - return idLeaves; + if (lx * lx + ly * ly / 2 + lz * lz < radius * radius) return idLeaves; return 0; } -void DefaultWorldGenerator::generate(voxel* voxels, int cx, int cz, int seed){ +void DefaultWorldGenerator::generate(voxel* voxels, int cx, int cz, int seed) { const int treesTile = 12; fnl_state noise = fnlCreateState(); noise.noise_type = FNL_NOISE_OPENSIMPLEX2; @@ -129,24 +145,27 @@ void DefaultWorldGenerator::generate(voxel* voxels, int cx, int cz, int seed){ PseudoRandom randomgrass; int padding = 8; - Map2D heights(cx * CHUNK_W - padding, - cz * CHUNK_D - padding, - CHUNK_W + padding * 2, - CHUNK_D + padding * 2); + Map2D heights( + cx * CHUNK_W - padding, + cz * CHUNK_D - padding, + CHUNK_W + padding * 2, + CHUNK_D + padding * 2 + ); - for (int z = -padding; z < CHUNK_D+padding; z++){ - for (int x = -padding; x < CHUNK_W+padding; x++){ + for (int z = -padding; z < CHUNK_D + padding; z++) { + for (int x = -padding; x < CHUNK_W + padding; x++) { int cur_x = x + cx * CHUNK_W; int cur_z = z + cz * CHUNK_D; float height = calc_height(&noise, cur_x, cur_z); float hum = fnlGetNoise2D(&noise, cur_x * 0.3 + 633, cur_z * 0.3); - float sand = fnlGetNoise2D(&noise, cur_x * 0.1 - 633, cur_z * 0.1 + 1000); - float cliff = pow((sand + abs(sand)) / 2, 2); - float w = pow(fmax(-abs(height-SEA_LEVEL)+4,0)/6,2) * cliff; - float h1 = -abs(height-SEA_LEVEL - 0.03); - float h2 = abs(height-SEA_LEVEL + 0.04); - float h = (h1 + h2)*100; - height += (h * w); + float sand = + fnlGetNoise2D(&noise, cur_x * 0.1 - 633, cur_z * 0.1 + 1000); + float cliff = pow((sand + abs(sand)) / 2, 2); + float w = pow(fmax(-abs(height - SEA_LEVEL) + 4, 0) / 6, 2) * cliff; + float h1 = -abs(height - SEA_LEVEL - 0.03); + float h2 = abs(height - SEA_LEVEL + 0.04); + float h = (h1 + h2) * 100; + height += (h * w); heights.set(MAPS::HEIGHT, cur_x, cur_z, height); heights.set(MAPS::TREE, cur_x, cur_z, hum); heights.set(MAPS::SAND, cur_x, cur_z, sand); @@ -154,49 +173,63 @@ void DefaultWorldGenerator::generate(voxel* voxels, int cx, int cz, int seed){ } } - for (int z = 0; z < CHUNK_D; z++){ + for (int z = 0; z < CHUNK_D; z++) { int cur_z = z + cz * CHUNK_D; - for (int x = 0; x < CHUNK_W; x++){ + for (int x = 0; x < CHUNK_W; x++) { int cur_x = x + cx * CHUNK_W; float height = heights.get(MAPS::HEIGHT, cur_x, cur_z); - for (int cur_y = 0; cur_y < CHUNK_H; cur_y++){ + for (int cur_y = 0; cur_y < CHUNK_H; cur_y++) { // int cur_y = y; int id = cur_y < SEA_LEVEL ? idWater : BLOCK_AIR; blockstate state {}; - if ((cur_y == (int)height) && (SEA_LEVEL-2 < cur_y)) { + if ((cur_y == (int)height) && (SEA_LEVEL - 2 < cur_y)) { id = idGrassBlock; - } else if (cur_y < (height - 6)){ + } else if (cur_y < (height - 6)) { id = idStone; - } else if (cur_y < height){ + } else if (cur_y < height) { id = idDirt; } else { int tree = generate_tree( - &noise, &randomtree, heights, - cur_x, cur_y, cur_z, - treesTile, idWood, idLeaves); + &noise, + &randomtree, + heights, + cur_x, + cur_y, + cur_z, + treesTile, + idWood, + idLeaves + ); if (tree) { id = tree; state.rotation = BLOCK_DIR_UP; } } - float sand = fmax(heights.get(MAPS::SAND, cur_x, cur_z), heights.get(MAPS::CLIFF, cur_x, cur_z)); - if (((height - (1.1 - 0.2 * pow(height - 54, 4)) + - (5*sand)) < cur_y + (height - 0.01- (int)height)) - && (cur_y < height)){ + float sand = fmax( + heights.get(MAPS::SAND, cur_x, cur_z), + heights.get(MAPS::CLIFF, cur_x, cur_z) + ); + if (((height - (1.1 - 0.2 * pow(height - 54, 4)) + (5 * sand)) < + cur_y + (height - 0.01 - (int)height)) && + (cur_y < height)) { id = idSand; } - if (cur_y <= 2) - id = idBazalt; + if (cur_y <= 2) id = idBazalt; - randomgrass.setSeed(cur_x,cur_z); - if ((id == 0) && ((height > SEA_LEVEL+0.4) || (sand > 0.1)) && ((int)(height + 1) == cur_y) && ((unsigned short)randomgrass.rand() > 56000)){ + randomgrass.setSeed(cur_x, cur_z); + if ((id == 0) && ((height > SEA_LEVEL + 0.4) || (sand > 0.1)) && + ((int)(height + 1) == cur_y) && + ((unsigned short)randomgrass.rand() > 56000)) { id = idGrass; } - if ((id == 0) && (height > SEA_LEVEL+0.4) && ((int)(height + 1) == cur_y) && ((unsigned short)randomgrass.rand() > 65000)){ + if ((id == 0) && (height > SEA_LEVEL + 0.4) && + ((int)(height + 1) == cur_y) && + ((unsigned short)randomgrass.rand() > 65000)) { id = idFlower; } - if ((height > SEA_LEVEL+1) && ((int)(height + 1) == cur_y) && ((unsigned short)randomgrass.rand() > 65533)){ + if ((height > SEA_LEVEL + 1) && ((int)(height + 1) == cur_y) && + ((unsigned short)randomgrass.rand() > 65533)) { id = idWood; state.rotation = BLOCK_DIR_UP; } diff --git a/src/voxels/DefaultWorldGenerator.hpp b/src/voxels/DefaultWorldGenerator.hpp index d42e2749..63fbb6d6 100644 --- a/src/voxels/DefaultWorldGenerator.hpp +++ b/src/voxels/DefaultWorldGenerator.hpp @@ -9,10 +9,10 @@ class Content; class DefaultWorldGenerator : WorldGenerator { public: - - DefaultWorldGenerator(const Content* content) : WorldGenerator(content) {} + DefaultWorldGenerator(const Content* content) : WorldGenerator(content) { + } void generate(voxel* voxels, int x, int z, int seed); }; -#endif // VOXELS_DEFAULTWORLDGENERATOR_HPP_ +#endif // VOXELS_DEFAULTWORLDGENERATOR_HPP_ diff --git a/src/voxels/FlatWorldGenerator.cpp b/src/voxels/FlatWorldGenerator.cpp index f729d32b..2121f888 100644 --- a/src/voxels/FlatWorldGenerator.cpp +++ b/src/voxels/FlatWorldGenerator.cpp @@ -1,24 +1,24 @@ #include "FlatWorldGenerator.hpp" -#include "voxel.hpp" -#include "Chunk.hpp" #include "../content/Content.hpp" #include "../core_defs.hpp" +#include "Chunk.hpp" +#include "voxel.hpp" void FlatWorldGenerator::generate(voxel* voxels, int cx, int cz, int seed) { for (int z = 0; z < CHUNK_D; z++) { for (int x = 0; x < CHUNK_W; x++) { - for (int cur_y = 0; cur_y < CHUNK_H; cur_y++){ + for (int cur_y = 0; cur_y < CHUNK_H; cur_y++) { int id = BLOCK_AIR; blockstate state {}; - if(cur_y == 2) { + if (cur_y == 2) { id = idBazalt; - } else if(cur_y == 6) { + } else if (cur_y == 6) { id = idGrassBlock; - } else if(cur_y > 2 && cur_y <= 5) { + } else if (cur_y > 2 && cur_y <= 5) { id = idDirt; - } + } voxels[(cur_y * CHUNK_D + z) * CHUNK_W + x].id = id; voxels[(cur_y * CHUNK_D + z) * CHUNK_W + x].state = state; diff --git a/src/voxels/FlatWorldGenerator.hpp b/src/voxels/FlatWorldGenerator.hpp index c9a2d25f..bc507b30 100644 --- a/src/voxels/FlatWorldGenerator.hpp +++ b/src/voxels/FlatWorldGenerator.hpp @@ -9,10 +9,10 @@ class Content; class FlatWorldGenerator : WorldGenerator { public: - - FlatWorldGenerator(const Content* content) : WorldGenerator(content) {} + FlatWorldGenerator(const Content* content) : WorldGenerator(content) { + } void generate(voxel* voxels, int x, int z, int seed); }; -#endif // VOXELS_FLATWORLDGENERATOR_HPP_ +#endif // VOXELS_FLATWORLDGENERATOR_HPP_ diff --git a/src/voxels/VoxelsVolume.cpp b/src/voxels/VoxelsVolume.cpp index 5da88add..d74f69ee 100644 --- a/src/voxels/VoxelsVolume.cpp +++ b/src/voxels/VoxelsVolume.cpp @@ -1,20 +1,25 @@ #include "VoxelsVolume.hpp" -VoxelsVolume::VoxelsVolume( - int x, int y, int z, int w, int h, int d -) : x(x), y(y), z(z), w(w), h(h), d(d), - voxels(std::make_unique(w * h * d)), - lights(std::make_unique(w * h * d)) -{ +VoxelsVolume::VoxelsVolume(int x, int y, int z, int w, int h, int d) + : x(x), + y(y), + z(z), + w(w), + h(h), + d(d), + voxels(std::make_unique(w * h * d)), + lights(std::make_unique(w * h * d)) { for (int i = 0; i < w * h * d; i++) { voxels[i].id = BLOCK_VOID; } } -VoxelsVolume::VoxelsVolume(int w, int h, int d) : VoxelsVolume(0, 0, 0, w, h, d) -{} +VoxelsVolume::VoxelsVolume(int w, int h, int d) + : VoxelsVolume(0, 0, 0, w, h, d) { +} -VoxelsVolume::~VoxelsVolume() {} +VoxelsVolume::~VoxelsVolume() { +} void VoxelsVolume::setPosition(int x, int y, int z) { this->x = x; diff --git a/src/voxels/VoxelsVolume.hpp b/src/voxels/VoxelsVolume.hpp index d6e6474a..59afbbaf 100644 --- a/src/voxels/VoxelsVolume.hpp +++ b/src/voxels/VoxelsVolume.hpp @@ -1,8 +1,8 @@ #ifndef VOXELS_VOXELSVOLUME_HPP_ #define VOXELS_VOXELSVOLUME_HPP_ -#include "../typedefs.hpp" #include "../constants.hpp" +#include "../typedefs.hpp" #include "voxel.hpp" class VoxelsVolume { @@ -50,18 +50,20 @@ public: } inline blockid_t pickBlockId(int bx, int by, int bz) const { - if (bx < x || by < y || bz < z || bx >= x + w || by >= y + h || bz >= z + d) { + if (bx < x || by < y || bz < z || bx >= x + w || by >= y + h || + bz >= z + d) { return BLOCK_VOID; } return voxels[vox_index(bx - x, by - y, bz - z, w, d)].id; } inline light_t pickLight(int bx, int by, int bz) const { - if (bx < x || by < y || bz < z || bx >= x + w || by >= y + h || bz >= z + d) { + if (bx < x || by < y || bz < z || bx >= x + w || by >= y + h || + bz >= z + d) { return 0; } return lights[vox_index(bx - x, by - y, bz - z, w, d)]; } }; -#endif // VOXELS_VOXELSVOLUME_HPP_ +#endif // VOXELS_VOXELSVOLUME_HPP_ diff --git a/src/voxels/WorldGenerator.cpp b/src/voxels/WorldGenerator.cpp index 9bcccdeb..84d44d25 100644 --- a/src/voxels/WorldGenerator.cpp +++ b/src/voxels/WorldGenerator.cpp @@ -1,18 +1,19 @@ #include "WorldGenerator.hpp" -#include "voxel.hpp" -#include "Chunk.hpp" -#include "Block.hpp" #include "../content/Content.hpp" +#include "Block.hpp" +#include "Chunk.hpp" +#include "voxel.hpp" WorldGenerator::WorldGenerator(const Content* content) - : idStone(content->blocks.require("base:stone").rt.id), - idDirt(content->blocks.require("base:dirt").rt.id), - idGrassBlock(content->blocks.require("base:grass_block").rt.id), - idSand(content->blocks.require("base:sand").rt.id), - idWater(content->blocks.require("base:water").rt.id), - idWood(content->blocks.require("base:wood").rt.id), - idLeaves(content->blocks.require("base:leaves").rt.id), - idGrass(content->blocks.require("base:grass").rt.id), - idFlower(content->blocks.require("base:flower").rt.id), - idBazalt(content->blocks.require("base:bazalt").rt.id) {} + : idStone(content->blocks.require("base:stone").rt.id), + idDirt(content->blocks.require("base:dirt").rt.id), + idGrassBlock(content->blocks.require("base:grass_block").rt.id), + idSand(content->blocks.require("base:sand").rt.id), + idWater(content->blocks.require("base:water").rt.id), + idWood(content->blocks.require("base:wood").rt.id), + idLeaves(content->blocks.require("base:leaves").rt.id), + idGrass(content->blocks.require("base:grass").rt.id), + idFlower(content->blocks.require("base:flower").rt.id), + idBazalt(content->blocks.require("base:bazalt").rt.id) { +} diff --git a/src/voxels/WorldGenerator.hpp b/src/voxels/WorldGenerator.hpp index 5b8839ac..1c57c0ff 100644 --- a/src/voxels/WorldGenerator.hpp +++ b/src/voxels/WorldGenerator.hpp @@ -1,9 +1,10 @@ #ifndef VOXELS_WORLDGENERATOR_HPP_ #define VOXELS_WORLDGENERATOR_HPP_ -#include "../typedefs.hpp" #include +#include "../typedefs.hpp" + struct voxel; class Content; @@ -26,4 +27,4 @@ public: virtual void generate(voxel* voxels, int x, int z, int seed) = 0; }; -#endif // VOXELS_WORLDGENERATOR_HPP_ +#endif // VOXELS_WORLDGENERATOR_HPP_ diff --git a/src/voxels/voxel.hpp b/src/voxels/voxel.hpp index 460a6a4f..637375f5 100644 --- a/src/voxels/voxel.hpp +++ b/src/voxels/voxel.hpp @@ -11,14 +11,14 @@ inline constexpr int BLOCK_DIR_UP = 0x4; inline constexpr int BLOCK_DIR_DOWN = 0x5; struct blockstate { - uint8_t rotation : 3; // block rotation index - uint8_t segment : 3; // segment block bits - uint8_t reserved : 2; // reserved bits - uint8_t userbits : 8; // bits for use in block script + uint8_t rotation : 3; // block rotation index + uint8_t segment : 3; // segment block bits + uint8_t reserved : 2; // reserved bits + uint8_t userbits : 8; // bits for use in block script }; -static_assert (sizeof(blockstate) == 2); +static_assert(sizeof(blockstate) == 2); -/// @brief blockstate cast to an integer (optimized out in most cases) +/// @brief blockstate cast to an integer (optimized out in most cases) inline constexpr blockstate_t blockstate2int(blockstate b) { return static_cast(b.rotation) | static_cast(b.segment) << 3 | @@ -26,14 +26,13 @@ inline constexpr blockstate_t blockstate2int(blockstate b) { static_cast(b.userbits) << 8; } -/// @brief integer cast to a blockstate (optimized out in most cases) +/// @brief integer cast to a blockstate (optimized out in most cases) inline constexpr blockstate int2blockstate(blockstate_t i) { return { static_cast(i & 0b111), static_cast((i >> 3) & 0b111), static_cast((i >> 6) & 0b11), - static_cast((i >> 8) & 0xFF) - }; + static_cast((i >> 8) & 0xFF)}; } struct voxel { @@ -42,4 +41,4 @@ struct voxel { }; static_assert(sizeof(voxel) == 4); -#endif // VOXELS_VOXEL_HPP_ +#endif // VOXELS_VOXEL_HPP_ diff --git a/src/window/Camera.cpp b/src/window/Camera.cpp index 80b16af2..df8f56d3 100644 --- a/src/window/Camera.cpp +++ b/src/window/Camera.cpp @@ -1,60 +1,60 @@ #include "Camera.hpp" -#include "Window.hpp" #include +#include "Window.hpp" + Camera::Camera(glm::vec3 position, float fov) : fov(fov), position(position) { updateVectors(); } -void Camera::updateVectors(){ - front = glm::vec3(rotation * glm::vec4(0,0,-1,1)); - right = glm::vec3(rotation * glm::vec4(1,0,0,1)); - up = glm::vec3(rotation * glm::vec4(0,1,0,1)); - dir = glm::vec3(rotation * glm::vec4(0,0,-1,1)); +void Camera::updateVectors() { + front = glm::vec3(rotation * glm::vec4(0, 0, -1, 1)); + right = glm::vec3(rotation * glm::vec4(1, 0, 0, 1)); + up = glm::vec3(rotation * glm::vec4(0, 1, 0, 1)); + dir = glm::vec3(rotation * glm::vec4(0, 0, -1, 1)); dir.y = 0; float len = glm::length(dir); - if (len > 0.0f){ + if (len > 0.0f) { dir.x /= len; dir.z /= len; } } -void Camera::rotate(float x, float y, float z){ - rotation = glm::rotate(rotation, y, glm::vec3(0,1,0)); - rotation = glm::rotate(rotation, x, glm::vec3(1,0,0)); - rotation = glm::rotate(rotation, z, glm::vec3(0,0,1)); +void Camera::rotate(float x, float y, float z) { + rotation = glm::rotate(rotation, y, glm::vec3(0, 1, 0)); + rotation = glm::rotate(rotation, x, glm::vec3(1, 0, 0)); + rotation = glm::rotate(rotation, z, glm::vec3(0, 0, 1)); updateVectors(); } -glm::mat4 Camera::getProjection(){ +glm::mat4 Camera::getProjection() { float aspect = this->aspect; - if (aspect == 0.0f){ + if (aspect == 0.0f) { aspect = (float)Window::width / (float)Window::height; } if (perspective) - return glm::perspective(fov*zoom, aspect, 0.05f, 1500.0f); + return glm::perspective(fov * zoom, aspect, 0.05f, 1500.0f); + else if (flipped) + return glm::ortho(0.0f, fov * aspect, fov, 0.0f); else - if (flipped) - return glm::ortho(0.0f, fov*aspect, fov, 0.0f); - else - return glm::ortho(0.0f, fov*aspect, 0.0f, fov); + return glm::ortho(0.0f, fov * aspect, 0.0f, fov); } -glm::mat4 Camera::getView(bool pos){ +glm::mat4 Camera::getView(bool pos) { glm::vec3 position = this->position; if (!pos) { position = glm::vec3(0.0f); } if (perspective) { - return glm::lookAt(position, position+front, up); + return glm::lookAt(position, position + front, up); } else { return glm::translate(glm::mat4(1.0f), position); } } -glm::mat4 Camera::getProjView(bool pos){ - return getProjection()*getView(pos); +glm::mat4 Camera::getProjView(bool pos) { + return getProjection() * getView(pos); } void Camera::setFov(float fov) { diff --git a/src/window/Camera.hpp b/src/window/Camera.hpp index 4fded3ec..2c2cccfe 100644 --- a/src/window/Camera.hpp +++ b/src/window/Camera.hpp @@ -29,11 +29,11 @@ public: void rotate(float x, float y, float z); glm::mat4 getProjection(); - glm::mat4 getView(bool position=true); - glm::mat4 getProjView(bool position=true); + glm::mat4 getView(bool position = true); + glm::mat4 getProjView(bool position = true); void setFov(float fov); float getFov() const; }; -#endif // WINDOW_CAMERA_HPP_ +#endif // WINDOW_CAMERA_HPP_ diff --git a/src/window/Events.cpp b/src/window/Events.cpp index 6c237a28..e2d3288e 100644 --- a/src/window/Events.cpp +++ b/src/window/Events.cpp @@ -1,12 +1,13 @@ #include "Events.hpp" -#include "Window.hpp" -#include "../debug/Logger.hpp" -#include "../util/stringutil.hpp" #include #include #include +#include "../debug/Logger.hpp" +#include "../util/stringutil.hpp" +#include "Window.hpp" + static debug::Logger logger("events"); inline constexpr short _MOUSE_KEYS_OFFSET = 1024; @@ -61,7 +62,9 @@ bool Events::jclicked(int button) { void Events::toggleCursor() { cursor_drag = false; _cursor_locked = !_cursor_locked; - Window::setCursorMode(_cursor_locked ? GLFW_CURSOR_DISABLED : GLFW_CURSOR_NORMAL); + Window::setCursorMode( + _cursor_locked ? GLFW_CURSOR_DISABLED : GLFW_CURSOR_NORMAL + ); } void Events::pollEvents() { @@ -79,8 +82,12 @@ void Events::pollEvents() { bool newstate = false; switch (binding.type) { - case inputtype::keyboard: newstate = pressed(binding.code); break; - case inputtype::mouse: newstate = clicked(binding.code); break; + case inputtype::keyboard: + newstate = pressed(binding.code); + break; + case inputtype::mouse: + newstate = clicked(binding.code); + break; } if (newstate) { @@ -101,7 +108,7 @@ void Events::pollEvents() { Binding& Events::getBinding(const std::string& name) { auto found = bindings.find(name); if (found == bindings.end()) { - throw std::runtime_error("binding '"+name+"' does not exists"); + throw std::runtime_error("binding '" + name + "' does not exists"); } return found->second; } @@ -151,17 +158,16 @@ void Events::setPosition(float xpos, float ypos) { if (Events::cursor_drag) { Events::delta.x += xpos - Events::cursor.x; Events::delta.y += ypos - Events::cursor.y; - } - else { + } else { Events::cursor_drag = true; } Events::cursor.x = xpos; Events::cursor.y = ypos; } -#include "../data/dynamic.hpp" #include "../coders/json.hpp" #include "../coders/toml.hpp" +#include "../data/dynamic.hpp" std::string Events::writeBindings() { dynamic::Map obj; @@ -169,20 +175,27 @@ std::string Events::writeBindings() { const auto& binding = entry.second; std::string value; switch (binding.type) { - case inputtype::keyboard: - value = "key:"+input_util::get_name(static_cast(binding.code)); + case inputtype::keyboard: + value = + "key:" + + input_util::get_name(static_cast(binding.code)); break; - case inputtype::mouse: - value = "mouse:"+input_util::get_name(static_cast(binding.code)); + case inputtype::mouse: + value = + "mouse:" + + input_util::get_name(static_cast(binding.code)); break; - default: throw std::runtime_error("unsupported control type"); + default: + throw std::runtime_error("unsupported control type"); } obj.put(entry.first, value); } return toml::stringify(obj); } -void Events::loadBindings(const std::string& filename, const std::string& source) { +void Events::loadBindings( + const std::string& filename, const std::string& source +) { auto map = toml::parse(filename, source); for (auto& entry : map->values) { if (auto value = std::get_if(&entry.second)) { @@ -196,8 +209,9 @@ void Events::loadBindings(const std::string& filename, const std::string& source type = inputtype::mouse; code = static_cast(input_util::mousecode_from(codename)); } else { - logger.error() << "unknown input type: " << prefix - << " (binding " << util::quote(entry.first) << ")"; + logger.error() + << "unknown input type: " << prefix << " (binding " + << util::quote(entry.first) << ")"; continue; } Events::bind(entry.first, type, code); diff --git a/src/window/Events.hpp b/src/window/Events.hpp index 18402488..5977d8ae 100644 --- a/src/window/Events.hpp +++ b/src/window/Events.hpp @@ -1,12 +1,12 @@ #ifndef WINDOW_EVENTS_HPP_ #define WINDOW_EVENTS_HPP_ -#include "input.hpp" -#include "../typedefs.hpp" - #include -#include #include +#include + +#include "../typedefs.hpp" +#include "input.hpp" inline constexpr short KEYS_BUFFER_SIZE = 1036; @@ -52,7 +52,9 @@ public: static void setPosition(float xpos, float ypos); static std::string writeBindings(); - static void loadBindings(const std::string& filename, const std::string& source); + static void loadBindings( + const std::string& filename, const std::string& source + ); }; -#endif // WINDOW_EVENTS_HPP_ +#endif // WINDOW_EVENTS_HPP_ diff --git a/src/window/Window.cpp b/src/window/Window.cpp index bb266afe..798e862e 100644 --- a/src/window/Window.cpp +++ b/src/window/Window.cpp @@ -1,16 +1,18 @@ -#include #include "Window.hpp" -#include "Events.hpp" + +#include +#include + +#include +#include +#include + #include "../debug/Logger.hpp" #include "../graphics/core/ImageData.hpp" #include "../graphics/core/Texture.hpp" #include "../settings.hpp" #include "../util/ObjectsKeeper.hpp" - -#include -#include -#include -#include +#include "Events.hpp" static debug::Logger logger("window"); @@ -36,16 +38,16 @@ void mouse_button_callback(GLFWwindow*, int button, int action, int) { Events::setButton(button, action == GLFW_PRESS); } -void key_callback(GLFWwindow*, int key, int /*scancode*/, int action, int /*mode*/) { +void key_callback( + GLFWwindow*, int key, int /*scancode*/, int action, int /*mode*/ +) { if (key == GLFW_KEY_UNKNOWN) return; if (action == GLFW_PRESS) { Events::setKey(key, true); Events::pressedKeys.push_back(static_cast(key)); - } - else if (action == GLFW_RELEASE) { + } else if (action == GLFW_RELEASE) { Events::setKey(key, false); - } - else if (action == GLFW_REPEAT) { + } else if (action == GLFW_REPEAT) { Events::pressedKeys.push_back(static_cast(key)); } } @@ -82,24 +84,36 @@ void window_size_callback(GLFWwindow*, int width, int height) { Window::resetScissor(); } -void character_callback(GLFWwindow*, unsigned int codepoint){ +void character_callback(GLFWwindow*, unsigned int codepoint) { Events::codepoints.push_back(codepoint); } const char* glfwErrorName(int error) { switch (error) { - case GLFW_NO_ERROR: return "no error"; - case GLFW_NOT_INITIALIZED: return "not initialized"; - case GLFW_NO_CURRENT_CONTEXT: return "no current context"; - case GLFW_INVALID_ENUM: return "invalid enum"; - case GLFW_INVALID_VALUE: return "invalid value"; - case GLFW_OUT_OF_MEMORY: return "out of memory"; - case GLFW_API_UNAVAILABLE: return "api unavailable"; - case GLFW_VERSION_UNAVAILABLE: return "version unavailable"; - case GLFW_PLATFORM_ERROR: return "platform error"; - case GLFW_FORMAT_UNAVAILABLE: return "format unavailable"; - case GLFW_NO_WINDOW_CONTEXT: return "no window context"; - default: return "unknown error"; + case GLFW_NO_ERROR: + return "no error"; + case GLFW_NOT_INITIALIZED: + return "not initialized"; + case GLFW_NO_CURRENT_CONTEXT: + return "no current context"; + case GLFW_INVALID_ENUM: + return "invalid enum"; + case GLFW_INVALID_VALUE: + return "invalid value"; + case GLFW_OUT_OF_MEMORY: + return "out of memory"; + case GLFW_API_UNAVAILABLE: + return "api unavailable"; + case GLFW_VERSION_UNAVAILABLE: + return "version unavailable"; + case GLFW_PLATFORM_ERROR: + return "platform error"; + case GLFW_FORMAT_UNAVAILABLE: + return "format unavailable"; + case GLFW_NO_WINDOW_CONTEXT: + return "no window context"; + default: + return "unknown error"; } } @@ -111,14 +125,14 @@ void error_callback(int error, const char* description) { } } -int Window::initialize(DisplaySettings* settings){ +int Window::initialize(DisplaySettings* settings) { Window::settings = settings; Window::width = settings->width.get(); Window::height = settings->height.get(); - std::string title = "VoxelEngine-Cpp v" + - std::to_string(ENGINE_VERSION_MAJOR) + "." + - std::to_string(ENGINE_VERSION_MINOR); + std::string title = "VoxelEngine-Cpp v" + + std::to_string(ENGINE_VERSION_MAJOR) + "." + + std::to_string(ENGINE_VERSION_MINOR); glfwSetErrorCallback(error_callback); if (glfwInit() == GLFW_FALSE) { @@ -139,7 +153,7 @@ int Window::initialize(DisplaySettings* settings){ glfwWindowHint(GLFW_SAMPLES, settings->samples.get()); window = glfwCreateWindow(width, height, title.c_str(), nullptr, nullptr); - if (window == nullptr){ + if (window == nullptr) { logger.error() << "failed to create GLFW window"; glfwTerminate(); return -1; @@ -147,24 +161,26 @@ int Window::initialize(DisplaySettings* settings){ glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; - + GLenum glewErr = glewInit(); - if (glewErr != GLEW_OK){ + if (glewErr != GLEW_OK) { if (glewErr == GLEW_ERROR_NO_GLX_DISPLAY) { // see issue #240 - logger.warning() << "glewInit() returned GLEW_ERROR_NO_GLX_DISPLAY; ignored"; + logger.warning() + << "glewInit() returned GLEW_ERROR_NO_GLX_DISPLAY; ignored"; } else { - logger.error() << "failed to initialize GLEW:\n" << glewGetErrorString(glewErr); + logger.error() << "failed to initialize GLEW:\n" + << glewGetErrorString(glewErr); return -1; } } - glViewport(0,0, width, height); - glClearColor(0.0f,0.0f,0.0f, 1); + glViewport(0, 0, width, height); + glClearColor(0.0f, 0.0f, 0.0f, 1); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - GLint maxTextureSize[1]{static_cast(Texture::MAX_RESOLUTION)}; + GLint maxTextureSize[1] {static_cast(Texture::MAX_RESOLUTION)}; glGetIntegerv(GL_MAX_TEXTURE_SIZE, maxTextureSize); if (maxTextureSize[0] > 0) { Texture::MAX_RESOLUTION = maxTextureSize[0]; @@ -179,11 +195,14 @@ int Window::initialize(DisplaySettings* settings){ glfwSetScrollCallback(window, scroll_callback); observers_keeper = util::ObjectsKeeper(); - observers_keeper.keepAlive(settings->fullscreen.observe([=](bool value) { - if (value != isFullscreen()) { - toggleFullscreen(); - } - }, true)); + observers_keeper.keepAlive(settings->fullscreen.observe( + [=](bool value) { + if (value != isFullscreen()) { + toggleFullscreen(); + } + }, + true + )); glfwSwapInterval(1); setFramerate(settings->framerate.get()); @@ -213,11 +232,11 @@ void Window::setBgColor(glm::vec4 color) { glClearColor(color.r, color.g, color.b, color.a); } -void Window::viewport(int x, int y, int width, int height){ +void Window::viewport(int x, int y, int width, int height) { glViewport(x, y, width, height); } -void Window::setCursorMode(int mode){ +void Window::setCursorMode(int mode) { glfwSetInputMode(window, GLFW_CURSOR, mode); } @@ -245,9 +264,12 @@ void Window::pushScissor(glm::vec4 area) { if (area.z < 0.0f || area.w < 0.0f) { glScissor(0, 0, 0, 0); } else { - glScissor(area.x, Window::height-area.w, - std::max(0, int(area.z-area.x)), - std::max(0, int(area.w-area.y))); + glScissor( + area.x, + Window::height - area.w, + std::max(0, int(area.z - area.x)), + std::max(0, int(area.w - area.y)) + ); } scissorArea = area; } @@ -262,9 +284,12 @@ void Window::popScissor() { if (area.z < 0.0f || area.w < 0.0f) { glScissor(0, 0, 0, 0); } else { - glScissor(area.x, Window::height-area.w, - std::max(0, int(area.z-area.x)), - std::max(0, int(area.w-area.y))); + glScissor( + area.x, + Window::height - area.w, + std::max(0, int(area.z - area.x)), + std::max(0, int(area.w - area.y)) + ); } if (scissorStack.empty()) { glDisable(GL_SCISSOR_TEST); @@ -272,16 +297,16 @@ void Window::popScissor() { scissorArea = area; } -void Window::terminate(){ +void Window::terminate() { observers_keeper = util::ObjectsKeeper(); glfwTerminate(); } -bool Window::isShouldClose(){ +bool Window::isShouldClose() { return glfwWindowShouldClose(window); } -void Window::setShouldClose(bool flag){ +void Window::setShouldClose(bool flag) { glfwSetWindowShouldClose(window, flag); } @@ -292,7 +317,7 @@ void Window::setFramerate(int framerate) { Window::framerate = framerate; } -void Window::toggleFullscreen(){ +void Window::toggleFullscreen() { fullscreen = !fullscreen; GLFWmonitor* monitor = glfwGetPrimaryMonitor(); @@ -302,12 +327,17 @@ void Window::toggleFullscreen(){ if (fullscreen) { glfwGetWindowPos(window, &posX, &posY); - glfwSetWindowMonitor(window, monitor, 0, 0, mode->width, mode->height, GLFW_DONT_CARE); - } - else { - glfwSetWindowMonitor(window, nullptr, - posX, posY, - settings->width.get(), settings->height.get(), + glfwSetWindowMonitor( + window, monitor, 0, 0, mode->width, mode->height, GLFW_DONT_CARE + ); + } else { + glfwSetWindowMonitor( + window, + nullptr, + posX, + posY, + settings->width.get(), + settings->height.get(), GLFW_DONT_CARE ); glfwSetWindowAttrib(window, GLFW_MAXIMIZED, GLFW_FALSE); @@ -327,8 +357,9 @@ void Window::swapBuffers() { Window::resetScissor(); double currentTime = time(); if (framerate > 0 && currentTime - prevSwap < (1.0 / framerate)) { - std::this_thread::sleep_for(std::chrono::milliseconds( - static_cast((1.0/framerate - (currentTime-prevSwap))*1000))); + std::this_thread::sleep_for(std::chrono::milliseconds(static_cast( + (1.0 / framerate - (currentTime - prevSwap)) * 1000 + ))); } prevSwap = time(); } @@ -361,18 +392,26 @@ void Window::setClipboardText(const char* text) { bool Window::tryToMaximize(GLFWwindow* window, GLFWmonitor* monitor) { glm::ivec4 windowFrame(0); glm::ivec4 workArea(0); - glfwGetWindowFrameSize(window, &windowFrame.x, &windowFrame.y, &windowFrame.z, &windowFrame.w); - glfwGetMonitorWorkarea(monitor, &workArea.x, &workArea.y, &workArea.z, &workArea.w); + glfwGetWindowFrameSize( + window, &windowFrame.x, &windowFrame.y, &windowFrame.z, &windowFrame.w + ); + glfwGetMonitorWorkarea( + monitor, &workArea.x, &workArea.y, &workArea.z, &workArea.w + ); if (Window::width > (uint)workArea.z) Window::width = (uint)workArea.z; if (Window::height > (uint)workArea.w) Window::height = (uint)workArea.w; if (Window::width >= (uint)(workArea.z - (windowFrame.x + windowFrame.z)) && - Window::height >= (uint)(workArea.w - (windowFrame.y + windowFrame.w))) { + Window::height >= + (uint)(workArea.w - (windowFrame.y + windowFrame.w))) { glfwMaximizeWindow(window); return true; } glfwSetWindowSize(window, Window::width, Window::height); - glfwSetWindowPos(window, workArea.x + (workArea.z - Window::width) / 2, - workArea.y + (workArea.w - Window::height) / 2 + windowFrame.y / 2); + glfwSetWindowPos( + window, + workArea.x + (workArea.z - Window::width) / 2, + workArea.y + (workArea.w - Window::height) / 2 + windowFrame.y / 2 + ); return false; } @@ -380,7 +419,6 @@ void Window::setIcon(const ImageData* image) { GLFWimage icon { static_cast(image->getWidth()), static_cast(image->getHeight()), - image->getData() - }; + image->getData()}; glfwSetWindowIcon(window, 1, &icon); } diff --git a/src/window/Window.hpp b/src/window/Window.hpp index 44e6e7b6..a19ed5bc 100644 --- a/src/window/Window.hpp +++ b/src/window/Window.hpp @@ -1,12 +1,12 @@ #ifndef WINDOW_WINDOW_HPP_ #define WINDOW_WINDOW_HPP_ -#include "../typedefs.hpp" - +#include +#include #include #include -#include -#include + +#include "../typedefs.hpp" class ImageData; struct DisplaySettings; @@ -64,4 +64,4 @@ public: static std::unique_ptr takeScreenshot(); }; -#endif // WINDOW_WINDOW_HPP_ +#endif // WINDOW_WINDOW_HPP_ diff --git a/src/window/input.cpp b/src/window/input.cpp index cfb06e84..14117a41 100644 --- a/src/window/input.cpp +++ b/src/window/input.cpp @@ -1,10 +1,12 @@ #include "input.hpp" + #include + #include #ifdef _WIN32 #include -#endif // _WIN32 +#endif // _WIN32 static std::unordered_map keycodes { {"enter", GLFW_KEY_ENTER}, @@ -44,10 +46,14 @@ static std::unordered_map keynames {}; std::string input_util::get_name(mousecode code) { switch (code) { - case mousecode::BUTTON_1: return "left"; - case mousecode::BUTTON_2: return "right"; - case mousecode::BUTTON_3: return "middle"; - default: return "unknown"; + case mousecode::BUTTON_1: + return "left"; + case mousecode::BUTTON_2: + return "right"; + case mousecode::BUTTON_3: + return "middle"; + default: + return "unknown"; } } @@ -74,13 +80,13 @@ void Binding::reset(mousecode code) { void input_util::initialize() { for (int i = 0; i <= 9; i++) { - keycodes[std::to_string(i)] = GLFW_KEY_0+i; + keycodes[std::to_string(i)] = GLFW_KEY_0 + i; } for (int i = 0; i < 25; i++) { - keycodes["f"+std::to_string(i+1)] = GLFW_KEY_F1+i; + keycodes["f" + std::to_string(i + 1)] = GLFW_KEY_F1 + i; } for (char i = 'a'; i <= 'z'; i++) { - keycodes[std::string({i})] = GLFW_KEY_A-'a'+i; + keycodes[std::string({i})] = GLFW_KEY_A - 'a' + i; } for (const auto& entry : keycodes) { keynames[entry.second] = entry.first; @@ -107,66 +113,112 @@ std::string input_util::to_string(keycode code) { int icode_repr = static_cast(code); #ifdef _WIN32 char name[64]; - int result = GetKeyNameTextA(glfwGetKeyScancode(icode_repr) << 16, name, 64); + int result = + GetKeyNameTextA(glfwGetKeyScancode(icode_repr) << 16, name, 64); if (result == NULL) return "Unknown"; return std::string(name); #else - const char* name = glfwGetKeyName(icode_repr, glfwGetKeyScancode(icode_repr)); + const char* name = + glfwGetKeyName(icode_repr, glfwGetKeyScancode(icode_repr)); if (name == nullptr) { switch (icode_repr) { - case GLFW_KEY_TAB: return "Tab"; - case GLFW_KEY_LEFT_CONTROL: return "Left Ctrl"; - case GLFW_KEY_RIGHT_CONTROL: return "Right Ctrl"; - case GLFW_KEY_LEFT_ALT: return "Left Alt"; - case GLFW_KEY_RIGHT_ALT: return "Right Alt"; - case GLFW_KEY_LEFT_SHIFT: return "Left Shift"; - case GLFW_KEY_RIGHT_SHIFT: return "Right Shift"; - case GLFW_KEY_CAPS_LOCK: return "Caps-Lock"; - case GLFW_KEY_SPACE: return "Space"; - case GLFW_KEY_ESCAPE: return "Esc"; - case GLFW_KEY_ENTER: return "Enter"; - case GLFW_KEY_UP: return "Up"; - case GLFW_KEY_DOWN: return "Down"; - case GLFW_KEY_LEFT: return "Left"; - case GLFW_KEY_RIGHT: return "Right"; - case GLFW_KEY_BACKSPACE: return "Backspace"; - case GLFW_KEY_F1: return "F1"; - case GLFW_KEY_F2: return "F2"; - case GLFW_KEY_F3: return "F3"; - case GLFW_KEY_F4: return "F4"; - case GLFW_KEY_F5: return "F5"; - case GLFW_KEY_F6: return "F6"; - case GLFW_KEY_F7: return "F7"; - case GLFW_KEY_F8: return "F8"; - case GLFW_KEY_F9: return "F9"; - case GLFW_KEY_F10: return "F10"; - case GLFW_KEY_F11: return "F11"; - case GLFW_KEY_F12: return "F12"; - case GLFW_KEY_DELETE: return "Delete"; - case GLFW_KEY_HOME: return "Home"; - case GLFW_KEY_END: return "End"; - case GLFW_KEY_LEFT_SUPER: return "Left Super"; - case GLFW_KEY_RIGHT_SUPER: return "Right Super"; - case GLFW_KEY_PAGE_UP: return "Page Up"; - case GLFW_KEY_PAGE_DOWN: return "Page Down"; - case GLFW_KEY_INSERT: return "Insert"; - case GLFW_KEY_PRINT_SCREEN: return "Print Screen"; - case GLFW_KEY_NUM_LOCK: return "Num Lock"; - case GLFW_KEY_MENU: return "Menu"; - case GLFW_KEY_PAUSE: return "Pause"; - default: - return "Unknown"; + case GLFW_KEY_TAB: + return "Tab"; + case GLFW_KEY_LEFT_CONTROL: + return "Left Ctrl"; + case GLFW_KEY_RIGHT_CONTROL: + return "Right Ctrl"; + case GLFW_KEY_LEFT_ALT: + return "Left Alt"; + case GLFW_KEY_RIGHT_ALT: + return "Right Alt"; + case GLFW_KEY_LEFT_SHIFT: + return "Left Shift"; + case GLFW_KEY_RIGHT_SHIFT: + return "Right Shift"; + case GLFW_KEY_CAPS_LOCK: + return "Caps-Lock"; + case GLFW_KEY_SPACE: + return "Space"; + case GLFW_KEY_ESCAPE: + return "Esc"; + case GLFW_KEY_ENTER: + return "Enter"; + case GLFW_KEY_UP: + return "Up"; + case GLFW_KEY_DOWN: + return "Down"; + case GLFW_KEY_LEFT: + return "Left"; + case GLFW_KEY_RIGHT: + return "Right"; + case GLFW_KEY_BACKSPACE: + return "Backspace"; + case GLFW_KEY_F1: + return "F1"; + case GLFW_KEY_F2: + return "F2"; + case GLFW_KEY_F3: + return "F3"; + case GLFW_KEY_F4: + return "F4"; + case GLFW_KEY_F5: + return "F5"; + case GLFW_KEY_F6: + return "F6"; + case GLFW_KEY_F7: + return "F7"; + case GLFW_KEY_F8: + return "F8"; + case GLFW_KEY_F9: + return "F9"; + case GLFW_KEY_F10: + return "F10"; + case GLFW_KEY_F11: + return "F11"; + case GLFW_KEY_F12: + return "F12"; + case GLFW_KEY_DELETE: + return "Delete"; + case GLFW_KEY_HOME: + return "Home"; + case GLFW_KEY_END: + return "End"; + case GLFW_KEY_LEFT_SUPER: + return "Left Super"; + case GLFW_KEY_RIGHT_SUPER: + return "Right Super"; + case GLFW_KEY_PAGE_UP: + return "Page Up"; + case GLFW_KEY_PAGE_DOWN: + return "Page Down"; + case GLFW_KEY_INSERT: + return "Insert"; + case GLFW_KEY_PRINT_SCREEN: + return "Print Screen"; + case GLFW_KEY_NUM_LOCK: + return "Num Lock"; + case GLFW_KEY_MENU: + return "Menu"; + case GLFW_KEY_PAUSE: + return "Pause"; + default: + return "Unknown"; } } return std::string(name); -#endif // _WIN32 +#endif // _WIN32 } std::string input_util::to_string(mousecode code) { switch (code) { - case mousecode::BUTTON_1: return "LMB"; - case mousecode::BUTTON_2: return "RMB"; - case mousecode::BUTTON_3: return "MMB"; - default: return "unknown button"; + case mousecode::BUTTON_1: + return "LMB"; + case mousecode::BUTTON_2: + return "RMB"; + case mousecode::BUTTON_3: + return "MMB"; + default: + return "unknown button"; } } diff --git a/src/window/input.hpp b/src/window/input.hpp index fe991e4b..5cc51671 100644 --- a/src/window/input.hpp +++ b/src/window/input.hpp @@ -1,10 +1,10 @@ #ifndef WINDOW_INPUT_HPP_ #define WINDOW_INPUT_HPP_ -#include "../util/RunnablesList.hpp" - #include +#include "../util/RunnablesList.hpp" + /// @brief Represents glfw3 keycode values. enum class keycode : int { SPACE = 32, @@ -100,17 +100,14 @@ enum class keycode : int { /// @brief Represents glfw3 mouse button IDs. /// @details There is a subset of glfw3 mouse button IDs. enum class mousecode : int { - BUTTON_1 = 0, // Left mouse button - BUTTON_2 = 1, // Right mouse button - BUTTON_3 = 2, // Middle mouse button + BUTTON_1 = 0, // Left mouse button + BUTTON_2 = 1, // Right mouse button + BUTTON_3 = 2, // Middle mouse button UNKNOWN = -1, }; inline mousecode MOUSECODES_ALL[] { - mousecode::BUTTON_1, - mousecode::BUTTON_2, - mousecode::BUTTON_3 -}; + mousecode::BUTTON_1, mousecode::BUTTON_2, mousecode::BUTTON_3}; namespace input_util { void initialize(); @@ -141,9 +138,10 @@ struct Binding { int code; bool state = false; bool justChange = false; - + Binding() = default; - Binding(inputtype type, int code) : type(type), code(code) {} + Binding(inputtype type, int code) : type(type), code(code) { + } bool active() const { return state; @@ -152,23 +150,22 @@ struct Binding { bool jactive() const { return state && justChange; } - + void reset(inputtype, int); void reset(keycode); void reset(mousecode); inline std::string text() const { switch (type) { - case inputtype::keyboard: { - return input_util::to_string(static_cast(code)); - } - case inputtype::mouse: { - return input_util::to_string(static_cast(code)); - } + case inputtype::keyboard: { + return input_util::to_string(static_cast(code)); + } + case inputtype::mouse: { + return input_util::to_string(static_cast(code)); + } } return ""; } }; - -#endif // WINDOW_INPUT_HPP_ +#endif // WINDOW_INPUT_HPP_ diff --git a/src/world/Level.cpp b/src/world/Level.cpp index 2195a20a..f27ae8d8 100644 --- a/src/world/Level.cpp +++ b/src/world/Level.cpp @@ -1,33 +1,34 @@ #include "Level.hpp" -#include "World.hpp" -#include "LevelEvents.hpp" -#include "../settings.hpp" + #include "../content/Content.hpp" +#include "../data/dynamic_util.hpp" +#include "../items/Inventories.hpp" +#include "../items/Inventory.hpp" #include "../lighting/Lighting.hpp" +#include "../objects/Entities.hpp" +#include "../objects/Player.hpp" +#include "../physics/Hitbox.hpp" +#include "../physics/PhysicsSolver.hpp" +#include "../settings.hpp" #include "../voxels/Chunk.hpp" #include "../voxels/Chunks.hpp" #include "../voxels/ChunksStorage.hpp" -#include "../physics/Hitbox.hpp" -#include "../physics/PhysicsSolver.hpp" -#include "../objects/Player.hpp" -#include "../objects/Entities.hpp" -#include "../items/Inventory.hpp" -#include "../items/Inventories.hpp" #include "../window/Camera.hpp" -#include "../data/dynamic_util.hpp" +#include "LevelEvents.hpp" +#include "World.hpp" Level::Level( std::unique_ptr worldPtr, const Content* content, EngineSettings& settings -) : world(std::move(worldPtr)), - content(content), - chunksStorage(std::make_unique(this)), - physics(std::make_unique(glm::vec3(0, -22.6f, 0))), - events(std::make_unique()), - entities(std::make_unique(this)), - settings(settings) -{ +) + : world(std::move(worldPtr)), + content(content), + chunksStorage(std::make_unique(this)), + physics(std::make_unique(glm::vec3(0, -22.6f, 0))), + events(std::make_unique()), + entities(std::make_unique(this)), + settings(settings) { auto& cameraIndices = content->getIndices(ResourceType::CAMERA); for (size_t i = 0; i < cameraIndices.size(); i++) { auto camera = std::make_shared(); @@ -48,45 +49,45 @@ Level::Level( if (world->nextEntityId) { entities->setNextID(world->nextEntityId); } - auto inv = std::make_shared( + auto inv = std::make_shared( world->getNextInventoryId(), DEF_PLAYER_INVENTORY_SIZE ); - auto player = spawnObject( + auto player = spawnObject( this, glm::vec3(0, DEF_PLAYER_Y, 0), DEF_PLAYER_SPEED, inv, 0 ); - uint matrixSize = ( - settings.chunks.loadDistance.get() + - settings.chunks.padding.get() - ) * 2; + uint matrixSize = + (settings.chunks.loadDistance.get() + settings.chunks.padding.get()) * + 2; chunks = std::make_unique( - matrixSize, matrixSize, 0, 0, world->wfile.get(), this - ); - lighting = std::make_unique(content, chunks.get()); + matrixSize, matrixSize, 0, 0, world->wfile.get(), this + ); + lighting = std::make_unique(content, chunks.get()); - events->listen(EVT_CHUNK_HIDDEN, [this](lvl_event_type, Chunk* chunk) { - this->chunksStorage->remove(chunk->x, chunk->z); - }); + events->listen(EVT_CHUNK_HIDDEN, [this](lvl_event_type, Chunk* chunk) { + this->chunksStorage->remove(chunk->x, chunk->z); + }); - inventories = std::make_unique(*this); - inventories->store(player->getInventory()); + inventories = std::make_unique(*this); + inventories->store(player->getInventory()); } -Level::~Level(){ - for(auto obj : objects) { - obj.reset(); - } +Level::~Level() { + for (auto obj : objects) { + obj.reset(); + } } void Level::loadMatrix(int32_t x, int32_t z, uint32_t radius) { - chunks->setCenter(x, z); + chunks->setCenter(x, z); uint32_t diameter = std::min( - radius*2LL, - (settings.chunks.loadDistance.get() + settings.chunks.padding.get()) * 2LL + radius * 2LL, + (settings.chunks.loadDistance.get() + settings.chunks.padding.get()) * + 2LL ); - if (chunks->w != diameter) { - chunks->resize(diameter, diameter); - } + if (chunks->w != diameter) { + chunks->resize(diameter, diameter); + } } World* Level::getWorld() { diff --git a/src/world/Level.hpp b/src/world/Level.hpp index cb2c0710..04faa6a7 100644 --- a/src/world/Level.hpp +++ b/src/world/Level.hpp @@ -1,11 +1,11 @@ #ifndef WORLD_LEVEL_HPP_ #define WORLD_LEVEL_HPP_ -#include "../interfaces/Object.hpp" - #include #include +#include "../interfaces/Object.hpp" + inline constexpr float DEF_PLAYER_Y = 100.0f; inline constexpr float DEF_PLAYER_SPEED = 4.0f; inline constexpr int DEF_PLAYER_INVENTORY_SIZE = 40; @@ -36,42 +36,49 @@ public: std::unique_ptr lighting; std::unique_ptr events; std::unique_ptr entities; - std::vector> cameras; // move somewhere? + std::vector> cameras; // move somewhere? const EngineSettings& settings; Level( - std::unique_ptr world, - const Content* content, + std::unique_ptr world, + const Content* content, EngineSettings& settings ); ~Level(); void loadMatrix(int32_t x, int32_t z, uint32_t radius); - + World* getWorld(); /// Spawns object of class T and returns pointer to it. /// @param T class that derives the Object class /// @param args pass arguments needed for T class constructor - template + template std::shared_ptr spawnObject(Args&&... args) { - static_assert(std::is_base_of::value, "T must be a derived of Object class"); + static_assert( + std::is_base_of::value, + "T must be a derived of Object class" + ); std::shared_ptr tObj = std::make_shared(args...); - - std::shared_ptr obj = std::dynamic_pointer_cast(tObj); + + std::shared_ptr obj = + std::dynamic_pointer_cast(tObj); obj->objectUID = objects.size(); objects.push_back(obj); obj->spawned(); return tObj; } - template + template std::shared_ptr getObject(uint64_t id) { - static_assert(std::is_base_of::value, "T must be a derived of Object class"); + static_assert( + std::is_base_of::value, + "T must be a derived of Object class" + ); if (id >= objects.size()) return nullptr; std::shared_ptr object = std::dynamic_pointer_cast(objects[id]); - return object; + return object; } void onSave(); diff --git a/src/world/LevelEvents.cpp b/src/world/LevelEvents.cpp index a5045802..12bedc1a 100644 --- a/src/world/LevelEvents.cpp +++ b/src/world/LevelEvents.cpp @@ -1,16 +1,17 @@ #include "LevelEvents.hpp" + #include "../voxels/Chunk.hpp" using std::vector; void LevelEvents::listen(lvl_event_type type, const chunk_event_func& func) { - auto& callbacks = chunk_callbacks[type]; - callbacks.push_back(func); + auto& callbacks = chunk_callbacks[type]; + callbacks.push_back(func); } void LevelEvents::trigger(lvl_event_type type, Chunk* chunk) { - const auto& callbacks = chunk_callbacks[type]; - for (const chunk_event_func& func : callbacks) { - func(type, chunk); - } + const auto& callbacks = chunk_callbacks[type]; + for (const chunk_event_func& func : callbacks) { + func(type, chunk); + } } diff --git a/src/world/LevelEvents.hpp b/src/world/LevelEvents.hpp index 605c5c18..7e3247ed 100644 --- a/src/world/LevelEvents.hpp +++ b/src/world/LevelEvents.hpp @@ -2,8 +2,8 @@ #define WORLD_LEVEL_EVENTS_HPP_ #include -#include #include +#include class Chunk; @@ -14,10 +14,11 @@ enum lvl_event_type { using chunk_event_func = std::function; class LevelEvents { - std::unordered_map> chunk_callbacks; + std::unordered_map> + chunk_callbacks; public: void listen(lvl_event_type type, const chunk_event_func& func); void trigger(lvl_event_type type, Chunk* chunk); }; -#endif // WORLD_LEVEL_EVENTS_HPP_ +#endif // WORLD_LEVEL_EVENTS_HPP_ diff --git a/src/world/World.cpp b/src/world/World.cpp index c8ad542a..e6cff781 100644 --- a/src/world/World.cpp +++ b/src/world/World.cpp @@ -1,49 +1,48 @@ #include "World.hpp" -#include "Level.hpp" +#include +#include +#include -#include "../settings.hpp" #include "../content/Content.hpp" #include "../content/ContentLUT.hpp" #include "../debug/Logger.hpp" #include "../files/WorldFiles.hpp" #include "../items/Inventories.hpp" -#include "../objects/Player.hpp" #include "../objects/Entities.hpp" +#include "../objects/Player.hpp" +#include "../settings.hpp" #include "../voxels/Chunk.hpp" #include "../voxels/Chunks.hpp" #include "../voxels/ChunksStorage.hpp" #include "../world/WorldGenerators.hpp" #include "Level.hpp" -#include -#include -#include - static debug::Logger logger("world"); -const float DAYIME_SPECIFIC_SPEED = 1.0f/1440.0f; //1.0f/60.0f/24.0f; +const float DAYIME_SPECIFIC_SPEED = 1.0f / 1440.0f; // 1.0f/60.0f/24.0f; world_load_error::world_load_error(const std::string& message) : std::runtime_error(message) { } World::World( - std::string name, + std::string name, std::string generator, const fs::path& directory, - uint64_t seed, + uint64_t seed, EngineSettings& settings, const Content* content, const std::vector& packs -) : name(std::move(name)), - generator(std::move(generator)), - seed(seed), - content(content), - packs(packs), - wfile(std::make_unique(directory, settings.debug)) -{} +) + : name(std::move(name)), + generator(std::move(generator)), + seed(seed), + content(content), + packs(packs), + wfile(std::make_unique(directory, settings.debug)) { +} -World::~World(){ +World::~World() { } void World::updateTimers(float delta) { @@ -74,7 +73,7 @@ void World::write(Level* level) { level->chunks->saveAll(); nextEntityId = level->entities->peekNextID(); wfile->write(this, content); - + auto playerFile = dynamic::Map(); auto& players = playerFile.putList("players"); for (const auto& object : level->objects) { @@ -92,7 +91,7 @@ std::unique_ptr World::create( const std::string& generator, const fs::path& directory, uint64_t seed, - EngineSettings& settings, + EngineSettings& settings, const Content* content, const std::vector& packs ) { @@ -109,7 +108,13 @@ std::unique_ptr World::load( const std::vector& packs ) { auto world = std::make_unique( - ".", WorldGenerators::getDefaultGeneratorID(), directory, 0, settings, content, packs + ".", + WorldGenerators::getDefaultGeneratorID(), + directory, + 0, + settings, + content, + packs ); auto& wfile = world->wfile; @@ -131,8 +136,8 @@ std::unique_ptr World::load( for (size_t i = 0; i < players->size(); i++) { auto player = level->spawnObject( level.get(), - glm::vec3(0, DEF_PLAYER_Y, 0), - DEF_PLAYER_SPEED, + glm::vec3(0, DEF_PLAYER_Y, 0), + DEF_PLAYER_SPEED, level->inventories->create(DEF_PLAYER_INVENTORY_SIZE), 0 ); @@ -150,10 +155,9 @@ std::unique_ptr World::load( } std::shared_ptr World::checkIndices( - const fs::path& directory, - const Content* content + const fs::path& directory, const Content* content ) { - fs::path indicesFile = directory/fs::path("indices.json"); + fs::path indicesFile = directory / fs::path("indices.json"); if (fs::is_regular_file(indicesFile)) { return ContentLUT::create(indicesFile, content); } @@ -170,8 +174,7 @@ void World::setGenerator(const std::string& generator) { bool World::hasPack(const std::string& id) const { for (auto& pack : packs) { - if (pack.id == id) - return true; + if (pack.id == id) return true; } return false; } @@ -205,7 +208,7 @@ void World::deserialize(dynamic::Map* root) { generator = WorldGenerators::getDefaultGeneratorID(); } if (auto verobj = root->map("version")) { - int major=0, minor=-1; + int major = 0, minor = -1; verobj->num("major", major); verobj->num("minor", minor); logger.info() << "world version: " << major << "." << minor; @@ -232,7 +235,7 @@ std::unique_ptr World::serialize() const { root->put("name", name); root->put("generator", generator); root->put("seed", static_cast(seed)); - + auto& timeobj = root->putMap("time"); timeobj.put("day-time", daytime); timeobj.put("day-time-speed", daytimeSpeed); diff --git a/src/world/World.hpp b/src/world/World.hpp index f3e14513..2c4eac32 100644 --- a/src/world/World.hpp +++ b/src/world/World.hpp @@ -1,16 +1,16 @@ #ifndef WORLD_WORLD_HPP_ #define WORLD_WORLD_HPP_ -#include "../typedefs.hpp" -#include "../util/timeutil.hpp" -#include "../data/dynamic.hpp" -#include "../interfaces/Serializable.hpp" -#include "../content/ContentPack.hpp" - +#include +#include #include #include -#include -#include + +#include "../content/ContentPack.hpp" +#include "../data/dynamic.hpp" +#include "../interfaces/Serializable.hpp" +#include "../typedefs.hpp" +#include "../util/timeutil.hpp" class Content; class WorldFiles; @@ -22,7 +22,7 @@ namespace fs = std::filesystem; class world_load_error : public std::runtime_error { public: - world_load_error(const std::string &message); + world_load_error(const std::string& message); }; /// @brief holds all world data except the level (chunks and objects) @@ -39,27 +39,27 @@ class World : Serializable { public: std::unique_ptr wfile; - /// @brief Day/night loop timer in range 0..1 where + /// @brief Day/night loop timer in range 0..1 where /// 0.0 - is midnight and /// 0.5 - is noon float daytime = timeutil::time_value(10, 00, 00); // looking bad float daytimeSpeed = 1.0f; - + /// @brief total time passed in the world (not depending on daytimeSpeed) double totalTime = 0.0; - /// @brief will be replaced with weather in future + /// @brief will be replaced with weather in future float fog = 0.0f; entityid_t nextEntityId = 0; World( - std::string name, + std::string name, std::string generator, const fs::path& directory, - uint64_t seed, + uint64_t seed, EngineSettings& settings, const Content* content, const std::vector& packs @@ -70,14 +70,14 @@ public: /// @brief Update world day-time and total time /// @param delta delta-time void updateTimers(float delta); - + /// @brief Write all unsaved level data to the world directory void write(Level* level); - /// @brief Check world indices and generate ContentLUT if convert required + /// @brief Check world indices and generate ContentLUT if convert required /// @param directory world directory /// @param content current Content instance - /// @return ContentLUT if world convert required else nullptr + /// @return ContentLUT if world convert required else nullptr static std::shared_ptr checkIndices( const fs::path& directory, const Content* content ); @@ -88,7 +88,7 @@ public: /// @param type of the world /// @param seed world generation seed /// @param settings current engine settings - /// @param content current engine Content instance + /// @param content current engine Content instance /// with all world content-packs applied /// @param packs vector of all world content-packs /// @return Level instance containing World instance @@ -96,16 +96,16 @@ public: const std::string& name, const std::string& generator, const fs::path& directory, - uint64_t seed, - EngineSettings& settings, + uint64_t seed, + EngineSettings& settings, const Content* content, const std::vector& packs ); /// @brief Load an existing world - /// @param directory root world directory + /// @param directory root world directory /// @param settings current engine settings - /// @param content current engine Content instance + /// @param content current engine Content instance /// with all world content-packs applied /// @param packs vector of all world content-packs /// @return Level instance containing World instance @@ -121,7 +121,7 @@ public: void setSeed(uint64_t seed); void setGenerator(const std::string& generator); - /// @brief Check if world has content-pack installed + /// @brief Check if world has content-pack installed /// @param id content-pack id bool hasPack(const std::string& id) const; @@ -137,7 +137,7 @@ public: /// @brief Get vector of all content-packs installed in world const std::vector& getPacks() const; - + /// @brief Get next inventory id and increment it's counter /// @return integer >= 1 int64_t getNextInventoryId() { @@ -150,7 +150,7 @@ public: } std::unique_ptr serialize() const override; - void deserialize(dynamic::Map *src) override; + void deserialize(dynamic::Map* src) override; }; -#endif // WORLD_WORLD_HPP_ +#endif // WORLD_WORLD_HPP_ diff --git a/src/world/WorldGenerators.cpp b/src/world/WorldGenerators.cpp index 073a5141..75925323 100644 --- a/src/world/WorldGenerators.cpp +++ b/src/world/WorldGenerators.cpp @@ -1,9 +1,11 @@ #include "WorldGenerators.hpp" -#include "../voxels/WorldGenerator.hpp" -#include "../voxels/FlatWorldGenerator.hpp" -#include "../content/Content.hpp" + #include +#include "../content/Content.hpp" +#include "../voxels/FlatWorldGenerator.hpp" +#include "../voxels/WorldGenerator.hpp" + std::vector WorldGenerators::getGeneratorsIDs() { std::vector ids; for (auto& entry : generators) { @@ -16,10 +18,12 @@ std::string WorldGenerators::getDefaultGeneratorID() { return "core:default"; } -std::unique_ptr WorldGenerators::createGenerator(const std::string& id, const Content* content) { +std::unique_ptr WorldGenerators::createGenerator( + const std::string& id, const Content* content +) { auto found = generators.find(id); if (found == generators.end()) { - throw std::runtime_error("unknown generator id: "+id); + throw std::runtime_error("unknown generator id: " + id); } return std::unique_ptr(found->second(content)); } diff --git a/src/world/WorldGenerators.hpp b/src/world/WorldGenerators.hpp index 65202103..e21ddb12 100644 --- a/src/world/WorldGenerators.hpp +++ b/src/world/WorldGenerators.hpp @@ -1,19 +1,18 @@ #ifndef WORLD_WORLDGENERATORS_HPP_ #define WORLD_WORLDGENERATORS_HPP_ -#include "../voxels/WorldGenerator.hpp" #include -#include #include +#include + +#include "../voxels/WorldGenerator.hpp" class Content; -typedef WorldGenerator* (*gen_constructor) (const Content*); - +typedef WorldGenerator* (*gen_constructor)(const Content*); class WorldGenerators { static inline std::map generators; - public: template static void addGenerator(std::string id); @@ -23,16 +22,14 @@ public: static std::string getDefaultGeneratorID(); static std::unique_ptr createGenerator( - const std::string &id, const Content *content + const std::string& id, const Content* content ); }; template void WorldGenerators::addGenerator(std::string id) { - generators[id] = - [] (const Content* content) - { - return (WorldGenerator*) new T(content); + generators[id] = [](const Content* content) { + return (WorldGenerator*)new T(content); }; }