From 3dcf9e963e3d3c5d209cd3676c2f979a58c6c1ab Mon Sep 17 00:00:00 2001 From: TheBrokenRail <17478432+TheBrokenRail@users.noreply.github.com> Date: Sun, 26 Sep 2021 12:04:09 -0400 Subject: Touch UI support for desktop builds (#10729) --- src/defaultsettings.cpp | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) (limited to 'src/defaultsettings.cpp') diff --git a/src/defaultsettings.cpp b/src/defaultsettings.cpp index 2cb345ba7..d705552d6 100644 --- a/src/defaultsettings.cpp +++ b/src/defaultsettings.cpp @@ -285,7 +285,7 @@ void set_default_settings() settings->setDefault("aux1_descends", "false"); settings->setDefault("doubletap_jump", "false"); settings->setDefault("always_fly_fast", "true"); -#ifdef __ANDROID__ +#ifdef HAVE_TOUCHSCREENGUI settings->setDefault("autojump", "true"); #else settings->setDefault("autojump", "false"); @@ -457,6 +457,7 @@ void set_default_settings() settings->setDefault("enable_console", "false"); settings->setDefault("screen_dpi", "72"); + settings->setDefault("display_density_factor", "1"); // Altered settings for macOS #if defined(__MACH__) && defined(__APPLE__) @@ -464,15 +465,17 @@ void set_default_settings() settings->setDefault("fps_max", "0"); #endif +#ifdef HAVE_TOUCHSCREENGUI + settings->setDefault("touchtarget", "true"); + settings->setDefault("touchscreen_threshold","20"); + settings->setDefault("fixed_virtual_joystick", "false"); + settings->setDefault("virtual_joystick_triggers_aux1", "false"); +#endif // Altered settings for Android #ifdef __ANDROID__ settings->setDefault("screen_w", "0"); settings->setDefault("screen_h", "0"); settings->setDefault("fullscreen", "true"); - settings->setDefault("touchtarget", "true"); - settings->setDefault("touchscreen_threshold","20"); - settings->setDefault("fixed_virtual_joystick", "false"); - settings->setDefault("virtual_joystick_triggers_aux1", "false"); settings->setDefault("smooth_lighting", "false"); settings->setDefault("max_simultaneous_block_sends_per_client", "10"); settings->setDefault("emergequeue_limit_diskonly", "16"); -- cgit v1.2.3 From 9b650b9efb1d4617c97e86639ff115067a73e83a Mon Sep 17 00:00:00 2001 From: Vitaliy Date: Thu, 30 Dec 2021 00:59:53 +0300 Subject: Add more neighbors on mesh update (#6765) --- builtin/settingtypes.txt | 4 +++ src/client/client.cpp | 53 ++++++------------------------------ src/client/mesh_generator_thread.cpp | 53 +++++++++++++++++++++--------------- src/client/mesh_generator_thread.h | 5 ++-- src/defaultsettings.cpp | 2 ++ 5 files changed, 49 insertions(+), 68 deletions(-) (limited to 'src/defaultsettings.cpp') diff --git a/builtin/settingtypes.txt b/builtin/settingtypes.txt index 81ebef67d..1bc5e7982 100644 --- a/builtin/settingtypes.txt +++ b/builtin/settingtypes.txt @@ -475,6 +475,10 @@ connected_glass (Connect glass) bool false # Disable for speed or for different looks. smooth_lighting (Smooth lighting) bool true +# Enables tradeoffs that reduce CPU load or increase rendering performance +# at the expense of minor visual glitches that do not impact game playability. +performance_tradeoffs (Tradeoffs for performance) bool false + # Clouds are a client side effect. enable_clouds (Clouds) bool true diff --git a/src/client/client.cpp b/src/client/client.cpp index 3ee1298ff..6e4a90a79 100644 --- a/src/client/client.cpp +++ b/src/client/client.cpp @@ -1611,20 +1611,7 @@ void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent) void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent) { - try{ - addUpdateMeshTask(blockpos, ack_to_server, urgent); - } - catch(InvalidPositionException &e){} - - // Leading edge - for (int i=0;i<6;i++) - { - try{ - v3s16 p = blockpos + g_6dirs[i]; - addUpdateMeshTask(p, false, urgent); - } - catch(InvalidPositionException &e){} - } + m_mesh_update_thread.updateBlock(&m_env.getMap(), blockpos, ack_to_server, urgent, true); } void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent) @@ -1636,38 +1623,16 @@ void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool ur < cached_blocks; size_t cache_hit_counter = 0; + CachedMapBlockData *cached_block = cacheBlock(map, p, FORCE_UPDATE); + if (!cached_block->data) + return false; // nothing to update cached_blocks.reserve(3*3*3); - v3s16 dp; - for (dp.X = -1; dp.X <= 1; dp.X++) - for (dp.Y = -1; dp.Y <= 1; dp.Y++) - for (dp.Z = -1; dp.Z <= 1; dp.Z++) { - v3s16 p1 = p + dp; - CachedMapBlockData *cached_block; - if (dp == v3s16(0, 0, 0)) - cached_block = cacheBlock(map, p1, FORCE_UPDATE); - else - cached_block = cacheBlock(map, p1, SKIP_UPDATE_IF_ALREADY_CACHED, - &cache_hit_counter); - cached_blocks.push_back(cached_block); - } + cached_blocks.push_back(cached_block); + for (v3s16 dp : g_26dirs) + cached_blocks.push_back(cacheBlock(map, p + dp, + SKIP_UPDATE_IF_ALREADY_CACHED, + &cache_hit_counter)); g_profiler->avg("MeshUpdateQueue: MapBlocks from cache [%]", 100.0f * cache_hit_counter / cached_blocks.size()); @@ -116,7 +112,7 @@ void MeshUpdateQueue::addBlock(Map *map, v3s16 p, bool ack_block_to_server, bool q->ack_block_to_server = true; q->crack_level = m_client->getCrackLevel(); q->crack_pos = m_client->getCrackPos(); - return; + return true; } } @@ -134,6 +130,7 @@ void MeshUpdateQueue::addBlock(Map *map, v3s16 p, bool ack_block_to_server, bool for (CachedMapBlockData *cached_block : cached_blocks) { cached_block->refcount_from_queue++; } + return true; } // Returned pointer must be deleted @@ -212,10 +209,7 @@ void MeshUpdateQueue::fillDataFromMapBlockCache(QueuedMeshUpdate *q) std::time_t t_now = std::time(0); // Collect data for 3*3*3 blocks from cache - v3s16 dp; - for (dp.X = -1; dp.X <= 1; dp.X++) - for (dp.Y = -1; dp.Y <= 1; dp.Y++) - for (dp.Z = -1; dp.Z <= 1; dp.Z++) { + for (v3s16 dp : g_27dirs) { v3s16 p = q->p + dp; CachedMapBlockData *cached_block = getCachedBlock(p); if (cached_block) { @@ -272,10 +266,25 @@ MeshUpdateThread::MeshUpdateThread(Client *client): } void MeshUpdateThread::updateBlock(Map *map, v3s16 p, bool ack_block_to_server, - bool urgent) + bool urgent, bool update_neighbors) { - // Allow the MeshUpdateQueue to do whatever it wants - m_queue_in.addBlock(map, p, ack_block_to_server, urgent); + static thread_local const bool many_neighbors = + g_settings->getBool("smooth_lighting") + && !g_settings->getFlag("performance_tradeoffs"); + if (!m_queue_in.addBlock(map, p, ack_block_to_server, urgent)) { + warningstream << "Update requested for non-existent block at (" + << p.X << ", " << p.Y << ", " << p.Z << ")" << std::endl; + return; + } + if (update_neighbors) { + if (many_neighbors) { + for (v3s16 dp : g_26dirs) + m_queue_in.addBlock(map, p + dp, false, urgent); + } else { + for (v3s16 dp : g_6dirs) + m_queue_in.addBlock(map, p + dp, false, urgent); + } + } deferUpdate(); } diff --git a/src/client/mesh_generator_thread.h b/src/client/mesh_generator_thread.h index 4371b8390..1b734bc06 100644 --- a/src/client/mesh_generator_thread.h +++ b/src/client/mesh_generator_thread.h @@ -66,7 +66,7 @@ public: // Caches the block at p and its neighbors (if needed) and queues a mesh // update for the block at p - void addBlock(Map *map, v3s16 p, bool ack_block_to_server, bool urgent); + bool addBlock(Map *map, v3s16 p, bool ack_block_to_server, bool urgent); // Returned pointer must be deleted // Returns NULL if queue is empty @@ -113,7 +113,8 @@ public: // Caches the block at p and its neighbors (if needed) and queues a mesh // update for the block at p - void updateBlock(Map *map, v3s16 p, bool ack_block_to_server, bool urgent); + void updateBlock(Map *map, v3s16 p, bool ack_block_to_server, bool urgent, + bool update_neighbors = false); v3s16 m_camera_offset; MutexedQueue m_queue_out; diff --git a/src/defaultsettings.cpp b/src/defaultsettings.cpp index d705552d6..635ec2257 100644 --- a/src/defaultsettings.cpp +++ b/src/defaultsettings.cpp @@ -184,6 +184,7 @@ void set_default_settings() settings->setDefault("leaves_style", "fancy"); settings->setDefault("connected_glass", "false"); settings->setDefault("smooth_lighting", "true"); + settings->setDefault("performance_tradeoffs", "false"); settings->setDefault("lighting_alpha", "0.0"); settings->setDefault("lighting_beta", "1.5"); settings->setDefault("display_gamma", "1.0"); @@ -477,6 +478,7 @@ void set_default_settings() settings->setDefault("screen_h", "0"); settings->setDefault("fullscreen", "true"); settings->setDefault("smooth_lighting", "false"); + settings->setDefault("performance_tradeoffs", "true"); settings->setDefault("max_simultaneous_block_sends_per_client", "10"); settings->setDefault("emergequeue_limit_diskonly", "16"); settings->setDefault("emergequeue_limit_generate", "16"); -- cgit v1.2.3 From 4a16ab3585dafdf4d36b2807a1ee9507be64b363 Mon Sep 17 00:00:00 2001 From: Vincent Robinson Date: Thu, 30 Dec 2021 12:54:21 -0800 Subject: Improve TTF support for pixel-style fonts (#11848) --- builtin/settingtypes.txt | 18 +++++++++++++++--- minetest.conf.example | 14 +++++++++++++- src/client/fontengine.cpp | 17 +++++++++++------ src/defaultsettings.cpp | 2 ++ 4 files changed, 41 insertions(+), 10 deletions(-) (limited to 'src/defaultsettings.cpp') diff --git a/builtin/settingtypes.txt b/builtin/settingtypes.txt index 1bc5e7982..22e69e30a 100644 --- a/builtin/settingtypes.txt +++ b/builtin/settingtypes.txt @@ -900,9 +900,15 @@ font_shadow (Font shadow) int 1 # Opaqueness (alpha) of the shadow behind the default font, between 0 and 255. font_shadow_alpha (Font shadow alpha) int 127 0 255 -# Font size of the default font in point (pt). +# Font size of the default font where 1 unit = 1 pixel at 96 DPI font_size (Font size) int 16 1 +# For pixel-style fonts that do not scale well, this ensures that font sizes used +# with this font will always be divisible by this value, in pixels. For instance, +# a pixel font 16 pixels tall should have this set to 16, so it will only ever be +# sized 16, 32, 48, etc., so a mod requesting a size of 25 will get 32. +font_size_divisible_by (Font size divisible by) int 1 1 + # Path to the default font. # If “freetype” setting is enabled: Must be a TrueType font. # If “freetype” setting is disabled: Must be a bitmap or XML vectors font. @@ -913,8 +919,14 @@ font_path_bold (Bold font path) filepath fonts/Arimo-Bold.ttf font_path_italic (Italic font path) filepath fonts/Arimo-Italic.ttf font_path_bold_italic (Bold and italic font path) filepath fonts/Arimo-BoldItalic.ttf -# Font size of the monospace font in point (pt). -mono_font_size (Monospace font size) int 15 1 +# Font size of the monospace font where 1 unit = 1 pixel at 96 DPI +mono_font_size (Monospace font size) int 16 1 + +# For pixel-style fonts that do not scale well, this ensures that font sizes used +# with this font will always be divisible by this value, in pixels. For instance, +# a pixel font 16 pixels tall should have this set to 16, so it will only ever be +# sized 16, 32, 48, etc., so a mod requesting a size of 25 will get 32. +mono_font_size_divisible_by (Monospace font size divisible by) int 1 1 # Path to the monospace font. # If “freetype” setting is enabled: Must be a TrueType font. diff --git a/minetest.conf.example b/minetest.conf.example index 3f4d01420..919c2d52c 100644 --- a/minetest.conf.example +++ b/minetest.conf.example @@ -1055,6 +1055,12 @@ # type: int min: 1 # font_size = 16 +# For pixel-style fonts that do not scale well, this ensures that font sizes used +# with this font will always be divisible by this value, in pixels. For instance, +# a pixel font 16 pixels tall should have this set to 16, so it will only ever be +# sized 16, 32, 48, etc., so a mod requesting a size of 25 will get 32. +# font_size_divisible_by = 1 + # Path to the default font. # If “freetype” setting is enabled: Must be a TrueType font. # If “freetype” setting is disabled: Must be a bitmap or XML vectors font. @@ -1073,7 +1079,13 @@ # Font size of the monospace font in point (pt). # type: int min: 1 -# mono_font_size = 15 +# mono_font_size = 16 + +# For pixel-style fonts that do not scale well, this ensures that font sizes used +# with this font will always be divisible by this value, in pixels. For instance, +# a pixel font 16 pixels tall should have this set to 16, so it will only ever be +# sized 16, 32, 48, etc., so a mod requesting a size of 25 will get 32. +# mono_font_size_divisible_by = 1 # Path to the monospace font. # If “freetype” setting is enabled: Must be a TrueType font. diff --git a/src/client/fontengine.cpp b/src/client/fontengine.cpp index 35e908b0c..e537b756c 100644 --- a/src/client/fontengine.cpp +++ b/src/client/fontengine.cpp @@ -66,11 +66,13 @@ FontEngine::FontEngine(gui::IGUIEnvironment* env) : g_settings->registerChangedCallback("font_path_bolditalic", font_setting_changed, NULL); g_settings->registerChangedCallback("font_shadow", font_setting_changed, NULL); g_settings->registerChangedCallback("font_shadow_alpha", font_setting_changed, NULL); + g_settings->registerChangedCallback("font_size_divisible_by", font_setting_changed, NULL); g_settings->registerChangedCallback("fallback_font_path", font_setting_changed, NULL); } g_settings->registerChangedCallback("mono_font_path", font_setting_changed, NULL); g_settings->registerChangedCallback("mono_font_size", font_setting_changed, NULL); + g_settings->registerChangedCallback("mono_font_size_divisible_by", font_setting_changed, NULL); g_settings->registerChangedCallback("screen_dpi", font_setting_changed, NULL); g_settings->registerChangedCallback("gui_scaling", font_setting_changed, NULL); } @@ -252,15 +254,18 @@ gui::IGUIFont *FontEngine::initFont(const FontSpec &spec) if (spec.italic) setting_suffix.append("_italic"); - u32 size = std::floor(RenderingEngine::getDisplayDensity() * - g_settings->getFloat("gui_scaling") * spec.size); + u32 size = std::max(spec.size * RenderingEngine::getDisplayDensity() * + g_settings->getFloat("gui_scaling"), 1); - if (size == 0) { - errorstream << "FontEngine: attempt to use font size 0" << std::endl; - errorstream << " display density: " << RenderingEngine::getDisplayDensity() << std::endl; - abort(); + // Constrain the font size to a certain multiple, if necessary + u16 divisible_by = g_settings->getU16(setting_prefix + "font_size_divisible_by"); + if (divisible_by > 1) { + size = std::max( + std::round((double)size / divisible_by) * divisible_by, divisible_by); } + sanity_check(size != 0); + u16 font_shadow = 0; u16 font_shadow_alpha = 0; g_settings->getU16NoEx(setting_prefix + "font_shadow", font_shadow); diff --git a/src/defaultsettings.cpp b/src/defaultsettings.cpp index 635ec2257..47790a552 100644 --- a/src/defaultsettings.cpp +++ b/src/defaultsettings.cpp @@ -313,10 +313,12 @@ void set_default_settings() settings->setDefault("font_italic", "false"); settings->setDefault("font_shadow", "1"); settings->setDefault("font_shadow_alpha", "127"); + settings->setDefault("font_size_divisible_by", "1"); settings->setDefault("mono_font_path", porting::getDataPath("fonts" DIR_DELIM "Cousine-Regular.ttf")); settings->setDefault("mono_font_path_italic", porting::getDataPath("fonts" DIR_DELIM "Cousine-Italic.ttf")); settings->setDefault("mono_font_path_bold", porting::getDataPath("fonts" DIR_DELIM "Cousine-Bold.ttf")); settings->setDefault("mono_font_path_bold_italic", porting::getDataPath("fonts" DIR_DELIM "Cousine-BoldItalic.ttf")); + settings->setDefault("mono_font_size_divisible_by", "1"); settings->setDefault("fallback_font_path", porting::getDataPath("fonts" DIR_DELIM "DroidSansFallbackFull.ttf")); std::string font_size_str = std::to_string(TTF_DEFAULT_FONT_SIZE); -- cgit v1.2.3 From 76dbd0d2d04712dcad4f7c6afecb97fa8d662d6d Mon Sep 17 00:00:00 2001 From: sfan5 Date: Sat, 8 Jan 2022 14:53:25 +0100 Subject: Fully remove bitmap font support (#11863) Freetype is now a build requirement. --- .github/workflows/build.yml | 23 ------ README.md | 18 ++--- android/native/jni/Android.mk | 1 - builtin/settingtypes.txt | 16 +--- doc/Doxyfile.in | 1 - fonts/mono_dejavu_sans_10.xml | Bin 257014 -> 0 bytes fonts/mono_dejavu_sans_100.png | Bin 56121 -> 0 bytes fonts/mono_dejavu_sans_11.xml | Bin 263644 -> 0 bytes fonts/mono_dejavu_sans_110.png | Bin 67613 -> 0 bytes fonts/mono_dejavu_sans_12.xml | Bin 268932 -> 0 bytes fonts/mono_dejavu_sans_120.png | Bin 73938 -> 0 bytes fonts/mono_dejavu_sans_14.xml | Bin 269188 -> 0 bytes fonts/mono_dejavu_sans_140.png | Bin 89073 -> 0 bytes fonts/mono_dejavu_sans_16.xml | Bin 275642 -> 0 bytes fonts/mono_dejavu_sans_160.png | Bin 101939 -> 0 bytes fonts/mono_dejavu_sans_18.xml | Bin 279962 -> 0 bytes fonts/mono_dejavu_sans_180.png | Bin 122274 -> 0 bytes fonts/mono_dejavu_sans_20.xml | Bin 282588 -> 0 bytes fonts/mono_dejavu_sans_200.png | Bin 138662 -> 0 bytes fonts/mono_dejavu_sans_22.xml | Bin 283950 -> 0 bytes fonts/mono_dejavu_sans_220.png | Bin 152844 -> 0 bytes fonts/mono_dejavu_sans_24.xml | Bin 286626 -> 0 bytes fonts/mono_dejavu_sans_240.png | Bin 170247 -> 0 bytes fonts/mono_dejavu_sans_26.xml | Bin 289710 -> 0 bytes fonts/mono_dejavu_sans_260.png | Bin 190156 -> 0 bytes fonts/mono_dejavu_sans_28.xml | Bin 292596 -> 0 bytes fonts/mono_dejavu_sans_280.png | Bin 200848 -> 0 bytes fonts/mono_dejavu_sans_4.xml | Bin 237740 -> 0 bytes fonts/mono_dejavu_sans_40.png | Bin 15668 -> 0 bytes fonts/mono_dejavu_sans_6.xml | Bin 245472 -> 0 bytes fonts/mono_dejavu_sans_60.png | Bin 29291 -> 0 bytes fonts/mono_dejavu_sans_8.xml | Bin 251876 -> 0 bytes fonts/mono_dejavu_sans_80.png | Bin 45552 -> 0 bytes fonts/mono_dejavu_sans_9.xml | Bin 254016 -> 0 bytes fonts/mono_dejavu_sans_90.png | Bin 50995 -> 0 bytes src/CMakeLists.txt | 49 ++++------- src/client/fontengine.cpp | 153 +++++------------------------------ src/client/fontengine.h | 9 +-- src/cmake_config.h.in | 1 - src/constants.h | 1 - src/defaultsettings.cpp | 11 +-- src/gui/guiChatConsole.cpp | 14 +--- src/gui/guiHyperText.cpp | 23 ++---- src/gui/guiHyperText.h | 11 +-- src/irrlicht_changes/CMakeLists.txt | 7 +- src/irrlicht_changes/static_text.cpp | 13 +-- src/irrlicht_changes/static_text.h | 36 --------- src/version.cpp | 1 - util/buildbot/buildwin32.sh | 1 - util/buildbot/buildwin64.sh | 1 - 50 files changed, 71 insertions(+), 319 deletions(-) delete mode 100644 fonts/mono_dejavu_sans_10.xml delete mode 100644 fonts/mono_dejavu_sans_100.png delete mode 100644 fonts/mono_dejavu_sans_11.xml delete mode 100644 fonts/mono_dejavu_sans_110.png delete mode 100644 fonts/mono_dejavu_sans_12.xml delete mode 100644 fonts/mono_dejavu_sans_120.png delete mode 100644 fonts/mono_dejavu_sans_14.xml delete mode 100644 fonts/mono_dejavu_sans_140.png delete mode 100644 fonts/mono_dejavu_sans_16.xml delete mode 100644 fonts/mono_dejavu_sans_160.png delete mode 100644 fonts/mono_dejavu_sans_18.xml delete mode 100644 fonts/mono_dejavu_sans_180.png delete mode 100644 fonts/mono_dejavu_sans_20.xml delete mode 100644 fonts/mono_dejavu_sans_200.png delete mode 100644 fonts/mono_dejavu_sans_22.xml delete mode 100644 fonts/mono_dejavu_sans_220.png delete mode 100644 fonts/mono_dejavu_sans_24.xml delete mode 100644 fonts/mono_dejavu_sans_240.png delete mode 100644 fonts/mono_dejavu_sans_26.xml delete mode 100644 fonts/mono_dejavu_sans_260.png delete mode 100644 fonts/mono_dejavu_sans_28.xml delete mode 100644 fonts/mono_dejavu_sans_280.png delete mode 100644 fonts/mono_dejavu_sans_4.xml delete mode 100644 fonts/mono_dejavu_sans_40.png delete mode 100644 fonts/mono_dejavu_sans_6.xml delete mode 100644 fonts/mono_dejavu_sans_60.png delete mode 100644 fonts/mono_dejavu_sans_8.xml delete mode 100644 fonts/mono_dejavu_sans_80.png delete mode 100644 fonts/mono_dejavu_sans_9.xml delete mode 100644 fonts/mono_dejavu_sans_90.png (limited to 'src/defaultsettings.cpp') diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index af1de15ec..b1ba78ed0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -150,29 +150,6 @@ jobs: run: | ./bin/minetestserver --run-unittests - # Build without freetype (client-only) - clang_9_no_freetype: - name: "clang_9 (FREETYPE=0)" - runs-on: ubuntu-18.04 - steps: - - uses: actions/checkout@v2 - - name: Install deps - run: | - source ./util/ci/common.sh - install_linux_deps clang-9 - - - name: Build - run: | - ./util/ci/build.sh - env: - CC: clang-9 - CXX: clang++-9 - CMAKE_FLAGS: "-DENABLE_FREETYPE=0 -DBUILD_SERVER=0" - - - name: Test - run: | - ./bin/minetest --run-unittests - docker: name: "Docker image" runs-on: ubuntu-18.04 diff --git a/README.md b/README.md index 009ae8d38..03a161c9a 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,8 @@ Compiling | GCC | 4.9+ | Can be replaced with Clang 3.4+ | | CMake | 3.5+ | | | IrrlichtMt | - | Custom version of Irrlicht, see https://github.com/minetest/irrlicht | -| SQLite3 | 3.0+ | | +| Freetype | 2.0+ | | +| SQLite3 | 3+ | | | Zstd | 1.0+ | | | LuaJIT | 2.0+ | Bundled Lua 5.1 is used if not present | | GMP | 5.0.0+ | Bundled mini-GMP is used if not present | @@ -143,7 +144,7 @@ Compiling For Debian/Ubuntu users: - sudo apt install g++ make libc6-dev cmake libpng-dev libjpeg-dev libxxf86vm-dev libgl1-mesa-dev libsqlite3-dev libogg-dev libvorbis-dev libopenal-dev libcurl4-gnutls-dev libfreetype6-dev zlib1g-dev libgmp-dev libjsoncpp-dev libzstd-dev + sudo apt install g++ make libc6-dev cmake libpng-dev libjpeg-dev libxxf86vm-dev libgl1-mesa-dev libsqlite3-dev libogg-dev libvorbis-dev libopenal-dev libcurl4-gnutls-dev libfreetype6-dev zlib1g-dev libgmp-dev libjsoncpp-dev libzstd-dev libluajit-5.1-dev For Fedora users: @@ -247,7 +248,6 @@ General options and their default values: MinSizeRel - Release build with -Os passed to compiler to make executable as small as possible ENABLE_CURL=ON - Build with cURL; Enables use of online mod repo, public serverlist and remote media fetching via http ENABLE_CURSES=ON - Build with (n)curses; Enables a server side terminal (command line option: --terminal) - ENABLE_FREETYPE=ON - Build with FreeType2; Allows using TTF fonts ENABLE_GETTEXT=ON - Build with Gettext; Allows using translations ENABLE_GLES=OFF - Build for OpenGL ES instead of OpenGL (requires support by IrrlichtMt) ENABLE_LEVELDB=ON - Build with LevelDB; Enables use of LevelDB map backend @@ -273,10 +273,10 @@ Library specific options: EGL_INCLUDE_DIR - Only if building with GLES; directory that contains egl.h EGL_LIBRARY - Only if building with GLES; path to libEGL.a/libEGL.so EXTRA_DLL - Only on Windows; optional paths to additional DLLs that should be packaged - FREETYPE_INCLUDE_DIR_freetype2 - Only if building with FreeType 2; directory that contains an freetype directory with files such as ftimage.h in it - FREETYPE_INCLUDE_DIR_ft2build - Only if building with FreeType 2; directory that contains ft2build.h - FREETYPE_LIBRARY - Only if building with FreeType 2; path to libfreetype.a/libfreetype.so/freetype.lib - FREETYPE_DLL - Only if building with FreeType 2 on Windows; path to libfreetype.dll + FREETYPE_INCLUDE_DIR_freetype2 - Directory that contains files such as ftimage.h + FREETYPE_INCLUDE_DIR_ft2build - Directory that contains ft2build.h + FREETYPE_LIBRARY - Path to libfreetype.a/libfreetype.so/freetype.lib + FREETYPE_DLL - Only on Windows; path to libfreetype-6.dll GETTEXT_DLL - Only when building with gettext on Windows; paths to libintl + libiconv DLLs GETTEXT_INCLUDE_DIR - Only when building with gettext; directory that contains iconv.h GETTEXT_LIBRARY - Only when building with gettext on Windows; path to libintl.dll.a @@ -337,7 +337,6 @@ vcpkg install zlib zstd curl[winssl] openal-soft libvorbis libogg libjpeg-turbo - **Don't forget about IrrlichtMt.** The easiest way is to clone it to `lib/irrlichtmt` as described in the Linux section. - `curl` is optional, but required to read the serverlist, `curl[winssl]` is required to use the content store. - `openal-soft`, `libvorbis` and `libogg` are optional, but required to use sound. -- `freetype` is optional, it allows true-type font rendering. - `luajit` is optional, it replaces the integrated Lua interpreter with a faster just-in-time interpreter. - `gmp` and `jsoncpp` are optional, otherwise the bundled versions will be compiled @@ -429,8 +428,7 @@ cmake .. \ -DCMAKE_OSX_DEPLOYMENT_TARGET=10.14 \ -DCMAKE_FIND_FRAMEWORK=LAST \ -DCMAKE_INSTALL_PREFIX=../build/macos/ \ - -DRUN_IN_PLACE=FALSE \ - -DENABLE_FREETYPE=TRUE -DENABLE_GETTEXT=TRUE + -DRUN_IN_PLACE=FALSE -DENABLE_GETTEXT=TRUE make -j$(nproc) make install diff --git a/android/native/jni/Android.mk b/android/native/jni/Android.mk index 85c13bfb3..f8ca74d3c 100644 --- a/android/native/jni/Android.mk +++ b/android/native/jni/Android.mk @@ -91,7 +91,6 @@ LOCAL_CFLAGS += \ -DENABLE_GLES=1 \ -DUSE_CURL=1 \ -DUSE_SOUND=1 \ - -DUSE_FREETYPE=1 \ -DUSE_LEVELDB=0 \ -DUSE_LUAJIT=1 \ -DUSE_GETTEXT=1 \ diff --git a/builtin/settingtypes.txt b/builtin/settingtypes.txt index 22e69e30a..c25a941de 100644 --- a/builtin/settingtypes.txt +++ b/builtin/settingtypes.txt @@ -886,10 +886,6 @@ tooltip_show_delay (Tooltip delay) int 400 # Append item name to tooltip. tooltip_append_itemname (Append item name) bool false -# Whether FreeType fonts are used, requires FreeType support to be compiled in. -# If disabled, bitmap and XML vectors fonts are used instead. -freetype (FreeType fonts) bool true - font_bold (Font bold by default) bool false font_italic (Font italic by default) bool false @@ -909,9 +905,7 @@ font_size (Font size) int 16 1 # sized 16, 32, 48, etc., so a mod requesting a size of 25 will get 32. font_size_divisible_by (Font size divisible by) int 1 1 -# Path to the default font. -# If “freetype” setting is enabled: Must be a TrueType font. -# If “freetype” setting is disabled: Must be a bitmap or XML vectors font. +# Path to the default font. Must be a TrueType font. # The fallback font will be used if the font cannot be loaded. font_path (Regular font path) filepath fonts/Arimo-Regular.ttf @@ -928,9 +922,7 @@ mono_font_size (Monospace font size) int 16 1 # sized 16, 32, 48, etc., so a mod requesting a size of 25 will get 32. mono_font_size_divisible_by (Monospace font size divisible by) int 1 1 -# Path to the monospace font. -# If “freetype” setting is enabled: Must be a TrueType font. -# If “freetype” setting is disabled: Must be a bitmap or XML vectors font. +# Path to the monospace font. Must be a TrueType font. # This font is used for e.g. the console and profiler screen. mono_font_path (Monospace font path) filepath fonts/Cousine-Regular.ttf @@ -938,9 +930,7 @@ mono_font_path_bold (Bold monospace font path) filepath fonts/Cousine-Bold.ttf mono_font_path_italic (Italic monospace font path) filepath fonts/Cousine-Italic.ttf mono_font_path_bold_italic (Bold and italic monospace font path) filepath fonts/Cousine-BoldItalic.ttf -# Path of the fallback font. -# If “freetype” setting is enabled: Must be a TrueType font. -# If “freetype” setting is disabled: Must be a bitmap or XML vectors font. +# Path of the fallback font. Must be a TrueType font. # This font will be used for certain languages or if the default font is unavailable. fallback_font_path (Fallback font path) filepath fonts/DroidSansFallbackFull.ttf diff --git a/doc/Doxyfile.in b/doc/Doxyfile.in index d7816f0e4..ae36fd6bf 100644 --- a/doc/Doxyfile.in +++ b/doc/Doxyfile.in @@ -16,7 +16,6 @@ PREDEFINED = "USE_SPATIAL=1" \ "USE_REDIS=1" \ "USE_SOUND=1" \ "USE_CURL=1" \ - "USE_FREETYPE=1" \ "USE_GETTEXT=1" # Input diff --git a/fonts/mono_dejavu_sans_10.xml b/fonts/mono_dejavu_sans_10.xml deleted file mode 100644 index 0276cedb6..000000000 Binary files a/fonts/mono_dejavu_sans_10.xml and /dev/null differ diff --git a/fonts/mono_dejavu_sans_100.png b/fonts/mono_dejavu_sans_100.png deleted file mode 100644 index 45a312542..000000000 Binary files a/fonts/mono_dejavu_sans_100.png and /dev/null differ diff --git a/fonts/mono_dejavu_sans_11.xml b/fonts/mono_dejavu_sans_11.xml deleted file mode 100644 index f727ed2bb..000000000 Binary files a/fonts/mono_dejavu_sans_11.xml and /dev/null differ diff --git a/fonts/mono_dejavu_sans_110.png b/fonts/mono_dejavu_sans_110.png deleted file mode 100644 index c90c0e242..000000000 Binary files a/fonts/mono_dejavu_sans_110.png and /dev/null differ diff --git a/fonts/mono_dejavu_sans_12.xml b/fonts/mono_dejavu_sans_12.xml deleted file mode 100644 index 38f6427be..000000000 Binary files a/fonts/mono_dejavu_sans_12.xml and /dev/null differ diff --git a/fonts/mono_dejavu_sans_120.png b/fonts/mono_dejavu_sans_120.png deleted file mode 100644 index 0cebd70e8..000000000 Binary files a/fonts/mono_dejavu_sans_120.png and /dev/null differ diff --git a/fonts/mono_dejavu_sans_14.xml b/fonts/mono_dejavu_sans_14.xml deleted file mode 100644 index b90a34960..000000000 Binary files a/fonts/mono_dejavu_sans_14.xml and /dev/null differ diff --git a/fonts/mono_dejavu_sans_140.png b/fonts/mono_dejavu_sans_140.png deleted file mode 100644 index a413759ea..000000000 Binary files a/fonts/mono_dejavu_sans_140.png and /dev/null differ diff --git a/fonts/mono_dejavu_sans_16.xml b/fonts/mono_dejavu_sans_16.xml deleted file mode 100644 index 3f7d2c2a2..000000000 Binary files a/fonts/mono_dejavu_sans_16.xml and /dev/null differ diff --git a/fonts/mono_dejavu_sans_160.png b/fonts/mono_dejavu_sans_160.png deleted file mode 100644 index bd8a2f40a..000000000 Binary files a/fonts/mono_dejavu_sans_160.png and /dev/null differ diff --git a/fonts/mono_dejavu_sans_18.xml b/fonts/mono_dejavu_sans_18.xml deleted file mode 100644 index 92865cbfc..000000000 Binary files a/fonts/mono_dejavu_sans_18.xml and /dev/null differ diff --git a/fonts/mono_dejavu_sans_180.png b/fonts/mono_dejavu_sans_180.png deleted file mode 100644 index a299afcbe..000000000 Binary files a/fonts/mono_dejavu_sans_180.png and /dev/null differ diff --git a/fonts/mono_dejavu_sans_20.xml b/fonts/mono_dejavu_sans_20.xml deleted file mode 100644 index acd8c77d0..000000000 Binary files a/fonts/mono_dejavu_sans_20.xml and /dev/null differ diff --git a/fonts/mono_dejavu_sans_200.png b/fonts/mono_dejavu_sans_200.png deleted file mode 100644 index 68ee62681..000000000 Binary files a/fonts/mono_dejavu_sans_200.png and /dev/null differ diff --git a/fonts/mono_dejavu_sans_22.xml b/fonts/mono_dejavu_sans_22.xml deleted file mode 100644 index eafb4def6..000000000 Binary files a/fonts/mono_dejavu_sans_22.xml and /dev/null differ diff --git a/fonts/mono_dejavu_sans_220.png b/fonts/mono_dejavu_sans_220.png deleted file mode 100644 index 042d7e094..000000000 Binary files a/fonts/mono_dejavu_sans_220.png and /dev/null differ diff --git a/fonts/mono_dejavu_sans_24.xml b/fonts/mono_dejavu_sans_24.xml deleted file mode 100644 index fc8b6232e..000000000 Binary files a/fonts/mono_dejavu_sans_24.xml and /dev/null differ diff --git a/fonts/mono_dejavu_sans_240.png b/fonts/mono_dejavu_sans_240.png deleted file mode 100644 index d2d68c5bb..000000000 Binary files a/fonts/mono_dejavu_sans_240.png and /dev/null differ diff --git a/fonts/mono_dejavu_sans_26.xml b/fonts/mono_dejavu_sans_26.xml deleted file mode 100644 index 829f09948..000000000 Binary files a/fonts/mono_dejavu_sans_26.xml and /dev/null differ diff --git a/fonts/mono_dejavu_sans_260.png b/fonts/mono_dejavu_sans_260.png deleted file mode 100644 index 3a8cb6c57..000000000 Binary files a/fonts/mono_dejavu_sans_260.png and /dev/null differ diff --git a/fonts/mono_dejavu_sans_28.xml b/fonts/mono_dejavu_sans_28.xml deleted file mode 100644 index b5b25bd07..000000000 Binary files a/fonts/mono_dejavu_sans_28.xml and /dev/null differ diff --git a/fonts/mono_dejavu_sans_280.png b/fonts/mono_dejavu_sans_280.png deleted file mode 100644 index ccf62ba48..000000000 Binary files a/fonts/mono_dejavu_sans_280.png and /dev/null differ diff --git a/fonts/mono_dejavu_sans_4.xml b/fonts/mono_dejavu_sans_4.xml deleted file mode 100644 index cfebb39b3..000000000 Binary files a/fonts/mono_dejavu_sans_4.xml and /dev/null differ diff --git a/fonts/mono_dejavu_sans_40.png b/fonts/mono_dejavu_sans_40.png deleted file mode 100644 index 24ed693f7..000000000 Binary files a/fonts/mono_dejavu_sans_40.png and /dev/null differ diff --git a/fonts/mono_dejavu_sans_6.xml b/fonts/mono_dejavu_sans_6.xml deleted file mode 100644 index d0e1de21d..000000000 Binary files a/fonts/mono_dejavu_sans_6.xml and /dev/null differ diff --git a/fonts/mono_dejavu_sans_60.png b/fonts/mono_dejavu_sans_60.png deleted file mode 100644 index 326af996f..000000000 Binary files a/fonts/mono_dejavu_sans_60.png and /dev/null differ diff --git a/fonts/mono_dejavu_sans_8.xml b/fonts/mono_dejavu_sans_8.xml deleted file mode 100644 index c48bf7ccc..000000000 Binary files a/fonts/mono_dejavu_sans_8.xml and /dev/null differ diff --git a/fonts/mono_dejavu_sans_80.png b/fonts/mono_dejavu_sans_80.png deleted file mode 100644 index 04326dbb2..000000000 Binary files a/fonts/mono_dejavu_sans_80.png and /dev/null differ diff --git a/fonts/mono_dejavu_sans_9.xml b/fonts/mono_dejavu_sans_9.xml deleted file mode 100644 index 74e841034..000000000 Binary files a/fonts/mono_dejavu_sans_9.xml and /dev/null differ diff --git a/fonts/mono_dejavu_sans_90.png b/fonts/mono_dejavu_sans_90.png deleted file mode 100644 index 65ac51858..000000000 Binary files a/fonts/mono_dejavu_sans_90.png and /dev/null differ diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index e3389cea9..ed0929564 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -122,16 +122,8 @@ if(BUILD_CLIENT) endif() endif() - -option(ENABLE_FREETYPE "Enable FreeType2 (TrueType fonts and basic unicode support)" TRUE) -set(USE_FREETYPE FALSE) - -if(BUILD_CLIENT AND ENABLE_FREETYPE) - find_package(Freetype) - if(FREETYPE_FOUND) - message(STATUS "Freetype enabled.") - set(USE_FREETYPE TRUE) - endif() +if(BUILD_CLIENT) + find_package(Freetype REQUIRED) endif() option(ENABLE_CURSES "Enable ncurses console" TRUE) @@ -495,13 +487,11 @@ include_directories( ${PROJECT_SOURCE_DIR} ${ZLIB_INCLUDE_DIR} ${ZSTD_INCLUDE_DIR} - ${SOUND_INCLUDE_DIRS} ${SQLITE3_INCLUDE_DIR} ${LUA_INCLUDE_DIR} ${GMP_INCLUDE_DIR} ${JSON_INCLUDE_DIR} ${LUA_BIT_INCLUDE_DIR} - ${X11_INCLUDE_DIR} ${PROJECT_SOURCE_DIR}/script ) @@ -509,8 +499,12 @@ if(USE_GETTEXT) include_directories(${GETTEXT_INCLUDE_DIR}) endif() -if(USE_FREETYPE) - include_directories(${FREETYPE_INCLUDE_DIRS}) +if(BUILD_CLIENT) + include_directories( + ${FREETYPE_INCLUDE_DIRS} + ${SOUND_INCLUDE_DIRS} + ${X11_INCLUDE_DIR} + ) endif() if(USE_CURL) @@ -539,6 +533,7 @@ if(BUILD_CLIENT) ${GMP_LIBRARY} ${JSON_LIBRARY} ${LUA_BIT_LIBRARY} + ${FREETYPE_LIBRARY} ${PLATFORM_LIBS} ) if(NOT USE_LUAJIT) @@ -573,17 +568,11 @@ if(BUILD_CLIENT) ${CURL_LIBRARY} ) endif() - if(USE_FREETYPE) - if(FREETYPE_PKGCONFIG_FOUND) - set_target_properties(${PROJECT_NAME} - PROPERTIES - COMPILE_FLAGS "${FREETYPE_CFLAGS_STR}" - ) - endif() - target_link_libraries( - ${PROJECT_NAME} - ${FREETYPE_LIBRARY} - ) + if(FREETYPE_PKGCONFIG_FOUND) + set_target_properties(${PROJECT_NAME} + PROPERTIES + COMPILE_FLAGS "${FREETYPE_CFLAGS_STR}" + ) endif() if (USE_CURSES) target_link_libraries(${PROJECT_NAME} ${CURSES_LIBRARIES}) @@ -896,14 +885,8 @@ if(BUILD_CLIENT) endforeach() endif() - # Install necessary fonts depending on configuration - if(USE_FREETYPE) - install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/../fonts" DESTINATION "${SHAREDIR}" - FILES_MATCHING PATTERN "*.ttf" PATTERN "*.txt") - else() - install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/../fonts" DESTINATION "${SHAREDIR}" - FILES_MATCHING PATTERN "*.png" PATTERN "*.xml") - endif() + install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/../fonts" DESTINATION "${SHAREDIR}" + FILES_MATCHING PATTERN "*.ttf" PATTERN "*.txt") endif(BUILD_CLIENT) if(BUILD_SERVER) diff --git a/src/client/fontengine.cpp b/src/client/fontengine.cpp index e537b756c..ad8305b45 100644 --- a/src/client/fontengine.cpp +++ b/src/client/fontengine.cpp @@ -24,10 +24,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "porting.h" #include "filesys.h" #include "gettext.h" - -#if USE_FREETYPE #include "irrlicht_changes/CGUITTFont.h" -#endif /** maximum size distance for getting a "similar" font size */ #define MAX_FONT_SIZE_OFFSET 10 @@ -45,9 +42,8 @@ static void font_setting_changed(const std::string &name, void *userdata) FontEngine::FontEngine(gui::IGUIEnvironment* env) : m_env(env) { - for (u32 &i : m_default_size) { - i = (FontMode) FONT_SIZE_UNSPECIFIED; + i = FONT_SIZE_UNSPECIFIED; } assert(g_settings != NULL); // pre-condition @@ -56,25 +52,19 @@ FontEngine::FontEngine(gui::IGUIEnvironment* env) : readSettings(); - if (m_currentMode != FM_Simple) { - g_settings->registerChangedCallback("font_size", font_setting_changed, NULL); - g_settings->registerChangedCallback("font_bold", font_setting_changed, NULL); - g_settings->registerChangedCallback("font_italic", font_setting_changed, NULL); - g_settings->registerChangedCallback("font_path", font_setting_changed, NULL); - g_settings->registerChangedCallback("font_path_bold", font_setting_changed, NULL); - g_settings->registerChangedCallback("font_path_italic", font_setting_changed, NULL); - g_settings->registerChangedCallback("font_path_bolditalic", font_setting_changed, NULL); - g_settings->registerChangedCallback("font_shadow", font_setting_changed, NULL); - g_settings->registerChangedCallback("font_shadow_alpha", font_setting_changed, NULL); - g_settings->registerChangedCallback("font_size_divisible_by", font_setting_changed, NULL); - g_settings->registerChangedCallback("fallback_font_path", font_setting_changed, NULL); - } + const char *settings[] = { + "font_size", "font_bold", "font_italic", "font_size_divisible_by", + "mono_font_size", "mono_font_size_divisible_by", + "font_shadow", "font_shadow_alpha", + "font_path", "font_path_bold", "font_path_italic", "font_path_bold_italic", + "mono_font_path", "mono_font_path_bold", "mono_font_path_italic", + "mono_font_path_bold_italic", + "fallback_font_path", + "screen_dpi", "gui_scaling", + }; - g_settings->registerChangedCallback("mono_font_path", font_setting_changed, NULL); - g_settings->registerChangedCallback("mono_font_size", font_setting_changed, NULL); - g_settings->registerChangedCallback("mono_font_size_divisible_by", font_setting_changed, NULL); - g_settings->registerChangedCallback("screen_dpi", font_setting_changed, NULL); - g_settings->registerChangedCallback("gui_scaling", font_setting_changed, NULL); + for (auto name : settings) + g_settings->registerChangedCallback(name, font_setting_changed, NULL); } /******************************************************************************/ @@ -108,16 +98,8 @@ irr::gui::IGUIFont *FontEngine::getFont(FontSpec spec, bool may_fail) { if (spec.mode == FM_Unspecified) { spec.mode = m_currentMode; - } else if (m_currentMode == FM_Simple) { - // Freetype disabled -> Force simple mode - spec.mode = (spec.mode == FM_Mono || - spec.mode == FM_SimpleMono) ? - FM_SimpleMono : FM_Simple; - // Support for those could be added, but who cares? - spec.bold = false; - spec.italic = false; } else if (spec.mode == _FM_Fallback) { - // Fallback font doesn't support these either + // Fallback font doesn't support these spec.bold = false; spec.italic = false; } @@ -134,11 +116,7 @@ irr::gui::IGUIFont *FontEngine::getFont(FontSpec spec, bool may_fail) return it->second; // Font does not yet exist - gui::IGUIFont *font = nullptr; - if (spec.mode == FM_Simple || spec.mode == FM_SimpleMono) - font = initSimpleFont(spec); - else - font = initFont(spec); + gui::IGUIFont *font = initFont(spec); if (!font && !may_fail) { errorstream << "Minetest cannot continue without a valid font. " @@ -185,13 +163,6 @@ unsigned int FontEngine::getDefaultFontSize() unsigned int FontEngine::getFontSize(FontMode mode) { - if (m_currentMode == FM_Simple) { - if (mode == FM_Mono || mode == FM_SimpleMono) - return m_default_size[FM_SimpleMono]; - else - return m_default_size[FM_Simple]; - } - if (mode == FM_Unspecified) return m_default_size[FM_Standard]; @@ -201,20 +172,12 @@ unsigned int FontEngine::getFontSize(FontMode mode) /******************************************************************************/ void FontEngine::readSettings() { - if (USE_FREETYPE && g_settings->getBool("freetype")) { - m_default_size[FM_Standard] = g_settings->getU16("font_size"); - m_default_size[_FM_Fallback] = g_settings->getU16("font_size"); - m_default_size[FM_Mono] = g_settings->getU16("mono_font_size"); + m_default_size[FM_Standard] = g_settings->getU16("font_size"); + m_default_size[_FM_Fallback] = g_settings->getU16("font_size"); + m_default_size[FM_Mono] = g_settings->getU16("mono_font_size"); - m_default_bold = g_settings->getBool("font_bold"); - m_default_italic = g_settings->getBool("font_italic"); - - } else { - m_currentMode = FM_Simple; - } - - m_default_size[FM_Simple] = g_settings->getU16("font_size"); - m_default_size[FM_SimpleMono] = g_settings->getU16("mono_font_size"); + m_default_bold = g_settings->getBool("font_bold"); + m_default_italic = g_settings->getBool("font_italic"); cleanCache(); updateFontCache(); @@ -283,7 +246,6 @@ gui::IGUIFont *FontEngine::initFont(const FontSpec &spec) Settings::getLayer(SL_DEFAULTS)->get(path_setting) }; -#if USE_FREETYPE for (const std::string &font_path : fallback_settings) { gui::CGUITTFont *font = gui::CGUITTFont::createTTFont(m_env, font_path.c_str(), size, true, true, font_shadow, @@ -302,80 +264,5 @@ gui::IGUIFont *FontEngine::initFont(const FontSpec &spec) } return font; } -#else - errorstream << "FontEngine: Tried to load TTF font but Minetest was" - " compiled without Freetype." << std::endl; -#endif return nullptr; } - -/** initialize a font without freetype */ -gui::IGUIFont *FontEngine::initSimpleFont(const FontSpec &spec) -{ - assert(spec.mode == FM_Simple || spec.mode == FM_SimpleMono); - assert(spec.size != FONT_SIZE_UNSPECIFIED); - - const std::string &font_path = g_settings->get( - (spec.mode == FM_SimpleMono) ? "mono_font_path" : "font_path"); - - size_t pos_dot = font_path.find_last_of('.'); - std::string basename = font_path, ending; - if (pos_dot != std::string::npos) - ending = lowercase(font_path.substr(pos_dot)); - - if (ending == ".ttf") { - errorstream << "FontEngine: Found font \"" << font_path - << "\" but freetype is not available." << std::endl; - return nullptr; - } - - if (ending == ".xml" || ending == ".png") - basename = font_path.substr(0, pos_dot); - - u32 size = std::floor( - RenderingEngine::getDisplayDensity() * - g_settings->getFloat("gui_scaling") * - spec.size); - - irr::gui::IGUIFont *font = nullptr; - std::string font_extensions[] = { ".png", ".xml" }; - - // Find nearest matching font scale - // Does a "zig-zag motion" (positibe/negative), from 0 to MAX_FONT_SIZE_OFFSET - for (s32 zoffset = 0; zoffset < MAX_FONT_SIZE_OFFSET * 2; zoffset++) { - std::stringstream path; - - // LSB to sign - s32 sign = (zoffset & 1) ? -1 : 1; - s32 offset = zoffset >> 1; - - for (const std::string &ext : font_extensions) { - path.str(""); // Clear - path << basename << "_" << (size + offset * sign) << ext; - - if (!fs::PathExists(path.str())) - continue; - - font = m_env->getFont(path.str().c_str()); - - if (font) { - verbosestream << "FontEngine: found font: " << path.str() << std::endl; - break; - } - } - - if (font) - break; - } - - // try name direct - if (font == NULL) { - if (fs::PathExists(font_path)) { - font = m_env->getFont(font_path.c_str()); - if (font) - verbosestream << "FontEngine: found font: " << font_path << std::endl; - } - } - - return font; -} diff --git a/src/client/fontengine.h b/src/client/fontengine.h index 403ac2e48..78608e517 100644 --- a/src/client/fontengine.h +++ b/src/client/fontengine.h @@ -34,8 +34,6 @@ enum FontMode : u8 { FM_Standard = 0, FM_Mono, _FM_Fallback, // do not use directly - FM_Simple, - FM_SimpleMono, FM_MaxMode, FM_Unspecified }; @@ -140,9 +138,6 @@ private: /** initialize a new TTF font */ gui::IGUIFont *initFont(const FontSpec &spec); - /** initialize a font without freetype */ - gui::IGUIFont *initSimpleFont(const FontSpec &spec); - /** update current minetest skin with font changes */ void updateSkin(); @@ -165,8 +160,8 @@ private: bool m_default_bold = false; bool m_default_italic = false; - /** current font engine mode */ - FontMode m_currentMode = FM_Standard; + /** default font engine mode (fixed) */ + static const FontMode m_currentMode = FM_Standard; DISABLE_CLASS_COPY(FontEngine); }; diff --git a/src/cmake_config.h.in b/src/cmake_config.h.in index cfcee4b58..cf436d6dc 100644 --- a/src/cmake_config.h.in +++ b/src/cmake_config.h.in @@ -18,7 +18,6 @@ #cmakedefine01 USE_GETTEXT #cmakedefine01 USE_CURL #cmakedefine01 USE_SOUND -#cmakedefine01 USE_FREETYPE #cmakedefine01 USE_CURSES #cmakedefine01 USE_LEVELDB #cmakedefine01 USE_LUAJIT diff --git a/src/constants.h b/src/constants.h index 3cc3af094..ed858912d 100644 --- a/src/constants.h +++ b/src/constants.h @@ -111,4 +111,3 @@ with this program; if not, write to the Free Software Foundation, Inc., */ #define TTF_DEFAULT_FONT_SIZE (16) -#define DEFAULT_FONT_SIZE (10) diff --git a/src/defaultsettings.cpp b/src/defaultsettings.cpp index 47790a552..9e4bb14b5 100644 --- a/src/defaultsettings.cpp +++ b/src/defaultsettings.cpp @@ -303,8 +303,7 @@ void set_default_settings() settings->setDefault("main_menu_path", ""); settings->setDefault("serverlist_file", "favoriteservers.json"); -#if USE_FREETYPE - settings->setDefault("freetype", "true"); + // General font settings settings->setDefault("font_path", porting::getDataPath("fonts" DIR_DELIM "Arimo-Regular.ttf")); settings->setDefault("font_path_italic", porting::getDataPath("fonts" DIR_DELIM "Arimo-Italic.ttf")); settings->setDefault("font_path_bold", porting::getDataPath("fonts" DIR_DELIM "Arimo-Bold.ttf")); @@ -322,14 +321,6 @@ void set_default_settings() settings->setDefault("fallback_font_path", porting::getDataPath("fonts" DIR_DELIM "DroidSansFallbackFull.ttf")); std::string font_size_str = std::to_string(TTF_DEFAULT_FONT_SIZE); -#else - settings->setDefault("freetype", "false"); - settings->setDefault("font_path", porting::getDataPath("fonts" DIR_DELIM "mono_dejavu_sans")); - settings->setDefault("mono_font_path", porting::getDataPath("fonts" DIR_DELIM "mono_dejavu_sans")); - - std::string font_size_str = std::to_string(DEFAULT_FONT_SIZE); -#endif - // General font settings settings->setDefault("font_size", font_size_str); settings->setDefault("mono_font_size", font_size_str); settings->setDefault("chat_font_size", "0"); // Default "font_size" diff --git a/src/gui/guiChatConsole.cpp b/src/gui/guiChatConsole.cpp index 0610c85cc..01e10ea2e 100644 --- a/src/gui/guiChatConsole.cpp +++ b/src/gui/guiChatConsole.cpp @@ -30,12 +30,9 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client/fontengine.h" #include "log.h" #include "gettext.h" +#include "irrlicht_changes/CGUITTFont.h" #include -#if USE_FREETYPE - #include "irrlicht_changes/CGUITTFont.h" -#endif - inline u32 clamp_u8(s32 value) { return (u32) MYMIN(MYMAX(value, 0), 255); @@ -328,19 +325,16 @@ void GUIChatConsole::drawText() core::rect destrect( x, y, x + m_fontsize.X * fragment.text.size(), y + m_fontsize.Y); -#if USE_FREETYPE if (m_font->getType() == irr::gui::EGFT_CUSTOM) { - // Draw colored text if FreeType is enabled - irr::gui::CGUITTFont *tmp = dynamic_cast(m_font); + // Draw colored text if possible + gui::CGUITTFont *tmp = static_cast(m_font); tmp->draw( fragment.text, destrect, false, false, &AbsoluteClippingRect); - } else -#endif - { + } else { // Otherwise use standard text m_font->draw( fragment.text.c_str(), diff --git a/src/gui/guiHyperText.cpp b/src/gui/guiHyperText.cpp index ccfdcb81d..40450ce5f 100644 --- a/src/gui/guiHyperText.cpp +++ b/src/gui/guiHyperText.cpp @@ -17,31 +17,26 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ -#include "IGUIEnvironment.h" -#include "IGUIElement.h" +#include "guiHyperText.h" #include "guiScrollBar.h" -#include "IGUIFont.h" -#include -#include -#include -using namespace irr::gui; #include "client/fontengine.h" -#include #include "client/tile.h" #include "IVideoDriver.h" #include "client/client.h" #include "client/renderingengine.h" #include "hud.h" -#include "guiHyperText.h" #include "util/string.h" +#include "irrlicht_changes/CGUITTFont.h" -bool check_color(const std::string &str) +using namespace irr::gui; + +static bool check_color(const std::string &str) { irr::video::SColor color; return parseColorString(str, color, false); } -bool check_integer(const std::string &str) +static bool check_integer(const std::string &str) { if (str.empty()) return false; @@ -616,12 +611,10 @@ TextDrawer::TextDrawer(const wchar_t *text, Client *client, if (e.font) { e.dim.Width = e.font->getDimension(e.text.c_str()).Width; e.dim.Height = e.font->getDimension(L"Yy").Height; -#if USE_FREETYPE if (e.font->getType() == irr::gui::EGFT_CUSTOM) { - e.baseline = e.dim.Height - 1 - - ((irr::gui::CGUITTFont *)e.font)->getAscender() / 64; + CGUITTFont *tmp = static_cast(e.font); + e.baseline = e.dim.Height - 1 - tmp->getAscender() / 64; } -#endif } else { e.dim = {0, 0}; } diff --git a/src/gui/guiHyperText.h b/src/gui/guiHyperText.h index 5b936262e..04c664df5 100644 --- a/src/gui/guiHyperText.h +++ b/src/gui/guiHyperText.h @@ -19,16 +19,17 @@ with this program; if not, write to the Free Software Foundation, Inc., #pragma once -#include "config.h" // for USE_FREETYPE +#include +#include +#include +#include +#include "irrlichttypes_extrabloated.h" using namespace irr; class ISimpleTextureSource; class Client; - -#if USE_FREETYPE -#include "irrlicht_changes/CGUITTFont.h" -#endif +class GUIScrollBar; class ParsedText { diff --git a/src/irrlicht_changes/CMakeLists.txt b/src/irrlicht_changes/CMakeLists.txt index 87c88f7e8..19f431af3 100644 --- a/src/irrlicht_changes/CMakeLists.txt +++ b/src/irrlicht_changes/CMakeLists.txt @@ -1,14 +1,9 @@ if (BUILD_CLIENT) set(client_irrlicht_changes_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/static_text.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/CGUITTFont.cpp ) - if (USE_FREETYPE) - set(client_irrlicht_changes_SRCS ${client_irrlicht_changes_SRCS} - ${CMAKE_CURRENT_SOURCE_DIR}/CGUITTFont.cpp - ) - endif() - # CMake require us to set a local scope and then parent scope # Else the last set win in parent scope set(client_irrlicht_changes_SRCS ${client_irrlicht_changes_SRCS} PARENT_SCOPE) diff --git a/src/irrlicht_changes/static_text.cpp b/src/irrlicht_changes/static_text.cpp index f548c3f71..baf0ea626 100644 --- a/src/irrlicht_changes/static_text.cpp +++ b/src/irrlicht_changes/static_text.cpp @@ -12,17 +12,12 @@ #include #include -#if USE_FREETYPE - #include "CGUITTFont.h" -#endif - +#include "CGUITTFont.h" #include "util/string.h" namespace irr { -#if USE_FREETYPE - namespace gui { //! constructor @@ -108,14 +103,12 @@ void StaticText::draw() font->getDimension(str.c_str()).Width; } -#if USE_FREETYPE if (font->getType() == irr::gui::EGFT_CUSTOM) { - irr::gui::CGUITTFont *tmp = static_cast(font); + CGUITTFont *tmp = static_cast(font); tmp->draw(str, r, HAlign == EGUIA_CENTER, VAlign == EGUIA_CENTER, (RestrainTextInside ? &AbsoluteClippingRect : NULL)); } else -#endif { // Draw non-colored text font->draw(str.c_str(), @@ -590,8 +583,6 @@ s32 StaticText::getTextWidth() const } // end namespace gui -#endif // USE_FREETYPE - } // end namespace irr diff --git a/src/irrlicht_changes/static_text.h b/src/irrlicht_changes/static_text.h index 17a3bf753..74ef62008 100644 --- a/src/irrlicht_changes/static_text.h +++ b/src/irrlicht_changes/static_text.h @@ -20,7 +20,6 @@ #include "config.h" #include -#if USE_FREETYPE namespace irr { @@ -230,41 +229,6 @@ inline void setStaticText(irr::gui::IGUIStaticText *static_text, const EnrichedS } } -#else // USE_FREETYPE - -namespace irr -{ -namespace gui -{ - -class StaticText -{ -public: - static irr::gui::IGUIStaticText *add( - irr::gui::IGUIEnvironment *guienv, - const EnrichedString &text, - const core::rect< s32 > &rectangle, - bool border = false, - bool wordWrap = true, - irr::gui::IGUIElement *parent = NULL, - s32 id = -1, - bool fillBackground = false) - { - return guienv->addStaticText(text.c_str(), rectangle, border, wordWrap, parent, id, fillBackground); - } -}; - -} // end namespace gui - -} // end namespace irr - -inline void setStaticText(irr::gui::IGUIStaticText *static_text, const EnrichedString &text) -{ - static_text->setText(text.c_str()); -} - -#endif - inline void setStaticText(irr::gui::IGUIStaticText *static_text, const wchar_t *text) { setStaticText(static_text, EnrichedString(text, static_text->getOverrideColor())); diff --git a/src/version.cpp b/src/version.cpp index c555f30af..f2aac37df 100644 --- a/src/version.cpp +++ b/src/version.cpp @@ -37,7 +37,6 @@ const char *g_build_info = #ifndef SERVER "USE_GETTEXT=" STR(USE_GETTEXT) "\n" "USE_SOUND=" STR(USE_SOUND) "\n" - "USE_FREETYPE=" STR(USE_FREETYPE) "\n" #endif "STATIC_SHAREDIR=" STR(STATIC_SHAREDIR) #if USE_GETTEXT && defined(STATIC_LOCALEDIR) diff --git a/util/buildbot/buildwin32.sh b/util/buildbot/buildwin32.sh index 696297aed..2eb9dab11 100755 --- a/util/buildbot/buildwin32.sh +++ b/util/buildbot/buildwin32.sh @@ -129,7 +129,6 @@ cmake -S $sourcedir -B . \ -DENABLE_SOUND=1 \ -DENABLE_CURL=1 \ -DENABLE_GETTEXT=1 \ - -DENABLE_FREETYPE=1 \ -DENABLE_LEVELDB=1 \ \ -DCMAKE_PREFIX_PATH=$libdir/irrlicht \ diff --git a/util/buildbot/buildwin64.sh b/util/buildbot/buildwin64.sh index 20d0b3a6a..3dd4db687 100755 --- a/util/buildbot/buildwin64.sh +++ b/util/buildbot/buildwin64.sh @@ -129,7 +129,6 @@ cmake -S $sourcedir -B . \ -DENABLE_SOUND=1 \ -DENABLE_CURL=1 \ -DENABLE_GETTEXT=1 \ - -DENABLE_FREETYPE=1 \ -DENABLE_LEVELDB=1 \ \ -DCMAKE_PREFIX_PATH=$libdir/irrlicht \ -- cgit v1.2.3 From a9bccb964f6c6ffe9d4f84922d9be640e4dd2f1e Mon Sep 17 00:00:00 2001 From: sfan5 Date: Fri, 17 Dec 2021 17:21:14 +0100 Subject: Raise max mapgen limit constant to align with mapblock size --- builtin/game/chat.lua | 2 +- builtin/settingtypes.txt | 2 +- minetest.conf.example | 4 +-- src/constants.h | 2 +- src/defaultsettings.cpp | 2 +- src/map.cpp | 9 +----- src/mapblock.h | 2 +- src/unittest/CMakeLists.txt | 1 + src/unittest/test_map.cpp | 68 +++++++++++++++++++++++++++++++++++++++++++++ 9 files changed, 77 insertions(+), 15 deletions(-) create mode 100644 src/unittest/test_map.cpp (limited to 'src/defaultsettings.cpp') diff --git a/builtin/game/chat.lua b/builtin/game/chat.lua index 0f5739d5c..b73e32876 100644 --- a/builtin/game/chat.lua +++ b/builtin/game/chat.lua @@ -524,7 +524,7 @@ end -- Teleports player to

if possible local function teleport_to_pos(name, p) - local lm = 31000 + local lm = 31007 -- equals MAX_MAP_GENERATION_LIMIT in C++ if p.x < -lm or p.x > lm or p.y < -lm or p.y > lm or p.z < -lm or p.z > lm then return false, S("Cannot teleport out of map bounds!") diff --git a/builtin/settingtypes.txt b/builtin/settingtypes.txt index 9f01c67cf..42b45aa00 100644 --- a/builtin/settingtypes.txt +++ b/builtin/settingtypes.txt @@ -1459,7 +1459,7 @@ max_block_generate_distance (Max block generate distance) int 10 # Limit of map generation, in nodes, in all 6 directions from (0, 0, 0). # Only mapchunks completely within the mapgen limit are generated. # Value is stored per-world. -mapgen_limit (Map generation limit) int 31000 0 31000 +mapgen_limit (Map generation limit) int 31007 0 31007 # Global map generation attributes. # In Mapgen v6 the 'decorations' flag controls all decorations except trees diff --git a/minetest.conf.example b/minetest.conf.example index dd51fe259..7f4b5d946 100644 --- a/minetest.conf.example +++ b/minetest.conf.example @@ -1767,8 +1767,8 @@ # Limit of map generation, in nodes, in all 6 directions from (0, 0, 0). # Only mapchunks completely within the mapgen limit are generated. # Value is stored per-world. -# type: int min: 0 max: 31000 -# mapgen_limit = 31000 +# type: int min: 0 max: 31007 +# mapgen_limit = 31007 # Global map generation attributes. # In Mapgen v6 the 'decorations' flag controls all decorations except trees diff --git a/src/constants.h b/src/constants.h index ed858912d..b9d4f8d70 100644 --- a/src/constants.h +++ b/src/constants.h @@ -64,7 +64,7 @@ with this program; if not, write to the Free Software Foundation, Inc., // I really don't want to make every algorithm to check if it's going near // the limit or not, so this is lower. // This is the maximum value the setting map_generation_limit can be -#define MAX_MAP_GENERATION_LIMIT (31000) +#define MAX_MAP_GENERATION_LIMIT (31007) // Size of node in floating-point units // The original idea behind this is to disallow plain casts between diff --git a/src/defaultsettings.cpp b/src/defaultsettings.cpp index 9e4bb14b5..600fc65f3 100644 --- a/src/defaultsettings.cpp +++ b/src/defaultsettings.cpp @@ -435,7 +435,7 @@ void set_default_settings() // Mapgen settings->setDefault("mg_name", "v7"); settings->setDefault("water_level", "1"); - settings->setDefault("mapgen_limit", "31000"); + settings->setDefault("mapgen_limit", "31007"); settings->setDefault("chunksize", "5"); settings->setDefault("fixed_map_seed", ""); settings->setDefault("max_block_generate_distance", "10"); diff --git a/src/map.cpp b/src/map.cpp index 77031e17d..a11bbb96a 100644 --- a/src/map.cpp +++ b/src/map.cpp @@ -1444,11 +1444,7 @@ MapSector *ServerMap::createSector(v2s16 p2d) /* Do not create over max mapgen limit */ - const s16 max_limit_bp = MAX_MAP_GENERATION_LIMIT / MAP_BLOCKSIZE; - if (p2d.X < -max_limit_bp || - p2d.X > max_limit_bp || - p2d.Y < -max_limit_bp || - p2d.Y > max_limit_bp) + if (blockpos_over_max_limit(v3s16(p2d.X, 0, p2d.Y))) throw InvalidPositionException("createSector(): pos. over max mapgen limit"); /* @@ -1457,9 +1453,6 @@ MapSector *ServerMap::createSector(v2s16 p2d) sector = new MapSector(this, p2d, m_gamedef); - // Sector position on map in nodes - //v2s16 nodepos2d = p2d * MAP_BLOCKSIZE; - /* Insert to container */ diff --git a/src/mapblock.h b/src/mapblock.h index e729fdb1c..a86db7b70 100644 --- a/src/mapblock.h +++ b/src/mapblock.h @@ -601,7 +601,7 @@ typedef std::vector MapBlockVect; inline bool objectpos_over_limit(v3f p) { - const float max_limit_bs = MAX_MAP_GENERATION_LIMIT * BS; + const float max_limit_bs = (MAX_MAP_GENERATION_LIMIT + 0.5f) * BS; return p.X < -max_limit_bs || p.X > max_limit_bs || p.Y < -max_limit_bs || diff --git a/src/unittest/CMakeLists.txt b/src/unittest/CMakeLists.txt index ce7921b55..936436364 100644 --- a/src/unittest/CMakeLists.txt +++ b/src/unittest/CMakeLists.txt @@ -11,6 +11,7 @@ set (UNITTEST_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/test_filepath.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_inventory.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_irrptr.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/test_map.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_map_settings_manager.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_mapnode.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_modchannels.cpp diff --git a/src/unittest/test_map.cpp b/src/unittest/test_map.cpp new file mode 100644 index 000000000..82e55e1aa --- /dev/null +++ b/src/unittest/test_map.cpp @@ -0,0 +1,68 @@ +/* +Minetest + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 2.1 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "test.h" + +#include +#include "mapblock.h" + +class TestMap : public TestBase +{ +public: + TestMap() { TestManager::registerTestModule(this); } + const char *getName() { return "TestMap"; } + + void runTests(IGameDef *gamedef); + + void testMaxMapgenLimit(); +}; + +static TestMap g_test_instance; + +void TestMap::runTests(IGameDef *gamedef) +{ + TEST(testMaxMapgenLimit); +} + +//////////////////////////////////////////////////////////////////////////////// + +void TestMap::testMaxMapgenLimit() +{ + // limit must end on a mapblock boundary + UASSERTEQ(int, MAX_MAP_GENERATION_LIMIT % MAP_BLOCKSIZE, MAP_BLOCKSIZE - 1); + + // objectpos_over_limit should do exactly this except the last node + // actually spans from LIMIT-0.5 to LIMIT+0.5 + float limit_times_bs = MAX_MAP_GENERATION_LIMIT * BS; + UASSERT(objectpos_over_limit(v3f(limit_times_bs-BS/2)) == false); + UASSERT(objectpos_over_limit(v3f(limit_times_bs)) == false); + UASSERT(objectpos_over_limit(v3f(limit_times_bs+BS/2)) == false); + UASSERT(objectpos_over_limit(v3f(limit_times_bs+BS)) == true); + + UASSERT(objectpos_over_limit(v3f(-limit_times_bs+BS/2)) == false); + UASSERT(objectpos_over_limit(v3f(-limit_times_bs)) == false); + UASSERT(objectpos_over_limit(v3f(-limit_times_bs-BS/2)) == false); + UASSERT(objectpos_over_limit(v3f(-limit_times_bs-BS)) == true); + + // blockpos_over_max_limit + s16 limit_block = MAX_MAP_GENERATION_LIMIT / MAP_BLOCKSIZE; + UASSERT(blockpos_over_max_limit(v3s16(limit_block)) == false); + UASSERT(blockpos_over_max_limit(v3s16(limit_block+1)) == true); + UASSERT(blockpos_over_max_limit(v3s16(-limit_block)) == false); + UASSERT(blockpos_over_max_limit(v3s16(-limit_block-1)) == true); +} -- cgit v1.2.3 From ad1da994b2b9d660c41f8ba784ff830aa2693d3b Mon Sep 17 00:00:00 2001 From: Lars Müller <34514239+appgurueu@users.noreply.github.com> Date: Tue, 8 Feb 2022 19:33:10 +0100 Subject: Increase max objects per block defaults (#12055) --- builtin/settingtypes.txt | 2 +- minetest.conf.example | 2 +- src/defaultsettings.cpp | 3 +-- 3 files changed, 3 insertions(+), 4 deletions(-) (limited to 'src/defaultsettings.cpp') diff --git a/builtin/settingtypes.txt b/builtin/settingtypes.txt index ef8b84cff..ff2d72927 100644 --- a/builtin/settingtypes.txt +++ b/builtin/settingtypes.txt @@ -1306,7 +1306,7 @@ max_clearobjects_extra_loaded_blocks (Max. clearobjects extra blocks) int 4096 server_unload_unused_data_timeout (Unload unused server data) int 29 # Maximum number of statically stored objects in a block. -max_objects_per_block (Maximum objects per block) int 64 +max_objects_per_block (Maximum objects per block) int 256 # See https://www.sqlite.org/pragma.html#pragma_synchronous sqlite_synchronous (Synchronous SQLite) enum 2 0,1,2 diff --git a/minetest.conf.example b/minetest.conf.example index 7f4b5d946..ed2ebc969 100644 --- a/minetest.conf.example +++ b/minetest.conf.example @@ -1514,7 +1514,7 @@ # Maximum number of statically stored objects in a block. # type: int -# max_objects_per_block = 64 +# max_objects_per_block = 256 # See https://www.sqlite.org/pragma.html#pragma_synchronous # type: enum values: 0, 1, 2 diff --git a/src/defaultsettings.cpp b/src/defaultsettings.cpp index 600fc65f3..b935c0e21 100644 --- a/src/defaultsettings.cpp +++ b/src/defaultsettings.cpp @@ -386,7 +386,7 @@ void set_default_settings() settings->setDefault("time_speed", "72"); settings->setDefault("world_start_time", "6125"); settings->setDefault("server_unload_unused_data_timeout", "29"); - settings->setDefault("max_objects_per_block", "64"); + settings->setDefault("max_objects_per_block", "256"); settings->setDefault("server_map_save_interval", "5.3"); settings->setDefault("chat_message_max_size", "500"); settings->setDefault("chat_message_limit_per_10sec", "8.0"); @@ -479,7 +479,6 @@ void set_default_settings() settings->setDefault("enable_3d_clouds", "false"); settings->setDefault("fps_max", "30"); settings->setDefault("fps_max_unfocused", "10"); - settings->setDefault("max_objects_per_block", "20"); settings->setDefault("sqlite_synchronous", "1"); settings->setDefault("map_compression_level_disk", "-1"); settings->setDefault("map_compression_level_net", "-1"); -- cgit v1.2.3 From 0f25fa7af655b98fa401176a523f269c843d1943 Mon Sep 17 00:00:00 2001 From: x2048 Date: Sat, 26 Mar 2022 16:58:26 +0100 Subject: Add API to control shadow intensity from the game/mod (#11944) * Also Disable shadows when sun/moon is hidden. Fixes #11972. --- builtin/settingtypes.txt | 5 +- client/shaders/nodes_shader/opengl_fragment.glsl | 85 ++++++++++---------- client/shaders/nodes_shader/opengl_vertex.glsl | 57 +++++++------- client/shaders/object_shader/opengl_fragment.glsl | 84 ++++++++++---------- client/shaders/object_shader/opengl_vertex.glsl | 56 ++++++------- doc/lua_api.txt | 7 ++ games/devtest/mods/experimental/init.lua | 1 + games/devtest/mods/experimental/lighting.lua | 8 ++ src/client/client.h | 1 + src/client/game.cpp | 7 +- src/client/localplayer.h | 4 + src/client/shadows/dynamicshadowsrender.cpp | 95 ++++++++++++++++------- src/client/shadows/dynamicshadowsrender.h | 10 ++- src/client/sky.h | 2 + src/defaultsettings.cpp | 2 +- src/lighting.h | 27 +++++++ src/network/clientopcodes.cpp | 1 + src/network/clientpackethandler.cpp | 8 ++ src/network/networkprotocol.h | 7 +- src/remoteplayer.h | 7 ++ src/script/lua_api/l_object.cpp | 43 ++++++++++ src/script/lua_api/l_object.h | 6 ++ src/server.cpp | 17 ++++ src/server.h | 4 + 24 files changed, 375 insertions(+), 169 deletions(-) create mode 100644 games/devtest/mods/experimental/lighting.lua create mode 100644 src/lighting.h (limited to 'src/defaultsettings.cpp') diff --git a/builtin/settingtypes.txt b/builtin/settingtypes.txt index ff2d72927..3dc165bd1 100644 --- a/builtin/settingtypes.txt +++ b/builtin/settingtypes.txt @@ -592,9 +592,10 @@ enable_waving_plants (Waving plants) bool false # Requires shaders to be enabled. enable_dynamic_shadows (Dynamic shadows) bool false -# Set the shadow strength. +# Set the shadow strength gamma. +# Adjusts the intensity of in-game dynamic shadows. # Lower value means lighter shadows, higher value means darker shadows. -shadow_strength (Shadow strength) float 0.2 0.05 1.0 +shadow_strength_gamma (Shadow strength gamma) float 1.0 0.1 10.0 # Maximum distance to render shadows. shadow_map_max_distance (Shadow map max distance in nodes to render shadows) float 120.0 10.0 1000.0 diff --git a/client/shaders/nodes_shader/opengl_fragment.glsl b/client/shaders/nodes_shader/opengl_fragment.glsl index e5f5c703a..adc8adccb 100644 --- a/client/shaders/nodes_shader/opengl_fragment.glsl +++ b/client/shaders/nodes_shader/opengl_fragment.glsl @@ -16,6 +16,7 @@ uniform float animationTimer; uniform float f_textureresolution; uniform mat4 m_ShadowViewProj; uniform float f_shadowfar; + uniform float f_shadow_strength; varying float normalOffsetScale; varying float adj_shadow_strength; varying float cosLight; @@ -483,55 +484,57 @@ void main(void) vec4 col = vec4(color.rgb * varColor.rgb, 1.0); #ifdef ENABLE_DYNAMIC_SHADOWS - float shadow_int = 0.0; - vec3 shadow_color = vec3(0.0, 0.0, 0.0); - vec3 posLightSpace = getLightSpacePosition(); + if (f_shadow_strength > 0.0) { + float shadow_int = 0.0; + vec3 shadow_color = vec3(0.0, 0.0, 0.0); + vec3 posLightSpace = getLightSpacePosition(); - float distance_rate = (1 - pow(clamp(2.0 * length(posLightSpace.xy - 0.5),0.0,1.0), 20.0)); - float f_adj_shadow_strength = max(adj_shadow_strength-mtsmoothstep(0.9,1.1, posLightSpace.z ),0.0); + float distance_rate = (1 - pow(clamp(2.0 * length(posLightSpace.xy - 0.5),0.0,1.0), 20.0)); + float f_adj_shadow_strength = max(adj_shadow_strength-mtsmoothstep(0.9,1.1, posLightSpace.z ),0.0); - if (distance_rate > 1e-7) { - + if (distance_rate > 1e-7) { + #ifdef COLORED_SHADOWS - vec4 visibility; - if (cosLight > 0.0) - visibility = getShadowColor(ShadowMapSampler, posLightSpace.xy, posLightSpace.z); - else - visibility = vec4(1.0, 0.0, 0.0, 0.0); - shadow_int = visibility.r; - shadow_color = visibility.gba; + vec4 visibility; + if (cosLight > 0.0) + visibility = getShadowColor(ShadowMapSampler, posLightSpace.xy, posLightSpace.z); + else + visibility = vec4(1.0, 0.0, 0.0, 0.0); + shadow_int = visibility.r; + shadow_color = visibility.gba; #else - if (cosLight > 0.0) - shadow_int = getShadow(ShadowMapSampler, posLightSpace.xy, posLightSpace.z); - else - shadow_int = 1.0; + if (cosLight > 0.0) + shadow_int = getShadow(ShadowMapSampler, posLightSpace.xy, posLightSpace.z); + else + shadow_int = 1.0; #endif - shadow_int *= distance_rate; - shadow_int = clamp(shadow_int, 0.0, 1.0); + shadow_int *= distance_rate; + shadow_int = clamp(shadow_int, 0.0, 1.0); - } + } - // turns out that nightRatio falls off much faster than - // actual brightness of artificial light in relation to natual light. - // Power ratio was measured on torches in MTG (brightness = 14). - float adjusted_night_ratio = pow(max(0.0, nightRatio), 0.6); - - // Apply self-shadowing when light falls at a narrow angle to the surface - // Cosine of the cut-off angle. - const float self_shadow_cutoff_cosine = 0.035; - if (f_normal_length != 0 && cosLight < self_shadow_cutoff_cosine) { - shadow_int = max(shadow_int, 1 - clamp(cosLight, 0.0, self_shadow_cutoff_cosine)/self_shadow_cutoff_cosine); - shadow_color = mix(vec3(0.0), shadow_color, min(cosLight, self_shadow_cutoff_cosine)/self_shadow_cutoff_cosine); - } + // turns out that nightRatio falls off much faster than + // actual brightness of artificial light in relation to natual light. + // Power ratio was measured on torches in MTG (brightness = 14). + float adjusted_night_ratio = pow(max(0.0, nightRatio), 0.6); + + // Apply self-shadowing when light falls at a narrow angle to the surface + // Cosine of the cut-off angle. + const float self_shadow_cutoff_cosine = 0.035; + if (f_normal_length != 0 && cosLight < self_shadow_cutoff_cosine) { + shadow_int = max(shadow_int, 1 - clamp(cosLight, 0.0, self_shadow_cutoff_cosine)/self_shadow_cutoff_cosine); + shadow_color = mix(vec3(0.0), shadow_color, min(cosLight, self_shadow_cutoff_cosine)/self_shadow_cutoff_cosine); + } - shadow_int *= f_adj_shadow_strength; - - // calculate fragment color from components: - col.rgb = - adjusted_night_ratio * col.rgb + // artificial light - (1.0 - adjusted_night_ratio) * ( // natural light - col.rgb * (1.0 - shadow_int * (1.0 - shadow_color)) + // filtered texture color - dayLight * shadow_color * shadow_int); // reflected filtered sunlight/moonlight + shadow_int *= f_adj_shadow_strength; + + // calculate fragment color from components: + col.rgb = + adjusted_night_ratio * col.rgb + // artificial light + (1.0 - adjusted_night_ratio) * ( // natural light + col.rgb * (1.0 - shadow_int * (1.0 - shadow_color)) + // filtered texture color + dayLight * shadow_color * shadow_int); // reflected filtered sunlight/moonlight + } #endif #if ENABLE_TONE_MAPPING diff --git a/client/shaders/nodes_shader/opengl_vertex.glsl b/client/shaders/nodes_shader/opengl_vertex.glsl index 95cd138a8..5e77ac719 100644 --- a/client/shaders/nodes_shader/opengl_vertex.glsl +++ b/client/shaders/nodes_shader/opengl_vertex.glsl @@ -195,34 +195,35 @@ void main(void) varColor = clamp(color, 0.0, 1.0); #ifdef ENABLE_DYNAMIC_SHADOWS - vec3 nNormal = normalize(vNormal); - cosLight = dot(nNormal, -v_LightDirection); - - // Calculate normal offset scale based on the texel size adjusted for - // curvature of the SM texture. This code must be change together with - // getPerspectiveFactor or any light-space transformation. - vec3 eyeToVertex = worldPosition - eyePosition + cameraOffset; - // Distance from the vertex to the player - float distanceToPlayer = length(eyeToVertex - v_LightDirection * dot(eyeToVertex, v_LightDirection)) / f_shadowfar; - // perspective factor estimation according to the - float perspectiveFactor = distanceToPlayer * bias0 + bias1; - float texelSize = f_shadowfar * perspectiveFactor * perspectiveFactor / - (f_textureresolution * bias1 - perspectiveFactor * bias0); - float slopeScale = clamp(pow(1.0 - cosLight*cosLight, 0.5), 0.0, 1.0); - normalOffsetScale = texelSize * slopeScale; - - if (f_timeofday < 0.2) { - adj_shadow_strength = f_shadow_strength * 0.5 * - (1.0 - mtsmoothstep(0.18, 0.2, f_timeofday)); - } else if (f_timeofday >= 0.8) { - adj_shadow_strength = f_shadow_strength * 0.5 * - mtsmoothstep(0.8, 0.83, f_timeofday); - } else { - adj_shadow_strength = f_shadow_strength * - mtsmoothstep(0.20, 0.25, f_timeofday) * - (1.0 - mtsmoothstep(0.7, 0.8, f_timeofday)); + if (f_shadow_strength > 0.0) { + vec3 nNormal = normalize(vNormal); + cosLight = dot(nNormal, -v_LightDirection); + + // Calculate normal offset scale based on the texel size adjusted for + // curvature of the SM texture. This code must be change together with + // getPerspectiveFactor or any light-space transformation. + vec3 eyeToVertex = worldPosition - eyePosition + cameraOffset; + // Distance from the vertex to the player + float distanceToPlayer = length(eyeToVertex - v_LightDirection * dot(eyeToVertex, v_LightDirection)) / f_shadowfar; + // perspective factor estimation according to the + float perspectiveFactor = distanceToPlayer * bias0 + bias1; + float texelSize = f_shadowfar * perspectiveFactor * perspectiveFactor / + (f_textureresolution * bias1 - perspectiveFactor * bias0); + float slopeScale = clamp(pow(1.0 - cosLight*cosLight, 0.5), 0.0, 1.0); + normalOffsetScale = texelSize * slopeScale; + + if (f_timeofday < 0.2) { + adj_shadow_strength = f_shadow_strength * 0.5 * + (1.0 - mtsmoothstep(0.18, 0.2, f_timeofday)); + } else if (f_timeofday >= 0.8) { + adj_shadow_strength = f_shadow_strength * 0.5 * + mtsmoothstep(0.8, 0.83, f_timeofday); + } else { + adj_shadow_strength = f_shadow_strength * + mtsmoothstep(0.20, 0.25, f_timeofday) * + (1.0 - mtsmoothstep(0.7, 0.8, f_timeofday)); + } + f_normal_length = length(vNormal); } - f_normal_length = length(vNormal); #endif - } diff --git a/client/shaders/object_shader/opengl_fragment.glsl b/client/shaders/object_shader/opengl_fragment.glsl index fdfcec0c8..edb9d2bb1 100644 --- a/client/shaders/object_shader/opengl_fragment.glsl +++ b/client/shaders/object_shader/opengl_fragment.glsl @@ -34,6 +34,8 @@ const float fogShadingParameter = 1.0 / (1.0 - fogStart); uniform float f_textureresolution; uniform mat4 m_ShadowViewProj; uniform float f_shadowfar; + uniform float f_timeofday; + uniform float f_shadow_strength; varying float normalOffsetScale; varying float adj_shadow_strength; varying float cosLight; @@ -470,55 +472,57 @@ void main(void) col.rgb *= vIDiff; #ifdef ENABLE_DYNAMIC_SHADOWS - float shadow_int = 0.0; - vec3 shadow_color = vec3(0.0, 0.0, 0.0); - vec3 posLightSpace = getLightSpacePosition(); + if (f_shadow_strength > 0.0) { + float shadow_int = 0.0; + vec3 shadow_color = vec3(0.0, 0.0, 0.0); + vec3 posLightSpace = getLightSpacePosition(); - float distance_rate = (1 - pow(clamp(2.0 * length(posLightSpace.xy - 0.5),0.0,1.0), 20.0)); - float f_adj_shadow_strength = max(adj_shadow_strength-mtsmoothstep(0.9,1.1, posLightSpace.z ),0.0); + float distance_rate = (1 - pow(clamp(2.0 * length(posLightSpace.xy - 0.5),0.0,1.0), 20.0)); + float f_adj_shadow_strength = max(adj_shadow_strength-mtsmoothstep(0.9,1.1, posLightSpace.z ),0.0); - if (distance_rate > 1e-7) { + if (distance_rate > 1e-7) { #ifdef COLORED_SHADOWS - vec4 visibility; - if (cosLight > 0.0) - visibility = getShadowColor(ShadowMapSampler, posLightSpace.xy, posLightSpace.z); - else - visibility = vec4(1.0, 0.0, 0.0, 0.0); - shadow_int = visibility.r; - shadow_color = visibility.gba; + vec4 visibility; + if (cosLight > 0.0) + visibility = getShadowColor(ShadowMapSampler, posLightSpace.xy, posLightSpace.z); + else + visibility = vec4(1.0, 0.0, 0.0, 0.0); + shadow_int = visibility.r; + shadow_color = visibility.gba; #else - if (cosLight > 0.0) - shadow_int = getShadow(ShadowMapSampler, posLightSpace.xy, posLightSpace.z); - else - shadow_int = 1.0; + if (cosLight > 0.0) + shadow_int = getShadow(ShadowMapSampler, posLightSpace.xy, posLightSpace.z); + else + shadow_int = 1.0; #endif - shadow_int *= distance_rate; - shadow_int = clamp(shadow_int, 0.0, 1.0); + shadow_int *= distance_rate; + shadow_int = clamp(shadow_int, 0.0, 1.0); - } + } - // turns out that nightRatio falls off much faster than - // actual brightness of artificial light in relation to natual light. - // Power ratio was measured on torches in MTG (brightness = 14). - float adjusted_night_ratio = pow(max(0.0, nightRatio), 0.6); - - // cosine of the normal-to-light angle when - // we start to apply self-shadowing - const float self_shadow_cutoff_cosine = 0.14; - if (f_normal_length != 0 && cosLight < self_shadow_cutoff_cosine) { - shadow_int = max(shadow_int, 1 - clamp(cosLight, 0.0, self_shadow_cutoff_cosine)/self_shadow_cutoff_cosine); - shadow_color = mix(vec3(0.0), shadow_color, min(cosLight, self_shadow_cutoff_cosine)/self_shadow_cutoff_cosine); - } + // turns out that nightRatio falls off much faster than + // actual brightness of artificial light in relation to natual light. + // Power ratio was measured on torches in MTG (brightness = 14). + float adjusted_night_ratio = pow(max(0.0, nightRatio), 0.6); + + // cosine of the normal-to-light angle when + // we start to apply self-shadowing + const float self_shadow_cutoff_cosine = 0.14; + if (f_normal_length != 0 && cosLight < self_shadow_cutoff_cosine) { + shadow_int = max(shadow_int, 1 - clamp(cosLight, 0.0, self_shadow_cutoff_cosine)/self_shadow_cutoff_cosine); + shadow_color = mix(vec3(0.0), shadow_color, min(cosLight, self_shadow_cutoff_cosine)/self_shadow_cutoff_cosine); + } - shadow_int *= f_adj_shadow_strength; - - // calculate fragment color from components: - col.rgb = - adjusted_night_ratio * col.rgb + // artificial light - (1.0 - adjusted_night_ratio) * ( // natural light - col.rgb * (1.0 - shadow_int * (1.0 - shadow_color)) + // filtered texture color - dayLight * shadow_color * shadow_int); // reflected filtered sunlight/moonlight + shadow_int *= f_adj_shadow_strength; + + // calculate fragment color from components: + col.rgb = + adjusted_night_ratio * col.rgb + // artificial light + (1.0 - adjusted_night_ratio) * ( // natural light + col.rgb * (1.0 - shadow_int * (1.0 - shadow_color)) + // filtered texture color + dayLight * shadow_color * shadow_int); // reflected filtered sunlight/moonlight + } #endif #if ENABLE_TONE_MAPPING diff --git a/client/shaders/object_shader/opengl_vertex.glsl b/client/shaders/object_shader/opengl_vertex.glsl index 185551c58..ff0067302 100644 --- a/client/shaders/object_shader/opengl_vertex.glsl +++ b/client/shaders/object_shader/opengl_vertex.glsl @@ -105,33 +105,35 @@ void main(void) #ifdef ENABLE_DYNAMIC_SHADOWS - vec3 nNormal = normalize(vNormal); - cosLight = dot(nNormal, -v_LightDirection); - - // Calculate normal offset scale based on the texel size adjusted for - // curvature of the SM texture. This code must be change together with - // getPerspectiveFactor or any light-space transformation. - vec3 eyeToVertex = worldPosition - eyePosition + cameraOffset; - // Distance from the vertex to the player - float distanceToPlayer = length(eyeToVertex - v_LightDirection * dot(eyeToVertex, v_LightDirection)) / f_shadowfar; - // perspective factor estimation according to the - float perspectiveFactor = distanceToPlayer * bias0 + bias1; - float texelSize = f_shadowfar * perspectiveFactor * perspectiveFactor / - (f_textureresolution * bias1 - perspectiveFactor * bias0); - float slopeScale = clamp(pow(1.0 - cosLight*cosLight, 0.5), 0.0, 1.0); - normalOffsetScale = texelSize * slopeScale; - - if (f_timeofday < 0.2) { - adj_shadow_strength = f_shadow_strength * 0.5 * - (1.0 - mtsmoothstep(0.18, 0.2, f_timeofday)); - } else if (f_timeofday >= 0.8) { - adj_shadow_strength = f_shadow_strength * 0.5 * - mtsmoothstep(0.8, 0.83, f_timeofday); - } else { - adj_shadow_strength = f_shadow_strength * - mtsmoothstep(0.20, 0.25, f_timeofday) * - (1.0 - mtsmoothstep(0.7, 0.8, f_timeofday)); + if (f_shadow_strength > 0.0) { + vec3 nNormal = normalize(vNormal); + cosLight = dot(nNormal, -v_LightDirection); + + // Calculate normal offset scale based on the texel size adjusted for + // curvature of the SM texture. This code must be change together with + // getPerspectiveFactor or any light-space transformation. + vec3 eyeToVertex = worldPosition - eyePosition + cameraOffset; + // Distance from the vertex to the player + float distanceToPlayer = length(eyeToVertex - v_LightDirection * dot(eyeToVertex, v_LightDirection)) / f_shadowfar; + // perspective factor estimation according to the + float perspectiveFactor = distanceToPlayer * bias0 + bias1; + float texelSize = f_shadowfar * perspectiveFactor * perspectiveFactor / + (f_textureresolution * bias1 - perspectiveFactor * bias0); + float slopeScale = clamp(pow(1.0 - cosLight*cosLight, 0.5), 0.0, 1.0); + normalOffsetScale = texelSize * slopeScale; + + if (f_timeofday < 0.2) { + adj_shadow_strength = f_shadow_strength * 0.5 * + (1.0 - mtsmoothstep(0.18, 0.2, f_timeofday)); + } else if (f_timeofday >= 0.8) { + adj_shadow_strength = f_shadow_strength * 0.5 * + mtsmoothstep(0.8, 0.83, f_timeofday); + } else { + adj_shadow_strength = f_shadow_strength * + mtsmoothstep(0.20, 0.25, f_timeofday) * + (1.0 - mtsmoothstep(0.7, 0.8, f_timeofday)); + } + f_normal_length = length(vNormal); } - f_normal_length = length(vNormal); #endif } diff --git a/doc/lua_api.txt b/doc/lua_api.txt index 52da17e9c..029c53616 100644 --- a/doc/lua_api.txt +++ b/doc/lua_api.txt @@ -7019,6 +7019,13 @@ object you are working with still exists. * Returns `false` if failed. * Resource intensive - use sparsely * To get blockpos, integer divide pos by 16 +* `set_lighting(light_definition)`: sets lighting for the player + * `light_definition` is a table with the following optional fields: + * `shadows` is a table that controls ambient shadows + * `intensity` sets the intensity of the shadows from 0 (no shadows, default) to 1 (blackness) + * Returns true on success. +* `get_lighting()`: returns the current state of lighting for the player. + * Result is a table with the same fields as `light_definition` in `set_lighting`. `PcgRandom` ----------- diff --git a/games/devtest/mods/experimental/init.lua b/games/devtest/mods/experimental/init.lua index b292f792e..70091179c 100644 --- a/games/devtest/mods/experimental/init.lua +++ b/games/devtest/mods/experimental/init.lua @@ -7,6 +7,7 @@ experimental = {} dofile(minetest.get_modpath("experimental").."/detached.lua") dofile(minetest.get_modpath("experimental").."/items.lua") dofile(minetest.get_modpath("experimental").."/commands.lua") +dofile(minetest.get_modpath("experimental").."/lighting.lua") function experimental.print_to_everything(msg) minetest.log("action", msg) diff --git a/games/devtest/mods/experimental/lighting.lua b/games/devtest/mods/experimental/lighting.lua new file mode 100644 index 000000000..2b350550f --- /dev/null +++ b/games/devtest/mods/experimental/lighting.lua @@ -0,0 +1,8 @@ +core.register_chatcommand("set_lighting", { + params = "shadow_intensity", + description = "Set lighting parameters.", + func = function(player_name, param) + local shadow_intensity = tonumber(param) + minetest.get_player_by_name(player_name):set_lighting({shadows = { intensity = shadow_intensity} }) + end +}) \ No newline at end of file diff --git a/src/client/client.h b/src/client/client.h index 84c85471d..0e29fdbe2 100644 --- a/src/client/client.h +++ b/src/client/client.h @@ -227,6 +227,7 @@ public: void handleCommand_PlayerSpeed(NetworkPacket *pkt); void handleCommand_MediaPush(NetworkPacket *pkt); void handleCommand_MinimapModes(NetworkPacket *pkt); + void handleCommand_SetLighting(NetworkPacket *pkt); void ProcessData(NetworkPacket *pkt); diff --git a/src/client/game.cpp b/src/client/game.cpp index 7450fb91c..edc69dcc2 100644 --- a/src/client/game.cpp +++ b/src/client/game.cpp @@ -4037,7 +4037,12 @@ void Game::updateShadows() float in_timeofday = fmod(runData.time_of_day_smooth, 1.0f); - float timeoftheday = fmod(getWickedTimeOfDay(in_timeofday) + 0.75f, 0.5f) + 0.25f; + float timeoftheday = getWickedTimeOfDay(in_timeofday); + bool is_day = timeoftheday > 0.25 && timeoftheday < 0.75; + bool is_shadow_visible = is_day ? sky->getSunVisible() : sky->getMoonVisible(); + shadow->setShadowIntensity(is_shadow_visible ? client->getEnv().getLocalPlayer()->getLighting().shadow_intensity : 0.0f); + + timeoftheday = fmod(timeoftheday + 0.75f, 0.5f) + 0.25f; const float offset_constant = 10000.0f; v3f light(0.0f, 0.0f, -1.0f); diff --git a/src/client/localplayer.h b/src/client/localplayer.h index 577be2803..3d0072fc1 100644 --- a/src/client/localplayer.h +++ b/src/client/localplayer.h @@ -23,6 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "environment.h" #include "constants.h" #include "settings.h" +#include "lighting.h" #include class Client; @@ -158,6 +159,8 @@ public: added_velocity += vel; } + inline Lighting& getLighting() { return m_lighting; } + private: void accelerate(const v3f &target_speed, const f32 max_increase_H, const f32 max_increase_V, const bool use_pitch); @@ -209,4 +212,5 @@ private: GenericCAO *m_cao = nullptr; Client *m_client; + Lighting m_lighting; }; diff --git a/src/client/shadows/dynamicshadowsrender.cpp b/src/client/shadows/dynamicshadowsrender.cpp index 528415aaf..24adb21e2 100644 --- a/src/client/shadows/dynamicshadowsrender.cpp +++ b/src/client/shadows/dynamicshadowsrender.cpp @@ -18,6 +18,7 @@ with this program; if not, write to the Free Software Foundation, Inc., */ #include +#include #include "client/shadows/dynamicshadowsrender.h" #include "client/shadows/shadowsScreenQuad.h" #include "client/shadows/shadowsshadercallbacks.h" @@ -33,9 +34,13 @@ ShadowRenderer::ShadowRenderer(IrrlichtDevice *device, Client *client) : m_device(device), m_smgr(device->getSceneManager()), m_driver(device->getVideoDriver()), m_client(client), m_current_frame(0) { + m_shadows_supported = true; // assume shadows supported. We will check actual support in initialize m_shadows_enabled = true; - m_shadow_strength = g_settings->getFloat("shadow_strength"); + m_shadow_strength_gamma = g_settings->getFloat("shadow_strength_gamma"); + if (std::isnan(m_shadow_strength_gamma)) + m_shadow_strength_gamma = 1.0f; + m_shadow_strength_gamma = core::clamp(m_shadow_strength_gamma, 0.1f, 10.0f); m_shadow_map_max_distance = g_settings->getFloat("shadow_map_max_distance"); @@ -49,6 +54,9 @@ ShadowRenderer::ShadowRenderer(IrrlichtDevice *device, Client *client) : ShadowRenderer::~ShadowRenderer() { + // call to disable releases dynamically allocated resources + disable(); + if (m_shadow_depth_cb) delete m_shadow_depth_cb; if (m_shadow_mix_cb) @@ -72,15 +80,25 @@ ShadowRenderer::~ShadowRenderer() m_driver->removeTexture(shadowMapClientMapFuture); } +void ShadowRenderer::disable() +{ + m_shadows_enabled = false; + if (shadowMapTextureFinal) { + m_driver->setRenderTarget(shadowMapTextureFinal, true, true, + video::SColor(255, 255, 255, 255)); + m_driver->setRenderTarget(0, true, true); + } +} + void ShadowRenderer::initialize() { auto *gpu = m_driver->getGPUProgrammingServices(); // we need glsl - if (m_shadows_enabled && gpu && m_driver->queryFeature(video::EVDF_ARB_GLSL)) { + if (m_shadows_supported && gpu && m_driver->queryFeature(video::EVDF_ARB_GLSL)) { createShaders(); } else { - m_shadows_enabled = false; + m_shadows_supported = false; warningstream << "Shadows: GLSL Shader not supported on this system." << std::endl; @@ -94,6 +112,8 @@ void ShadowRenderer::initialize() m_texture_format_color = m_shadow_map_texture_32bit ? video::ECOLOR_FORMAT::ECF_G32R32F : video::ECOLOR_FORMAT::ECF_G16R16F; + + m_shadows_enabled &= m_shadows_supported; } @@ -124,6 +144,16 @@ f32 ShadowRenderer::getMaxShadowFar() const return 0.0f; } +void ShadowRenderer::setShadowIntensity(float shadow_intensity) +{ + m_shadow_strength = pow(shadow_intensity, 1.0f / m_shadow_strength_gamma); + if (m_shadow_strength > 1E-2) + enable(); + else + disable(); +} + + void ShadowRenderer::addNodeToShadowList( scene::ISceneNode *node, E_SHADOW_MODE shadowMode) { @@ -153,6 +183,7 @@ void ShadowRenderer::updateSMTextures() shadowMapTextureDynamicObjects = getSMTexture( std::string("shadow_dynamic_") + itos(m_shadow_map_texture_size), m_texture_format, true); + assert(shadowMapTextureDynamicObjects != nullptr); } if (!shadowMapClientMap) { @@ -161,6 +192,7 @@ void ShadowRenderer::updateSMTextures() std::string("shadow_clientmap_") + itos(m_shadow_map_texture_size), m_shadow_map_colored ? m_texture_format_color : m_texture_format, true); + assert(shadowMapClientMap != nullptr); } if (!shadowMapClientMapFuture && m_map_shadow_update_frames > 1) { @@ -168,6 +200,7 @@ void ShadowRenderer::updateSMTextures() std::string("shadow_clientmap_bb_") + itos(m_shadow_map_texture_size), m_shadow_map_colored ? m_texture_format_color : m_texture_format, true); + assert(shadowMapClientMapFuture != nullptr); } if (m_shadow_map_colored && !shadowMapTextureColors) { @@ -175,6 +208,7 @@ void ShadowRenderer::updateSMTextures() std::string("shadow_colored_") + itos(m_shadow_map_texture_size), m_shadow_map_colored ? m_texture_format_color : m_texture_format, true); + assert(shadowMapTextureColors != nullptr); } // The merge all shadowmaps texture @@ -194,6 +228,7 @@ void ShadowRenderer::updateSMTextures() shadowMapTextureFinal = getSMTexture( std::string("shadowmap_final_") + itos(m_shadow_map_texture_size), frt, true); + assert(shadowMapTextureFinal != nullptr); } if (!m_shadow_node_array.empty() && !m_light_list.empty()) { @@ -270,6 +305,10 @@ void ShadowRenderer::update(video::ITexture *outputTarget) updateSMTextures(); + if (shadowMapTextureFinal == nullptr) { + return; + } + if (!m_shadow_node_array.empty() && !m_light_list.empty()) { for (DirectionalLight &light : m_light_list) { @@ -307,19 +346,23 @@ void ShadowRenderer::drawDebug() /* this code just shows shadows textures in screen and in ONLY for debugging*/ #if 0 // this is debug, ignore for now. - m_driver->draw2DImage(shadowMapTextureFinal, - core::rect(0, 50, 128, 128 + 50), - core::rect({0, 0}, shadowMapTextureFinal->getSize())); + if (shadowMapTextureFinal) + m_driver->draw2DImage(shadowMapTextureFinal, + core::rect(0, 50, 128, 128 + 50), + core::rect({0, 0}, shadowMapTextureFinal->getSize())); - m_driver->draw2DImage(shadowMapClientMap, - core::rect(0, 50 + 128, 128, 128 + 50 + 128), - core::rect({0, 0}, shadowMapTextureFinal->getSize())); - m_driver->draw2DImage(shadowMapTextureDynamicObjects, - core::rect(0, 128 + 50 + 128, 128, - 128 + 50 + 128 + 128), - core::rect({0, 0}, shadowMapTextureDynamicObjects->getSize())); + if (shadowMapClientMap) + m_driver->draw2DImage(shadowMapClientMap, + core::rect(0, 50 + 128, 128, 128 + 50 + 128), + core::rect({0, 0}, shadowMapTextureFinal->getSize())); + + if (shadowMapTextureDynamicObjects) + m_driver->draw2DImage(shadowMapTextureDynamicObjects, + core::rect(0, 128 + 50 + 128, 128, + 128 + 50 + 128 + 128), + core::rect({0, 0}, shadowMapTextureDynamicObjects->getSize())); - if (m_shadow_map_colored) { + if (m_shadow_map_colored && shadowMapTextureColors) { m_driver->draw2DImage(shadowMapTextureColors, core::rect(128,128 + 50 + 128 + 128, @@ -469,13 +512,13 @@ void ShadowRenderer::createShaders() if (depth_shader == -1) { std::string depth_shader_vs = getShaderPath("shadow_shaders", "pass1_vertex.glsl"); if (depth_shader_vs.empty()) { - m_shadows_enabled = false; + m_shadows_supported = false; errorstream << "Error shadow mapping vs shader not found." << std::endl; return; } std::string depth_shader_fs = getShaderPath("shadow_shaders", "pass1_fragment.glsl"); if (depth_shader_fs.empty()) { - m_shadows_enabled = false; + m_shadows_supported = false; errorstream << "Error shadow mapping fs shader not found." << std::endl; return; } @@ -490,7 +533,7 @@ void ShadowRenderer::createShaders() if (depth_shader == -1) { // upsi, something went wrong loading shader. delete m_shadow_depth_cb; - m_shadows_enabled = false; + m_shadows_supported = false; errorstream << "Error compiling shadow mapping shader." << std::endl; return; } @@ -506,13 +549,13 @@ void ShadowRenderer::createShaders() if (depth_shader_entities == -1) { std::string depth_shader_vs = getShaderPath("shadow_shaders", "pass1_vertex.glsl"); if (depth_shader_vs.empty()) { - m_shadows_enabled = false; + m_shadows_supported = false; errorstream << "Error shadow mapping vs shader not found." << std::endl; return; } std::string depth_shader_fs = getShaderPath("shadow_shaders", "pass1_fragment.glsl"); if (depth_shader_fs.empty()) { - m_shadows_enabled = false; + m_shadows_supported = false; errorstream << "Error shadow mapping fs shader not found." << std::endl; return; } @@ -525,7 +568,7 @@ void ShadowRenderer::createShaders() if (depth_shader_entities == -1) { // upsi, something went wrong loading shader. - m_shadows_enabled = false; + m_shadows_supported = false; errorstream << "Error compiling shadow mapping shader (dynamic)." << std::endl; return; } @@ -539,14 +582,14 @@ void ShadowRenderer::createShaders() if (mixcsm_shader == -1) { std::string depth_shader_vs = getShaderPath("shadow_shaders", "pass2_vertex.glsl"); if (depth_shader_vs.empty()) { - m_shadows_enabled = false; + m_shadows_supported = false; errorstream << "Error cascade shadow mapping fs shader not found." << std::endl; return; } std::string depth_shader_fs = getShaderPath("shadow_shaders", "pass2_fragment.glsl"); if (depth_shader_fs.empty()) { - m_shadows_enabled = false; + m_shadows_supported = false; errorstream << "Error cascade shadow mapping fs shader not found." << std::endl; return; } @@ -565,7 +608,7 @@ void ShadowRenderer::createShaders() // upsi, something went wrong loading shader. delete m_shadow_mix_cb; delete m_screen_quad; - m_shadows_enabled = false; + m_shadows_supported = false; errorstream << "Error compiling cascade shadow mapping shader." << std::endl; return; } @@ -579,13 +622,13 @@ void ShadowRenderer::createShaders() if (m_shadow_map_colored && depth_shader_trans == -1) { std::string depth_shader_vs = getShaderPath("shadow_shaders", "pass1_trans_vertex.glsl"); if (depth_shader_vs.empty()) { - m_shadows_enabled = false; + m_shadows_supported = false; errorstream << "Error shadow mapping vs shader not found." << std::endl; return; } std::string depth_shader_fs = getShaderPath("shadow_shaders", "pass1_trans_fragment.glsl"); if (depth_shader_fs.empty()) { - m_shadows_enabled = false; + m_shadows_supported = false; errorstream << "Error shadow mapping fs shader not found." << std::endl; return; } @@ -601,7 +644,7 @@ void ShadowRenderer::createShaders() // upsi, something went wrong loading shader. delete m_shadow_depth_trans_cb; m_shadow_map_colored = false; - m_shadows_enabled = false; + m_shadows_supported = false; errorstream << "Error compiling colored shadow mapping shader." << std::endl; return; } diff --git a/src/client/shadows/dynamicshadowsrender.h b/src/client/shadows/dynamicshadowsrender.h index e4b3c3e22..dc8f79c56 100644 --- a/src/client/shadows/dynamicshadowsrender.h +++ b/src/client/shadows/dynamicshadowsrender.h @@ -82,11 +82,12 @@ public: } - bool is_active() const { return m_shadows_enabled; } + bool is_active() const { return m_shadows_enabled && shadowMapTextureFinal != nullptr; } void setTimeOfDay(float isDay) { m_time_day = isDay; }; + void setShadowIntensity(float shadow_intensity); s32 getShadowSamples() const { return m_shadow_samples; } - float getShadowStrength() const { return m_shadow_strength; } + float getShadowStrength() const { return m_shadows_enabled ? m_shadow_strength : 0.0f; } float getTimeOfDay() const { return m_time_day; } private: @@ -101,6 +102,9 @@ private: void mixShadowsQuad(); void updateSMTextures(); + void disable(); + void enable() { m_shadows_enabled = m_shadows_supported; } + // a bunch of variables IrrlichtDevice *m_device{nullptr}; scene::ISceneManager *m_smgr{nullptr}; @@ -116,12 +120,14 @@ private: std::vector m_shadow_node_array; float m_shadow_strength; + float m_shadow_strength_gamma; float m_shadow_map_max_distance; float m_shadow_map_texture_size; float m_time_day{0.0f}; int m_shadow_samples; bool m_shadow_map_texture_32bit; bool m_shadows_enabled; + bool m_shadows_supported; bool m_shadow_map_colored; u8 m_map_shadow_update_frames; /* Use this number of frames to update map shaodw */ u8 m_current_frame{0}; /* Current frame */ diff --git a/src/client/sky.h b/src/client/sky.h index 3dc057b70..e03683f12 100644 --- a/src/client/sky.h +++ b/src/client/sky.h @@ -65,6 +65,7 @@ public: } void setSunVisible(bool sun_visible) { m_sun_params.visible = sun_visible; } + bool getSunVisible() const { return m_sun_params.visible; } void setSunTexture(const std::string &sun_texture, const std::string &sun_tonemap, ITextureSource *tsrc); void setSunScale(f32 sun_scale) { m_sun_params.scale = sun_scale; } @@ -72,6 +73,7 @@ public: void setSunriseTexture(const std::string &sunglow_texture, ITextureSource* tsrc); void setMoonVisible(bool moon_visible) { m_moon_params.visible = moon_visible; } + bool getMoonVisible() const { return m_moon_params.visible; } void setMoonTexture(const std::string &moon_texture, const std::string &moon_tonemap, ITextureSource *tsrc); void setMoonScale(f32 moon_scale) { m_moon_params.scale = moon_scale; } diff --git a/src/defaultsettings.cpp b/src/defaultsettings.cpp index b935c0e21..2e9a19199 100644 --- a/src/defaultsettings.cpp +++ b/src/defaultsettings.cpp @@ -266,7 +266,7 @@ void set_default_settings() // Effects Shadows settings->setDefault("enable_dynamic_shadows", "false"); - settings->setDefault("shadow_strength", "0.2"); + settings->setDefault("shadow_strength_gamma", "1.0"); settings->setDefault("shadow_map_max_distance", "200.0"); settings->setDefault("shadow_map_texture_size", "2048"); settings->setDefault("shadow_map_texture_32bit", "true"); diff --git a/src/lighting.h b/src/lighting.h new file mode 100644 index 000000000..e0d9cee09 --- /dev/null +++ b/src/lighting.h @@ -0,0 +1,27 @@ +/* +Minetest +Copyright (C) 2021 x2048, Dmitry Kostenko + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 2.1 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#pragma once + +/** Describes ambient light settings for a player + */ +struct Lighting +{ + float shadow_intensity {0.0f}; +}; diff --git a/src/network/clientopcodes.cpp b/src/network/clientopcodes.cpp index a98a5e7d1..6a78b4652 100644 --- a/src/network/clientopcodes.cpp +++ b/src/network/clientopcodes.cpp @@ -123,6 +123,7 @@ const ToClientCommandHandler toClientCommandTable[TOCLIENT_NUM_MSG_TYPES] = { "TOCLIENT_SRP_BYTES_S_B", TOCLIENT_STATE_NOT_CONNECTED, &Client::handleCommand_SrpBytesSandB }, // 0x60 { "TOCLIENT_FORMSPEC_PREPEND", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_FormspecPrepend }, // 0x61, { "TOCLIENT_MINIMAP_MODES", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_MinimapModes }, // 0x62, + { "TOCLIENT_SET_LIGHTING", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_SetLighting }, // 0x63, }; const static ServerCommandFactory null_command_factory = { "TOSERVER_NULL", 0, false }; diff --git a/src/network/clientpackethandler.cpp b/src/network/clientpackethandler.cpp index 48ad60ac6..15b576640 100644 --- a/src/network/clientpackethandler.cpp +++ b/src/network/clientpackethandler.cpp @@ -1682,3 +1682,11 @@ void Client::handleCommand_MinimapModes(NetworkPacket *pkt) if (m_minimap) m_minimap->setModeIndex(mode); } + +void Client::handleCommand_SetLighting(NetworkPacket *pkt) +{ + Lighting& lighting = m_env.getLocalPlayer()->getLighting(); + + if (pkt->getRemainingBytes() >= 4) + *pkt >> lighting.shadow_intensity; +} diff --git a/src/network/networkprotocol.h b/src/network/networkprotocol.h index a5ff53216..f98a829ba 100644 --- a/src/network/networkprotocol.h +++ b/src/network/networkprotocol.h @@ -762,7 +762,12 @@ enum ToClientCommand std::string extra */ - TOCLIENT_NUM_MSG_TYPES = 0x63, + TOCLIENT_SET_LIGHTING = 0x63, + /* + f32 shadow_intensity + */ + + TOCLIENT_NUM_MSG_TYPES = 0x64, }; enum ToServerCommand diff --git a/src/remoteplayer.h b/src/remoteplayer.h index e33630841..0ab33adfe 100644 --- a/src/remoteplayer.h +++ b/src/remoteplayer.h @@ -22,6 +22,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "player.h" #include "skyparams.h" +#include "lighting.h" class PlayerSAO; @@ -125,6 +126,10 @@ public: *frame_speed = local_animation_speed; } + void setLighting(const Lighting &lighting) { m_lighting = lighting; } + + const Lighting& getLighting() const { return m_lighting; } + void setDirty(bool dirty) { m_dirty = true; } u16 protocol_version = 0; @@ -160,5 +165,7 @@ private: MoonParams m_moon_params; StarParams m_star_params; + Lighting m_lighting; + session_t m_peer_id = PEER_ID_INEXISTENT; }; diff --git a/src/script/lua_api/l_object.cpp b/src/script/lua_api/l_object.cpp index 1ed6b0d5c..6153a0399 100644 --- a/src/script/lua_api/l_object.cpp +++ b/src/script/lua_api/l_object.cpp @@ -2295,6 +2295,47 @@ int ObjectRef::l_set_minimap_modes(lua_State *L) return 0; } +// set_lighting(self, lighting) +int ObjectRef::l_set_lighting(lua_State *L) +{ + NO_MAP_LOCK_REQUIRED; + ObjectRef *ref = checkobject(L, 1); + RemotePlayer *player = getplayer(ref); + if (player == nullptr) + return 0; + + luaL_checktype(L, 2, LUA_TTABLE); + Lighting lighting = player->getLighting(); + lua_getfield(L, 2, "shadows"); + if (lua_istable(L, -1)) { + lighting.shadow_intensity = getfloatfield_default(L, -1, "intensity", lighting.shadow_intensity); + } + lua_pop(L, -1); + + getServer(L)->setLighting(player, lighting); + lua_pushboolean(L, true); + return 1; +} + +// get_lighting(self) +int ObjectRef::l_get_lighting(lua_State *L) +{ + NO_MAP_LOCK_REQUIRED; + ObjectRef *ref = checkobject(L, 1); + RemotePlayer *player = getplayer(ref); + if (player == nullptr) + return 0; + + const Lighting &lighting = player->getLighting(); + + lua_newtable(L); // result + lua_newtable(L); // "shadows" + lua_pushnumber(L, lighting.shadow_intensity); + lua_setfield(L, -2, "intensity"); + lua_setfield(L, -2, "shadows"); + return 1; +} + ObjectRef::ObjectRef(ServerActiveObject *object): m_object(object) {} @@ -2448,5 +2489,7 @@ luaL_Reg ObjectRef::methods[] = { luamethod(ObjectRef, get_eye_offset), luamethod(ObjectRef, send_mapblock), luamethod(ObjectRef, set_minimap_modes), + luamethod(ObjectRef, set_lighting), + luamethod(ObjectRef, get_lighting), {0,0} }; diff --git a/src/script/lua_api/l_object.h b/src/script/lua_api/l_object.h index 084d40c05..3e4e6681a 100644 --- a/src/script/lua_api/l_object.h +++ b/src/script/lua_api/l_object.h @@ -376,4 +376,10 @@ private: // set_minimap_modes(self, modes, wanted_mode) static int l_set_minimap_modes(lua_State *L); + + // set_lighting(self, lighting) + static int l_set_lighting(lua_State *L); + + // get_lighting(self) + static int l_get_lighting(lua_State *L); }; diff --git a/src/server.cpp b/src/server.cpp index d9205c895..4bc049e32 100644 --- a/src/server.cpp +++ b/src/server.cpp @@ -1795,6 +1795,16 @@ void Server::SendOverrideDayNightRatio(session_t peer_id, bool do_override, Send(&pkt); } +void Server::SendSetLighting(session_t peer_id, const Lighting &lighting) +{ + NetworkPacket pkt(TOCLIENT_SET_LIGHTING, + 4, peer_id); + + pkt << lighting.shadow_intensity; + + Send(&pkt); +} + void Server::SendTimeOfDay(session_t peer_id, u16 time, f32 time_speed) { NetworkPacket pkt(TOCLIENT_TIME_OF_DAY, 0, peer_id); @@ -3386,6 +3396,13 @@ void Server::overrideDayNightRatio(RemotePlayer *player, bool do_override, SendOverrideDayNightRatio(player->getPeerId(), do_override, ratio); } +void Server::setLighting(RemotePlayer *player, const Lighting &lighting) +{ + sanity_check(player); + player->setLighting(lighting); + SendSetLighting(player->getPeerId(), lighting); +} + void Server::notifyPlayers(const std::wstring &msg) { SendChatMessage(PEER_ID_INEXISTENT, ChatMessage(msg)); diff --git a/src/server.h b/src/server.h index 2741b3157..c05393291 100644 --- a/src/server.h +++ b/src/server.h @@ -69,6 +69,7 @@ struct SkyboxParams; struct SunParams; struct MoonParams; struct StarParams; +struct Lighting; class ServerThread; class ServerModManager; class ServerInventoryManager; @@ -333,6 +334,8 @@ public: void overrideDayNightRatio(RemotePlayer *player, bool do_override, float brightness); + void setLighting(RemotePlayer *player, const Lighting &lighting); + /* con::PeerHandler implementation. */ void peerAdded(con::Peer *peer); void deletingPeer(con::Peer *peer, bool timeout); @@ -459,6 +462,7 @@ private: void SendSetStars(session_t peer_id, const StarParams ¶ms); void SendCloudParams(session_t peer_id, const CloudParams ¶ms); void SendOverrideDayNightRatio(session_t peer_id, bool do_override, float ratio); + void SendSetLighting(session_t peer_id, const Lighting &lighting); void broadcastModChannelMessage(const std::string &channel, const std::string &message, session_t from_peer); -- cgit v1.2.3 From b0b9732359d43325c8bd820abeb8417353365a0c Mon Sep 17 00:00:00 2001 From: x2048 Date: Sat, 2 Apr 2022 10:42:27 +0200 Subject: Add depth sorting for node faces (#11696) Use BSP tree to order transparent triangles https://en.wikipedia.org/wiki/Binary_space_partitioning --- builtin/settingtypes.txt | 4 + src/client/clientmap.cpp | 244 ++++++++++++++++++++++++++------------ src/client/clientmap.h | 43 ++++--- src/client/content_mapblock.cpp | 57 ++++++++- src/client/mapblock_mesh.cpp | 257 +++++++++++++++++++++++++++++++++++++++- src/client/mapblock_mesh.h | 101 ++++++++++++++++ src/client/tile.h | 15 ++- src/defaultsettings.cpp | 1 + 8 files changed, 629 insertions(+), 93 deletions(-) (limited to 'src/defaultsettings.cpp') diff --git a/builtin/settingtypes.txt b/builtin/settingtypes.txt index 3dc165bd1..b4230735b 100644 --- a/builtin/settingtypes.txt +++ b/builtin/settingtypes.txt @@ -858,6 +858,10 @@ autoscale_mode (Autoscaling mode) enum disable disable,enable,force # A restart is required after changing this. show_entity_selectionbox (Show entity selection boxes) bool false +# Distance in nodes at which transparency depth sorting is enabled +# Use this to limit the performance impact of transparency depth sorting +transparency_sorting_distance (Transparency Sorting Distance) int 16 0 128 + [*Menus] # Use a cloud animation for the main menu background. diff --git a/src/client/clientmap.cpp b/src/client/clientmap.cpp index 1a024e464..f070a58bb 100644 --- a/src/client/clientmap.cpp +++ b/src/client/clientmap.cpp @@ -97,9 +97,32 @@ ClientMap::ClientMap( m_cache_trilinear_filter = g_settings->getBool("trilinear_filter"); m_cache_bilinear_filter = g_settings->getBool("bilinear_filter"); m_cache_anistropic_filter = g_settings->getBool("anisotropic_filter"); + m_cache_transparency_sorting_distance = g_settings->getU16("transparency_sorting_distance"); } +void ClientMap::updateCamera(v3f pos, v3f dir, f32 fov, v3s16 offset) +{ + v3s16 previous_node = floatToInt(m_camera_position, BS) + m_camera_offset; + v3s16 previous_block = getContainerPos(previous_node, MAP_BLOCKSIZE); + + m_camera_position = pos; + m_camera_direction = dir; + m_camera_fov = fov; + m_camera_offset = offset; + + v3s16 current_node = floatToInt(m_camera_position, BS) + m_camera_offset; + v3s16 current_block = getContainerPos(current_node, MAP_BLOCKSIZE); + + // reorder the blocks when camera crosses block boundary + if (previous_block != current_block) + m_needs_update_drawlist = true; + + // reorder transparent meshes when camera crosses node boundary + if (previous_node != current_node) + m_needs_update_transparent_meshes = true; +} + MapSector * ClientMap::emergeSector(v2s16 p2d) { // Check that it doesn't exist already @@ -323,22 +346,17 @@ void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass) u32 mesh_animate_count = 0; //u32 mesh_animate_count_far = 0; + /* + Update transparent meshes + */ + if (is_transparent_pass) + updateTransparentMeshBuffers(); + /* Draw the selected MapBlocks */ MeshBufListList grouped_buffers; - - struct DrawDescriptor { - v3s16 m_pos; - scene::IMeshBuffer *m_buffer; - bool m_reuse_material; - - DrawDescriptor(const v3s16 &pos, scene::IMeshBuffer *buffer, bool reuse_material) : - m_pos(pos), m_buffer(buffer), m_reuse_material(reuse_material) - {} - }; - std::vector draw_order; video::SMaterial previous_material; @@ -375,7 +393,15 @@ void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass) /* Get the meshbuffers of the block */ - { + if (is_transparent_pass) { + // In transparent pass, the mesh will give us + // the partial buffers in the correct order + for (auto &buffer : block->mesh->getTransparentBuffers()) + draw_order.emplace_back(block_pos, &buffer); + } + else { + // otherwise, group buffers across meshes + // using MeshBufListList MapBlockMesh *mapBlockMesh = block->mesh; assert(mapBlockMesh); @@ -389,35 +415,14 @@ void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass) video::SMaterial& material = buf->getMaterial(); video::IMaterialRenderer* rnd = - driver->getMaterialRenderer(material.MaterialType); + driver->getMaterialRenderer(material.MaterialType); bool transparent = (rnd && rnd->isTransparent()); - if (transparent == is_transparent_pass) { + if (!transparent) { if (buf->getVertexCount() == 0) errorstream << "Block [" << analyze_block(block) - << "] contains an empty meshbuf" << std::endl; - - material.setFlag(video::EMF_TRILINEAR_FILTER, - m_cache_trilinear_filter); - material.setFlag(video::EMF_BILINEAR_FILTER, - m_cache_bilinear_filter); - material.setFlag(video::EMF_ANISOTROPIC_FILTER, - m_cache_anistropic_filter); - material.setFlag(video::EMF_WIREFRAME, - m_control.show_wireframe); - - if (is_transparent_pass) { - // Same comparison as in MeshBufListList - bool new_material = material.getTexture(0) != previous_material.getTexture(0) || - material != previous_material; - - draw_order.emplace_back(block_pos, buf, !new_material); - - if (new_material) - previous_material = material; - } - else { - grouped_buffers.add(buf, block_pos, layer); - } + << "] contains an empty meshbuf" << std::endl; + + grouped_buffers.add(buf, block_pos, layer); } } } @@ -442,8 +447,17 @@ void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass) // Render all mesh buffers in order drawcall_count += draw_order.size(); + for (auto &descriptor : draw_order) { - scene::IMeshBuffer *buf = descriptor.m_buffer; + scene::IMeshBuffer *buf; + + if (descriptor.m_use_partial_buffer) { + descriptor.m_partial_buffer->beforeDraw(); + buf = descriptor.m_partial_buffer->getBuffer(); + } + else { + buf = descriptor.m_buffer; + } // Check and abort if the machine is swapping a lot if (draw.getTimerTime() > 2000) { @@ -454,6 +468,17 @@ void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass) if (!descriptor.m_reuse_material) { auto &material = buf->getMaterial(); + + // Apply filter settings + material.setFlag(video::EMF_TRILINEAR_FILTER, + m_cache_trilinear_filter); + material.setFlag(video::EMF_BILINEAR_FILTER, + m_cache_bilinear_filter); + material.setFlag(video::EMF_ANISOTROPIC_FILTER, + m_cache_anistropic_filter); + material.setFlag(video::EMF_WIREFRAME, + m_control.show_wireframe); + // pass the shadow map texture to the buffer texture ShadowRenderer *shadow = m_rendering_engine->get_shadow_renderer(); if (shadow && shadow->is_active()) { @@ -475,7 +500,7 @@ void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass) driver->setTransform(video::ETS_WORLD, m); driver->drawMeshBuffer(buf); - vertex_count += buf->getVertexCount(); + vertex_count += buf->getIndexCount(); } g_profiler->avg(prefix + "draw meshes [ms]", draw.stop(true)); @@ -698,7 +723,9 @@ void ClientMap::renderMapShadows(video::IVideoDriver *driver, u32 drawcall_count = 0; u32 vertex_count = 0; - MeshBufListList drawbufs; + MeshBufListList grouped_buffers; + std::vector draw_order; + int count = 0; int low_bound = is_transparent_pass ? 0 : m_drawlist_shadow.size() / total_frames * frame; @@ -727,7 +754,15 @@ void ClientMap::renderMapShadows(video::IVideoDriver *driver, /* Get the meshbuffers of the block */ - { + if (is_transparent_pass) { + // In transparent pass, the mesh will give us + // the partial buffers in the correct order + for (auto &buffer : block->mesh->getTransparentBuffers()) + draw_order.emplace_back(block_pos, &buffer); + } + else { + // otherwise, group buffers across meshes + // using MeshBufListList MapBlockMesh *mapBlockMesh = block->mesh; assert(mapBlockMesh); @@ -742,49 +777,74 @@ void ClientMap::renderMapShadows(video::IVideoDriver *driver, video::SMaterial &mat = buf->getMaterial(); auto rnd = driver->getMaterialRenderer(mat.MaterialType); bool transparent = rnd && rnd->isTransparent(); - if (transparent == is_transparent_pass) - drawbufs.add(buf, block_pos, layer); + if (!transparent) + grouped_buffers.add(buf, block_pos, layer); } } } } + u32 buffer_count = 0; + for (auto &lists : grouped_buffers.lists) + for (MeshBufList &list : lists) + buffer_count += list.bufs.size(); + + draw_order.reserve(draw_order.size() + buffer_count); + + // Capture draw order for all solid meshes + for (auto &lists : grouped_buffers.lists) { + for (MeshBufList &list : lists) { + // iterate in reverse to draw closest blocks first + for (auto it = list.bufs.rbegin(); it != list.bufs.rend(); ++it) + draw_order.emplace_back(it->first, it->second, it != list.bufs.rbegin()); + } + } + TimeTaker draw("Drawing shadow mesh buffers"); core::matrix4 m; // Model matrix v3f offset = intToFloat(m_camera_offset, BS); + u32 material_swaps = 0; - // Render all layers in order - for (auto &lists : drawbufs.lists) { - for (MeshBufList &list : lists) { - // Check and abort if the machine is swapping a lot - if (draw.getTimerTime() > 1000) { - infostream << "ClientMap::renderMapShadows(): Rendering " - "took >1s, returning." << std::endl; - break; - } - for (auto &pair : list.bufs) { - scene::IMeshBuffer *buf = pair.second; - - // override some material properties - video::SMaterial local_material = buf->getMaterial(); - local_material.MaterialType = material.MaterialType; - local_material.BackfaceCulling = material.BackfaceCulling; - local_material.FrontfaceCulling = material.FrontfaceCulling; - local_material.BlendOperation = material.BlendOperation; - local_material.Lighting = false; - driver->setMaterial(local_material); - - v3f block_wpos = intToFloat(pair.first * MAP_BLOCKSIZE, BS); - m.setTranslation(block_wpos - offset); - - driver->setTransform(video::ETS_WORLD, m); - driver->drawMeshBuffer(buf); - vertex_count += buf->getVertexCount(); - } + // Render all mesh buffers in order + drawcall_count += draw_order.size(); + + for (auto &descriptor : draw_order) { + scene::IMeshBuffer *buf; + + if (descriptor.m_use_partial_buffer) { + descriptor.m_partial_buffer->beforeDraw(); + buf = descriptor.m_partial_buffer->getBuffer(); + } + else { + buf = descriptor.m_buffer; + } - drawcall_count += list.bufs.size(); + // Check and abort if the machine is swapping a lot + if (draw.getTimerTime() > 1000) { + infostream << "ClientMap::renderMapShadows(): Rendering " + "took >1s, returning." << std::endl; + break; } + + if (!descriptor.m_reuse_material) { + // override some material properties + video::SMaterial local_material = buf->getMaterial(); + local_material.MaterialType = material.MaterialType; + local_material.BackfaceCulling = material.BackfaceCulling; + local_material.FrontfaceCulling = material.FrontfaceCulling; + local_material.BlendOperation = material.BlendOperation; + local_material.Lighting = false; + driver->setMaterial(local_material); + ++material_swaps; + } + + v3f block_wpos = intToFloat(descriptor.m_pos * MAP_BLOCKSIZE, BS); + m.setTranslation(block_wpos - offset); + + driver->setTransform(video::ETS_WORLD, m); + driver->drawMeshBuffer(buf); + vertex_count += buf->getIndexCount(); } // restore the driver material state @@ -796,6 +856,7 @@ void ClientMap::renderMapShadows(video::IVideoDriver *driver, g_profiler->avg(prefix + "draw meshes [ms]", draw.stop(true)); g_profiler->avg(prefix + "vertices drawn [#]", vertex_count); g_profiler->avg(prefix + "drawcalls [#]", drawcall_count); + g_profiler->avg(prefix + "material swaps [#]", material_swaps); } /* @@ -891,3 +952,40 @@ void ClientMap::updateDrawListShadow(const v3f &shadow_light_pos, const v3f &sha g_profiler->avg("SHADOW MapBlocks drawn [#]", m_drawlist_shadow.size()); g_profiler->avg("SHADOW MapBlocks loaded [#]", blocks_loaded); } + +void ClientMap::updateTransparentMeshBuffers() +{ + ScopeProfiler sp(g_profiler, "CM::updateTransparentMeshBuffers", SPT_AVG); + u32 sorted_blocks = 0; + u32 unsorted_blocks = 0; + f32 sorting_distance_sq = pow(m_cache_transparency_sorting_distance * BS, 2.0f); + + + // Update the order of transparent mesh buffers in each mesh + for (auto it = m_drawlist.begin(); it != m_drawlist.end(); it++) { + MapBlock* block = it->second; + if (!block->mesh) + continue; + + if (m_needs_update_transparent_meshes || + block->mesh->getTransparentBuffers().size() == 0) { + + v3s16 block_pos = block->getPos(); + v3f block_pos_f = intToFloat(block_pos * MAP_BLOCKSIZE + MAP_BLOCKSIZE / 2, BS); + f32 distance = m_camera_position.getDistanceFromSQ(block_pos_f); + if (distance <= sorting_distance_sq) { + block->mesh->updateTransparentBuffers(m_camera_position, block_pos); + ++sorted_blocks; + } + else { + block->mesh->consolidateTransparentBuffers(); + ++unsorted_blocks; + } + } + } + + g_profiler->avg("CM::Transparent Buffers - Sorted", sorted_blocks); + g_profiler->avg("CM::Transparent Buffers - Unsorted", unsorted_blocks); + m_needs_update_transparent_meshes = false; +} + diff --git a/src/client/clientmap.h b/src/client/clientmap.h index b4dc42395..d8554313d 100644 --- a/src/client/clientmap.h +++ b/src/client/clientmap.h @@ -56,6 +56,7 @@ struct MeshBufListList class Client; class ITextureSource; +class PartialMeshBuffer; /* ClientMap @@ -85,21 +86,7 @@ public: ISceneNode::drop(); } - void updateCamera(const v3f &pos, const v3f &dir, f32 fov, const v3s16 &offset) - { - v3s16 previous_block = getContainerPos(floatToInt(m_camera_position, BS) + m_camera_offset, MAP_BLOCKSIZE); - - m_camera_position = pos; - m_camera_direction = dir; - m_camera_fov = fov; - m_camera_offset = offset; - - v3s16 current_block = getContainerPos(floatToInt(m_camera_position, BS) + m_camera_offset, MAP_BLOCKSIZE); - - // reorder the blocks when camera crosses block boundary - if (previous_block != current_block) - m_needs_update_drawlist = true; - } + void updateCamera(v3f pos, v3f dir, f32 fov, v3s16 offset); /* Forcefully get a sector from somewhere @@ -150,6 +137,10 @@ public: f32 getCameraFov() const { return m_camera_fov; } private: + + // update the vertex order in transparent mesh buffers + void updateTransparentMeshBuffers(); + // Orders blocks by distance to the camera class MapBlockComparer { @@ -167,6 +158,26 @@ private: v3s16 m_camera_block; }; + + // reference to a mesh buffer used when rendering the map. + struct DrawDescriptor { + v3s16 m_pos; + union { + scene::IMeshBuffer *m_buffer; + const PartialMeshBuffer *m_partial_buffer; + }; + bool m_reuse_material:1; + bool m_use_partial_buffer:1; + + DrawDescriptor(v3s16 pos, scene::IMeshBuffer *buffer, bool reuse_material) : + m_pos(pos), m_buffer(buffer), m_reuse_material(reuse_material), m_use_partial_buffer(false) + {} + + DrawDescriptor(v3s16 pos, const PartialMeshBuffer *buffer) : + m_pos(pos), m_partial_buffer(buffer), m_reuse_material(false), m_use_partial_buffer(true) + {} + }; + Client *m_client; RenderingEngine *m_rendering_engine; @@ -179,6 +190,7 @@ private: v3f m_camera_direction = v3f(0,0,1); f32 m_camera_fov = M_PI; v3s16 m_camera_offset; + bool m_needs_update_transparent_meshes = true; std::map m_drawlist; std::map m_drawlist_shadow; @@ -190,4 +202,5 @@ private: bool m_cache_bilinear_filter; bool m_cache_anistropic_filter; bool m_added_to_shadow_renderer{false}; + u16 m_cache_transparency_sorting_distance; }; diff --git a/src/client/content_mapblock.cpp b/src/client/content_mapblock.cpp index bb2d6398f..947793ed0 100644 --- a/src/client/content_mapblock.cpp +++ b/src/client/content_mapblock.cpp @@ -381,12 +381,12 @@ void MapblockMeshGenerator::drawAutoLightedCuboid(aabb3f box, const f32 *txc, box.MinEdge *= f->visual_scale; box.MaxEdge *= f->visual_scale; } - box.MinEdge += origin; - box.MaxEdge += origin; if (!txc) { generateCuboidTextureCoords(box, texture_coord_buf); txc = texture_coord_buf; } + box.MinEdge += origin; + box.MaxEdge += origin; if (!tiles) { tiles = &tile; tile_count = 1; @@ -1377,6 +1377,59 @@ void MapblockMeshGenerator::drawNodeboxNode() std::vector boxes; n.getNodeBoxes(nodedef, &boxes, neighbors_set); + + bool isTransparent = false; + + for (const TileSpec &tile : tiles) { + if (tile.layers[0].isTransparent()) { + isTransparent = true; + break; + } + } + + if (isTransparent) { + std::vector sections; + // Preallocate 8 default splits + Min&Max for each nodebox + sections.reserve(8 + 2 * boxes.size()); + + for (int axis = 0; axis < 3; axis++) { + // identify sections + + if (axis == 0) { + // Default split at node bounds, up to 3 nodes in each direction + for (float s = -3.5f * BS; s < 4.0f * BS; s += 1.0f * BS) + sections.push_back(s); + } + else { + // Avoid readding the same 8 default splits for Y and Z + sections.resize(8); + } + + // Add edges of existing node boxes, rounded to 1E-3 + for (size_t i = 0; i < boxes.size(); i++) { + sections.push_back(std::floor(boxes[i].MinEdge[axis] * 1E3) * 1E-3); + sections.push_back(std::floor(boxes[i].MaxEdge[axis] * 1E3) * 1E-3); + } + + // split the boxes at recorded sections + // limit splits to avoid runaway crash if inner loop adds infinite splits + // due to e.g. precision problems. + // 100 is just an arbitrary, reasonably high number. + for (size_t i = 0; i < boxes.size() && i < 100; i++) { + aabb3f *box = &boxes[i]; + for (float section : sections) { + if (box->MinEdge[axis] < section && box->MaxEdge[axis] > section) { + aabb3f copy(*box); + copy.MinEdge[axis] = section; + box->MaxEdge[axis] = section; + boxes.push_back(copy); + box = &boxes[i]; // find new address of the box in case of reallocation + } + } + } + } + } + for (auto &box : boxes) drawAutoLightedCuboid(box, nullptr, tiles, 6); } diff --git a/src/client/mapblock_mesh.cpp b/src/client/mapblock_mesh.cpp index 03522eca9..8c7d66186 100644 --- a/src/client/mapblock_mesh.cpp +++ b/src/client/mapblock_mesh.cpp @@ -30,6 +30,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client/meshgen/collector.h" #include "client/renderingengine.h" #include +#include /* MeshMakeData @@ -1003,6 +1004,173 @@ static void applyTileColor(PreMeshBuffer &pmb) } } +/* + MapBlockBspTree +*/ + +void MapBlockBspTree::buildTree(const std::vector *triangles) +{ + this->triangles = triangles; + + nodes.clear(); + + // assert that triangle index can fit into s32 + assert(triangles->size() <= 0x7FFFFFFFL); + std::vector indexes; + indexes.reserve(triangles->size()); + for (u32 i = 0; i < triangles->size(); i++) + indexes.push_back(i); + + root = buildTree(v3f(1, 0, 0), v3f(85, 85, 85), 40, indexes, 0); +} + +/** + * @brief Find a candidate plane to split a set of triangles in two + * + * The candidate plane is represented by one of the triangles from the set. + * + * @param list Vector of indexes of the triangles in the set + * @param triangles Vector of all triangles in the BSP tree + * @return Address of the triangle that represents the proposed split plane + */ +static const MeshTriangle *findSplitCandidate(const std::vector &list, const std::vector &triangles) +{ + // find the center of the cluster. + v3f center(0, 0, 0); + size_t n = list.size(); + for (s32 i : list) { + center += triangles[i].centroid / n; + } + + // find the triangle with the largest area and closest to the center + const MeshTriangle *candidate_triangle = &triangles[list[0]]; + const MeshTriangle *ith_triangle; + for (s32 i : list) { + ith_triangle = &triangles[i]; + if (ith_triangle->areaSQ > candidate_triangle->areaSQ || + (ith_triangle->areaSQ == candidate_triangle->areaSQ && + ith_triangle->centroid.getDistanceFromSQ(center) < candidate_triangle->centroid.getDistanceFromSQ(center))) { + candidate_triangle = ith_triangle; + } + } + return candidate_triangle; +} + +s32 MapBlockBspTree::buildTree(v3f normal, v3f origin, float delta, const std::vector &list, u32 depth) +{ + // if the list is empty, don't bother + if (list.empty()) + return -1; + + // if there is only one triangle, or the delta is insanely small, this is a leaf node + if (list.size() == 1 || delta < 0.01) { + nodes.emplace_back(normal, origin, list, -1, -1); + return nodes.size() - 1; + } + + std::vector front_list; + std::vector back_list; + std::vector node_list; + + // split the list + for (s32 i : list) { + const MeshTriangle &triangle = (*triangles)[i]; + float factor = normal.dotProduct(triangle.centroid - origin); + if (factor == 0) + node_list.push_back(i); + else if (factor > 0) + front_list.push_back(i); + else + back_list.push_back(i); + } + + // define the new split-plane + v3f candidate_normal(normal.Z, normal.X, normal.Y); + float candidate_delta = delta; + if (depth % 3 == 2) + candidate_delta /= 2; + + s32 front_index = -1; + s32 back_index = -1; + + if (!front_list.empty()) { + v3f next_normal = candidate_normal; + v3f next_origin = origin + delta * normal; + float next_delta = candidate_delta; + if (next_delta < 10) { + const MeshTriangle *candidate = findSplitCandidate(front_list, *triangles); + next_normal = candidate->getNormal(); + next_origin = candidate->centroid; + } + front_index = buildTree(next_normal, next_origin, next_delta, front_list, depth + 1); + + // if there are no other triangles, don't create a new node + if (back_list.empty() && node_list.empty()) + return front_index; + } + + if (!back_list.empty()) { + v3f next_normal = candidate_normal; + v3f next_origin = origin - delta * normal; + float next_delta = candidate_delta; + if (next_delta < 10) { + const MeshTriangle *candidate = findSplitCandidate(back_list, *triangles); + next_normal = candidate->getNormal(); + next_origin = candidate->centroid; + } + + back_index = buildTree(next_normal, next_origin, next_delta, back_list, depth + 1); + + // if there are no other triangles, don't create a new node + if (front_list.empty() && node_list.empty()) + return back_index; + } + + nodes.emplace_back(normal, origin, node_list, front_index, back_index); + + return nodes.size() - 1; +} + +void MapBlockBspTree::traverse(s32 node, v3f viewpoint, std::vector &output) const +{ + if (node < 0) return; // recursion break; + + const TreeNode &n = nodes[node]; + float factor = n.normal.dotProduct(viewpoint - n.origin); + + if (factor > 0) + traverse(n.back_ref, viewpoint, output); + else + traverse(n.front_ref, viewpoint, output); + + if (factor != 0) + for (s32 i : n.triangle_refs) + output.push_back(i); + + if (factor > 0) + traverse(n.front_ref, viewpoint, output); + else + traverse(n.back_ref, viewpoint, output); +} + + + +/* + PartialMeshBuffer +*/ + +void PartialMeshBuffer::beforeDraw() const +{ + // Patch the indexes in the mesh buffer before draw + + m_buffer->Indices.clear(); + if (!m_vertex_indexes.empty()) { + for (auto index : m_vertex_indexes) + m_buffer->Indices.push_back(index); + } + m_buffer->setDirty(scene::EBT_INDEX); +} + /* MapBlockMesh */ @@ -1173,8 +1341,31 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): scene::SMeshBuffer *buf = new scene::SMeshBuffer(); buf->Material = material; - buf->append(&p.vertices[0], p.vertices.size(), - &p.indices[0], p.indices.size()); + switch (p.layer.material_type) { + // list of transparent materials taken from tile.h + case TILE_MATERIAL_ALPHA: + case TILE_MATERIAL_LIQUID_TRANSPARENT: + case TILE_MATERIAL_WAVING_LIQUID_TRANSPARENT: + { + buf->append(&p.vertices[0], p.vertices.size(), + &p.indices[0], 0); + + MeshTriangle t; + t.buffer = buf; + for (u32 i = 0; i < p.indices.size(); i += 3) { + t.p1 = p.indices[i]; + t.p2 = p.indices[i + 1]; + t.p3 = p.indices[i + 2]; + t.updateAttributes(); + m_transparent_triangles.push_back(t); + } + } + break; + default: + buf->append(&p.vertices[0], p.vertices.size(), + &p.indices[0], p.indices.size()); + break; + } mesh->addMeshBuffer(buf); buf->drop(); } @@ -1187,6 +1378,7 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): } //std::cout<<"added "< triangle_refs; + m_bsp_tree.traverse(rel_camera_pos, triangle_refs); + + // arrange index sequences into partial buffers + m_transparent_buffers.clear(); + + scene::SMeshBuffer *current_buffer = nullptr; + std::vector current_strain; + for (auto i : triangle_refs) { + const auto &t = m_transparent_triangles[i]; + if (current_buffer != t.buffer) { + if (current_buffer) { + m_transparent_buffers.emplace_back(current_buffer, current_strain); + current_strain.clear(); + } + current_buffer = t.buffer; + } + current_strain.push_back(t.p1); + current_strain.push_back(t.p2); + current_strain.push_back(t.p3); + } + + if (!current_strain.empty()) + m_transparent_buffers.emplace_back(current_buffer, current_strain); +} + +void MapBlockMesh::consolidateTransparentBuffers() +{ + m_transparent_buffers.clear(); + + scene::SMeshBuffer *current_buffer = nullptr; + std::vector current_strain; + + // use the fact that m_transparent_triangles is already arranged by buffer + for (const auto &t : m_transparent_triangles) { + if (current_buffer != t.buffer) { + if (current_buffer != nullptr) { + this->m_transparent_buffers.emplace_back(current_buffer, current_strain); + current_strain.clear(); + } + current_buffer = t.buffer; + } + current_strain.push_back(t.p1); + current_strain.push_back(t.p2); + current_strain.push_back(t.p3); + } + + if (!current_strain.empty()) { + this->m_transparent_buffers.emplace_back(current_buffer, current_strain); + } +} + video::SColor encode_light(u16 light, u8 emissive_light) { // Get components diff --git a/src/client/mapblock_mesh.h b/src/client/mapblock_mesh.h index 3b17c4af9..cfc39ade2 100644 --- a/src/client/mapblock_mesh.h +++ b/src/client/mapblock_mesh.h @@ -71,6 +71,91 @@ struct MeshMakeData void setSmoothLighting(bool smooth_lighting); }; +// represents a triangle as indexes into the vertex buffer in SMeshBuffer +class MeshTriangle +{ +public: + scene::SMeshBuffer *buffer; + u16 p1, p2, p3; + v3f centroid; + float areaSQ; + + void updateAttributes() + { + v3f v1 = buffer->getPosition(p1); + v3f v2 = buffer->getPosition(p2); + v3f v3 = buffer->getPosition(p3); + + centroid = (v1 + v2 + v3) / 3; + areaSQ = (v2-v1).crossProduct(v3-v1).getLengthSQ() / 4; + } + + v3f getNormal() const { + v3f v1 = buffer->getPosition(p1); + v3f v2 = buffer->getPosition(p2); + v3f v3 = buffer->getPosition(p3); + + return (v2-v1).crossProduct(v3-v1); + } +}; + +/** + * Implements a binary space partitioning tree + * See also: https://en.wikipedia.org/wiki/Binary_space_partitioning + */ +class MapBlockBspTree +{ +public: + MapBlockBspTree() {} + + void buildTree(const std::vector *triangles); + + void traverse(v3f viewpoint, std::vector &output) const + { + traverse(root, viewpoint, output); + } + +private: + // Tree node definition; + struct TreeNode + { + v3f normal; + v3f origin; + std::vector triangle_refs; + s32 front_ref; + s32 back_ref; + + TreeNode() = default; + TreeNode(v3f normal, v3f origin, const std::vector &triangle_refs, s32 front_ref, s32 back_ref) : + normal(normal), origin(origin), triangle_refs(triangle_refs), front_ref(front_ref), back_ref(back_ref) + {} + }; + + + s32 buildTree(v3f normal, v3f origin, float delta, const std::vector &list, u32 depth); + void traverse(s32 node, v3f viewpoint, std::vector &output) const; + + const std::vector *triangles = nullptr; // this reference is managed externally + std::vector nodes; // list of nodes + s32 root = -1; // index of the root node +}; + +class PartialMeshBuffer +{ +public: + PartialMeshBuffer(scene::SMeshBuffer *buffer, const std::vector &vertex_indexes) : + m_buffer(buffer), m_vertex_indexes(vertex_indexes) + {} + + scene::IMeshBuffer *getBuffer() const { return m_buffer; } + const std::vector &getVertexIndexes() const { return m_vertex_indexes; } + + void beforeDraw() const; +private: + scene::SMeshBuffer *m_buffer; + std::vector m_vertex_indexes; +}; + /* Holds a mesh for a mapblock. @@ -125,6 +210,15 @@ public: m_animation_force_timer--; } + /// update transparent buffers to render towards the camera + void updateTransparentBuffers(v3f camera_pos, v3s16 block_pos); + void consolidateTransparentBuffers(); + + /// get the list of transparent buffers + const std::vector &getTransparentBuffers() const + { + return this->m_transparent_buffers; + } private: scene::IMesh *m_mesh[MAX_TILE_LAYERS]; MinimapMapblock *m_minimap_mapblock; @@ -158,6 +252,13 @@ private: // of sunlit vertices // Keys are pairs of (mesh index, buffer index in the mesh) std::map, std::map > m_daynight_diffs; + + // list of all semitransparent triangles in the mapblock + std::vector m_transparent_triangles; + // Binary Space Partitioning tree for the block + MapBlockBspTree m_bsp_tree; + // Ordered list of references to parts of transparent buffers to draw + std::vector m_transparent_buffers; }; /*! diff --git a/src/client/tile.h b/src/client/tile.h index fe96cef58..88ff91f8e 100644 --- a/src/client/tile.h +++ b/src/client/tile.h @@ -260,6 +260,18 @@ struct TileLayer && (material_flags & MATERIAL_FLAG_TILEABLE_VERTICAL); } + bool isTransparent() const + { + switch (material_type) { + case TILE_MATERIAL_BASIC: + case TILE_MATERIAL_ALPHA: + case TILE_MATERIAL_LIQUID_TRANSPARENT: + case TILE_MATERIAL_WAVING_LIQUID_TRANSPARENT: + return true; + } + return false; + } + // Ordered for size, please do not reorder video::ITexture *texture = nullptr; @@ -308,7 +320,8 @@ struct TileSpec for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) { if (layers[layer] != other.layers[layer]) return false; - if (!layers[layer].isTileable()) + // Only non-transparent tiles can be merged into fast faces + if (layers[layer].isTransparent() || !layers[layer].isTileable()) return false; } return rotation == 0 diff --git a/src/defaultsettings.cpp b/src/defaultsettings.cpp index 2e9a19199..b86287157 100644 --- a/src/defaultsettings.cpp +++ b/src/defaultsettings.cpp @@ -244,6 +244,7 @@ void set_default_settings() settings->setDefault("enable_particles", "true"); settings->setDefault("arm_inertia", "true"); settings->setDefault("show_nametag_backgrounds", "true"); + settings->setDefault("transparency_sorting_distance", "16"); settings->setDefault("enable_minimap", "true"); settings->setDefault("minimap_shape_round", "true"); -- cgit v1.2.3 From 45d318a77300b014b13366ee9fa4cfc69e08f360 Mon Sep 17 00:00:00 2001 From: Froggo <92762044+Froggo8311@users.noreply.github.com> Date: Fri, 6 May 2022 15:15:16 -0500 Subject: Enable chat clickable weblinks by default (#12115) Co-authored-by: rubenwardy --- builtin/settingtypes.txt | 2 +- minetest.conf.example | 2 +- src/defaultsettings.cpp | 4 +++- 3 files changed, 5 insertions(+), 3 deletions(-) (limited to 'src/defaultsettings.cpp') diff --git a/builtin/settingtypes.txt b/builtin/settingtypes.txt index e3589d76f..ff69d9741 100644 --- a/builtin/settingtypes.txt +++ b/builtin/settingtypes.txt @@ -988,7 +988,7 @@ mute_sound (Mute sound) bool false [Client] # Clickable weblinks (middle-click or Ctrl+left-click) enabled in chat console output. -clickable_chat_weblinks (Chat weblinks) bool false +clickable_chat_weblinks (Chat weblinks) bool true # Optional override for chat weblink color. chat_weblink_color (Weblink color) string diff --git a/minetest.conf.example b/minetest.conf.example index 68757680c..4b4bda0c5 100644 --- a/minetest.conf.example +++ b/minetest.conf.example @@ -1176,7 +1176,7 @@ # Clickable weblinks (middle-click or Ctrl+left-click) enabled in chat console output. # type: bool -# clickable_chat_weblinks = false +# clickable_chat_weblinks = true # Optional override for chat weblink color. # type: string diff --git a/src/defaultsettings.cpp b/src/defaultsettings.cpp index b86287157..11d52efd3 100644 --- a/src/defaultsettings.cpp +++ b/src/defaultsettings.cpp @@ -65,7 +65,6 @@ void set_default_settings() settings->setDefault("max_out_chat_queue_size", "20"); settings->setDefault("pause_on_lost_focus", "false"); settings->setDefault("enable_register_confirmation", "true"); - settings->setDefault("clickable_chat_weblinks", "false"); settings->setDefault("chat_weblink_color", "#8888FF"); // Keymap @@ -465,6 +464,9 @@ void set_default_settings() settings->setDefault("touchscreen_threshold","20"); settings->setDefault("fixed_virtual_joystick", "false"); settings->setDefault("virtual_joystick_triggers_aux1", "false"); + settings->setDefault("clickable_chat_weblinks", "false"); +#else + settings->setDefault("clickable_chat_weblinks", "true"); #endif // Altered settings for Android #ifdef __ANDROID__ -- cgit v1.2.3